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