2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2014 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
36 #include "syzygy/tbprobe.h"
40 volatile SignalsType Signals;
42 std::vector<RootMove> RootMoves;
44 Time::point SearchTime;
45 StateStackPtr SetupStates;
56 using namespace Search;
60 // Different node types, used as template parameter
61 enum NodeType { Root, PV, NonPV };
63 // Dynamic razoring margin based on depth
64 inline Value razor_margin(Depth d) { return Value(512 + 32 * d); }
66 // Futility lookup tables (initialized at startup) and their access functions
67 int FutilityMoveCounts[2][16]; // [improving][depth]
69 inline Value futility_margin(Depth d) {
70 return Value(200 * d);
73 // Reduction lookup tables (initialized at startup) and their access function
74 int8_t Reductions[2][2][64][64]; // [pv][improving][depth][moveNumber]
76 template <bool PvNode> inline Depth reduction(bool i, Depth d, int mn) {
77 return (Depth) Reductions[PvNode][i][std::min(int(d), 63)][std::min(mn, 63)];
82 double BestMoveChanges;
83 Value DrawValue[COLOR_NB];
86 MovesStats Countermoves, Followupmoves;
88 template <NodeType NT, bool SpNode>
89 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode);
91 template <NodeType NT, bool InCheck>
92 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
94 void id_loop(Position& pos);
95 Value value_to_tt(Value v, int ply);
96 Value value_from_tt(Value v, int ply);
97 void update_pv(Move* pv, Move move, Move* childPv);
98 void update_stats(const Position& pos, Stack* ss, Move move, Depth depth, Move* quiets, int quietsCnt);
99 string uci_pv(const Position& pos, Depth depth, Value alpha, Value beta);
102 Skill(int l, size_t rootSize) : level(l),
103 candidates(l < 20 ? std::min(4, (int)rootSize) : 0),
106 if (candidates) // Swap best PV line with the sub-optimal one
107 std::swap(RootMoves[0], *std::find(RootMoves.begin(),
108 RootMoves.end(), best ? best : pick_move()));
111 size_t candidates_size() const { return candidates; }
112 bool time_to_pick(Depth depth) const { return depth / ONE_PLY == 1 + level; }
123 /// Search::init() is called during startup to initialize various lookup tables
125 void Search::init() {
127 // Init reductions array
128 for (int d = 1; d < 64; ++d)
129 for (int mc = 1; mc < 64; ++mc)
131 double pvRed = 0.00 + log(double(d)) * log(double(mc)) / 3.00;
132 double nonPVRed = 0.33 + log(double(d)) * log(double(mc)) / 2.25;
134 Reductions[1][1][d][mc] = int8_t( pvRed >= 1.0 ? pvRed + 0.5: 0);
135 Reductions[0][1][d][mc] = int8_t(nonPVRed >= 1.0 ? nonPVRed + 0.5: 0);
137 Reductions[1][0][d][mc] = Reductions[1][1][d][mc];
138 Reductions[0][0][d][mc] = Reductions[0][1][d][mc];
140 // Increase reduction when eval is not improving
141 if (Reductions[0][0][d][mc] >= 2)
142 Reductions[0][0][d][mc] += 1;
145 // Init futility move count array
146 for (int d = 0; d < 16; ++d)
148 FutilityMoveCounts[0][d] = int(2.4 + 0.773 * pow(d + 0.00, 1.8));
149 FutilityMoveCounts[1][d] = int(2.9 + 1.045 * pow(d + 0.49, 1.8));
154 /// Search::perft() is our utility to verify move generation. All the leaf nodes
155 /// up to the given depth are generated and counted and the sum returned.
157 uint64_t Search::perft(Position& pos, Depth depth) {
160 uint64_t cnt, nodes = 0;
162 const bool leaf = (depth == 2 * ONE_PLY);
164 for (MoveList<LEGAL> it(pos); *it; ++it)
166 if (Root && depth <= ONE_PLY)
170 pos.do_move(*it, st, ci, pos.gives_check(*it, ci));
171 cnt = leaf ? MoveList<LEGAL>(pos).size() : perft<false>(pos, depth - ONE_PLY);
176 sync_cout << UCI::format_move(*it, pos.is_chess960()) << ": " << cnt << sync_endl;
181 template uint64_t Search::perft<true>(Position& pos, Depth depth);
184 /// Search::think() is the external interface to Stockfish's search, and is
185 /// called by the main thread when the program receives the UCI 'go' command. It
186 /// searches from RootPos and at the end prints the "bestmove" to output.
188 void Search::think() {
190 TimeMgr.init(Limits, RootPos.game_ply(), RootPos.side_to_move());
192 int cf = Options["Contempt"] * PawnValueEg / 100; // From centipawns
193 DrawValue[ RootPos.side_to_move()] = VALUE_DRAW - Value(cf);
194 DrawValue[~RootPos.side_to_move()] = VALUE_DRAW + Value(cf);
198 TBProbeDepth = Options["SyzygyProbeDepth"] * ONE_PLY;
199 TB50MoveRule = Options["Syzygy50MoveRule"];
200 TBCardinality = Options["SyzygyProbeLimit"];
202 // Skip TB probing when no TB found: !TBLargest -> !TBCardinality
203 if (TBCardinality > Tablebases::TBLargest)
205 TBCardinality = Tablebases::TBLargest;
206 TBProbeDepth = DEPTH_ZERO;
209 if (RootMoves.empty())
211 RootMoves.push_back(MOVE_NONE);
212 sync_cout << "info depth 0 score "
213 << UCI::format_value(RootPos.checkers() ? -VALUE_MATE : VALUE_DRAW)
218 if (TBCardinality >= RootPos.count<ALL_PIECES>(WHITE)
219 + RootPos.count<ALL_PIECES>(BLACK))
221 // If the current root position is in the tablebases then RootMoves
222 // contains only moves that preserve the draw or win.
223 RootInTB = Tablebases::root_probe(RootPos, TBScore);
226 TBCardinality = 0; // Do not probe tablebases during the search
228 else // If DTZ tables are missing, use WDL tables as a fallback
230 // Filter out moves that do not preserve a draw or win
231 RootInTB = Tablebases::root_probe_wdl(RootPos, TBScore);
233 // Only probe during search if winning
234 if (TBScore <= VALUE_DRAW)
240 TBHits = RootMoves.size();
243 TBScore = TBScore > VALUE_DRAW ? VALUE_MATE - MAX_PLY - 1
244 : TBScore < VALUE_DRAW ? -VALUE_MATE + MAX_PLY + 1
249 for (size_t i = 0; i < Threads.size(); ++i)
250 Threads[i]->maxPly = 0;
252 Threads.timer->run = true;
253 Threads.timer->notify_one(); // Wake up the recurring timer
255 id_loop(RootPos); // Let's start searching !
257 Threads.timer->run = false;
260 // When we reach the maximum depth, we can arrive here without a raise of
261 // Signals.stop. However, if we are pondering or in an infinite search,
262 // the UCI protocol states that we shouldn't print the best move before the
263 // GUI sends a "stop" or "ponderhit" command. We therefore simply wait here
264 // until the GUI sends one of those commands (which also raises Signals.stop).
265 if (!Signals.stop && (Limits.ponder || Limits.infinite))
267 Signals.stopOnPonderhit = true;
268 RootPos.this_thread()->wait_for(Signals.stop);
271 sync_cout << "bestmove " << UCI::format_move(RootMoves[0].pv[0], RootPos.is_chess960());
273 if (RootMoves[0].pv.size() > 1)
274 std::cout << " ponder " << UCI::format_move(RootMoves[0].pv[1], RootPos.is_chess960());
276 std::cout << sync_endl;
282 // id_loop() is the main iterative deepening loop. It calls search() repeatedly
283 // with increasing depth until the allocated thinking time has been consumed,
284 // user stops the search, or the maximum search depth is reached.
286 void id_loop(Position& pos) {
288 Stack stack[MAX_PLY+4], *ss = stack+2; // To allow referencing (ss-2) and (ss+2)
290 Value bestValue, alpha, beta, delta;
292 std::memset(ss-2, 0, 5 * sizeof(Stack));
296 bestValue = delta = alpha = -VALUE_INFINITE;
297 beta = VALUE_INFINITE;
302 Countermoves.clear();
303 Followupmoves.clear();
305 size_t multiPV = Options["MultiPV"];
306 Skill skill(Options["Skill Level"], RootMoves.size());
308 // Do we have to play with skill handicap? In this case enable MultiPV search
309 // that we will use behind the scenes to retrieve a set of possible moves.
310 multiPV = std::max(multiPV, skill.candidates_size());
312 // Iterative deepening loop until requested to stop or target depth reached
313 while (++depth < DEPTH_MAX && !Signals.stop && (!Limits.depth || depth <= Limits.depth))
315 // Age out PV variability metric
316 BestMoveChanges *= 0.5;
318 // Save the last iteration's scores before first PV line is searched and
319 // all the move scores except the (new) PV are set to -VALUE_INFINITE.
320 for (size_t i = 0; i < RootMoves.size(); ++i)
321 RootMoves[i].prevScore = RootMoves[i].score;
323 // MultiPV loop. We perform a full root search for each PV line
324 for (PVIdx = 0; PVIdx < std::min(multiPV, RootMoves.size()) && !Signals.stop; ++PVIdx)
326 // Reset aspiration window starting size
327 if (depth >= 5 * ONE_PLY)
330 alpha = std::max(RootMoves[PVIdx].prevScore - delta,-VALUE_INFINITE);
331 beta = std::min(RootMoves[PVIdx].prevScore + delta, VALUE_INFINITE);
334 // Start with a small aspiration window and, in the case of a fail
335 // high/low, re-search with a bigger window until we're not failing
339 bestValue = search<Root, false>(pos, ss, alpha, beta, depth, false);
341 // Bring the best move to the front. It is critical that sorting
342 // is done with a stable algorithm because all the values but the
343 // first and eventually the new best one are set to -VALUE_INFINITE
344 // and we want to keep the same order for all the moves except the
345 // new PV that goes to the front. Note that in case of MultiPV
346 // search the already searched PV lines are preserved.
347 std::stable_sort(RootMoves.begin() + PVIdx, RootMoves.end());
349 // Write PV back to transposition table in case the relevant
350 // entries have been overwritten during the search.
351 for (size_t i = 0; i <= PVIdx; ++i)
352 RootMoves[i].insert_pv_in_tt(pos);
354 // If search has been stopped break immediately. Sorting and
355 // writing PV back to TT is safe because RootMoves is still
356 // valid, although it refers to previous iteration.
360 // When failing high/low give some update (without cluttering
361 // the UI) before a re-search.
362 if ( (bestValue <= alpha || bestValue >= beta)
363 && Time::now() - SearchTime > 3000)
364 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
366 // In case of failing low/high increase aspiration window and
367 // re-search, otherwise exit the loop.
368 if (bestValue <= alpha)
370 beta = (alpha + beta) / 2;
371 alpha = std::max(bestValue - delta, -VALUE_INFINITE);
373 Signals.failedLowAtRoot = true;
374 Signals.stopOnPonderhit = false;
376 else if (bestValue >= beta)
378 alpha = (alpha + beta) / 2;
379 beta = std::min(bestValue + delta, VALUE_INFINITE);
386 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
389 // Sort the PV lines searched so far and update the GUI
390 std::stable_sort(RootMoves.begin(), RootMoves.begin() + PVIdx + 1);
393 sync_cout << "info nodes " << RootPos.nodes_searched()
394 << " time " << Time::now() - SearchTime << sync_endl;
396 else if ( PVIdx + 1 == std::min(multiPV, RootMoves.size())
397 || Time::now() - SearchTime > 3000)
398 sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
401 // If skill levels are enabled and time is up, pick a sub-optimal best move
402 if (skill.candidates_size() && skill.time_to_pick(depth))
405 // Have we found a "mate in x"?
407 && bestValue >= VALUE_MATE_IN_MAX_PLY
408 && VALUE_MATE - bestValue <= 2 * Limits.mate)
411 // Do we have time for the next iteration? Can we stop searching now?
412 if (Limits.use_time_management() && !Signals.stop && !Signals.stopOnPonderhit)
414 // Take some extra time if the best move has changed
415 if (depth > 4 * ONE_PLY && multiPV == 1)
416 TimeMgr.pv_instability(BestMoveChanges);
418 // Stop the search if only one legal move is available or all
419 // of the available time has been used.
420 if ( RootMoves.size() == 1
421 || Time::now() - SearchTime > TimeMgr.available_time())
423 // If we are allowed to ponder do not stop the search now but
424 // keep pondering until the GUI sends "ponderhit" or "stop".
426 Signals.stopOnPonderhit = true;
435 // search<>() is the main search function for both PV and non-PV nodes and for
436 // normal and SplitPoint nodes. When called just after a split point the search
437 // is simpler because we have already probed the hash table, done a null move
438 // search, and searched the first move before splitting, so we don't have to
439 // repeat all this work again. We also don't need to store anything to the hash
440 // table here: This is taken care of after we return from the split point.
442 template <NodeType NT, bool SpNode>
443 Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth, bool cutNode) {
445 const bool RootNode = NT == Root;
446 const bool PvNode = NT == PV || NT == Root;
448 assert(-VALUE_INFINITE <= alpha && alpha < beta && beta <= VALUE_INFINITE);
449 assert(PvNode || (alpha == beta - 1));
450 assert(depth > DEPTH_ZERO);
452 Move pv[MAX_PLY+1], quietsSearched[64];
455 SplitPoint* splitPoint;
457 Move ttMove, move, excludedMove, bestMove;
458 Depth ext, newDepth, predictedDepth;
459 Value bestValue, value, ttValue, eval, nullValue, futilityValue;
460 bool inCheck, givesCheck, singularExtensionNode, improving;
461 bool captureOrPromotion, dangerous, doFullDepthSearch;
462 int moveCount, quietCount;
464 // Step 1. Initialize node
465 Thread* thisThread = pos.this_thread();
466 inCheck = pos.checkers();
470 splitPoint = ss->splitPoint;
471 bestMove = splitPoint->bestMove;
472 bestValue = splitPoint->bestValue;
474 ttMove = excludedMove = MOVE_NONE;
475 ttValue = VALUE_NONE;
477 assert(splitPoint->bestValue > -VALUE_INFINITE && splitPoint->moveCount > 0);
482 moveCount = quietCount = 0;
483 bestValue = -VALUE_INFINITE;
484 ss->ply = (ss-1)->ply + 1;
486 // Used to send selDepth info to GUI
487 if (PvNode && thisThread->maxPly < ss->ply)
488 thisThread->maxPly = ss->ply;
492 // Step 2. Check for aborted search and immediate draw
493 if (Signals.stop || pos.is_draw() || ss->ply >= MAX_PLY)
494 return ss->ply >= MAX_PLY && !inCheck ? evaluate(pos) : DrawValue[pos.side_to_move()];
496 // Step 3. Mate distance pruning. Even if we mate at the next move our score
497 // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
498 // a shorter mate was found upward in the tree then there is no need to search
499 // because we will never beat the current alpha. Same logic but with reversed
500 // signs applies also in the opposite condition of being mated instead of giving
501 // mate. In this case return a fail-high score.
502 alpha = std::max(mated_in(ss->ply), alpha);
503 beta = std::min(mate_in(ss->ply+1), beta);
508 assert(0 <= ss->ply && ss->ply < MAX_PLY);
510 ss->currentMove = ss->ttMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
511 (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
512 (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
514 // Step 4. Transposition table lookup
515 // We don't want the score of a partial search to overwrite a previous full search
516 // TT value, so we use a different position key in case of an excluded move.
517 excludedMove = ss->excludedMove;
518 posKey = excludedMove ? pos.exclusion_key() : pos.key();
519 tte = TT.probe(posKey);
520 ss->ttMove = ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
521 ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
523 // At non-PV nodes we check for a fail high/low. We don't probe at PV nodes
526 && tte->depth() >= depth
527 && ttValue != VALUE_NONE // Only in case of TT access race
528 && (ttValue >= beta ? (tte->bound() & BOUND_LOWER)
529 : (tte->bound() & BOUND_UPPER)))
531 ss->currentMove = ttMove; // Can be MOVE_NONE
533 // If ttMove is quiet, update killers, history, counter move and followup move on TT hit
534 if (ttValue >= beta && ttMove && !pos.capture_or_promotion(ttMove) && !inCheck)
535 update_stats(pos, ss, ttMove, depth, NULL, 0);
540 // Step 4a. Tablebase probe
541 if (!RootNode && TBCardinality)
543 int piecesCnt = pos.count<ALL_PIECES>(WHITE) + pos.count<ALL_PIECES>(BLACK);
545 if ( piecesCnt <= TBCardinality
546 && (piecesCnt < TBCardinality || depth >= TBProbeDepth)
547 && pos.rule50_count() == 0)
549 int found, v = Tablebases::probe_wdl(pos, &found);
556 value = v < -1 ? -VALUE_MATE + MAX_PLY + ss->ply
557 : v > 1 ? VALUE_MATE - MAX_PLY - ss->ply
558 : VALUE_DRAW + 2 * v;
562 value = v < 0 ? -VALUE_MATE + MAX_PLY + ss->ply
563 : v > 0 ? VALUE_MATE - MAX_PLY - ss->ply
567 TT.store(posKey, value_to_tt(value, ss->ply), BOUND_EXACT,
568 std::min(DEPTH_MAX - ONE_PLY, depth + 6 * ONE_PLY), MOVE_NONE, VALUE_NONE);
575 // Step 5. Evaluate the position statically and update parent's gain statistics
578 ss->staticEval = eval = VALUE_NONE;
584 // Never assume anything on values stored in TT
585 if ((ss->staticEval = eval = tte->eval_value()) == VALUE_NONE)
586 eval = ss->staticEval = evaluate(pos);
588 // Can ttValue be used as a better position evaluation?
589 if (ttValue != VALUE_NONE)
590 if (tte->bound() & (ttValue > eval ? BOUND_LOWER : BOUND_UPPER))
595 eval = ss->staticEval =
596 (ss-1)->currentMove != MOVE_NULL ? evaluate(pos) : -(ss-1)->staticEval + 2 * Eval::Tempo;
598 TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->staticEval);
601 if ( !pos.captured_piece_type()
602 && ss->staticEval != VALUE_NONE
603 && (ss-1)->staticEval != VALUE_NONE
604 && (move = (ss-1)->currentMove) != MOVE_NULL
606 && type_of(move) == NORMAL)
608 Square to = to_sq(move);
609 Gains.update(pos.piece_on(to), to, -(ss-1)->staticEval - ss->staticEval);
612 // Step 6. Razoring (skipped when in check)
614 && depth < 4 * ONE_PLY
615 && eval + razor_margin(depth) <= alpha
616 && ttMove == MOVE_NONE
617 && !pos.pawn_on_7th(pos.side_to_move()))
619 if ( depth <= ONE_PLY
620 && eval + razor_margin(3 * ONE_PLY) <= alpha)
621 return qsearch<NonPV, false>(pos, ss, alpha, beta, DEPTH_ZERO);
623 Value ralpha = alpha - razor_margin(depth);
624 Value v = qsearch<NonPV, false>(pos, ss, ralpha, ralpha+1, DEPTH_ZERO);
629 // Step 7. Futility pruning: child node (skipped when in check)
632 && depth < 7 * ONE_PLY
633 && eval - futility_margin(depth) >= beta
634 && eval < VALUE_KNOWN_WIN // Do not return unproven wins
635 && pos.non_pawn_material(pos.side_to_move()))
636 return eval - futility_margin(depth);
638 // Step 8. Null move search with verification search (is omitted in PV nodes)
641 && depth >= 2 * ONE_PLY
643 && pos.non_pawn_material(pos.side_to_move()))
645 ss->currentMove = MOVE_NULL;
647 assert(eval - beta >= 0);
649 // Null move dynamic reduction based on depth and value
650 Depth R = (3 + depth / 4 + std::min((eval - beta) / PawnValueMg, 3)) * ONE_PLY;
652 pos.do_null_move(st);
653 (ss+1)->skipNullMove = true;
654 nullValue = depth-R < ONE_PLY ? -qsearch<NonPV, false>(pos, ss+1, -beta, -beta+1, DEPTH_ZERO)
655 : - search<NonPV, false>(pos, ss+1, -beta, -beta+1, depth-R, !cutNode);
656 (ss+1)->skipNullMove = false;
657 pos.undo_null_move();
659 if (nullValue >= beta)
661 // Do not return unproven mate scores
662 if (nullValue >= VALUE_MATE_IN_MAX_PLY)
665 if (depth < 12 * ONE_PLY && abs(beta) < VALUE_KNOWN_WIN)
668 // Do verification search at high depths
669 ss->skipNullMove = true;
670 Value v = depth-R < ONE_PLY ? qsearch<NonPV, false>(pos, ss, beta-1, beta, DEPTH_ZERO)
671 : search<NonPV, false>(pos, ss, beta-1, beta, depth-R, false);
672 ss->skipNullMove = false;
679 // Step 9. ProbCut (skipped when in check)
680 // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
681 // and a reduced search returns a value much above beta, we can (almost) safely
682 // prune the previous move.
684 && depth >= 5 * ONE_PLY
686 && abs(beta) < VALUE_MATE_IN_MAX_PLY)
688 Value rbeta = std::min(beta + 200, VALUE_INFINITE);
689 Depth rdepth = depth - 4 * ONE_PLY;
691 assert(rdepth >= ONE_PLY);
692 assert((ss-1)->currentMove != MOVE_NONE);
693 assert((ss-1)->currentMove != MOVE_NULL);
695 MovePicker mp(pos, ttMove, History, pos.captured_piece_type());
698 while ((move = mp.next_move<false>()) != MOVE_NONE)
699 if (pos.legal(move, ci.pinned))
701 ss->currentMove = move;
702 pos.do_move(move, st, ci, pos.gives_check(move, ci));
703 value = -search<NonPV, false>(pos, ss+1, -rbeta, -rbeta+1, rdepth, !cutNode);
710 // Step 10. Internal iterative deepening (skipped when in check)
711 if ( depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
713 && (PvNode || ss->staticEval + 256 >= beta))
715 Depth d = 2 * (depth - 2 * ONE_PLY) - (PvNode ? DEPTH_ZERO : depth / 2);
716 ss->skipNullMove = true;
717 search<PvNode ? PV : NonPV, false>(pos, ss, alpha, beta, d / 2, true);
718 ss->skipNullMove = false;
720 tte = TT.probe(posKey);
721 ttMove = tte ? tte->move() : MOVE_NONE;
724 moves_loop: // When in check and at SpNode search starts from here
726 Square prevMoveSq = to_sq((ss-1)->currentMove);
727 Move countermoves[] = { Countermoves[pos.piece_on(prevMoveSq)][prevMoveSq].first,
728 Countermoves[pos.piece_on(prevMoveSq)][prevMoveSq].second };
730 Square prevOwnMoveSq = to_sq((ss-2)->currentMove);
731 Move followupmoves[] = { Followupmoves[pos.piece_on(prevOwnMoveSq)][prevOwnMoveSq].first,
732 Followupmoves[pos.piece_on(prevOwnMoveSq)][prevOwnMoveSq].second };
734 MovePicker mp(pos, ttMove, depth, History, countermoves, followupmoves, ss);
736 value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
737 improving = ss->staticEval >= (ss-2)->staticEval
738 || ss->staticEval == VALUE_NONE
739 ||(ss-2)->staticEval == VALUE_NONE;
741 singularExtensionNode = !RootNode
743 && depth >= 8 * ONE_PLY
744 && ttMove != MOVE_NONE
745 /* && ttValue != VALUE_NONE Already implicit in the next condition */
746 && abs(ttValue) < VALUE_KNOWN_WIN
747 && !excludedMove // Recursive singular search is not allowed
748 && (tte->bound() & BOUND_LOWER)
749 && tte->depth() >= depth - 3 * ONE_PLY;
751 // Step 11. Loop through moves
752 // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
753 while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
757 if (move == excludedMove)
760 // At root obey the "searchmoves" option and skip moves not listed in Root
761 // Move List. As a consequence any illegal move is also skipped. In MultiPV
762 // mode we also skip PV moves which have been already searched.
763 if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
768 // Shared counter cannot be decremented later if the move turns out to be illegal
769 if (!pos.legal(move, ci.pinned))
772 moveCount = ++splitPoint->moveCount;
773 splitPoint->mutex.unlock();
780 Signals.firstRootMove = (moveCount == 1);
782 if (thisThread == Threads.main() && Time::now() - SearchTime > 3000)
783 sync_cout << "info depth " << depth / ONE_PLY
784 << " currmove " << UCI::format_move(move, pos.is_chess960())
785 << " currmovenumber " << moveCount + PVIdx << sync_endl;
792 captureOrPromotion = pos.capture_or_promotion(move);
794 givesCheck = type_of(move) == NORMAL && !ci.dcCandidates
795 ? ci.checkSq[type_of(pos.piece_on(from_sq(move)))] & to_sq(move)
796 : pos.gives_check(move, ci);
798 dangerous = givesCheck
799 || type_of(move) != NORMAL
800 || pos.advanced_pawn_push(move);
802 // Step 12. Extend checks
803 if (givesCheck && pos.see_sign(move) >= VALUE_ZERO)
806 // Singular extension search. If all moves but one fail low on a search of
807 // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
808 // is singular and should be extended. To verify this we do a reduced search
809 // on all the other moves but the ttMove and if the result is lower than
810 // ttValue minus a margin then we extend the ttMove.
811 if ( singularExtensionNode
814 && pos.legal(move, ci.pinned))
816 Value rBeta = ttValue - 2 * depth / ONE_PLY;
817 ss->excludedMove = move;
818 ss->skipNullMove = true;
819 value = search<NonPV, false>(pos, ss, rBeta - 1, rBeta, depth / 2, cutNode);
820 ss->skipNullMove = false;
821 ss->excludedMove = MOVE_NONE;
827 // Update the current move (this must be done after singular extension search)
828 newDepth = depth - ONE_PLY + ext;
830 // Step 13. Pruning at shallow depth (exclude PV nodes)
832 && !captureOrPromotion
835 && bestValue > VALUE_MATED_IN_MAX_PLY)
837 // Move count based pruning
838 if ( depth < 16 * ONE_PLY
839 && moveCount >= FutilityMoveCounts[improving][depth])
842 splitPoint->mutex.lock();
847 predictedDepth = newDepth - reduction<PvNode>(improving, depth, moveCount);
849 // Futility pruning: parent node
850 if (predictedDepth < 7 * ONE_PLY)
852 futilityValue = ss->staticEval + futility_margin(predictedDepth)
853 + 128 + Gains[pos.moved_piece(move)][to_sq(move)];
855 if (futilityValue <= alpha)
857 bestValue = std::max(bestValue, futilityValue);
861 splitPoint->mutex.lock();
862 if (bestValue > splitPoint->bestValue)
863 splitPoint->bestValue = bestValue;
869 // Prune moves with negative SEE at low depths
870 if (predictedDepth < 4 * ONE_PLY && pos.see_sign(move) < VALUE_ZERO)
873 splitPoint->mutex.lock();
879 // Speculative prefetch as early as possible
880 prefetch((char*)TT.first_entry(pos.key_after(move)));
882 // Check for legality just before making the move
883 if (!RootNode && !SpNode && !pos.legal(move, ci.pinned))
889 ss->currentMove = move;
890 if (!SpNode && !captureOrPromotion && quietCount < 64)
891 quietsSearched[quietCount++] = move;
893 // Step 14. Make the move
894 pos.do_move(move, st, ci, givesCheck);
896 // Step 15. Reduced depth search (LMR). If the move fails high it will be
897 // re-searched at full depth.
898 if ( depth >= 3 * ONE_PLY
900 && !captureOrPromotion
901 && move != ss->killers[0]
902 && move != ss->killers[1])
904 ss->reduction = reduction<PvNode>(improving, depth, moveCount);
906 if ( (!PvNode && cutNode)
907 || History[pos.piece_on(to_sq(move))][to_sq(move)] < 0)
908 ss->reduction += ONE_PLY;
910 if (move == countermoves[0] || move == countermoves[1])
911 ss->reduction = std::max(DEPTH_ZERO, ss->reduction - ONE_PLY);
913 // Decrease reduction for moves that escape a capture
915 && type_of(move) == NORMAL
916 && type_of(pos.piece_on(to_sq(move))) != PAWN
917 && pos.see(make_move(to_sq(move), from_sq(move))) < 0)
918 ss->reduction = std::max(DEPTH_ZERO, ss->reduction - ONE_PLY);
920 Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
922 alpha = splitPoint->alpha;
924 value = -search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, d, true);
926 // Re-search at intermediate depth if reduction is very high
927 if (value > alpha && ss->reduction >= 4 * ONE_PLY)
929 Depth d2 = std::max(newDepth - 2 * ONE_PLY, ONE_PLY);
930 value = -search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, d2, true);
933 doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
934 ss->reduction = DEPTH_ZERO;
937 doFullDepthSearch = !PvNode || moveCount > 1;
939 // Step 16. Full depth search, when LMR is skipped or fails high
940 if (doFullDepthSearch)
943 alpha = splitPoint->alpha;
945 value = newDepth < ONE_PLY ?
946 givesCheck ? -qsearch<NonPV, true>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
947 : -qsearch<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
948 : - search<NonPV, false>(pos, ss+1, -(alpha+1), -alpha, newDepth, !cutNode);
951 // For PV nodes only, do a full PV search on the first move or after a fail
952 // high (in the latter case search only if value < beta), otherwise let the
953 // parent node fail low with value <= alpha and to try another move.
954 if (PvNode && (moveCount == 1 || (value > alpha && (RootNode || value < beta))))
957 (ss+1)->pv[0] = MOVE_NONE;
959 value = newDepth < ONE_PLY ?
960 givesCheck ? -qsearch<PV, true>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
961 : -qsearch<PV, false>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
962 : - search<PV, false>(pos, ss+1, -beta, -alpha, newDepth, false);
965 // Step 17. Undo move
968 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
970 // Step 18. Check for new best move
973 splitPoint->mutex.lock();
974 bestValue = splitPoint->bestValue;
975 alpha = splitPoint->alpha;
978 // Finished searching the move. If a stop or a cutoff occurred, the return
979 // value of the search cannot be trusted, and we return immediately without
980 // updating best move, PV and TT.
981 if (Signals.stop || thisThread->cutoff_occurred())
986 RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
988 // PV move or new best move ?
989 if (moveCount == 1 || value > alpha)
996 for (Move* m = (ss+1)->pv; *m != MOVE_NONE; ++m)
999 // We record how often the best move has been changed in each
1000 // iteration. This information is used for time management: When
1001 // the best move changes frequently, we allocate some more time.
1006 // All other moves but the PV are set to the lowest value: this is
1007 // not a problem when sorting because the sort is stable and the
1008 // move position in the list is preserved - just the PV is pushed up.
1009 rm.score = -VALUE_INFINITE;
1012 if (value > bestValue)
1014 bestValue = SpNode ? splitPoint->bestValue = value : value;
1018 bestMove = SpNode ? splitPoint->bestMove = move : move;
1020 if (PvNode && !RootNode) // Update pv even in fail-high case
1021 update_pv(SpNode ? splitPoint->ss->pv : ss->pv, move, (ss+1)->pv);
1023 if (PvNode && value < beta) // Update alpha! Always alpha < beta
1024 alpha = SpNode ? splitPoint->alpha = value : value;
1027 assert(value >= beta); // Fail high
1030 splitPoint->cutoff = true;
1037 // Step 19. Check for splitting the search
1039 && Threads.size() >= 2
1040 && depth >= Threads.minimumSplitDepth
1041 && ( !thisThread->activeSplitPoint
1042 || !thisThread->activeSplitPoint->allSlavesSearching)
1043 && thisThread->splitPointsSize < MAX_SPLITPOINTS_PER_THREAD)
1045 assert(bestValue > -VALUE_INFINITE && bestValue < beta);
1047 thisThread->split(pos, ss, alpha, beta, &bestValue, &bestMove,
1048 depth, moveCount, &mp, NT, cutNode);
1050 if (Signals.stop || thisThread->cutoff_occurred())
1053 if (bestValue >= beta)
1061 // Following condition would detect a stop or a cutoff set only after move
1062 // loop has been completed. But in this case bestValue is valid because we
1063 // have fully searched our subtree, and we can anyhow save the result in TT.
1065 if (Signals.stop || thisThread->cutoff_occurred())
1069 // Step 20. Check for mate and stalemate
1070 // All legal moves have been searched and if there are no legal moves, it
1071 // must be mate or stalemate. If we are in a singular extension search then
1072 // return a fail low score.
1074 bestValue = excludedMove ? alpha
1075 : inCheck ? mated_in(ss->ply) : DrawValue[pos.side_to_move()];
1077 // Quiet best move: update killers, history, countermoves and followupmoves
1078 else if (bestValue >= beta && !pos.capture_or_promotion(bestMove) && !inCheck)
1079 update_stats(pos, ss, bestMove, depth, quietsSearched, quietCount - 1);
1081 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1082 bestValue >= beta ? BOUND_LOWER :
1083 PvNode && bestMove ? BOUND_EXACT : BOUND_UPPER,
1084 depth, bestMove, ss->staticEval);
1086 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1092 // qsearch() is the quiescence search function, which is called by the main
1093 // search function when the remaining depth is zero (or, to be more precise,
1094 // less than ONE_PLY).
1096 template <NodeType NT, bool InCheck>
1097 Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1099 const bool PvNode = NT == PV;
1101 assert(NT == PV || NT == NonPV);
1102 assert(InCheck == !!pos.checkers());
1103 assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1104 assert(PvNode || (alpha == beta - 1));
1105 assert(depth <= DEPTH_ZERO);
1111 Move ttMove, move, bestMove;
1112 Value bestValue, value, ttValue, futilityValue, futilityBase, oldAlpha;
1113 bool givesCheck, evasionPrunable;
1118 oldAlpha = alpha; // To flag BOUND_EXACT when eval above alpha and no available moves
1120 ss->pv[0] = MOVE_NONE;
1123 ss->currentMove = bestMove = MOVE_NONE;
1124 ss->ply = (ss-1)->ply + 1;
1126 // Check for an instant draw or if the maximum ply has been reached
1127 if (pos.is_draw() || ss->ply >= MAX_PLY)
1128 return ss->ply >= MAX_PLY && !InCheck ? evaluate(pos) : DrawValue[pos.side_to_move()];
1130 assert(0 <= ss->ply && ss->ply < MAX_PLY);
1132 // Decide whether or not to include checks: this fixes also the type of
1133 // TT entry depth that we are going to use. Note that in qsearch we use
1134 // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1135 ttDepth = InCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
1136 : DEPTH_QS_NO_CHECKS;
1138 // Transposition table lookup
1140 tte = TT.probe(posKey);
1141 ttMove = tte ? tte->move() : MOVE_NONE;
1142 ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1146 && tte->depth() >= ttDepth
1147 && ttValue != VALUE_NONE // Only in case of TT access race
1148 && (ttValue >= beta ? (tte->bound() & BOUND_LOWER)
1149 : (tte->bound() & BOUND_UPPER)))
1151 ss->currentMove = ttMove; // Can be MOVE_NONE
1155 // Evaluate the position statically
1158 ss->staticEval = VALUE_NONE;
1159 bestValue = futilityBase = -VALUE_INFINITE;
1165 // Never assume anything on values stored in TT
1166 if ((ss->staticEval = bestValue = tte->eval_value()) == VALUE_NONE)
1167 ss->staticEval = bestValue = evaluate(pos);
1169 // Can ttValue be used as a better position evaluation?
1170 if (ttValue != VALUE_NONE)
1171 if (tte->bound() & (ttValue > bestValue ? BOUND_LOWER : BOUND_UPPER))
1172 bestValue = ttValue;
1175 ss->staticEval = bestValue =
1176 (ss-1)->currentMove != MOVE_NULL ? evaluate(pos) : -(ss-1)->staticEval + 2 * Eval::Tempo;
1178 // Stand pat. Return immediately if static value is at least beta
1179 if (bestValue >= beta)
1182 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER,
1183 DEPTH_NONE, MOVE_NONE, ss->staticEval);
1188 if (PvNode && bestValue > alpha)
1191 futilityBase = bestValue + 128;
1194 // Initialize a MovePicker object for the current position, and prepare
1195 // to search the moves. Because the depth is <= 0 here, only captures,
1196 // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1198 MovePicker mp(pos, ttMove, depth, History, to_sq((ss-1)->currentMove));
1201 // Loop through the moves until no moves remain or a beta cutoff occurs
1202 while ((move = mp.next_move<false>()) != MOVE_NONE)
1204 assert(is_ok(move));
1206 givesCheck = type_of(move) == NORMAL && !ci.dcCandidates
1207 ? ci.checkSq[type_of(pos.piece_on(from_sq(move)))] & to_sq(move)
1208 : pos.gives_check(move, ci);
1214 && futilityBase > -VALUE_KNOWN_WIN
1215 && !pos.advanced_pawn_push(move))
1217 assert(type_of(move) != ENPASSANT); // Due to !pos.advanced_pawn_push
1219 futilityValue = futilityBase + PieceValue[EG][pos.piece_on(to_sq(move))];
1221 if (futilityValue < beta)
1223 bestValue = std::max(bestValue, futilityValue);
1227 if (futilityBase < beta && pos.see(move) <= VALUE_ZERO)
1229 bestValue = std::max(bestValue, futilityBase);
1234 // Detect non-capture evasions that are candidates to be pruned
1235 evasionPrunable = InCheck
1236 && bestValue > VALUE_MATED_IN_MAX_PLY
1237 && !pos.capture(move)
1238 && !pos.can_castle(pos.side_to_move());
1240 // Don't search moves with negative SEE values
1242 && (!InCheck || evasionPrunable)
1243 && type_of(move) != PROMOTION
1244 && pos.see_sign(move) < VALUE_ZERO)
1247 // Speculative prefetch as early as possible
1248 prefetch((char*)TT.first_entry(pos.key_after(move)));
1250 // Check for legality just before making the move
1251 if (!pos.legal(move, ci.pinned))
1254 ss->currentMove = move;
1256 // Make and search the move
1257 pos.do_move(move, st, ci, givesCheck);
1258 value = givesCheck ? -qsearch<NT, true>(pos, ss+1, -beta, -alpha, depth - ONE_PLY)
1259 : -qsearch<NT, false>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1260 pos.undo_move(move);
1262 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1264 // Check for new best move
1265 if (value > bestValue)
1271 if (PvNode) // Update pv even in fail-high case
1272 update_pv(ss->pv, move, (ss+1)->pv);
1274 if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1281 TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1282 ttDepth, move, ss->staticEval);
1290 // All legal moves have been searched. A special case: If we're in check
1291 // and no legal moves were found, it is checkmate.
1292 if (InCheck && bestValue == -VALUE_INFINITE)
1293 return mated_in(ss->ply); // Plies to mate from the root
1295 TT.store(posKey, value_to_tt(bestValue, ss->ply),
1296 PvNode && bestValue > oldAlpha ? BOUND_EXACT : BOUND_UPPER,
1297 ttDepth, bestMove, ss->staticEval);
1299 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1305 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1306 // "plies to mate from the current position". Non-mate scores are unchanged.
1307 // The function is called before storing a value in the transposition table.
1309 Value value_to_tt(Value v, int ply) {
1311 assert(v != VALUE_NONE);
1313 return v >= VALUE_MATE_IN_MAX_PLY ? v + ply
1314 : v <= VALUE_MATED_IN_MAX_PLY ? v - ply : v;
1318 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1319 // from the transposition table (which refers to the plies to mate/be mated
1320 // from current position) to "plies to mate/be mated from the root".
1322 Value value_from_tt(Value v, int ply) {
1324 return v == VALUE_NONE ? VALUE_NONE
1325 : v >= VALUE_MATE_IN_MAX_PLY ? v - ply
1326 : v <= VALUE_MATED_IN_MAX_PLY ? v + ply : v;
1330 // update_pv() adds current move and appends child pv[]
1332 void update_pv(Move* pv, Move move, Move* childPv) {
1334 for (*pv++ = move; childPv && *childPv != MOVE_NONE; )
1339 // update_stats() updates killers, history, countermoves and followupmoves stats after a fail-high
1342 void update_stats(const Position& pos, Stack* ss, Move move, Depth depth, Move* quiets, int quietsCnt) {
1344 if (ss->killers[0] != move)
1346 ss->killers[1] = ss->killers[0];
1347 ss->killers[0] = move;
1350 // Increase history value of the cut-off move and decrease all the other
1351 // played quiet moves.
1352 Value bonus = Value((depth / ONE_PLY) * (depth / ONE_PLY));
1353 History.update(pos.moved_piece(move), to_sq(move), bonus);
1354 for (int i = 0; i < quietsCnt; ++i)
1357 History.update(pos.moved_piece(m), to_sq(m), -bonus);
1360 if (is_ok((ss-1)->currentMove))
1362 Square prevMoveSq = to_sq((ss-1)->currentMove);
1363 Countermoves.update(pos.piece_on(prevMoveSq), prevMoveSq, move);
1366 if (is_ok((ss-2)->currentMove) && (ss-1)->currentMove == (ss-1)->ttMove)
1368 Square prevOwnMoveSq = to_sq((ss-2)->currentMove);
1369 Followupmoves.update(pos.piece_on(prevOwnMoveSq), prevOwnMoveSq, move);
1374 // When playing with a strength handicap, choose best move among the first 'candidates'
1375 // RootMoves using a statistical rule dependent on 'level'. Idea by Heinz van Saanen.
1377 Move Skill::pick_move() {
1381 // PRNG sequence should be not deterministic
1382 for (int i = Time::now() % 50; i > 0; --i)
1383 rk.rand<unsigned>();
1385 // RootMoves are already sorted by score in descending order
1386 int variance = std::min(RootMoves[0].score - RootMoves[candidates - 1].score, PawnValueMg);
1387 int weakness = 120 - 2 * level;
1388 int max_s = -VALUE_INFINITE;
1391 // Choose best move. For each move score we add two terms both dependent on
1392 // weakness. One deterministic and bigger for weaker moves, and one random,
1393 // then we choose the move with the resulting highest score.
1394 for (size_t i = 0; i < candidates; ++i)
1396 int s = RootMoves[i].score;
1398 // Don't allow crazy blunders even at very low skills
1399 if (i > 0 && RootMoves[i - 1].score > s + 2 * PawnValueMg)
1402 // This is our magic formula
1403 s += ( weakness * int(RootMoves[0].score - s)
1404 + variance * (rk.rand<unsigned>() % weakness)) / 128;
1409 best = RootMoves[i].pv[0];
1416 // uci_pv() formats PV information according to the UCI protocol. UCI
1417 // requires that all (if any) unsearched PV lines are sent using a previous
1420 string uci_pv(const Position& pos, Depth depth, Value alpha, Value beta) {
1422 std::stringstream ss;
1423 Time::point elapsed = Time::now() - SearchTime + 1;
1424 size_t uciPVSize = std::min((size_t)Options["MultiPV"], RootMoves.size());
1427 for (size_t i = 0; i < Threads.size(); ++i)
1428 if (Threads[i]->maxPly > selDepth)
1429 selDepth = Threads[i]->maxPly;
1431 for (size_t i = 0; i < uciPVSize; ++i)
1433 bool updated = (i <= PVIdx);
1435 if (depth == ONE_PLY && !updated)
1438 Depth d = updated ? depth : depth - ONE_PLY;
1439 Value v = updated ? RootMoves[i].score : RootMoves[i].prevScore;
1441 bool tb = RootInTB && abs(v) < VALUE_MATE - MAX_PLY;
1442 v = tb ? TBScore : v;
1444 if (ss.rdbuf()->in_avail()) // Not at first line
1447 ss << "info depth " << d / ONE_PLY
1448 << " seldepth " << selDepth
1449 << " multipv " << i + 1
1450 << " score " << ((!tb && i == PVIdx) ? UCI::format_value(v, alpha, beta) : UCI::format_value(v))
1451 << " nodes " << pos.nodes_searched()
1452 << " nps " << pos.nodes_searched() * 1000 / elapsed
1453 << " tbhits " << TBHits
1454 << " time " << elapsed
1457 for (size_t j = 0; j < RootMoves[i].pv.size(); ++j)
1458 ss << " " << UCI::format_move(RootMoves[i].pv[j], pos.is_chess960());
1467 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1468 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1469 /// first, even if the old TT entries have been overwritten.
1471 void RootMove::insert_pv_in_tt(Position& pos) {
1473 StateInfo state[MAX_PLY], *st = state;
1477 for ( ; idx < pv.size(); ++idx)
1479 tte = TT.probe(pos.key());
1481 if (!tte || tte->move() != pv[idx]) // Don't overwrite correct entries
1482 TT.store(pos.key(), VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[idx], VALUE_NONE);
1484 assert(MoveList<LEGAL>(pos).contains(pv[idx]));
1486 pos.do_move(pv[idx], *st++);
1489 while (idx) pos.undo_move(pv[--idx]);
1493 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1495 void Thread::idle_loop() {
1497 // Pointer 'this_sp' is not null only if we are called from split(), and not
1498 // at the thread creation. This means we are the split point's master.
1499 SplitPoint* this_sp = splitPointsSize ? activeSplitPoint : NULL;
1501 assert(!this_sp || (this_sp->masterThread == this && searching));
1505 // If this thread has been assigned work, launch a search
1508 Threads.mutex.lock();
1510 assert(activeSplitPoint);
1511 SplitPoint* sp = activeSplitPoint;
1513 Threads.mutex.unlock();
1515 Stack stack[MAX_PLY+4], *ss = stack+2; // To allow referencing (ss-2) and (ss+2)
1516 Position pos(*sp->pos, this);
1518 std::memcpy(ss-2, sp->ss-2, 5 * sizeof(Stack));
1519 ss->splitPoint = sp;
1523 assert(activePosition == NULL);
1525 activePosition = &pos;
1527 if (sp->nodeType == NonPV)
1528 search<NonPV, true>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
1530 else if (sp->nodeType == PV)
1531 search<PV, true>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
1533 else if (sp->nodeType == Root)
1534 search<Root, true>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
1542 activePosition = NULL;
1543 sp->slavesMask.reset(idx);
1544 sp->allSlavesSearching = false;
1545 sp->nodes += pos.nodes_searched();
1547 // Wake up the master thread so to allow it to return from the idle
1548 // loop in case we are the last slave of the split point.
1549 if ( this != sp->masterThread
1550 && sp->slavesMask.none())
1552 assert(!sp->masterThread->searching);
1553 sp->masterThread->notify_one();
1556 // After releasing the lock we can't access any SplitPoint related data
1557 // in a safe way because it could have been released under our feet by
1561 // Try to late join to another split point if none of its slaves has
1562 // already finished.
1563 if (Threads.size() > 2)
1564 for (size_t i = 0; i < Threads.size(); ++i)
1566 const int size = Threads[i]->splitPointsSize; // Local copy
1567 sp = size ? &Threads[i]->splitPoints[size - 1] : NULL;
1570 && sp->allSlavesSearching
1571 && available_to(Threads[i]))
1573 // Recheck the conditions under lock protection
1574 Threads.mutex.lock();
1577 if ( sp->allSlavesSearching
1578 && available_to(Threads[i]))
1580 sp->slavesMask.set(idx);
1581 activeSplitPoint = sp;
1586 Threads.mutex.unlock();
1588 break; // Just a single attempt
1593 // Grab the lock to avoid races with Thread::notify_one()
1596 // If we are master and all slaves have finished then exit idle_loop
1597 if (this_sp && this_sp->slavesMask.none())
1604 // If we are not searching, wait for a condition to be signaled instead of
1605 // wasting CPU time polling for work.
1606 if (!searching && !exit)
1607 sleepCondition.wait(mutex);
1614 /// check_time() is called by the timer thread when the timer triggers. It is
1615 /// used to print debug info and, more importantly, to detect when we are out of
1616 /// available time and thus stop the search.
1620 static Time::point lastInfoTime = Time::now();
1621 Time::point elapsed = Time::now() - SearchTime;
1623 if (Time::now() - lastInfoTime >= 1000)
1625 lastInfoTime = Time::now();
1629 // An engine may not stop pondering until told so by the GUI
1633 if (Limits.use_time_management())
1635 bool stillAtFirstMove = Signals.firstRootMove
1636 && !Signals.failedLowAtRoot
1637 && elapsed > TimeMgr.available_time() * 75 / 100;
1639 if ( stillAtFirstMove
1640 || elapsed > TimeMgr.maximum_time() - 2 * TimerThread::Resolution)
1641 Signals.stop = true;
1643 else if (Limits.movetime && elapsed >= Limits.movetime)
1644 Signals.stop = true;
1646 else if (Limits.nodes)
1648 Threads.mutex.lock();
1650 int64_t nodes = RootPos.nodes_searched();
1652 // Loop across all split points and sum accumulated SplitPoint nodes plus
1653 // all the currently active positions nodes.
1654 for (size_t i = 0; i < Threads.size(); ++i)
1655 for (int j = 0; j < Threads[i]->splitPointsSize; ++j)
1657 SplitPoint& sp = Threads[i]->splitPoints[j];
1663 for (size_t idx = 0; idx < Threads.size(); ++idx)
1664 if (sp.slavesMask.test(idx) && Threads[idx]->activePosition)
1665 nodes += Threads[idx]->activePosition->nodes_searched();
1670 Threads.mutex.unlock();
1672 if (nodes >= Limits.nodes)
1673 Signals.stop = true;