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-2010 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/>.
43 #include "ucioption.h"
49 //// Local definitions
57 // ThreadsManager class is used to handle all the threads related stuff in search,
58 // init, starting, parking and, the most important, launching a slave thread at a
59 // split point are what this class does. All the access to shared thread data is
60 // done through this class, so that we avoid using global variables instead.
62 class ThreadsManager {
63 /* As long as the single ThreadsManager object is defined as a global we don't
64 need to explicitly initialize to zero its data members because variables with
65 static storage duration are automatically set to zero before enter main()
71 int active_threads() const { return ActiveThreads; }
72 void set_active_threads(int newActiveThreads) { ActiveThreads = newActiveThreads; }
73 void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
74 void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
76 void resetNodeCounters();
77 void resetBetaCounters();
78 int64_t nodes_searched() const;
79 void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
80 bool available_thread_exists(int master) const;
81 bool thread_is_available(int slave, int master) const;
82 bool thread_should_stop(int threadID) const;
83 void wake_sleeping_threads();
84 void put_threads_to_sleep();
85 void idle_loop(int threadID, SplitPoint* waitSp);
86 bool split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
87 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode);
90 friend void poll(SearchStack ss[], int ply);
93 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
94 Thread threads[MAX_THREADS];
95 SplitPoint SplitPointStack[MAX_THREADS][ACTIVE_SPLIT_POINTS_MAX];
97 Lock MPLock, WaitLock;
99 #if !defined(_MSC_VER)
100 pthread_cond_t WaitCond;
102 HANDLE SitIdleEvent[MAX_THREADS];
108 // RootMove struct is used for moves at the root at the tree. For each
109 // root move, we store a score, a node count, and a PV (really a refutation
110 // in the case of moves which fail low).
114 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
116 // RootMove::operator<() is the comparison function used when
117 // sorting the moves. A move m1 is considered to be better
118 // than a move m2 if it has a higher score, or if the moves
119 // have equal score but m1 has the higher node count.
120 bool operator<(const RootMove& m) const {
122 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
127 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
128 Move pv[PLY_MAX_PLUS_2];
132 // The RootMoveList class is essentially an array of RootMove objects, with
133 // a handful of methods for accessing the data in the individual moves.
138 RootMoveList(Position& pos, Move searchMoves[]);
140 int move_count() const { return count; }
141 Move get_move(int moveNum) const { return moves[moveNum].move; }
142 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
143 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
144 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
145 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
147 void set_move_nodes(int moveNum, int64_t nodes);
148 void set_beta_counters(int moveNum, int64_t our, int64_t their);
149 void set_move_pv(int moveNum, const Move pv[]);
151 void sort_multipv(int n);
154 static const int MaxRootMoves = 500;
155 RootMove moves[MaxRootMoves];
164 // Maximum depth for razoring
165 const Depth RazorDepth = 4 * OnePly;
167 // Dynamic razoring margin based on depth
168 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
170 // Step 8. Null move search with verification search
172 // Null move margin. A null move search will not be done if the static
173 // evaluation of the position is more than NullMoveMargin below beta.
174 const Value NullMoveMargin = Value(0x200);
176 // Maximum depth for use of dynamic threat detection when null move fails low
177 const Depth ThreatDepth = 5 * OnePly;
179 // Step 9. Internal iterative deepening
181 // Minimum depth for use of internal iterative deepening
182 const Depth IIDDepthAtPVNodes = 5 * OnePly;
183 const Depth IIDDepthAtNonPVNodes = 8 * OnePly;
185 // At Non-PV nodes we do an internal iterative deepening search
186 // when the static evaluation is at most IIDMargin below beta.
187 const Value IIDMargin = Value(0x100);
189 // Step 11. Decide the new search depth
191 // Extensions. Configurable UCI options
192 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
193 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
194 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
196 // Minimum depth for use of singular extension
197 const Depth SingularExtensionDepthAtPVNodes = 6 * OnePly;
198 const Depth SingularExtensionDepthAtNonPVNodes = 8 * OnePly;
200 // If the TT move is at least SingularExtensionMargin better then the
201 // remaining ones we will extend it.
202 const Value SingularExtensionMargin = Value(0x20);
204 // Step 12. Futility pruning
206 // Futility margin for quiescence search
207 const Value FutilityMarginQS = Value(0x80);
209 // Futility lookup tables (initialized at startup) and their getter functions
210 int32_t FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
211 int FutilityMoveCountArray[32]; // [depth]
213 inline Value futility_margin(Depth d, int mn) { return Value(d < 7 * OnePly ? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
214 inline int futility_move_count(Depth d) { return d < 16 * OnePly ? FutilityMoveCountArray[d] : 512; }
216 // Step 14. Reduced search
218 int ReductionLevel = 2; // 0 = most aggressive reductions, 7 = minimum reductions
220 // Reduction lookup tables (initialized at startup) and their getter functions
221 int8_t PVReductionMatrix[8][64][64]; // [depth][moveNumber]
222 int8_t NonPVReductionMatrix[8][64][64]; // [depth][moveNumber]
224 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[ReductionLevel][Min(d / 2, 63)][Min(mn, 63)]; }
225 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[ReductionLevel][Min(d / 2, 63)][Min(mn, 63)]; }
227 // Common adjustments
229 // Search depth at iteration 1
230 const Depth InitialDepth = OnePly;
232 // Easy move margin. An easy move candidate must be at least this much
233 // better than the second best move.
234 const Value EasyMoveMargin = Value(0x200);
236 // Last seconds noise filtering (LSN)
237 const bool UseLSNFiltering = true;
238 const int LSNTime = 4000; // In milliseconds
239 const Value LSNValue = value_from_centipawns(200);
240 bool loseOnTime = false;
248 // Scores and number of times the best move changed for each iteration
249 Value ValueByIteration[PLY_MAX_PLUS_2];
250 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
252 // Search window management
258 // Time managment variables
259 int SearchStartTime, MaxNodes, MaxDepth, MaxSearchTime;
260 int AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
261 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
262 bool FirstRootMove, AbortSearch, Quit, AspirationFailLow;
264 // Show current line?
265 bool ShowCurrentLine;
269 std::ofstream LogFile;
271 // Multi-threads related variables
272 Depth MinimumSplitDepth;
273 int MaxThreadsPerSplitPoint;
276 // Node counters, used only by thread[0] but try to keep in different cache
277 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
279 int NodesBetweenPolls = 30000;
286 Value id_loop(const Position& pos, Move searchMoves[]);
287 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr);
288 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
289 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
290 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
291 void sp_search(SplitPoint* sp, int threadID);
292 void sp_search_pv(SplitPoint* sp, int threadID);
293 void init_node(SearchStack ss[], int ply, int threadID);
294 void update_pv(SearchStack ss[], int ply);
295 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
296 bool connected_moves(const Position& pos, Move m1, Move m2);
297 bool value_is_mate(Value value);
298 bool move_is_killer(Move m, const SearchStack& ss);
299 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
300 bool ok_to_do_nullmove(const Position& pos);
301 bool ok_to_prune(const Position& pos, Move m, Move threat);
302 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
303 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
304 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
305 void update_killers(Move m, SearchStack& ss);
306 void update_gains(const Position& pos, Move move, Value before, Value after);
308 int current_search_time();
310 void poll(SearchStack ss[], int ply);
312 void wait_for_stop_or_ponderhit();
313 void init_ss_array(SearchStack ss[]);
314 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value);
316 #if !defined(_MSC_VER)
317 void *init_thread(void *threadID);
319 DWORD WINAPI init_thread(LPVOID threadID);
329 /// init_threads(), exit_threads() and nodes_searched() are helpers to
330 /// give accessibility to some TM methods from outside of current file.
332 void init_threads() { TM.init_threads(); }
333 void exit_threads() { TM.exit_threads(); }
334 int64_t nodes_searched() { return TM.nodes_searched(); }
337 /// perft() is our utility to verify move generation is bug free. All the legal
338 /// moves up to given depth are generated and counted and the sum returned.
340 int perft(Position& pos, Depth depth)
345 MovePicker mp(pos, MOVE_NONE, depth, H);
347 // If we are at the last ply we don't need to do and undo
348 // the moves, just to count them.
349 if (depth <= OnePly) // Replace with '<' to test also qsearch
351 while (mp.get_next_move()) sum++;
355 // Loop through all legal moves
357 while ((move = mp.get_next_move()) != MOVE_NONE)
359 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
360 sum += perft(pos, depth - OnePly);
367 /// think() is the external interface to Stockfish's search, and is called when
368 /// the program receives the UCI 'go' command. It initializes various
369 /// search-related global variables, and calls root_search(). It returns false
370 /// when a quit command is received during the search.
372 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
373 int time[], int increment[], int movesToGo, int maxDepth,
374 int maxNodes, int maxTime, Move searchMoves[]) {
376 // Initialize global search variables
377 StopOnPonderhit = AbortSearch = Quit = AspirationFailLow = false;
378 MaxSearchTime = AbsoluteMaxSearchTime = ExtraSearchTime = 0;
380 TM.resetNodeCounters();
381 SearchStartTime = get_system_time();
382 ExactMaxTime = maxTime;
385 InfiniteSearch = infinite;
386 PonderSearch = ponder;
387 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
389 // Look for a book move, only during games, not tests
390 if (UseTimeManagement && get_option_value_bool("OwnBook"))
392 if (get_option_value_string("Book File") != OpeningBook.file_name())
393 OpeningBook.open(get_option_value_string("Book File"));
395 Move bookMove = OpeningBook.get_move(pos);
396 if (bookMove != MOVE_NONE)
399 wait_for_stop_or_ponderhit();
401 cout << "bestmove " << bookMove << endl;
406 // Reset loseOnTime flag at the beginning of a new game
407 if (button_was_pressed("New Game"))
410 // Read UCI option values
411 TT.set_size(get_option_value_int("Hash"));
412 if (button_was_pressed("Clear Hash"))
415 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
416 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
417 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
418 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
419 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
420 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
421 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
422 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
423 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
424 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
425 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
426 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
428 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
429 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
430 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
431 MultiPV = get_option_value_int("MultiPV");
432 Chess960 = get_option_value_bool("UCI_Chess960");
433 UseLogFile = get_option_value_bool("Use Search Log");
436 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
438 read_weights(pos.side_to_move());
440 // Set the number of active threads
441 int newActiveThreads = get_option_value_int("Threads");
442 if (newActiveThreads != TM.active_threads())
444 TM.set_active_threads(newActiveThreads);
445 init_eval(TM.active_threads());
448 // Wake up sleeping threads
449 TM.wake_sleeping_threads();
452 int myTime = time[side_to_move];
453 int myIncrement = increment[side_to_move];
454 if (UseTimeManagement)
456 if (!movesToGo) // Sudden death time control
460 MaxSearchTime = myTime / 30 + myIncrement;
461 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
463 else // Blitz game without increment
465 MaxSearchTime = myTime / 30;
466 AbsoluteMaxSearchTime = myTime / 8;
469 else // (x moves) / (y minutes)
473 MaxSearchTime = myTime / 2;
474 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
478 MaxSearchTime = myTime / Min(movesToGo, 20);
479 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
483 if (get_option_value_bool("Ponder"))
485 MaxSearchTime += MaxSearchTime / 4;
486 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
490 // Set best NodesBetweenPolls interval to avoid lagging under
491 // heavy time pressure.
493 NodesBetweenPolls = Min(MaxNodes, 30000);
494 else if (myTime && myTime < 1000)
495 NodesBetweenPolls = 1000;
496 else if (myTime && myTime < 5000)
497 NodesBetweenPolls = 5000;
499 NodesBetweenPolls = 30000;
501 // Write search information to log file
503 LogFile << "Searching: " << pos.to_fen() << endl
504 << "infinite: " << infinite
505 << " ponder: " << ponder
506 << " time: " << myTime
507 << " increment: " << myIncrement
508 << " moves to go: " << movesToGo << endl;
510 // LSN filtering. Used only for developing purposes, disabled by default
514 // Step 2. If after last move we decided to lose on time, do it now!
515 while (SearchStartTime + myTime + 1000 > get_system_time())
519 // We're ready to start thinking. Call the iterative deepening loop function
520 Value v = id_loop(pos, searchMoves);
524 // Step 1. If this is sudden death game and our position is hopeless,
525 // decide to lose on time.
526 if ( !loseOnTime // If we already lost on time, go to step 3.
536 // Step 3. Now after stepping over the time limit, reset flag for next match.
544 TM.put_threads_to_sleep();
549 // init_reduction_tables()
551 void init_reduction_tables(int8_t pvTable[64][64], int8_t nonPvTable[64][64], int pvInhib, int nonPvInhib)
553 double pvBase = 1.001 - log(3.0) * log(16.0) / pvInhib;
554 double nonPvBase = 1.001 - log(3.0) * log(4.0) / nonPvInhib;
556 // Init reduction lookup tables
557 for (int i = 1; i < 64; i++) // i == depth (OnePly = 1)
558 for (int j = 1; j < 64; j++) // j == moveNumber
560 double pvRed = pvBase + log(double(i)) * log(double(j)) / pvInhib;
561 double nonPVRed = nonPvBase + log(double(i)) * log(double(j)) / nonPvInhib;
563 pvTable[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
564 nonPvTable[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
568 // init_search() is called during startup. It initializes various lookup tables
572 for (int i = 0; i < 8; i++)
573 init_reduction_tables(PVReductionMatrix[i], NonPVReductionMatrix[i], 4.0 * pow(1.3, i), 2.0 * pow(1.3, i));
575 // Init futility margins array
576 for (int i = 0; i < 16; i++) // i == depth (OnePly = 2)
577 for (int j = 0; j < 64; j++) // j == moveNumber
579 // FIXME: test using log instead of BSR
580 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j;
583 // Init futility move count array
584 for (int i = 0; i < 32; i++) // i == depth (OnePly = 2)
585 FutilityMoveCountArray[i] = 3 + (1 << (3 * i / 8));
589 // SearchStack::init() initializes a search stack. Used at the beginning of a
590 // new search from the root.
591 void SearchStack::init(int ply) {
593 pv[ply] = pv[ply + 1] = MOVE_NONE;
594 currentMove = threatMove = MOVE_NONE;
595 reduction = Depth(0);
599 void SearchStack::initKillers() {
601 mateKiller = MOVE_NONE;
602 for (int i = 0; i < KILLER_MAX; i++)
603 killers[i] = MOVE_NONE;
608 // id_loop() is the main iterative deepening loop. It calls root_search
609 // repeatedly with increasing depth until the allocated thinking time has
610 // been consumed, the user stops the search, or the maximum search depth is
613 Value id_loop(const Position& pos, Move searchMoves[]) {
616 SearchStack ss[PLY_MAX_PLUS_2];
617 Move EasyMove = MOVE_NONE;
618 Value value, alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
620 // Moves to search are verified, copied, scored and sorted
621 RootMoveList rml(p, searchMoves);
623 // Handle special case of searching on a mate/stale position
624 if (rml.move_count() == 0)
627 wait_for_stop_or_ponderhit();
629 return pos.is_check() ? -VALUE_MATE : VALUE_DRAW;
632 // Print RootMoveList startup scoring to the standard output,
633 // so to output information also for iteration 1.
634 cout << "info depth " << 1
635 << "\ninfo depth " << 1
636 << " score " << value_to_string(rml.get_move_score(0))
637 << " time " << current_search_time()
638 << " nodes " << TM.nodes_searched()
640 << " pv " << rml.get_move(0) << "\n";
646 ValueByIteration[1] = rml.get_move_score(0);
649 // Is one move significantly better than others after initial scoring ?
650 if ( rml.move_count() == 1
651 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
652 EasyMove = rml.get_move(0);
654 // Iterative deepening loop
655 while (Iteration < PLY_MAX)
657 // Initialize iteration
659 BestMoveChangesByIteration[Iteration] = 0;
661 cout << "info depth " << Iteration << endl;
663 // Calculate dynamic aspiration window based on previous iterations
664 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
666 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
667 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
669 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
670 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
672 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
673 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
676 // Choose optimum reduction level
679 if (UseTimeManagement)
681 int level = int(floor(log(float(MaxSearchTime) / current_search_time()) / log(2.0) + 1.0));
682 ReductionLevel = Min(Max(level, 0), 7);
689 // Search to the current depth, rml is updated and sorted, alpha and beta could change
690 value = root_search(p, ss, rml, &alpha, &beta);
692 // Write PV to transposition table, in case the relevant entries have
693 // been overwritten during the search.
694 TT.insert_pv(p, ss[0].pv);
697 break; // Value cannot be trusted. Break out immediately!
699 //Save info about search result
700 ValueByIteration[Iteration] = value;
702 // Drop the easy move if differs from the new best move
703 if (ss[0].pv[0] != EasyMove)
704 EasyMove = MOVE_NONE;
706 if (UseTimeManagement)
709 bool stopSearch = false;
711 // Stop search early if there is only a single legal move,
712 // we search up to Iteration 6 anyway to get a proper score.
713 if (Iteration >= 6 && rml.move_count() == 1)
716 // Stop search early when the last two iterations returned a mate score
718 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
719 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
722 // Stop search early if one move seems to be much better than the others
723 int64_t nodes = TM.nodes_searched();
725 && EasyMove == ss[0].pv[0]
726 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
727 && current_search_time() > MaxSearchTime / 16)
728 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
729 && current_search_time() > MaxSearchTime / 32)))
732 // Add some extra time if the best move has changed during the last two iterations
733 if (Iteration > 5 && Iteration <= 50)
734 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
735 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
737 // Stop search if most of MaxSearchTime is consumed at the end of the
738 // iteration. We probably don't have enough time to search the first
739 // move at the next iteration anyway.
740 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
746 StopOnPonderhit = true;
752 if (MaxDepth && Iteration >= MaxDepth)
756 // If we are pondering or in infinite search, we shouldn't print the
757 // best move before we are told to do so.
758 if (!AbortSearch && (PonderSearch || InfiniteSearch))
759 wait_for_stop_or_ponderhit();
761 // Print final search statistics
762 cout << "info nodes " << TM.nodes_searched()
764 << " time " << current_search_time()
765 << " hashfull " << TT.full() << endl;
767 // Print the best move and the ponder move to the standard output
768 if (ss[0].pv[0] == MOVE_NONE)
770 ss[0].pv[0] = rml.get_move(0);
771 ss[0].pv[1] = MOVE_NONE;
774 assert(ss[0].pv[0] != MOVE_NONE);
776 cout << "bestmove " << ss[0].pv[0];
778 if (ss[0].pv[1] != MOVE_NONE)
779 cout << " ponder " << ss[0].pv[1];
786 dbg_print_mean(LogFile);
788 if (dbg_show_hit_rate)
789 dbg_print_hit_rate(LogFile);
791 LogFile << "\nNodes: " << TM.nodes_searched()
792 << "\nNodes/second: " << nps()
793 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
796 p.do_move(ss[0].pv[0], st);
797 LogFile << "\nPonder move: "
798 << move_to_san(p, ss[0].pv[1]) // Works also with MOVE_NONE
801 return rml.get_move_score(0);
805 // root_search() is the function which searches the root node. It is
806 // similar to search_pv except that it uses a different move ordering
807 // scheme, prints some information to the standard output and handles
808 // the fail low/high loops.
810 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value* alphaPtr, Value* betaPtr) {
817 Depth depth, ext, newDepth;
818 Value value, alpha, beta;
819 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
820 int researchCountFH, researchCountFL;
822 researchCountFH = researchCountFL = 0;
825 isCheck = pos.is_check();
827 // Step 1. Initialize node and poll (omitted at root, but I can see no good reason for this, FIXME)
828 // Step 2. Check for aborted search (omitted at root, because we do not initialize root node)
829 // Step 3. Mate distance pruning (omitted at root)
830 // Step 4. Transposition table lookup (omitted at root)
832 // Step 5. Evaluate the position statically
833 // At root we do this only to get reference value for child nodes
835 ss[0].eval = evaluate(pos, ei, 0);
837 ss[0].eval = VALUE_NONE; // HACK because we do not initialize root node
839 // Step 6. Razoring (omitted at root)
840 // Step 7. Static null move pruning (omitted at root)
841 // Step 8. Null move search with verification search (omitted at root)
842 // Step 9. Internal iterative deepening (omitted at root)
844 // Step extra. Fail low loop
845 // We start with small aspiration window and in case of fail low, we research
846 // with bigger window until we are not failing low anymore.
849 // Sort the moves before to (re)search
852 // Step 10. Loop through all moves in the root move list
853 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
855 // This is used by time management
856 FirstRootMove = (i == 0);
858 // Save the current node count before the move is searched
859 nodes = TM.nodes_searched();
861 // Reset beta cut-off counters
862 TM.resetBetaCounters();
864 // Pick the next root move, and print the move and the move number to
865 // the standard output.
866 move = ss[0].currentMove = rml.get_move(i);
868 if (current_search_time() >= 1000)
869 cout << "info currmove " << move
870 << " currmovenumber " << i + 1 << endl;
872 moveIsCheck = pos.move_is_check(move);
873 captureOrPromotion = pos.move_is_capture_or_promotion(move);
875 // Step 11. Decide the new search depth
876 depth = (Iteration - 2) * OnePly + InitialDepth;
877 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
878 newDepth = depth + ext;
880 // Step 12. Futility pruning (omitted at root)
882 // Step extra. Fail high loop
883 // If move fails high, we research with bigger window until we are not failing
885 value = - VALUE_INFINITE;
889 // Step 13. Make the move
890 pos.do_move(move, st, ci, moveIsCheck);
892 // Step extra. pv search
893 // We do pv search for first moves (i < MultiPV)
894 // and for fail high research (value > alpha)
895 if (i < MultiPV || value > alpha)
897 // Aspiration window is disabled in multi-pv case
899 alpha = -VALUE_INFINITE;
901 // Full depth PV search, done on first move or after a fail high
902 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
906 // Step 14. Reduced search
907 // if the move fails high will be re-searched at full depth
908 bool doFullDepthSearch = true;
910 if ( depth >= 3 * OnePly
912 && !captureOrPromotion
913 && !move_is_castle(move))
915 ss[0].reduction = pv_reduction(depth, i - MultiPV + 2);
918 // Reduced depth non-pv search using alpha as upperbound
919 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
920 doFullDepthSearch = (value > alpha);
924 // Step 15. Full depth search
925 if (doFullDepthSearch)
927 // Full depth non-pv search using alpha as upperbound
928 ss[0].reduction = Depth(0);
929 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
931 // If we are above alpha then research at same depth but as PV
932 // to get a correct score or eventually a fail high above beta.
934 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
938 // Step 16. Undo move
941 // Can we exit fail high loop ?
942 if (AbortSearch || value < beta)
945 // We are failing high and going to do a research. It's important to update
946 // the score before research in case we run out of time while researching.
947 rml.set_move_score(i, value);
949 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
950 rml.set_move_pv(i, ss[0].pv);
952 // Print information to the standard output
953 print_pv_info(pos, ss, alpha, beta, value);
955 // Prepare for a research after a fail high, each time with a wider window
956 *betaPtr = beta = Min(beta + AspirationDelta * (1 << researchCountFH), VALUE_INFINITE);
959 } // End of fail high loop
961 // Finished searching the move. If AbortSearch is true, the search
962 // was aborted because the user interrupted the search or because we
963 // ran out of time. In this case, the return value of the search cannot
964 // be trusted, and we break out of the loop without updating the best
969 // Remember beta-cutoff and searched nodes counts for this move. The
970 // info is used to sort the root moves for the next iteration.
972 TM.get_beta_counters(pos.side_to_move(), our, their);
973 rml.set_beta_counters(i, our, their);
974 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
976 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
977 assert(value < beta);
979 // Step 17. Check for new best move
980 if (value <= alpha && i >= MultiPV)
981 rml.set_move_score(i, -VALUE_INFINITE);
984 // PV move or new best move!
987 rml.set_move_score(i, value);
989 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
990 rml.set_move_pv(i, ss[0].pv);
994 // We record how often the best move has been changed in each
995 // iteration. This information is used for time managment: When
996 // the best move changes frequently, we allocate some more time.
998 BestMoveChangesByIteration[Iteration]++;
1000 // Print information to the standard output
1001 print_pv_info(pos, ss, alpha, beta, value);
1003 // Raise alpha to setup proper non-pv search upper bound
1009 rml.sort_multipv(i);
1010 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1012 cout << "info multipv " << j + 1
1013 << " score " << value_to_string(rml.get_move_score(j))
1014 << " depth " << (j <= i ? Iteration : Iteration - 1)
1015 << " time " << current_search_time()
1016 << " nodes " << TM.nodes_searched()
1020 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1021 cout << rml.get_move_pv(j, k) << " ";
1025 alpha = rml.get_move_score(Min(i, MultiPV - 1));
1027 } // PV move or new best move
1029 assert(alpha >= *alphaPtr);
1031 AspirationFailLow = (alpha == *alphaPtr);
1033 if (AspirationFailLow && StopOnPonderhit)
1034 StopOnPonderhit = false;
1037 // Can we exit fail low loop ?
1038 if (AbortSearch || !AspirationFailLow)
1041 // Prepare for a research after a fail low, each time with a wider window
1042 *alphaPtr = alpha = Max(alpha - AspirationDelta * (1 << researchCountFL), -VALUE_INFINITE);
1047 // Sort the moves before to return
1054 // search_pv() is the main search function for PV nodes.
1056 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1057 Depth depth, int ply, int threadID) {
1059 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1060 assert(beta > alpha && beta <= VALUE_INFINITE);
1061 assert(ply >= 0 && ply < PLY_MAX);
1062 assert(threadID >= 0 && threadID < TM.active_threads());
1064 Move movesSearched[256];
1069 Depth ext, newDepth;
1070 Value bestValue, value, oldAlpha;
1071 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1072 bool mateThreat = false;
1074 bestValue = value = -VALUE_INFINITE;
1077 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1079 // Step 1. Initialize node and poll
1080 // Polling can abort search.
1081 init_node(ss, ply, threadID);
1083 // Step 2. Check for aborted search and immediate draw
1084 if (AbortSearch || TM.thread_should_stop(threadID))
1087 if (pos.is_draw() || ply >= PLY_MAX - 1)
1090 // Step 3. Mate distance pruning
1092 alpha = Max(value_mated_in(ply), alpha);
1093 beta = Min(value_mate_in(ply+1), beta);
1097 // Step 4. Transposition table lookup
1098 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1099 // This is to avoid problems in the following areas:
1101 // * Repetition draw detection
1102 // * Fifty move rule detection
1103 // * Searching for a mate
1104 // * Printing of full PV line
1105 tte = TT.retrieve(pos.get_key());
1106 ttMove = (tte ? tte->move() : MOVE_NONE);
1108 // Step 5. Evaluate the position statically
1109 // At PV nodes we do this only to update gain statistics
1110 isCheck = pos.is_check();
1113 ss[ply].eval = evaluate(pos, ei, threadID);
1114 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1117 // Step 6. Razoring (is omitted in PV nodes)
1118 // Step 7. Static null move pruning (is omitted in PV nodes)
1119 // Step 8. Null move search with verification search (is omitted in PV nodes)
1121 // Step 9. Internal iterative deepening
1122 if ( depth >= IIDDepthAtPVNodes
1123 && ttMove == MOVE_NONE)
1125 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1126 ttMove = ss[ply].pv[ply];
1127 tte = TT.retrieve(pos.get_key());
1130 // Step 10. Loop through moves
1131 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1133 // Initialize a MovePicker object for the current position
1134 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1135 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1138 while ( alpha < beta
1139 && (move = mp.get_next_move()) != MOVE_NONE
1140 && !TM.thread_should_stop(threadID))
1142 assert(move_is_ok(move));
1144 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1145 moveIsCheck = pos.move_is_check(move, ci);
1146 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1148 // Step 11. Decide the new search depth
1149 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1151 // Singular extension search. We extend the TT move if its value is much better than
1152 // its siblings. To verify this we do a reduced search on all the other moves but the
1153 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1154 if ( depth >= SingularExtensionDepthAtPVNodes
1156 && move == tte->move()
1158 && is_lower_bound(tte->type())
1159 && tte->depth() >= depth - 3 * OnePly)
1161 Value ttValue = value_from_tt(tte->value(), ply);
1163 if (abs(ttValue) < VALUE_KNOWN_WIN)
1165 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1167 if (excValue < ttValue - SingularExtensionMargin)
1172 newDepth = depth - OnePly + ext;
1174 // Update current move (this must be done after singular extension search)
1175 movesSearched[moveCount++] = ss[ply].currentMove = move;
1177 // Step 12. Futility pruning (is omitted in PV nodes)
1179 // Step 13. Make the move
1180 pos.do_move(move, st, ci, moveIsCheck);
1182 // Step extra. pv search (only in PV nodes)
1183 // The first move in list is the expected PV
1185 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1188 // Step 14. Reduced search
1189 // if the move fails high will be re-searched at full depth.
1190 bool doFullDepthSearch = true;
1192 if ( depth >= 3 * OnePly
1194 && !captureOrPromotion
1195 && !move_is_castle(move)
1196 && !move_is_killer(move, ss[ply]))
1198 ss[ply].reduction = pv_reduction(depth, moveCount);
1199 if (ss[ply].reduction)
1201 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1202 doFullDepthSearch = (value > alpha);
1206 // Step 15. Full depth search
1207 if (doFullDepthSearch)
1209 ss[ply].reduction = Depth(0);
1210 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1212 // Step extra. pv search (only in PV nodes)
1213 if (value > alpha && value < beta)
1214 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1218 // Step 16. Undo move
1219 pos.undo_move(move);
1221 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1223 // Step 17. Check for new best move
1224 if (value > bestValue)
1231 if (value == value_mate_in(ply + 1))
1232 ss[ply].mateKiller = move;
1236 // Step 18. Check for split
1237 if ( TM.active_threads() > 1
1239 && depth >= MinimumSplitDepth
1241 && TM.available_thread_exists(threadID)
1243 && !TM.thread_should_stop(threadID)
1244 && TM.split(pos, ss, ply, &alpha, beta, &bestValue,
1245 depth, mateThreat, &moveCount, &mp, threadID, true))
1249 // Step 19. Check for mate and stalemate
1250 // All legal moves have been searched and if there were
1251 // no legal moves, it must be mate or stalemate.
1253 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1255 // Step 20. Update tables
1256 // If the search is not aborted, update the transposition table,
1257 // history counters, and killer moves.
1258 if (AbortSearch || TM.thread_should_stop(threadID))
1261 if (bestValue <= oldAlpha)
1262 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1264 else if (bestValue >= beta)
1266 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1267 move = ss[ply].pv[ply];
1268 if (!pos.move_is_capture_or_promotion(move))
1270 update_history(pos, move, depth, movesSearched, moveCount);
1271 update_killers(move, ss[ply]);
1273 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1276 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1282 // search() is the search function for zero-width nodes.
1284 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1285 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1287 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1288 assert(ply >= 0 && ply < PLY_MAX);
1289 assert(threadID >= 0 && threadID < TM.active_threads());
1291 Move movesSearched[256];
1296 Depth ext, newDepth;
1297 Value bestValue, refinedValue, nullValue, value, futilityValueScaled;
1298 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1299 bool mateThreat = false;
1301 refinedValue = bestValue = value = -VALUE_INFINITE;
1304 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1306 // Step 1. Initialize node and poll
1307 // Polling can abort search.
1308 init_node(ss, ply, threadID);
1310 // Step 2. Check for aborted search and immediate draw
1311 if (AbortSearch || TM.thread_should_stop(threadID))
1314 if (pos.is_draw() || ply >= PLY_MAX - 1)
1317 // Step 3. Mate distance pruning
1318 if (value_mated_in(ply) >= beta)
1321 if (value_mate_in(ply + 1) < beta)
1324 // Step 4. Transposition table lookup
1326 // We don't want the score of a partial search to overwrite a previous full search
1327 // TT value, so we use a different position key in case of an excluded move exists.
1328 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1330 tte = TT.retrieve(posKey);
1331 ttMove = (tte ? tte->move() : MOVE_NONE);
1333 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1335 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1336 return value_from_tt(tte->value(), ply);
1339 // Step 5. Evaluate the position statically
1340 isCheck = pos.is_check();
1344 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1345 ss[ply].eval = value_from_tt(tte->value(), ply);
1347 ss[ply].eval = evaluate(pos, ei, threadID);
1349 refinedValue = refine_eval(tte, ss[ply].eval, ply); // Enhance accuracy with TT value if possible
1350 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1354 if ( !value_is_mate(beta)
1356 && depth < RazorDepth
1357 && refinedValue < beta - razor_margin(depth)
1358 && ss[ply - 1].currentMove != MOVE_NULL
1359 && ttMove == MOVE_NONE
1360 && !pos.has_pawn_on_7th(pos.side_to_move()))
1362 Value rbeta = beta - razor_margin(depth);
1363 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1365 // Logically we should return (v + razor_margin(depth)), but
1366 // surprisingly this did slightly weaker in tests.
1370 // Step 7. Static null move pruning
1371 // We're betting that the opponent doesn't have a move that will reduce
1372 // the score by more than fuility_margin(depth) if we do a null move.
1375 && depth < RazorDepth
1376 && refinedValue - futility_margin(depth, 0) >= beta)
1377 return refinedValue - futility_margin(depth, 0);
1379 // Step 8. Null move search with verification search
1380 // When we jump directly to qsearch() we do a null move only if static value is
1381 // at least beta. Otherwise we do a null move if static value is not more than
1382 // NullMoveMargin under beta.
1386 && !value_is_mate(beta)
1387 && ok_to_do_nullmove(pos)
1388 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0))
1390 ss[ply].currentMove = MOVE_NULL;
1392 pos.do_null_move(st);
1394 // Null move dynamic reduction based on depth
1395 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1397 // Null move dynamic reduction based on value
1398 if (refinedValue - beta > PawnValueMidgame)
1401 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1403 pos.undo_null_move();
1405 if (nullValue >= beta)
1407 // Do not return unproven mate scores
1408 if (nullValue >= value_mate_in(PLY_MAX))
1411 if (depth < 6 * OnePly)
1414 // Do zugzwang verification search
1415 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1419 // The null move failed low, which means that we may be faced with
1420 // some kind of threat. If the previous move was reduced, check if
1421 // the move that refuted the null move was somehow connected to the
1422 // move which was reduced. If a connection is found, return a fail
1423 // low score (which will cause the reduced move to fail high in the
1424 // parent node, which will trigger a re-search with full depth).
1425 if (nullValue == value_mated_in(ply + 2))
1428 ss[ply].threatMove = ss[ply + 1].currentMove;
1429 if ( depth < ThreatDepth
1430 && ss[ply - 1].reduction
1431 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1436 // Step 9. Internal iterative deepening
1437 if ( depth >= IIDDepthAtNonPVNodes
1438 && ttMove == MOVE_NONE
1440 && ss[ply].eval >= beta - IIDMargin)
1442 search(pos, ss, beta, depth/2, ply, false, threadID);
1443 ttMove = ss[ply].pv[ply];
1444 tte = TT.retrieve(posKey);
1447 // Step 10. Loop through moves
1448 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1450 // Initialize a MovePicker object for the current position
1451 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply], beta);
1454 while ( bestValue < beta
1455 && (move = mp.get_next_move()) != MOVE_NONE
1456 && !TM.thread_should_stop(threadID))
1458 assert(move_is_ok(move));
1460 if (move == excludedMove)
1463 moveIsCheck = pos.move_is_check(move, ci);
1464 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1465 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1467 // Step 11. Decide the new search depth
1468 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1470 // Singular extension search. We extend the TT move if its value is much better than
1471 // its siblings. To verify this we do a reduced search on all the other moves but the
1472 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1473 if ( depth >= SingularExtensionDepthAtNonPVNodes
1475 && move == tte->move()
1476 && !excludedMove // Do not allow recursive single-reply search
1478 && is_lower_bound(tte->type())
1479 && tte->depth() >= depth - 3 * OnePly)
1481 Value ttValue = value_from_tt(tte->value(), ply);
1483 if (abs(ttValue) < VALUE_KNOWN_WIN)
1485 Value excValue = search(pos, ss, ttValue - SingularExtensionMargin, depth / 2, ply, false, threadID, move);
1487 if (excValue < ttValue - SingularExtensionMargin)
1492 newDepth = depth - OnePly + ext;
1494 // Update current move (this must be done after singular extension search)
1495 movesSearched[moveCount++] = ss[ply].currentMove = move;
1497 // Step 12. Futility pruning
1500 && !captureOrPromotion
1501 && !move_is_castle(move)
1504 // Move count based pruning
1505 if ( moveCount >= futility_move_count(depth)
1506 && ok_to_prune(pos, move, ss[ply].threatMove)
1507 && bestValue > value_mated_in(PLY_MAX))
1510 // Value based pruning
1511 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); // We illogically ignore reduction condition depth >= 3*OnePly
1512 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount)
1513 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1515 if (futilityValueScaled < beta)
1517 if (futilityValueScaled > bestValue)
1518 bestValue = futilityValueScaled;
1523 // Step 13. Make the move
1524 pos.do_move(move, st, ci, moveIsCheck);
1526 // Step 14. Reduced search
1527 // if the move fails high will be re-searched at full depth.
1528 bool doFullDepthSearch = true;
1530 if ( depth >= 3*OnePly
1532 && !captureOrPromotion
1533 && !move_is_castle(move)
1534 && !move_is_killer(move, ss[ply]))
1536 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1537 if (ss[ply].reduction)
1539 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1540 doFullDepthSearch = (value >= beta);
1544 // Step 15. Full depth search
1545 if (doFullDepthSearch)
1547 ss[ply].reduction = Depth(0);
1548 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1551 // Step 16. Undo move
1552 pos.undo_move(move);
1554 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1556 // Step 17. Check for new best move
1557 if (value > bestValue)
1563 if (value == value_mate_in(ply + 1))
1564 ss[ply].mateKiller = move;
1567 // Step 18. Check for split
1568 if ( TM.active_threads() > 1
1570 && depth >= MinimumSplitDepth
1572 && TM.available_thread_exists(threadID)
1574 && !TM.thread_should_stop(threadID)
1575 && TM.split(pos, ss, ply, NULL, beta, &bestValue,
1576 depth, mateThreat, &moveCount, &mp, threadID, false))
1580 // Step 19. Check for mate and stalemate
1581 // All legal moves have been searched and if there were
1582 // no legal moves, it must be mate or stalemate.
1583 // If one move was excluded return fail low.
1585 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1587 // Step 20. Update tables
1588 // If the search is not aborted, update the transposition table,
1589 // history counters, and killer moves.
1590 if (AbortSearch || TM.thread_should_stop(threadID))
1593 if (bestValue < beta)
1594 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1597 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1598 move = ss[ply].pv[ply];
1599 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1600 if (!pos.move_is_capture_or_promotion(move))
1602 update_history(pos, move, depth, movesSearched, moveCount);
1603 update_killers(move, ss[ply]);
1608 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1614 // qsearch() is the quiescence search function, which is called by the main
1615 // search function when the remaining depth is zero (or, to be more precise,
1616 // less than OnePly).
1618 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1619 Depth depth, int ply, int threadID) {
1621 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1622 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1624 assert(ply >= 0 && ply < PLY_MAX);
1625 assert(threadID >= 0 && threadID < TM.active_threads());
1630 Value staticValue, bestValue, value, futilityBase, futilityValue;
1631 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1632 const TTEntry* tte = NULL;
1634 bool pvNode = (beta - alpha != 1);
1635 Value oldAlpha = alpha;
1637 // Initialize, and make an early exit in case of an aborted search,
1638 // an instant draw, maximum ply reached, etc.
1639 init_node(ss, ply, threadID);
1641 // After init_node() that calls poll()
1642 if (AbortSearch || TM.thread_should_stop(threadID))
1645 if (pos.is_draw() || ply >= PLY_MAX - 1)
1648 // Transposition table lookup. At PV nodes, we don't use the TT for
1649 // pruning, but only for move ordering.
1650 tte = TT.retrieve(pos.get_key());
1651 ttMove = (tte ? tte->move() : MOVE_NONE);
1653 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1655 assert(tte->type() != VALUE_TYPE_EVAL);
1657 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1658 return value_from_tt(tte->value(), ply);
1661 isCheck = pos.is_check();
1663 // Evaluate the position statically
1665 staticValue = -VALUE_INFINITE;
1666 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1667 staticValue = value_from_tt(tte->value(), ply);
1669 staticValue = evaluate(pos, ei, threadID);
1673 ss[ply].eval = staticValue;
1674 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1677 // Initialize "stand pat score", and return it immediately if it is
1679 bestValue = staticValue;
1681 if (bestValue >= beta)
1683 // Store the score to avoid a future costly evaluation() call
1684 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1685 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1690 if (bestValue > alpha)
1693 // If we are near beta then try to get a cutoff pushing checks a bit further
1694 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1696 // Initialize a MovePicker object for the current position, and prepare
1697 // to search the moves. Because the depth is <= 0 here, only captures,
1698 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1699 // and we are near beta) will be generated.
1700 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1702 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1703 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1705 // Loop through the moves until no moves remain or a beta cutoff
1707 while ( alpha < beta
1708 && (move = mp.get_next_move()) != MOVE_NONE)
1710 assert(move_is_ok(move));
1712 moveIsCheck = pos.move_is_check(move, ci);
1714 // Update current move
1716 ss[ply].currentMove = move;
1724 && !move_is_promotion(move)
1725 && !pos.move_is_passed_pawn_push(move))
1727 futilityValue = futilityBase
1728 + pos.endgame_value_of_piece_on(move_to(move))
1729 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1731 if (futilityValue < alpha)
1733 if (futilityValue > bestValue)
1734 bestValue = futilityValue;
1739 // Detect blocking evasions that are candidate to be pruned
1740 evasionPrunable = isCheck
1741 && bestValue != -VALUE_INFINITE
1742 && !pos.move_is_capture(move)
1743 && pos.type_of_piece_on(move_from(move)) != KING
1744 && !pos.can_castle(pos.side_to_move());
1746 // Don't search moves with negative SEE values
1747 if ( (!isCheck || evasionPrunable)
1750 && !move_is_promotion(move)
1751 && pos.see_sign(move) < 0)
1754 // Make and search the move
1755 pos.do_move(move, st, ci, moveIsCheck);
1756 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1757 pos.undo_move(move);
1759 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1762 if (value > bestValue)
1773 // All legal moves have been searched. A special case: If we're in check
1774 // and no legal moves were found, it is checkmate.
1775 if (!moveCount && pos.is_check()) // Mate!
1776 return value_mated_in(ply);
1778 // Update transposition table
1779 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1780 if (bestValue <= oldAlpha)
1782 // If bestValue isn't changed it means it is still the static evaluation
1783 // of the node, so keep this info to avoid a future evaluation() call.
1784 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1785 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1787 else if (bestValue >= beta)
1789 move = ss[ply].pv[ply];
1790 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1792 // Update killers only for good checking moves
1793 if (!pos.move_is_capture_or_promotion(move))
1794 update_killers(move, ss[ply]);
1797 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1799 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1805 // sp_search() is used to search from a split point. This function is called
1806 // by each thread working at the split point. It is similar to the normal
1807 // search() function, but simpler. Because we have already probed the hash
1808 // table, done a null move search, and searched the first move before
1809 // splitting, we don't have to repeat all this work in sp_search(). We
1810 // also don't need to store anything to the hash table here: This is taken
1811 // care of after we return from the split point.
1813 void sp_search(SplitPoint* sp, int threadID) {
1815 assert(threadID >= 0 && threadID < TM.active_threads());
1816 assert(TM.active_threads() > 1);
1820 Depth ext, newDepth;
1821 Value value, futilityValueScaled;
1822 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1824 value = -VALUE_INFINITE;
1826 Position pos(*sp->pos);
1828 SearchStack* ss = sp->sstack[threadID];
1829 isCheck = pos.is_check();
1831 // Step 10. Loop through moves
1832 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1833 lock_grab(&(sp->lock));
1835 while ( sp->bestValue < sp->beta
1836 && !TM.thread_should_stop(threadID)
1837 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1839 moveCount = ++sp->moves;
1840 lock_release(&(sp->lock));
1842 assert(move_is_ok(move));
1844 moveIsCheck = pos.move_is_check(move, ci);
1845 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1847 // Step 11. Decide the new search depth
1848 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1849 newDepth = sp->depth - OnePly + ext;
1851 // Update current move
1852 ss[sp->ply].currentMove = move;
1854 // Step 12. Futility pruning
1857 && !captureOrPromotion
1858 && !move_is_castle(move))
1860 // Move count based pruning
1861 if ( moveCount >= futility_move_count(sp->depth)
1862 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1863 && sp->bestValue > value_mated_in(PLY_MAX))
1865 lock_grab(&(sp->lock));
1869 // Value based pruning
1870 Depth predictedDepth = newDepth - nonpv_reduction(sp->depth, moveCount);
1871 futilityValueScaled = ss[sp->ply].eval + futility_margin(predictedDepth, moveCount)
1872 + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1874 if (futilityValueScaled < sp->beta)
1876 lock_grab(&(sp->lock));
1878 if (futilityValueScaled > sp->bestValue)
1879 sp->bestValue = futilityValueScaled;
1884 // Step 13. Make the move
1885 pos.do_move(move, st, ci, moveIsCheck);
1887 // Step 14. Reduced search
1888 // if the move fails high will be re-searched at full depth.
1889 bool doFullDepthSearch = true;
1892 && !captureOrPromotion
1893 && !move_is_castle(move)
1894 && !move_is_killer(move, ss[sp->ply]))
1896 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1897 if (ss[sp->ply].reduction)
1899 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1900 doFullDepthSearch = (value >= sp->beta && !TM.thread_should_stop(threadID));
1904 // Step 15. Full depth search
1905 if (doFullDepthSearch)
1907 ss[sp->ply].reduction = Depth(0);
1908 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1911 // Step 16. Undo move
1912 pos.undo_move(move);
1914 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1916 // Step 17. Check for new best move
1917 lock_grab(&(sp->lock));
1919 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1921 sp->bestValue = value;
1922 if (sp->bestValue >= sp->beta)
1924 sp->stopRequest = true;
1925 sp_update_pv(sp->parentSstack, ss, sp->ply);
1930 /* Here we have the lock still grabbed */
1932 sp->slaves[threadID] = 0;
1935 lock_release(&(sp->lock));
1939 // sp_search_pv() is used to search from a PV split point. This function
1940 // is called by each thread working at the split point. It is similar to
1941 // the normal search_pv() function, but simpler. Because we have already
1942 // probed the hash table and searched the first move before splitting, we
1943 // don't have to repeat all this work in sp_search_pv(). We also don't
1944 // need to store anything to the hash table here: This is taken care of
1945 // after we return from the split point.
1947 void sp_search_pv(SplitPoint* sp, int threadID) {
1949 assert(threadID >= 0 && threadID < TM.active_threads());
1950 assert(TM.active_threads() > 1);
1954 Depth ext, newDepth;
1956 bool moveIsCheck, captureOrPromotion, dangerous;
1958 value = -VALUE_INFINITE;
1960 Position pos(*sp->pos);
1962 SearchStack* ss = sp->sstack[threadID];
1964 // Step 10. Loop through moves
1965 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1966 lock_grab(&(sp->lock));
1968 while ( sp->alpha < sp->beta
1969 && !TM.thread_should_stop(threadID)
1970 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1972 moveCount = ++sp->moves;
1973 lock_release(&(sp->lock));
1975 assert(move_is_ok(move));
1977 moveIsCheck = pos.move_is_check(move, ci);
1978 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1980 // Step 11. Decide the new search depth
1981 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1982 newDepth = sp->depth - OnePly + ext;
1984 // Update current move
1985 ss[sp->ply].currentMove = move;
1987 // Step 12. Futility pruning (is omitted in PV nodes)
1989 // Step 13. Make the move
1990 pos.do_move(move, st, ci, moveIsCheck);
1992 // Step 14. Reduced search
1993 // if the move fails high will be re-searched at full depth.
1994 bool doFullDepthSearch = true;
1997 && !captureOrPromotion
1998 && !move_is_castle(move)
1999 && !move_is_killer(move, ss[sp->ply]))
2001 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
2002 if (ss[sp->ply].reduction)
2004 Value localAlpha = sp->alpha;
2005 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2006 doFullDepthSearch = (value > localAlpha && !TM.thread_should_stop(threadID));
2010 // Step 15. Full depth search
2011 if (doFullDepthSearch)
2013 Value localAlpha = sp->alpha;
2014 ss[sp->ply].reduction = Depth(0);
2015 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2017 if (value > localAlpha && value < sp->beta && !TM.thread_should_stop(threadID))
2019 // If another thread has failed high then sp->alpha has been increased
2020 // to be higher or equal then beta, if so, avoid to start a PV search.
2021 localAlpha = sp->alpha;
2022 if (localAlpha < sp->beta)
2023 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2027 // Step 16. Undo move
2028 pos.undo_move(move);
2030 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2032 // Step 17. Check for new best move
2033 lock_grab(&(sp->lock));
2035 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
2037 sp->bestValue = value;
2038 if (value > sp->alpha)
2040 // Ask threads to stop before to modify sp->alpha
2041 if (value >= sp->beta)
2042 sp->stopRequest = true;
2046 sp_update_pv(sp->parentSstack, ss, sp->ply);
2047 if (value == value_mate_in(sp->ply + 1))
2048 ss[sp->ply].mateKiller = move;
2053 /* Here we have the lock still grabbed */
2055 sp->slaves[threadID] = 0;
2058 lock_release(&(sp->lock));
2062 // init_node() is called at the beginning of all the search functions
2063 // (search(), search_pv(), qsearch(), and so on) and initializes the
2064 // search stack object corresponding to the current node. Once every
2065 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2066 // for user input and checks whether it is time to stop the search.
2068 void init_node(SearchStack ss[], int ply, int threadID) {
2070 assert(ply >= 0 && ply < PLY_MAX);
2071 assert(threadID >= 0 && threadID < TM.active_threads());
2073 TM.incrementNodeCounter(threadID);
2078 if (NodesSincePoll >= NodesBetweenPolls)
2085 ss[ply + 2].initKillers();
2089 // update_pv() is called whenever a search returns a value > alpha.
2090 // It updates the PV in the SearchStack object corresponding to the
2093 void update_pv(SearchStack ss[], int ply) {
2095 assert(ply >= 0 && ply < PLY_MAX);
2099 ss[ply].pv[ply] = ss[ply].currentMove;
2101 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2102 ss[ply].pv[p] = ss[ply + 1].pv[p];
2104 ss[ply].pv[p] = MOVE_NONE;
2108 // sp_update_pv() is a variant of update_pv for use at split points. The
2109 // difference between the two functions is that sp_update_pv also updates
2110 // the PV at the parent node.
2112 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2114 assert(ply >= 0 && ply < PLY_MAX);
2118 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2120 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2121 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2123 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2127 // connected_moves() tests whether two moves are 'connected' in the sense
2128 // that the first move somehow made the second move possible (for instance
2129 // if the moving piece is the same in both moves). The first move is assumed
2130 // to be the move that was made to reach the current position, while the
2131 // second move is assumed to be a move from the current position.
2133 bool connected_moves(const Position& pos, Move m1, Move m2) {
2135 Square f1, t1, f2, t2;
2138 assert(move_is_ok(m1));
2139 assert(move_is_ok(m2));
2141 if (m2 == MOVE_NONE)
2144 // Case 1: The moving piece is the same in both moves
2150 // Case 2: The destination square for m2 was vacated by m1
2156 // Case 3: Moving through the vacated square
2157 if ( piece_is_slider(pos.piece_on(f2))
2158 && bit_is_set(squares_between(f2, t2), f1))
2161 // Case 4: The destination square for m2 is defended by the moving piece in m1
2162 p = pos.piece_on(t1);
2163 if (bit_is_set(pos.attacks_from(p, t1), t2))
2166 // Case 5: Discovered check, checking piece is the piece moved in m1
2167 if ( piece_is_slider(p)
2168 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2169 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2171 // discovered_check_candidates() works also if the Position's side to
2172 // move is the opposite of the checking piece.
2173 Color them = opposite_color(pos.side_to_move());
2174 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2176 if (bit_is_set(dcCandidates, f2))
2183 // value_is_mate() checks if the given value is a mate one
2184 // eventually compensated for the ply.
2186 bool value_is_mate(Value value) {
2188 assert(abs(value) <= VALUE_INFINITE);
2190 return value <= value_mated_in(PLY_MAX)
2191 || value >= value_mate_in(PLY_MAX);
2195 // move_is_killer() checks if the given move is among the
2196 // killer moves of that ply.
2198 bool move_is_killer(Move m, const SearchStack& ss) {
2200 const Move* k = ss.killers;
2201 for (int i = 0; i < KILLER_MAX; i++, k++)
2209 // extension() decides whether a move should be searched with normal depth,
2210 // or with extended depth. Certain classes of moves (checking moves, in
2211 // particular) are searched with bigger depth than ordinary moves and in
2212 // any case are marked as 'dangerous'. Note that also if a move is not
2213 // extended, as example because the corresponding UCI option is set to zero,
2214 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2216 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2217 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2219 assert(m != MOVE_NONE);
2221 Depth result = Depth(0);
2222 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2227 result += CheckExtension[pvNode];
2230 result += SingleEvasionExtension[pvNode];
2233 result += MateThreatExtension[pvNode];
2236 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2238 Color c = pos.side_to_move();
2239 if (relative_rank(c, move_to(m)) == RANK_7)
2241 result += PawnPushTo7thExtension[pvNode];
2244 if (pos.pawn_is_passed(c, move_to(m)))
2246 result += PassedPawnExtension[pvNode];
2251 if ( captureOrPromotion
2252 && pos.type_of_piece_on(move_to(m)) != PAWN
2253 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2254 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2255 && !move_is_promotion(m)
2258 result += PawnEndgameExtension[pvNode];
2263 && captureOrPromotion
2264 && pos.type_of_piece_on(move_to(m)) != PAWN
2265 && pos.see_sign(m) >= 0)
2271 return Min(result, OnePly);
2275 // ok_to_do_nullmove() looks at the current position and decides whether
2276 // doing a 'null move' should be allowed. In order to avoid zugzwang
2277 // problems, null moves are not allowed when the side to move has very
2278 // little material left. Currently, the test is a bit too simple: Null
2279 // moves are avoided only when the side to move has only pawns left.
2280 // It's probably a good idea to avoid null moves in at least some more
2281 // complicated endgames, e.g. KQ vs KR. FIXME
2283 bool ok_to_do_nullmove(const Position& pos) {
2285 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2289 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2290 // non-tactical moves late in the move list close to the leaves are
2291 // candidates for pruning.
2293 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2295 assert(move_is_ok(m));
2296 assert(threat == MOVE_NONE || move_is_ok(threat));
2297 assert(!pos.move_is_check(m));
2298 assert(!pos.move_is_capture_or_promotion(m));
2299 assert(!pos.move_is_passed_pawn_push(m));
2301 Square mfrom, mto, tfrom, tto;
2303 // Prune if there isn't any threat move
2304 if (threat == MOVE_NONE)
2307 mfrom = move_from(m);
2309 tfrom = move_from(threat);
2310 tto = move_to(threat);
2312 // Case 1: Don't prune moves which move the threatened piece
2316 // Case 2: If the threatened piece has value less than or equal to the
2317 // value of the threatening piece, don't prune move which defend it.
2318 if ( pos.move_is_capture(threat)
2319 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2320 || pos.type_of_piece_on(tfrom) == KING)
2321 && pos.move_attacks_square(m, tto))
2324 // Case 3: If the moving piece in the threatened move is a slider, don't
2325 // prune safe moves which block its ray.
2326 if ( piece_is_slider(pos.piece_on(tfrom))
2327 && bit_is_set(squares_between(tfrom, tto), mto)
2328 && pos.see_sign(m) >= 0)
2335 // ok_to_use_TT() returns true if a transposition table score
2336 // can be used at a given point in search.
2338 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2340 Value v = value_from_tt(tte->value(), ply);
2342 return ( tte->depth() >= depth
2343 || v >= Max(value_mate_in(PLY_MAX), beta)
2344 || v < Min(value_mated_in(PLY_MAX), beta))
2346 && ( (is_lower_bound(tte->type()) && v >= beta)
2347 || (is_upper_bound(tte->type()) && v < beta));
2351 // refine_eval() returns the transposition table score if
2352 // possible otherwise falls back on static position evaluation.
2354 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2359 Value v = value_from_tt(tte->value(), ply);
2361 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2362 || (is_upper_bound(tte->type()) && v < defaultEval))
2369 // update_history() registers a good move that produced a beta-cutoff
2370 // in history and marks as failures all the other moves of that ply.
2372 void update_history(const Position& pos, Move move, Depth depth,
2373 Move movesSearched[], int moveCount) {
2377 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2379 for (int i = 0; i < moveCount - 1; i++)
2381 m = movesSearched[i];
2385 if (!pos.move_is_capture_or_promotion(m))
2386 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2391 // update_killers() add a good move that produced a beta-cutoff
2392 // among the killer moves of that ply.
2394 void update_killers(Move m, SearchStack& ss) {
2396 if (m == ss.killers[0])
2399 for (int i = KILLER_MAX - 1; i > 0; i--)
2400 ss.killers[i] = ss.killers[i - 1];
2406 // update_gains() updates the gains table of a non-capture move given
2407 // the static position evaluation before and after the move.
2409 void update_gains(const Position& pos, Move m, Value before, Value after) {
2412 && before != VALUE_NONE
2413 && after != VALUE_NONE
2414 && pos.captured_piece() == NO_PIECE_TYPE
2415 && !move_is_castle(m)
2416 && !move_is_promotion(m))
2417 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2421 // current_search_time() returns the number of milliseconds which have passed
2422 // since the beginning of the current search.
2424 int current_search_time() {
2426 return get_system_time() - SearchStartTime;
2430 // nps() computes the current nodes/second count.
2434 int t = current_search_time();
2435 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2439 // poll() performs two different functions: It polls for user input, and it
2440 // looks at the time consumed so far and decides if it's time to abort the
2443 void poll(SearchStack ss[], int ply) {
2445 static int lastInfoTime;
2446 int t = current_search_time();
2451 // We are line oriented, don't read single chars
2452 std::string command;
2454 if (!std::getline(std::cin, command))
2457 if (command == "quit")
2460 PonderSearch = false;
2464 else if (command == "stop")
2467 PonderSearch = false;
2469 else if (command == "ponderhit")
2473 // Print search information
2477 else if (lastInfoTime > t)
2478 // HACK: Must be a new search where we searched less than
2479 // NodesBetweenPolls nodes during the first second of search.
2482 else if (t - lastInfoTime >= 1000)
2489 if (dbg_show_hit_rate)
2490 dbg_print_hit_rate();
2492 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2493 << " time " << t << " hashfull " << TT.full() << endl;
2495 // We only support current line printing in single thread mode
2496 if (ShowCurrentLine && TM.active_threads() == 1)
2498 cout << "info currline";
2499 for (int p = 0; p < ply; p++)
2500 cout << " " << ss[p].currentMove;
2506 // Should we stop the search?
2510 bool stillAtFirstMove = FirstRootMove
2511 && !AspirationFailLow
2512 && t > MaxSearchTime + ExtraSearchTime;
2514 bool noMoreTime = t > AbsoluteMaxSearchTime
2515 || stillAtFirstMove;
2517 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2518 || (ExactMaxTime && t >= ExactMaxTime)
2519 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2524 // ponderhit() is called when the program is pondering (i.e. thinking while
2525 // it's the opponent's turn to move) in order to let the engine know that
2526 // it correctly predicted the opponent's move.
2530 int t = current_search_time();
2531 PonderSearch = false;
2533 bool stillAtFirstMove = FirstRootMove
2534 && !AspirationFailLow
2535 && t > MaxSearchTime + ExtraSearchTime;
2537 bool noMoreTime = t > AbsoluteMaxSearchTime
2538 || stillAtFirstMove;
2540 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2545 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2547 void init_ss_array(SearchStack ss[]) {
2549 for (int i = 0; i < 3; i++)
2552 ss[i].initKillers();
2557 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2558 // while the program is pondering. The point is to work around a wrinkle in
2559 // the UCI protocol: When pondering, the engine is not allowed to give a
2560 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2561 // We simply wait here until one of these commands is sent, and return,
2562 // after which the bestmove and pondermove will be printed (in id_loop()).
2564 void wait_for_stop_or_ponderhit() {
2566 std::string command;
2570 if (!std::getline(std::cin, command))
2573 if (command == "quit")
2578 else if (command == "ponderhit" || command == "stop")
2584 // print_pv_info() prints to standard output and eventually to log file information on
2585 // the current PV line. It is called at each iteration or after a new pv is found.
2587 void print_pv_info(const Position& pos, SearchStack ss[], Value alpha, Value beta, Value value) {
2589 cout << "info depth " << Iteration
2590 << " score " << value_to_string(value)
2591 << ((value >= beta) ? " lowerbound" :
2592 ((value <= alpha)? " upperbound" : ""))
2593 << " time " << current_search_time()
2594 << " nodes " << TM.nodes_searched()
2598 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
2599 cout << ss[0].pv[j] << " ";
2605 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
2606 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
2608 LogFile << pretty_pv(pos, current_search_time(), Iteration,
2609 TM.nodes_searched(), value, type, ss[0].pv) << endl;
2614 // init_thread() is the function which is called when a new thread is
2615 // launched. It simply calls the idle_loop() function with the supplied
2616 // threadID. There are two versions of this function; one for POSIX
2617 // threads and one for Windows threads.
2619 #if !defined(_MSC_VER)
2621 void* init_thread(void *threadID) {
2623 TM.idle_loop(*(int*)threadID, NULL);
2629 DWORD WINAPI init_thread(LPVOID threadID) {
2631 TM.idle_loop(*(int*)threadID, NULL);
2638 /// The ThreadsManager class
2640 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2641 // get_beta_counters() are getters/setters for the per thread
2642 // counters used to sort the moves at root.
2644 void ThreadsManager::resetNodeCounters() {
2646 for (int i = 0; i < MAX_THREADS; i++)
2647 threads[i].nodes = 0ULL;
2650 void ThreadsManager::resetBetaCounters() {
2652 for (int i = 0; i < MAX_THREADS; i++)
2653 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2656 int64_t ThreadsManager::nodes_searched() const {
2658 int64_t result = 0ULL;
2659 for (int i = 0; i < ActiveThreads; i++)
2660 result += threads[i].nodes;
2665 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2668 for (int i = 0; i < MAX_THREADS; i++)
2670 our += threads[i].betaCutOffs[us];
2671 their += threads[i].betaCutOffs[opposite_color(us)];
2676 // idle_loop() is where the threads are parked when they have no work to do.
2677 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2678 // object for which the current thread is the master.
2680 void ThreadsManager::idle_loop(int threadID, SplitPoint* waitSp) {
2682 assert(threadID >= 0 && threadID < MAX_THREADS);
2686 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2687 // master should exit as last one.
2688 if (AllThreadsShouldExit)
2691 threads[threadID].state = THREAD_TERMINATED;
2695 // If we are not thinking, wait for a condition to be signaled
2696 // instead of wasting CPU time polling for work.
2697 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2700 assert(threadID != 0);
2701 threads[threadID].state = THREAD_SLEEPING;
2703 #if !defined(_MSC_VER)
2704 lock_grab(&WaitLock);
2705 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2706 pthread_cond_wait(&WaitCond, &WaitLock);
2707 lock_release(&WaitLock);
2709 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2713 // If thread has just woken up, mark it as available
2714 if (threads[threadID].state == THREAD_SLEEPING)
2715 threads[threadID].state = THREAD_AVAILABLE;
2717 // If this thread has been assigned work, launch a search
2718 if (threads[threadID].state == THREAD_WORKISWAITING)
2720 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2722 threads[threadID].state = THREAD_SEARCHING;
2724 if (threads[threadID].splitPoint->pvNode)
2725 sp_search_pv(threads[threadID].splitPoint, threadID);
2727 sp_search(threads[threadID].splitPoint, threadID);
2729 assert(threads[threadID].state == THREAD_SEARCHING);
2731 threads[threadID].state = THREAD_AVAILABLE;
2734 // If this thread is the master of a split point and all threads have
2735 // finished their work at this split point, return from the idle loop.
2736 if (waitSp != NULL && waitSp->cpus == 0)
2738 assert(threads[threadID].state == THREAD_AVAILABLE);
2740 threads[threadID].state = THREAD_SEARCHING;
2747 // init_threads() is called during startup. It launches all helper threads,
2748 // and initializes the split point stack and the global locks and condition
2751 void ThreadsManager::init_threads() {
2756 #if !defined(_MSC_VER)
2757 pthread_t pthread[1];
2760 // Initialize global locks
2761 lock_init(&MPLock, NULL);
2762 lock_init(&WaitLock, NULL);
2764 #if !defined(_MSC_VER)
2765 pthread_cond_init(&WaitCond, NULL);
2767 for (i = 0; i < MAX_THREADS; i++)
2768 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2771 // Initialize SplitPointStack locks
2772 for (i = 0; i < MAX_THREADS; i++)
2773 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2775 SplitPointStack[i][j].parent = NULL;
2776 lock_init(&(SplitPointStack[i][j].lock), NULL);
2779 // Will be set just before program exits to properly end the threads
2780 AllThreadsShouldExit = false;
2782 // Threads will be put to sleep as soon as created
2783 AllThreadsShouldSleep = true;
2785 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2787 threads[0].state = THREAD_SEARCHING;
2788 for (i = 1; i < MAX_THREADS; i++)
2789 threads[i].state = THREAD_AVAILABLE;
2791 // Launch the helper threads
2792 for (i = 1; i < MAX_THREADS; i++)
2795 #if !defined(_MSC_VER)
2796 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2798 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2803 cout << "Failed to create thread number " << i << endl;
2804 Application::exit_with_failure();
2807 // Wait until the thread has finished launching and is gone to sleep
2808 while (threads[i].state != THREAD_SLEEPING);
2813 // exit_threads() is called when the program exits. It makes all the
2814 // helper threads exit cleanly.
2816 void ThreadsManager::exit_threads() {
2818 ActiveThreads = MAX_THREADS; // HACK
2819 AllThreadsShouldSleep = true; // HACK
2820 wake_sleeping_threads();
2822 // This makes the threads to exit idle_loop()
2823 AllThreadsShouldExit = true;
2825 // Wait for thread termination
2826 for (int i = 1; i < MAX_THREADS; i++)
2827 while (threads[i].state != THREAD_TERMINATED);
2829 // Now we can safely destroy the locks
2830 for (int i = 0; i < MAX_THREADS; i++)
2831 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2832 lock_destroy(&(SplitPointStack[i][j].lock));
2834 lock_destroy(&WaitLock);
2835 lock_destroy(&MPLock);
2839 // thread_should_stop() checks whether the thread should stop its search.
2840 // This can happen if a beta cutoff has occurred in the thread's currently
2841 // active split point, or in some ancestor of the current split point.
2843 bool ThreadsManager::thread_should_stop(int threadID) const {
2845 assert(threadID >= 0 && threadID < ActiveThreads);
2849 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent);
2854 // thread_is_available() checks whether the thread with threadID "slave" is
2855 // available to help the thread with threadID "master" at a split point. An
2856 // obvious requirement is that "slave" must be idle. With more than two
2857 // threads, this is not by itself sufficient: If "slave" is the master of
2858 // some active split point, it is only available as a slave to the other
2859 // threads which are busy searching the split point at the top of "slave"'s
2860 // split point stack (the "helpful master concept" in YBWC terminology).
2862 bool ThreadsManager::thread_is_available(int slave, int master) const {
2864 assert(slave >= 0 && slave < ActiveThreads);
2865 assert(master >= 0 && master < ActiveThreads);
2866 assert(ActiveThreads > 1);
2868 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2871 // Make a local copy to be sure doesn't change under our feet
2872 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2874 if (localActiveSplitPoints == 0)
2875 // No active split points means that the thread is available as
2876 // a slave for any other thread.
2879 if (ActiveThreads == 2)
2882 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2883 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2884 // could have been set to 0 by another thread leading to an out of bound access.
2885 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2892 // available_thread_exists() tries to find an idle thread which is available as
2893 // a slave for the thread with threadID "master".
2895 bool ThreadsManager::available_thread_exists(int master) const {
2897 assert(master >= 0 && master < ActiveThreads);
2898 assert(ActiveThreads > 1);
2900 for (int i = 0; i < ActiveThreads; i++)
2901 if (thread_is_available(i, master))
2908 // split() does the actual work of distributing the work at a node between
2909 // several threads at PV nodes. If it does not succeed in splitting the
2910 // node (because no idle threads are available, or because we have no unused
2911 // split point objects), the function immediately returns false. If
2912 // splitting is possible, a SplitPoint object is initialized with all the
2913 // data that must be copied to the helper threads (the current position and
2914 // search stack, alpha, beta, the search depth, etc.), and we tell our
2915 // helper threads that they have been assigned work. This will cause them
2916 // to instantly leave their idle loops and call sp_search_pv(). When all
2917 // threads have returned from sp_search_pv (or, equivalently, when
2918 // splitPoint->cpus becomes 0), split() returns true.
2920 bool ThreadsManager::split(const Position& p, SearchStack* sstck, int ply,
2921 Value* alpha, const Value beta, Value* bestValue,
2922 Depth depth, bool mateThreat, int* moves, MovePicker* mp, int master, bool pvNode) {
2925 assert(sstck != NULL);
2926 assert(ply >= 0 && ply < PLY_MAX);
2927 assert(*bestValue >= -VALUE_INFINITE);
2928 assert( ( pvNode && *bestValue <= *alpha)
2929 || (!pvNode && *bestValue < beta ));
2930 assert(!pvNode || *alpha < beta);
2931 assert(beta <= VALUE_INFINITE);
2932 assert(depth > Depth(0));
2933 assert(master >= 0 && master < ActiveThreads);
2934 assert(ActiveThreads > 1);
2936 SplitPoint* splitPoint;
2940 // If no other thread is available to help us, or if we have too many
2941 // active split points, don't split.
2942 if ( !available_thread_exists(master)
2943 || threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2945 lock_release(&MPLock);
2949 // Pick the next available split point object from the split point stack
2950 splitPoint = &SplitPointStack[master][threads[master].activeSplitPoints];
2952 // Initialize the split point object
2953 splitPoint->parent = threads[master].splitPoint;
2954 splitPoint->stopRequest = false;
2955 splitPoint->ply = ply;
2956 splitPoint->depth = depth;
2957 splitPoint->mateThreat = mateThreat;
2958 splitPoint->alpha = pvNode ? *alpha : beta - 1;
2959 splitPoint->beta = beta;
2960 splitPoint->pvNode = pvNode;
2961 splitPoint->bestValue = *bestValue;
2962 splitPoint->master = master;
2963 splitPoint->mp = mp;
2964 splitPoint->moves = *moves;
2965 splitPoint->cpus = 1;
2966 splitPoint->pos = &p;
2967 splitPoint->parentSstack = sstck;
2968 for (int i = 0; i < ActiveThreads; i++)
2969 splitPoint->slaves[i] = 0;
2971 threads[master].splitPoint = splitPoint;
2972 threads[master].activeSplitPoints++;
2974 // If we are here it means we are not available
2975 assert(threads[master].state != THREAD_AVAILABLE);
2977 // Allocate available threads setting state to THREAD_BOOKED
2978 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2979 if (thread_is_available(i, master))
2981 threads[i].state = THREAD_BOOKED;
2982 threads[i].splitPoint = splitPoint;
2983 splitPoint->slaves[i] = 1;
2987 assert(splitPoint->cpus > 1);
2989 // We can release the lock because slave threads are already booked and master is not available
2990 lock_release(&MPLock);
2992 // Tell the threads that they have work to do. This will make them leave
2993 // their idle loop. But before copy search stack tail for each thread.
2994 for (int i = 0; i < ActiveThreads; i++)
2995 if (i == master || splitPoint->slaves[i])
2997 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
2999 assert(i == master || threads[i].state == THREAD_BOOKED);
3001 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
3004 // Everything is set up. The master thread enters the idle loop, from
3005 // which it will instantly launch a search, because its state is
3006 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
3007 // idle loop, which means that the main thread will return from the idle
3008 // loop when all threads have finished their work at this split point
3009 // (i.e. when splitPoint->cpus == 0).
3010 idle_loop(master, splitPoint);
3012 // We have returned from the idle loop, which means that all threads are
3013 // finished. Update alpha, beta and bestValue, and return.
3017 *alpha = splitPoint->alpha;
3019 *bestValue = splitPoint->bestValue;
3020 threads[master].activeSplitPoints--;
3021 threads[master].splitPoint = splitPoint->parent;
3023 lock_release(&MPLock);
3028 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3029 // to start a new search from the root.
3031 void ThreadsManager::wake_sleeping_threads() {
3033 assert(AllThreadsShouldSleep);
3034 assert(ActiveThreads > 0);
3036 AllThreadsShouldSleep = false;
3038 if (ActiveThreads == 1)
3041 #if !defined(_MSC_VER)
3042 pthread_mutex_lock(&WaitLock);
3043 pthread_cond_broadcast(&WaitCond);
3044 pthread_mutex_unlock(&WaitLock);
3046 for (int i = 1; i < MAX_THREADS; i++)
3047 SetEvent(SitIdleEvent[i]);
3053 // put_threads_to_sleep() makes all the threads go to sleep just before
3054 // to leave think(), at the end of the search. Threads should have already
3055 // finished the job and should be idle.
3057 void ThreadsManager::put_threads_to_sleep() {
3059 assert(!AllThreadsShouldSleep);
3061 // This makes the threads to go to sleep
3062 AllThreadsShouldSleep = true;
3065 /// The RootMoveList class
3067 // RootMoveList c'tor
3069 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
3071 SearchStack ss[PLY_MAX_PLUS_2];
3072 MoveStack mlist[MaxRootMoves];
3074 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
3076 // Generate all legal moves
3077 MoveStack* last = generate_moves(pos, mlist);
3079 // Add each move to the moves[] array
3080 for (MoveStack* cur = mlist; cur != last; cur++)
3082 bool includeMove = includeAllMoves;
3084 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
3085 includeMove = (searchMoves[k] == cur->move);
3090 // Find a quick score for the move
3092 pos.do_move(cur->move, st);
3093 moves[count].move = cur->move;
3094 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
3095 moves[count].pv[0] = cur->move;
3096 moves[count].pv[1] = MOVE_NONE;
3097 pos.undo_move(cur->move);
3104 // RootMoveList simple methods definitions
3106 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
3108 moves[moveNum].nodes = nodes;
3109 moves[moveNum].cumulativeNodes += nodes;
3112 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
3114 moves[moveNum].ourBeta = our;
3115 moves[moveNum].theirBeta = their;
3118 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
3122 for (j = 0; pv[j] != MOVE_NONE; j++)
3123 moves[moveNum].pv[j] = pv[j];
3125 moves[moveNum].pv[j] = MOVE_NONE;
3129 // RootMoveList::sort() sorts the root move list at the beginning of a new
3132 void RootMoveList::sort() {
3134 sort_multipv(count - 1); // Sort all items
3138 // RootMoveList::sort_multipv() sorts the first few moves in the root move
3139 // list by their scores and depths. It is used to order the different PVs
3140 // correctly in MultiPV mode.
3142 void RootMoveList::sort_multipv(int n) {
3146 for (i = 1; i <= n; i++)
3148 RootMove rm = moves[i];
3149 for (j = i; j > 0 && moves[j - 1] < rm; j--)
3150 moves[j] = moves[j - 1];