summaryrefslogtreecommitdiff
path: root/libraries/ghc-prim/cbits/popcnt.c
blob: 70662e80459d1bcaf7727b157b1fc677a43097f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "Rts.h"
#include "MachDeps.h"

static const unsigned char popcount_tab[] =
{
    0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
    1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
    1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
    2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
    1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
    2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
    2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
    3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8,
};

extern StgWord hs_popcnt8(StgWord x);
StgWord
hs_popcnt8(StgWord x)
{
  return popcount_tab[(unsigned char)x];
}

extern StgWord hs_popcnt16(StgWord x);
StgWord
hs_popcnt16(StgWord x)
{
  return popcount_tab[(unsigned char)x] +
      popcount_tab[(unsigned char)(x >> 8)];
}

extern StgWord hs_popcnt32(StgWord x);
StgWord
hs_popcnt32(StgWord x)
{
  return popcount_tab[(unsigned char)x] +
      popcount_tab[(unsigned char)(x >> 8)] +
      popcount_tab[(unsigned char)(x >> 16)] +
      popcount_tab[(unsigned char)(x >> 24)];
}

extern StgWord hs_popcnt64(StgWord64 x);
StgWord
hs_popcnt64(StgWord64 x)
{
  return popcount_tab[(unsigned char)x] +
      popcount_tab[(unsigned char)(x >> 8)] +
      popcount_tab[(unsigned char)(x >> 16)] +
      popcount_tab[(unsigned char)(x >> 24)] +
      popcount_tab[(unsigned char)(x >> 32)] +
      popcount_tab[(unsigned char)(x >> 40)] +
      popcount_tab[(unsigned char)(x >> 48)] +
      popcount_tab[(unsigned char)(x >> 56)];
}

#if WORD_SIZE_IN_BITS == 32

extern StgWord hs_popcnt(StgWord x);
StgWord
hs_popcnt(StgWord x)
{
  return popcount_tab[(unsigned char)x] +
      popcount_tab[(unsigned char)(x >> 8)] +
      popcount_tab[(unsigned char)(x >> 16)] +
      popcount_tab[(unsigned char)(x >> 24)];
}

#elif WORD_SIZE_IN_BITS == 64

extern StgWord hs_popcnt(StgWord x);
StgWord
hs_popcnt(StgWord x)
{
  return popcount_tab[(unsigned char)x] +
      popcount_tab[(unsigned char)(x >> 8)] +
      popcount_tab[(unsigned char)(x >> 16)] +
      popcount_tab[(unsigned char)(x >> 24)] +
      popcount_tab[(unsigned char)(x >> 32)] +
      popcount_tab[(unsigned char)(x >> 40)] +
      popcount_tab[(unsigned char)(x >> 48)] +
      popcount_tab[(unsigned char)(x >> 56)];
}

#else

#error Unknown machine word size

#endif