]> git.sesse.net Git - stockfish/blob - src/bitboard.h
70835e8eeff144ef08c7b19753933ea18ca7798e
[stockfish] / src / bitboard.h
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #ifndef BITBOARD_H_INCLUDED
20 #define BITBOARD_H_INCLUDED
21
22 #include <string>
23
24 #include "types.h"
25
26 namespace Stockfish {
27
28 namespace Bitbases {
29
30 void init();
31 bool probe(Square wksq, Square wpsq, Square bksq, Color us);
32
33 } // namespace Stockfish::Bitbases
34
35 namespace Bitboards {
36
37 void init();
38 std::string pretty(Bitboard b);
39
40 } // namespace Stockfish::Bitboards
41
42 constexpr Bitboard AllSquares = ~Bitboard(0);
43 constexpr Bitboard DarkSquares = 0xAA55AA55AA55AA55ULL;
44
45 constexpr Bitboard FileABB = 0x0101010101010101ULL;
46 constexpr Bitboard FileBBB = FileABB << 1;
47 constexpr Bitboard FileCBB = FileABB << 2;
48 constexpr Bitboard FileDBB = FileABB << 3;
49 constexpr Bitboard FileEBB = FileABB << 4;
50 constexpr Bitboard FileFBB = FileABB << 5;
51 constexpr Bitboard FileGBB = FileABB << 6;
52 constexpr Bitboard FileHBB = FileABB << 7;
53
54 constexpr Bitboard Rank1BB = 0xFF;
55 constexpr Bitboard Rank2BB = Rank1BB << (8 * 1);
56 constexpr Bitboard Rank3BB = Rank1BB << (8 * 2);
57 constexpr Bitboard Rank4BB = Rank1BB << (8 * 3);
58 constexpr Bitboard Rank5BB = Rank1BB << (8 * 4);
59 constexpr Bitboard Rank6BB = Rank1BB << (8 * 5);
60 constexpr Bitboard Rank7BB = Rank1BB << (8 * 6);
61 constexpr Bitboard Rank8BB = Rank1BB << (8 * 7);
62
63 constexpr Bitboard QueenSide   = FileABB | FileBBB | FileCBB | FileDBB;
64 constexpr Bitboard CenterFiles = FileCBB | FileDBB | FileEBB | FileFBB;
65 constexpr Bitboard KingSide    = FileEBB | FileFBB | FileGBB | FileHBB;
66 constexpr Bitboard Center      = (FileDBB | FileEBB) & (Rank4BB | Rank5BB);
67
68 constexpr Bitboard KingFlank[FILE_NB] = {
69   QueenSide ^ FileDBB, QueenSide, QueenSide,
70   CenterFiles, CenterFiles,
71   KingSide, KingSide, KingSide ^ FileEBB
72 };
73
74 extern uint8_t PopCnt16[1 << 16];
75 extern uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
76
77 extern Bitboard SquareBB[SQUARE_NB];
78 extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
79 extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
80 extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
81 extern Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
82
83
84 /// Magic holds all magic bitboards relevant data for a single square
85 struct Magic {
86   Bitboard  mask;
87   Bitboard  magic;
88   Bitboard* attacks;
89   unsigned  shift;
90
91   // Compute the attack's index using the 'magic bitboards' approach
92   unsigned index(Bitboard occupied) const {
93
94     if (HasPext)
95         return unsigned(pext(occupied, mask));
96
97     if (Is64Bit)
98         return unsigned(((occupied & mask) * magic) >> shift);
99
100     unsigned lo = unsigned(occupied) & unsigned(mask);
101     unsigned hi = unsigned(occupied >> 32) & unsigned(mask >> 32);
102     return (lo * unsigned(magic) ^ hi * unsigned(magic >> 32)) >> shift;
103   }
104 };
105
106 extern Magic RookMagics[SQUARE_NB];
107 extern Magic BishopMagics[SQUARE_NB];
108
109 inline Bitboard square_bb(Square s) {
110   assert(is_ok(s));
111   return SquareBB[s];
112 }
113
114
115 /// Overloads of bitwise operators between a Bitboard and a Square for testing
116 /// whether a given bit is set in a bitboard, and for setting and clearing bits.
117
118 inline Bitboard  operator&( Bitboard  b, Square s) { return b &  square_bb(s); }
119 inline Bitboard  operator|( Bitboard  b, Square s) { return b |  square_bb(s); }
120 inline Bitboard  operator^( Bitboard  b, Square s) { return b ^  square_bb(s); }
121 inline Bitboard& operator|=(Bitboard& b, Square s) { return b |= square_bb(s); }
122 inline Bitboard& operator^=(Bitboard& b, Square s) { return b ^= square_bb(s); }
123
124 inline Bitboard  operator&(Square s, Bitboard b) { return b & s; }
125 inline Bitboard  operator|(Square s, Bitboard b) { return b | s; }
126 inline Bitboard  operator^(Square s, Bitboard b) { return b ^ s; }
127
128 inline Bitboard  operator|(Square s1, Square s2) { return square_bb(s1) | s2; }
129
130 constexpr bool more_than_one(Bitboard b) {
131   return b & (b - 1);
132 }
133
134
135 constexpr bool opposite_colors(Square s1, Square s2) {
136   return (s1 + rank_of(s1) + s2 + rank_of(s2)) & 1;
137 }
138
139
140 /// rank_bb() and file_bb() return a bitboard representing all the squares on
141 /// the given file or rank.
142
143 constexpr Bitboard rank_bb(Rank r) {
144   return Rank1BB << (8 * r);
145 }
146
147 constexpr Bitboard rank_bb(Square s) {
148   return rank_bb(rank_of(s));
149 }
150
151 constexpr Bitboard file_bb(File f) {
152   return FileABB << f;
153 }
154
155 constexpr Bitboard file_bb(Square s) {
156   return file_bb(file_of(s));
157 }
158
159
160 /// shift() moves a bitboard one or two steps as specified by the direction D
161
162 template<Direction D>
163 constexpr Bitboard shift(Bitboard b) {
164   return  D == NORTH      ?  b             << 8 : D == SOUTH      ?  b             >> 8
165         : D == NORTH+NORTH?  b             <<16 : D == SOUTH+SOUTH?  b             >>16
166         : D == EAST       ? (b & ~FileHBB) << 1 : D == WEST       ? (b & ~FileABB) >> 1
167         : D == NORTH_EAST ? (b & ~FileHBB) << 9 : D == NORTH_WEST ? (b & ~FileABB) << 7
168         : D == SOUTH_EAST ? (b & ~FileHBB) >> 7 : D == SOUTH_WEST ? (b & ~FileABB) >> 9
169         : 0;
170 }
171
172
173 /// pawn_attacks_bb() returns the squares attacked by pawns of the given color
174 /// from the squares in the given bitboard.
175
176 template<Color C>
177 constexpr Bitboard pawn_attacks_bb(Bitboard b) {
178   return C == WHITE ? shift<NORTH_WEST>(b) | shift<NORTH_EAST>(b)
179                     : shift<SOUTH_WEST>(b) | shift<SOUTH_EAST>(b);
180 }
181
182 inline Bitboard pawn_attacks_bb(Color c, Square s) {
183
184   assert(is_ok(s));
185   return PawnAttacks[c][s];
186 }
187
188
189 /// pawn_double_attacks_bb() returns the squares doubly attacked by pawns of the
190 /// given color from the squares in the given bitboard.
191
192 template<Color C>
193 constexpr Bitboard pawn_double_attacks_bb(Bitboard b) {
194   return C == WHITE ? shift<NORTH_WEST>(b) & shift<NORTH_EAST>(b)
195                     : shift<SOUTH_WEST>(b) & shift<SOUTH_EAST>(b);
196 }
197
198
199 /// adjacent_files_bb() returns a bitboard representing all the squares on the
200 /// adjacent files of a given square.
201
202 constexpr Bitboard adjacent_files_bb(Square s) {
203   return shift<EAST>(file_bb(s)) | shift<WEST>(file_bb(s));
204 }
205
206
207 /// line_bb() returns a bitboard representing an entire line (from board edge
208 /// to board edge) that intersects the two given squares. If the given squares
209 /// are not on a same file/rank/diagonal, the function returns 0. For instance,
210 /// line_bb(SQ_C4, SQ_F7) will return a bitboard with the A2-G8 diagonal.
211
212 inline Bitboard line_bb(Square s1, Square s2) {
213
214   assert(is_ok(s1) && is_ok(s2));
215   return LineBB[s1][s2];
216 }
217
218
219 /// between_bb(s1, s2) returns a bitboard representing the squares in the semi-open
220 /// segment between the squares s1 and s2 (excluding s1 but including s2). If the
221 /// given squares are not on a same file/rank/diagonal, it returns s2. For instance,
222 /// between_bb(SQ_C4, SQ_F7) will return a bitboard with squares D5, E6 and F7, but
223 /// between_bb(SQ_E6, SQ_F8) will return a bitboard with the square F8. This trick
224 /// allows to generate non-king evasion moves faster: the defending piece must either
225 /// interpose itself to cover the check or capture the checking piece.
226
227 inline Bitboard between_bb(Square s1, Square s2) {
228   assert(is_ok(s1) && is_ok(s2));
229   return BetweenBB[s1][s2];
230 }
231
232
233 /// forward_ranks_bb() returns a bitboard representing the squares on the ranks in
234 /// front of the given one, from the point of view of the given color. For instance,
235 /// forward_ranks_bb(BLACK, SQ_D3) will return the 16 squares on ranks 1 and 2.
236
237 constexpr Bitboard forward_ranks_bb(Color c, Square s) {
238   return c == WHITE ? ~Rank1BB << 8 * relative_rank(WHITE, s)
239                     : ~Rank8BB >> 8 * relative_rank(BLACK, s);
240 }
241
242
243 /// forward_file_bb() returns a bitboard representing all the squares along the
244 /// line in front of the given one, from the point of view of the given color.
245
246 constexpr Bitboard forward_file_bb(Color c, Square s) {
247   return forward_ranks_bb(c, s) & file_bb(s);
248 }
249
250
251 /// pawn_attack_span() returns a bitboard representing all the squares that can
252 /// be attacked by a pawn of the given color when it moves along its file, starting
253 /// from the given square.
254
255 constexpr Bitboard pawn_attack_span(Color c, Square s) {
256   return forward_ranks_bb(c, s) & adjacent_files_bb(s);
257 }
258
259
260 /// passed_pawn_span() returns a bitboard which can be used to test if a pawn of
261 /// the given color and on the given square is a passed pawn.
262
263 constexpr Bitboard passed_pawn_span(Color c, Square s) {
264   return pawn_attack_span(c, s) | forward_file_bb(c, s);
265 }
266
267
268 /// aligned() returns true if the squares s1, s2 and s3 are aligned either on a
269 /// straight or on a diagonal line.
270
271 inline bool aligned(Square s1, Square s2, Square s3) {
272   return line_bb(s1, s2) & s3;
273 }
274
275
276 /// distance() functions return the distance between x and y, defined as the
277 /// number of steps for a king in x to reach y.
278
279 template<typename T1 = Square> inline int distance(Square x, Square y);
280 template<> inline int distance<File>(Square x, Square y) { return std::abs(file_of(x) - file_of(y)); }
281 template<> inline int distance<Rank>(Square x, Square y) { return std::abs(rank_of(x) - rank_of(y)); }
282 template<> inline int distance<Square>(Square x, Square y) { return SquareDistance[x][y]; }
283
284 inline int edge_distance(File f) { return std::min(f, File(FILE_H - f)); }
285 inline int edge_distance(Rank r) { return std::min(r, Rank(RANK_8 - r)); }
286
287
288 /// attacks_bb(Square) returns the pseudo attacks of the give piece type
289 /// assuming an empty board.
290
291 template<PieceType Pt>
292 inline Bitboard attacks_bb(Square s) {
293
294   assert((Pt != PAWN) && (is_ok(s)));
295
296   return PseudoAttacks[Pt][s];
297 }
298
299
300 /// attacks_bb(Square, Bitboard) returns the attacks by the given piece
301 /// assuming the board is occupied according to the passed Bitboard.
302 /// Sliding piece attacks do not continue passed an occupied square.
303
304 template<PieceType Pt>
305 inline Bitboard attacks_bb(Square s, Bitboard occupied) {
306
307   assert((Pt != PAWN) && (is_ok(s)));
308
309   switch (Pt)
310   {
311   case BISHOP: return BishopMagics[s].attacks[BishopMagics[s].index(occupied)];
312   case ROOK  : return   RookMagics[s].attacks[  RookMagics[s].index(occupied)];
313   case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
314   default    : return PseudoAttacks[Pt][s];
315   }
316 }
317
318 inline Bitboard attacks_bb(PieceType pt, Square s, Bitboard occupied) {
319
320   assert((pt != PAWN) && (is_ok(s)));
321
322   switch (pt)
323   {
324   case BISHOP: return attacks_bb<BISHOP>(s, occupied);
325   case ROOK  : return attacks_bb<  ROOK>(s, occupied);
326   case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
327   default    : return PseudoAttacks[pt][s];
328   }
329 }
330
331
332 /// popcount() counts the number of non-zero bits in a bitboard
333
334 inline int popcount(Bitboard b) {
335
336 #ifndef USE_POPCNT
337
338   union { Bitboard bb; uint16_t u[4]; } v = { b };
339   return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
340
341 #elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
342
343   return (int)_mm_popcnt_u64(b);
344
345 #else // Assumed gcc or compatible compiler
346
347   return __builtin_popcountll(b);
348
349 #endif
350 }
351
352
353 /// lsb() and msb() return the least/most significant bit in a non-zero bitboard
354
355 #if defined(__GNUC__)  // GCC, Clang, ICC
356
357 inline Square lsb(Bitboard b) {
358   assert(b);
359   return Square(__builtin_ctzll(b));
360 }
361
362 inline Square msb(Bitboard b) {
363   assert(b);
364   return Square(63 ^ __builtin_clzll(b));
365 }
366
367 #elif defined(_MSC_VER)  // MSVC
368
369 #ifdef _WIN64  // MSVC, WIN64
370
371 inline Square lsb(Bitboard b) {
372   assert(b);
373   unsigned long idx;
374   _BitScanForward64(&idx, b);
375   return (Square) idx;
376 }
377
378 inline Square msb(Bitboard b) {
379   assert(b);
380   unsigned long idx;
381   _BitScanReverse64(&idx, b);
382   return (Square) idx;
383 }
384
385 #else  // MSVC, WIN32
386
387 inline Square lsb(Bitboard b) {
388   assert(b);
389   unsigned long idx;
390
391   if (b & 0xffffffff) {
392       _BitScanForward(&idx, int32_t(b));
393       return Square(idx);
394   } else {
395       _BitScanForward(&idx, int32_t(b >> 32));
396       return Square(idx + 32);
397   }
398 }
399
400 inline Square msb(Bitboard b) {
401   assert(b);
402   unsigned long idx;
403
404   if (b >> 32) {
405       _BitScanReverse(&idx, int32_t(b >> 32));
406       return Square(idx + 32);
407   } else {
408       _BitScanReverse(&idx, int32_t(b));
409       return Square(idx);
410   }
411 }
412
413 #endif
414
415 #else  // Compiler is neither GCC nor MSVC compatible
416
417 #error "Compiler not supported."
418
419 #endif
420
421 /// least_significant_square_bb() returns the bitboard of the least significant
422 /// square of a non-zero bitboard. It is equivalent to square_bb(lsb(bb)).
423
424 inline Bitboard least_significant_square_bb(Bitboard b) {
425   assert(b);
426   return b & -b;
427 }
428
429 /// pop_lsb() finds and clears the least significant bit in a non-zero bitboard
430
431 inline Square pop_lsb(Bitboard* b) {
432   assert(*b);
433   const Square s = lsb(*b);
434   *b &= *b - 1;
435   return s;
436 }
437
438
439 /// frontmost_sq() returns the most advanced square for the given color,
440 /// requires a non-zero bitboard.
441 inline Square frontmost_sq(Color c, Bitboard b) {
442   assert(b);
443   return c == WHITE ? msb(b) : lsb(b);
444 }
445
446 } // namespace Stockfish
447
448 #endif // #ifndef BITBOARD_H_INCLUDED