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