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