xref: /openbsd-src/gnu/llvm/compiler-rt/lib/builtins/popcountsi2.c (revision 1f9cb04fc6f537ca6cf5a53c28927340cba218a2)
13cab2bb3Spatrick //===-- popcountsi2.c - Implement __popcountsi2 ---------------------------===//
23cab2bb3Spatrick //
33cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
43cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
53cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63cab2bb3Spatrick //
73cab2bb3Spatrick //===----------------------------------------------------------------------===//
83cab2bb3Spatrick //
93cab2bb3Spatrick // This file implements __popcountsi2 for the compiler_rt library.
103cab2bb3Spatrick //
113cab2bb3Spatrick //===----------------------------------------------------------------------===//
123cab2bb3Spatrick 
133cab2bb3Spatrick #include "int_lib.h"
143cab2bb3Spatrick 
153cab2bb3Spatrick // Returns: count of 1 bits
163cab2bb3Spatrick 
__popcountsi2(si_int a)17*1f9cb04fSpatrick COMPILER_RT_ABI int __popcountsi2(si_int a) {
183cab2bb3Spatrick   su_int x = (su_int)a;
193cab2bb3Spatrick   x = x - ((x >> 1) & 0x55555555);
203cab2bb3Spatrick   // Every 2 bits holds the sum of every pair of bits
213cab2bb3Spatrick   x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
223cab2bb3Spatrick   // Every 4 bits holds the sum of every 4-set of bits (3 significant bits)
233cab2bb3Spatrick   x = (x + (x >> 4)) & 0x0F0F0F0F;
243cab2bb3Spatrick   // Every 8 bits holds the sum of every 8-set of bits (4 significant bits)
253cab2bb3Spatrick   x = (x + (x >> 16));
263cab2bb3Spatrick   // The lower 16 bits hold two 8 bit sums (5 significant bits).
273cab2bb3Spatrick   //    Upper 16 bits are garbage
283cab2bb3Spatrick   return (x + (x >> 8)) & 0x0000003F; // (6 significant bits)
293cab2bb3Spatrick }
30