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