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