xref: /rk3399_ARM-atf/lib/compiler-rt/builtins/popcountsi2.c (revision 8a6a9560b5dcccfb68064c0c8c9b4b47981c6ac7)
1*8a6a9560SDaniel Boulby //===-- popcountsi2.c - Implement __popcountsi2 ---------------------------===//
2*8a6a9560SDaniel Boulby //
3*8a6a9560SDaniel Boulby // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*8a6a9560SDaniel Boulby // See https://llvm.org/LICENSE.txt for license information.
5*8a6a9560SDaniel Boulby // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*8a6a9560SDaniel Boulby //
7*8a6a9560SDaniel Boulby //===----------------------------------------------------------------------===//
8*8a6a9560SDaniel Boulby //
9*8a6a9560SDaniel Boulby // This file implements __popcountsi2 for the compiler_rt library.
10*8a6a9560SDaniel Boulby //
11*8a6a9560SDaniel Boulby //===----------------------------------------------------------------------===//
12162fc183SLionel Debieve 
13162fc183SLionel Debieve #include "int_lib.h"
14162fc183SLionel Debieve 
15*8a6a9560SDaniel Boulby // Returns: count of 1 bits
16162fc183SLionel Debieve 
17*8a6a9560SDaniel Boulby COMPILER_RT_ABI int __popcountsi2(si_int a) {
18162fc183SLionel Debieve   su_int x = (su_int)a;
19162fc183SLionel Debieve   x = x - ((x >> 1) & 0x55555555);
20*8a6a9560SDaniel Boulby   // Every 2 bits holds the sum of every pair of bits
21162fc183SLionel Debieve   x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
22*8a6a9560SDaniel Boulby   // Every 4 bits holds the sum of every 4-set of bits (3 significant bits)
23162fc183SLionel Debieve   x = (x + (x >> 4)) & 0x0F0F0F0F;
24*8a6a9560SDaniel Boulby   // Every 8 bits holds the sum of every 8-set of bits (4 significant bits)
25162fc183SLionel Debieve   x = (x + (x >> 16));
26*8a6a9560SDaniel Boulby   // The lower 16 bits hold two 8 bit sums (5 significant bits).
27*8a6a9560SDaniel Boulby   //    Upper 16 bits are garbage
28*8a6a9560SDaniel Boulby   return (x + (x >> 8)) & 0x0000003F; // (6 significant bits)
29162fc183SLionel Debieve }
30