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++; }
80 void resetNodeCounters();
81 int64_t nodes_searched() const;
82 bool available_thread_exists(int master) const;
83 bool thread_is_available(int slave, int master) const;
84 bool thread_should_stop(int threadID) const;
85 void wake_sleeping_threads();
86 void put_threads_to_sleep();
87 void idle_loop(int threadID, SplitPoint* sp);
90 void split(const Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
91 Depth depth, Move threatMove, bool mateThreat, int* moveCount, MovePicker* mp, bool pvNode);
97 volatile bool AllThreadsShouldExit, AllThreadsShouldSleep;
98 Thread threads[MAX_THREADS];
100 Lock MPLock, WaitLock;
102 #if !defined(_MSC_VER)
103 pthread_cond_t WaitCond;
105 HANDLE SitIdleEvent[MAX_THREADS];
111 // RootMove struct is used for moves at the root at the tree. For each
112 // root move, we store a score, a node count, and a PV (really a refutation
113 // in the case of moves which fail low).
117 RootMove() : mp_score(0), nodes(0), cumulativeNodes(0) {}
119 // RootMove::operator<() is the comparison function used when
120 // sorting the moves. A move m1 is considered to be better
121 // than a move m2 if it has a higher score, or if the moves
122 // have equal score but m1 has the higher beta cut-off count.
123 bool operator<(const RootMove& m) const {
125 return score != m.score ? score < m.score : mp_score <= m.mp_score;
131 int64_t nodes, cumulativeNodes;
132 Move pv[PLY_MAX_PLUS_2];
136 // The RootMoveList class is essentially an array of RootMove objects, with
137 // a handful of methods for accessing the data in the individual moves.
142 RootMoveList(Position& pos, Move searchMoves[]);
144 int move_count() const { return count; }
145 Move get_move(int moveNum) const { return moves[moveNum].move; }
146 Value get_move_score(int moveNum) const { return moves[moveNum].score; }
147 void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
148 Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
149 int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
150 void score_moves(const Position& pos);
152 void set_move_nodes(int moveNum, int64_t nodes);
153 void set_move_pv(int moveNum, const Move pv[]);
155 void sort_multipv(int n);
158 static const int MaxRootMoves = 500;
159 RootMove moves[MaxRootMoves];
168 // Maximum depth for razoring
169 const Depth RazorDepth = 4 * ONE_PLY;
171 // Dynamic razoring margin based on depth
172 inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
174 // Step 8. Null move search with verification search
176 // Null move margin. A null move search will not be done if the static
177 // evaluation of the position is more than NullMoveMargin below beta.
178 const Value NullMoveMargin = Value(0x200);
180 // Maximum depth for use of dynamic threat detection when null move fails low
181 const Depth ThreatDepth = 5 * ONE_PLY;
183 // Step 9. Internal iterative deepening
185 // Minimum depth for use of internal iterative deepening
186 const Depth IIDDepth[2] = { 8 * ONE_PLY /* non-PV */, 5 * ONE_PLY /* PV */};
188 // At Non-PV nodes we do an internal iterative deepening search
189 // when the static evaluation is bigger then beta - IIDMargin.
190 const Value IIDMargin = Value(0x100);
192 // Step 11. Decide the new search depth
194 // Extensions. Configurable UCI options
195 // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
196 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
197 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
199 // Minimum depth for use of singular extension
200 const Depth SingularExtensionDepth[2] = { 8 * ONE_PLY /* non-PV */, 6 * ONE_PLY /* PV */};
202 // If the TT move is at least SingularExtensionMargin better then the
203 // remaining ones we will extend it.
204 const Value SingularExtensionMargin = Value(0x20);
206 // Step 12. Futility pruning
208 // Futility margin for quiescence search
209 const Value FutilityMarginQS = Value(0x80);
211 // Futility lookup tables (initialized at startup) and their getter functions
212 int32_t FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
213 int FutilityMoveCountArray[32]; // [depth]
215 inline Value futility_margin(Depth d, int mn) { return Value(d < 7 * ONE_PLY ? FutilityMarginsMatrix[Max(d, 1)][Min(mn, 63)] : 2 * VALUE_INFINITE); }
216 inline int futility_move_count(Depth d) { return d < 16 * ONE_PLY ? FutilityMoveCountArray[d] : 512; }
218 // Step 14. Reduced search
220 // Reduction lookup tables (initialized at startup) and their getter functions
221 int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
223 template <NodeType PV>
224 inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / 2, 63)][Min(mn, 63)]; }
226 // Common adjustments
228 // Search depth at iteration 1
229 const Depth InitialDepth = ONE_PLY;
231 // Easy move margin. An easy move candidate must be at least this much
232 // better than the second best move.
233 const Value EasyMoveMargin = Value(0x200);
241 // Scores and number of times the best move changed for each iteration
242 Value ValueByIteration[PLY_MAX_PLUS_2];
243 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
245 // Search window management
251 // Time managment variables
252 int SearchStartTime, MaxNodes, MaxDepth, ExactMaxTime;
253 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
254 bool FirstRootMove, AbortSearch, Quit, AspirationFailLow;
259 std::ofstream LogFile;
261 // Multi-threads related variables
262 Depth MinimumSplitDepth;
263 int MaxThreadsPerSplitPoint;
264 ThreadsManager ThreadsMgr;
266 // Node counters, used only by thread[0] but try to keep in different cache
267 // lines (64 bytes each) from the heavy multi-thread read accessed variables.
269 int NodesBetweenPolls = 30000;
276 Value id_loop(const Position& pos, Move searchMoves[]);
277 Value root_search(Position& pos, SearchStack* ss, Move* pv, RootMoveList& rml, Value* alphaPtr, Value* betaPtr);
279 template <NodeType PvNode>
280 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply);
282 template <NodeType PvNode>
283 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply);
285 template <NodeType PvNode>
286 void sp_search(SplitPoint* sp, int threadID);
288 template <NodeType PvNode>
289 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous);
291 bool connected_moves(const Position& pos, Move m1, Move m2);
292 bool value_is_mate(Value value);
293 Value value_to_tt(Value v, int ply);
294 Value value_from_tt(Value v, int ply);
295 bool move_is_killer(Move m, SearchStack* ss);
296 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
297 bool connected_threat(const Position& pos, Move m, Move threat);
298 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
299 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
300 void update_killers(Move m, SearchStack* ss);
301 void update_gains(const Position& pos, Move move, Value before, Value after);
303 int current_search_time();
304 std::string value_to_uci(Value v);
308 void wait_for_stop_or_ponderhit();
309 void init_ss_array(SearchStack* ss, int size);
310 void print_pv_info(const Position& pos, Move pv[], Value alpha, Value beta, Value value);
311 void insert_pv_in_tt(const Position& pos, Move pv[]);
312 void extract_pv_from_tt(const Position& pos, Move bestMove, Move pv[]);
314 #if !defined(_MSC_VER)
315 void *init_thread(void *threadID);
317 DWORD WINAPI init_thread(LPVOID threadID);
327 /// init_threads(), exit_threads() and nodes_searched() are helpers to
328 /// give accessibility to some TM methods from outside of current file.
330 void init_threads() { ThreadsMgr.init_threads(); }
331 void exit_threads() { ThreadsMgr.exit_threads(); }
332 int64_t nodes_searched() { return ThreadsMgr.nodes_searched(); }
335 /// init_search() is called during startup. It initializes various lookup tables
339 int d; // depth (ONE_PLY == 2)
340 int hd; // half depth (ONE_PLY == 1)
343 // Init reductions array
344 for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
346 double pvRed = 0.33 + log(double(hd)) * log(double(mc)) / 4.5;
347 double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
348 ReductionMatrix[PV][hd][mc] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(ONE_PLY)) : 0);
349 ReductionMatrix[NonPV][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
352 // Init futility margins array
353 for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
354 FutilityMarginsMatrix[d][mc] = 112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45;
356 // Init futility move count array
357 for (d = 0; d < 32; d++)
358 FutilityMoveCountArray[d] = 3 + (1 << (3 * d / 8));
362 /// perft() is our utility to verify move generation is bug free. All the legal
363 /// moves up to given depth are generated and counted and the sum returned.
365 int perft(Position& pos, Depth depth)
367 MoveStack mlist[256];
372 // Generate all legal moves
373 MoveStack* last = generate_moves(pos, mlist);
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 <= ONE_PLY)
378 return int(last - mlist);
380 // Loop through all legal moves
382 for (MoveStack* cur = mlist; cur != last; cur++)
385 pos.do_move(m, st, ci, pos.move_is_check(m, ci));
386 sum += perft(pos, depth - ONE_PLY);
393 /// think() is the external interface to Stockfish's search, and is called when
394 /// the program receives the UCI 'go' command. It initializes various
395 /// search-related global variables, and calls root_search(). It returns false
396 /// when a quit command is received during the search.
398 bool think(const Position& pos, bool infinite, bool ponder, int time[], int increment[],
399 int movesToGo, int maxDepth, int maxNodes, int maxTime, Move searchMoves[]) {
401 // Initialize global search variables
402 StopOnPonderhit = AbortSearch = Quit = AspirationFailLow = false;
404 ThreadsMgr.resetNodeCounters();
405 SearchStartTime = get_system_time();
406 ExactMaxTime = maxTime;
409 InfiniteSearch = infinite;
410 PonderSearch = ponder;
411 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
413 // Look for a book move, only during games, not tests
414 if (UseTimeManagement && get_option_value_bool("OwnBook"))
416 if (get_option_value_string("Book File") != OpeningBook.file_name())
417 OpeningBook.open(get_option_value_string("Book File"));
419 Move bookMove = OpeningBook.get_move(pos, get_option_value_bool("Best Book Move"));
420 if (bookMove != MOVE_NONE)
423 wait_for_stop_or_ponderhit();
425 cout << "bestmove " << bookMove << endl;
430 // Read UCI option values
431 TT.set_size(get_option_value_int("Hash"));
432 if (button_was_pressed("Clear Hash"))
435 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
436 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
437 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
438 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
439 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
440 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
441 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
442 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
443 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
444 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
445 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
446 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
448 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * ONE_PLY;
449 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
450 MultiPV = get_option_value_int("MultiPV");
451 Chess960 = get_option_value_bool("UCI_Chess960");
452 UseLogFile = get_option_value_bool("Use Search Log");
455 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
457 read_weights(pos.side_to_move());
459 // Set the number of active threads
460 int newActiveThreads = get_option_value_int("Threads");
461 if (newActiveThreads != ThreadsMgr.active_threads())
463 ThreadsMgr.set_active_threads(newActiveThreads);
464 init_eval(ThreadsMgr.active_threads());
467 // Wake up sleeping threads
468 ThreadsMgr.wake_sleeping_threads();
471 int myTime = time[pos.side_to_move()];
472 int myIncrement = increment[pos.side_to_move()];
473 if (UseTimeManagement)
474 TimeMgr.init(myTime, myIncrement, movesToGo, pos.startpos_ply_counter());
476 // Set best NodesBetweenPolls interval to avoid lagging under
477 // heavy time pressure.
479 NodesBetweenPolls = Min(MaxNodes, 30000);
480 else if (myTime && myTime < 1000)
481 NodesBetweenPolls = 1000;
482 else if (myTime && myTime < 5000)
483 NodesBetweenPolls = 5000;
485 NodesBetweenPolls = 30000;
487 // Write search information to log file
489 LogFile << "Searching: " << pos.to_fen() << endl
490 << "infinite: " << infinite
491 << " ponder: " << ponder
492 << " time: " << myTime
493 << " increment: " << myIncrement
494 << " moves to go: " << movesToGo << endl;
496 // We're ready to start thinking. Call the iterative deepening loop function
497 id_loop(pos, searchMoves);
502 ThreadsMgr.put_threads_to_sleep();
510 // id_loop() is the main iterative deepening loop. It calls root_search
511 // repeatedly with increasing depth until the allocated thinking time has
512 // been consumed, the user stops the search, or the maximum search depth is
515 Value id_loop(const Position& pos, Move searchMoves[]) {
517 Position p(pos, pos.thread());
518 SearchStack ss[PLY_MAX_PLUS_2];
519 Move pv[PLY_MAX_PLUS_2];
520 Move EasyMove = MOVE_NONE;
521 Value value, alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
523 // Moves to search are verified, copied, scored and sorted
524 RootMoveList rml(p, searchMoves);
526 // Handle special case of searching on a mate/stale position
527 if (rml.move_count() == 0)
530 wait_for_stop_or_ponderhit();
532 return pos.is_check() ? -VALUE_MATE : VALUE_DRAW;
535 // Print RootMoveList startup scoring to the standard output,
536 // so to output information also for iteration 1.
537 cout << "info depth " << 1
538 << "\ninfo depth " << 1
539 << " score " << value_to_uci(rml.get_move_score(0))
540 << " time " << current_search_time()
541 << " nodes " << ThreadsMgr.nodes_searched()
543 << " pv " << rml.get_move(0) << "\n";
548 init_ss_array(ss, PLY_MAX_PLUS_2);
549 pv[0] = pv[1] = MOVE_NONE;
550 ValueByIteration[1] = rml.get_move_score(0);
553 // Is one move significantly better than others after initial scoring ?
554 if ( rml.move_count() == 1
555 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
556 EasyMove = rml.get_move(0);
558 // Iterative deepening loop
559 while (Iteration < PLY_MAX)
561 // Initialize iteration
563 BestMoveChangesByIteration[Iteration] = 0;
565 cout << "info depth " << Iteration << endl;
567 // Calculate dynamic aspiration window based on previous iterations
568 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
570 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
571 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
573 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
574 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
576 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
577 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
580 // Search to the current depth, rml is updated and sorted, alpha and beta could change
581 value = root_search(p, ss, pv, rml, &alpha, &beta);
583 // Write PV to transposition table, in case the relevant entries have
584 // been overwritten during the search.
585 insert_pv_in_tt(p, pv);
588 break; // Value cannot be trusted. Break out immediately!
590 //Save info about search result
591 ValueByIteration[Iteration] = value;
593 // Drop the easy move if differs from the new best move
594 if (pv[0] != EasyMove)
595 EasyMove = MOVE_NONE;
597 if (UseTimeManagement)
600 bool stopSearch = false;
602 // Stop search early if there is only a single legal move,
603 // we search up to Iteration 6 anyway to get a proper score.
604 if (Iteration >= 6 && rml.move_count() == 1)
607 // Stop search early when the last two iterations returned a mate score
609 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
610 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
613 // Stop search early if one move seems to be much better than the others
614 int64_t nodes = ThreadsMgr.nodes_searched();
617 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
618 && current_search_time() > TimeMgr.available_time() / 16)
619 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
620 && current_search_time() > TimeMgr.available_time() / 32)))
623 // Add some extra time if the best move has changed during the last two iterations
624 if (Iteration > 5 && Iteration <= 50)
625 TimeMgr.pv_unstability(BestMoveChangesByIteration[Iteration],
626 BestMoveChangesByIteration[Iteration-1]);
628 // Stop search if most of MaxSearchTime is consumed at the end of the
629 // iteration. We probably don't have enough time to search the first
630 // move at the next iteration anyway.
631 if (current_search_time() > (TimeMgr.available_time() * 80) / 128)
637 StopOnPonderhit = true;
643 if (MaxDepth && Iteration >= MaxDepth)
647 // If we are pondering or in infinite search, we shouldn't print the
648 // best move before we are told to do so.
649 if (!AbortSearch && (PonderSearch || InfiniteSearch))
650 wait_for_stop_or_ponderhit();
652 // Print final search statistics
653 cout << "info nodes " << ThreadsMgr.nodes_searched()
655 << " time " << current_search_time() << endl;
657 // Print the best move and the ponder move to the standard output
658 if (pv[0] == MOVE_NONE)
660 pv[0] = rml.get_move(0);
664 assert(pv[0] != MOVE_NONE);
666 cout << "bestmove " << pv[0];
668 if (pv[1] != MOVE_NONE)
669 cout << " ponder " << pv[1];
676 dbg_print_mean(LogFile);
678 if (dbg_show_hit_rate)
679 dbg_print_hit_rate(LogFile);
681 LogFile << "\nNodes: " << ThreadsMgr.nodes_searched()
682 << "\nNodes/second: " << nps()
683 << "\nBest move: " << move_to_san(p, pv[0]);
686 p.do_move(pv[0], st);
687 LogFile << "\nPonder move: "
688 << move_to_san(p, pv[1]) // Works also with MOVE_NONE
691 return rml.get_move_score(0);
695 // root_search() is the function which searches the root node. It is
696 // similar to search_pv except that it uses a different move ordering
697 // scheme, prints some information to the standard output and handles
698 // the fail low/high loops.
700 Value root_search(Position& pos, SearchStack* ss, Move* pv, RootMoveList& rml, Value* alphaPtr, Value* betaPtr) {
707 Depth depth, ext, newDepth;
708 Value value, alpha, beta;
709 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
710 int researchCountFH, researchCountFL;
712 researchCountFH = researchCountFL = 0;
715 isCheck = pos.is_check();
716 depth = (Iteration - 2) * ONE_PLY + InitialDepth;
718 // Step 1. Initialize node (polling is omitted at root)
719 ss->currentMove = ss->bestMove = MOVE_NONE;
721 // Step 2. Check for aborted search (omitted at root)
722 // Step 3. Mate distance pruning (omitted at root)
723 // Step 4. Transposition table lookup (omitted at root)
725 // Step 5. Evaluate the position statically
726 // At root we do this only to get reference value for child nodes
727 ss->eval = isCheck ? VALUE_NONE : evaluate(pos, ei);
729 // Step 6. Razoring (omitted at root)
730 // Step 7. Static null move pruning (omitted at root)
731 // Step 8. Null move search with verification search (omitted at root)
732 // Step 9. Internal iterative deepening (omitted at root)
734 // Step extra. Fail low loop
735 // We start with small aspiration window and in case of fail low, we research
736 // with bigger window until we are not failing low anymore.
739 // Sort the moves before to (re)search
740 rml.score_moves(pos);
743 // Step 10. Loop through all moves in the root move list
744 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
746 // This is used by time management
747 FirstRootMove = (i == 0);
749 // Save the current node count before the move is searched
750 nodes = ThreadsMgr.nodes_searched();
752 // Pick the next root move, and print the move and the move number to
753 // the standard output.
754 move = ss->currentMove = rml.get_move(i);
756 if (current_search_time() >= 1000)
757 cout << "info currmove " << move
758 << " currmovenumber " << i + 1 << endl;
760 moveIsCheck = pos.move_is_check(move);
761 captureOrPromotion = pos.move_is_capture_or_promotion(move);
763 // Step 11. Decide the new search depth
764 ext = extension<PV>(pos, move, captureOrPromotion, moveIsCheck, false, false, &dangerous);
765 newDepth = depth + ext;
767 // Step 12. Futility pruning (omitted at root)
769 // Step extra. Fail high loop
770 // If move fails high, we research with bigger window until we are not failing
772 value = - VALUE_INFINITE;
776 // Step 13. Make the move
777 pos.do_move(move, st, ci, moveIsCheck);
779 // Step extra. pv search
780 // We do pv search for first moves (i < MultiPV)
781 // and for fail high research (value > alpha)
782 if (i < MultiPV || value > alpha)
784 // Aspiration window is disabled in multi-pv case
786 alpha = -VALUE_INFINITE;
788 // Full depth PV search, done on first move or after a fail high
789 value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, 1);
793 // Step 14. Reduced search
794 // if the move fails high will be re-searched at full depth
795 bool doFullDepthSearch = true;
797 if ( depth >= 3 * ONE_PLY
799 && !captureOrPromotion
800 && !move_is_castle(move))
802 ss->reduction = reduction<PV>(depth, i - MultiPV + 2);
805 assert(newDepth-ss->reduction >= ONE_PLY);
807 // Reduced depth non-pv search using alpha as upperbound
808 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth-ss->reduction, 1);
809 doFullDepthSearch = (value > alpha);
812 // The move failed high, but if reduction is very big we could
813 // face a false positive, retry with a less aggressive reduction,
814 // if the move fails high again then go with full depth search.
815 if (doFullDepthSearch && ss->reduction > 2 * ONE_PLY)
817 assert(newDepth - ONE_PLY >= ONE_PLY);
819 ss->reduction = ONE_PLY;
820 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth-ss->reduction, 1);
821 doFullDepthSearch = (value > alpha);
823 ss->reduction = DEPTH_ZERO; // Restore original reduction
826 // Step 15. Full depth search
827 if (doFullDepthSearch)
829 // Full depth non-pv search using alpha as upperbound
830 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth, 1);
832 // If we are above alpha then research at same depth but as PV
833 // to get a correct score or eventually a fail high above beta.
835 value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, 1);
839 // Step 16. Undo move
842 // Can we exit fail high loop ?
843 if (AbortSearch || value < beta)
846 // We are failing high and going to do a research. It's important to update
847 // the score before research in case we run out of time while researching.
848 rml.set_move_score(i, value);
850 extract_pv_from_tt(pos, move, pv);
851 rml.set_move_pv(i, pv);
853 // Print information to the standard output
854 print_pv_info(pos, pv, alpha, beta, value);
856 // Prepare for a research after a fail high, each time with a wider window
857 *betaPtr = beta = Min(beta + AspirationDelta * (1 << researchCountFH), VALUE_INFINITE);
860 } // End of fail high loop
862 // Finished searching the move. If AbortSearch is true, the search
863 // was aborted because the user interrupted the search or because we
864 // ran out of time. In this case, the return value of the search cannot
865 // be trusted, and we break out of the loop without updating the best
870 // Remember searched nodes counts for this move
871 rml.set_move_nodes(i, ThreadsMgr.nodes_searched() - nodes);
873 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
874 assert(value < beta);
876 // Step 17. Check for new best move
877 if (value <= alpha && i >= MultiPV)
878 rml.set_move_score(i, -VALUE_INFINITE);
881 // PV move or new best move!
884 rml.set_move_score(i, value);
886 extract_pv_from_tt(pos, move, pv);
887 rml.set_move_pv(i, pv);
891 // We record how often the best move has been changed in each
892 // iteration. This information is used for time managment: When
893 // the best move changes frequently, we allocate some more time.
895 BestMoveChangesByIteration[Iteration]++;
897 // Print information to the standard output
898 print_pv_info(pos, pv, alpha, beta, value);
900 // Raise alpha to setup proper non-pv search upper bound
907 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
909 cout << "info multipv " << j + 1
910 << " score " << value_to_uci(rml.get_move_score(j))
911 << " depth " << (j <= i ? Iteration : Iteration - 1)
912 << " time " << current_search_time()
913 << " nodes " << ThreadsMgr.nodes_searched()
917 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
918 cout << rml.get_move_pv(j, k) << " ";
922 alpha = rml.get_move_score(Min(i, MultiPV - 1));
924 } // PV move or new best move
926 assert(alpha >= *alphaPtr);
928 AspirationFailLow = (alpha == *alphaPtr);
930 if (AspirationFailLow && StopOnPonderhit)
931 StopOnPonderhit = false;
934 // Can we exit fail low loop ?
935 if (AbortSearch || !AspirationFailLow)
938 // Prepare for a research after a fail low, each time with a wider window
939 *alphaPtr = alpha = Max(alpha - AspirationDelta * (1 << researchCountFL), -VALUE_INFINITE);
944 // Sort the moves before to return
951 // search<>() is the main search function for both PV and non-PV nodes
953 template <NodeType PvNode>
954 Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
956 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
957 assert(beta > alpha && beta <= VALUE_INFINITE);
958 assert(PvNode || alpha == beta - 1);
959 assert(ply > 0 && ply < PLY_MAX);
960 assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
962 Move movesSearched[256];
967 Move ttMove, move, excludedMove, threatMove;
969 Value bestValue, value, oldAlpha;
970 Value refinedValue, nullValue, futilityValueScaled; // Non-PV specific
971 bool isCheck, singleEvasion, singularExtensionNode, moveIsCheck, captureOrPromotion, dangerous;
972 bool mateThreat = false;
974 int threadID = pos.thread();
975 refinedValue = bestValue = value = -VALUE_INFINITE;
978 // Step 1. Initialize node and poll. Polling can abort search
979 ThreadsMgr.incrementNodeCounter(threadID);
980 ss->currentMove = ss->bestMove = threatMove = MOVE_NONE;
981 (ss+2)->killers[0] = (ss+2)->killers[1] = (ss+2)->mateKiller = MOVE_NONE;
983 if (threadID == 0 && ++NodesSincePoll > NodesBetweenPolls)
989 // Step 2. Check for aborted search and immediate draw
990 if (AbortSearch || ThreadsMgr.thread_should_stop(threadID))
993 if (pos.is_draw() || ply >= PLY_MAX - 1)
996 // Step 3. Mate distance pruning
997 alpha = Max(value_mated_in(ply), alpha);
998 beta = Min(value_mate_in(ply+1), beta);
1002 // Step 4. Transposition table lookup
1004 // We don't want the score of a partial search to overwrite a previous full search
1005 // TT value, so we use a different position key in case of an excluded move exists.
1006 excludedMove = ss->excludedMove;
1007 posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1009 tte = TT.retrieve(posKey);
1010 ttMove = (tte ? tte->move() : MOVE_NONE);
1012 // At PV nodes, we don't use the TT for pruning, but only for move ordering.
1013 // This is to avoid problems in the following areas:
1015 // * Repetition draw detection
1016 // * Fifty move rule detection
1017 // * Searching for a mate
1018 // * Printing of full PV line
1020 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1022 // Refresh tte entry to avoid aging
1023 TT.store(posKey, tte->value(), tte->type(), tte->depth(), ttMove, tte->static_value(), tte->king_danger());
1025 ss->bestMove = ttMove; // Can be MOVE_NONE
1026 return value_from_tt(tte->value(), ply);
1029 // Step 5. Evaluate the position statically and
1030 // update gain statistics of parent move.
1031 isCheck = pos.is_check();
1033 ss->eval = VALUE_NONE;
1036 assert(tte->static_value() != VALUE_NONE);
1038 ss->eval = tte->static_value();
1039 ei.kingDanger[pos.side_to_move()] = tte->king_danger();
1040 refinedValue = refine_eval(tte, ss->eval, ply);
1044 refinedValue = ss->eval = evaluate(pos, ei);
1045 TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ei.kingDanger[pos.side_to_move()]);
1048 // Save gain for the parent non-capture move
1049 update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1051 // Step 6. Razoring (is omitted in PV nodes)
1053 && depth < RazorDepth
1055 && refinedValue < beta - razor_margin(depth)
1056 && ttMove == MOVE_NONE
1057 && (ss-1)->currentMove != MOVE_NULL
1058 && !value_is_mate(beta)
1059 && !pos.has_pawn_on_7th(pos.side_to_move()))
1061 Value rbeta = beta - razor_margin(depth);
1062 Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO, ply);
1064 // Logically we should return (v + razor_margin(depth)), but
1065 // surprisingly this did slightly weaker in tests.
1069 // Step 7. Static null move pruning (is omitted in PV nodes)
1070 // We're betting that the opponent doesn't have a move that will reduce
1071 // the score by more than futility_margin(depth) if we do a null move.
1073 && !ss->skipNullMove
1074 && depth < RazorDepth
1076 && refinedValue >= beta + futility_margin(depth, 0)
1077 && !value_is_mate(beta)
1078 && pos.non_pawn_material(pos.side_to_move()))
1079 return refinedValue - futility_margin(depth, 0);
1081 // Step 8. Null move search with verification search (is omitted in PV nodes)
1082 // When we jump directly to qsearch() we do a null move only if static value is
1083 // at least beta. Otherwise we do a null move if static value is not more than
1084 // NullMoveMargin under beta.
1086 && !ss->skipNullMove
1089 && refinedValue >= beta - (depth >= 4 * ONE_PLY ? NullMoveMargin : 0)
1090 && !value_is_mate(beta)
1091 && pos.non_pawn_material(pos.side_to_move()))
1093 ss->currentMove = MOVE_NULL;
1095 // Null move dynamic reduction based on depth
1096 int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
1098 // Null move dynamic reduction based on value
1099 if (refinedValue - beta > PawnValueMidgame)
1102 pos.do_null_move(st);
1103 (ss+1)->skipNullMove = true;
1105 nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO, ply+1)
1106 : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY, ply+1);
1107 (ss+1)->skipNullMove = false;
1108 pos.undo_null_move();
1110 if (nullValue >= beta)
1112 // Do not return unproven mate scores
1113 if (nullValue >= value_mate_in(PLY_MAX))
1116 if (depth < 6 * ONE_PLY)
1119 // Do verification search at high depths
1120 ss->skipNullMove = true;
1121 Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY, ply);
1122 ss->skipNullMove = false;
1129 // The null move failed low, which means that we may be faced with
1130 // some kind of threat. If the previous move was reduced, check if
1131 // the move that refuted the null move was somehow connected to the
1132 // move which was reduced. If a connection is found, return a fail
1133 // low score (which will cause the reduced move to fail high in the
1134 // parent node, which will trigger a re-search with full depth).
1135 if (nullValue == value_mated_in(ply + 2))
1138 threatMove = (ss+1)->bestMove;
1139 if ( depth < ThreatDepth
1140 && (ss-1)->reduction
1141 && connected_moves(pos, (ss-1)->currentMove, threatMove))
1146 // Step 9. Internal iterative deepening
1147 if ( depth >= IIDDepth[PvNode]
1148 && ttMove == MOVE_NONE
1149 && (PvNode || (!isCheck && ss->eval >= beta - IIDMargin)))
1151 Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
1153 ss->skipNullMove = true;
1154 search<PvNode>(pos, ss, alpha, beta, d, ply);
1155 ss->skipNullMove = false;
1157 ttMove = ss->bestMove;
1158 tte = TT.retrieve(posKey);
1161 // Expensive mate threat detection (only for PV nodes)
1163 mateThreat = pos.has_mate_threat();
1165 // Initialize a MovePicker object for the current position
1166 MovePicker mp = MovePicker(pos, ttMove, depth, H, ss, (PvNode ? -VALUE_INFINITE : beta));
1168 ss->bestMove = MOVE_NONE;
1169 singleEvasion = isCheck && mp.number_of_evasions() == 1;
1170 singularExtensionNode = depth >= SingularExtensionDepth[PvNode]
1173 && !excludedMove // Do not allow recursive singular extension search
1174 && (tte->type() & VALUE_TYPE_LOWER)
1175 && tte->depth() >= depth - 3 * ONE_PLY;
1177 // Step 10. Loop through moves
1178 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1179 while ( bestValue < beta
1180 && (move = mp.get_next_move()) != MOVE_NONE
1181 && !ThreadsMgr.thread_should_stop(threadID))
1183 assert(move_is_ok(move));
1185 if (move == excludedMove)
1188 moveIsCheck = pos.move_is_check(move, ci);
1189 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1191 // Step 11. Decide the new search depth
1192 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1194 // Singular extension search. If all moves but one fail low on a search of (alpha-s, beta-s),
1195 // and just one fails high on (alpha, beta), then that move is singular and should be extended.
1196 // To verify this we do a reduced search on all the other moves but the ttMove, if result is
1197 // lower then ttValue minus a margin then we extend ttMove.
1198 if ( singularExtensionNode
1199 && move == tte->move()
1202 Value ttValue = value_from_tt(tte->value(), ply);
1204 if (abs(ttValue) < VALUE_KNOWN_WIN)
1206 Value b = ttValue - SingularExtensionMargin;
1207 ss->excludedMove = move;
1208 ss->skipNullMove = true;
1209 Value v = search<NonPV>(pos, ss, b - 1, b, depth / 2, ply);
1210 ss->skipNullMove = false;
1211 ss->excludedMove = MOVE_NONE;
1212 ss->bestMove = MOVE_NONE;
1218 newDepth = depth - ONE_PLY + ext;
1220 // Update current move (this must be done after singular extension search)
1221 movesSearched[moveCount++] = ss->currentMove = move;
1223 // Step 12. Futility pruning (is omitted in PV nodes)
1225 && !captureOrPromotion
1229 && !move_is_castle(move))
1231 // Move count based pruning
1232 if ( moveCount >= futility_move_count(depth)
1233 && !(threatMove && connected_threat(pos, move, threatMove))
1234 && bestValue > value_mated_in(PLY_MAX))
1237 // Value based pruning
1238 // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1239 // but fixing this made program slightly weaker.
1240 Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount);
1241 futilityValueScaled = ss->eval + futility_margin(predictedDepth, moveCount)
1242 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1244 if (futilityValueScaled < beta)
1246 if (futilityValueScaled > bestValue)
1247 bestValue = futilityValueScaled;
1252 // Step 13. Make the move
1253 pos.do_move(move, st, ci, moveIsCheck);
1255 // Step extra. pv search (only in PV nodes)
1256 // The first move in list is the expected PV
1257 if (PvNode && moveCount == 1)
1258 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO, ply+1)
1259 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth, ply+1);
1262 // Step 14. Reduced depth search
1263 // If the move fails high will be re-searched at full depth.
1264 bool doFullDepthSearch = true;
1266 if ( depth >= 3 * ONE_PLY
1267 && !captureOrPromotion
1269 && !move_is_castle(move)
1270 && !move_is_killer(move, ss))
1272 ss->reduction = reduction<PvNode>(depth, moveCount);
1275 Depth d = newDepth - ss->reduction;
1276 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO, ply+1)
1277 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d, ply+1);
1279 doFullDepthSearch = (value > alpha);
1282 // The move failed high, but if reduction is very big we could
1283 // face a false positive, retry with a less aggressive reduction,
1284 // if the move fails high again then go with full depth search.
1285 if (doFullDepthSearch && ss->reduction > 2 * ONE_PLY)
1287 assert(newDepth - ONE_PLY >= ONE_PLY);
1289 ss->reduction = ONE_PLY;
1290 value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth-ss->reduction, ply+1);
1291 doFullDepthSearch = (value > alpha);
1293 ss->reduction = DEPTH_ZERO; // Restore original reduction
1296 // Step 15. Full depth search
1297 if (doFullDepthSearch)
1299 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO, ply+1)
1300 : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth, ply+1);
1302 // Step extra. pv search (only in PV nodes)
1303 // Search only for possible new PV nodes, if instead value >= beta then
1304 // parent node fails low with value <= alpha and tries another move.
1305 if (PvNode && value > alpha && value < beta)
1306 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO, ply+1)
1307 : - search<PV>(pos, ss+1, -beta, -alpha, newDepth, ply+1);
1311 // Step 16. Undo move
1312 pos.undo_move(move);
1314 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1316 // Step 17. Check for new best move
1317 if (value > bestValue)
1322 if (PvNode && value < beta) // We want always alpha < beta
1325 if (value == value_mate_in(ply + 1))
1326 ss->mateKiller = move;
1328 ss->bestMove = move;
1332 // Step 18. Check for split
1333 if ( depth >= MinimumSplitDepth
1334 && ThreadsMgr.active_threads() > 1
1336 && ThreadsMgr.available_thread_exists(threadID)
1338 && !ThreadsMgr.thread_should_stop(threadID)
1340 ThreadsMgr.split<FakeSplit>(pos, ss, ply, &alpha, beta, &bestValue, depth,
1341 threatMove, mateThreat, &moveCount, &mp, PvNode);
1344 // Step 19. Check for mate and stalemate
1345 // All legal moves have been searched and if there are
1346 // no legal moves, it must be mate or stalemate.
1347 // If one move was excluded return fail low score.
1349 return excludedMove ? oldAlpha : isCheck ? value_mated_in(ply) : VALUE_DRAW;
1351 // Step 20. Update tables
1352 // If the search is not aborted, update the transposition table,
1353 // history counters, and killer moves.
1354 if (AbortSearch || ThreadsMgr.thread_should_stop(threadID))
1357 ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1358 move = (bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove);
1359 TT.store(posKey, value_to_tt(bestValue, ply), vt, depth, move, ss->eval, ei.kingDanger[pos.side_to_move()]);
1361 // Update killers and history only for non capture moves that fails high
1362 if ( bestValue >= beta
1363 && !pos.move_is_capture_or_promotion(move))
1365 update_history(pos, move, depth, movesSearched, moveCount);
1366 update_killers(move, ss);
1369 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1375 // qsearch() is the quiescence search function, which is called by the main
1376 // search function when the remaining depth is zero (or, to be more precise,
1377 // less than ONE_PLY).
1379 template <NodeType PvNode>
1380 Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
1382 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1383 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1384 assert(PvNode || alpha == beta - 1);
1386 assert(ply > 0 && ply < PLY_MAX);
1387 assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
1392 Value bestValue, value, futilityValue, futilityBase;
1393 bool isCheck, deepChecks, enoughMaterial, moveIsCheck, evasionPrunable;
1395 Value oldAlpha = alpha;
1397 ThreadsMgr.incrementNodeCounter(pos.thread());
1398 ss->bestMove = ss->currentMove = MOVE_NONE;
1400 // Check for an instant draw or maximum ply reached
1401 if (pos.is_draw() || ply >= PLY_MAX - 1)
1404 // Transposition table lookup. At PV nodes, we don't use the TT for
1405 // pruning, but only for move ordering.
1406 tte = TT.retrieve(pos.get_key());
1407 ttMove = (tte ? tte->move() : MOVE_NONE);
1409 if (!PvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1411 ss->bestMove = ttMove; // Can be MOVE_NONE
1412 return value_from_tt(tte->value(), ply);
1415 isCheck = pos.is_check();
1417 // Evaluate the position statically
1420 bestValue = futilityBase = -VALUE_INFINITE;
1421 ss->eval = VALUE_NONE;
1422 deepChecks = enoughMaterial = false;
1428 assert(tte->static_value() != VALUE_NONE);
1430 ei.kingDanger[pos.side_to_move()] = tte->king_danger();
1431 bestValue = tte->static_value();
1434 bestValue = evaluate(pos, ei);
1436 ss->eval = bestValue;
1437 update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1439 // Stand pat. Return immediately if static value is at least beta
1440 if (bestValue >= beta)
1443 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()]);
1448 if (PvNode && bestValue > alpha)
1451 // If we are near beta then try to get a cutoff pushing checks a bit further
1452 deepChecks = (depth == -ONE_PLY && bestValue >= beta - PawnValueMidgame / 8);
1454 // Futility pruning parameters, not needed when in check
1455 futilityBase = bestValue + FutilityMarginQS + ei.kingDanger[pos.side_to_move()];
1456 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1459 // Initialize a MovePicker object for the current position, and prepare
1460 // to search the moves. Because the depth is <= 0 here, only captures,
1461 // queen promotions and checks (only if depth == 0 or depth == -ONE_PLY
1462 // and we are near beta) will be generated.
1463 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? DEPTH_ZERO : depth, H);
1466 // Loop through the moves until no moves remain or a beta cutoff occurs
1467 while ( alpha < beta
1468 && (move = mp.get_next_move()) != MOVE_NONE)
1470 assert(move_is_ok(move));
1472 moveIsCheck = pos.move_is_check(move, ci);
1480 && !move_is_promotion(move)
1481 && !pos.move_is_passed_pawn_push(move))
1483 futilityValue = futilityBase
1484 + pos.endgame_value_of_piece_on(move_to(move))
1485 + (move_is_ep(move) ? PawnValueEndgame : VALUE_ZERO);
1487 if (futilityValue < alpha)
1489 if (futilityValue > bestValue)
1490 bestValue = futilityValue;
1495 // Detect blocking evasions that are candidate to be pruned
1496 evasionPrunable = isCheck
1497 && bestValue > value_mated_in(PLY_MAX)
1498 && !pos.move_is_capture(move)
1499 && pos.type_of_piece_on(move_from(move)) != KING
1500 && !pos.can_castle(pos.side_to_move());
1502 // Don't search moves with negative SEE values
1504 && (!isCheck || evasionPrunable)
1506 && !move_is_promotion(move)
1507 && pos.see_sign(move) < 0)
1510 // Update current move
1511 ss->currentMove = move;
1513 // Make and search the move
1514 pos.do_move(move, st, ci, moveIsCheck);
1515 value = -qsearch<PvNode>(pos, ss+1, -beta, -alpha, depth-ONE_PLY, ply+1);
1516 pos.undo_move(move);
1518 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1521 if (value > bestValue)
1527 ss->bestMove = move;
1532 // All legal moves have been searched. A special case: If we're in check
1533 // and no legal moves were found, it is checkmate.
1534 if (isCheck && bestValue == -VALUE_INFINITE)
1535 return value_mated_in(ply);
1537 // Update transposition table
1538 Depth d = (depth == DEPTH_ZERO ? DEPTH_ZERO : DEPTH_ZERO - ONE_PLY);
1539 ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1540 TT.store(pos.get_key(), value_to_tt(bestValue, ply), vt, d, ss->bestMove, ss->eval, ei.kingDanger[pos.side_to_move()]);
1542 // Update killers only for checking moves that fails high
1543 if ( bestValue >= beta
1544 && !pos.move_is_capture_or_promotion(ss->bestMove))
1545 update_killers(ss->bestMove, ss);
1547 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1553 // sp_search() is used to search from a split point. This function is called
1554 // by each thread working at the split point. It is similar to the normal
1555 // search() function, but simpler. Because we have already probed the hash
1556 // table, done a null move search, and searched the first move before
1557 // splitting, we don't have to repeat all this work in sp_search(). We
1558 // also don't need to store anything to the hash table here: This is taken
1559 // care of after we return from the split point.
1561 template <NodeType PvNode>
1562 void sp_search(SplitPoint* sp, int threadID) {
1564 assert(threadID >= 0 && threadID < ThreadsMgr.active_threads());
1565 assert(ThreadsMgr.active_threads() > 1);
1569 Depth ext, newDepth;
1571 Value futilityValueScaled; // NonPV specific
1572 bool isCheck, moveIsCheck, captureOrPromotion, dangerous;
1574 value = -VALUE_INFINITE;
1576 Position pos(*sp->pos, threadID);
1578 SearchStack* ss = sp->sstack[threadID] + 1;
1579 isCheck = pos.is_check();
1581 // Step 10. Loop through moves
1582 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1583 lock_grab(&(sp->lock));
1585 while ( sp->bestValue < sp->beta
1586 && (move = sp->mp->get_next_move()) != MOVE_NONE
1587 && !ThreadsMgr.thread_should_stop(threadID))
1589 moveCount = ++sp->moveCount;
1590 lock_release(&(sp->lock));
1592 assert(move_is_ok(move));
1594 moveIsCheck = pos.move_is_check(move, ci);
1595 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1597 // Step 11. Decide the new search depth
1598 ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, false, sp->mateThreat, &dangerous);
1599 newDepth = sp->depth - ONE_PLY + ext;
1601 // Update current move
1602 ss->currentMove = move;
1604 // Step 12. Futility pruning (is omitted in PV nodes)
1606 && !captureOrPromotion
1609 && !move_is_castle(move))
1611 // Move count based pruning
1612 if ( moveCount >= futility_move_count(sp->depth)
1613 && !(sp->threatMove && connected_threat(pos, move, sp->threatMove))
1614 && sp->bestValue > value_mated_in(PLY_MAX))
1616 lock_grab(&(sp->lock));
1620 // Value based pruning
1621 Depth predictedDepth = newDepth - reduction<NonPV>(sp->depth, moveCount);
1622 futilityValueScaled = ss->eval + futility_margin(predictedDepth, moveCount)
1623 + H.gain(pos.piece_on(move_from(move)), move_to(move));
1625 if (futilityValueScaled < sp->beta)
1627 lock_grab(&(sp->lock));
1629 if (futilityValueScaled > sp->bestValue)
1630 sp->bestValue = futilityValueScaled;
1635 // Step 13. Make the move
1636 pos.do_move(move, st, ci, moveIsCheck);
1638 // Step 14. Reduced search
1639 // If the move fails high will be re-searched at full depth.
1640 bool doFullDepthSearch = true;
1642 if ( !captureOrPromotion
1644 && !move_is_castle(move)
1645 && !move_is_killer(move, ss))
1647 ss->reduction = reduction<PvNode>(sp->depth, moveCount);
1650 Value localAlpha = sp->alpha;
1651 Depth d = newDepth - ss->reduction;
1652 value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, DEPTH_ZERO, sp->ply+1)
1653 : - search<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, d, sp->ply+1);
1655 doFullDepthSearch = (value > localAlpha);
1658 // The move failed high, but if reduction is very big we could
1659 // face a false positive, retry with a less aggressive reduction,
1660 // if the move fails high again then go with full depth search.
1661 if (doFullDepthSearch && ss->reduction > 2 * ONE_PLY)
1663 assert(newDepth - ONE_PLY >= ONE_PLY);
1665 ss->reduction = ONE_PLY;
1666 Value localAlpha = sp->alpha;
1667 value = -search<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, newDepth-ss->reduction, sp->ply+1);
1668 doFullDepthSearch = (value > localAlpha);
1670 ss->reduction = DEPTH_ZERO; // Restore original reduction
1673 // Step 15. Full depth search
1674 if (doFullDepthSearch)
1676 Value localAlpha = sp->alpha;
1677 value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, DEPTH_ZERO, sp->ply+1)
1678 : - search<NonPV>(pos, ss+1, -(localAlpha+1), -localAlpha, newDepth, sp->ply+1);
1680 // Step extra. pv search (only in PV nodes)
1681 // Search only for possible new PV nodes, if instead value >= beta then
1682 // parent node fails low with value <= alpha and tries another move.
1683 if (PvNode && value > localAlpha && value < sp->beta)
1684 value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -sp->beta, -sp->alpha, DEPTH_ZERO, sp->ply+1)
1685 : - search<PV>(pos, ss+1, -sp->beta, -sp->alpha, newDepth, sp->ply+1);
1688 // Step 16. Undo move
1689 pos.undo_move(move);
1691 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1693 // Step 17. Check for new best move
1694 lock_grab(&(sp->lock));
1696 if (value > sp->bestValue && !ThreadsMgr.thread_should_stop(threadID))
1698 sp->bestValue = value;
1700 if (sp->bestValue > sp->alpha)
1702 if (!PvNode || value >= sp->beta)
1703 sp->stopRequest = true;
1705 if (PvNode && value < sp->beta) // This guarantees that always: sp->alpha < sp->beta
1708 sp->parentSstack->bestMove = ss->bestMove = move;
1713 /* Here we have the lock still grabbed */
1715 sp->slaves[threadID] = 0;
1717 lock_release(&(sp->lock));
1721 // connected_moves() tests whether two moves are 'connected' in the sense
1722 // that the first move somehow made the second move possible (for instance
1723 // if the moving piece is the same in both moves). The first move is assumed
1724 // to be the move that was made to reach the current position, while the
1725 // second move is assumed to be a move from the current position.
1727 bool connected_moves(const Position& pos, Move m1, Move m2) {
1729 Square f1, t1, f2, t2;
1732 assert(move_is_ok(m1));
1733 assert(move_is_ok(m2));
1735 if (m2 == MOVE_NONE)
1738 // Case 1: The moving piece is the same in both moves
1744 // Case 2: The destination square for m2 was vacated by m1
1750 // Case 3: Moving through the vacated square
1751 if ( piece_is_slider(pos.piece_on(f2))
1752 && bit_is_set(squares_between(f2, t2), f1))
1755 // Case 4: The destination square for m2 is defended by the moving piece in m1
1756 p = pos.piece_on(t1);
1757 if (bit_is_set(pos.attacks_from(p, t1), t2))
1760 // Case 5: Discovered check, checking piece is the piece moved in m1
1761 if ( piece_is_slider(p)
1762 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1763 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1765 // discovered_check_candidates() works also if the Position's side to
1766 // move is the opposite of the checking piece.
1767 Color them = opposite_color(pos.side_to_move());
1768 Bitboard dcCandidates = pos.discovered_check_candidates(them);
1770 if (bit_is_set(dcCandidates, f2))
1777 // value_is_mate() checks if the given value is a mate one eventually
1778 // compensated for the ply.
1780 bool value_is_mate(Value value) {
1782 assert(abs(value) <= VALUE_INFINITE);
1784 return value <= value_mated_in(PLY_MAX)
1785 || value >= value_mate_in(PLY_MAX);
1789 // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1790 // "plies to mate from the current ply". Non-mate scores are unchanged.
1791 // The function is called before storing a value to the transposition table.
1793 Value value_to_tt(Value v, int ply) {
1795 if (v >= value_mate_in(PLY_MAX))
1798 if (v <= value_mated_in(PLY_MAX))
1805 // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1806 // the transposition table to a mate score corrected for the current ply.
1808 Value value_from_tt(Value v, int ply) {
1810 if (v >= value_mate_in(PLY_MAX))
1813 if (v <= value_mated_in(PLY_MAX))
1820 // move_is_killer() checks if the given move is among the killer moves
1822 bool move_is_killer(Move m, SearchStack* ss) {
1824 if (ss->killers[0] == m || ss->killers[1] == m)
1831 // extension() decides whether a move should be searched with normal depth,
1832 // or with extended depth. Certain classes of moves (checking moves, in
1833 // particular) are searched with bigger depth than ordinary moves and in
1834 // any case are marked as 'dangerous'. Note that also if a move is not
1835 // extended, as example because the corresponding UCI option is set to zero,
1836 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1837 template <NodeType PvNode>
1838 Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck,
1839 bool singleEvasion, bool mateThreat, bool* dangerous) {
1841 assert(m != MOVE_NONE);
1843 Depth result = DEPTH_ZERO;
1844 *dangerous = moveIsCheck | singleEvasion | mateThreat;
1848 if (moveIsCheck && pos.see_sign(m) >= 0)
1849 result += CheckExtension[PvNode];
1852 result += SingleEvasionExtension[PvNode];
1855 result += MateThreatExtension[PvNode];
1858 if (pos.type_of_piece_on(move_from(m)) == PAWN)
1860 Color c = pos.side_to_move();
1861 if (relative_rank(c, move_to(m)) == RANK_7)
1863 result += PawnPushTo7thExtension[PvNode];
1866 if (pos.pawn_is_passed(c, move_to(m)))
1868 result += PassedPawnExtension[PvNode];
1873 if ( captureOrPromotion
1874 && pos.type_of_piece_on(move_to(m)) != PAWN
1875 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1876 - pos.midgame_value_of_piece_on(move_to(m)) == VALUE_ZERO)
1877 && !move_is_promotion(m)
1880 result += PawnEndgameExtension[PvNode];
1885 && captureOrPromotion
1886 && pos.type_of_piece_on(move_to(m)) != PAWN
1887 && pos.see_sign(m) >= 0)
1889 result += ONE_PLY / 2;
1893 return Min(result, ONE_PLY);
1897 // connected_threat() tests whether it is safe to forward prune a move or if
1898 // is somehow coonected to the threat move returned by null search.
1900 bool connected_threat(const Position& pos, Move m, Move threat) {
1902 assert(move_is_ok(m));
1903 assert(threat && move_is_ok(threat));
1904 assert(!pos.move_is_check(m));
1905 assert(!pos.move_is_capture_or_promotion(m));
1906 assert(!pos.move_is_passed_pawn_push(m));
1908 Square mfrom, mto, tfrom, tto;
1910 mfrom = move_from(m);
1912 tfrom = move_from(threat);
1913 tto = move_to(threat);
1915 // Case 1: Don't prune moves which move the threatened piece
1919 // Case 2: If the threatened piece has value less than or equal to the
1920 // value of the threatening piece, don't prune move which defend it.
1921 if ( pos.move_is_capture(threat)
1922 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
1923 || pos.type_of_piece_on(tfrom) == KING)
1924 && pos.move_attacks_square(m, tto))
1927 // Case 3: If the moving piece in the threatened move is a slider, don't
1928 // prune safe moves which block its ray.
1929 if ( piece_is_slider(pos.piece_on(tfrom))
1930 && bit_is_set(squares_between(tfrom, tto), mto)
1931 && pos.see_sign(m) >= 0)
1938 // ok_to_use_TT() returns true if a transposition table score
1939 // can be used at a given point in search.
1941 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1943 Value v = value_from_tt(tte->value(), ply);
1945 return ( tte->depth() >= depth
1946 || v >= Max(value_mate_in(PLY_MAX), beta)
1947 || v < Min(value_mated_in(PLY_MAX), beta))
1949 && ( ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1950 || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1954 // refine_eval() returns the transposition table score if
1955 // possible otherwise falls back on static position evaluation.
1957 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1961 Value v = value_from_tt(tte->value(), ply);
1963 if ( ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1964 || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1971 // update_history() registers a good move that produced a beta-cutoff
1972 // in history and marks as failures all the other moves of that ply.
1974 void update_history(const Position& pos, Move move, Depth depth,
1975 Move movesSearched[], int moveCount) {
1979 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
1981 for (int i = 0; i < moveCount - 1; i++)
1983 m = movesSearched[i];
1987 if (!pos.move_is_capture_or_promotion(m))
1988 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
1993 // update_killers() add a good move that produced a beta-cutoff
1994 // among the killer moves of that ply.
1996 void update_killers(Move m, SearchStack* ss) {
1998 if (m == ss->killers[0])
2001 ss->killers[1] = ss->killers[0];
2006 // update_gains() updates the gains table of a non-capture move given
2007 // the static position evaluation before and after the move.
2009 void update_gains(const Position& pos, Move m, Value before, Value after) {
2012 && before != VALUE_NONE
2013 && after != VALUE_NONE
2014 && pos.captured_piece_type() == PIECE_TYPE_NONE
2015 && !move_is_special(m))
2016 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2020 // current_search_time() returns the number of milliseconds which have passed
2021 // since the beginning of the current search.
2023 int current_search_time() {
2025 return get_system_time() - SearchStartTime;
2029 // value_to_uci() converts a value to a string suitable for use with the UCI protocol
2031 std::string value_to_uci(Value v) {
2033 std::stringstream s;
2035 if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
2036 s << "cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to pawn = 100
2038 s << "mate " << (v > 0 ? (VALUE_MATE - v + 1) / 2 : -(VALUE_MATE + v) / 2 );
2043 // nps() computes the current nodes/second count.
2047 int t = current_search_time();
2048 return (t > 0 ? int((ThreadsMgr.nodes_searched() * 1000) / t) : 0);
2052 // poll() performs two different functions: It polls for user input, and it
2053 // looks at the time consumed so far and decides if it's time to abort the
2058 static int lastInfoTime;
2059 int t = current_search_time();
2064 // We are line oriented, don't read single chars
2065 std::string command;
2067 if (!std::getline(std::cin, command))
2070 if (command == "quit")
2073 PonderSearch = false;
2077 else if (command == "stop")
2080 PonderSearch = false;
2082 else if (command == "ponderhit")
2086 // Print search information
2090 else if (lastInfoTime > t)
2091 // HACK: Must be a new search where we searched less than
2092 // NodesBetweenPolls nodes during the first second of search.
2095 else if (t - lastInfoTime >= 1000)
2102 if (dbg_show_hit_rate)
2103 dbg_print_hit_rate();
2105 cout << "info nodes " << ThreadsMgr.nodes_searched() << " nps " << nps()
2106 << " time " << t << endl;
2109 // Should we stop the search?
2113 bool stillAtFirstMove = FirstRootMove
2114 && !AspirationFailLow
2115 && t > TimeMgr.available_time();
2117 bool noMoreTime = t > TimeMgr.maximum_time()
2118 || stillAtFirstMove;
2120 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2121 || (ExactMaxTime && t >= ExactMaxTime)
2122 || (Iteration >= 3 && MaxNodes && ThreadsMgr.nodes_searched() >= MaxNodes))
2127 // ponderhit() is called when the program is pondering (i.e. thinking while
2128 // it's the opponent's turn to move) in order to let the engine know that
2129 // it correctly predicted the opponent's move.
2133 int t = current_search_time();
2134 PonderSearch = false;
2136 bool stillAtFirstMove = FirstRootMove
2137 && !AspirationFailLow
2138 && t > TimeMgr.available_time();
2140 bool noMoreTime = t > TimeMgr.maximum_time()
2141 || stillAtFirstMove;
2143 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2148 // init_ss_array() does a fast reset of the first entries of a SearchStack
2149 // array and of all the excludedMove and skipNullMove entries.
2151 void init_ss_array(SearchStack* ss, int size) {
2153 for (int i = 0; i < size; i++, ss++)
2155 ss->excludedMove = MOVE_NONE;
2156 ss->skipNullMove = false;
2157 ss->reduction = DEPTH_ZERO;
2160 ss->killers[0] = ss->killers[1] = ss->mateKiller = MOVE_NONE;
2165 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2166 // while the program is pondering. The point is to work around a wrinkle in
2167 // the UCI protocol: When pondering, the engine is not allowed to give a
2168 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2169 // We simply wait here until one of these commands is sent, and return,
2170 // after which the bestmove and pondermove will be printed (in id_loop()).
2172 void wait_for_stop_or_ponderhit() {
2174 std::string command;
2178 if (!std::getline(std::cin, command))
2181 if (command == "quit")
2186 else if (command == "ponderhit" || command == "stop")
2192 // print_pv_info() prints to standard output and eventually to log file information on
2193 // the current PV line. It is called at each iteration or after a new pv is found.
2195 void print_pv_info(const Position& pos, Move pv[], Value alpha, Value beta, Value value) {
2197 cout << "info depth " << Iteration
2198 << " score " << value_to_uci(value)
2199 << (value >= beta ? " lowerbound" : value <= alpha ? " upperbound" : "")
2200 << " time " << current_search_time()
2201 << " nodes " << ThreadsMgr.nodes_searched()
2205 for (Move* m = pv; *m != MOVE_NONE; m++)
2212 ValueType t = value >= beta ? VALUE_TYPE_LOWER :
2213 value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT;
2215 LogFile << pretty_pv(pos, current_search_time(), Iteration,
2216 ThreadsMgr.nodes_searched(), value, t, pv) << endl;
2221 // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2222 // the PV back into the TT. This makes sure the old PV moves are searched
2223 // first, even if the old TT entries have been overwritten.
2225 void insert_pv_in_tt(const Position& pos, Move pv[]) {
2229 Position p(pos, pos.thread());
2233 for (int i = 0; pv[i] != MOVE_NONE; i++)
2235 tte = TT.retrieve(p.get_key());
2236 if (!tte || tte->move() != pv[i])
2238 v = (p.is_check() ? VALUE_NONE : evaluate(p, ei));
2239 TT.store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[i], v, ei.kingDanger[pos.side_to_move()]);
2241 p.do_move(pv[i], st);
2246 // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2247 // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2248 // allow to always have a ponder move even when we fail high at root and also a
2249 // long PV to print that is important for position analysis.
2251 void extract_pv_from_tt(const Position& pos, Move bestMove, Move pv[]) {
2255 Position p(pos, pos.thread());
2258 assert(bestMove != MOVE_NONE);
2261 p.do_move(pv[ply++], st);
2263 while ( (tte = TT.retrieve(p.get_key())) != NULL
2264 && tte->move() != MOVE_NONE
2265 && move_is_legal(p, tte->move())
2267 && (!p.is_draw() || ply < 2))
2269 pv[ply] = tte->move();
2270 p.do_move(pv[ply++], st);
2272 pv[ply] = MOVE_NONE;
2276 // init_thread() is the function which is called when a new thread is
2277 // launched. It simply calls the idle_loop() function with the supplied
2278 // threadID. There are two versions of this function; one for POSIX
2279 // threads and one for Windows threads.
2281 #if !defined(_MSC_VER)
2283 void* init_thread(void *threadID) {
2285 ThreadsMgr.idle_loop(*(int*)threadID, NULL);
2291 DWORD WINAPI init_thread(LPVOID threadID) {
2293 ThreadsMgr.idle_loop(*(int*)threadID, NULL);
2300 /// The ThreadsManager class
2302 // resetNodeCounters(), resetBetaCounters(), searched_nodes() and
2303 // get_beta_counters() are getters/setters for the per thread
2304 // counters used to sort the moves at root.
2306 void ThreadsManager::resetNodeCounters() {
2308 for (int i = 0; i < MAX_THREADS; i++)
2309 threads[i].nodes = 0ULL;
2312 int64_t ThreadsManager::nodes_searched() const {
2314 int64_t result = 0ULL;
2315 for (int i = 0; i < ActiveThreads; i++)
2316 result += threads[i].nodes;
2322 // idle_loop() is where the threads are parked when they have no work to do.
2323 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2324 // object for which the current thread is the master.
2326 void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2328 assert(threadID >= 0 && threadID < MAX_THREADS);
2332 // Slave threads can exit as soon as AllThreadsShouldExit raises,
2333 // master should exit as last one.
2334 if (AllThreadsShouldExit)
2337 threads[threadID].state = THREAD_TERMINATED;
2341 // If we are not thinking, wait for a condition to be signaled
2342 // instead of wasting CPU time polling for work.
2343 while (AllThreadsShouldSleep || threadID >= ActiveThreads)
2346 assert(threadID != 0);
2347 threads[threadID].state = THREAD_SLEEPING;
2349 #if !defined(_MSC_VER)
2350 lock_grab(&WaitLock);
2351 if (AllThreadsShouldSleep || threadID >= ActiveThreads)
2352 pthread_cond_wait(&WaitCond, &WaitLock);
2353 lock_release(&WaitLock);
2355 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2359 // If thread has just woken up, mark it as available
2360 if (threads[threadID].state == THREAD_SLEEPING)
2361 threads[threadID].state = THREAD_AVAILABLE;
2363 // If this thread has been assigned work, launch a search
2364 if (threads[threadID].state == THREAD_WORKISWAITING)
2366 assert(!AllThreadsShouldExit && !AllThreadsShouldSleep);
2368 threads[threadID].state = THREAD_SEARCHING;
2370 if (threads[threadID].splitPoint->pvNode)
2371 sp_search<PV>(threads[threadID].splitPoint, threadID);
2373 sp_search<NonPV>(threads[threadID].splitPoint, threadID);
2375 assert(threads[threadID].state == THREAD_SEARCHING);
2377 threads[threadID].state = THREAD_AVAILABLE;
2380 // If this thread is the master of a split point and all slaves have
2381 // finished their work at this split point, return from the idle loop.
2383 for ( ; sp && i < ActiveThreads && !sp->slaves[i]; i++) {}
2385 if (i == ActiveThreads)
2387 // Because sp->slaves[] is reset under lock protection,
2388 // be sure sp->lock has been released before to return.
2389 lock_grab(&(sp->lock));
2390 lock_release(&(sp->lock));
2392 assert(threads[threadID].state == THREAD_AVAILABLE);
2394 threads[threadID].state = THREAD_SEARCHING;
2401 // init_threads() is called during startup. It launches all helper threads,
2402 // and initializes the split point stack and the global locks and condition
2405 void ThreadsManager::init_threads() {
2410 #if !defined(_MSC_VER)
2411 pthread_t pthread[1];
2414 // Initialize global locks
2416 lock_init(&WaitLock);
2418 #if !defined(_MSC_VER)
2419 pthread_cond_init(&WaitCond, NULL);
2421 for (i = 0; i < MAX_THREADS; i++)
2422 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
2425 // Initialize splitPoints[] locks
2426 for (i = 0; i < MAX_THREADS; i++)
2427 for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2428 lock_init(&(threads[i].splitPoints[j].lock));
2430 // Will be set just before program exits to properly end the threads
2431 AllThreadsShouldExit = false;
2433 // Threads will be put to sleep as soon as created
2434 AllThreadsShouldSleep = true;
2436 // All threads except the main thread should be initialized to THREAD_AVAILABLE
2438 threads[0].state = THREAD_SEARCHING;
2439 for (i = 1; i < MAX_THREADS; i++)
2440 threads[i].state = THREAD_AVAILABLE;
2442 // Launch the helper threads
2443 for (i = 1; i < MAX_THREADS; i++)
2446 #if !defined(_MSC_VER)
2447 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
2449 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, NULL) != NULL);
2454 cout << "Failed to create thread number " << i << endl;
2455 Application::exit_with_failure();
2458 // Wait until the thread has finished launching and is gone to sleep
2459 while (threads[i].state != THREAD_SLEEPING) {}
2464 // exit_threads() is called when the program exits. It makes all the
2465 // helper threads exit cleanly.
2467 void ThreadsManager::exit_threads() {
2469 ActiveThreads = MAX_THREADS; // HACK
2470 AllThreadsShouldSleep = true; // HACK
2471 wake_sleeping_threads();
2473 // This makes the threads to exit idle_loop()
2474 AllThreadsShouldExit = true;
2476 // Wait for thread termination
2477 for (int i = 1; i < MAX_THREADS; i++)
2478 while (threads[i].state != THREAD_TERMINATED) {}
2480 // Now we can safely destroy the locks
2481 for (int i = 0; i < MAX_THREADS; i++)
2482 for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2483 lock_destroy(&(threads[i].splitPoints[j].lock));
2485 lock_destroy(&WaitLock);
2486 lock_destroy(&MPLock);
2490 // thread_should_stop() checks whether the thread should stop its search.
2491 // This can happen if a beta cutoff has occurred in the thread's currently
2492 // active split point, or in some ancestor of the current split point.
2494 bool ThreadsManager::thread_should_stop(int threadID) const {
2496 assert(threadID >= 0 && threadID < ActiveThreads);
2500 for (sp = threads[threadID].splitPoint; sp && !sp->stopRequest; sp = sp->parent) {}
2505 // thread_is_available() checks whether the thread with threadID "slave" is
2506 // available to help the thread with threadID "master" at a split point. An
2507 // obvious requirement is that "slave" must be idle. With more than two
2508 // threads, this is not by itself sufficient: If "slave" is the master of
2509 // some active split point, it is only available as a slave to the other
2510 // threads which are busy searching the split point at the top of "slave"'s
2511 // split point stack (the "helpful master concept" in YBWC terminology).
2513 bool ThreadsManager::thread_is_available(int slave, int master) const {
2515 assert(slave >= 0 && slave < ActiveThreads);
2516 assert(master >= 0 && master < ActiveThreads);
2517 assert(ActiveThreads > 1);
2519 if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2522 // Make a local copy to be sure doesn't change under our feet
2523 int localActiveSplitPoints = threads[slave].activeSplitPoints;
2525 if (localActiveSplitPoints == 0)
2526 // No active split points means that the thread is available as
2527 // a slave for any other thread.
2530 if (ActiveThreads == 2)
2533 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2534 // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2535 // could have been set to 0 by another thread leading to an out of bound access.
2536 if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
2543 // available_thread_exists() tries to find an idle thread which is available as
2544 // a slave for the thread with threadID "master".
2546 bool ThreadsManager::available_thread_exists(int master) const {
2548 assert(master >= 0 && master < ActiveThreads);
2549 assert(ActiveThreads > 1);
2551 for (int i = 0; i < ActiveThreads; i++)
2552 if (thread_is_available(i, master))
2559 // split() does the actual work of distributing the work at a node between
2560 // several available threads. If it does not succeed in splitting the
2561 // node (because no idle threads are available, or because we have no unused
2562 // split point objects), the function immediately returns. If splitting is
2563 // possible, a SplitPoint object is initialized with all the data that must be
2564 // copied to the helper threads and we tell our helper threads that they have
2565 // been assigned work. This will cause them to instantly leave their idle loops
2566 // and call sp_search(). When all threads have returned from sp_search() then
2569 template <bool Fake>
2570 void ThreadsManager::split(const Position& p, SearchStack* ss, int ply, Value* alpha,
2571 const Value beta, Value* bestValue, Depth depth, Move threatMove,
2572 bool mateThreat, int* moveCount, MovePicker* mp, bool pvNode) {
2574 assert(ply > 0 && ply < PLY_MAX);
2575 assert(*bestValue >= -VALUE_INFINITE);
2576 assert(*bestValue <= *alpha);
2577 assert(*alpha < beta);
2578 assert(beta <= VALUE_INFINITE);
2579 assert(depth > DEPTH_ZERO);
2580 assert(p.thread() >= 0 && p.thread() < ActiveThreads);
2581 assert(ActiveThreads > 1);
2583 int i, master = p.thread();
2584 Thread& masterThread = threads[master];
2588 // If no other thread is available to help us, or if we have too many
2589 // active split points, don't split.
2590 if ( !available_thread_exists(master)
2591 || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
2593 lock_release(&MPLock);
2597 // Pick the next available split point object from the split point stack
2598 SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
2600 // Initialize the split point object
2601 splitPoint.parent = masterThread.splitPoint;
2602 splitPoint.stopRequest = false;
2603 splitPoint.ply = ply;
2604 splitPoint.depth = depth;
2605 splitPoint.threatMove = threatMove;
2606 splitPoint.mateThreat = mateThreat;
2607 splitPoint.alpha = *alpha;
2608 splitPoint.beta = beta;
2609 splitPoint.pvNode = pvNode;
2610 splitPoint.bestValue = *bestValue;
2612 splitPoint.moveCount = *moveCount;
2613 splitPoint.pos = &p;
2614 splitPoint.parentSstack = ss;
2615 for (i = 0; i < ActiveThreads; i++)
2616 splitPoint.slaves[i] = 0;
2618 masterThread.splitPoint = &splitPoint;
2620 // If we are here it means we are not available
2621 assert(masterThread.state != THREAD_AVAILABLE);
2623 int workersCnt = 1; // At least the master is included
2625 // Allocate available threads setting state to THREAD_BOOKED
2626 for (i = 0; !Fake && i < ActiveThreads && workersCnt < MaxThreadsPerSplitPoint; i++)
2627 if (thread_is_available(i, master))
2629 threads[i].state = THREAD_BOOKED;
2630 threads[i].splitPoint = &splitPoint;
2631 splitPoint.slaves[i] = 1;
2635 assert(Fake || workersCnt > 1);
2637 // We can release the lock because slave threads are already booked and master is not available
2638 lock_release(&MPLock);
2640 // Tell the threads that they have work to do. This will make them leave
2641 // their idle loop. But before copy search stack tail for each thread.
2642 for (i = 0; i < ActiveThreads; i++)
2643 if (i == master || splitPoint.slaves[i])
2645 memcpy(splitPoint.sstack[i], ss - 1, 4 * sizeof(SearchStack));
2647 assert(i == master || threads[i].state == THREAD_BOOKED);
2649 threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2652 // Everything is set up. The master thread enters the idle loop, from
2653 // which it will instantly launch a search, because its state is
2654 // THREAD_WORKISWAITING. We send the split point as a second parameter to the
2655 // idle loop, which means that the main thread will return from the idle
2656 // loop when all threads have finished their work at this split point.
2657 idle_loop(master, &splitPoint);
2659 // We have returned from the idle loop, which means that all threads are
2660 // finished. Update alpha and bestValue, and return.
2663 *alpha = splitPoint.alpha;
2664 *bestValue = splitPoint.bestValue;
2665 masterThread.activeSplitPoints--;
2666 masterThread.splitPoint = splitPoint.parent;
2668 lock_release(&MPLock);
2672 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2673 // to start a new search from the root.
2675 void ThreadsManager::wake_sleeping_threads() {
2677 assert(AllThreadsShouldSleep);
2678 assert(ActiveThreads > 0);
2680 AllThreadsShouldSleep = false;
2682 if (ActiveThreads == 1)
2685 #if !defined(_MSC_VER)
2686 pthread_mutex_lock(&WaitLock);
2687 pthread_cond_broadcast(&WaitCond);
2688 pthread_mutex_unlock(&WaitLock);
2690 for (int i = 1; i < MAX_THREADS; i++)
2691 SetEvent(SitIdleEvent[i]);
2697 // put_threads_to_sleep() makes all the threads go to sleep just before
2698 // to leave think(), at the end of the search. Threads should have already
2699 // finished the job and should be idle.
2701 void ThreadsManager::put_threads_to_sleep() {
2703 assert(!AllThreadsShouldSleep);
2705 // This makes the threads to go to sleep
2706 AllThreadsShouldSleep = true;
2709 /// The RootMoveList class
2711 // RootMoveList c'tor
2713 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2715 SearchStack ss[PLY_MAX_PLUS_2];
2716 MoveStack mlist[MaxRootMoves];
2718 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2720 // Initialize search stack
2721 init_ss_array(ss, PLY_MAX_PLUS_2);
2722 ss[0].currentMove = ss[0].bestMove = MOVE_NONE;
2723 ss[0].eval = VALUE_NONE;
2725 // Generate all legal moves
2726 MoveStack* last = generate_moves(pos, mlist);
2728 // Add each move to the moves[] array
2729 for (MoveStack* cur = mlist; cur != last; cur++)
2731 bool includeMove = includeAllMoves;
2733 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2734 includeMove = (searchMoves[k] == cur->move);
2739 // Find a quick score for the move
2740 pos.do_move(cur->move, st);
2741 ss[0].currentMove = cur->move;
2742 moves[count].move = cur->move;
2743 moves[count].score = -qsearch<PV>(pos, ss+1, -VALUE_INFINITE, VALUE_INFINITE, DEPTH_ZERO, 1);
2744 moves[count].pv[0] = cur->move;
2745 moves[count].pv[1] = MOVE_NONE;
2746 pos.undo_move(cur->move);
2752 // Score root moves using the standard way used in main search, the moves
2753 // are scored according to the order in which are returned by MovePicker.
2755 void RootMoveList::score_moves(const Position& pos)
2759 MovePicker mp = MovePicker(pos, MOVE_NONE, ONE_PLY, H);
2761 while ((move = mp.get_next_move()) != MOVE_NONE)
2762 for (int i = 0; i < count; i++)
2763 if (moves[i].move == move)
2765 moves[i].mp_score = score--;
2770 // RootMoveList simple methods definitions
2772 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2774 moves[moveNum].nodes = nodes;
2775 moves[moveNum].cumulativeNodes += nodes;
2778 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2782 for (j = 0; pv[j] != MOVE_NONE; j++)
2783 moves[moveNum].pv[j] = pv[j];
2785 moves[moveNum].pv[j] = MOVE_NONE;
2789 // RootMoveList::sort() sorts the root move list at the beginning of a new
2792 void RootMoveList::sort() {
2794 sort_multipv(count - 1); // Sort all items
2798 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2799 // list by their scores and depths. It is used to order the different PVs
2800 // correctly in MultiPV mode.
2802 void RootMoveList::sort_multipv(int n) {
2806 for (i = 1; i <= n; i++)
2808 RootMove rm = moves[i];
2809 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2810 moves[j] = moves[j - 1];