]> git.sesse.net Git - stockfish/blob - src/search.cpp
e976274f28fd4369dc8793b4782e80ef7e7cabc7
[stockfish] / src / search.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2019 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cmath>
24 #include <cstring>   // For std::memset
25 #include <iostream>
26 #include <sstream>
27
28 #include "evaluate.h"
29 #include "misc.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "position.h"
33 #include "search.h"
34 #include "thread.h"
35 #include "timeman.h"
36 #include "tt.h"
37 #include "uci.h"
38 #include "syzygy/tbprobe.h"
39
40 namespace Search {
41
42   LimitsType Limits;
43 }
44
45 namespace Tablebases {
46
47   int Cardinality;
48   bool RootInTB;
49   bool UseRule50;
50   Depth ProbeDepth;
51 }
52
53 namespace TB = Tablebases;
54
55 using std::string;
56 using Eval::evaluate;
57 using namespace Search;
58
59 namespace {
60
61   // Different node types, used as a template parameter
62   enum NodeType { NonPV, PV };
63
64   constexpr uint64_t ttHitAverageWindow     = 4096;
65   constexpr uint64_t ttHitAverageResolution = 1024;
66
67   // Razor and futility margins
68   constexpr int RazorMargin = 661;
69   Value futility_margin(Depth d, bool improving) {
70     return Value(198 * (d - improving));
71   }
72
73   // Reductions lookup table, initialized at startup
74   int Reductions[MAX_MOVES]; // [depth or moveNumber]
75
76   Depth reduction(bool i, Depth d, int mn) {
77     int r = Reductions[d] * Reductions[mn];
78     return (r + 520) / 1024 + (!i && r > 999);
79   }
80
81   constexpr int futility_move_count(bool improving, Depth depth) {
82     return (5 + depth * depth) * (1 + improving) / 2 - 1;
83   }
84
85   // History and stats update bonus, based on depth
86   int stat_bonus(Depth d) {
87     return d > 17 ? -8 : 22 * d * d + 151 * d - 140;
88   }
89
90   // Add a small random component to draw evaluations to avoid 3fold-blindness
91   Value value_draw(Thread* thisThread) {
92     return VALUE_DRAW + Value(2 * (thisThread->nodes & 1) - 1);
93   }
94
95   // Skill structure is used to implement strength limit
96   struct Skill {
97     explicit Skill(int l) : level(l) {}
98     bool enabled() const { return level < 20; }
99     bool time_to_pick(Depth depth) const { return depth == 1 + level; }
100     Move pick_best(size_t multiPV);
101
102     int level;
103     Move best = MOVE_NONE;
104   };
105
106   // Breadcrumbs are used to mark nodes as being searched by a given thread
107   struct Breadcrumb {
108     std::atomic<Thread*> thread;
109     std::atomic<Key> key;
110   };
111   std::array<Breadcrumb, 1024> breadcrumbs;
112
113   // ThreadHolding structure keeps track of which thread left breadcrumbs at the given
114   // node for potential reductions. A free node will be marked upon entering the moves
115   // loop by the constructor, and unmarked upon leaving that loop by the destructor.
116   struct ThreadHolding {
117     explicit ThreadHolding(Thread* thisThread, Key posKey, int ply) {
118        location = ply < 8 ? &breadcrumbs[posKey & (breadcrumbs.size() - 1)] : nullptr;
119        otherThread = false;
120        owning = false;
121        if (location)
122        {
123           // See if another already marked this location, if not, mark it ourselves
124           Thread* tmp = (*location).thread.load(std::memory_order_relaxed);
125           if (tmp == nullptr)
126           {
127               (*location).thread.store(thisThread, std::memory_order_relaxed);
128               (*location).key.store(posKey, std::memory_order_relaxed);
129               owning = true;
130           }
131           else if (   tmp != thisThread
132                    && (*location).key.load(std::memory_order_relaxed) == posKey)
133               otherThread = true;
134        }
135     }
136
137     ~ThreadHolding() {
138        if (owning) // Free the marked location
139            (*location).thread.store(nullptr, std::memory_order_relaxed);
140     }
141
142     bool marked() { return otherThread; }
143
144     private:
145     Breadcrumb* location;
146     bool otherThread, owning;
147   };
148
149   template <NodeType NT>
150   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode);
151
152   template <NodeType NT>
153   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth = 0);
154
155   Value value_to_tt(Value v, int ply);
156   Value value_from_tt(Value v, int ply, int r50c);
157   void update_pv(Move* pv, Move move, Move* childPv);
158   void update_continuation_histories(Stack* ss, Piece pc, Square to, int bonus);
159   void update_quiet_stats(const Position& pos, Stack* ss, Move move, int bonus);
160   void update_all_stats(const Position& pos, Stack* ss, Move bestMove, Value bestValue, Value beta, Square prevSq,
161                         Move* quietsSearched, int quietCount, Move* capturesSearched, int captureCount, Depth depth);
162
163   // perft() is our utility to verify move generation. All the leaf nodes up
164   // to the given depth are generated and counted, and the sum is returned.
165   template<bool Root>
166   uint64_t perft(Position& pos, Depth depth) {
167
168     StateInfo st;
169     uint64_t cnt, nodes = 0;
170     const bool leaf = (depth == 2);
171
172     for (const auto& m : MoveList<LEGAL>(pos))
173     {
174         if (Root && depth <= 1)
175             cnt = 1, nodes++;
176         else
177         {
178             pos.do_move(m, st);
179             cnt = leaf ? MoveList<LEGAL>(pos).size() : perft<false>(pos, depth - 1);
180             nodes += cnt;
181             pos.undo_move(m);
182         }
183         if (Root)
184             sync_cout << UCI::move(m, pos.is_chess960()) << ": " << cnt << sync_endl;
185     }
186     return nodes;
187   }
188
189 } // namespace
190
191
192 /// Search::init() is called at startup to initialize various lookup tables
193
194 void Search::init() {
195
196   for (int i = 1; i < MAX_MOVES; ++i)
197       Reductions[i] = int((23.4 + std::log(Threads.size()) / 2) * std::log(i));
198 }
199
200
201 /// Search::clear() resets search state to its initial value
202
203 void Search::clear() {
204
205   Threads.main()->wait_for_search_finished();
206
207   Time.availableNodes = 0;
208   TT.clear();
209   Threads.clear();
210   Tablebases::init(Options["SyzygyPath"]); // Free mapped files
211 }
212
213
214 /// MainThread::search() is started when the program receives the UCI 'go'
215 /// command. It searches from the root position and outputs the "bestmove".
216
217 void MainThread::search() {
218
219   if (Limits.perft)
220   {
221       nodes = perft<true>(rootPos, Limits.perft);
222       sync_cout << "\nNodes searched: " << nodes << "\n" << sync_endl;
223       return;
224   }
225
226   Color us = rootPos.side_to_move();
227   Time.init(Limits, us, rootPos.game_ply());
228   TT.new_search();
229
230   if (rootMoves.empty())
231   {
232       rootMoves.emplace_back(MOVE_NONE);
233       sync_cout << "info depth 0 score "
234                 << UCI::value(rootPos.checkers() ? -VALUE_MATE : VALUE_DRAW)
235                 << sync_endl;
236   }
237   else
238   {
239       for (Thread* th : Threads)
240       {
241           th->bestMoveChanges = 0;
242           if (th != this)
243               th->start_searching();
244       }
245
246       Thread::search(); // Let's start searching!
247   }
248
249   // When we reach the maximum depth, we can arrive here without a raise of
250   // Threads.stop. However, if we are pondering or in an infinite search,
251   // the UCI protocol states that we shouldn't print the best move before the
252   // GUI sends a "stop" or "ponderhit" command. We therefore simply wait here
253   // until the GUI sends one of those commands.
254
255   while (!Threads.stop && (ponder || Limits.infinite))
256   {} // Busy wait for a stop or a ponder reset
257
258   // Stop the threads if not already stopped (also raise the stop if
259   // "ponderhit" just reset Threads.ponder).
260   Threads.stop = true;
261
262   // Wait until all threads have finished
263   for (Thread* th : Threads)
264       if (th != this)
265           th->wait_for_search_finished();
266
267   // When playing in 'nodes as time' mode, subtract the searched nodes from
268   // the available ones before exiting.
269   if (Limits.npmsec)
270       Time.availableNodes += Limits.inc[us] - Threads.nodes_searched();
271
272   Thread* bestThread = this;
273
274   // Check if there are threads with a better score than main thread
275   if (    Options["MultiPV"] == 1
276       && !Limits.depth
277       && !(Skill(Options["Skill Level"]).enabled() || Options["UCI_LimitStrength"])
278       &&  rootMoves[0].pv[0] != MOVE_NONE)
279   {
280       std::map<Move, int64_t> votes;
281       Value minScore = this->rootMoves[0].score;
282
283       // Find out minimum score
284       for (Thread* th: Threads)
285           minScore = std::min(minScore, th->rootMoves[0].score);
286
287       // Vote according to score and depth, and select the best thread
288       for (Thread* th : Threads)
289       {
290           votes[th->rootMoves[0].pv[0]] +=
291               (th->rootMoves[0].score - minScore + 14) * int(th->completedDepth);
292
293           if (bestThread->rootMoves[0].score >= VALUE_MATE_IN_MAX_PLY)
294           {
295               // Make sure we pick the shortest mate
296               if (th->rootMoves[0].score > bestThread->rootMoves[0].score)
297                   bestThread = th;
298           }
299           else if (   th->rootMoves[0].score >= VALUE_MATE_IN_MAX_PLY
300                    || votes[th->rootMoves[0].pv[0]] > votes[bestThread->rootMoves[0].pv[0]])
301               bestThread = th;
302       }
303   }
304
305   previousScore = bestThread->rootMoves[0].score;
306
307   // Send again PV info if we have a new best thread
308   if (bestThread != this)
309       sync_cout << UCI::pv(bestThread->rootPos, bestThread->completedDepth, -VALUE_INFINITE, VALUE_INFINITE) << sync_endl;
310
311   sync_cout << "bestmove " << UCI::move(bestThread->rootMoves[0].pv[0], rootPos.is_chess960());
312
313   if (bestThread->rootMoves[0].pv.size() > 1 || bestThread->rootMoves[0].extract_ponder_from_tt(rootPos))
314       std::cout << " ponder " << UCI::move(bestThread->rootMoves[0].pv[1], rootPos.is_chess960());
315
316   std::cout << sync_endl;
317 }
318
319
320 /// Thread::search() is the main iterative deepening loop. It calls search()
321 /// repeatedly with increasing depth until the allocated thinking time has been
322 /// consumed, the user stops the search, or the maximum search depth is reached.
323
324 void Thread::search() {
325
326   // To allow access to (ss-7) up to (ss+2), the stack must be oversized.
327   // The former is needed to allow update_continuation_histories(ss-1, ...),
328   // which accesses its argument at ss-6, also near the root.
329   // The latter is needed for statScores and killer initialization.
330   Stack stack[MAX_PLY+10], *ss = stack+7;
331   Move  pv[MAX_PLY+1];
332   Value bestValue, alpha, beta, delta;
333   Move  lastBestMove = MOVE_NONE;
334   Depth lastBestMoveDepth = 0;
335   MainThread* mainThread = (this == Threads.main() ? Threads.main() : nullptr);
336   double timeReduction = 1, totBestMoveChanges = 0;
337   Color us = rootPos.side_to_move();
338
339   std::memset(ss-7, 0, 10 * sizeof(Stack));
340   for (int i = 7; i > 0; i--)
341       (ss-i)->continuationHistory = &this->continuationHistory[0][0][NO_PIECE][0]; // Use as a sentinel
342
343   ss->pv = pv;
344
345   bestValue = delta = alpha = -VALUE_INFINITE;
346   beta = VALUE_INFINITE;
347
348   size_t multiPV = Options["MultiPV"];
349
350   // Pick integer skill levels, but non-deterministically round up or down
351   // such that the average integer skill corresponds to the input floating point one.
352   // UCI_Elo is converted to a suitable fractional skill level, using anchoring
353   // to CCRL Elo (goldfish 1.13 = 2000) and a fit through Ordo derived Elo
354   // for match (TC 60+0.6) results spanning a wide range of k values.
355   PRNG rng(now());
356   double floatLevel = Options["UCI_LimitStrength"] ?
357                         clamp(std::pow((Options["UCI_Elo"] - 1346.6) / 143.4, 1 / 0.806), 0.0, 20.0) :
358                         double(Options["Skill Level"]);
359   int intLevel = int(floatLevel) +
360                  ((floatLevel - int(floatLevel)) * 1024 > rng.rand<unsigned>() % 1024  ? 1 : 0);
361   Skill skill(intLevel);
362
363   // When playing with strength handicap enable MultiPV search that we will
364   // use behind the scenes to retrieve a set of possible moves.
365   if (skill.enabled())
366       multiPV = std::max(multiPV, (size_t)4);
367
368   multiPV = std::min(multiPV, rootMoves.size());
369   ttHitAverage = ttHitAverageWindow * ttHitAverageResolution / 2;
370
371   int ct = int(Options["Contempt"]) * PawnValueEg / 100; // From centipawns
372
373   // In analysis mode, adjust contempt in accordance with user preference
374   if (Limits.infinite || Options["UCI_AnalyseMode"])
375       ct =  Options["Analysis Contempt"] == "Off"  ? 0
376           : Options["Analysis Contempt"] == "Both" ? ct
377           : Options["Analysis Contempt"] == "White" && us == BLACK ? -ct
378           : Options["Analysis Contempt"] == "Black" && us == WHITE ? -ct
379           : ct;
380
381   // Evaluation score is from the white point of view
382   contempt = (us == WHITE ?  make_score(ct, ct / 2)
383                           : -make_score(ct, ct / 2));
384
385   // Iterative deepening loop until requested to stop or the target depth is reached
386   while (   ++rootDepth < MAX_PLY
387          && !Threads.stop
388          && !(Limits.depth && mainThread && rootDepth > Limits.depth))
389   {
390       // Age out PV variability metric
391       if (mainThread)
392           totBestMoveChanges /= 2;
393
394       // Save the last iteration's scores before first PV line is searched and
395       // all the move scores except the (new) PV are set to -VALUE_INFINITE.
396       for (RootMove& rm : rootMoves)
397           rm.previousScore = rm.score;
398
399       size_t pvFirst = 0;
400       pvLast = 0;
401
402       // MultiPV loop. We perform a full root search for each PV line
403       for (pvIdx = 0; pvIdx < multiPV && !Threads.stop; ++pvIdx)
404       {
405           if (pvIdx == pvLast)
406           {
407               pvFirst = pvLast;
408               for (pvLast++; pvLast < rootMoves.size(); pvLast++)
409                   if (rootMoves[pvLast].tbRank != rootMoves[pvFirst].tbRank)
410                       break;
411           }
412
413           // Reset UCI info selDepth for each depth and each PV line
414           selDepth = 0;
415
416           // Reset aspiration window starting size
417           if (rootDepth >= 4)
418           {
419               Value previousScore = rootMoves[pvIdx].previousScore;
420               delta = Value(21 + abs(previousScore) / 128);
421               alpha = std::max(previousScore - delta,-VALUE_INFINITE);
422               beta  = std::min(previousScore + delta, VALUE_INFINITE);
423
424               // Adjust contempt based on root move's previousScore (dynamic contempt)
425               int dct = ct + (111 - ct / 2) * previousScore / (abs(previousScore) + 176);
426
427               contempt = (us == WHITE ?  make_score(dct, dct / 2)
428                                       : -make_score(dct, dct / 2));
429           }
430
431           // Start with a small aspiration window and, in the case of a fail
432           // high/low, re-search with a bigger window until we don't fail
433           // high/low anymore.
434           int failedHighCnt = 0;
435           while (true)
436           {
437               Depth adjustedDepth = std::max(1, rootDepth - failedHighCnt);
438               bestValue = ::search<PV>(rootPos, ss, alpha, beta, adjustedDepth, false);
439
440               // Bring the best move to the front. It is critical that sorting
441               // is done with a stable algorithm because all the values but the
442               // first and eventually the new best one are set to -VALUE_INFINITE
443               // and we want to keep the same order for all the moves except the
444               // new PV that goes to the front. Note that in case of MultiPV
445               // search the already searched PV lines are preserved.
446               std::stable_sort(rootMoves.begin() + pvIdx, rootMoves.begin() + pvLast);
447
448               // If search has been stopped, we break immediately. Sorting is
449               // safe because RootMoves is still valid, although it refers to
450               // the previous iteration.
451               if (Threads.stop)
452                   break;
453
454               // When failing high/low give some update (without cluttering
455               // the UI) before a re-search.
456               if (   mainThread
457                   && multiPV == 1
458                   && (bestValue <= alpha || bestValue >= beta)
459                   && Time.elapsed() > 3000)
460                   sync_cout << UCI::pv(rootPos, rootDepth, alpha, beta) << sync_endl;
461
462               // In case of failing low/high increase aspiration window and
463               // re-search, otherwise exit the loop.
464               if (bestValue <= alpha)
465               {
466                   beta = (alpha + beta) / 2;
467                   alpha = std::max(bestValue - delta, -VALUE_INFINITE);
468
469                   failedHighCnt = 0;
470                   if (mainThread)
471                       mainThread->stopOnPonderhit = false;
472               }
473               else if (bestValue >= beta)
474               {
475                   beta = std::min(bestValue + delta, VALUE_INFINITE);
476                   ++failedHighCnt;
477               }
478               else
479               {
480                   ++rootMoves[pvIdx].bestMoveCount;
481                   break;
482               }
483
484               delta += delta / 4 + 5;
485
486               assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
487           }
488
489           // Sort the PV lines searched so far and update the GUI
490           std::stable_sort(rootMoves.begin() + pvFirst, rootMoves.begin() + pvIdx + 1);
491
492           if (    mainThread
493               && (Threads.stop || pvIdx + 1 == multiPV || Time.elapsed() > 3000))
494               sync_cout << UCI::pv(rootPos, rootDepth, alpha, beta) << sync_endl;
495       }
496
497       if (!Threads.stop)
498           completedDepth = rootDepth;
499
500       if (rootMoves[0].pv[0] != lastBestMove) {
501          lastBestMove = rootMoves[0].pv[0];
502          lastBestMoveDepth = rootDepth;
503       }
504
505       // Have we found a "mate in x"?
506       if (   Limits.mate
507           && bestValue >= VALUE_MATE_IN_MAX_PLY
508           && VALUE_MATE - bestValue <= 2 * Limits.mate)
509           Threads.stop = true;
510
511       if (!mainThread)
512           continue;
513
514       // If skill level is enabled and time is up, pick a sub-optimal best move
515       if (skill.enabled() && skill.time_to_pick(rootDepth))
516           skill.pick_best(multiPV);
517
518       // Do we have time for the next iteration? Can we stop searching now?
519       if (    Limits.use_time_management()
520           && !Threads.stop
521           && !mainThread->stopOnPonderhit)
522       {
523           double fallingEval = (354 + 10 * (mainThread->previousScore - bestValue)) / 692.0;
524           fallingEval = clamp(fallingEval, 0.5, 1.5);
525
526           // If the bestMove is stable over several iterations, reduce time accordingly
527           timeReduction = lastBestMoveDepth + 9 < completedDepth ? 1.97 : 0.98;
528           double reduction = (1.36 + mainThread->previousTimeReduction) / (2.29 * timeReduction);
529
530           // Use part of the gained time from a previous stable move for the current move
531           for (Thread* th : Threads)
532           {
533               totBestMoveChanges += th->bestMoveChanges;
534               th->bestMoveChanges = 0;
535           }
536           double bestMoveInstability = 1 + totBestMoveChanges / Threads.size();
537
538           // Stop the search if we have only one legal move, or if available time elapsed
539           if (   rootMoves.size() == 1
540               || Time.elapsed() > Time.optimum() * fallingEval * reduction * bestMoveInstability)
541           {
542               // If we are allowed to ponder do not stop the search now but
543               // keep pondering until the GUI sends "ponderhit" or "stop".
544               if (mainThread->ponder)
545                   mainThread->stopOnPonderhit = true;
546               else
547                   Threads.stop = true;
548           }
549       }
550   }
551
552   if (!mainThread)
553       return;
554
555   mainThread->previousTimeReduction = timeReduction;
556
557   // If skill level is enabled, swap best PV line with the sub-optimal one
558   if (skill.enabled())
559       std::swap(rootMoves[0], *std::find(rootMoves.begin(), rootMoves.end(),
560                 skill.best ? skill.best : skill.pick_best(multiPV)));
561 }
562
563
564 namespace {
565
566   // search<>() is the main search function for both PV and non-PV nodes
567
568   template <NodeType NT>
569   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode) {
570
571     constexpr bool PvNode = NT == PV;
572     const bool rootNode = PvNode && ss->ply == 0;
573
574     // Check if we have an upcoming move which draws by repetition, or
575     // if the opponent had an alternative move earlier to this position.
576     if (   pos.rule50_count() >= 3
577         && alpha < VALUE_DRAW
578         && !rootNode
579         && pos.has_game_cycle(ss->ply))
580     {
581         alpha = value_draw(pos.this_thread());
582         if (alpha >= beta)
583             return alpha;
584     }
585
586     // Dive into quiescence search when the depth reaches zero
587     if (depth <= 0)
588         return qsearch<NT>(pos, ss, alpha, beta);
589
590     assert(-VALUE_INFINITE <= alpha && alpha < beta && beta <= VALUE_INFINITE);
591     assert(PvNode || (alpha == beta - 1));
592     assert(0 < depth && depth < MAX_PLY);
593     assert(!(PvNode && cutNode));
594
595     Move pv[MAX_PLY+1], capturesSearched[32], quietsSearched[64];
596     StateInfo st;
597     TTEntry* tte;
598     Key posKey;
599     Move ttMove, move, excludedMove, bestMove;
600     Depth extension, newDepth;
601     Value bestValue, value, ttValue, eval, maxValue;
602     bool ttHit, ttPv, inCheck, givesCheck, improving, didLMR, priorCapture;
603     bool captureOrPromotion, doFullDepthSearch, moveCountPruning, ttCapture, singularLMR;
604     Piece movedPiece;
605     int moveCount, captureCount, quietCount;
606
607     // Step 1. Initialize node
608     Thread* thisThread = pos.this_thread();
609     inCheck = pos.checkers();
610     priorCapture = pos.captured_piece();
611     Color us = pos.side_to_move();
612     moveCount = captureCount = quietCount = ss->moveCount = 0;
613     bestValue = -VALUE_INFINITE;
614     maxValue = VALUE_INFINITE;
615
616     // Check for the available remaining time
617     if (thisThread == Threads.main())
618         static_cast<MainThread*>(thisThread)->check_time();
619
620     // Used to send selDepth info to GUI (selDepth counts from 1, ply from 0)
621     if (PvNode && thisThread->selDepth < ss->ply + 1)
622         thisThread->selDepth = ss->ply + 1;
623
624     if (!rootNode)
625     {
626         // Step 2. Check for aborted search and immediate draw
627         if (   Threads.stop.load(std::memory_order_relaxed)
628             || pos.is_draw(ss->ply)
629             || ss->ply >= MAX_PLY)
630             return (ss->ply >= MAX_PLY && !inCheck) ? evaluate(pos)
631                                                     : value_draw(pos.this_thread());
632
633         // Step 3. Mate distance pruning. Even if we mate at the next move our score
634         // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
635         // a shorter mate was found upward in the tree then there is no need to search
636         // because we will never beat the current alpha. Same logic but with reversed
637         // signs applies also in the opposite condition of being mated instead of giving
638         // mate. In this case return a fail-high score.
639         alpha = std::max(mated_in(ss->ply), alpha);
640         beta = std::min(mate_in(ss->ply+1), beta);
641         if (alpha >= beta)
642             return alpha;
643     }
644
645     assert(0 <= ss->ply && ss->ply < MAX_PLY);
646
647     (ss+1)->ply = ss->ply + 1;
648     (ss+1)->excludedMove = bestMove = MOVE_NONE;
649     (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
650     Square prevSq = to_sq((ss-1)->currentMove);
651
652     // Initialize statScore to zero for the grandchildren of the current position.
653     // So statScore is shared between all grandchildren and only the first grandchild
654     // starts with statScore = 0. Later grandchildren start with the last calculated
655     // statScore of the previous grandchild. This influences the reduction rules in
656     // LMR which are based on the statScore of parent position.
657     if (rootNode)
658         (ss+4)->statScore = 0;
659     else
660         (ss+2)->statScore = 0;
661
662     // Step 4. Transposition table lookup. We don't want the score of a partial
663     // search to overwrite a previous full search TT value, so we use a different
664     // position key in case of an excluded move.
665     excludedMove = ss->excludedMove;
666     posKey = pos.key() ^ Key(excludedMove << 16); // Isn't a very good hash
667     tte = TT.probe(posKey, ttHit);
668     ttValue = ttHit ? value_from_tt(tte->value(), ss->ply, pos.rule50_count()) : VALUE_NONE;
669     ttMove =  rootNode ? thisThread->rootMoves[thisThread->pvIdx].pv[0]
670             : ttHit    ? tte->move() : MOVE_NONE;
671     ttPv = PvNode || (ttHit && tte->is_pv());
672     // thisThread->ttHitAverage can be used to approximate the running average of ttHit
673     thisThread->ttHitAverage =   (ttHitAverageWindow - 1) * thisThread->ttHitAverage / ttHitAverageWindow
674                                 + ttHitAverageResolution * ttHit;
675
676     // At non-PV nodes we check for an early TT cutoff
677     if (  !PvNode
678         && ttHit
679         && tte->depth() >= depth
680         && ttValue != VALUE_NONE // Possible in case of TT access race
681         && (ttValue >= beta ? (tte->bound() & BOUND_LOWER)
682                             : (tte->bound() & BOUND_UPPER)))
683     {
684         // If ttMove is quiet, update move sorting heuristics on TT hit
685         if (ttMove)
686         {
687             if (ttValue >= beta)
688             {
689                 if (!pos.capture_or_promotion(ttMove))
690                     update_quiet_stats(pos, ss, ttMove, stat_bonus(depth));
691
692                 // Extra penalty for early quiet moves of the previous ply
693                 if ((ss-1)->moveCount <= 2 && !priorCapture)
694                     update_continuation_histories(ss-1, pos.piece_on(prevSq), prevSq, -stat_bonus(depth + 1));
695             }
696             // Penalty for a quiet ttMove that fails low
697             else if (!pos.capture_or_promotion(ttMove))
698             {
699                 int penalty = -stat_bonus(depth);
700                 thisThread->mainHistory[us][from_to(ttMove)] << penalty;
701                 update_continuation_histories(ss, pos.moved_piece(ttMove), to_sq(ttMove), penalty);
702             }
703         }
704         return ttValue;
705     }
706
707     // Step 5. Tablebases probe
708     if (!rootNode && TB::Cardinality)
709     {
710         int piecesCount = pos.count<ALL_PIECES>();
711
712         if (    piecesCount <= TB::Cardinality
713             && (piecesCount <  TB::Cardinality || depth >= TB::ProbeDepth)
714             &&  pos.rule50_count() == 0
715             && !pos.can_castle(ANY_CASTLING))
716         {
717             TB::ProbeState err;
718             TB::WDLScore wdl = Tablebases::probe_wdl(pos, &err);
719
720             // Force check of time on the next occasion
721             if (thisThread == Threads.main())
722                 static_cast<MainThread*>(thisThread)->callsCnt = 0;
723
724             if (err != TB::ProbeState::FAIL)
725             {
726                 thisThread->tbHits.fetch_add(1, std::memory_order_relaxed);
727
728                 int drawScore = TB::UseRule50 ? 1 : 0;
729
730                 value =  wdl < -drawScore ? -VALUE_MATE + MAX_PLY + ss->ply + 1
731                        : wdl >  drawScore ?  VALUE_MATE - MAX_PLY - ss->ply - 1
732                                           :  VALUE_DRAW + 2 * wdl * drawScore;
733
734                 Bound b =  wdl < -drawScore ? BOUND_UPPER
735                          : wdl >  drawScore ? BOUND_LOWER : BOUND_EXACT;
736
737                 if (    b == BOUND_EXACT
738                     || (b == BOUND_LOWER ? value >= beta : value <= alpha))
739                 {
740                     tte->save(posKey, value_to_tt(value, ss->ply), ttPv, b,
741                               std::min(MAX_PLY - 1, depth + 6),
742                               MOVE_NONE, VALUE_NONE);
743
744                     return value;
745                 }
746
747                 if (PvNode)
748                 {
749                     if (b == BOUND_LOWER)
750                         bestValue = value, alpha = std::max(alpha, bestValue);
751                     else
752                         maxValue = value;
753                 }
754             }
755         }
756     }
757
758     // Step 6. Static evaluation of the position
759     if (inCheck)
760     {
761         ss->staticEval = eval = VALUE_NONE;
762         improving = false;
763         goto moves_loop;  // Skip early pruning when in check
764     }
765     else if (ttHit)
766     {
767         // Never assume anything about values stored in TT
768         ss->staticEval = eval = tte->eval();
769         if (eval == VALUE_NONE)
770             ss->staticEval = eval = evaluate(pos);
771
772         if (eval == VALUE_DRAW)
773             eval = value_draw(thisThread);
774
775         // Can ttValue be used as a better position evaluation?
776         if (    ttValue != VALUE_NONE
777             && (tte->bound() & (ttValue > eval ? BOUND_LOWER : BOUND_UPPER)))
778             eval = ttValue;
779     }
780     else
781     {
782         if ((ss-1)->currentMove != MOVE_NULL)
783         {
784             int bonus = -(ss-1)->statScore / 512;
785
786             ss->staticEval = eval = evaluate(pos) + bonus;
787         }
788         else
789             ss->staticEval = eval = -(ss-1)->staticEval + 2 * Eval::Tempo;
790
791         tte->save(posKey, VALUE_NONE, ttPv, BOUND_NONE, DEPTH_NONE, MOVE_NONE, eval);
792     }
793
794     // Step 7. Razoring (~2 Elo)
795     if (   !rootNode // The required rootNode PV handling is not available in qsearch
796         &&  depth < 2
797         &&  eval <= alpha - RazorMargin)
798         return qsearch<NT>(pos, ss, alpha, beta);
799
800     improving =   ss->staticEval >= (ss-2)->staticEval
801                || (ss-2)->staticEval == VALUE_NONE;
802
803     // Step 8. Futility pruning: child node (~30 Elo)
804     if (   !PvNode
805         &&  depth < 7
806         &&  eval - futility_margin(depth, improving) >= beta
807         &&  eval < VALUE_KNOWN_WIN) // Do not return unproven wins
808         return eval;
809
810     // Step 9. Null move search with verification search (~40 Elo)
811     if (   !PvNode
812         && (ss-1)->currentMove != MOVE_NULL
813         && (ss-1)->statScore < 22661
814         &&  eval >= beta
815         &&  eval >= ss->staticEval
816         &&  ss->staticEval >= beta - 33 * depth + 299 - improving * 30
817         && !excludedMove
818         &&  pos.non_pawn_material(us)
819         && (ss->ply >= thisThread->nmpMinPly || us != thisThread->nmpColor))
820     {
821         assert(eval - beta >= 0);
822
823         // Null move dynamic reduction based on depth and value
824         Depth R = (835 + 70 * depth) / 256 + std::min(int(eval - beta) / 185, 3);
825
826         ss->currentMove = MOVE_NULL;
827         ss->continuationHistory = &thisThread->continuationHistory[0][0][NO_PIECE][0];
828
829         pos.do_null_move(st);
830
831         Value nullValue = -search<NonPV>(pos, ss+1, -beta, -beta+1, depth-R, !cutNode);
832
833         pos.undo_null_move();
834
835         if (nullValue >= beta)
836         {
837             // Do not return unproven mate scores
838             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
839                 nullValue = beta;
840
841             if (thisThread->nmpMinPly || (abs(beta) < VALUE_KNOWN_WIN && depth < 13))
842                 return nullValue;
843
844             assert(!thisThread->nmpMinPly); // Recursive verification is not allowed
845
846             // Do verification search at high depths, with null move pruning disabled
847             // for us, until ply exceeds nmpMinPly.
848             thisThread->nmpMinPly = ss->ply + 3 * (depth-R) / 4;
849             thisThread->nmpColor = us;
850
851             Value v = search<NonPV>(pos, ss, beta-1, beta, depth-R, false);
852
853             thisThread->nmpMinPly = 0;
854
855             if (v >= beta)
856                 return nullValue;
857         }
858     }
859
860     // Step 10. ProbCut (~10 Elo)
861     // If we have a good enough capture and a reduced search returns a value
862     // much above beta, we can (almost) safely prune the previous move.
863     if (   !PvNode
864         &&  depth >= 5
865         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
866     {
867         Value raisedBeta = std::min(beta + 191 - 46 * improving, VALUE_INFINITE);
868         MovePicker mp(pos, ttMove, raisedBeta - ss->staticEval, &thisThread->captureHistory);
869         int probCutCount = 0;
870
871         while (  (move = mp.next_move()) != MOVE_NONE
872                && probCutCount < 2 + 2 * cutNode)
873             if (move != excludedMove && pos.legal(move))
874             {
875                 assert(pos.capture_or_promotion(move));
876                 assert(depth >= 5);
877
878                 captureOrPromotion = true;
879                 probCutCount++;
880
881                 ss->currentMove = move;
882                 ss->continuationHistory = &thisThread->continuationHistory[inCheck]
883                                                                           [captureOrPromotion]
884                                                                           [pos.moved_piece(move)]
885                                                                           [to_sq(move)];
886
887                 pos.do_move(move, st);
888
889                 // Perform a preliminary qsearch to verify that the move holds
890                 value = -qsearch<NonPV>(pos, ss+1, -raisedBeta, -raisedBeta+1);
891
892                 // If the qsearch held, perform the regular search
893                 if (value >= raisedBeta)
894                     value = -search<NonPV>(pos, ss+1, -raisedBeta, -raisedBeta+1, depth - 4, !cutNode);
895
896                 pos.undo_move(move);
897
898                 if (value >= raisedBeta)
899                     return value;
900             }
901     }
902
903     // Step 11. Internal iterative deepening (~2 Elo)
904     if (depth >= 7 && !ttMove)
905     {
906         search<NT>(pos, ss, alpha, beta, depth - 7, cutNode);
907
908         tte = TT.probe(posKey, ttHit);
909         ttValue = ttHit ? value_from_tt(tte->value(), ss->ply, pos.rule50_count()) : VALUE_NONE;
910         ttMove = ttHit ? tte->move() : MOVE_NONE;
911     }
912
913 moves_loop: // When in check, search starts from here
914
915     const PieceToHistory* contHist[] = { (ss-1)->continuationHistory, (ss-2)->continuationHistory,
916                                           nullptr                   , (ss-4)->continuationHistory,
917                                           nullptr                   , (ss-6)->continuationHistory };
918
919     Move countermove = thisThread->counterMoves[pos.piece_on(prevSq)][prevSq];
920
921     MovePicker mp(pos, ttMove, depth, &thisThread->mainHistory,
922                                       &thisThread->captureHistory,
923                                       contHist,
924                                       countermove,
925                                       ss->killers);
926
927     value = bestValue;
928     singularLMR = moveCountPruning = false;
929     ttCapture = ttMove && pos.capture_or_promotion(ttMove);
930
931     // Mark this node as being searched
932     ThreadHolding th(thisThread, posKey, ss->ply);
933
934     // Step 12. Loop through all pseudo-legal moves until no moves remain
935     // or a beta cutoff occurs.
936     while ((move = mp.next_move(moveCountPruning)) != MOVE_NONE)
937     {
938       assert(is_ok(move));
939
940       if (move == excludedMove)
941           continue;
942
943       // At root obey the "searchmoves" option and skip moves not listed in Root
944       // Move List. As a consequence any illegal move is also skipped. In MultiPV
945       // mode we also skip PV moves which have been already searched and those
946       // of lower "TB rank" if we are in a TB root position.
947       if (rootNode && !std::count(thisThread->rootMoves.begin() + thisThread->pvIdx,
948                                   thisThread->rootMoves.begin() + thisThread->pvLast, move))
949           continue;
950
951       ss->moveCount = ++moveCount;
952
953       if (rootNode && thisThread == Threads.main() && Time.elapsed() > 3000)
954           sync_cout << "info depth " << depth
955                     << " currmove " << UCI::move(move, pos.is_chess960())
956                     << " currmovenumber " << moveCount + thisThread->pvIdx << sync_endl;
957       if (PvNode)
958           (ss+1)->pv = nullptr;
959
960       extension = 0;
961       captureOrPromotion = pos.capture_or_promotion(move);
962       movedPiece = pos.moved_piece(move);
963       givesCheck = pos.gives_check(move);
964
965       // Calculate new depth for this move
966       newDepth = depth - 1;
967
968       // Step 13. Pruning at shallow depth (~170 Elo)
969       if (  !rootNode
970           && pos.non_pawn_material(us)
971           && bestValue > VALUE_MATED_IN_MAX_PLY)
972       {
973           // Skip quiet moves if movecount exceeds our FutilityMoveCount threshold
974           moveCountPruning = moveCount >= futility_move_count(improving, depth);
975
976           if (   !captureOrPromotion
977               && !givesCheck)
978           {
979               // Reduced depth of the next LMR search
980               int lmrDepth = std::max(newDepth - reduction(improving, depth, moveCount), 0);
981
982               // Countermoves based pruning (~20 Elo)
983               if (   lmrDepth < 4 + ((ss-1)->statScore > 0 || (ss-1)->moveCount == 1)
984                   && (*contHist[0])[movedPiece][to_sq(move)] < CounterMovePruneThreshold
985                   && (*contHist[1])[movedPiece][to_sq(move)] < CounterMovePruneThreshold)
986                   continue;
987
988               // Futility pruning: parent node (~2 Elo)
989               if (   lmrDepth < 6
990                   && !inCheck
991                   && ss->staticEval + 250 + 211 * lmrDepth <= alpha)
992                   continue;
993
994               // Prune moves with negative SEE (~10 Elo)
995               if (!pos.see_ge(move, Value(-(31 - std::min(lmrDepth, 18)) * lmrDepth * lmrDepth)))
996                   continue;
997           }
998           else if (!pos.see_ge(move, Value(-199) * depth)) // (~20 Elo)
999                   continue;
1000       }
1001
1002       // Step 14. Extensions (~70 Elo)
1003
1004       // Singular extension search (~60 Elo). If all moves but one fail low on a
1005       // search of (alpha-s, beta-s), and just one fails high on (alpha, beta),
1006       // then that move is singular and should be extended. To verify this we do
1007       // a reduced search on all the other moves but the ttMove and if the
1008       // result is lower than ttValue minus a margin then we will extend the ttMove.
1009       if (    depth >= 6
1010           &&  move == ttMove
1011           && !rootNode
1012           && !excludedMove // Avoid recursive singular search
1013        /* &&  ttValue != VALUE_NONE Already implicit in the next condition */
1014           &&  abs(ttValue) < VALUE_KNOWN_WIN
1015           && (tte->bound() & BOUND_LOWER)
1016           &&  tte->depth() >= depth - 3
1017           &&  pos.legal(move))
1018       {
1019           Value singularBeta = ttValue - 2 * depth;
1020           Depth halfDepth = depth / 2;
1021           ss->excludedMove = move;
1022           value = search<NonPV>(pos, ss, singularBeta - 1, singularBeta, halfDepth, cutNode);
1023           ss->excludedMove = MOVE_NONE;
1024
1025           if (value < singularBeta)
1026           {
1027               extension = 1;
1028               singularLMR = true;
1029           }
1030
1031           // Multi-cut pruning
1032           // Our ttMove is assumed to fail high, and now we failed high also on a reduced
1033           // search without the ttMove. So we assume this expected Cut-node is not singular,
1034           // that multiple moves fail high, and we can prune the whole subtree by returning
1035           // a soft bound.
1036           else if (   eval >= beta
1037                    && singularBeta >= beta)
1038               return singularBeta;
1039       }
1040
1041       // Check extension (~2 Elo)
1042       else if (    givesCheck
1043                && (pos.is_discovery_check_on_king(~us, move) || pos.see_ge(move)))
1044           extension = 1;
1045
1046       // Passed pawn extension
1047       else if (   move == ss->killers[0]
1048                && pos.advanced_pawn_push(move)
1049                && pos.pawn_passed(us, to_sq(move)))
1050           extension = 1;
1051
1052       // Last captures extension
1053       else if (   PvNode
1054                && PieceValue[EG][pos.captured_piece()] > PawnValueEg
1055                && pos.non_pawn_material() <= 2 * RookValueMg)
1056           extension = 1;
1057
1058       // Castling extension
1059       if (type_of(move) == CASTLING)
1060           extension = 1;
1061
1062       // Add extension to new depth
1063       newDepth += extension;
1064
1065       // Speculative prefetch as early as possible
1066       prefetch(TT.first_entry(pos.key_after(move)));
1067
1068       // Check for legality just before making the move
1069       if (!rootNode && !pos.legal(move))
1070       {
1071           ss->moveCount = --moveCount;
1072           continue;
1073       }
1074
1075       // Update the current move (this must be done after singular extension search)
1076       ss->currentMove = move;
1077       ss->continuationHistory = &thisThread->continuationHistory[inCheck]
1078                                                                 [captureOrPromotion]
1079                                                                 [movedPiece]
1080                                                                 [to_sq(move)];
1081
1082       // Step 15. Make the move
1083       pos.do_move(move, st, givesCheck);
1084
1085       // Step 16. Reduced depth search (LMR). If the move fails high it will be
1086       // re-searched at full depth.
1087       if (    depth >= 3
1088           &&  moveCount > 1 + 2 * rootNode
1089           && (!rootNode || thisThread->best_move_count(move) == 0)
1090           && (  !captureOrPromotion
1091               || moveCountPruning
1092               || ss->staticEval + PieceValue[EG][pos.captured_piece()] <= alpha
1093               || cutNode
1094               || thisThread->ttHitAverage < 384 * ttHitAverageResolution * ttHitAverageWindow / 1024))
1095       {
1096           Depth r = reduction(improving, depth, moveCount);
1097
1098           // Decrease reduction if the ttHit running average is large
1099           if (thisThread->ttHitAverage > 544 * ttHitAverageResolution * ttHitAverageWindow / 1024)
1100               r--;
1101
1102           // Reduction if other threads are searching this position.
1103           if (th.marked())
1104               r++;
1105
1106           // Decrease reduction if position is or has been on the PV
1107           if (ttPv)
1108               r -= 2;
1109
1110           // Decrease reduction if opponent's move count is high (~10 Elo)
1111           if ((ss-1)->moveCount > 15)
1112               r--;
1113
1114           // Decrease reduction if ttMove has been singularly extended
1115           if (singularLMR)
1116               r -= 2;
1117
1118           if (!captureOrPromotion)
1119           {
1120               // Increase reduction if ttMove is a capture (~0 Elo)
1121               if (ttCapture)
1122                   r++;
1123
1124               // Increase reduction for cut nodes (~5 Elo)
1125               if (cutNode)
1126                   r += 2;
1127
1128               // Decrease reduction for moves that escape a capture. Filter out
1129               // castling moves, because they are coded as "king captures rook" and
1130               // hence break make_move(). (~5 Elo)
1131               else if (    type_of(move) == NORMAL
1132                        && !pos.see_ge(reverse_move(move)))
1133                   r -= 2;
1134
1135               ss->statScore =  thisThread->mainHistory[us][from_to(move)]
1136                              + (*contHist[0])[movedPiece][to_sq(move)]
1137                              + (*contHist[1])[movedPiece][to_sq(move)]
1138                              + (*contHist[3])[movedPiece][to_sq(move)]
1139                              - 4729;
1140
1141               // Reset statScore to zero if negative and most stats shows >= 0
1142               if (    ss->statScore < 0
1143                   && (*contHist[0])[movedPiece][to_sq(move)] >= 0
1144                   && (*contHist[1])[movedPiece][to_sq(move)] >= 0
1145                   && thisThread->mainHistory[us][from_to(move)] >= 0)
1146                   ss->statScore = 0;
1147
1148               // Decrease/increase reduction by comparing opponent's stat score (~10 Elo)
1149               if (ss->statScore >= -99 && (ss-1)->statScore < -116)
1150                   r--;
1151
1152               else if ((ss-1)->statScore >= -117 && ss->statScore < -144)
1153                   r++;
1154
1155               // Decrease/increase reduction for moves with a good/bad history (~30 Elo)
1156               r -= ss->statScore / 16384;
1157           }
1158
1159           Depth d = clamp(newDepth - r, 1, newDepth);
1160
1161           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d, true);
1162
1163           doFullDepthSearch = (value > alpha && d != newDepth), didLMR = true;
1164       }
1165       else
1166           doFullDepthSearch = !PvNode || moveCount > 1, didLMR = false;
1167
1168       // Step 17. Full depth search when LMR is skipped or fails high
1169       if (doFullDepthSearch)
1170       {
1171           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth, !cutNode);
1172
1173           if (didLMR && !captureOrPromotion)
1174           {
1175               int bonus = value > alpha ?  stat_bonus(newDepth)
1176                                         : -stat_bonus(newDepth);
1177
1178               if (move == ss->killers[0])
1179                   bonus += bonus / 4;
1180
1181               update_continuation_histories(ss, movedPiece, to_sq(move), bonus);
1182           }
1183       }
1184
1185       // For PV nodes only, do a full PV search on the first move or after a fail
1186       // high (in the latter case search only if value < beta), otherwise let the
1187       // parent node fail low with value <= alpha and try another move.
1188       if (PvNode && (moveCount == 1 || (value > alpha && (rootNode || value < beta))))
1189       {
1190           (ss+1)->pv = pv;
1191           (ss+1)->pv[0] = MOVE_NONE;
1192
1193           value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, false);
1194       }
1195
1196       // Step 18. Undo move
1197       pos.undo_move(move);
1198
1199       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1200
1201       // Step 19. Check for a new best move
1202       // Finished searching the move. If a stop occurred, the return value of
1203       // the search cannot be trusted, and we return immediately without
1204       // updating best move, PV and TT.
1205       if (Threads.stop.load(std::memory_order_relaxed))
1206           return VALUE_ZERO;
1207
1208       if (rootNode)
1209       {
1210           RootMove& rm = *std::find(thisThread->rootMoves.begin(),
1211                                     thisThread->rootMoves.end(), move);
1212
1213           // PV move or new best move?
1214           if (moveCount == 1 || value > alpha)
1215           {
1216               rm.score = value;
1217               rm.selDepth = thisThread->selDepth;
1218               rm.pv.resize(1);
1219
1220               assert((ss+1)->pv);
1221
1222               for (Move* m = (ss+1)->pv; *m != MOVE_NONE; ++m)
1223                   rm.pv.push_back(*m);
1224
1225               // We record how often the best move has been changed in each
1226               // iteration. This information is used for time management: When
1227               // the best move changes frequently, we allocate some more time.
1228               if (moveCount > 1)
1229                   ++thisThread->bestMoveChanges;
1230           }
1231           else
1232               // All other moves but the PV are set to the lowest value: this
1233               // is not a problem when sorting because the sort is stable and the
1234               // move position in the list is preserved - just the PV is pushed up.
1235               rm.score = -VALUE_INFINITE;
1236       }
1237
1238       if (value > bestValue)
1239       {
1240           bestValue = value;
1241
1242           if (value > alpha)
1243           {
1244               bestMove = move;
1245
1246               if (PvNode && !rootNode) // Update pv even in fail-high case
1247                   update_pv(ss->pv, move, (ss+1)->pv);
1248
1249               if (PvNode && value < beta) // Update alpha! Always alpha < beta
1250                   alpha = value;
1251               else
1252               {
1253                   assert(value >= beta); // Fail high
1254                   ss->statScore = 0;
1255                   break;
1256               }
1257           }
1258       }
1259
1260       if (move != bestMove)
1261       {
1262           if (captureOrPromotion && captureCount < 32)
1263               capturesSearched[captureCount++] = move;
1264
1265           else if (!captureOrPromotion && quietCount < 64)
1266               quietsSearched[quietCount++] = move;
1267       }
1268     }
1269
1270     // The following condition would detect a stop only after move loop has been
1271     // completed. But in this case bestValue is valid because we have fully
1272     // searched our subtree, and we can anyhow save the result in TT.
1273     /*
1274        if (Threads.stop)
1275         return VALUE_DRAW;
1276     */
1277
1278     // Step 20. Check for mate and stalemate
1279     // All legal moves have been searched and if there are no legal moves, it
1280     // must be a mate or a stalemate. If we are in a singular extension search then
1281     // return a fail low score.
1282
1283     assert(moveCount || !inCheck || excludedMove || !MoveList<LEGAL>(pos).size());
1284
1285     if (!moveCount)
1286         bestValue = excludedMove ? alpha
1287                    :     inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1288
1289     else if (bestMove)
1290         update_all_stats(pos, ss, bestMove, bestValue, beta, prevSq,
1291                          quietsSearched, quietCount, capturesSearched, captureCount, depth);
1292
1293     // Bonus for prior countermove that caused the fail low
1294     else if (   (depth >= 3 || PvNode)
1295              && !priorCapture)
1296         update_continuation_histories(ss-1, pos.piece_on(prevSq), prevSq, stat_bonus(depth));
1297
1298     if (PvNode)
1299         bestValue = std::min(bestValue, maxValue);
1300
1301     if (!excludedMove)
1302         tte->save(posKey, value_to_tt(bestValue, ss->ply), ttPv,
1303                   bestValue >= beta ? BOUND_LOWER :
1304                   PvNode && bestMove ? BOUND_EXACT : BOUND_UPPER,
1305                   depth, bestMove, ss->staticEval);
1306
1307     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1308
1309     return bestValue;
1310   }
1311
1312
1313   // qsearch() is the quiescence search function, which is called by the main search
1314   // function with zero depth, or recursively with further decreasing depth per call.
1315   template <NodeType NT>
1316   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1317
1318     constexpr bool PvNode = NT == PV;
1319
1320     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1321     assert(PvNode || (alpha == beta - 1));
1322     assert(depth <= 0);
1323
1324     Move pv[MAX_PLY+1];
1325     StateInfo st;
1326     TTEntry* tte;
1327     Key posKey;
1328     Move ttMove, move, bestMove;
1329     Depth ttDepth;
1330     Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
1331     bool ttHit, pvHit, inCheck, givesCheck, captureOrPromotion, evasionPrunable;
1332     int moveCount;
1333
1334     if (PvNode)
1335     {
1336         oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
1337         (ss+1)->pv = pv;
1338         ss->pv[0] = MOVE_NONE;
1339     }
1340
1341     Thread* thisThread = pos.this_thread();
1342     (ss+1)->ply = ss->ply + 1;
1343     bestMove = MOVE_NONE;
1344     inCheck = pos.checkers();
1345     moveCount = 0;
1346
1347     // Check for an immediate draw or maximum ply reached
1348     if (   pos.is_draw(ss->ply)
1349         || ss->ply >= MAX_PLY)
1350         return (ss->ply >= MAX_PLY && !inCheck) ? evaluate(pos) : VALUE_DRAW;
1351
1352     assert(0 <= ss->ply && ss->ply < MAX_PLY);
1353
1354     // Decide whether or not to include checks: this fixes also the type of
1355     // TT entry depth that we are going to use. Note that in qsearch we use
1356     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1357     ttDepth = inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
1358                                                   : DEPTH_QS_NO_CHECKS;
1359     // Transposition table lookup
1360     posKey = pos.key();
1361     tte = TT.probe(posKey, ttHit);
1362     ttValue = ttHit ? value_from_tt(tte->value(), ss->ply, pos.rule50_count()) : VALUE_NONE;
1363     ttMove = ttHit ? tte->move() : MOVE_NONE;
1364     pvHit = ttHit && tte->is_pv();
1365
1366     if (  !PvNode
1367         && ttHit
1368         && tte->depth() >= ttDepth
1369         && ttValue != VALUE_NONE // Only in case of TT access race
1370         && (ttValue >= beta ? (tte->bound() & BOUND_LOWER)
1371                             : (tte->bound() & BOUND_UPPER)))
1372         return ttValue;
1373
1374     // Evaluate the position statically
1375     if (inCheck)
1376     {
1377         ss->staticEval = VALUE_NONE;
1378         bestValue = futilityBase = -VALUE_INFINITE;
1379     }
1380     else
1381     {
1382         if (ttHit)
1383         {
1384             // Never assume anything about values stored in TT
1385             if ((ss->staticEval = bestValue = tte->eval()) == VALUE_NONE)
1386                 ss->staticEval = bestValue = evaluate(pos);
1387
1388             // Can ttValue be used as a better position evaluation?
1389             if (    ttValue != VALUE_NONE
1390                 && (tte->bound() & (ttValue > bestValue ? BOUND_LOWER : BOUND_UPPER)))
1391                 bestValue = ttValue;
1392         }
1393         else
1394             ss->staticEval = bestValue =
1395             (ss-1)->currentMove != MOVE_NULL ? evaluate(pos)
1396                                              : -(ss-1)->staticEval + 2 * Eval::Tempo;
1397
1398         // Stand pat. Return immediately if static value is at least beta
1399         if (bestValue >= beta)
1400         {
1401             if (!ttHit)
1402                 tte->save(posKey, value_to_tt(bestValue, ss->ply), pvHit, BOUND_LOWER,
1403                           DEPTH_NONE, MOVE_NONE, ss->staticEval);
1404
1405             return bestValue;
1406         }
1407
1408         if (PvNode && bestValue > alpha)
1409             alpha = bestValue;
1410
1411         futilityBase = bestValue + 153;
1412     }
1413
1414     const PieceToHistory* contHist[] = { (ss-1)->continuationHistory, (ss-2)->continuationHistory,
1415                                           nullptr                   , (ss-4)->continuationHistory,
1416                                           nullptr                   , (ss-6)->continuationHistory };
1417
1418     // Initialize a MovePicker object for the current position, and prepare
1419     // to search the moves. Because the depth is <= 0 here, only captures,
1420     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1421     // be generated.
1422     MovePicker mp(pos, ttMove, depth, &thisThread->mainHistory,
1423                                       &thisThread->captureHistory,
1424                                       contHist,
1425                                       to_sq((ss-1)->currentMove));
1426
1427     // Loop through the moves until no moves remain or a beta cutoff occurs
1428     while ((move = mp.next_move()) != MOVE_NONE)
1429     {
1430       assert(is_ok(move));
1431
1432       givesCheck = pos.gives_check(move);
1433       captureOrPromotion = pos.capture_or_promotion(move);
1434
1435       moveCount++;
1436
1437       // Futility pruning
1438       if (   !inCheck
1439           && !givesCheck
1440           &&  futilityBase > -VALUE_KNOWN_WIN
1441           && !pos.advanced_pawn_push(move))
1442       {
1443           assert(type_of(move) != ENPASSANT); // Due to !pos.advanced_pawn_push
1444
1445           futilityValue = futilityBase + PieceValue[EG][pos.piece_on(to_sq(move))];
1446
1447           if (futilityValue <= alpha)
1448           {
1449               bestValue = std::max(bestValue, futilityValue);
1450               continue;
1451           }
1452
1453           if (futilityBase <= alpha && !pos.see_ge(move, VALUE_ZERO + 1))
1454           {
1455               bestValue = std::max(bestValue, futilityBase);
1456               continue;
1457           }
1458       }
1459
1460       // Detect non-capture evasions that are candidates to be pruned
1461       evasionPrunable =    inCheck
1462                        &&  (depth != 0 || moveCount > 2)
1463                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1464                        && !pos.capture(move);
1465
1466       // Don't search moves with negative SEE values
1467       if (  (!inCheck || evasionPrunable)
1468           && !(givesCheck && pos.is_discovery_check_on_king(~pos.side_to_move(), move))
1469           && !pos.see_ge(move))
1470           continue;
1471
1472       // Speculative prefetch as early as possible
1473       prefetch(TT.first_entry(pos.key_after(move)));
1474
1475       // Check for legality just before making the move
1476       if (!pos.legal(move))
1477       {
1478           moveCount--;
1479           continue;
1480       }
1481
1482       ss->currentMove = move;
1483       ss->continuationHistory = &thisThread->continuationHistory[inCheck]
1484                                                                 [captureOrPromotion]
1485                                                                 [pos.moved_piece(move)]
1486                                                                 [to_sq(move)];
1487
1488       // Make and search the move
1489       pos.do_move(move, st, givesCheck);
1490       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth - 1);
1491       pos.undo_move(move);
1492
1493       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1494
1495       // Check for a new best move
1496       if (value > bestValue)
1497       {
1498           bestValue = value;
1499
1500           if (value > alpha)
1501           {
1502               bestMove = move;
1503
1504               if (PvNode) // Update pv even in fail-high case
1505                   update_pv(ss->pv, move, (ss+1)->pv);
1506
1507               if (PvNode && value < beta) // Update alpha here!
1508                   alpha = value;
1509               else
1510                   break; // Fail high
1511           }
1512        }
1513     }
1514
1515     // All legal moves have been searched. A special case: If we're in check
1516     // and no legal moves were found, it is checkmate.
1517     if (inCheck && bestValue == -VALUE_INFINITE)
1518         return mated_in(ss->ply); // Plies to mate from the root
1519
1520     tte->save(posKey, value_to_tt(bestValue, ss->ply), pvHit,
1521               bestValue >= beta ? BOUND_LOWER :
1522               PvNode && bestValue > oldAlpha  ? BOUND_EXACT : BOUND_UPPER,
1523               ttDepth, bestMove, ss->staticEval);
1524
1525     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1526
1527     return bestValue;
1528   }
1529
1530
1531   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1532   // "plies to mate from the current position". Non-mate scores are unchanged.
1533   // The function is called before storing a value in the transposition table.
1534
1535   Value value_to_tt(Value v, int ply) {
1536
1537     assert(v != VALUE_NONE);
1538
1539     return  v >= VALUE_MATE_IN_MAX_PLY  ? v + ply
1540           : v <= VALUE_MATED_IN_MAX_PLY ? v - ply : v;
1541   }
1542
1543
1544   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1545   // from the transposition table (which refers to the plies to mate/be mated
1546   // from current position) to "plies to mate/be mated from the root".
1547
1548   Value value_from_tt(Value v, int ply, int r50c) {
1549
1550     return  v == VALUE_NONE             ? VALUE_NONE
1551           : v >= VALUE_MATE_IN_MAX_PLY  ? VALUE_MATE - v > 99 - r50c ? VALUE_MATE_IN_MAX_PLY  : v - ply
1552           : v <= VALUE_MATED_IN_MAX_PLY ? VALUE_MATE + v > 99 - r50c ? VALUE_MATED_IN_MAX_PLY : v + ply : v;
1553   }
1554
1555
1556   // update_pv() adds current move and appends child pv[]
1557
1558   void update_pv(Move* pv, Move move, Move* childPv) {
1559
1560     for (*pv++ = move; childPv && *childPv != MOVE_NONE; )
1561         *pv++ = *childPv++;
1562     *pv = MOVE_NONE;
1563   }
1564
1565
1566   // update_all_stats() updates stats at the end of search() when a bestMove is found
1567
1568   void update_all_stats(const Position& pos, Stack* ss, Move bestMove, Value bestValue, Value beta, Square prevSq,
1569                         Move* quietsSearched, int quietCount, Move* capturesSearched, int captureCount, Depth depth) {
1570
1571     int bonus1, bonus2;
1572     Color us = pos.side_to_move();
1573     Thread* thisThread = pos.this_thread();
1574     CapturePieceToHistory& captureHistory = thisThread->captureHistory;
1575     Piece moved_piece = pos.moved_piece(bestMove);
1576     PieceType captured = type_of(pos.piece_on(to_sq(bestMove)));
1577
1578     bonus1 = stat_bonus(depth + 1);
1579     bonus2 = bestValue > beta + PawnValueMg ? bonus1               // larger bonus
1580                                             : stat_bonus(depth);   // smaller bonus
1581
1582     if (!pos.capture_or_promotion(bestMove))
1583     {
1584         update_quiet_stats(pos, ss, bestMove, bonus2);
1585
1586         // Decrease all the non-best quiet moves
1587         for (int i = 0; i < quietCount; ++i)
1588         {
1589             thisThread->mainHistory[us][from_to(quietsSearched[i])] << -bonus2;
1590             update_continuation_histories(ss, pos.moved_piece(quietsSearched[i]), to_sq(quietsSearched[i]), -bonus2);
1591         }
1592     }
1593     else
1594         captureHistory[moved_piece][to_sq(bestMove)][captured] << bonus1;
1595
1596     // Extra penalty for a quiet TT or main killer move in previous ply when it gets refuted
1597     if (   ((ss-1)->moveCount == 1 || ((ss-1)->currentMove == (ss-1)->killers[0]))
1598         && !pos.captured_piece())
1599             update_continuation_histories(ss-1, pos.piece_on(prevSq), prevSq, -bonus1);
1600
1601     // Decrease all the non-best capture moves
1602     for (int i = 0; i < captureCount; ++i)
1603     {
1604         moved_piece = pos.moved_piece(capturesSearched[i]);
1605         captured = type_of(pos.piece_on(to_sq(capturesSearched[i])));
1606         captureHistory[moved_piece][to_sq(capturesSearched[i])][captured] << -bonus1;
1607     }
1608   }
1609
1610
1611   // update_continuation_histories() updates histories of the move pairs formed
1612   // by moves at ply -1, -2, and -4 with current move.
1613
1614   void update_continuation_histories(Stack* ss, Piece pc, Square to, int bonus) {
1615
1616     for (int i : {1, 2, 4, 6})
1617         if (is_ok((ss-i)->currentMove))
1618             (*(ss-i)->continuationHistory)[pc][to] << bonus;
1619   }
1620
1621
1622   // update_quiet_stats() updates move sorting heuristics
1623
1624   void update_quiet_stats(const Position& pos, Stack* ss, Move move, int bonus) {
1625
1626     if (ss->killers[0] != move)
1627     {
1628         ss->killers[1] = ss->killers[0];
1629         ss->killers[0] = move;
1630     }
1631
1632     Color us = pos.side_to_move();
1633     Thread* thisThread = pos.this_thread();
1634     thisThread->mainHistory[us][from_to(move)] << bonus;
1635     update_continuation_histories(ss, pos.moved_piece(move), to_sq(move), bonus);
1636
1637     if (type_of(pos.moved_piece(move)) != PAWN)
1638         thisThread->mainHistory[us][from_to(reverse_move(move))] << -bonus;
1639
1640     if (is_ok((ss-1)->currentMove))
1641     {
1642         Square prevSq = to_sq((ss-1)->currentMove);
1643         thisThread->counterMoves[pos.piece_on(prevSq)][prevSq] = move;
1644     }
1645   }
1646
1647   // When playing with strength handicap, choose best move among a set of RootMoves
1648   // using a statistical rule dependent on 'level'. Idea by Heinz van Saanen.
1649
1650   Move Skill::pick_best(size_t multiPV) {
1651
1652     const RootMoves& rootMoves = Threads.main()->rootMoves;
1653     static PRNG rng(now()); // PRNG sequence should be non-deterministic
1654
1655     // RootMoves are already sorted by score in descending order
1656     Value topScore = rootMoves[0].score;
1657     int delta = std::min(topScore - rootMoves[multiPV - 1].score, PawnValueMg);
1658     int weakness = 120 - 2 * level;
1659     int maxScore = -VALUE_INFINITE;
1660
1661     // Choose best move. For each move score we add two terms, both dependent on
1662     // weakness. One is deterministic and bigger for weaker levels, and one is
1663     // random. Then we choose the move with the resulting highest score.
1664     for (size_t i = 0; i < multiPV; ++i)
1665     {
1666         // This is our magic formula
1667         int push = (  weakness * int(topScore - rootMoves[i].score)
1668                     + delta * (rng.rand<unsigned>() % weakness)) / 128;
1669
1670         if (rootMoves[i].score + push >= maxScore)
1671         {
1672             maxScore = rootMoves[i].score + push;
1673             best = rootMoves[i].pv[0];
1674         }
1675     }
1676
1677     return best;
1678   }
1679
1680 } // namespace
1681
1682 /// MainThread::check_time() is used to print debug info and, more importantly,
1683 /// to detect when we are out of available time and thus stop the search.
1684
1685 void MainThread::check_time() {
1686
1687   if (--callsCnt > 0)
1688       return;
1689
1690   // When using nodes, ensure checking rate is not lower than 0.1% of nodes
1691   callsCnt = Limits.nodes ? std::min(1024, int(Limits.nodes / 1024)) : 1024;
1692
1693   static TimePoint lastInfoTime = now();
1694
1695   TimePoint elapsed = Time.elapsed();
1696   TimePoint tick = Limits.startTime + elapsed;
1697
1698   if (tick - lastInfoTime >= 1000)
1699   {
1700       lastInfoTime = tick;
1701       dbg_print();
1702   }
1703
1704   // We should not stop pondering until told so by the GUI
1705   if (ponder)
1706       return;
1707
1708   if (   (Limits.use_time_management() && (elapsed > Time.maximum() - 10 || stopOnPonderhit))
1709       || (Limits.movetime && elapsed >= Limits.movetime)
1710       || (Limits.nodes && Threads.nodes_searched() >= (uint64_t)Limits.nodes))
1711       Threads.stop = true;
1712 }
1713
1714
1715 /// UCI::pv() formats PV information according to the UCI protocol. UCI requires
1716 /// that all (if any) unsearched PV lines are sent using a previous search score.
1717
1718 string UCI::pv(const Position& pos, Depth depth, Value alpha, Value beta) {
1719
1720   std::stringstream ss;
1721   TimePoint elapsed = Time.elapsed() + 1;
1722   const RootMoves& rootMoves = pos.this_thread()->rootMoves;
1723   size_t pvIdx = pos.this_thread()->pvIdx;
1724   size_t multiPV = std::min((size_t)Options["MultiPV"], rootMoves.size());
1725   uint64_t nodesSearched = Threads.nodes_searched();
1726   uint64_t tbHits = Threads.tb_hits() + (TB::RootInTB ? rootMoves.size() : 0);
1727
1728   for (size_t i = 0; i < multiPV; ++i)
1729   {
1730       bool updated = (i <= pvIdx && rootMoves[i].score != -VALUE_INFINITE);
1731
1732       if (depth == 1 && !updated)
1733           continue;
1734
1735       Depth d = updated ? depth : depth - 1;
1736       Value v = updated ? rootMoves[i].score : rootMoves[i].previousScore;
1737
1738       bool tb = TB::RootInTB && abs(v) < VALUE_MATE - MAX_PLY;
1739       v = tb ? rootMoves[i].tbScore : v;
1740
1741       if (ss.rdbuf()->in_avail()) // Not at first line
1742           ss << "\n";
1743
1744       ss << "info"
1745          << " depth "    << d
1746          << " seldepth " << rootMoves[i].selDepth
1747          << " multipv "  << i + 1
1748          << " score "    << UCI::value(v);
1749
1750       if (!tb && i == pvIdx)
1751           ss << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1752
1753       ss << " nodes "    << nodesSearched
1754          << " nps "      << nodesSearched * 1000 / elapsed;
1755
1756       if (elapsed > 1000) // Earlier makes little sense
1757           ss << " hashfull " << TT.hashfull();
1758
1759       ss << " tbhits "   << tbHits
1760          << " time "     << elapsed
1761          << " pv";
1762
1763       for (Move m : rootMoves[i].pv)
1764           ss << " " << UCI::move(m, pos.is_chess960());
1765   }
1766
1767   return ss.str();
1768 }
1769
1770
1771 /// RootMove::extract_ponder_from_tt() is called in case we have no ponder move
1772 /// before exiting the search, for instance, in case we stop the search during a
1773 /// fail high at root. We try hard to have a ponder move to return to the GUI,
1774 /// otherwise in case of 'ponder on' we have nothing to think on.
1775
1776 bool RootMove::extract_ponder_from_tt(Position& pos) {
1777
1778     StateInfo st;
1779     bool ttHit;
1780
1781     assert(pv.size() == 1);
1782
1783     if (pv[0] == MOVE_NONE)
1784         return false;
1785
1786     pos.do_move(pv[0], st);
1787     TTEntry* tte = TT.probe(pos.key(), ttHit);
1788
1789     if (ttHit)
1790     {
1791         Move m = tte->move(); // Local copy to be SMP safe
1792         if (MoveList<LEGAL>(pos).contains(m))
1793             pv.push_back(m);
1794     }
1795
1796     pos.undo_move(pv[0]);
1797     return pv.size() > 1;
1798 }
1799
1800 void Tablebases::rank_root_moves(Position& pos, Search::RootMoves& rootMoves) {
1801
1802     RootInTB = false;
1803     UseRule50 = bool(Options["Syzygy50MoveRule"]);
1804     ProbeDepth = int(Options["SyzygyProbeDepth"]);
1805     Cardinality = int(Options["SyzygyProbeLimit"]);
1806     bool dtz_available = true;
1807
1808     // Tables with fewer pieces than SyzygyProbeLimit are searched with
1809     // ProbeDepth == DEPTH_ZERO
1810     if (Cardinality > MaxCardinality)
1811     {
1812         Cardinality = MaxCardinality;
1813         ProbeDepth = 0;
1814     }
1815
1816     if (Cardinality >= popcount(pos.pieces()) && !pos.can_castle(ANY_CASTLING))
1817     {
1818         // Rank moves using DTZ tables
1819         RootInTB = root_probe(pos, rootMoves);
1820
1821         if (!RootInTB)
1822         {
1823             // DTZ tables are missing; try to rank moves using WDL tables
1824             dtz_available = false;
1825             RootInTB = root_probe_wdl(pos, rootMoves);
1826         }
1827     }
1828
1829     if (RootInTB)
1830     {
1831         // Sort moves according to TB rank
1832         std::sort(rootMoves.begin(), rootMoves.end(),
1833                   [](const RootMove &a, const RootMove &b) { return a.tbRank > b.tbRank; } );
1834
1835         // Probe during search only if DTZ is not available and we are winning
1836         if (dtz_available || rootMoves[0].tbScore <= VALUE_DRAW)
1837             Cardinality = 0;
1838     }
1839     else
1840     {
1841         // Clean up if root_probe() and root_probe_wdl() have failed
1842         for (auto& m : rootMoves)
1843             m.tbRank = 0;
1844     }
1845 }