]> git.sesse.net Git - stockfish/blob - src/bitboard.h
Simplify popcnt
[stockfish] / src / bitboard.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #ifndef BITBOARD_H_INCLUDED
22 #define BITBOARD_H_INCLUDED
23
24 #include <string>
25
26 #include "types.h"
27
28 namespace Bitbases {
29
30 void init();
31 bool probe(Square wksq, Square wpsq, Square bksq, Color us);
32
33 }
34
35 namespace Bitboards {
36
37 void init();
38 const std::string pretty(Bitboard b);
39
40 }
41
42 const Bitboard DarkSquares = 0xAA55AA55AA55AA55ULL;
43
44 const Bitboard FileABB = 0x0101010101010101ULL;
45 const Bitboard FileBBB = FileABB << 1;
46 const Bitboard FileCBB = FileABB << 2;
47 const Bitboard FileDBB = FileABB << 3;
48 const Bitboard FileEBB = FileABB << 4;
49 const Bitboard FileFBB = FileABB << 5;
50 const Bitboard FileGBB = FileABB << 6;
51 const Bitboard FileHBB = FileABB << 7;
52
53 const Bitboard Rank1BB = 0xFF;
54 const Bitboard Rank2BB = Rank1BB << (8 * 1);
55 const Bitboard Rank3BB = Rank1BB << (8 * 2);
56 const Bitboard Rank4BB = Rank1BB << (8 * 3);
57 const Bitboard Rank5BB = Rank1BB << (8 * 4);
58 const Bitboard Rank6BB = Rank1BB << (8 * 5);
59 const Bitboard Rank7BB = Rank1BB << (8 * 6);
60 const Bitboard Rank8BB = Rank1BB << (8 * 7);
61
62 extern int SquareDistance[SQUARE_NB][SQUARE_NB];
63
64 extern Bitboard  RookMasks  [SQUARE_NB];
65 extern Bitboard  RookMagics [SQUARE_NB];
66 extern Bitboard* RookAttacks[SQUARE_NB];
67 extern unsigned  RookShifts [SQUARE_NB];
68
69 extern Bitboard  BishopMasks  [SQUARE_NB];
70 extern Bitboard  BishopMagics [SQUARE_NB];
71 extern Bitboard* BishopAttacks[SQUARE_NB];
72 extern unsigned  BishopShifts [SQUARE_NB];
73
74 extern Bitboard SquareBB[SQUARE_NB];
75 extern Bitboard FileBB[FILE_NB];
76 extern Bitboard RankBB[RANK_NB];
77 extern Bitboard AdjacentFilesBB[FILE_NB];
78 extern Bitboard InFrontBB[COLOR_NB][RANK_NB];
79 extern Bitboard StepAttacksBB[PIECE_NB][SQUARE_NB];
80 extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
81 extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
82 extern Bitboard DistanceRingBB[SQUARE_NB][8];
83 extern Bitboard ForwardBB[COLOR_NB][SQUARE_NB];
84 extern Bitboard PassedPawnMask[COLOR_NB][SQUARE_NB];
85 extern Bitboard PawnAttackSpan[COLOR_NB][SQUARE_NB];
86 extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
87
88
89 /// Overloads of bitwise operators between a Bitboard and a Square for testing
90 /// whether a given bit is set in a bitboard, and for setting and clearing bits.
91
92 inline Bitboard operator&(Bitboard b, Square s) {
93   return b & SquareBB[s];
94 }
95
96 inline Bitboard operator|(Bitboard b, Square s) {
97   return b | SquareBB[s];
98 }
99
100 inline Bitboard operator^(Bitboard b, Square s) {
101   return b ^ SquareBB[s];
102 }
103
104 inline Bitboard& operator|=(Bitboard& b, Square s) {
105   return b |= SquareBB[s];
106 }
107
108 inline Bitboard& operator^=(Bitboard& b, Square s) {
109   return b ^= SquareBB[s];
110 }
111
112 inline bool more_than_one(Bitboard b) {
113   return b & (b - 1);
114 }
115
116
117 /// rank_bb() and file_bb() return a bitboard representing all the squares on
118 /// the given file or rank.
119
120 inline Bitboard rank_bb(Rank r) {
121   return RankBB[r];
122 }
123
124 inline Bitboard rank_bb(Square s) {
125   return RankBB[rank_of(s)];
126 }
127
128 inline Bitboard file_bb(File f) {
129   return FileBB[f];
130 }
131
132 inline Bitboard file_bb(Square s) {
133   return FileBB[file_of(s)];
134 }
135
136
137 /// shift_bb() moves a bitboard one step along direction Delta. Mainly for pawns
138
139 template<Square Delta>
140 inline Bitboard shift_bb(Bitboard b) {
141   return  Delta == DELTA_N  ?  b             << 8 : Delta == DELTA_S  ?  b             >> 8
142         : Delta == DELTA_NE ? (b & ~FileHBB) << 9 : Delta == DELTA_SE ? (b & ~FileHBB) >> 7
143         : Delta == DELTA_NW ? (b & ~FileABB) << 7 : Delta == DELTA_SW ? (b & ~FileABB) >> 9
144         : 0;
145 }
146
147
148 /// adjacent_files_bb() returns a bitboard representing all the squares on the
149 /// adjacent files of the given one.
150
151 inline Bitboard adjacent_files_bb(File f) {
152   return AdjacentFilesBB[f];
153 }
154
155
156 /// between_bb() returns a bitboard representing all the squares between the two
157 /// given ones. For instance, between_bb(SQ_C4, SQ_F7) returns a bitboard with
158 /// the bits for square d5 and e6 set. If s1 and s2 are not on the same rank, file
159 /// or diagonal, 0 is returned.
160
161 inline Bitboard between_bb(Square s1, Square s2) {
162   return BetweenBB[s1][s2];
163 }
164
165
166 /// in_front_bb() returns a bitboard representing all the squares on all the ranks
167 /// in front of the given one, from the point of view of the given color. For
168 /// instance, in_front_bb(BLACK, RANK_3) will return the squares on ranks 1 and 2.
169
170 inline Bitboard in_front_bb(Color c, Rank r) {
171   return InFrontBB[c][r];
172 }
173
174
175 /// forward_bb() returns a bitboard representing all the squares along the line
176 /// in front of the given one, from the point of view of the given color:
177 ///        ForwardBB[c][s] = in_front_bb(c, s) & file_bb(s)
178
179 inline Bitboard forward_bb(Color c, Square s) {
180   return ForwardBB[c][s];
181 }
182
183
184 /// pawn_attack_span() returns a bitboard representing all the squares that can be
185 /// attacked by a pawn of the given color when it moves along its file, starting
186 /// from the given square:
187 ///       PawnAttackSpan[c][s] = in_front_bb(c, s) & adjacent_files_bb(s);
188
189 inline Bitboard pawn_attack_span(Color c, Square s) {
190   return PawnAttackSpan[c][s];
191 }
192
193
194 /// passed_pawn_mask() returns a bitboard mask which can be used to test if a
195 /// pawn of the given color and on the given square is a passed pawn:
196 ///       PassedPawnMask[c][s] = pawn_attack_span(c, s) | forward_bb(c, s)
197
198 inline Bitboard passed_pawn_mask(Color c, Square s) {
199   return PassedPawnMask[c][s];
200 }
201
202
203 /// aligned() returns true if the squares s1, s2 and s3 are aligned either on a
204 /// straight or on a diagonal line.
205
206 inline bool aligned(Square s1, Square s2, Square s3) {
207   return LineBB[s1][s2] & s3;
208 }
209
210
211 /// distance() functions return the distance between x and y, defined as the
212 /// number of steps for a king in x to reach y. Works with squares, ranks, files.
213
214 template<typename T> inline int distance(T x, T y) { return x < y ? y - x : x - y; }
215 template<> inline int distance<Square>(Square x, Square y) { return SquareDistance[x][y]; }
216
217 template<typename T1, typename T2> inline int distance(T2 x, T2 y);
218 template<> inline int distance<File>(Square x, Square y) { return distance(file_of(x), file_of(y)); }
219 template<> inline int distance<Rank>(Square x, Square y) { return distance(rank_of(x), rank_of(y)); }
220
221
222 /// attacks_bb() returns a bitboard representing all the squares attacked by a
223 /// piece of type Pt (bishop or rook) placed on 's'. The helper magic_index()
224 /// looks up the index using the 'magic bitboards' approach.
225 template<PieceType Pt>
226 inline unsigned magic_index(Square s, Bitboard occupied) {
227
228   Bitboard* const Masks  = Pt == ROOK ? RookMasks  : BishopMasks;
229   Bitboard* const Magics = Pt == ROOK ? RookMagics : BishopMagics;
230   unsigned* const Shifts = Pt == ROOK ? RookShifts : BishopShifts;
231
232   if (HasPext)
233       return unsigned(pext(occupied, Masks[s]));
234
235   if (Is64Bit)
236       return unsigned(((occupied & Masks[s]) * Magics[s]) >> Shifts[s]);
237
238   unsigned lo = unsigned(occupied) & unsigned(Masks[s]);
239   unsigned hi = unsigned(occupied >> 32) & unsigned(Masks[s] >> 32);
240   return (lo * unsigned(Magics[s]) ^ hi * unsigned(Magics[s] >> 32)) >> Shifts[s];
241 }
242
243 template<PieceType Pt>
244 inline Bitboard attacks_bb(Square s, Bitboard occupied) {
245   return (Pt == ROOK ? RookAttacks : BishopAttacks)[s][magic_index<Pt>(s, occupied)];
246 }
247
248 inline Bitboard attacks_bb(Piece pc, Square s, Bitboard occupied) {
249
250   switch (type_of(pc))
251   {
252   case BISHOP: return attacks_bb<BISHOP>(s, occupied);
253   case ROOK  : return attacks_bb<ROOK>(s, occupied);
254   case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
255   default    : return StepAttacksBB[pc][s];
256   }
257 }
258
259
260 /// popcount() counts the number of non-zero bits in a bitboard
261
262 inline int popcount(Bitboard b) {
263
264 #ifndef USE_POPCNT
265
266   extern uint8_t PopCnt16[1 << 16];
267   union { Bitboard bb; uint16_t u[4]; } v = { b };
268   return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
269
270 #elif defined(_MSC_VER) && defined(__INTEL_COMPILER)
271
272   return _mm_popcnt_u64(b);
273
274 #elif defined(_MSC_VER)
275
276   return (int)__popcnt64(b);
277
278 #else // Assumed gcc or compatible compiler
279
280   return __builtin_popcountll(b);
281
282 #endif
283 }
284
285
286 /// lsb() and msb() return the least/most significant bit in a non-zero bitboard
287
288 #if defined(__GNUC__)
289
290 inline Square lsb(Bitboard b) {
291   assert(b);
292   return Square(__builtin_ctzll(b));
293 }
294
295 inline Square msb(Bitboard b) {
296   assert(b);
297   return Square(63 - __builtin_clzll(b));
298 }
299
300 #elif defined(_WIN64) && defined(_MSC_VER)
301
302 inline Square lsb(Bitboard b) {
303   assert(b);
304   unsigned long idx;
305   _BitScanForward64(&idx, b);
306   return (Square) idx;
307 }
308
309 inline Square msb(Bitboard b) {
310   assert(b);
311   unsigned long idx;
312   _BitScanReverse64(&idx, b);
313   return (Square) idx;
314 }
315
316 #else
317
318 #define NO_BSF // Fallback on software implementation for other cases
319
320 Square lsb(Bitboard b);
321 Square msb(Bitboard b);
322
323 #endif
324
325
326 /// pop_lsb() finds and clears the least significant bit in a non-zero bitboard
327
328 inline Square pop_lsb(Bitboard* b) {
329   const Square s = lsb(*b);
330   *b &= *b - 1;
331   return s;
332 }
333
334
335 /// frontmost_sq() and backmost_sq() return the square corresponding to the
336 /// most/least advanced bit relative to the given color.
337
338 inline Square frontmost_sq(Color c, Bitboard b) { return c == WHITE ? msb(b) : lsb(b); }
339 inline Square  backmost_sq(Color c, Bitboard b) { return c == WHITE ? lsb(b) : msb(b); }
340
341 #endif // #ifndef BITBOARD_H_INCLUDED