]> git.sesse.net Git - stockfish/blob - src/syzygy/tbprobe.cpp
Refactor tbprobe.cpp
[stockfish] / src / syzygy / tbprobe.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (c) 2013 Ronald de Man
4   Copyright (C) 2016-2018 Marco Costalba, Lucas Braesch
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <algorithm>
21 #include <atomic>
22 #include <cstdint>
23 #include <cstring>   // For std::memset and std::memcpy
24 #include <deque>
25 #include <fstream>
26 #include <iostream>
27 #include <list>
28 #include <sstream>
29 #include <type_traits>
30
31 #include "../bitboard.h"
32 #include "../movegen.h"
33 #include "../position.h"
34 #include "../search.h"
35 #include "../thread_win32.h"
36 #include "../types.h"
37
38 #include "tbprobe.h"
39
40 #ifndef _WIN32
41 #include <fcntl.h>
42 #include <unistd.h>
43 #include <sys/mman.h>
44 #include <sys/stat.h>
45 #else
46 #define WIN32_LEAN_AND_MEAN
47 #define NOMINMAX
48 #include <windows.h>
49 #endif
50
51 using namespace Tablebases;
52
53 int Tablebases::MaxCardinality;
54
55 namespace {
56
57 constexpr int TBPIECES = 6; // Max number of supported pieces
58
59 enum TBType { WDL, DTZ }; // Used as template parameter
60
61 // Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables
62 enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, SingleValue = 128 };
63
64 inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
65 inline Square operator^=(Square& s, int i) { return s = Square(int(s) ^ i); }
66 inline Square operator^(Square s, int i) { return Square(int(s) ^ i); }
67
68 // DTZ tables don't store valid scores for moves that reset the rule50 counter
69 // like captures and pawn moves but we can easily recover the correct dtz of the
70 // previous move if we know the position's WDL score.
71 int dtz_before_zeroing(WDLScore wdl) {
72     return wdl == WDLWin         ?  1   :
73            wdl == WDLCursedWin   ?  101 :
74            wdl == WDLBlessedLoss ? -101 :
75            wdl == WDLLoss        ? -1   : 0;
76 }
77
78 // Return the sign of a number (-1, 0, 1)
79 template <typename T> int sign_of(T val) {
80     return (T(0) < val) - (val < T(0));
81 }
82
83 // Numbers in little endian used by sparseIndex[] to point into blockLength[]
84 struct SparseEntry {
85     char block[4];   // Number of block
86     char offset[2];  // Offset within the block
87 };
88
89 static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
90
91 typedef uint16_t Sym; // Huffman symbol
92
93 struct LR {
94     enum Side { Left, Right, Value };
95
96     uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
97                    // bits is the right-hand symbol. If symbol has length 1,
98                    // then the first byte is the stored value.
99     template<Side S>
100     Sym get() {
101         return S == Left  ? ((lr[1] & 0xF) << 8) | lr[0] :
102                S == Right ?  (lr[2] << 4) | (lr[1] >> 4) :
103                S == Value ?   lr[0] : (assert(false), Sym(-1));
104     }
105 };
106
107 static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
108
109 struct PairsData {
110     int flags;
111     size_t sizeofBlock;            // Block size in bytes
112     size_t span;                   // About every span values there is a SparseIndex[] entry
113     int blocksNum;                 // Number of blocks in the TB file
114     int maxSymLen;                 // Maximum length in bits of the Huffman symbols
115     int minSymLen;                 // Minimum length in bits of the Huffman symbols
116     Sym* lowestSym;                // lowestSym[l] is the symbol of length l with the lowest value
117     LR* btree;                     // btree[sym] stores the left and right symbols that expand sym
118     uint16_t* blockLength;         // Number of stored positions (minus one) for each block: 1..65536
119     int blockLengthSize;           // Size of blockLength[] table: padded so it's bigger than blocksNum
120     SparseEntry* sparseIndex;      // Partial indices into blockLength[]
121     size_t sparseIndexSize;        // Size of SparseIndex[] table
122     uint8_t* data;                 // Start of Huffman compressed data
123     std::vector<uint64_t> base64;  // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l
124     std::vector<uint8_t> symlen;   // Number of values (-1) represented by a given Huffman symbol: 1..256
125     Piece pieces[TBPIECES];        // Position pieces: the order of pieces defines the groups
126     uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces
127     int groupLen[TBPIECES+1];      // Number of pieces in a given group: KRKN -> (3, 1)
128     uint16_t map_idx[4];           // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss (used in DTZ)
129 };
130
131 template<TBType Type>
132 struct TBEntry {
133     typedef typename std::conditional<Type == WDL, WDLScore, int>::type Result;
134
135     static constexpr int Sides = Type == WDL ? 2 : 1;
136
137     std::atomic_bool ready;
138     void* baseAddress;
139     uint8_t* map;
140     uint64_t mapping;
141     Key key;
142     Key key2;
143     int pieceCount;
144     bool hasPawns;
145     bool hasUniquePieces;
146     uint8_t pawnCount[2]; // [Lead color / other color]
147     PairsData items[Sides][4]; // [wtm / btm][FILE_A..FILE_D or 0]
148
149     PairsData* get(int stm, int f) {
150         return &items[stm % Sides][hasPawns ? f : 0];
151     }
152
153     TBEntry() : ready(false), baseAddress(nullptr) {}
154     explicit TBEntry(const std::string& code);
155     explicit TBEntry(const TBEntry<WDL>& wdl);
156     ~TBEntry();
157 };
158
159 template<>
160 TBEntry<WDL>::TBEntry(const std::string& code) : TBEntry() {
161
162     StateInfo st;
163     Position pos;
164
165     key = pos.set(code, WHITE, &st).material_key();
166     pieceCount = popcount(pos.pieces());
167     hasPawns = pos.pieces(PAWN);
168
169     hasUniquePieces = false;
170     for (Color c = WHITE; c <= BLACK; ++c)
171         for (PieceType pt = PAWN; pt < KING; ++pt)
172             if (popcount(pos.pieces(c, pt)) == 1)
173                 hasUniquePieces = true;
174
175     if (hasPawns) {
176         // Set the leading color. In case both sides have pawns the leading color
177         // is the side with less pawns because this leads to better compression.
178         bool c =   !pos.count<PAWN>(BLACK)
179                 || (   pos.count<PAWN>(WHITE)
180                     && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
181
182         pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
183         pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
184     }
185
186     key2 = pos.set(code, BLACK, &st).material_key();
187 }
188
189 template<>
190 TBEntry<DTZ>::TBEntry(const TBEntry<WDL>& wdl) : TBEntry() {
191
192     key = wdl.key;
193     key2 = wdl.key2;
194     pieceCount = wdl.pieceCount;
195     hasPawns = wdl.hasPawns;
196     hasUniquePieces = wdl.hasUniquePieces;
197
198     if (hasPawns) {
199         pawnCount[0] = wdl.pawnCount[0];
200         pawnCount[1] = wdl.pawnCount[1];
201     }
202 }
203
204 int MapPawns[SQUARE_NB];
205 int MapB1H1H7[SQUARE_NB];
206 int MapA1D1D4[SQUARE_NB];
207 int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
208
209 // Comparison function to sort leading pawns in ascending MapPawns[] order
210 bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; }
211 int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); }
212
213 constexpr Value WDL_to_value[] = {
214    -VALUE_MATE + MAX_PLY + 1,
215     VALUE_DRAW - 2,
216     VALUE_DRAW,
217     VALUE_DRAW + 2,
218     VALUE_MATE - MAX_PLY - 1
219 };
220
221 const std::string PieceToChar = " PNBRQK  pnbrqk";
222
223 int Binomial[6][SQUARE_NB];    // [k][n] k elements from a set of n elements
224 int LeadPawnIdx[5][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB]
225 int LeadPawnsSize[5][4];       // [leadPawnsCnt][FILE_A..FILE_D]
226
227 enum { BigEndian, LittleEndian };
228
229 template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
230 inline void swap_byte(T& x)
231 {
232     char tmp, *c = (char*)&x;
233     for (int i = 0; i < Half; ++i)
234         tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
235 }
236 template<> inline void swap_byte<uint8_t, 0, 0>(uint8_t&) {}
237
238 template<typename T, int LE> T number(void* addr)
239 {
240     const union { uint32_t i; char c[4]; } Le = { 0x01020304 };
241     const bool IsLittleEndian = (Le.c[0] == 4);
242
243     T v;
244
245     if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare)
246         std::memcpy(&v, addr, sizeof(T));
247     else
248         v = *((T*)addr);
249
250     if (LE != IsLittleEndian)
251         swap_byte(v);
252     return v;
253 }
254
255 class HashTable {
256
257     typedef std::pair<TBEntry<WDL>*, TBEntry<DTZ>*> EntryPair;
258     typedef std::pair<Key, EntryPair> Entry;
259
260     static constexpr int TBHASHBITS = 10;
261     static constexpr int HSHMAX     = 5;
262
263     Entry hashTable[1 << TBHASHBITS][HSHMAX];
264
265     std::deque<TBEntry<WDL>> wdlTable;
266     std::deque<TBEntry<DTZ>> dtzTable;
267
268     void insert(Key key, TBEntry<WDL>* wdl, TBEntry<DTZ>* dtz) {
269         for (Entry& entry : hashTable[key >> (64 - TBHASHBITS)])
270             if (!entry.second.first || entry.first == key) {
271                 entry = std::make_pair(key, std::make_pair(wdl, dtz));
272                 return;
273             }
274
275         std::cerr << "HSHMAX too low!" << std::endl;
276         exit(1);
277     }
278
279 public:
280     template<TBType Type>
281     TBEntry<Type>* get(Key key) {
282         for (Entry& entry : hashTable[key >> (64 - TBHASHBITS)])
283             if (entry.first == key)
284                 return std::get<Type>(entry.second);
285
286         return nullptr;
287     }
288
289     void clear() {
290         memset(hashTable, 0, sizeof(hashTable));
291         wdlTable.clear();
292         dtzTable.clear();
293     }
294     size_t size() const { return wdlTable.size(); }
295     void insert(const std::vector<PieceType>& pieces);
296 };
297
298 HashTable EntryTable;
299
300 class TBFile : public std::ifstream {
301
302     std::string fname;
303
304 public:
305     // Look for and open the file among the Paths directories where the .rtbw
306     // and .rtbz files can be found. Multiple directories are separated by ";"
307     // on Windows and by ":" on Unix-based operating systems.
308     //
309     // Example:
310     // C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
311     static std::string Paths;
312
313     TBFile(const std::string& f) {
314
315 #ifndef _WIN32
316         constexpr char SepChar = ':';
317 #else
318         constexpr char SepChar = ';';
319 #endif
320         std::stringstream ss(Paths);
321         std::string path;
322
323         while (std::getline(ss, path, SepChar)) {
324             fname = path + "/" + f;
325             std::ifstream::open(fname);
326             if (is_open())
327                 return;
328         }
329     }
330
331     // Memory map the file and check it. File should be already open and will be
332     // closed after mapping.
333     uint8_t* map(void** baseAddress, uint64_t* mapping, const uint8_t* TB_MAGIC) {
334
335         assert(is_open());
336
337         close(); // Need to re-open to get native file descriptor
338
339 #ifndef _WIN32
340         struct stat statbuf;
341         int fd = ::open(fname.c_str(), O_RDONLY);
342
343         if (fd == -1)
344             return *baseAddress = nullptr, nullptr;
345
346         fstat(fd, &statbuf);
347         *mapping = statbuf.st_size;
348         *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
349         ::close(fd);
350
351         if (*baseAddress == MAP_FAILED) {
352             std::cerr << "Could not mmap() " << fname << std::endl;
353             exit(1);
354         }
355 #else
356         HANDLE fd = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
357                                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
358
359         if (fd == INVALID_HANDLE_VALUE)
360             return *baseAddress = nullptr, nullptr;
361
362         DWORD size_high;
363         DWORD size_low = GetFileSize(fd, &size_high);
364         HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
365         CloseHandle(fd);
366
367         if (!mmap) {
368             std::cerr << "CreateFileMapping() failed" << std::endl;
369             exit(1);
370         }
371
372         *mapping = (uint64_t)mmap;
373         *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
374
375         if (!*baseAddress) {
376             std::cerr << "MapViewOfFile() failed, name = " << fname
377                       << ", error = " << GetLastError() << std::endl;
378             exit(1);
379         }
380 #endif
381         uint8_t* data = (uint8_t*)*baseAddress;
382
383         if (   *data++ != *TB_MAGIC++
384             || *data++ != *TB_MAGIC++
385             || *data++ != *TB_MAGIC++
386             || *data++ != *TB_MAGIC) {
387             std::cerr << "Corrupted table in file " << fname << std::endl;
388             unmap(*baseAddress, *mapping);
389             return *baseAddress = nullptr, nullptr;
390         }
391
392         return data;
393     }
394
395     static void unmap(void* baseAddress, uint64_t mapping) {
396
397 #ifndef _WIN32
398         munmap(baseAddress, mapping);
399 #else
400         UnmapViewOfFile(baseAddress);
401         CloseHandle((HANDLE)mapping);
402 #endif
403     }
404 };
405
406 std::string TBFile::Paths;
407
408 template<TBType Type>
409 TBEntry<Type>::~TBEntry() {
410     if (baseAddress)
411         TBFile::unmap(baseAddress, mapping);
412 }
413
414 void HashTable::insert(const std::vector<PieceType>& pieces) {
415
416     std::string code;
417
418     for (PieceType pt : pieces)
419         code += PieceToChar[pt];
420
421     TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); // KRK -> KRvK
422
423     if (!file.is_open()) // Only WDL file is checked
424         return;
425
426     file.close();
427
428     MaxCardinality = std::max((int)pieces.size(), MaxCardinality);
429
430     wdlTable.emplace_back(code);
431     dtzTable.emplace_back(wdlTable.back());
432
433     insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back());
434     insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
435 }
436
437 // TB tables are compressed with canonical Huffman code. The compressed data is divided into
438 // blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
439 // Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
440 // (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
441 // WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
442 // Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
443 // 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
444 // of draws or mostly of wins, but such tables are actually quite common. In principle, the
445 // blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
446 // mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
447 // in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
448 // The generator picks the size that leads to the smallest table. The "book" of symbols and
449 // Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
450 // will have one table for wtm and one for btm, a TB file with pawns will have tables per
451 // file a,b,c,d also in this case one set for wtm and one for btm.
452 int decompress_pairs(PairsData* d, uint64_t idx) {
453
454     // Special case where all table positions store the same value
455     if (d->flags & TBFlag::SingleValue)
456         return d->minSymLen;
457
458     // First we need to locate the right block that stores the value at index "idx".
459     // Because each block n stores blockLength[n] + 1 values, the index i of the block
460     // that contains the value at position idx is:
461     //
462     //                    for (i = -1, sum = 0; sum <= idx; i++)
463     //                        sum += blockLength[i + 1] + 1;
464     //
465     // This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
466     // point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
467     // that stores the blockLength[] index and the offset within that block of the value
468     // with index I(k), where:
469     //
470     //       I(k) = k * d->span + d->span / 2      (1)
471
472     // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
473     uint32_t k = idx / d->span;
474
475     // Then we read the corresponding SparseIndex[] entry
476     uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
477     int offset     = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
478
479     // Now compute the difference idx - I(k). From definition of k we know that
480     //
481     //       idx = k * d->span + idx % d->span    (2)
482     //
483     // So from (1) and (2) we can compute idx - I(K):
484     int diff = idx % d->span - d->span / 2;
485
486     // Sum the above to offset to find the offset corresponding to our idx
487     offset += diff;
488
489     // Move to previous/next block, until we reach the correct block that contains idx,
490     // that is when 0 <= offset <= d->blockLength[block]
491     while (offset < 0)
492         offset += d->blockLength[--block] + 1;
493
494     while (offset > d->blockLength[block])
495         offset -= d->blockLength[block++] + 1;
496
497     // Finally, we find the start address of our block of canonical Huffman symbols
498     uint32_t* ptr = (uint32_t*)(d->data + block * d->sizeofBlock);
499
500     // Read the first 64 bits in our block, this is a (truncated) sequence of
501     // unknown number of symbols of unknown length but we know the first one
502     // is at the beginning of this 64 bits sequence.
503     uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
504     int buf64Size = 64;
505     Sym sym;
506
507     while (true) {
508         int len = 0; // This is the symbol length - d->min_sym_len
509
510         // Now get the symbol length. For any symbol s64 of length l right-padded
511         // to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
512         // can find the symbol length iterating through base64[].
513         while (buf64 < d->base64[len])
514             ++len;
515
516         // All the symbols of a given length are consecutive integers (numerical
517         // sequence property), so we can compute the offset of our symbol of
518         // length len, stored at the beginning of buf64.
519         sym = (buf64 - d->base64[len]) >> (64 - len - d->minSymLen);
520
521         // Now add the value of the lowest symbol of length len to get our symbol
522         sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
523
524         // If our offset is within the number of values represented by symbol sym
525         // we are done...
526         if (offset < d->symlen[sym] + 1)
527             break;
528
529         // ...otherwise update the offset and continue to iterate
530         offset -= d->symlen[sym] + 1;
531         len += d->minSymLen; // Get the real length
532         buf64 <<= len;       // Consume the just processed symbol
533         buf64Size -= len;
534
535         if (buf64Size <= 32) { // Refill the buffer
536             buf64Size += 32;
537             buf64 |= (uint64_t)number<uint32_t, BigEndian>(ptr++) << (64 - buf64Size);
538         }
539     }
540
541     // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
542     // We binary-search for our value recursively expanding into the left and
543     // right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
544     // that will store the value we need.
545     while (d->symlen[sym]) {
546
547         Sym left = d->btree[sym].get<LR::Left>();
548
549         // If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
550         // expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
551         // we know that, for instance the ten-th value (offset = 10) will be on
552         // the left side because in Recursive Pairing child symbols are adjacent.
553         if (offset < d->symlen[left] + 1)
554             sym = left;
555         else {
556             offset -= d->symlen[left] + 1;
557             sym = d->btree[sym].get<LR::Right>();
558         }
559     }
560
561     return d->btree[sym].get<LR::Value>();
562 }
563
564 bool check_dtz_stm(TBEntry<WDL>*, int, File) { return true; }
565
566 bool check_dtz_stm(TBEntry<DTZ>* entry, int stm, File f) {
567
568     int flags = entry->get(stm, f)->flags;
569     return   (flags & TBFlag::STM) == stm
570           || ((entry->key == entry->key2) && !entry->hasPawns);
571 }
572
573 // DTZ scores are sorted by frequency of occurrence and then assigned the
574 // values 0, 1, 2, ... in order of decreasing frequency. This is done for each
575 // of the four WDLScore values. The mapping information necessary to reconstruct
576 // the original values is stored in the TB file and read during map[] init.
577 WDLScore map_score(TBEntry<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); }
578
579 int map_score(TBEntry<DTZ>* entry, File f, int value, WDLScore wdl) {
580
581     constexpr int WDLMap[] = { 1, 3, 0, 2, 0 };
582
583     int flags = entry->get(0, f)->flags;
584
585     uint8_t* map = entry->map;
586     uint16_t* idx = entry->get(0, f)->map_idx;
587     if (flags & TBFlag::Mapped)
588         value = map[idx[WDLMap[wdl + 2]] + value];
589
590     // DTZ tables store distance to zero in number of moves or plies. We
591     // want to return plies, so we have convert to plies when needed.
592     if (   (wdl == WDLWin  && !(flags & TBFlag::WinPlies))
593         || (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
594         ||  wdl == WDLCursedWin
595         ||  wdl == WDLBlessedLoss)
596         value *= 2;
597
598     return value + 1;
599 }
600
601 // Compute a unique index out of a position and use it to probe the TB file. To
602 // encode k pieces of same type and color, first sort the pieces by square in
603 // ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
604 //
605 //      idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
606 //
607 template<TBType Type, typename T = typename TBEntry<Type>::Result>
608 T do_probe_table(const Position& pos, TBEntry<Type>* entry, WDLScore wdl, ProbeState* result) {
609
610     Square squares[TBPIECES];
611     Piece pieces[TBPIECES];
612     uint64_t idx;
613     int next = 0, size = 0, leadPawnsCnt = 0;
614     PairsData* d;
615     Bitboard b, leadPawns = 0;
616     File tbFile = FILE_A;
617
618     // A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
619     // If both sides have the same pieces keys are equal. In this case TB tables
620     // only store the 'white to move' case, so if the position to lookup has black
621     // to move, we need to switch the color and flip the squares before to lookup.
622     bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
623
624     // TB files are calculated for white as stronger side. For instance we have
625     // KRvK, not KvKR. A position where stronger side is white will have its
626     // material key == entry->key, otherwise we have to switch the color and
627     // flip the squares before to lookup.
628     bool blackStronger = (pos.material_key() != entry->key);
629
630     int flipColor   = (symmetricBlackToMove || blackStronger) * 8;
631     int flipSquares = (symmetricBlackToMove || blackStronger) * 070;
632     int stm         = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
633
634     // For pawns, TB files store 4 separate tables according if leading pawn is on
635     // file a, b, c or d after reordering. The leading pawn is the one with maximum
636     // MapPawns[] value, that is the one most toward the edges and with lowest rank.
637     if (entry->hasPawns) {
638
639         // In all the 4 tables, pawns are at the beginning of the piece sequence and
640         // their color is the reference one. So we just pick the first one.
641         Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor);
642
643         assert(type_of(pc) == PAWN);
644
645         leadPawns = b = pos.pieces(color_of(pc), PAWN);
646         do
647             squares[size++] = pop_lsb(&b) ^ flipSquares;
648         while (b);
649
650         leadPawnsCnt = size;
651
652         std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
653
654         tbFile = file_of(squares[0]);
655         if (tbFile > FILE_D)
656             tbFile = file_of(squares[0] ^ 7); // Horizontal flip: SQ_H1 -> SQ_A1
657     }
658
659     // DTZ tables are one-sided, i.e. they store positions only for white to
660     // move or only for black to move, so check for side to move to be stm,
661     // early exit otherwise.
662     if (Type == DTZ && !check_dtz_stm(entry, stm, tbFile))
663         return *result = CHANGE_STM, T();
664
665     // Now we are ready to get all the position pieces (but the lead pawns) and
666     // directly map them to the correct color and square.
667     b = pos.pieces() ^ leadPawns;
668     do {
669         Square s = pop_lsb(&b);
670         squares[size] = s ^ flipSquares;
671         pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
672     } while (b);
673
674     assert(size >= 2);
675
676     d = entry->get(stm, tbFile);
677
678     // Then we reorder the pieces to have the same sequence as the one stored
679     // in pieces[i]: the sequence that ensures the best compression.
680     for (int i = leadPawnsCnt; i < size; ++i)
681         for (int j = i; j < size; ++j)
682             if (d->pieces[i] == pieces[j])
683             {
684                 std::swap(pieces[i], pieces[j]);
685                 std::swap(squares[i], squares[j]);
686                 break;
687             }
688
689     // Now we map again the squares so that the square of the lead piece is in
690     // the triangle A1-D1-D4.
691     if (file_of(squares[0]) > FILE_D)
692         for (int i = 0; i < size; ++i)
693             squares[i] ^= 7; // Horizontal flip: SQ_H1 -> SQ_A1
694
695     // Encode leading pawns starting with the one with minimum MapPawns[] and
696     // proceeding in ascending order.
697     if (entry->hasPawns) {
698         idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
699
700         std::sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
701
702         for (int i = 1; i < leadPawnsCnt; ++i)
703             idx += Binomial[i][MapPawns[squares[i]]];
704
705         goto encode_remaining; // With pawns we have finished special treatments
706     }
707
708     // In positions withouth pawns, we further flip the squares to ensure leading
709     // piece is below RANK_5.
710     if (rank_of(squares[0]) > RANK_4)
711         for (int i = 0; i < size; ++i)
712             squares[i] ^= 070; // Vertical flip: SQ_A8 -> SQ_A1
713
714     // Look for the first piece of the leading group not on the A1-D4 diagonal
715     // and ensure it is mapped below the diagonal.
716     for (int i = 0; i < d->groupLen[0]; ++i) {
717         if (!off_A1H8(squares[i]))
718             continue;
719
720         if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C3
721             for (int j = i; j < size; ++j)
722                 squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
723         break;
724     }
725
726     // Encode the leading group.
727     //
728     // Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
729     // and bK (each 0...63). The simplest way to map this position to an index
730     // is like this:
731     //
732     //   index = wK * 64 * 64 + wR * 64 + bK;
733     //
734     // But this way the TB is going to have 64*64*64 = 262144 positions, with
735     // lots of positions being equivalent (because they are mirrors of each
736     // other) and lots of positions being invalid (two pieces on one square,
737     // adjacent kings, etc.).
738     // Usually the first step is to take the wK and bK together. There are just
739     // 462 ways legal and not-mirrored ways to place the wK and bK on the board.
740     // Once we have placed the wK and bK, there are 62 squares left for the wR
741     // Mapping its square from 0..63 to available squares 0..61 can be done like:
742     //
743     //   wR -= (wR > wK) + (wR > bK);
744     //
745     // In words: if wR "comes later" than wK, we deduct 1, and the same if wR
746     // "comes later" than bK. In case of two same pieces like KRRvK we want to
747     // place the two Rs "together". If we have 62 squares left, we can place two
748     // Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
749     // swapped and still get the same position.)
750     //
751     // In case we have at least 3 unique pieces (inlcuded kings) we encode them
752     // together.
753     if (entry->hasUniquePieces) {
754
755         int adjust1 =  squares[1] > squares[0];
756         int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
757
758         // First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
759         // triangle to 0...5. There are 63 squares for second piece and and 62
760         // (mapped to 0...61) for the third.
761         if (off_A1H8(squares[0]))
762             idx = (   MapA1D1D4[squares[0]]  * 63
763                    + (squares[1] - adjust1)) * 62
764                    +  squares[2] - adjust2;
765
766         // First piece is on a1-h8 diagonal, second below: map this occurence to
767         // 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
768         // to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
769         else if (off_A1H8(squares[1]))
770             idx = (  6 * 63 + rank_of(squares[0]) * 28
771                    + MapB1H1H7[squares[1]])       * 62
772                    + squares[2] - adjust2;
773
774         // First two pieces are on a1-h8 diagonal, third below
775         else if (off_A1H8(squares[2]))
776             idx =  6 * 63 * 62 + 4 * 28 * 62
777                  +  rank_of(squares[0])        * 7 * 28
778                  + (rank_of(squares[1]) - adjust1) * 28
779                  +  MapB1H1H7[squares[2]];
780
781         // All 3 pieces on the diagonal a1-h8
782         else
783             idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28
784                  +  rank_of(squares[0])         * 7 * 6
785                  + (rank_of(squares[1]) - adjust1)  * 6
786                  + (rank_of(squares[2]) - adjust2);
787     } else
788         // We don't have at least 3 unique pieces, like in KRRvKBB, just map
789         // the kings.
790         idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
791
792 encode_remaining:
793     idx *= d->groupIdx[0];
794     Square* groupSq = squares + d->groupLen[0];
795
796     // Encode remainig pawns then pieces according to square, in ascending order
797     bool remainingPawns = entry->hasPawns && entry->pawnCount[1];
798
799     while (d->groupLen[++next])
800     {
801         std::sort(groupSq, groupSq + d->groupLen[next]);
802         uint64_t n = 0;
803
804         // Map down a square if "comes later" than a square in the previous
805         // groups (similar to what done earlier for leading group pieces).
806         for (int i = 0; i < d->groupLen[next]; ++i)
807         {
808             auto f = [&](Square s) { return groupSq[i] > s; };
809             auto adjust = std::count_if(squares, groupSq, f);
810             n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
811         }
812
813         remainingPawns = false;
814         idx += n * d->groupIdx[next];
815         groupSq += d->groupLen[next];
816     }
817
818     // Now that we have the index, decompress the pair and get the score
819     return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
820 }
821
822 // Group together pieces that will be encoded together. The general rule is that
823 // a group contains pieces of same type and color. The exception is the leading
824 // group that, in case of positions withouth pawns, can be formed by 3 different
825 // pieces (default) or by the king pair when there is not a unique piece apart
826 // from the kings. When there are pawns, pawns are always first in pieces[].
827 //
828 // As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
829 //
830 // The actual grouping depends on the TB generator and can be inferred from the
831 // sequence of pieces in piece[] array.
832 template<TBType Type>
833 void set_groups(TBEntry<Type>& e, PairsData* d, int order[], File f) {
834
835     int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
836     d->groupLen[n] = 1;
837
838     // Number of pieces per group is stored in groupLen[], for instance in KRKN
839     // the encoder will default on '111', so groupLen[] will be (3, 1).
840     for (int i = 1; i < e.pieceCount; ++i)
841         if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
842             d->groupLen[n]++;
843         else
844             d->groupLen[++n] = 1;
845
846     d->groupLen[++n] = 0; // Zero-terminated
847
848     // The sequence in pieces[] defines the groups, but not the order in which
849     // they are encoded. If the pieces in a group g can be combined on the board
850     // in N(g) different ways, then the position encoding will be of the form:
851     //
852     //           g1 * N(g2) * N(g3) + g2 * N(g3) + g3
853     //
854     // This ensures unique encoding for the whole position. The order of the
855     // groups is a per-table parameter and could not follow the canonical leading
856     // pawns/pieces -> remainig pawns -> remaining pieces. In particular the
857     // first group is at order[0] position and the remaining pawns, when present,
858     // are at order[1] position.
859     bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
860     int next = pp ? 2 : 1;
861     int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
862     uint64_t idx = 1;
863
864     for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
865         if (k == order[0]) // Leading pawns or pieces
866         {
867             d->groupIdx[0] = idx;
868             idx *=         e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f]
869                   : e.hasUniquePieces ? 31332 : 462;
870         }
871         else if (k == order[1]) // Remaining pawns
872         {
873             d->groupIdx[1] = idx;
874             idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
875         }
876         else // Remainig pieces
877         {
878             d->groupIdx[next] = idx;
879             idx *= Binomial[d->groupLen[next]][freeSquares];
880             freeSquares -= d->groupLen[next++];
881         }
882
883     d->groupIdx[n] = idx;
884 }
885
886 // In Recursive Pairing each symbol represents a pair of childern symbols. So
887 // read d->btree[] symbols data and expand each one in his left and right child
888 // symbol until reaching the leafs that represent the symbol value.
889 uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
890
891     visited[s] = true; // We can set it now because tree is acyclic
892     Sym sr = d->btree[s].get<LR::Right>();
893
894     if (sr == 0xFFF)
895         return 0;
896
897     Sym sl = d->btree[s].get<LR::Left>();
898
899     if (!visited[sl])
900         d->symlen[sl] = set_symlen(d, sl, visited);
901
902     if (!visited[sr])
903         d->symlen[sr] = set_symlen(d, sr, visited);
904
905     return d->symlen[sl] + d->symlen[sr] + 1;
906 }
907
908 uint8_t* set_sizes(PairsData* d, uint8_t* data) {
909
910     d->flags = *data++;
911
912     if (d->flags & TBFlag::SingleValue) {
913         d->blocksNum = d->blockLengthSize = 0;
914         d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
915         d->minSymLen = *data++; // Here we store the single value
916         return data;
917     }
918
919     // groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
920     // element stores the biggest index that is the tb size.
921     uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
922
923     d->sizeofBlock = 1ULL << *data++;
924     d->span = 1ULL << *data++;
925     d->sparseIndexSize = (tbSize + d->span - 1) / d->span; // Round up
926     int padding = number<uint8_t, LittleEndian>(data++);
927     d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t);
928     d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
929                                                  // does not point out of range.
930     d->maxSymLen = *data++;
931     d->minSymLen = *data++;
932     d->lowestSym = (Sym*)data;
933     d->base64.resize(d->maxSymLen - d->minSymLen + 1);
934
935     // The canonical code is ordered such that longer symbols (in terms of
936     // the number of bits of their Huffman code) have lower numeric value,
937     // so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
938     // Starting from this we compute a base64[] table indexed by symbol length
939     // and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
940     // See http://www.eecs.harvard.edu/~michaelm/E210/huffman.pdf
941     for (int i = d->base64.size() - 2; i >= 0; --i) {
942         d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
943                                          - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2;
944
945         assert(d->base64[i] * 2 >= d->base64[i+1]);
946     }
947
948     // Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
949     // than d->base64[i+1] and given the above assert condition, we ensure that
950     // d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
951     // and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
952     for (size_t i = 0; i < d->base64.size(); ++i)
953         d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
954
955     data += d->base64.size() * sizeof(Sym);
956     d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t);
957     d->btree = (LR*)data;
958
959     // The comrpession scheme used is "Recursive Pairing", that replaces the most
960     // frequent adjacent pair of symbols in the source message by a new symbol,
961     // reevaluating the frequencies of all of the symbol pairs with respect to
962     // the extended alphabet, and then repeating the process.
963     // See http://www.larsson.dogma.net/dcc99.pdf
964     std::vector<bool> visited(d->symlen.size());
965
966     for (Sym sym = 0; sym < d->symlen.size(); ++sym)
967         if (!visited[sym])
968             d->symlen[sym] = set_symlen(d, sym, visited);
969
970     return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
971 }
972
973 uint8_t* set_dtz_map(TBEntry<WDL>&, uint8_t*, File) { return nullptr; }
974
975 uint8_t* set_dtz_map(TBEntry<DTZ>& e, uint8_t* data, File maxFile) {
976
977     e.map = data;
978
979     for (File f = FILE_A; f <= maxFile; ++f) {
980         if (e.get(0, f)->flags & TBFlag::Mapped)
981             for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x
982                 e.get(0, f)->map_idx[i] = (uint16_t)(data - e.map + 1);
983                 data += *data + 1;
984             }
985     }
986
987     return data += (uintptr_t)data & 1; // Word alignment
988 }
989
990 template<TBType Type>
991 void do_init(TBEntry<Type>& e, uint8_t* data) {
992
993     PairsData* d;
994
995     enum { Split = 1, HasPawns = 2 };
996
997     assert(e.hasPawns        == !!(*data & HasPawns));
998     assert((e.key != e.key2) == !!(*data & Split));
999
1000     data++; // First byte stores flags
1001
1002     const int sides = Type == WDL && (e.key != e.key2) ? 2 : 1;
1003     const File maxFile = e.hasPawns ? FILE_D : FILE_A;
1004
1005     bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
1006
1007     assert(!pp || e.pawnCount[0]);
1008
1009     for (File f = FILE_A; f <= maxFile; ++f) {
1010
1011         for (int i = 0; i < sides; i++)
1012             *e.get(i, f) = PairsData();
1013
1014         int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF },
1015                            { *data >>  4, pp ? *(data + 1) >>  4 : 0xF } };
1016         data += 1 + pp;
1017
1018         for (int k = 0; k < e.pieceCount; ++k, ++data)
1019             for (int i = 0; i < sides; i++)
1020                 e.get(i, f)->pieces[k] = Piece(i ? *data >>  4 : *data & 0xF);
1021
1022         for (int i = 0; i < sides; ++i)
1023             set_groups(e, e.get(i, f), order[i], f);
1024     }
1025
1026     data += (uintptr_t)data & 1; // Word alignment
1027
1028     for (File f = FILE_A; f <= maxFile; ++f)
1029         for (int i = 0; i < sides; i++)
1030             data = set_sizes(e.get(i, f), data);
1031
1032     if (Type == DTZ)
1033         data = set_dtz_map(e, data, maxFile);
1034
1035     for (File f = FILE_A; f <= maxFile; ++f)
1036         for (int i = 0; i < sides; i++) {
1037             (d = e.get(i, f))->sparseIndex = (SparseEntry*)data;
1038             data += d->sparseIndexSize * sizeof(SparseEntry);
1039         }
1040
1041     for (File f = FILE_A; f <= maxFile; ++f)
1042         for (int i = 0; i < sides; i++) {
1043             (d = e.get(i, f))->blockLength = (uint16_t*)data;
1044             data += d->blockLengthSize * sizeof(uint16_t);
1045         }
1046
1047     for (File f = FILE_A; f <= maxFile; ++f)
1048         for (int i = 0; i < sides; i++) {
1049             data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment
1050             (d = e.get(i, f))->data = data;
1051             data += d->blocksNum * d->sizeofBlock;
1052         }
1053 }
1054
1055 template<TBType Type>
1056 void* init(TBEntry<Type>& e, const Position& pos) {
1057
1058     static Mutex mutex;
1059
1060     // Avoid a thread reads 'ready' == true while another is still in do_init(),
1061     // this could happen due to compiler reordering.
1062     if (e.ready.load(std::memory_order_acquire))
1063         return e.baseAddress;
1064
1065     std::unique_lock<Mutex> lk(mutex);
1066
1067     if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock
1068         return e.baseAddress;
1069
1070     // Pieces strings in decreasing order for each color, like ("KPP","KR")
1071     std::string fname, w, b;
1072     for (PieceType pt = KING; pt >= PAWN; --pt) {
1073         w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]);
1074         b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]);
1075     }
1076
1077     constexpr uint8_t TB_MAGIC[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 },
1078                                     { 0x71, 0xE8, 0x23, 0x5D } };
1079
1080     fname =  (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w)
1081            + (Type == WDL ? ".rtbw" : ".rtbz");
1082
1083     uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping,
1084                                       TB_MAGIC[Type == WDL]);
1085     if (data)
1086         do_init(e, data);
1087
1088     e.ready.store(true, std::memory_order_release);
1089     return e.baseAddress;
1090 }
1091
1092 template<TBType Type, typename T = typename TBEntry<Type>::Result>
1093 T probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
1094
1095     if (!(pos.pieces() ^ pos.pieces(KING)))
1096         return T(WDLDraw); // KvK
1097
1098     TBEntry<Type>* entry = EntryTable.get<Type>(pos.material_key());
1099
1100     if (!entry || !init(*entry, pos))
1101         return *result = FAIL, T();
1102
1103     return do_probe_table(pos, entry, wdl, result);
1104 }
1105
1106 // For a position where the side to move has a winning capture it is not necessary
1107 // to store a winning value so the generator treats such positions as "don't cares"
1108 // and tries to assign to it a value that improves the compression ratio. Similarly,
1109 // if the side to move has a drawing capture, then the position is at least drawn.
1110 // If the position is won, then the TB needs to store a win value. But if the
1111 // position is drawn, the TB may store a loss value if that is better for compression.
1112 // All of this means that during probing, the engine must look at captures and probe
1113 // their results and must probe the position itself. The "best" result of these
1114 // probes is the correct result for the position.
1115 // DTZ table don't store values when a following move is a zeroing winning move
1116 // (winning capture or winning pawn move). Also DTZ store wrong values for positions
1117 // where the best move is an ep-move (even if losing). So in all these cases set
1118 // the state to ZEROING_BEST_MOVE.
1119 template<bool CheckZeroingMoves = false>
1120 WDLScore search(Position& pos, ProbeState* result) {
1121
1122     WDLScore value, bestValue = WDLLoss;
1123     StateInfo st;
1124
1125     auto moveList = MoveList<LEGAL>(pos);
1126     size_t totalCount = moveList.size(), moveCount = 0;
1127
1128     for (const Move& move : moveList)
1129     {
1130         if (   !pos.capture(move)
1131             && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
1132             continue;
1133
1134         moveCount++;
1135
1136         pos.do_move(move, st);
1137         value = -search(pos, result);
1138         pos.undo_move(move);
1139
1140         if (*result == FAIL)
1141             return WDLDraw;
1142
1143         if (value > bestValue)
1144         {
1145             bestValue = value;
1146
1147             if (value >= WDLWin)
1148             {
1149                 *result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
1150                 return value;
1151             }
1152         }
1153     }
1154
1155     // In case we have already searched all the legal moves we don't have to probe
1156     // the TB because the stored score could be wrong. For instance TB tables
1157     // do not contain information on position with ep rights, so in this case
1158     // the result of probe_wdl_table is wrong. Also in case of only capture
1159     // moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
1160     // return with ZEROING_BEST_MOVE set.
1161     bool noMoreMoves = (moveCount && moveCount == totalCount);
1162
1163     if (noMoreMoves)
1164         value = bestValue;
1165     else
1166     {
1167         value = probe_table<WDL>(pos, result);
1168
1169         if (*result == FAIL)
1170             return WDLDraw;
1171     }
1172
1173     // DTZ stores a "don't care" value if bestValue is a win
1174     if (bestValue >= value)
1175         return *result = (   bestValue > WDLDraw
1176                           || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
1177
1178     return *result = OK, value;
1179 }
1180
1181 } // namespace
1182
1183 void Tablebases::init(const std::string& paths) {
1184
1185     EntryTable.clear();
1186     MaxCardinality = 0;
1187     TBFile::Paths = paths;
1188
1189     if (paths.empty() || paths == "<empty>")
1190         return;
1191
1192     // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
1193     int code = 0;
1194     for (Square s = SQ_A1; s <= SQ_H8; ++s)
1195         if (off_A1H8(s) < 0)
1196             MapB1H1H7[s] = code++;
1197
1198     // MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
1199     std::vector<Square> diagonal;
1200     code = 0;
1201     for (Square s = SQ_A1; s <= SQ_D4; ++s)
1202         if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
1203             MapA1D1D4[s] = code++;
1204
1205         else if (!off_A1H8(s) && file_of(s) <= FILE_D)
1206             diagonal.push_back(s);
1207
1208     // Diagonal squares are encoded as last ones
1209     for (auto s : diagonal)
1210         MapA1D1D4[s] = code++;
1211
1212     // MapKK[] encodes all the 461 possible legal positions of two kings where
1213     // the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
1214     // diagonal, the other one shall not to be above the a1-h8 diagonal.
1215     std::vector<std::pair<int, Square>> bothOnDiagonal;
1216     code = 0;
1217     for (int idx = 0; idx < 10; idx++)
1218         for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
1219             if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
1220             {
1221                 for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
1222                     if ((PseudoAttacks[KING][s1] | s1) & s2)
1223                         continue; // Illegal position
1224
1225                     else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
1226                         continue; // First on diagonal, second above
1227
1228                     else if (!off_A1H8(s1) && !off_A1H8(s2))
1229                         bothOnDiagonal.push_back(std::make_pair(idx, s2));
1230
1231                     else
1232                         MapKK[idx][s2] = code++;
1233             }
1234
1235     // Legal positions with both kings on diagonal are encoded as last ones
1236     for (auto p : bothOnDiagonal)
1237         MapKK[p.first][p.second] = code++;
1238
1239     // Binomial[] stores the Binomial Coefficents using Pascal rule. There
1240     // are Binomial[k][n] ways to choose k elements from a set of n elements.
1241     Binomial[0][0] = 1;
1242
1243     for (int n = 1; n < 64; n++) // Squares
1244         for (int k = 0; k < 6 && k <= n; ++k) // Pieces
1245             Binomial[k][n] =  (k > 0 ? Binomial[k - 1][n - 1] : 0)
1246                             + (k < n ? Binomial[k    ][n - 1] : 0);
1247
1248     // MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
1249     // available squares when the leading one is in 's'. Moreover the pawn with
1250     // highest MapPawns[] is the leading pawn, the one nearest the edge and,
1251     // among pawns with same file, the one with lowest rank.
1252     int availableSquares = 47; // Available squares when lead pawn is in a2
1253
1254     // Init the tables for the encoding of leading pawns group: with 6-men TB we
1255     // can have up to 4 leading pawns (KPPPPK).
1256     for (int leadPawnsCnt = 1; leadPawnsCnt <= 4; ++leadPawnsCnt)
1257         for (File f = FILE_A; f <= FILE_D; ++f)
1258         {
1259             // Restart the index at every file because TB table is splitted
1260             // by file, so we can reuse the same index for different files.
1261             int idx = 0;
1262
1263             // Sum all possible combinations for a given file, starting with
1264             // the leading pawn on rank 2 and increasing the rank.
1265             for (Rank r = RANK_2; r <= RANK_7; ++r)
1266             {
1267                 Square sq = make_square(f, r);
1268
1269                 // Compute MapPawns[] at first pass.
1270                 // If sq is the leading pawn square, any other pawn cannot be
1271                 // below or more toward the edge of sq. There are 47 available
1272                 // squares when sq = a2 and reduced by 2 for any rank increase
1273                 // due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
1274                 if (leadPawnsCnt == 1)
1275                 {
1276                     MapPawns[sq] = availableSquares--;
1277                     MapPawns[sq ^ 7] = availableSquares--; // Horizontal flip
1278                 }
1279                 LeadPawnIdx[leadPawnsCnt][sq] = idx;
1280                 idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
1281             }
1282             // After a file is traversed, store the cumulated per-file index
1283             LeadPawnsSize[leadPawnsCnt][f] = idx;
1284         }
1285
1286     for (PieceType p1 = PAWN; p1 < KING; ++p1) {
1287         EntryTable.insert({KING, p1, KING});
1288
1289         for (PieceType p2 = PAWN; p2 <= p1; ++p2) {
1290             EntryTable.insert({KING, p1, p2, KING});
1291             EntryTable.insert({KING, p1, KING, p2});
1292
1293             for (PieceType p3 = PAWN; p3 < KING; ++p3)
1294                 EntryTable.insert({KING, p1, p2, KING, p3});
1295
1296             for (PieceType p3 = PAWN; p3 <= p2; ++p3) {
1297                 EntryTable.insert({KING, p1, p2, p3, KING});
1298
1299                 for (PieceType p4 = PAWN; p4 <= p3; ++p4)
1300                     EntryTable.insert({KING, p1, p2, p3, p4, KING});
1301
1302                 for (PieceType p4 = PAWN; p4 < KING; ++p4)
1303                     EntryTable.insert({KING, p1, p2, p3, KING, p4});
1304             }
1305
1306             for (PieceType p3 = PAWN; p3 <= p1; ++p3)
1307                 for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
1308                     EntryTable.insert({KING, p1, p2, KING, p3, p4});
1309         }
1310     }
1311
1312     sync_cout << "info string Found " << EntryTable.size() << " tablebases" << sync_endl;
1313 }
1314
1315 // Probe the WDL table for a particular position.
1316 // If *result != FAIL, the probe was successful.
1317 // The return value is from the point of view of the side to move:
1318 // -2 : loss
1319 // -1 : loss, but draw under 50-move rule
1320 //  0 : draw
1321 //  1 : win, but draw under 50-move rule
1322 //  2 : win
1323 WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
1324
1325     *result = OK;
1326     return search(pos, result);
1327 }
1328
1329 // Probe the DTZ table for a particular position.
1330 // If *result != FAIL, the probe was successful.
1331 // The return value is from the point of view of the side to move:
1332 //         n < -100 : loss, but draw under 50-move rule
1333 // -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0)
1334 //         0        : draw
1335 //     1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1336 //   100 < n        : win, but draw under 50-move rule
1337 //
1338 // The return value n can be off by 1: a return value -n can mean a loss
1339 // in n+1 ply and a return value +n can mean a win in n+1 ply. This
1340 // cannot happen for tables with positions exactly on the "edge" of
1341 // the 50-move rule.
1342 //
1343 // This implies that if dtz > 0 is returned, the position is certainly
1344 // a win if dtz + 50-move-counter <= 99. Care must be taken that the engine
1345 // picks moves that preserve dtz + 50-move-counter <= 99.
1346 //
1347 // If n = 100 immediately after a capture or pawn move, then the position
1348 // is also certainly a win, and during the whole phase until the next
1349 // capture or pawn move, the inequality to be preserved is
1350 // dtz + 50-movecounter <= 100.
1351 //
1352 // In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1353 // then do not accept moves leading to dtz + 50-move-counter == 100.
1354 int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
1355
1356     *result = OK;
1357     WDLScore wdl = search<true>(pos, result);
1358
1359     if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
1360         return 0;
1361
1362     // DTZ stores a 'don't care' value in this case, or even a plain wrong
1363     // one as in case the best move is a losing ep, so it cannot be probed.
1364     if (*result == ZEROING_BEST_MOVE)
1365         return dtz_before_zeroing(wdl);
1366
1367     int dtz = probe_table<DTZ>(pos, result, wdl);
1368
1369     if (*result == FAIL)
1370         return 0;
1371
1372     if (*result != CHANGE_STM)
1373         return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
1374
1375     // DTZ stores results for the other side, so we need to do a 1-ply search and
1376     // find the winning move that minimizes DTZ.
1377     StateInfo st;
1378     int minDTZ = 0xFFFF;
1379
1380     for (const Move& move : MoveList<LEGAL>(pos))
1381     {
1382         bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
1383
1384         pos.do_move(move, st);
1385
1386         // For zeroing moves we want the dtz of the move _before_ doing it,
1387         // otherwise we will get the dtz of the next move sequence. Search the
1388         // position after the move to get the score sign (because even in a
1389         // winning position we could make a losing capture or going for a draw).
1390         dtz = zeroing ? -dtz_before_zeroing(search(pos, result))
1391                       : -probe_dtz(pos, result);
1392
1393         pos.undo_move(move);
1394
1395         if (*result == FAIL)
1396             return 0;
1397
1398         // Convert result from 1-ply search. Zeroing moves are already accounted
1399         // by dtz_before_zeroing() that returns the DTZ of the previous move.
1400         if (!zeroing)
1401             dtz += sign_of(dtz);
1402
1403         // Skip the draws and if we are winning only pick positive dtz
1404         if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
1405             minDTZ = dtz;
1406     }
1407
1408     // Special handle a mate position, when there are no legal moves, in this
1409     // case return value is somewhat arbitrary, so stick to the original TB code
1410     // that returns -1 in this case.
1411     return minDTZ == 0xFFFF ? -1 : minDTZ;
1412 }
1413
1414 // Check whether there has been at least one repetition of positions
1415 // since the last capture or pawn move.
1416 static int has_repeated(StateInfo *st)
1417 {
1418     while (1) {
1419         int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1420
1421         if (e < i)
1422             return 0;
1423
1424         StateInfo *stp = st->previous->previous;
1425
1426         do {
1427             stp = stp->previous->previous;
1428
1429             if (stp->key == st->key)
1430                 return 1;
1431
1432             i += 2;
1433         } while (i <= e);
1434
1435         st = st->previous;
1436     }
1437 }
1438
1439 // Use the DTZ tables to filter out moves that don't preserve the win or draw.
1440 // If the position is lost, but DTZ is fairly high, only keep moves that
1441 // maximise DTZ.
1442 //
1443 // A return value false indicates that not all probes were successful and that
1444 // no moves were filtered out.
1445 bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves, Value& score)
1446 {
1447     assert(rootMoves.size());
1448
1449     ProbeState result;
1450     int dtz = probe_dtz(pos, &result);
1451
1452     if (result == FAIL)
1453         return false;
1454
1455     StateInfo st;
1456
1457     // Probe each move
1458     for (size_t i = 0; i < rootMoves.size(); ++i) {
1459         Move move = rootMoves[i].pv[0];
1460         pos.do_move(move, st);
1461         int v = 0;
1462
1463         if (pos.checkers() && dtz > 0) {
1464             ExtMove s[MAX_MOVES];
1465
1466             if (generate<LEGAL>(pos, s) == s)
1467                 v = 1;
1468         }
1469
1470         if (!v) {
1471             if (st.rule50 != 0) {
1472                 v = -probe_dtz(pos, &result);
1473
1474                 if (v > 0)
1475                     ++v;
1476                 else if (v < 0)
1477                     --v;
1478             } else {
1479                 v = -probe_wdl(pos, &result);
1480                 v = dtz_before_zeroing(WDLScore(v));
1481             }
1482         }
1483
1484         pos.undo_move(move);
1485
1486         if (result == FAIL)
1487             return false;
1488
1489         rootMoves[i].score = (Value)v;
1490     }
1491
1492     // Obtain 50-move counter for the root position.
1493     // In Stockfish there seems to be no clean way, so we do it like this:
1494     int cnt50 = st.previous ? st.previous->rule50 : 0;
1495
1496     // Use 50-move counter to determine whether the root position is
1497     // won, lost or drawn.
1498     WDLScore wdl = WDLDraw;
1499
1500     if (dtz > 0)
1501         wdl = (dtz + cnt50 <= 100) ? WDLWin : WDLCursedWin;
1502     else if (dtz < 0)
1503         wdl = (-dtz + cnt50 <= 100) ? WDLLoss : WDLBlessedLoss;
1504
1505     // Determine the score to report to the user.
1506     score = WDL_to_value[wdl + 2];
1507
1508     // If the position is winning or losing, but too few moves left, adjust the
1509     // score to show how close it is to winning or losing.
1510     // NOTE: int(PawnValueEg) is used as scaling factor in score_to_uci().
1511     if (wdl == WDLCursedWin && dtz <= 100)
1512         score = (Value)(((200 - dtz - cnt50) * int(PawnValueEg)) / 200);
1513     else if (wdl == WDLBlessedLoss && dtz >= -100)
1514         score = -(Value)(((200 + dtz - cnt50) * int(PawnValueEg)) / 200);
1515
1516     // Now be a bit smart about filtering out moves.
1517     size_t j = 0;
1518
1519     if (dtz > 0) { // winning (or 50-move rule draw)
1520         int best = 0xffff;
1521
1522         for (size_t i = 0; i < rootMoves.size(); ++i) {
1523             int v = rootMoves[i].score;
1524
1525             if (v > 0 && v < best)
1526                 best = v;
1527         }
1528
1529         int max = best;
1530
1531         // If the current phase has not seen repetitions, then try all moves
1532         // that stay safely within the 50-move budget, if there are any.
1533         if (!has_repeated(st.previous) && best + cnt50 <= 99)
1534             max = 99 - cnt50;
1535
1536         for (size_t i = 0; i < rootMoves.size(); ++i) {
1537             int v = rootMoves[i].score;
1538
1539             if (v > 0 && v <= max)
1540                 rootMoves[j++] = rootMoves[i];
1541         }
1542     } else if (dtz < 0) { // losing (or 50-move rule draw)
1543         int best = 0;
1544
1545         for (size_t i = 0; i < rootMoves.size(); ++i) {
1546             int v = rootMoves[i].score;
1547
1548             if (v < best)
1549                 best = v;
1550         }
1551
1552         // Try all moves, unless we approach or have a 50-move rule draw.
1553         if (-best * 2 + cnt50 < 100)
1554             return true;
1555
1556         for (size_t i = 0; i < rootMoves.size(); ++i) {
1557             if (rootMoves[i].score == best)
1558                 rootMoves[j++] = rootMoves[i];
1559         }
1560     } else { // drawing
1561         // Try all moves that preserve the draw.
1562         for (size_t i = 0; i < rootMoves.size(); ++i) {
1563             if (rootMoves[i].score == 0)
1564                 rootMoves[j++] = rootMoves[i];
1565         }
1566     }
1567
1568     rootMoves.resize(j, Search::RootMove(MOVE_NONE));
1569
1570     return true;
1571 }
1572
1573 // Use the WDL tables to filter out moves that don't preserve the win or draw.
1574 // This is a fallback for the case that some or all DTZ tables are missing.
1575 //
1576 // A return value false indicates that not all probes were successful and that
1577 // no moves were filtered out.
1578 bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, Value& score)
1579 {
1580     ProbeState result;
1581
1582     WDLScore wdl = Tablebases::probe_wdl(pos, &result);
1583
1584     if (result == FAIL)
1585         return false;
1586
1587     score = WDL_to_value[wdl + 2];
1588
1589     StateInfo st;
1590
1591     int best = WDLLoss;
1592
1593     // Probe each move
1594     for (size_t i = 0; i < rootMoves.size(); ++i) {
1595         Move move = rootMoves[i].pv[0];
1596         pos.do_move(move, st);
1597         WDLScore v = -Tablebases::probe_wdl(pos, &result);
1598         pos.undo_move(move);
1599
1600         if (result == FAIL)
1601             return false;
1602
1603         rootMoves[i].score = (Value)v;
1604
1605         if (v > best)
1606             best = v;
1607     }
1608
1609     size_t j = 0;
1610
1611     for (size_t i = 0; i < rootMoves.size(); ++i) {
1612         if (rootMoves[i].score == best)
1613             rootMoves[j++] = rootMoves[i];
1614     }
1615
1616     rootMoves.resize(j, Search::RootMove(MOVE_NONE));
1617
1618     return true;
1619 }