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