BitScan,
a function that determines the bit-index of the least significant 1 bit (LS1B) or the most significant 1 bit (MS1B) in an integer such as bitboards. If exactly one bit is set in an unsigned integer, representing a numerical value of a power of two, this is equivalent to a base-2 logarithm. Many implementations have been devised since the advent of bitboards, as described on this page, and some implementation samples of concrete open source engines listed for didactic purpose.
For recent x86-64 architectures like Core 2 duo and K10, one should use the Processor Instructions for Bitscans via intrinsics or inline assembly, see x86-64 timing. P4 and K8 have rather slow bitscan-instructions. K8 uses so called vector path instructions[2] with 9 or 11 cycles latency, even blocking other processor resources. For these processors, specially K8 with already fast multiplication, the De Bruijn Multiplication (64-bit mode) or Matt Taylor'sFolded 32-bit Multiplication (32-bit mode) might be the right choice. Other routines mentioned might be advantageous on certain architectures, specially with slow integer multiplications.
Non Empty Sets
Bitscan is most often used in serializing bitboards, and is therefor - due to a leading while-condition - not called with empty sets. Until stated otherwise, most mentioned bitscan-routines in C/C++ have the same prototype and assume none empty sets as actual parameter.
Bitscan forward
A bitscan forward is used to find the index of the least significant 1 bit (LS1B).
Trailing Zero Count
Bitscan forward is identical with a Trailing Zero Count for none empty sets, possibly available as machine instruction on some architectures, for instance the x86-64 bit-manipulation expansion set BMI1.
A 64-bit De Bruijn sequence contains 64-overlapped unique 6-bit sequences, thus a circle of 64 bits, where five leading zeros overlap five hidden "trailing" zeros. There are 226 = 67108864 odd sequences with 6 leading binary zeros and 226 even sequences with 5 leading binary zeros, which may be calculated from the odd ones by shifting left one.
With isolated LS1B
A multiplication with a power of two value (the isolated LS1B) acts like a left shift by it's exponent. Thus, if we multiply a 64-bit De Bruijn sequence with the isolated LS1B, we get a unique six bit subsequence inside the most significant bits. To obtain the bit-index we need to extract these upper six bits by shifting right the product, to lookup an array.
constint index64[64]={0, 1, 48, 2, 57, 49, 28, 3,
61, 58, 50, 42, 38, 29, 17, 4,
62, 55, 59, 36, 53, 51, 43, 22,
45, 39, 33, 30, 24, 18, 12, 5,
63, 47, 56, 27, 60, 41, 37, 16,
54, 35, 52, 21, 44, 32, 23, 11,
46, 26, 40, 15, 34, 20, 31, 10,
25, 14, 19, 9, 13, 8, 7, 6};/**
* bitScanForward
* @author Martin Läuter (1997)
* Charles E. Leiserson
* Harald Prokop
* Keith H. Randall
* "Using de Bruijn Sequences to Index a 1 in a Computer Word"
* @param bb bitboard to scan
* @precondition bb != 0
* @return index (0..63) of least significant one bit
*/int bitScanForward(U64 bb){const U64 debruijn64 = C64(0x03f79d71b4cb0a89);assert(bb !=0);return index64[((bb &-bb)* debruijn64)>>58];}
Instead of the classical LS1B isolation, Kim Walisch proposed the faster xor with the ones' decrement. The separation bb ^ (bb-1) contains all bits set including and below the LS1B. The 222 (4,194,304) upper De Bruijn sequences of the 226 available leave unique 6-bit indices. Using LS1B separation takes advantage of the x86 lea instruction, which saves the move instruction and unlike negate, has no data dependency on the flag register. Kim reported a 10 to 15 percent faster execution (compilers: g++-4.7 -O2, clang++-3.1 -O2, x86_64) than the traditional 64-bit De Bruijn bitscan on IntelNehalem and Sandy Bridge CPUs.
A 32-bit friendly implementation to find the the bit-index of LS1B by Matt Taylor[7]. The xor with the ones' decrement, bb ^ (bb-1) contains all bits set including and below the LS1B. The 32-bit xor-difference of both halves yields either the complement of the upper half, or the lower half otherwise. Some samples:
ls1b
bb ^ (bb-1)
folded
63
0xffffffffffffffff
0x00000000
62
0x7fffffffffffffff
0x80000000
59
0x0fffffffffffffff
0xf0000000
32
0x00000001ffffffff
0xfffffffe
31
0x00000000ffffffff
0xffffffff
30
0x000000007fffffff
0x7fffffff
0
0x0000000000000001
0x00000001
Even if this folded "LS1B" contains multiple consecutive one-bits, the multiplication is De Bruijn like. There are only two magic 32-bit constants with the combined property of 32- and 64-bit De Bruijn sequences to apply this minimal perfect hashing:
while Walter originally resets the LS1B, yielding in a cyclic index wrap:
LS1B
(bb & (bb-1)) ^ (bb-1)
folded
0
0x0000000000000000
0x00000000
63
0x7fffffffffffffff
0x80000000
60
0x0fffffffffffffff
0xf0000000
33
0x00000001ffffffff
0xfffffffe
32
0x00000000ffffffff
0xffffffff
31
0x000000007fffffff
0x7fffffff
1
0x0000000000000001
0x00000001
Bitscan by Modulo
Another idea is to apply a modulo (remainder of a division) operation of the isolated LS1B by the prime number 67 [9][10] . The remainder 0..66 can be used to perfectly hash the bit-index table. Three gaps are 0, 17, and 34, so the mod 67 can make a branchless trailing zero count:
Since div/mod is an expensive instruction, a modulo by a constant is likely replaced by reciprocal fixed point multiplication to get the quotient and a second multiplication and difference to get the remainder. Compared with De Bruijn multiplication it is still too slow.
Divide and Conquer
This is a broad group of bitscans that test in succession, like the trailing zero count based on Reinhard Scharnagl's proposal [11] :
A bitscan reverse is used to find the index of the most significant 1 bit (MS1B). For non empty sets it is equivalent to floor of the base-2 logarithm. MS1B isolalation or separation is more expensive than LS1B isolalation or separation, due to the LS1B related Two's complement tricks are not applicable. However, beside Divide and Conquer and Double conversion, Bitscan reverse with MS1B separation is mentioned.
/**
* bitScanReverse
* @author Eugene Nalimov
* @param bb bitboard to scan
* @return index (0..63) of most significant one bit
*/int bitScanReverse(U64 bb){int result =0;if(bb >0xFFFFFFFF){
bb >>=32;
result =32;}if(bb >0xFFFF){
bb >>=16;
result +=16;}if(bb >0xFF){
bb >>=8;
result +=8;}return result + ms1bTable[bb];}
typedefunsigned __int64 OneSizeFits;typedefunsignedint HotRats;const HotRats s =0;const HotRats heik =457;const HotRats y =1;const HotRats e =2;const HotRats r =3;const HotRats b =4;const HotRats o =5;const HotRats u =8;const HotRats t =16;const HotRats i =32;const HotRats ka =(1<<4)-1;const HotRats waka =(1<<8)-1;const HotRats jawaka =(1<<16)-1;const HotRats jazzFromHell =0-(16*3*heik);
HotRats freakOut(OneSizeFits all){
HotRats so,fa;
fa =(HotRats)(all >> i);
so =(fa!=s)<< o;
fa ^=(HotRats) all &(fa!=s)-y;
so ^=(jawaka < fa)<< b;
fa >>=(jawaka < fa)<< b;
so ^=( waka - fa)>> t & u;
fa >>=( waka - fa)>> t & u;
so ^=( ka - fa)>> u & b;
fa >>=( ka - fa)>> u & b;
so ^= jazzFromHell >> e*fa & r;return so;}
De Bruijn Multiplication
While the tribute to Frank Zappa is quite 32-bit friendly [15], Kim Walisch suggested to use the parallel prefix fill for a MS1B separation with the same De Bruijn multiplication and lookup as in his bitScanForward routine with separated LS1B, with less instructions in 64-bit mode. A log base 2 method was already devised by Eric Cole on January 8, 2006, and shaved off rounded up to one less than the next power of 2 by Mark Dickinson [16] on December 10, 2009, as published in Sean Eron Anderson's Bit Twiddling Hacks for 32-bit integers [17].
Assuming 64-bit doubles and little-endian structure (not portable!). Conversion to a double, interpreting the exponent. To avoid possible rounding errors, some lower bits may be cleared.
/**
* bitScanReverse
* @author Gerd Isenberg
* @param bb bitboard to scan
* @return index (0..63) of most significant one bit
* -1023 if passing zero
*/int bitScanReverse(U64 bb){union{double d;struct{unsignedint mantissal :32;unsignedint mantissah :20;unsignedint exponent :11;unsignedint sign :1;};} ud;
ud.d=(double)(bb & ~(bb >>32));// avoid rounding errorreturn ud.exponent-1023;}
Leading Zero Count
Some processors have a fast leading zero count instruction. The Motorola68020 has a bit field find first one instruction (BFFFO), which actually performs an up to 32-bit Leading Zero Count[18] . x86-64AMDK10 has lzcnt as part of the SSE4a extension [19][20] , BMI1 has lzcnt as well, while AVX-512CD even features leading zero count on vectors of eight bitbaords.
One can replace bitScanReverse of non empty sets by leadingZeroCount xor 63. Like trailing zero count, it returns 64 for empty sets, and might therefor save the leading condition in some applications.
Bitscan versus Zero Count
While the presented bitscan routines are suited to work only on none empty sets and return a value-range from 0 to 63 as bit-index, leading or trailing zero-count instructions or routines leave 64 for empty sets. Zero-counting has a immanent property of dealing correctly with empty sets - while it likely takes a conditional branch to implement this semantic in bit-scanning.
While traversing sets, one may combine bitscanning with reset found bit. That implies passing the bitboard per reference or pointer, and tends to confuse compilers to keep all inside registers inside a typical serialization loop [21] .
int bitScanForwardWithReset(U64 &bb){// also called dropForwardint idx = bitScanForward(bb);
bb &= bb -1;// reset bit outsidereturn idx;}
Generalized Bitscan
This generalized bitscan uses a boolean parameter to scan reverse or forward. It relies on bitScanReverse, but conditionally masks the LS1B in case of scanning forward. It might be used in the classical approach to get positive or negative ray directions with one generalized routine.
/**
* generalized bitScan
* @author Gerd Isenberg
* @param bb bitboard to scan
* @precondition bb != 0
* @param reverse, true bitScanReverse, false bitScanForward
* @return index (0..63) of least/most significant one bit
*/int bitScan(U64 bb, bool reverse){
U64 rMask;assert(bb !=0);
rMask =-(U64)reverse;
bb &=-bb | rMask;return bitScanReverse(bb);}
Processor Instructions for Bitscans
x86
x86-64 processors have bitscan instructions and can be accessed with compilers today through either inline assembly or compiler intrinsics. For the Microsoft/Intel C compiler, the intrinsics can be accessed by including and using the instructions _BitScanForward64[22] , _BitScanReverse64[23] or _lzcnt64 [24] .
unsigned char_BitScanForward64(unsignedlong* Index, unsigned __int64 Mask);unsignedchar _BitScanReverse64(unsignedlong* Index, unsigned __int64 Mask);unsigned __int64 __lzcnt64(unsigned __int64 value);// AMD K10 only see CPUID
Linux provides library functions [25] , find first bit set (ffsll) in a word leaves an index of 1..64, and zero of no bit is set [26] . GCC 4.4.5 further has the Built-in Function _builtin_ffsll for finding the least significant one bit, _builtin_ctzll for trailing, and _builtin_clzll for leading zero count [27] :
/* Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero */int __builtin_ffsll (unsignedlonglong);/* Returns the number of trailing 0-bits in x, starting at the least significant bit position.
If x is 0, the result is undefined */int __builtin_ctzll (unsignedlonglong);/* Returns the number of leading 0-bits in x, starting at the most significant bit position.
If x is 0, the result is undefined */int __builtin_clzll (unsignedlonglong);
Emulating Intrinsics
For the GNU C compiler, the intrinsics can be emulated with inline assembly[28] .
Intel and AMD specify different behavior. In praxis there seems no difference so far. However, as long as Intel docs explicitly state content undefined, it is recommend to don't rely on a pre-initialized content of that target register, if the source is zero.
Intel : If the content of the source operand is 0, the content of the destination operand is undefined.[35]
AMD: If the second operand contains 0, the instruction sets ZF to 1 and does not change the contents of the destination register.[36]
^N. G. de Bruijn (1975). Acknowledgement of priority to C. Flye Sainte-Marie on the counting of circular arrangements of 2n zeros and ones that show each n-letter word exactly once. Technical Report, Technische Hogeschool Eindhoven, available as pdf reprint
a function that determines the bit-index of the least significant 1 bit (LS1B) or the most significant 1 bit (MS1B) in an integer such as bitboards. If exactly one bit is set in an unsigned integer, representing a numerical value of a power of two, this is equivalent to a base-2 logarithm. Many implementations have been devised since the advent of bitboards, as described on this page, and some implementation samples of concrete open source engines listed for didactic purpose.
Table of Contents
Hardware vs. Software
For recent x86-64 architectures like Core 2 duo and K10, one should use the Processor Instructions for Bitscans via intrinsics or inline assembly, see x86-64 timing. P4 and K8 have rather slow bitscan-instructions. K8 uses so called vector path instructions [2] with 9 or 11 cycles latency, even blocking other processor resources. For these processors, specially K8 with already fast multiplication, the De Bruijn Multiplication (64-bit mode) or Matt Taylor's Folded 32-bit Multiplication (32-bit mode) might be the right choice. Other routines mentioned might be advantageous on certain architectures, specially with slow integer multiplications.Non Empty Sets
Bitscan is most often used in serializing bitboards, and is therefor - due to a leading while-condition - not called with empty sets. Until stated otherwise, most mentioned bitscan-routines in C/C++ have the same prototype and assume none empty sets as actual parameter.Bitscan forward
A bitscan forward is used to find the index of the least significant 1 bit (LS1B).Trailing Zero Count
Bitscan forward is identical with a Trailing Zero Count for none empty sets, possibly available as machine instruction on some architectures, for instance the x86-64 bit-manipulation expansion set BMI1.De Bruijn Multiplication
The De Bruijn bitscan was devised in 1997, according to Donald Knuth [3] by Martin Läuter, and independently by Charles Leiserson, Harald Prokop and Keith H. Randall a few month later [4] [5] , to determine the LS1B index by minimal perfect hashing. De Bruijn sequences were named after the Dutch mathematician Nicolaas de Bruijn. Interestingly sequences with the binary alphabet were already investigated by the French mathematician Camille Flye Sainte-Marie in 1894, but later "forgotten" and re-investigated and generalized by De Bruijn and Tanja van Ardenne-Ehrenfest half a century later [6] .A 64-bit De Bruijn sequence contains 64-overlapped unique 6-bit sequences, thus a circle of 64 bits, where five leading zeros overlap five hidden "trailing" zeros. There are 226 = 67108864 odd sequences with 6 leading binary zeros and 226 even sequences with 5 leading binary zeros, which may be calculated from the odd ones by shifting left one.
With isolated LS1B
A multiplication with a power of two value (the isolated LS1B) acts like a left shift by it's exponent. Thus, if we multiply a 64-bit De Bruijn sequence with the isolated LS1B, we get a unique six bit subsequence inside the most significant bits. To obtain the bit-index we need to extract these upper six bits by shifting right the product, to lookup an array.See also how to Generate your "private" De Bruijn Bitscan Routine.
With separated LS1B
Instead of the classical LS1B isolation, Kim Walisch proposed the faster xor with the ones' decrement. The separation bb ^ (bb-1) contains all bits set including and below the LS1B. The 222 (4,194,304) upper De Bruijn sequences of the 226 available leave unique 6-bit indices. Using LS1B separation takes advantage of the x86 lea instruction, which saves the move instruction and unlike negate, has no data dependency on the flag register. Kim reported a 10 to 15 percent faster execution (compilers: g++-4.7 -O2, clang++-3.1 -O2, x86_64) than the traditional 64-bit De Bruijn bitscan on Intel Nehalem and Sandy Bridge CPUs.Matt Taylor's Folding trick
A 32-bit friendly implementation to find the the bit-index of LS1B by Matt Taylor [7]. The xor with the ones' decrement, bb ^ (bb-1) contains all bits set including and below the LS1B. The 32-bit xor-difference of both halves yields either the complement of the upper half, or the lower half otherwise. Some samples:Even if this folded "LS1B" contains multiple consecutive one-bits, the multiplication is De Bruijn like. There are only two magic 32-bit constants with the combined property of 32- and 64-bit De Bruijn sequences to apply this minimal perfect hashing:
A slightly modified version may take one x86-register less in 32-bit mode, but calculates bb-1 twice:
with this VC6 generated x86 assembly to compare:
Walter Faxon's magic Bitscan
Walter Faxon's 32-bit friendly magic bitscan [8] uses a fast none minimal perfect hashing function:A slightly modified version may take one x86-register less in 32-bit mode, but calculates bb-1 twice:
The initial LS1B separation by bb ^ (bb-1) and folding is equivalent to Matt's,
Bitscan by Modulo
Another idea is to apply a modulo (remainder of a division) operation of the isolated LS1B by the prime number 67 [9] [10] . The remainder 0..66 can be used to perfectly hash the bit-index table. Three gaps are 0, 17, and 34, so the mod 67 can make a branchless trailing zero count:Since div/mod is an expensive instruction, a modulo by a constant is likely replaced by reciprocal fixed point multiplication to get the quotient and a second multiplication and difference to get the remainder. Compared with De Bruijn multiplication it is still too slow.
Divide and Conquer
This is a broad group of bitscans that test in succession, like the trailing zero count based on Reinhard Scharnagl's proposal [11] :What about direct calculation? On x86 this is a chain of test, set and lea instructions:
Double conversion of LS1B
Assuming 64-bit doubles and little-endian structure (not portable). We convert the isolated LS1B to a double and interprete the exponent:Index of LS1B by Popcount
If we have a fast population-count instruction, we can count the trailing zeros of LS1B after subtracting one:Bitscan reverse
A bitscan reverse is used to find the index of the most significant 1 bit (MS1B). For non empty sets it is equivalent to floor of the base-2 logarithm. MS1B isolalation or separation is more expensive than LS1B isolalation or separation, due to the LS1B related Two's complement tricks are not applicable. However, beside Divide and Conquer and Double conversion, Bitscan reverse with MS1B separation is mentioned.Divide and Conquer
As introduced by Eugene Nalimov in 2000, for an IA-64 version of Crafty [12] [13]Tribute to Frank Zappa
A branchless and little bit obfuscated version of the devide and conquer bitScanReverse with in-register-lookup [14] - as tribute to Frank Zappa with identifiers from Freak Out! (1966), Hot Rats (1969), Waka/Jawaka (1972), Sofa (1975), One Size Fits All (1975), Sheik Yerbouti (1979), and Jazz from Hell (1986):De Bruijn Multiplication
While the tribute to Frank Zappa is quite 32-bit friendly [15], Kim Walisch suggested to use the parallel prefix fill for a MS1B separation with the same De Bruijn multiplication and lookup as in his bitScanForward routine with separated LS1B, with less instructions in 64-bit mode. A log base 2 method was already devised by Eric Cole on January 8, 2006, and shaved off rounded up to one less than the next power of 2 by Mark Dickinson [16] on December 10, 2009, as published in Sean Eron Anderson's Bit Twiddling Hacks for 32-bit integers [17].Double conversion
Assuming 64-bit doubles and little-endian structure (not portable!). Conversion to a double, interpreting the exponent. To avoid possible rounding errors, some lower bits may be cleared.Leading Zero Count
Some processors have a fast leading zero count instruction. The Motorola 68020 has a bit field find first one instruction (BFFFO), which actually performs an up to 32-bit Leading Zero Count [18] . x86-64 AMD K10 has lzcnt as part of the SSE4a extension [19] [20] , BMI1 has lzcnt as well, while AVX-512CD even features leading zero count on vectors of eight bitbaords.One can replace bitScanReverse of non empty sets by leadingZeroCount xor 63. Like trailing zero count, it returns 64 for empty sets, and might therefor save the leading condition in some applications.
Bitscan versus Zero Count
While the presented bitscan routines are suited to work only on none empty sets and return a value-range from 0 to 63 as bit-index, leading or trailing zero-count instructions or routines leave 64 for empty sets. Zero-counting has a immanent property of dealing correctly with empty sets - while it likely takes a conditional branch to implement this semantic in bit-scanning.Bitscan with Reset
While traversing sets, one may combine bitscanning with reset found bit. That implies passing the bitboard per reference or pointer, and tends to confuse compilers to keep all inside registers inside a typical serialization loop [21] .Generalized Bitscan
This generalized bitscan uses a boolean parameter to scan reverse or forward. It relies on bitScanReverse, but conditionally masks the LS1B in case of scanning forward. It might be used in the classical approach to get positive or negative ray directions with one generalized routine.Processor Instructions for Bitscans
x86
x86-64 processors have bitscan instructions and can be accessed with compilers today through either inline assembly or compiler intrinsics. For the Microsoft/Intel C compiler, the intrinsics can be accessed by including and using the instructions _BitScanForward64 [22] , _BitScanReverse64 [23] or _lzcnt64 [24] .Linux provides library functions [25] , find first bit set (ffsll) in a word leaves an index of 1..64, and zero of no bit is set [26] . GCC 4.4.5 further has the Built-in Function _builtin_ffsll for finding the least significant one bit, _builtin_ctzll for trailing, and _builtin_clzll for leading zero count [27] :
Emulating Intrinsics
For the GNU C compiler, the intrinsics can be emulated with inline assembly [28] .Intrinsics versus asm
Alternatively, rather than to emulate the intrinsics one might use the standard prototype, by using intrinsics or inline assembly for GCC [29] :Bsf/Bsr x86-64 Timings
The instruction latency and reciprocal throughput [30] heavily differs between various x86-64 architectures:Ivy Bridge
Haswell [34]
Bsf/Bsr behavior with zero source
Intel and AMD specify different behavior. In praxis there seems no difference so far. However, as long as Intel docs explicitly state content undefined, it is recommend to don't rely on a pre-initialized content of that target register, if the source is zero.ARM
ARM has CLZ (Count Leading Zeros) instruction for 32-bit integers. ARM instruction is available in ARMv5 and above, 32-bit Thumb instruction is available in ARMv6T2 and ARMv7 [37] , the C-intrinsic is called _builtin_clz [38] [39] [40] .Engine Samples
See also
Publications
Forum Posts
1996 ...
2000 ...
Re: Will the Itanium have a BSF or BSR instruction? by Eugene Nalimov, CCC, August 16, 2000
Re: Nalimov: bsf/bsr intrinsics implementation still not optimal by Eugene Nalimov, CCC, September 23, 2004
2005 ...
2010 ...
2015 ...
External Links
References
What links here?
Up one Level