xref: /rk3399_ARM-atf/lib/compiler-rt/builtins/popcountsi2.c (revision 162fc183cf439efe029a581fbde8e4f936815f6d)
1*162fc183SLionel Debieve /* ===-- popcountsi2.c - Implement __popcountsi2 ---------------------------===
2*162fc183SLionel Debieve  *
3*162fc183SLionel Debieve  *                     The LLVM Compiler Infrastructure
4*162fc183SLionel Debieve  *
5*162fc183SLionel Debieve  * This file is dual licensed under the MIT and the University of Illinois Open
6*162fc183SLionel Debieve  * Source Licenses. See LICENSE.TXT for details.
7*162fc183SLionel Debieve  *
8*162fc183SLionel Debieve  * ===----------------------------------------------------------------------===
9*162fc183SLionel Debieve  *
10*162fc183SLionel Debieve  * This file implements __popcountsi2 for the compiler_rt library.
11*162fc183SLionel Debieve  *
12*162fc183SLionel Debieve  * ===----------------------------------------------------------------------===
13*162fc183SLionel Debieve  */
14*162fc183SLionel Debieve 
15*162fc183SLionel Debieve #include "int_lib.h"
16*162fc183SLionel Debieve 
17*162fc183SLionel Debieve /* Returns: count of 1 bits */
18*162fc183SLionel Debieve 
19*162fc183SLionel Debieve COMPILER_RT_ABI si_int
20*162fc183SLionel Debieve __popcountsi2(si_int a)
21*162fc183SLionel Debieve {
22*162fc183SLionel Debieve     su_int x = (su_int)a;
23*162fc183SLionel Debieve     x = x - ((x >> 1) & 0x55555555);
24*162fc183SLionel Debieve     /* Every 2 bits holds the sum of every pair of bits */
25*162fc183SLionel Debieve     x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
26*162fc183SLionel Debieve     /* Every 4 bits holds the sum of every 4-set of bits (3 significant bits) */
27*162fc183SLionel Debieve     x = (x + (x >> 4)) & 0x0F0F0F0F;
28*162fc183SLionel Debieve     /* Every 8 bits holds the sum of every 8-set of bits (4 significant bits) */
29*162fc183SLionel Debieve     x = (x + (x >> 16));
30*162fc183SLionel Debieve     /* The lower 16 bits hold two 8 bit sums (5 significant bits).*/
31*162fc183SLionel Debieve     /*    Upper 16 bits are garbage */
32*162fc183SLionel Debieve     return (x + (x >> 8)) & 0x0000003F;  /* (6 significant bits) */
33*162fc183SLionel Debieve }
34