]> git.sesse.net Git - stockfish/blob - src/bitboard.h
Small cleanups
[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-2020 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 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 LineBB[SQUARE_NB][SQUARE_NB];
79 extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
80 extern Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
81
82
83 /// Magic holds all magic bitboards relevant data for a single square
84 struct Magic {
85   Bitboard  mask;
86   Bitboard  magic;
87   Bitboard* attacks;
88   unsigned  shift;
89
90   // Compute the attack's index using the 'magic bitboards' approach
91   unsigned index(Bitboard occupied) const {
92
93     if (HasPext)
94         return unsigned(pext(occupied, mask));
95
96     if (Is64Bit)
97         return unsigned(((occupied & mask) * magic) >> shift);
98
99     unsigned lo = unsigned(occupied) & unsigned(mask);
100     unsigned hi = unsigned(occupied >> 32) & unsigned(mask >> 32);
101     return (lo * unsigned(magic) ^ hi * unsigned(magic >> 32)) >> shift;
102   }
103 };
104
105 extern Magic RookMagics[SQUARE_NB];
106 extern Magic BishopMagics[SQUARE_NB];
107
108 inline Bitboard square_bb(Square s) {
109   assert(is_ok(s));
110   return SquareBB[s];
111 }
112
113
114 /// Overloads of bitwise operators between a Bitboard and a Square for testing
115 /// whether a given bit is set in a bitboard, and for setting and clearing bits.
116
117 inline Bitboard  operator&( Bitboard  b, Square s) { return b &  square_bb(s); }
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
123 inline Bitboard  operator&(Square s, Bitboard b) { return b & s; }
124 inline Bitboard  operator|(Square s, Bitboard b) { return b | s; }
125 inline Bitboard  operator^(Square s, Bitboard b) { return b ^ s; }
126
127 inline Bitboard  operator|(Square s, Square s2) { return square_bb(s) | s2; }
128
129 constexpr bool more_than_one(Bitboard b) {
130   return b & (b - 1);
131 }
132
133 constexpr bool opposite_colors(Square s1, Square s2) {
134   return (s1 + rank_of(s1) + s2 + rank_of(s2)) & 1;
135 }
136
137
138 /// rank_bb() and file_bb() return a bitboard representing all the squares on
139 /// the given file or rank.
140
141 inline Bitboard rank_bb(Rank r) {
142   return Rank1BB << (8 * r);
143 }
144
145 inline Bitboard rank_bb(Square s) {
146   return rank_bb(rank_of(s));
147 }
148
149 inline Bitboard file_bb(File f) {
150   return FileABB << f;
151 }
152
153 inline Bitboard file_bb(Square s) {
154   return file_bb(file_of(s));
155 }
156
157
158 /// shift() moves a bitboard one or two steps as specified by the direction D
159
160 template<Direction D>
161 constexpr Bitboard shift(Bitboard b) {
162   return  D == NORTH      ?  b             << 8 : D == SOUTH      ?  b             >> 8
163         : D == NORTH+NORTH?  b             <<16 : D == SOUTH+SOUTH?  b             >>16
164         : D == EAST       ? (b & ~FileHBB) << 1 : D == WEST       ? (b & ~FileABB) >> 1
165         : D == NORTH_EAST ? (b & ~FileHBB) << 9 : D == NORTH_WEST ? (b & ~FileABB) << 7
166         : D == SOUTH_EAST ? (b & ~FileHBB) >> 7 : D == SOUTH_WEST ? (b & ~FileABB) >> 9
167         : 0;
168 }
169
170
171 /// pawn_attacks_bb() returns the squares attacked by pawns of the given color
172 /// from the squares in the given bitboard.
173
174 template<Color C>
175 constexpr Bitboard pawn_attacks_bb(Bitboard b) {
176   return C == WHITE ? shift<NORTH_WEST>(b) | shift<NORTH_EAST>(b)
177                     : shift<SOUTH_WEST>(b) | shift<SOUTH_EAST>(b);
178 }
179
180 inline Bitboard pawn_attacks_bb(Color c, Square s) {
181
182   assert(is_ok(s));
183   return PawnAttacks[c][s];
184 }
185
186
187 /// pawn_double_attacks_bb() returns the squares doubly attacked by pawns of the
188 /// given color from the squares in the given bitboard.
189
190 template<Color C>
191 constexpr Bitboard pawn_double_attacks_bb(Bitboard b) {
192   return C == WHITE ? shift<NORTH_WEST>(b) & shift<NORTH_EAST>(b)
193                     : shift<SOUTH_WEST>(b) & shift<SOUTH_EAST>(b);
194 }
195
196
197 /// adjacent_files_bb() returns a bitboard representing all the squares on the
198 /// adjacent files of the given one.
199
200 inline Bitboard adjacent_files_bb(Square s) {
201   return shift<EAST>(file_bb(s)) | shift<WEST>(file_bb(s));
202 }
203
204
205 /// line_bb(Square, Square) returns a bitboard representing an entire line,
206 /// from board edge to board edge, that intersects the given squares. If the
207 /// given squares are not on a same file/rank/diagonal, returns 0. For instance,
208 /// line_bb(SQ_C4, SQ_F7) will return a bitboard with the A2-G8 diagonal.
209
210 inline Bitboard line_bb(Square s1, Square s2) {
211
212   assert(is_ok(s1) && is_ok(s2));
213   return LineBB[s1][s2];
214 }
215
216
217 /// between_bb() returns a bitboard representing squares that are linearly
218 /// between the given squares (excluding the given squares). If the given
219 /// squares are not on a same file/rank/diagonal, return 0. For instance,
220 /// between_bb(SQ_C4, SQ_F7) will return a bitboard with squares D5 and E6.
221
222 inline Bitboard between_bb(Square s1, Square s2) {
223   Bitboard b = line_bb(s1, s2) & ((AllSquares << s1) ^ (AllSquares << s2));
224   return b & (b - 1); //exclude lsb
225 }
226
227
228 /// forward_ranks_bb() returns a bitboard representing the squares on the ranks
229 /// in front of the given one, from the point of view of the given color. For instance,
230 /// forward_ranks_bb(BLACK, SQ_D3) will return the 16 squares on ranks 1 and 2.
231
232 inline Bitboard forward_ranks_bb(Color c, Square s) {
233   return c == WHITE ? ~Rank1BB << 8 * relative_rank(WHITE, s)
234                     : ~Rank8BB >> 8 * relative_rank(BLACK, s);
235 }
236
237
238 /// forward_file_bb() returns a bitboard representing all the squares along the
239 /// line in front of the given one, from the point of view of the given color.
240
241 inline Bitboard forward_file_bb(Color c, Square s) {
242   return forward_ranks_bb(c, s) & file_bb(s);
243 }
244
245
246 /// pawn_attack_span() returns a bitboard representing all the squares that can
247 /// be attacked by a pawn of the given color when it moves along its file, starting
248 /// from the given square.
249
250 inline Bitboard pawn_attack_span(Color c, Square s) {
251   return forward_ranks_bb(c, s) & adjacent_files_bb(s);
252 }
253
254
255 /// passed_pawn_span() returns a bitboard which can be used to test if a pawn of
256 /// the given color and on the given square is a passed pawn.
257
258 inline Bitboard passed_pawn_span(Color c, Square s) {
259   return pawn_attack_span(c, s) | forward_file_bb(c, s);
260 }
261
262
263 /// aligned() returns true if the squares s1, s2 and s3 are aligned either on a
264 /// straight or on a diagonal line.
265
266 inline bool aligned(Square s1, Square s2, Square s3) {
267   return line_bb(s1, s2) & s3;
268 }
269
270
271 /// distance() functions return the distance between x and y, defined as the
272 /// number of steps for a king in x to reach y.
273
274 template<typename T1 = Square> inline int distance(Square x, Square y);
275 template<> inline int distance<File>(Square x, Square y) { return std::abs(file_of(x) - file_of(y)); }
276 template<> inline int distance<Rank>(Square x, Square y) { return std::abs(rank_of(x) - rank_of(y)); }
277 template<> inline int distance<Square>(Square x, Square y) { return SquareDistance[x][y]; }
278
279 inline int edge_distance(File f) { return std::min(f, File(FILE_H - f)); }
280 inline int edge_distance(Rank r) { return std::min(r, Rank(RANK_8 - r)); }
281
282
283 /// safe_destination() returns the bitboard of target square for the given step
284 /// from the given square. If the step is off the board, returns empty bitboard.
285
286 inline Bitboard safe_destination(Square s, int step)
287 {
288     Square to = Square(s + step);
289     return is_ok(to) && distance(s, to) <= 2 ? square_bb(to) : Bitboard(0);
290 }
291
292
293 /// attacks_bb(Square) returns the pseudo attacks of the give piece type
294 /// assuming an empty board.
295
296 template<PieceType Pt>
297 inline Bitboard attacks_bb(Square s) {
298
299   assert((Pt != PAWN) && (is_ok(s)));
300
301   return PseudoAttacks[Pt][s];
302 }
303
304
305 /// attacks_bb(Square, Bitboard) returns the attacks by the given piece
306 /// assuming the board is occupied according to the passed Bitboard.
307 /// Sliding piece attacks do not continue passed an occupied square.
308
309 template<PieceType Pt>
310 inline Bitboard attacks_bb(Square s, Bitboard occupied) {
311
312   assert((Pt != PAWN) && (is_ok(s)));
313
314   switch (Pt)
315   {
316   case BISHOP: return BishopMagics[s].attacks[BishopMagics[s].index(occupied)];
317   case ROOK  : return   RookMagics[s].attacks[  RookMagics[s].index(occupied)];
318   case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
319   default    : return PseudoAttacks[Pt][s];
320   }
321 }
322
323 inline Bitboard attacks_bb(PieceType pt, Square s, Bitboard occupied) {
324
325   assert((pt != PAWN) && (is_ok(s)));
326
327   switch (pt)
328   {
329   case BISHOP: return attacks_bb<BISHOP>(s, occupied);
330   case ROOK  : return attacks_bb<  ROOK>(s, occupied);
331   case QUEEN : return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
332   default    : return PseudoAttacks[pt][s];
333   }
334 }
335
336
337 /// popcount() counts the number of non-zero bits in a bitboard
338
339 inline int popcount(Bitboard b) {
340
341 #ifndef USE_POPCNT
342
343   union { Bitboard bb; uint16_t u[4]; } v = { b };
344   return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
345
346 #elif defined(_MSC_VER) || defined(__INTEL_COMPILER)
347
348   return (int)_mm_popcnt_u64(b);
349
350 #else // Assumed gcc or compatible compiler
351
352   return __builtin_popcountll(b);
353
354 #endif
355 }
356
357
358 /// lsb() and msb() return the least/most significant bit in a non-zero bitboard
359
360 #if defined(__GNUC__)  // GCC, Clang, ICC
361
362 inline Square lsb(Bitboard b) {
363   assert(b);
364   return Square(__builtin_ctzll(b));
365 }
366
367 inline Square msb(Bitboard b) {
368   assert(b);
369   return Square(63 ^ __builtin_clzll(b));
370 }
371
372 #elif defined(_MSC_VER)  // MSVC
373
374 #ifdef _WIN64  // MSVC, WIN64
375
376 inline Square lsb(Bitboard b) {
377   assert(b);
378   unsigned long idx;
379   _BitScanForward64(&idx, b);
380   return (Square) idx;
381 }
382
383 inline Square msb(Bitboard b) {
384   assert(b);
385   unsigned long idx;
386   _BitScanReverse64(&idx, b);
387   return (Square) idx;
388 }
389
390 #else  // MSVC, WIN32
391
392 inline Square lsb(Bitboard b) {
393   assert(b);
394   unsigned long idx;
395
396   if (b & 0xffffffff) {
397       _BitScanForward(&idx, int32_t(b));
398       return Square(idx);
399   } else {
400       _BitScanForward(&idx, int32_t(b >> 32));
401       return Square(idx + 32);
402   }
403 }
404
405 inline Square msb(Bitboard b) {
406   assert(b);
407   unsigned long idx;
408
409   if (b >> 32) {
410       _BitScanReverse(&idx, int32_t(b >> 32));
411       return Square(idx + 32);
412   } else {
413       _BitScanReverse(&idx, int32_t(b));
414       return Square(idx);
415   }
416 }
417
418 #endif
419
420 #else  // Compiler is neither GCC nor MSVC compatible
421
422 #error "Compiler not supported."
423
424 #endif
425
426
427 /// pop_lsb() finds and clears the least significant bit in a non-zero bitboard
428
429 inline Square pop_lsb(Bitboard* b) {
430   assert(*b);
431   const Square s = lsb(*b);
432   *b &= *b - 1;
433   return s;
434 }
435
436
437 /// frontmost_sq() returns the most advanced square for the given color,
438 /// requires a non-zero bitboard.
439 inline Square frontmost_sq(Color c, Bitboard b) {
440   assert(b);
441   return c == WHITE ? msb(b) : lsb(b);
442 }
443
444 #endif // #ifndef BITBOARD_H_INCLUDED