summaryrefslogtreecommitdiffstats
path: root/winpr/test/TestIntrinsics.c
blob: 2198d6763b1d2166e073ab033137cec6354d9a6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <winpr/crt.h>
#include <winpr/sysinfo.h>
#include <winpr/windows.h>

#include <winpr/intrin.h>

static BOOL g_LZCNT = FALSE;

static INLINE UINT32 lzcnt_s(UINT32 x)
{
	if (!x)
		return 32;

	if (!g_LZCNT)
	{
		UINT32 y = 0;
		int n = 32;
		y = x >> 16;
		if (y != 0)
		{
			n = n - 16;
			x = y;
		}
		y = x >> 8;
		if (y != 0)
		{
			n = n - 8;
			x = y;
		}
		y = x >> 4;
		if (y != 0)
		{
			n = n - 4;
			x = y;
		}
		y = x >> 2;
		if (y != 0)
		{
			n = n - 2;
			x = y;
		}
		y = x >> 1;
		if (y != 0)
			return n - 2;
		return n - x;
	}

	return __lzcnt(x);
}

static int test_lzcnt(void)
{
	if (lzcnt_s(0x1) != 31)
	{
		fprintf(stderr, "__lzcnt(0x1) != 31: %" PRIu32 "\n", __lzcnt(0x1));
		return -1;
	}

	if (lzcnt_s(0xFF) != 24)
	{
		fprintf(stderr, "__lzcnt(0xFF) != 24\n");
		return -1;
	}

	if (lzcnt_s(0xFFFF) != 16)
	{
		fprintf(stderr, "__lzcnt(0xFFFF) != 16\n");
		return -1;
	}

	if (lzcnt_s(0xFFFFFF) != 8)
	{
		fprintf(stderr, "__lzcnt(0xFFFFFF) != 8\n");
		return -1;
	}

	if (lzcnt_s(0xFFFFFFFF) != 0)
	{
		fprintf(stderr, "__lzcnt(0xFFFFFFFF) != 0\n");
		return -1;
	}

	return 0;
}

static int test_lzcnt16(void)
{
	if (__lzcnt16(0x1) != 15)
	{
		fprintf(stderr, "__lzcnt16(0x1) != 15\n");
		return -1;
	}

	if (__lzcnt16(0xFF) != 8)
	{
		fprintf(stderr, "__lzcnt16(0xFF) != 8\n");
		return -1;
	}

	if (__lzcnt16(0xFFFF) != 0)
	{
		fprintf(stderr, "__lzcnt16(0xFFFF) != 0\n");
		return -1;
	}

	return 0;
}

int TestIntrinsics(int argc, char* argv[])
{

	WINPR_UNUSED(argc);
	WINPR_UNUSED(argv);

	g_LZCNT = IsProcessorFeaturePresentEx(PF_EX_LZCNT);

	printf("LZCNT available: %" PRId32 "\n", g_LZCNT);

	// test_lzcnt16();
	return test_lzcnt();
}