popcountsi2.c revision 276789
167754Smsmith/* ===-- popcountsi2.c - Implement __popcountsi2 ---------------------------=== 267754Smsmith * 377424Smsmith * The LLVM Compiler Infrastructure 4167802Sjkim * 567754Smsmith * This file is dual licensed under the MIT and the University of Illinois Open 667754Smsmith * Source Licenses. See LICENSE.TXT for details. 767754Smsmith * 867754Smsmith * ===----------------------------------------------------------------------=== 967754Smsmith * 1067754Smsmith * This file implements __popcountsi2 for the compiler_rt library. 1167754Smsmith * 12167802Sjkim * ===----------------------------------------------------------------------=== 1370243Smsmith */ 1467754Smsmith 1567754Smsmith#include "int_lib.h" 1667754Smsmith 1767754Smsmith/* Returns: count of 1 bits */ 1867754Smsmith 1967754SmsmithCOMPILER_RT_ABI si_int 2067754Smsmith__popcountsi2(si_int a) 2167754Smsmith{ 2267754Smsmith su_int x = (su_int)a; 2367754Smsmith x = x - ((x >> 1) & 0x55555555); 2467754Smsmith /* Every 2 bits holds the sum of every pair of bits */ 2567754Smsmith x = ((x >> 2) & 0x33333333) + (x & 0x33333333); 2667754Smsmith /* Every 4 bits holds the sum of every 4-set of bits (3 significant bits) */ 2767754Smsmith x = (x + (x >> 4)) & 0x0F0F0F0F; 2867754Smsmith /* Every 8 bits holds the sum of every 8-set of bits (4 significant bits) */ 2967754Smsmith x = (x + (x >> 16)); 3067754Smsmith /* The lower 16 bits hold two 8 bit sums (5 significant bits).*/ 3167754Smsmith /* Upper 16 bits are garbage */ 3267754Smsmith return (x + (x >> 8)) & 0x0000003F; /* (6 significant bits) */ 3367754Smsmith} 3467754Smsmith