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