xref: /llvm-project/compiler-rt/test/builtins/Unit/popcountsi2_test.c (revision 0ee439b705e82a4fe20e266bc8fea96d0e60e1ec)
1 // RUN: %clang_builtins %s %librt -o %t && %run %t
2 // REQUIRES: librt_has_popcountsi2
3 
4 #include "int_lib.h"
5 #include <stdio.h>
6 #include <stdlib.h>
7 
8 // Returns: count of 1 bits
9 
10 COMPILER_RT_ABI int __popcountsi2(si_int a);
11 
naive_popcount(si_int a)12 int naive_popcount(si_int a)
13 {
14     int r = 0;
15     for (; a; a = (su_int)a >> 1)
16         r += a & 1;
17     return r;
18 }
19 
test__popcountsi2(si_int a)20 int test__popcountsi2(si_int a)
21 {
22     si_int x = __popcountsi2(a);
23     si_int expected = naive_popcount(a);
24     if (x != expected)
25         printf("error in __popcountsi2(0x%X) = %d, expected %d\n",
26                a, x, expected);
27     return x != expected;
28 }
29 
30 char assumption_2[sizeof(si_int)*CHAR_BIT == 32] = {0};
31 
main()32 int main()
33 {
34     if (test__popcountsi2(0))
35         return 1;
36     if (test__popcountsi2(1))
37         return 1;
38     if (test__popcountsi2(2))
39         return 1;
40     if (test__popcountsi2(0xFFFFFFFD))
41         return 1;
42     if (test__popcountsi2(0xFFFFFFFE))
43         return 1;
44     if (test__popcountsi2(0xFFFFFFFF))
45         return 1;
46     int i;
47     for (i = 0; i < 10000; ++i)
48         if (test__popcountsi2(rand()))
49             return 1;
50 
51    return 0;
52 }
53