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/>.
44 #include "ucioption.h"
50 //// Local definitions
56 enum NodeType { NonPV, PV };
58 // Set to true to force running with one thread.
59 // Used for debugging SMP code.
60 const bool FakeSplit = false;
62 // ThreadsManager class is used to handle all the threads related stuff in search,
63 // init, starting, parking and, the most important, launching a slave thread at a
64 // split point are what this class does. All the access to shared thread data is
65 // done through this class, so that we avoid using global variables instead.
67 class ThreadsManager {
68 /* As long as the single ThreadsManager object is defined as a global we don't
69 need to explicitly initialize to zero its data members because variables with
70 static storage duration are automatically set to zero before enter main()
76 int active_threads() const { return ActiveThreads; }
77 void set_active_threads(int newActiveThreads) { ActiveThreads = newActiveThreads; }
78 void incrementNodeCounter(int threadID) { threads[threadID].nodes++; }
79 void incrementBetaCounter(Color us, Depth d, int threadID) { threads[threadID].betaCutOffs[us] += unsigned(d); }
81 void resetNodeCounters();
82 void resetBetaCounters();
83 int64_t nodes_searched() const;
84 void get_beta_counters(Color us, int64_t& our, int64_t& their) const;
85 bool available_thread_exists(int master) const;
86 bool thread_is_available(int slave, int master) const;
87 bool thread_should_stop(int threadID) const;
88 void wake_sleeping_threads();
89 void put_threads_to_sleep();
90 void idle_loop(int threadID, SplitPoint* sp);
93 void split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
94 Depth depth, Move threatMove, bool mateThreat, int* moveCount, MovePicker* mp, bool pvNode);
100 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
101 Thread threads[MAX_THREADS];
103 Lock MPLock, WaitLock;
105 #if !defined(_MSC_VER)
106 pthread_cond_t WaitCond;
108 HANDLE SitIdleEvent[MAX_THREADS];
114 // RootMove struct is used for moves at the root at the tree. For each
115 // root move, we store a score, a node count, and a PV (really a refutation
116 // in the case of moves which fail low).
120 RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
122 // RootMove::operator<() is the comparison function used when
123 // sorting the moves. A move m1 is considered to be better
124 // than a move m2 if it has a higher score, or if the moves
125 // have equal score but m1 has the higher beta cut-off count.
126 bool operator<(const RootMove& m) const {
128 return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
133 int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
134 Move pv[PLY_MAX_PLUS_2];
138 // The RootMoveList class is essentially an array of RootMove objects, with
139 // a handful of methods for accessing the data in the individual moves.
144 RootMoveList(Position& pos, Move searchMoves[]);
146 int move_count() const { return count; }
147 Move get_move(int moveNum) const { return moves[moveNum].move; }
148 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
149 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
150 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
151 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
153 void set_move_nodes(int moveNum, int64_t nodes);
154 void set_beta_counters(int moveNum, int64_t our, int64_t their);
155 void set_move_pv(int moveNum, const Move pv[]);
157 void sort_multipv(int n);
160 static const int MaxRootMoves = 500;
161 RootMove moves[MaxRootMoves];
170 // Maximum depth for razoring
171 const Depth RazorDepth = 4 * OnePly;
173 // Dynamic razoring margin based on depth
174 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
176 // Step 8. Null move search with verification search
178 // Null move margin. A null move search will not be done if the static
179 // evaluation of the position is more than NullMoveMargin below beta.
180 const Value NullMoveMargin = Value(0x200);
182 // Maximum depth for use of dynamic threat detection when null move fails low
183 const Depth ThreatDepth = 5 * OnePly;
185 // Step 9. Internal iterative deepening
187 // Minimum depth for use of internal iterative deepening
188 const Depth IIDDepth[2] = { 8 * OnePly /* non-PV */, 5 * OnePly /* PV */};
190 // At Non-PV nodes we do an internal iterative deepening search
191 // when the static evaluation is bigger then beta - IIDMargin.
192 const Value IIDMargin = Value(0x100);
194 // Step 11. Decide the new search depth
196 // Extensions. Configurable UCI options
197 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
198 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
199 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
201 // Minimum depth for use of singular extension
202 const Depth SingularExtensionDepth[2] = { 7 * OnePly /* non-PV */, 6 * OnePly /* PV */};
204 // If the TT move is at least SingularExtensionMargin better then the
205 // remaining ones we will extend it.
206 const Value SingularExtensionMargin = Value(0x20);
208 // Step 12. Futility pruning
210 // Futility margin for quiescence search
211 const Value FutilityMarginQS = Value(0x80);
213 // Futility lookup tables (initialized at startup) and their getter functions
214 int32_t FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
215 int FutilityMoveCountArray[32]; // [depth]
217 inline Value futility_margin(Depth d, int mn) { return Value(d < 7 * OnePly ? FutilityMarginsMatrix[Max(d, 1)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
218 inline int futility_move_count(Depth d) { return d < 16 * OnePly ? FutilityMoveCountArray[d] : 512; }
220 // Step 14. Reduced search
222 // Reduction lookup tables (initialized at startup) and their getter functions
223 int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
225 template <NodeType PV>
226 inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / 2, 63)][Min(mn, 63)]; }
228 // Common adjustments
230 // Search depth at iteration 1
231 const Depth InitialDepth = OnePly;
233 // Easy move margin. An easy move candidate must be at least this much
234 // better than the second best move.
235 const Value EasyMoveMargin = Value(0x200);
243 // Scores and number of times the best move changed for each iteration
244 Value ValueByIteration[PLY_MAX_PLUS_2];
245 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
247 // Search window management
253 // Time managment variables
254 int SearchStartTime, MaxNodes, MaxDepth, OptimumSearchTime;
255 int MaximumSearchTime, ExtraSearchTime, ExactMaxTime;
256 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
257 bool FirstRootMove, AbortSearch, Quit, AspirationFailLow;
262 std::ofstream LogFile;
264 // Multi-threads related variables
265 Depth MinimumSplitDepth;
266 int MaxThreadsPerSplitPoint;
269 // Node counters, used only by thread[0] but try to keep in different cache
270 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
272 int NodesBetweenPolls = 30000;
279 Value id_loop(const Position& pos, Move searchMoves[]);
280 Value root_search(Position& pos, SearchStack* ss, Move* pv, RootMoveList& rml, Value* alphaPtr, Value* betaPtr);
282 template <NodeType PvNode>
283 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply);
285 template <NodeType PvNode>
286 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply);
288 template <NodeType PvNode>
289 void sp_search(SplitPoint* sp, int threadID);
291 template <NodeType PvNode>
292 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous);
294 bool connected_moves(const Position& pos, Move m1, Move m2);
295 bool value_is_mate(Value value);
296 Value value_to_tt(Value v, int ply);
297 Value value_from_tt(Value v, int ply);
298 bool move_is_killer(Move m, SearchStack* ss);
299 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
300 bool connected_threat(const Position& pos, Move m, Move threat);
301 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
302 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
303 void update_killers(Move m, SearchStack* ss);
304 void update_gains(const Position& pos, Move move, Value before, Value after);
306 int current_search_time();
307 std::string value_to_uci(Value v);
311 void wait_for_stop_or_ponderhit();
312 void init_ss_array(SearchStack* ss, int size);
313 void print_pv_info(const Position& pos, Move pv[], Value alpha, Value beta, Value value);
314 void insert_pv_in_tt(const Position& pos, Move pv[]);
315 void extract_pv_from_tt(const Position& pos, Move bestMove, Move pv[]);
317 #if !defined(_MSC_VER)
318 void *init_thread(void *threadID);
320 DWORD WINAPI init_thread(LPVOID threadID);
330 /// init_threads(), exit_threads() and nodes_searched() are helpers to
331 /// give accessibility to some TM methods from outside of current file.
333 void init_threads() { TM.init_threads(); }
334 void exit_threads() { TM.exit_threads(); }
335 int64_t nodes_searched() { return TM.nodes_searched(); }
338 /// init_search() is called during startup. It initializes various lookup tables
342 int d; // depth (OnePly == 2)
343 int hd; // half depth (OnePly == 1)
346 // Init reductions array
347 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
349 double pvRed = 0.33 + log(double(hd)) * log(double(mc)) / 4.5;
350 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
351 ReductionMatrix[PV][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
352 ReductionMatrix[NonPV][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
355 // Init futility margins array
356 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
357 FutilityMarginsMatrix[d][mc] = 112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45;
359 // Init futility move count array
360 for (d = 0; d < 32; d++)
361 FutilityMoveCountArray[d] = 3 + (1 << (3 * d / 8));
365 /// perft() is our utility to verify move generation is bug free. All the legal
366 /// moves up to given depth are generated and counted and the sum returned.
368 int perft(Position& pos, Depth depth)
373 MovePicker mp(pos, MOVE_NONE, depth, H);
375 // If we are at the last ply we don't need to do and undo
376 // the moves, just to count them.
377 if (depth <= OnePly) // Replace with '<' to test also qsearch
379 while (mp.get_next_move()) sum++;
383 // Loop through all legal moves
385 while ((move = mp.get_next_move()) != MOVE_NONE)
387 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
388 sum += perft(pos, depth - OnePly);
395 /// think() is the external interface to Stockfish's search, and is called when
396 /// the program receives the UCI 'go' command. It initializes various
397 /// search-related global variables, and calls root_search(). It returns false
398 /// when a quit command is received during the search.
400 bool think(const Position& pos, bool infinite, bool ponder, int time[], int increment[],
401 int movesToGo, int maxDepth, int maxNodes, int maxTime, Move searchMoves[]) {
403 // Initialize global search variables
404 StopOnPonderhit = AbortSearch = Quit = AspirationFailLow = false;
405 OptimumSearchTime = MaximumSearchTime = ExtraSearchTime = 0;
407 TM.resetNodeCounters();
408 SearchStartTime = get_system_time();
409 ExactMaxTime = maxTime;
412 InfiniteSearch = infinite;
413 PonderSearch = ponder;
414 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
416 // Look for a book move, only during games, not tests
417 if (UseTimeManagement && get_option_value_bool("OwnBook"))
419 if (get_option_value_string("Book File") != OpeningBook.file_name())
420 OpeningBook.open(get_option_value_string("Book File"));
422 Move bookMove = OpeningBook.get_move(pos, get_option_value_bool("Best Book Move"));
423 if (bookMove != MOVE_NONE)
426 wait_for_stop_or_ponderhit();
428 cout << "bestmove " << bookMove << endl;
433 // Read UCI option values
434 TT.set_size(get_option_value_int("Hash"));
435 if (button_was_pressed("Clear Hash"))
438 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
439 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
440 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
441 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
442 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
443 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
444 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
445 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
446 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
447 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
448 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
449 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
451 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
452 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
453 MultiPV = get_option_value_int("MultiPV");
454 Chess960 = get_option_value_bool("UCI_Chess960");
455 UseLogFile = get_option_value_bool("Use Search Log");
458 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
460 read_weights(pos.side_to_move());
462 // Set the number of active threads
463 int newActiveThreads = get_option_value_int("Threads");
464 if (newActiveThreads != TM.active_threads())
466 TM.set_active_threads(newActiveThreads);
467 init_eval(TM.active_threads());
470 // Wake up sleeping threads
471 TM.wake_sleeping_threads();
474 int myTime = time[pos.side_to_move()];
475 int myIncrement = increment[pos.side_to_move()];
476 if (UseTimeManagement)
477 TimeMgr.update(myTime, myIncrement, movesToGo, pos.startpos_ply_counter(),
478 &OptimumSearchTime, &MaximumSearchTime);
480 // Set best NodesBetweenPolls interval to avoid lagging under
481 // heavy time pressure.
483 NodesBetweenPolls = Min(MaxNodes, 30000);
484 else if (myTime && myTime < 1000)
485 NodesBetweenPolls = 1000;
486 else if (myTime && myTime < 5000)
487 NodesBetweenPolls = 5000;
489 NodesBetweenPolls = 30000;
491 // Write search information to log file
493 LogFile << "Searching: " << pos.to_fen() << endl
494 << "infinite: " << infinite
495 << " ponder: " << ponder
496 << " time: " << myTime
497 << " increment: " << myIncrement
498 << " moves to go: " << movesToGo << endl;
500 // We're ready to start thinking. Call the iterative deepening loop function
501 id_loop(pos, searchMoves);
506 TM.put_threads_to_sleep();
514 // id_loop() is the main iterative deepening loop. It calls root_search
515 // repeatedly with increasing depth until the allocated thinking time has
516 // been consumed, the user stops the search, or the maximum search depth is
519 Value id_loop(const Position& pos, Move searchMoves[]) {
521 Position p(pos, pos.thread());
522 SearchStack ss[PLY_MAX_PLUS_2];
523 Move pv[PLY_MAX_PLUS_2];
524 Move EasyMove = MOVE_NONE;
525 Value value, alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
527 // Moves to search are verified, copied, scored and sorted
528 RootMoveList rml(p, searchMoves);
530 // Handle special case of searching on a mate/stale position
531 if (rml.move_count() == 0)
534 wait_for_stop_or_ponderhit();
536 return pos.is_check() ? -VALUE_MATE : VALUE_DRAW;
539 // Print RootMoveList startup scoring to the standard output,
540 // so to output information also for iteration 1.
541 cout << "info depth " << 1
542 << "\ninfo depth " << 1
543 << " score " << value_to_uci(rml.get_move_score(0))
544 << " time " << current_search_time()
545 << " nodes " << TM.nodes_searched()
547 << " pv " << rml.get_move(0) << "\n";
552 init_ss_array(ss, PLY_MAX_PLUS_2);
553 pv[0] = pv[1] = MOVE_NONE;
554 ValueByIteration[1] = rml.get_move_score(0);
557 // Is one move significantly better than others after initial scoring ?
558 if ( rml.move_count() == 1
559 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
560 EasyMove = rml.get_move(0);
562 // Iterative deepening loop
563 while (Iteration < PLY_MAX)
565 // Initialize iteration
567 BestMoveChangesByIteration[Iteration] = 0;
569 cout << "info depth " << Iteration << endl;
571 // Calculate dynamic aspiration window based on previous iterations
572 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
574 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
575 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
577 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
578 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
580 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
581 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
584 // Search to the current depth, rml is updated and sorted, alpha and beta could change
585 value = root_search(p, ss, pv, rml, &alpha, &beta);
587 // Write PV to transposition table, in case the relevant entries have
588 // been overwritten during the search.
589 insert_pv_in_tt(p, pv);
592 break; // Value cannot be trusted. Break out immediately!
594 //Save info about search result
595 ValueByIteration[Iteration] = value;
597 // Drop the easy move if differs from the new best move
598 if (pv[0] != EasyMove)
599 EasyMove = MOVE_NONE;
601 if (UseTimeManagement)
604 bool stopSearch = false;
606 // Stop search early if there is only a single legal move,
607 // we search up to Iteration 6 anyway to get a proper score.
608 if (Iteration >= 6 && rml.move_count() == 1)
611 // Stop search early when the last two iterations returned a mate score
613 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
614 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
617 // Stop search early if one move seems to be much better than the others
618 int64_t nodes = TM.nodes_searched();
621 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
622 && current_search_time() > OptimumSearchTime / 16)
623 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
624 && current_search_time() > OptimumSearchTime / 32)))
627 // Add some extra time if the best move has changed during the last two iterations
628 if (Iteration > 5 && Iteration <= 50)
629 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (OptimumSearchTime / 2)
630 + BestMoveChangesByIteration[Iteration-1] * (OptimumSearchTime / 3);
632 // Stop search if most of MaxSearchTime is consumed at the end of the
633 // iteration. We probably don't have enough time to search the first
634 // move at the next iteration anyway.
635 if (current_search_time() > ((OptimumSearchTime + ExtraSearchTime) * 80) / 128)
641 StopOnPonderhit = true;
647 if (MaxDepth && Iteration >= MaxDepth)
651 // If we are pondering or in infinite search, we shouldn't print the
652 // best move before we are told to do so.
653 if (!AbortSearch && (PonderSearch || InfiniteSearch))
654 wait_for_stop_or_ponderhit();
656 // Print final search statistics
657 cout << "info nodes " << TM.nodes_searched()
659 << " time " << current_search_time() << endl;
661 // Print the best move and the ponder move to the standard output
662 if (pv[0] == MOVE_NONE)
664 pv[0] = rml.get_move(0);
668 assert(pv[0] != MOVE_NONE);
670 cout << "bestmove " << pv[0];
672 if (pv[1] != MOVE_NONE)
673 cout << " ponder " << pv[1];
680 dbg_print_mean(LogFile);
682 if (dbg_show_hit_rate)
683 dbg_print_hit_rate(LogFile);
685 LogFile << "\nNodes: " << TM.nodes_searched()
686 << "\nNodes/second: " << nps()
687 << "\nBest move: " << move_to_san(p, pv[0]);
690 p.do_move(pv[0], st);
691 LogFile << "\nPonder move: "
692 << move_to_san(p, pv[1]) // Works also with MOVE_NONE
695 return rml.get_move_score(0);
699 // root_search() is the function which searches the root node. It is
700 // similar to search_pv except that it uses a different move ordering
701 // scheme, prints some information to the standard output and handles
702 // the fail low/high loops.
704 Value root_search(Position& pos, SearchStack* ss, Move* pv, RootMoveList& rml, Value* alphaPtr, Value* betaPtr) {
711 Depth depth, ext, newDepth;
712 Value value, alpha, beta;
713 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
714 int researchCountFH, researchCountFL;
716 researchCountFH = researchCountFL = 0;
719 isCheck = pos.is_check();
721 // Step 1. Initialize node (polling is omitted at root)
722 ss->currentMove = ss->bestMove = MOVE_NONE;
724 // Step 2. Check for aborted search (omitted at root)
725 // Step 3. Mate distance pruning (omitted at root)
726 // Step 4. Transposition table lookup (omitted at root)
728 // Step 5. Evaluate the position statically
729 // At root we do this only to get reference value for child nodes
730 ss->eval = isCheck ? VALUE_NONE : evaluate(pos, ei);
732 // Step 6. Razoring (omitted at root)
733 // Step 7. Static null move pruning (omitted at root)
734 // Step 8. Null move search with verification search (omitted at root)
735 // Step 9. Internal iterative deepening (omitted at root)
737 // Step extra. Fail low loop
738 // We start with small aspiration window and in case of fail low, we research
739 // with bigger window until we are not failing low anymore.
742 // Sort the moves before to (re)search
745 // Step 10. Loop through all moves in the root move list
746 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
748 // This is used by time management
749 FirstRootMove = (i == 0);
751 // Save the current node count before the move is searched
752 nodes = TM.nodes_searched();
754 // Reset beta cut-off counters
755 TM.resetBetaCounters();
757 // Pick the next root move, and print the move and the move number to
758 // the standard output.
759 move = ss->currentMove = rml.get_move(i);
761 if (current_search_time() >= 1000)
762 cout << "info currmove " << move
763 << " currmovenumber " << i + 1 << endl;
765 moveIsCheck = pos.move_is_check(move);
766 captureOrPromotion = pos.move_is_capture_or_promotion(move);
768 // Step 11. Decide the new search depth
769 depth = (Iteration - 2) * OnePly + InitialDepth;
770 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, false, &dangerous);
771 newDepth = depth + ext;
773 // Step 12. Futility pruning (omitted at root)
775 // Step extra. Fail high loop
776 // If move fails high, we research with bigger window until we are not failing
778 value = - VALUE_INFINITE;
782 // Step 13. Make the move
783 pos.do_move(move, st, ci, moveIsCheck);
785 // Step extra. pv search
786 // We do pv search for first moves (i < MultiPV)
787 // and for fail high research (value > alpha)
788 if (i < MultiPV || value > alpha)
790 // Aspiration window is disabled in multi-pv case
792 alpha = -VALUE_INFINITE;
794 // Full depth PV search, done on first move or after a fail high
795 value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, 1);
799 // Step 14. Reduced search
800 // if the move fails high will be re-searched at full depth
801 bool doFullDepthSearch = true;
803 if ( depth >= 3 * OnePly
805 && !captureOrPromotion
806 && !move_is_castle(move))
808 ss->reduction = reduction<PV>(depth, i - MultiPV + 2);
811 assert(newDepth-ss->reduction >= OnePly);
813 // Reduced depth non-pv search using alpha as upperbound
814 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth-ss->reduction, 1);
815 doFullDepthSearch = (value > alpha);
818 // The move failed high, but if reduction is very big we could
819 // face a false positive, retry with a less aggressive reduction,
820 // if the move fails high again then go with full depth search.
821 if (doFullDepthSearch && ss->reduction > 2 * OnePly)
823 assert(newDepth - OnePly >= OnePly);
825 ss->reduction = OnePly;
826 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth-ss->reduction, 1);
827 doFullDepthSearch = (value > alpha);
829 ss->reduction = Depth(0); // Restore original reduction
832 // Step 15. Full depth search
833 if (doFullDepthSearch)
835 // Full depth non-pv search using alpha as upperbound
836 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth, 1);
838 // If we are above alpha then research at same depth but as PV
839 // to get a correct score or eventually a fail high above beta.
841 value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, 1);
845 // Step 16. Undo move
848 // Can we exit fail high loop ?
849 if (AbortSearch || value < beta)
852 // We are failing high and going to do a research. It's important to update
853 // the score before research in case we run out of time while researching.
854 rml.set_move_score(i, value);
856 extract_pv_from_tt(pos, move, pv);
857 rml.set_move_pv(i, pv);
859 // Print information to the standard output
860 print_pv_info(pos, pv, alpha, beta, value);
862 // Prepare for a research after a fail high, each time with a wider window
863 *betaPtr = beta = Min(beta + AspirationDelta * (1 << researchCountFH), VALUE_INFINITE);
866 } // End of fail high loop
868 // Finished searching the move. If AbortSearch is true, the search
869 // was aborted because the user interrupted the search or because we
870 // ran out of time. In this case, the return value of the search cannot
871 // be trusted, and we break out of the loop without updating the best
876 // Remember beta-cutoff and searched nodes counts for this move. The
877 // info is used to sort the root moves for the next iteration.
879 TM.get_beta_counters(pos.side_to_move(), our, their);
880 rml.set_beta_counters(i, our, their);
881 rml.set_move_nodes(i, TM.nodes_searched() - nodes);
883 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
884 assert(value < beta);
886 // Step 17. Check for new best move
887 if (value <= alpha && i >= MultiPV)
888 rml.set_move_score(i, -VALUE_INFINITE);
891 // PV move or new best move!
894 rml.set_move_score(i, value);
896 extract_pv_from_tt(pos, move, pv);
897 rml.set_move_pv(i, pv);
901 // We record how often the best move has been changed in each
902 // iteration. This information is used for time managment: When
903 // the best move changes frequently, we allocate some more time.
905 BestMoveChangesByIteration[Iteration]++;
907 // Print information to the standard output
908 print_pv_info(pos, pv, alpha, beta, value);
910 // Raise alpha to setup proper non-pv search upper bound
917 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
919 cout << "info multipv " << j + 1
920 << " score " << value_to_uci(rml.get_move_score(j))
921 << " depth " << (j <= i ? Iteration : Iteration - 1)
922 << " time " << current_search_time()
923 << " nodes " << TM.nodes_searched()
927 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
928 cout << rml.get_move_pv(j, k) << " ";
932 alpha = rml.get_move_score(Min(i, MultiPV - 1));
934 } // PV move or new best move
936 assert(alpha >= *alphaPtr);
938 AspirationFailLow = (alpha == *alphaPtr);
940 if (AspirationFailLow && StopOnPonderhit)
941 StopOnPonderhit = false;
944 // Can we exit fail low loop ?
945 if (AbortSearch || !AspirationFailLow)
948 // Prepare for a research after a fail low, each time with a wider window
949 *alphaPtr = alpha = Max(alpha - AspirationDelta * (1 << researchCountFL), -VALUE_INFINITE);
954 // Sort the moves before to return
961 // search<>() is the main search function for both PV and non-PV nodes
963 template <NodeType PvNode>
964 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
966 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
967 assert(beta > alpha && beta <= VALUE_INFINITE);
968 assert(PvNode || alpha == beta - 1);
969 assert(ply > 0 && ply < PLY_MAX);
970 assert(pos.thread() >= 0 && pos.thread() < TM.active_threads());
972 Move movesSearched[256];
975 const TTEntry *tte, *ttx;
977 Move ttMove, move, excludedMove, threatMove;
979 Value bestValue, value, oldAlpha;
980 Value refinedValue, nullValue, futilityValueScaled; // Non-PV specific
981 bool isCheck, singleEvasion, singularExtensionNode, moveIsCheck, captureOrPromotion, dangerous;
982 bool mateThreat = false;
984 int threadID = pos.thread();
985 refinedValue = bestValue = value = -VALUE_INFINITE;
988 // Step 1. Initialize node and poll. Polling can abort search
989 TM.incrementNodeCounter(threadID);
990 ss->currentMove = ss->bestMove = threatMove = MOVE_NONE;
991 (ss+2)->killers[0] = (ss+2)->killers[1] = (ss+2)->mateKiller = MOVE_NONE;
993 if (threadID == 0 && ++NodesSincePoll > NodesBetweenPolls)
999 // Step 2. Check for aborted search and immediate draw
1000 if (AbortSearch || TM.thread_should_stop(threadID))
1003 if (pos.is_draw() || ply >= PLY_MAX - 1)
1006 // Step 3. Mate distance pruning
1007 alpha = Max(value_mated_in(ply), alpha);
1008 beta = Min(value_mate_in(ply+1), beta);
1012 // Step 4. Transposition table lookup
1014 // We don't want the score of a partial search to overwrite a previous full search
1015 // TT value, so we use a different position key in case of an excluded move exists.
1016 excludedMove = ss->excludedMove;
1017 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1019 tte = TT.retrieve(posKey);
1020 ttMove = (tte ? tte->move() : MOVE_NONE);
1022 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1023 // This is to avoid problems in the following areas:
1025 // * Repetition draw detection
1026 // * Fifty move rule detection
1027 // * Searching for a mate
1028 // * Printing of full PV line
1030 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1032 // Refresh tte entry to avoid aging
1033 TT.store(posKey, tte->value(), tte->type(), tte->depth(), ttMove, tte->static_value(), tte->king_danger());
1035 ss->bestMove = ttMove; // Can be MOVE_NONE
1036 return value_from_tt(tte->value(), ply);
1039 // Step 5. Evaluate the position statically and
1040 // update gain statistics of parent move.
1041 isCheck = pos.is_check();
1043 ss->eval = VALUE_NONE;
1046 assert(tte->static_value() != VALUE_NONE);
1048 ss->eval = tte->static_value();
1049 ei.kingDanger[pos.side_to_move()] = tte->king_danger();
1050 refinedValue = refine_eval(tte, ss->eval, ply);
1054 refinedValue = ss->eval = evaluate(pos, ei);
1055 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ei.kingDanger[pos.side_to_move()]);
1058 // Save gain for the parent non-capture move
1059 update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1061 // Step 6. Razoring (is omitted in PV nodes)
1063 && depth < RazorDepth
1065 && refinedValue < beta - razor_margin(depth)
1066 && ttMove == MOVE_NONE
1067 && (ss-1)->currentMove != MOVE_NULL
1068 && !value_is_mate(beta)
1069 && !pos.has_pawn_on_7th(pos.side_to_move()))
1071 Value rbeta = beta - razor_margin(depth);
1072 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, Depth(0), ply);
1074 // Logically we should return (v + razor_margin(depth)), but
1075 // surprisingly this did slightly weaker in tests.
1079 // Step 7. Static null move pruning (is omitted in PV nodes)
1080 // We're betting that the opponent doesn't have a move that will reduce
1081 // the score by more than futility_margin(depth) if we do a null move.
1083 && !ss->skipNullMove
1084 && depth < RazorDepth
1086 && refinedValue >= beta + futility_margin(depth, 0)
1087 && !value_is_mate(beta)
1088 && pos.non_pawn_material(pos.side_to_move()))
1089 return refinedValue - futility_margin(depth, 0);
1091 // Step 8. Null move search with verification search (is omitted in PV nodes)
1092 // When we jump directly to qsearch() we do a null move only if static value is
1093 // at least beta. Otherwise we do a null move if static value is not more than
1094 // NullMoveMargin under beta.
1096 && !ss->skipNullMove
1099 && refinedValue >= beta - (depth >= 4 * OnePly ? NullMoveMargin : 0)
1100 && !value_is_mate(beta)
1101 && pos.non_pawn_material(pos.side_to_move()))
1103 ss->currentMove = MOVE_NULL;
1105 // Null move dynamic reduction based on depth
1106 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1108 // Null move dynamic reduction based on value
1109 if (refinedValue - beta > PawnValueMidgame)
1112 pos.do_null_move(st);
1113 (ss+1)->skipNullMove = true;
1115 nullValue = depth-R*OnePly < OnePly ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, Depth(0), ply+1)
1116 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*OnePly, ply+1);
1117 (ss+1)->skipNullMove = false;
1118 pos.undo_null_move();
1120 if (nullValue >= beta)
1122 // Do not return unproven mate scores
1123 if (nullValue >= value_mate_in(PLY_MAX))
1126 if (depth < 6 * OnePly)
1129 // Do verification search at high depths
1130 ss->skipNullMove = true;
1131 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*OnePly, ply);
1132 ss->skipNullMove = false;
1139 // The null move failed low, which means that we may be faced with
1140 // some kind of threat. If the previous move was reduced, check if
1141 // the move that refuted the null move was somehow connected to the
1142 // move which was reduced. If a connection is found, return a fail
1143 // low score (which will cause the reduced move to fail high in the
1144 // parent node, which will trigger a re-search with full depth).
1145 if (nullValue == value_mated_in(ply + 2))
1148 threatMove = (ss+1)->bestMove;
1149 if ( depth < ThreatDepth
1150 && (ss-1)->reduction
1151 && connected_moves(pos, (ss-1)->currentMove, threatMove))
1156 // Step 9. Internal iterative deepening
1157 if ( depth >= IIDDepth[PvNode]
1158 && ttMove == MOVE_NONE
1159 && (PvNode || (!isCheck && ss->eval >= beta - IIDMargin)))
1161 Depth d = (PvNode ? depth - 2 * OnePly : depth / 2);
1163 ss->skipNullMove = true;
1164 search<PvNode>(pos, ss, alpha, beta, d, ply);
1165 ss->skipNullMove = false;
1167 ttMove = ss->bestMove;
1168 tte = TT.retrieve(posKey);
1171 // Expensive mate threat detection (only for PV nodes)
1173 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1175 // Initialize a MovePicker object for the current position
1176 MovePicker mp = MovePicker(pos, ttMove, depth, H, ss, (PvNode ? -VALUE_INFINITE : beta));
1178 ss->bestMove = MOVE_NONE;
1179 singleEvasion = isCheck && mp.number_of_evasions() == 1;
1180 singularExtensionNode = depth >= SingularExtensionDepth[PvNode]
1183 && !excludedMove // Do not allow recursive singular extension search
1184 && is_lower_bound(tte->type())
1185 && tte->depth() >= depth - 3 * OnePly;
1187 // Step 10. Loop through moves
1188 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1189 while ( bestValue < beta
1190 && (move = mp.get_next_move()) != MOVE_NONE
1191 && !TM.thread_should_stop(threadID))
1193 assert(move_is_ok(move));
1195 if (move == excludedMove)
1198 moveIsCheck = pos.move_is_check(move, ci);
1199 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1201 // Step 11. Decide the new search depth
1202 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1204 // Singular extension search. If all moves but one fail low on a search of (alpha-s, beta-s),
1205 // and just one fails high on (alpha, beta), then that move is singular and should be extended.
1206 // To verify this we do a reduced search on all the other moves but the ttMove, if result is
1207 // lower then ttValue minus a margin then we extend ttMove.
1208 if ( singularExtensionNode
1209 && move == tte->move()
1212 // Avoid to do an expensive singular extension search on nodes where
1213 // such search have already been done in the past, so assume the last
1214 // singular extension search result is still valid.
1216 && depth < SingularExtensionDepth[PvNode] + 5 * OnePly
1217 && (ttx = TT.retrieve(pos.get_exclusion_key())) != NULL)
1219 if (is_upper_bound(ttx->type()))
1222 singularExtensionNode = false;
1225 Value ttValue = value_from_tt(tte->value(), ply);
1227 if (singularExtensionNode && abs(ttValue) < VALUE_KNOWN_WIN)
1229 Value b = ttValue - SingularExtensionMargin;
1230 ss->excludedMove = move;
1231 ss->skipNullMove = true;
1232 Value v = search<NonPV>(pos, ss, b - 1, b, depth / 2, ply);
1233 ss->skipNullMove = false;
1234 ss->excludedMove = MOVE_NONE;
1235 ss->bestMove = MOVE_NONE;
1241 newDepth = depth - OnePly + ext;
1243 // Update current move (this must be done after singular extension search)
1244 movesSearched[moveCount++] = ss->currentMove = move;
1246 // Step 12. Futility pruning (is omitted in PV nodes)
1248 && !captureOrPromotion
1252 && !move_is_castle(move))
1254 // Move count based pruning
1255 if ( moveCount >= futility_move_count(depth)
1256 && !(threatMove && connected_threat(pos, move, threatMove))
1257 && bestValue > value_mated_in(PLY_MAX))
1260 // Value based pruning
1261 // We illogically ignore reduction condition depth >= 3*OnePly for predicted depth,
1262 // but fixing this made program slightly weaker.
1263 Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount);
1264 futilityValueScaled = ss->eval + futility_margin(predictedDepth, moveCount)
1265 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1267 if (futilityValueScaled < beta)
1269 if (futilityValueScaled > bestValue)
1270 bestValue = futilityValueScaled;
1275 // Step 13. Make the move
1276 pos.do_move(move, st, ci, moveIsCheck);
1278 // Step extra. pv search (only in PV nodes)
1279 // The first move in list is the expected PV
1280 if (PvNode && moveCount == 1)
1281 value = newDepth < OnePly ? -qsearch<PV>(pos, ss+1, -beta, -alpha, Depth(0), ply+1)
1282 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth, ply+1);
1285 // Step 14. Reduced depth search
1286 // If the move fails high will be re-searched at full depth.
1287 bool doFullDepthSearch = true;
1289 if ( depth >= 3 * OnePly
1290 && !captureOrPromotion
1292 && !move_is_castle(move)
1293 && !move_is_killer(move, ss))
1295 ss->reduction = reduction<PvNode>(depth, moveCount);
1298 Depth d = newDepth - ss->reduction;
1299 value = d < OnePly ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, Depth(0), ply+1)
1300 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d, ply+1);
1302 doFullDepthSearch = (value > alpha);
1305 // The move failed high, but if reduction is very big we could
1306 // face a false positive, retry with a less aggressive reduction,
1307 // if the move fails high again then go with full depth search.
1308 if (doFullDepthSearch && ss->reduction > 2 * OnePly)
1310 assert(newDepth - OnePly >= OnePly);
1312 ss->reduction = OnePly;
1313 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth-ss->reduction, ply+1);
1314 doFullDepthSearch = (value > alpha);
1316 ss->reduction = Depth(0); // Restore original reduction
1319 // Step 15. Full depth search
1320 if (doFullDepthSearch)
1322 value = newDepth < OnePly ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, Depth(0), ply+1)
1323 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth, ply+1);
1325 // Step extra. pv search (only in PV nodes)
1326 // Search only for possible new PV nodes, if instead value >= beta then
1327 // parent node fails low with value <= alpha and tries another move.
1328 if (PvNode && value > alpha && value < beta)
1329 value = newDepth < OnePly ? -qsearch<PV>(pos, ss+1, -beta, -alpha, Depth(0), ply+1)
1330 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth, ply+1);
1334 // Step 16. Undo move
1335 pos.undo_move(move);
1337 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1339 // Step 17. Check for new best move
1340 if (value > bestValue)
1345 if (PvNode && value < beta) // We want always alpha < beta
1348 if (value == value_mate_in(ply + 1))
1349 ss->mateKiller = move;
1351 ss->bestMove = move;
1355 // Step 18. Check for split
1356 if ( depth >= MinimumSplitDepth
1357 && TM.active_threads() > 1
1359 && TM.available_thread_exists(threadID)
1361 && !TM.thread_should_stop(threadID)
1363 TM.split<FakeSplit>(pos, ss, ply, &alpha, beta, &bestValue, depth,
1364 threatMove, mateThreat, &moveCount, &mp, PvNode);
1367 // Step 19. Check for mate and stalemate
1368 // All legal moves have been searched and if there are
1369 // no legal moves, it must be mate or stalemate.
1370 // If one move was excluded return fail low score.
1372 return excludedMove ? oldAlpha : isCheck ? value_mated_in(ply) : VALUE_DRAW;
1374 // Step 20. Update tables
1375 // If the search is not aborted, update the transposition table,
1376 // history counters, and killer moves.
1377 if (AbortSearch || TM.thread_should_stop(threadID))
1380 ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1381 move = (bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove);
1382 TT.store(posKey, value_to_tt(bestValue, ply), vt, depth, move, ss->eval, ei.kingDanger[pos.side_to_move()]);
1384 // Update killers and history only for non capture moves that fails high
1385 if (bestValue >= beta)
1387 TM.incrementBetaCounter(pos.side_to_move(), depth, threadID);
1388 if (!pos.move_is_capture_or_promotion(move))
1390 update_history(pos, move, depth, movesSearched, moveCount);
1391 update_killers(move, ss);
1395 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1401 // qsearch() is the quiescence search function, which is called by the main
1402 // search function when the remaining depth is zero (or, to be more precise,
1403 // less than OnePly).
1405 template <NodeType PvNode>
1406 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
1408 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1409 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1410 assert(PvNode || alpha == beta - 1);
1412 assert(ply > 0 && ply < PLY_MAX);
1413 assert(pos.thread() >= 0 && pos.thread() < TM.active_threads());
1418 Value bestValue, value, futilityValue, futilityBase;
1419 bool isCheck, deepChecks, enoughMaterial, moveIsCheck, evasionPrunable;
1421 Value oldAlpha = alpha;
1423 TM.incrementNodeCounter(pos.thread());
1424 ss->bestMove = ss->currentMove = MOVE_NONE;
1426 // Check for an instant draw or maximum ply reached
1427 if (pos.is_draw() || ply >= PLY_MAX - 1)
1430 // Transposition table lookup. At PV nodes, we don't use the TT for
1431 // pruning, but only for move ordering.
1432 tte = TT.retrieve(pos.get_key());
1433 ttMove = (tte ? tte->move() : MOVE_NONE);
1435 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1437 ss->bestMove = ttMove; // Can be MOVE_NONE
1438 return value_from_tt(tte->value(), ply);
1441 isCheck = pos.is_check();
1443 // Evaluate the position statically
1446 bestValue = futilityBase = -VALUE_INFINITE;
1447 ss->eval = VALUE_NONE;
1448 deepChecks = enoughMaterial = false;
1454 assert(tte->static_value() != VALUE_NONE);
1456 ei.kingDanger[pos.side_to_move()] = tte->king_danger();
1457 bestValue = tte->static_value();
1460 bestValue = evaluate(pos, ei);
1462 ss->eval = bestValue;
1463 update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1465 // Stand pat. Return immediately if static value is at least beta
1466 if (bestValue >= beta)
1469 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, ei.kingDanger[pos.side_to_move()]);
1474 if (PvNode && bestValue > alpha)
1477 // If we are near beta then try to get a cutoff pushing checks a bit further
1478 deepChecks = (depth == -OnePly && bestValue >= beta - PawnValueMidgame / 8);
1480 // Futility pruning parameters, not needed when in check
1481 futilityBase = bestValue + FutilityMarginQS + ei.kingDanger[pos.side_to_move()];
1482 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1485 // Initialize a MovePicker object for the current position, and prepare
1486 // to search the moves. Because the depth is <= 0 here, only captures,
1487 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1488 // and we are near beta) will be generated.
1489 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1492 // Loop through the moves until no moves remain or a beta cutoff occurs
1493 while ( alpha < beta
1494 && (move = mp.get_next_move()) != MOVE_NONE)
1496 assert(move_is_ok(move));
1498 moveIsCheck = pos.move_is_check(move, ci);
1506 && !move_is_promotion(move)
1507 && !pos.move_is_passed_pawn_push(move))
1509 futilityValue = futilityBase
1510 + pos.endgame_value_of_piece_on(move_to(move))
1511 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1513 if (futilityValue < alpha)
1515 if (futilityValue > bestValue)
1516 bestValue = futilityValue;
1521 // Detect blocking evasions that are candidate to be pruned
1522 evasionPrunable = isCheck
1523 && bestValue > value_mated_in(PLY_MAX)
1524 && !pos.move_is_capture(move)
1525 && pos.type_of_piece_on(move_from(move)) != KING
1526 && !pos.can_castle(pos.side_to_move());
1528 // Don't search moves with negative SEE values
1530 && (!isCheck || evasionPrunable)
1532 && !move_is_promotion(move)
1533 && pos.see_sign(move) < 0)
1536 // Update current move
1537 ss->currentMove = move;
1539 // Make and search the move
1540 pos.do_move(move, st, ci, moveIsCheck);
1541 value = -qsearch<PvNode>(pos, ss+1, -beta, -alpha, depth-OnePly, ply+1);
1542 pos.undo_move(move);
1544 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1547 if (value > bestValue)
1553 ss->bestMove = move;
1558 // All legal moves have been searched. A special case: If we're in check
1559 // and no legal moves were found, it is checkmate.
1560 if (isCheck && bestValue == -VALUE_INFINITE)
1561 return value_mated_in(ply);
1563 // Update transposition table
1564 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1565 ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1566 TT.store(pos.get_key(), value_to_tt(bestValue, ply), vt, d, ss->bestMove, ss->eval, ei.kingDanger[pos.side_to_move()]);
1568 // Update killers only for checking moves that fails high
1569 if ( bestValue >= beta
1570 && !pos.move_is_capture_or_promotion(ss->bestMove))
1571 update_killers(ss->bestMove, ss);
1573 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1579 // sp_search() is used to search from a split point. This function is called
1580 // by each thread working at the split point. It is similar to the normal
1581 // search() function, but simpler. Because we have already probed the hash
1582 // table, done a null move search, and searched the first move before
1583 // splitting, we don't have to repeat all this work in sp_search(). We
1584 // also don't need to store anything to the hash table here: This is taken
1585 // care of after we return from the split point.
1587 template <NodeType PvNode>
1588 void sp_search(SplitPoint* sp, int threadID) {
1590 assert(threadID >= 0 && threadID < TM.active_threads());
1591 assert(TM.active_threads() > 1);
1595 Depth ext, newDepth;
1597 Value futilityValueScaled; // NonPV specific
1598 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1600 value = -VALUE_INFINITE;
1602 Position pos(*sp->pos, threadID);
1604 SearchStack* ss = sp->sstack[threadID] + 1;
1605 isCheck = pos.is_check();
1607 // Step 10. Loop through moves
1608 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1609 lock_grab(&(sp->lock));
1611 while ( sp->bestValue < sp->beta
1612 && (move = sp->mp->get_next_move()) != MOVE_NONE
1613 && !TM.thread_should_stop(threadID))
1615 moveCount = ++sp->moveCount;
1616 lock_release(&(sp->lock));
1618 assert(move_is_ok(move));
1620 moveIsCheck = pos.move_is_check(move, ci);
1621 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1623 // Step 11. Decide the new search depth
1624 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1625 newDepth = sp->depth - OnePly + ext;
1627 // Update current move
1628 ss->currentMove = move;
1630 // Step 12. Futility pruning (is omitted in PV nodes)
1632 && !captureOrPromotion
1635 && !move_is_castle(move))
1637 // Move count based pruning
1638 if ( moveCount >= futility_move_count(sp->depth)
1639 && !(sp->threatMove && connected_threat(pos, move, sp->threatMove))
1640 && sp->bestValue > value_mated_in(PLY_MAX))
1642 lock_grab(&(sp->lock));
1646 // Value based pruning
1647 Depth predictedDepth = newDepth - reduction<NonPV>(sp->depth, moveCount);
1648 futilityValueScaled = ss->eval + futility_margin(predictedDepth, moveCount)
1649 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1651 if (futilityValueScaled < sp->beta)
1653 lock_grab(&(sp->lock));
1655 if (futilityValueScaled > sp->bestValue)
1656 sp->bestValue = futilityValueScaled;
1661 // Step 13. Make the move
1662 pos.do_move(move, st, ci, moveIsCheck);
1664 // Step 14. Reduced search
1665 // If the move fails high will be re-searched at full depth.
1666 bool doFullDepthSearch = true;
1668 if ( !captureOrPromotion
1670 && !move_is_castle(move)
1671 && !move_is_killer(move, ss))
1673 ss->reduction = reduction<PvNode>(sp->depth, moveCount);
1676 Value localAlpha = sp->alpha;
1677 Depth d = newDepth - ss->reduction;
1678 value = d < OnePly ? -qsearch<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, Depth(0), sp->ply+1)
1679 : - search<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, d, sp->ply+1);
1681 doFullDepthSearch = (value > localAlpha);
1684 // The move failed high, but if reduction is very big we could
1685 // face a false positive, retry with a less aggressive reduction,
1686 // if the move fails high again then go with full depth search.
1687 if (doFullDepthSearch && ss->reduction > 2 * OnePly)
1689 assert(newDepth - OnePly >= OnePly);
1691 ss->reduction = OnePly;
1692 Value localAlpha = sp->alpha;
1693 value = -search<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, newDepth-ss->reduction, sp->ply+1);
1694 doFullDepthSearch = (value > localAlpha);
1696 ss->reduction = Depth(0); // Restore original reduction
1699 // Step 15. Full depth search
1700 if (doFullDepthSearch)
1702 Value localAlpha = sp->alpha;
1703 value = newDepth < OnePly ? -qsearch<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, Depth(0), sp->ply+1)
1704 : - search<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, newDepth, sp->ply+1);
1706 // Step extra. pv search (only in PV nodes)
1707 // Search only for possible new PV nodes, if instead value >= beta then
1708 // parent node fails low with value <= alpha and tries another move.
1709 if (PvNode && value > localAlpha && value < sp->beta)
1710 value = newDepth < OnePly ? -qsearch<PV>(pos, ss+1, -sp->beta, -sp->alpha, Depth(0), sp->ply+1)
1711 : - search<PV>(pos, ss+1, -sp->beta, -sp->alpha, newDepth, sp->ply+1);
1714 // Step 16. Undo move
1715 pos.undo_move(move);
1717 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1719 // Step 17. Check for new best move
1720 lock_grab(&(sp->lock));
1722 if (value > sp->bestValue && !TM.thread_should_stop(threadID))
1724 sp->bestValue = value;
1726 if (sp->bestValue > sp->alpha)
1728 if (!PvNode || value >= sp->beta)
1729 sp->stopRequest = true;
1731 if (PvNode && value < sp->beta) // This guarantees that always: sp->alpha < sp->beta
1734 sp->parentSstack->bestMove = ss->bestMove = move;
1739 /* Here we have the lock still grabbed */
1741 sp->slaves[threadID] = 0;
1743 lock_release(&(sp->lock));
1747 // connected_moves() tests whether two moves are 'connected' in the sense
1748 // that the first move somehow made the second move possible (for instance
1749 // if the moving piece is the same in both moves). The first move is assumed
1750 // to be the move that was made to reach the current position, while the
1751 // second move is assumed to be a move from the current position.
1753 bool connected_moves(const Position& pos, Move m1, Move m2) {
1755 Square f1, t1, f2, t2;
1758 assert(move_is_ok(m1));
1759 assert(move_is_ok(m2));
1761 if (m2 == MOVE_NONE)
1764 // Case 1: The moving piece is the same in both moves
1770 // Case 2: The destination square for m2 was vacated by m1
1776 // Case 3: Moving through the vacated square
1777 if ( piece_is_slider(pos.piece_on(f2))
1778 && bit_is_set(squares_between(f2, t2), f1))
1781 // Case 4: The destination square for m2 is defended by the moving piece in m1
1782 p = pos.piece_on(t1);
1783 if (bit_is_set(pos.attacks_from(p, t1), t2))
1786 // Case 5: Discovered check, checking piece is the piece moved in m1
1787 if ( piece_is_slider(p)
1788 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1789 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1791 // discovered_check_candidates() works also if the Position's side to
1792 // move is the opposite of the checking piece.
1793 Color them = opposite_color(pos.side_to_move());
1794 Bitboard dcCandidates = pos.discovered_check_candidates(them);
1796 if (bit_is_set(dcCandidates, f2))
1803 // value_is_mate() checks if the given value is a mate one eventually
1804 // compensated for the ply.
1806 bool value_is_mate(Value value) {
1808 assert(abs(value) <= VALUE_INFINITE);
1810 return value <= value_mated_in(PLY_MAX)
1811 || value >= value_mate_in(PLY_MAX);
1815 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1816 // "plies to mate from the current ply". Non-mate scores are unchanged.
1817 // The function is called before storing a value to the transposition table.
1819 Value value_to_tt(Value v, int ply) {
1821 if (v >= value_mate_in(PLY_MAX))
1824 if (v <= value_mated_in(PLY_MAX))
1831 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1832 // the transposition table to a mate score corrected for the current ply.
1834 Value value_from_tt(Value v, int ply) {
1836 if (v >= value_mate_in(PLY_MAX))
1839 if (v <= value_mated_in(PLY_MAX))
1846 // move_is_killer() checks if the given move is among the killer moves
1848 bool move_is_killer(Move m, SearchStack* ss) {
1850 if (ss->killers[0] == m || ss->killers[1] == m)
1857 // extension() decides whether a move should be searched with normal depth,
1858 // or with extended depth. Certain classes of moves (checking moves, in
1859 // particular) are searched with bigger depth than ordinary moves and in
1860 // any case are marked as 'dangerous'. Note that also if a move is not
1861 // extended, as example because the corresponding UCI option is set to zero,
1862 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1863 template <NodeType PvNode>
1864 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck,
1865 bool singleEvasion, bool mateThreat, bool* dangerous) {
1867 assert(m != MOVE_NONE);
1869 Depth result = Depth(0);
1870 *dangerous = moveIsCheck | singleEvasion | mateThreat;
1874 if (moveIsCheck && pos.see_sign(m) >= 0)
1875 result += CheckExtension[PvNode];
1878 result += SingleEvasionExtension[PvNode];
1881 result += MateThreatExtension[PvNode];
1884 if (pos.type_of_piece_on(move_from(m)) == PAWN)
1886 Color c = pos.side_to_move();
1887 if (relative_rank(c, move_to(m)) == RANK_7)
1889 result += PawnPushTo7thExtension[PvNode];
1892 if (pos.pawn_is_passed(c, move_to(m)))
1894 result += PassedPawnExtension[PvNode];
1899 if ( captureOrPromotion
1900 && pos.type_of_piece_on(move_to(m)) != PAWN
1901 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1902 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1903 && !move_is_promotion(m)
1906 result += PawnEndgameExtension[PvNode];
1911 && captureOrPromotion
1912 && pos.type_of_piece_on(move_to(m)) != PAWN
1913 && pos.see_sign(m) >= 0)
1919 return Min(result, OnePly);
1923 // connected_threat() tests whether it is safe to forward prune a move or if
1924 // is somehow coonected to the threat move returned by null search.
1926 bool connected_threat(const Position& pos, Move m, Move threat) {
1928 assert(move_is_ok(m));
1929 assert(threat && move_is_ok(threat));
1930 assert(!pos.move_is_check(m));
1931 assert(!pos.move_is_capture_or_promotion(m));
1932 assert(!pos.move_is_passed_pawn_push(m));
1934 Square mfrom, mto, tfrom, tto;
1936 mfrom = move_from(m);
1938 tfrom = move_from(threat);
1939 tto = move_to(threat);
1941 // Case 1: Don't prune moves which move the threatened piece
1945 // Case 2: If the threatened piece has value less than or equal to the
1946 // value of the threatening piece, don't prune move which defend it.
1947 if ( pos.move_is_capture(threat)
1948 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
1949 || pos.type_of_piece_on(tfrom) == KING)
1950 && pos.move_attacks_square(m, tto))
1953 // Case 3: If the moving piece in the threatened move is a slider, don't
1954 // prune safe moves which block its ray.
1955 if ( piece_is_slider(pos.piece_on(tfrom))
1956 && bit_is_set(squares_between(tfrom, tto), mto)
1957 && pos.see_sign(m) >= 0)
1964 // ok_to_use_TT() returns true if a transposition table score
1965 // can be used at a given point in search.
1967 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1969 Value v = value_from_tt(tte->value(), ply);
1971 return ( tte->depth() >= depth
1972 || v >= Max(value_mate_in(PLY_MAX), beta)
1973 || v < Min(value_mated_in(PLY_MAX), beta))
1975 && ( (is_lower_bound(tte->type()) && v >= beta)
1976 || (is_upper_bound(tte->type()) && v < beta));
1980 // refine_eval() returns the transposition table score if
1981 // possible otherwise falls back on static position evaluation.
1983 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1987 Value v = value_from_tt(tte->value(), ply);
1989 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
1990 || (is_upper_bound(tte->type()) && v < defaultEval))
1997 // update_history() registers a good move that produced a beta-cutoff
1998 // in history and marks as failures all the other moves of that ply.
2000 void update_history(const Position& pos, Move move, Depth depth,
2001 Move movesSearched[], int moveCount) {
2005 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2007 for (int i = 0; i < moveCount - 1; i++)
2009 m = movesSearched[i];
2013 if (!pos.move_is_capture_or_promotion(m))
2014 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2019 // update_killers() add a good move that produced a beta-cutoff
2020 // among the killer moves of that ply.
2022 void update_killers(Move m, SearchStack* ss) {
2024 if (m == ss->killers[0])
2027 ss->killers[1] = ss->killers[0];
2032 // update_gains() updates the gains table of a non-capture move given
2033 // the static position evaluation before and after the move.
2035 void update_gains(const Position& pos, Move m, Value before, Value after) {
2038 && before != VALUE_NONE
2039 && after != VALUE_NONE
2040 && pos.captured_piece() == NO_PIECE_TYPE
2041 && !move_is_special(m))
2042 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2046 // current_search_time() returns the number of milliseconds which have passed
2047 // since the beginning of the current search.
2049 int current_search_time() {
2051 return get_system_time() - SearchStartTime;
2055 // value_to_uci() converts a value to a string suitable for use with the UCI protocol
2057 std::string value_to_uci(Value v) {
2059 std::stringstream s;
2061 if (abs(v) < VALUE_MATE - PLY_MAX * OnePly)
2062 s << "cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to pawn = 100
2064 s << "mate " << (v > 0 ? (VALUE_MATE - v + 1) / 2 : -(VALUE_MATE + v) / 2 );
2069 // nps() computes the current nodes/second count.
2073 int t = current_search_time();
2074 return (t > 0 ? int((TM.nodes_searched() * 1000) / t) : 0);
2078 // poll() performs two different functions: It polls for user input, and it
2079 // looks at the time consumed so far and decides if it's time to abort the
2084 static int lastInfoTime;
2085 int t = current_search_time();
2090 // We are line oriented, don't read single chars
2091 std::string command;
2093 if (!std::getline(std::cin, command))
2096 if (command == "quit")
2099 PonderSearch = false;
2103 else if (command == "stop")
2106 PonderSearch = false;
2108 else if (command == "ponderhit")
2112 // Print search information
2116 else if (lastInfoTime > t)
2117 // HACK: Must be a new search where we searched less than
2118 // NodesBetweenPolls nodes during the first second of search.
2121 else if (t - lastInfoTime >= 1000)
2128 if (dbg_show_hit_rate)
2129 dbg_print_hit_rate();
2131 cout << "info nodes " << TM.nodes_searched() << " nps " << nps()
2132 << " time " << t << endl;
2135 // Should we stop the search?
2139 bool stillAtFirstMove = FirstRootMove
2140 && !AspirationFailLow
2141 && t > OptimumSearchTime + ExtraSearchTime;
2143 bool noMoreTime = t > MaximumSearchTime
2144 || stillAtFirstMove;
2146 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2147 || (ExactMaxTime && t >= ExactMaxTime)
2148 || (Iteration >= 3 && MaxNodes && TM.nodes_searched() >= MaxNodes))
2153 // ponderhit() is called when the program is pondering (i.e. thinking while
2154 // it's the opponent's turn to move) in order to let the engine know that
2155 // it correctly predicted the opponent's move.
2159 int t = current_search_time();
2160 PonderSearch = false;
2162 bool stillAtFirstMove = FirstRootMove
2163 && !AspirationFailLow
2164 && t > OptimumSearchTime + ExtraSearchTime;
2166 bool noMoreTime = t > MaximumSearchTime
2167 || stillAtFirstMove;
2169 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2174 // init_ss_array() does a fast reset of the first entries of a SearchStack
2175 // array and of all the excludedMove and skipNullMove entries.
2177 void init_ss_array(SearchStack* ss, int size) {
2179 for (int i = 0; i < size; i++, ss++)
2181 ss->excludedMove = MOVE_NONE;
2182 ss->skipNullMove = false;
2183 ss->reduction = Depth(0);
2186 ss->killers[0] = ss->killers[1] = ss->mateKiller = MOVE_NONE;
2191 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2192 // while the program is pondering. The point is to work around a wrinkle in
2193 // the UCI protocol: When pondering, the engine is not allowed to give a
2194 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2195 // We simply wait here until one of these commands is sent, and return,
2196 // after which the bestmove and pondermove will be printed (in id_loop()).
2198 void wait_for_stop_or_ponderhit() {
2200 std::string command;
2204 if (!std::getline(std::cin, command))
2207 if (command == "quit")
2212 else if (command == "ponderhit" || command == "stop")
2218 // print_pv_info() prints to standard output and eventually to log file information on
2219 // the current PV line. It is called at each iteration or after a new pv is found.
2221 void print_pv_info(const Position& pos, Move pv[], Value alpha, Value beta, Value value) {
2223 cout << "info depth " << Iteration
2224 << " score " << value_to_uci(value)
2225 << (value >= beta ? " lowerbound" : value <= alpha ? " upperbound" : "")
2226 << " time " << current_search_time()
2227 << " nodes " << TM.nodes_searched()
2231 for (Move* m = pv; *m != MOVE_NONE; m++)
2238 ValueType t = value >= beta ? VALUE_TYPE_LOWER :
2239 value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT;
2241 LogFile << pretty_pv(pos, current_search_time(), Iteration,
2242 TM.nodes_searched(), value, t, pv) << endl;
2247 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2248 // the PV back into the TT. This makes sure the old PV moves are searched
2249 // first, even if the old TT entries have been overwritten.
2251 void insert_pv_in_tt(const Position& pos, Move pv[]) {
2255 Position p(pos, pos.thread());
2259 for (int i = 0; pv[i] != MOVE_NONE; i++)
2261 tte = TT.retrieve(p.get_key());
2262 if (!tte || tte->move() != pv[i])
2264 v = (p.is_check() ? VALUE_NONE : evaluate(p, ei));
2265 TT.store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[i], v, ei.kingDanger[pos.side_to_move()]);
2267 p.do_move(pv[i], st);
2272 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2273 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2274 // allow to always have a ponder move even when we fail high at root and also a
2275 // long PV to print that is important for position analysis.
2277 void extract_pv_from_tt(const Position& pos, Move bestMove, Move pv[]) {
2281 Position p(pos, pos.thread());
2284 assert(bestMove != MOVE_NONE);
2287 p.do_move(pv[ply++], st);
2289 while ( (tte = TT.retrieve(p.get_key())) != NULL
2290 && tte->move() != MOVE_NONE
2291 && move_is_legal(p, tte->move())
2293 && (!p.is_draw() || ply < 2))
2295 pv[ply] = tte->move();
2296 p.do_move(pv[ply++], st);
2298 pv[ply] = MOVE_NONE;
2302 // init_thread() is the function which is called when a new thread is
2303 // launched. It simply calls the idle_loop() function with the supplied
2304 // threadID. There are two versions of this function; one for POSIX
2305 // threads and one for Windows threads.
2307 #if !defined(_MSC_VER)
2309 void* init_thread(void *threadID) {
2311 TM.idle_loop(*(int*)threadID, NULL);
2317 DWORD WINAPI init_thread(LPVOID threadID) {
2319 TM.idle_loop(*(int*)threadID, NULL);
2326 /// The ThreadsManager class
2328 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2329 // get_beta_counters() are getters/setters for the per thread
2330 // counters used to sort the moves at root.
2332 void ThreadsManager::resetNodeCounters() {
2334 for (int i = 0; i < MAX_THREADS; i++)
2335 threads[i].nodes = 0ULL;
2338 void ThreadsManager::resetBetaCounters() {
2340 for (int i = 0; i < MAX_THREADS; i++)
2341 threads[i].betaCutOffs[WHITE] = threads[i].betaCutOffs[BLACK] = 0ULL;
2344 int64_t ThreadsManager::nodes_searched() const {
2346 int64_t result = 0ULL;
2347 for (int i = 0; i < ActiveThreads; i++)
2348 result += threads[i].nodes;
2353 void ThreadsManager::get_beta_counters(Color us, int64_t& our, int64_t& their) const {
2356 for (int i = 0; i < MAX_THREADS; i++)
2358 our += threads[i].betaCutOffs[us];
2359 their += threads[i].betaCutOffs[opposite_color(us)];
2364 // idle_loop() is where the threads are parked when they have no work to do.
2365 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2366 // object for which the current thread is the master.
2368 void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2370 assert(threadID >= 0 && threadID < MAX_THREADS);
2374 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2375 // master should exit as last one.
2376 if (AllThreadsShouldExit)
2379 threads[threadID].state = THREAD_TERMINATED;
2383 // If we are not thinking, wait for a condition to be signaled
2384 // instead of wasting CPU time polling for work.
2385 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2388 assert(threadID != 0);
2389 threads[threadID].state = THREAD_SLEEPING;
2391 #if !defined(_MSC_VER)
2392 lock_grab(&WaitLock);
2393 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2394 pthread_cond_wait(&WaitCond, &WaitLock);
2395 lock_release(&WaitLock);
2397 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2401 // If thread has just woken up, mark it as available
2402 if (threads[threadID].state == THREAD_SLEEPING)
2403 threads[threadID].state = THREAD_AVAILABLE;
2405 // If this thread has been assigned work, launch a search
2406 if (threads[threadID].state == THREAD_WORKISWAITING)
2408 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2410 threads[threadID].state = THREAD_SEARCHING;
2412 if (threads[threadID].splitPoint->pvNode)
2413 sp_search<PV>(threads[threadID].splitPoint, threadID);
2415 sp_search<NonPV>(threads[threadID].splitPoint, threadID);
2417 assert(threads[threadID].state == THREAD_SEARCHING);
2419 threads[threadID].state = THREAD_AVAILABLE;
2422 // If this thread is the master of a split point and all slaves have
2423 // finished their work at this split point, return from the idle loop.
2425 for ( ; sp && i < ActiveThreads && !sp->slaves[i]; i++) {}
2427 if (i == ActiveThreads)
2429 // Because sp->slaves[] is reset under lock protection,
2430 // be sure sp->lock has been released before to return.
2431 lock_grab(&(sp->lock));
2432 lock_release(&(sp->lock));
2434 assert(threads[threadID].state == THREAD_AVAILABLE);
2436 threads[threadID].state = THREAD_SEARCHING;
2443 // init_threads() is called during startup. It launches all helper threads,
2444 // and initializes the split point stack and the global locks and condition
2447 void ThreadsManager::init_threads() {
2452 #if !defined(_MSC_VER)
2453 pthread_t pthread[1];
2456 // Initialize global locks
2458 lock_init(&WaitLock);
2460 #if !defined(_MSC_VER)
2461 pthread_cond_init(&WaitCond, NULL);
2463 for (i = 0; i < MAX_THREADS; i++)
2464 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2467 // Initialize splitPoints[] locks
2468 for (i = 0; i < MAX_THREADS; i++)
2469 for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2470 lock_init(&(threads[i].splitPoints[j].lock));
2472 // Will be set just before program exits to properly end the threads
2473 AllThreadsShouldExit = false;
2475 // Threads will be put to sleep as soon as created
2476 AllThreadsShouldSleep = true;
2478 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2480 threads[0].state = THREAD_SEARCHING;
2481 for (i = 1; i < MAX_THREADS; i++)
2482 threads[i].state = THREAD_AVAILABLE;
2484 // Launch the helper threads
2485 for (i = 1; i < MAX_THREADS; i++)
2488 #if !defined(_MSC_VER)
2489 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2491 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2496 cout << "Failed to create thread number " << i << endl;
2497 Application::exit_with_failure();
2500 // Wait until the thread has finished launching and is gone to sleep
2501 while (threads[i].state != THREAD_SLEEPING) {}
2506 // exit_threads() is called when the program exits. It makes all the
2507 // helper threads exit cleanly.
2509 void ThreadsManager::exit_threads() {
2511 ActiveThreads = MAX_THREADS; // HACK
2512 AllThreadsShouldSleep = true; // HACK
2513 wake_sleeping_threads();
2515 // This makes the threads to exit idle_loop()
2516 AllThreadsShouldExit = true;
2518 // Wait for thread termination
2519 for (int i = 1; i < MAX_THREADS; i++)
2520 while (threads[i].state != THREAD_TERMINATED) {}
2522 // Now we can safely destroy the locks
2523 for (int i = 0; i < MAX_THREADS; i++)
2524 for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2525 lock_destroy(&(threads[i].splitPoints[j].lock));
2527 lock_destroy(&WaitLock);
2528 lock_destroy(&MPLock);
2532 // thread_should_stop() checks whether the thread should stop its search.
2533 // This can happen if a beta cutoff has occurred in the thread's currently
2534 // active split point, or in some ancestor of the current split point.
2536 bool ThreadsManager::thread_should_stop(int threadID) const {
2538 assert(threadID >= 0 && threadID < ActiveThreads);
2542 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent) {}
2547 // thread_is_available() checks whether the thread with threadID "slave" is
2548 // available to help the thread with threadID "master" at a split point. An
2549 // obvious requirement is that "slave" must be idle. With more than two
2550 // threads, this is not by itself sufficient: If "slave" is the master of
2551 // some active split point, it is only available as a slave to the other
2552 // threads which are busy searching the split point at the top of "slave"'s
2553 // split point stack (the "helpful master concept" in YBWC terminology).
2555 bool ThreadsManager::thread_is_available(int slave, int master) const {
2557 assert(slave >= 0 && slave < ActiveThreads);
2558 assert(master >= 0 && master < ActiveThreads);
2559 assert(ActiveThreads > 1);
2561 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2564 // Make a local copy to be sure doesn't change under our feet
2565 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2567 if (localActiveSplitPoints == 0)
2568 // No active split points means that the thread is available as
2569 // a slave for any other thread.
2572 if (ActiveThreads == 2)
2575 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2576 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2577 // could have been set to 0 by another thread leading to an out of bound access.
2578 if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
2585 // available_thread_exists() tries to find an idle thread which is available as
2586 // a slave for the thread with threadID "master".
2588 bool ThreadsManager::available_thread_exists(int master) const {
2590 assert(master >= 0 && master < ActiveThreads);
2591 assert(ActiveThreads > 1);
2593 for (int i = 0; i < ActiveThreads; i++)
2594 if (thread_is_available(i, master))
2601 // split() does the actual work of distributing the work at a node between
2602 // several available threads. If it does not succeed in splitting the
2603 // node (because no idle threads are available, or because we have no unused
2604 // split point objects), the function immediately returns. If splitting is
2605 // possible, a SplitPoint object is initialized with all the data that must be
2606 // copied to the helper threads and we tell our helper threads that they have
2607 // been assigned work. This will cause them to instantly leave their idle loops
2608 // and call sp_search(). When all threads have returned from sp_search() then
2611 template <bool Fake>
2612 void ThreadsManager::split(const Position& p, SearchStack* ss, int ply, Value* alpha,
2613 const Value beta, Value* bestValue, Depth depth, Move threatMove,
2614 bool mateThreat, int* moveCount, MovePicker* mp, bool pvNode) {
2616 assert(ply > 0 && ply < PLY_MAX);
2617 assert(*bestValue >= -VALUE_INFINITE);
2618 assert(*bestValue <= *alpha);
2619 assert(*alpha < beta);
2620 assert(beta <= VALUE_INFINITE);
2621 assert(depth > Depth(0));
2622 assert(p.thread() >= 0 && p.thread() < ActiveThreads);
2623 assert(ActiveThreads > 1);
2625 int i, master = p.thread();
2626 Thread& masterThread = threads[master];
2630 // If no other thread is available to help us, or if we have too many
2631 // active split points, don't split.
2632 if ( !available_thread_exists(master)
2633 || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
2635 lock_release(&MPLock);
2639 // Pick the next available split point object from the split point stack
2640 SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
2642 // Initialize the split point object
2643 splitPoint.parent = masterThread.splitPoint;
2644 splitPoint.stopRequest = false;
2645 splitPoint.ply = ply;
2646 splitPoint.depth = depth;
2647 splitPoint.threatMove = threatMove;
2648 splitPoint.mateThreat = mateThreat;
2649 splitPoint.alpha = *alpha;
2650 splitPoint.beta = beta;
2651 splitPoint.pvNode = pvNode;
2652 splitPoint.bestValue = *bestValue;
2654 splitPoint.moveCount = *moveCount;
2655 splitPoint.pos = &p;
2656 splitPoint.parentSstack = ss;
2657 for (i = 0; i < ActiveThreads; i++)
2658 splitPoint.slaves[i] = 0;
2660 masterThread.splitPoint = &splitPoint;
2662 // If we are here it means we are not available
2663 assert(masterThread.state != THREAD_AVAILABLE);
2665 int workersCnt = 1; // At least the master is included
2667 // Allocate available threads setting state to THREAD_BOOKED
2668 for (i = 0; !Fake && i < ActiveThreads && workersCnt < MaxThreadsPerSplitPoint; i++)
2669 if (thread_is_available(i, master))
2671 threads[i].state = THREAD_BOOKED;
2672 threads[i].splitPoint = &splitPoint;
2673 splitPoint.slaves[i] = 1;
2677 assert(Fake || workersCnt > 1);
2679 // We can release the lock because slave threads are already booked and master is not available
2680 lock_release(&MPLock);
2682 // Tell the threads that they have work to do. This will make them leave
2683 // their idle loop. But before copy search stack tail for each thread.
2684 for (i = 0; i < ActiveThreads; i++)
2685 if (i == master || splitPoint.slaves[i])
2687 memcpy(splitPoint.sstack[i], ss - 1, 4 * sizeof(SearchStack));
2689 assert(i == master || threads[i].state == THREAD_BOOKED);
2691 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2694 // Everything is set up. The master thread enters the idle loop, from
2695 // which it will instantly launch a search, because its state is
2696 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2697 // idle loop, which means that the main thread will return from the idle
2698 // loop when all threads have finished their work at this split point.
2699 idle_loop(master, &splitPoint);
2701 // We have returned from the idle loop, which means that all threads are
2702 // finished. Update alpha and bestValue, and return.
2705 *alpha = splitPoint.alpha;
2706 *bestValue = splitPoint.bestValue;
2707 masterThread.activeSplitPoints--;
2708 masterThread.splitPoint = splitPoint.parent;
2710 lock_release(&MPLock);
2714 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2715 // to start a new search from the root.
2717 void ThreadsManager::wake_sleeping_threads() {
2719 assert(AllThreadsShouldSleep);
2720 assert(ActiveThreads > 0);
2722 AllThreadsShouldSleep = false;
2724 if (ActiveThreads == 1)
2727 #if !defined(_MSC_VER)
2728 pthread_mutex_lock(&WaitLock);
2729 pthread_cond_broadcast(&WaitCond);
2730 pthread_mutex_unlock(&WaitLock);
2732 for (int i = 1; i < MAX_THREADS; i++)
2733 SetEvent(SitIdleEvent[i]);
2739 // put_threads_to_sleep() makes all the threads go to sleep just before
2740 // to leave think(), at the end of the search. Threads should have already
2741 // finished the job and should be idle.
2743 void ThreadsManager::put_threads_to_sleep() {
2745 assert(!AllThreadsShouldSleep);
2747 // This makes the threads to go to sleep
2748 AllThreadsShouldSleep = true;
2751 /// The RootMoveList class
2753 // RootMoveList c'tor
2755 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2757 SearchStack ss[PLY_MAX_PLUS_2];
2758 MoveStack mlist[MaxRootMoves];
2760 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2762 // Initialize search stack
2763 init_ss_array(ss, PLY_MAX_PLUS_2);
2764 ss[0].currentMove = ss[0].bestMove = MOVE_NONE;
2765 ss[0].eval = VALUE_NONE;
2767 // Generate all legal moves
2768 MoveStack* last = generate_moves(pos, mlist);
2770 // Add each move to the moves[] array
2771 for (MoveStack* cur = mlist; cur != last; cur++)
2773 bool includeMove = includeAllMoves;
2775 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2776 includeMove = (searchMoves[k] == cur->move);
2781 // Find a quick score for the move
2782 pos.do_move(cur->move, st);
2783 ss[0].currentMove = cur->move;
2784 moves[count].move = cur->move;
2785 moves[count].score = -qsearch<PV>(pos, ss+1, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1);
2786 moves[count].pv[0] = cur->move;
2787 moves[count].pv[1] = MOVE_NONE;
2788 pos.undo_move(cur->move);
2795 // RootMoveList simple methods definitions
2797 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2799 moves[moveNum].nodes = nodes;
2800 moves[moveNum].cumulativeNodes += nodes;
2803 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2805 moves[moveNum].ourBeta = our;
2806 moves[moveNum].theirBeta = their;
2809 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2813 for (j = 0; pv[j] != MOVE_NONE; j++)
2814 moves[moveNum].pv[j] = pv[j];
2816 moves[moveNum].pv[j] = MOVE_NONE;
2820 // RootMoveList::sort() sorts the root move list at the beginning of a new
2823 void RootMoveList::sort() {
2825 sort_multipv(count - 1); // Sort all items
2829 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2830 // list by their scores and depths. It is used to order the different PVs
2831 // correctly in MultiPV mode.
2833 void RootMoveList::sort_multipv(int n) {
2837 for (i = 1; i <= n; i++)
2839 RootMove rm = moves[i];
2840 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2841 moves[j] = moves[j - 1];