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 Marco Costalba
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/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // The RootMove class is used for moves at the root at the tree. For each
51 // root move, we store a score, a node count, and a PV (really a refutation
52 // in the case of moves which fail low).
57 bool operator<(const RootMove&); // used to sort
61 int64_t nodes, cumulativeNodes;
62 Move pv[PLY_MAX_PLUS_2];
66 // The RootMoveList class is essentially an array of RootMove objects, with
67 // a handful of methods for accessing the data in the individual moves.
72 RootMoveList(Position &pos, Move searchMoves[]);
73 inline Move get_move(int moveNum) const;
74 inline Value get_move_score(int moveNum) const;
75 inline void set_move_score(int moveNum, Value score);
76 inline void set_move_nodes(int moveNum, int64_t nodes);
77 void set_move_pv(int moveNum, const Move pv[]);
78 inline Move get_move_pv(int moveNum, int i) const;
79 inline int64_t get_move_cumulative_nodes(int moveNum) const;
80 inline int move_count() const;
81 Move scan_for_easy_move() const;
83 void sort_multipv(int n);
86 static const int MaxRootMoves = 500;
87 RootMove moves[MaxRootMoves];
92 /// Constants and variables
94 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
97 int LMRNonPVMoves = 4;
99 // Depth limit for use of dynamic threat detection:
100 Depth ThreatDepth = 5*OnePly;
102 // Depth limit for selective search:
103 Depth SelectiveDepth = 7*OnePly;
105 // Use internal iterative deepening?
106 const bool UseIIDAtPVNodes = true;
107 const bool UseIIDAtNonPVNodes = false;
109 // Use null move driven internal iterative deepening?
110 bool UseNullDrivenIID = false;
112 // Internal iterative deepening margin. At Non-PV moves, when
113 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
114 // when the static evaluation is at most IIDMargin below beta.
115 const Value IIDMargin = Value(0x100);
118 const bool UseEasyMove = true;
120 // Easy move margin. An easy move candidate must be at least this much
121 // better than the second best move.
122 const Value EasyMoveMargin = Value(0x200);
124 // Problem margin. If the score of the first move at iteration N+1 has
125 // dropped by more than this since iteration N, the boolean variable
126 // "Problem" is set to true, which will make the program spend some extra
127 // time looking for a better move.
128 const Value ProblemMargin = Value(0x28);
130 // No problem margin. If the boolean "Problem" is true, and a new move
131 // is found at the root which is less than NoProblemMargin worse than the
132 // best move from the previous iteration, Problem is set back to false.
133 const Value NoProblemMargin = Value(0x14);
135 // Null move margin. A null move search will not be done if the approximate
136 // evaluation of the position is more than NullMoveMargin below beta.
137 const Value NullMoveMargin = Value(0x300);
139 // Pruning criterions. See the code and comments in ok_to_prune() to
140 // understand their precise meaning.
141 const bool PruneEscapeMoves = false;
142 const bool PruneDefendingMoves = false;
143 const bool PruneBlockingMoves = false;
145 // Use futility pruning?
146 bool UseQSearchFutilityPruning = true;
147 bool UseFutilityPruning = true;
149 // Margins for futility pruning in the quiescence search, at frontier
150 // nodes, and at pre-frontier nodes
151 Value FutilityMargin0 = Value(0x80);
152 Value FutilityMargin1 = Value(0x100);
153 Value FutilityMargin2 = Value(0x300);
156 Depth RazorDepth = 4*OnePly;
157 Value RazorMargin = Value(0x300);
159 // Last seconds noise filtering (LSN)
160 bool UseLSNFiltering = false;
161 bool looseOnTime = false;
162 int LSNTime = 4 * 1000; // In milliseconds
163 Value LSNValue = Value(0x200);
165 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
166 Depth CheckExtension[2] = {OnePly, OnePly};
167 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
168 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
169 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
170 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
171 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
173 // Search depth at iteration 1
174 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
178 int NodesBetweenPolls = 30000;
184 // Scores and number of times the best move changed for each iteration:
185 Value ValueByIteration[PLY_MAX_PLUS_2];
186 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
191 // Time managment variables
193 int MaxNodes, MaxDepth;
194 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
195 Move BestRootMove, PonderMove, EasyMove;
199 bool StopOnPonderhit;
204 bool PonderingEnabled;
207 // Show current line?
208 bool ShowCurrentLine = false;
211 bool UseLogFile = false;
212 std::ofstream LogFile;
214 // MP related variables
215 Depth MinimumSplitDepth = 4*OnePly;
216 int MaxThreadsPerSplitPoint = 4;
217 Thread Threads[THREAD_MAX];
219 bool AllThreadsShouldExit = false;
220 const int MaxActiveSplitPoints = 8;
221 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
224 #if !defined(_MSC_VER)
225 pthread_cond_t WaitCond;
226 pthread_mutex_t WaitLock;
228 HANDLE SitIdleEvent[THREAD_MAX];
234 Value id_loop(const Position &pos, Move searchMoves[]);
235 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
236 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
237 Depth depth, int ply, int threadID);
238 Value search(Position &pos, SearchStack ss[], Value beta,
239 Depth depth, int ply, bool allowNullmove, int threadID);
240 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
241 Depth depth, int ply, int threadID);
242 void sp_search(SplitPoint *sp, int threadID);
243 void sp_search_pv(SplitPoint *sp, int threadID);
244 void init_search_stack(SearchStack& ss);
245 void init_search_stack(SearchStack ss[]);
246 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
247 void update_pv(SearchStack ss[], int ply);
248 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
249 bool connected_moves(const Position &pos, Move m1, Move m2);
250 bool move_is_killer(Move m, const SearchStack& ss);
251 Depth extension(const Position &pos, Move m, bool pvNode, bool check, bool singleReply, bool mateThreat, bool* dangerous);
252 bool ok_to_do_nullmove(const Position &pos);
253 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
254 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
255 bool ok_to_history(const Position &pos, Move m);
256 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
257 void update_killers(Move m, SearchStack& ss);
259 bool fail_high_ply_1();
260 int current_search_time();
264 void print_current_line(SearchStack ss[], int ply, int threadID);
265 void wait_for_stop_or_ponderhit();
267 void idle_loop(int threadID, SplitPoint *waitSp);
268 void init_split_point_stack();
269 void destroy_split_point_stack();
270 bool thread_should_stop(int threadID);
271 bool thread_is_available(int slave, int master);
272 bool idle_thread_exists(int master);
273 bool split(const Position &pos, SearchStack *ss, int ply,
274 Value *alpha, Value *beta, Value *bestValue, Depth depth,
275 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
277 void wake_sleeping_threads();
279 #if !defined(_MSC_VER)
280 void *init_thread(void *threadID);
282 DWORD WINAPI init_thread(LPVOID threadID);
289 //// Global variables
292 // The main transposition table
293 TranspositionTable TT = TranspositionTable(TTDefaultSize);
296 // Number of active threads:
297 int ActiveThreads = 1;
299 // Locks. In principle, there is no need for IOLock to be a global variable,
300 // but it could turn out to be useful for debugging.
303 History H; // Should be made local?
305 // The empty search stack
306 SearchStack EmptySearchStack;
313 /// think() is the external interface to Stockfish's search, and is called when
314 /// the program receives the UCI 'go' command. It initializes various
315 /// search-related global variables, and calls root_search()
317 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
318 int time[], int increment[], int movesToGo, int maxDepth,
319 int maxNodes, int maxTime, Move searchMoves[]) {
321 // Look for a book move
322 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
325 if (get_option_value_string("Book File") != OpeningBook.file_name())
328 OpeningBook.open("book.bin");
330 bookMove = OpeningBook.get_move(pos);
331 if (bookMove != MOVE_NONE)
333 std::cout << "bestmove " << bookMove << std::endl;
338 // Initialize global search variables
340 SearchStartTime = get_system_time();
341 BestRootMove = MOVE_NONE;
342 PonderMove = MOVE_NONE;
343 EasyMove = MOVE_NONE;
344 for (int i = 0; i < THREAD_MAX; i++)
346 Threads[i].nodes = 0ULL;
347 Threads[i].failHighPly1 = false;
350 InfiniteSearch = infinite;
351 PonderSearch = ponder;
352 StopOnPonderhit = false;
357 ExactMaxTime = maxTime;
359 // Read UCI option values
360 TT.set_size(get_option_value_int("Hash"));
361 if (button_was_pressed("Clear Hash"))
364 PonderingEnabled = get_option_value_bool("Ponder");
365 MultiPV = get_option_value_int("MultiPV");
367 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
368 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
370 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
371 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
373 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
374 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
376 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
377 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
379 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
380 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
382 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
383 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
385 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
386 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
387 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
388 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
390 Chess960 = get_option_value_bool("UCI_Chess960");
391 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
392 UseLogFile = get_option_value_bool("Use Search Log");
394 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
396 UseNullDrivenIID = get_option_value_bool("Null driven IID");
397 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
398 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
400 FutilityMargin0 = value_from_centipawns(get_option_value_int("Futility Margin 0"));
401 FutilityMargin1 = value_from_centipawns(get_option_value_int("Futility Margin 1"));
402 FutilityMargin2 = value_from_centipawns(get_option_value_int("Futility Margin 2"));
404 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
405 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
407 UseLSNFiltering = get_option_value_bool("LSN filtering");
408 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
409 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
411 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
412 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
414 read_weights(pos.side_to_move());
416 int newActiveThreads = get_option_value_int("Threads");
417 if (newActiveThreads != ActiveThreads)
419 ActiveThreads = newActiveThreads;
420 init_eval(ActiveThreads);
423 // Wake up sleeping threads:
424 wake_sleeping_threads();
426 for (int i = 1; i < ActiveThreads; i++)
427 assert(thread_is_available(i, 0));
429 // Set thinking time:
430 int myTime = time[side_to_move];
431 int myIncrement = increment[side_to_move];
432 int oppTime = time[1 - side_to_move];
434 if (!movesToGo) // Sudden death time control
438 MaxSearchTime = myTime / 30 + myIncrement;
439 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
440 } else { // Blitz game without increment
441 MaxSearchTime = myTime / 30;
442 AbsoluteMaxSearchTime = myTime / 8;
445 else // (x moves) / (y minutes)
449 MaxSearchTime = myTime / 2;
450 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
452 MaxSearchTime = myTime / Min(movesToGo, 20);
453 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
457 if (PonderingEnabled)
459 MaxSearchTime += MaxSearchTime / 4;
460 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
463 // Fixed depth or fixed number of nodes?
466 InfiniteSearch = true; // HACK
471 NodesBetweenPolls = Min(MaxNodes, 30000);
472 InfiniteSearch = true; // HACK
475 NodesBetweenPolls = 30000;
478 // Write information to search log file:
480 LogFile << "Searching: " << pos.to_fen() << std::endl
481 << "infinite: " << infinite
482 << " ponder: " << ponder
483 << " time: " << myTime
484 << " increment: " << myIncrement
485 << " moves to go: " << movesToGo << std::endl;
488 // We're ready to start thinking. Call the iterative deepening loop
492 Value v = id_loop(pos, searchMoves);
493 looseOnTime = ( UseLSNFiltering
500 looseOnTime = false; // reset for next match
501 while (SearchStartTime + myTime + 1000 > get_system_time())
503 id_loop(pos, searchMoves); // to fail gracefully
520 /// init_threads() is called during startup. It launches all helper threads,
521 /// and initializes the split point stack and the global locks and condition
524 void init_threads() {
528 #if !defined(_MSC_VER)
529 pthread_t pthread[1];
532 for (i = 0; i < THREAD_MAX; i++)
533 Threads[i].activeSplitPoints = 0;
535 // Initialize global locks:
536 lock_init(&MPLock, NULL);
537 lock_init(&IOLock, NULL);
539 init_split_point_stack();
541 #if !defined(_MSC_VER)
542 pthread_mutex_init(&WaitLock, NULL);
543 pthread_cond_init(&WaitCond, NULL);
545 for (i = 0; i < THREAD_MAX; i++)
546 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
549 // All threads except the main thread should be initialized to idle state
550 for (i = 1; i < THREAD_MAX; i++)
552 Threads[i].stop = false;
553 Threads[i].workIsWaiting = false;
554 Threads[i].idle = true;
555 Threads[i].running = false;
558 // Launch the helper threads
559 for(i = 1; i < THREAD_MAX; i++)
561 #if !defined(_MSC_VER)
562 pthread_create(pthread, NULL, init_thread, (void*)(&i));
565 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
568 // Wait until the thread has finished launching:
569 while (!Threads[i].running);
572 // Init also the empty search stack
573 init_search_stack(EmptySearchStack);
577 /// stop_threads() is called when the program exits. It makes all the
578 /// helper threads exit cleanly.
580 void stop_threads() {
582 ActiveThreads = THREAD_MAX; // HACK
583 Idle = false; // HACK
584 wake_sleeping_threads();
585 AllThreadsShouldExit = true;
586 for (int i = 1; i < THREAD_MAX; i++)
588 Threads[i].stop = true;
589 while(Threads[i].running);
591 destroy_split_point_stack();
595 /// nodes_searched() returns the total number of nodes searched so far in
596 /// the current search.
598 int64_t nodes_searched() {
600 int64_t result = 0ULL;
601 for (int i = 0; i < ActiveThreads; i++)
602 result += Threads[i].nodes;
609 // id_loop() is the main iterative deepening loop. It calls root_search
610 // repeatedly with increasing depth until the allocated thinking time has
611 // been consumed, the user stops the search, or the maximum search depth is
614 Value id_loop(const Position &pos, Move searchMoves[]) {
617 SearchStack ss[PLY_MAX_PLUS_2];
619 // searchMoves are verified, copied, scored and sorted
620 RootMoveList rml(p, searchMoves);
625 init_search_stack(ss);
627 ValueByIteration[0] = Value(0);
628 ValueByIteration[1] = rml.get_move_score(0);
630 LastIterations = false;
632 EasyMove = rml.scan_for_easy_move();
634 // Iterative deepening loop
635 while (!AbortSearch && Iteration < PLY_MAX)
637 // Initialize iteration
640 BestMoveChangesByIteration[Iteration] = 0;
644 std::cout << "info depth " << Iteration << std::endl;
646 // Search to the current depth
647 ValueByIteration[Iteration] = root_search(p, ss, rml);
649 // Erase the easy move if it differs from the new best move
650 if (ss[0].pv[0] != EasyMove)
651 EasyMove = MOVE_NONE;
658 bool stopSearch = false;
660 // Stop search early if there is only a single legal move:
661 if (Iteration >= 6 && rml.move_count() == 1)
664 // Stop search early when the last two iterations returned a mate score
666 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
667 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
670 // Stop search early if one move seems to be much better than the rest
671 int64_t nodes = nodes_searched();
673 && EasyMove == ss[0].pv[0]
674 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
675 && current_search_time() > MaxSearchTime / 16)
676 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
677 && current_search_time() > MaxSearchTime / 32)))
680 // Add some extra time if the best move has changed during the last two iterations
681 if (Iteration > 5 && Iteration <= 50)
682 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
683 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
685 // Try to guess if the current iteration is the last one or the last two
686 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
688 // Stop search if most of MaxSearchTime is consumed at the end of the
689 // iteration. We probably don't have enough time to search the first
690 // move at the next iteration anyway.
691 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
699 StopOnPonderhit = true;
702 // Write PV to transposition table, in case the relevant entries have
703 // been overwritten during the search:
704 TT.insert_pv(p, ss[0].pv);
706 if (MaxDepth && Iteration >= MaxDepth)
712 // If we are pondering, we shouldn't print the best move before we
715 wait_for_stop_or_ponderhit();
717 // Print final search statistics
718 std::cout << "info nodes " << nodes_searched()
720 << " time " << current_search_time()
721 << " hashfull " << TT.full() << std::endl;
723 // Print the best move and the ponder move to the standard output
724 std::cout << "bestmove " << ss[0].pv[0];
725 if (ss[0].pv[1] != MOVE_NONE)
726 std::cout << " ponder " << ss[0].pv[1];
728 std::cout << std::endl;
733 dbg_print_mean(LogFile);
735 if (dbg_show_hit_rate)
736 dbg_print_hit_rate(LogFile);
739 LogFile << "Nodes: " << nodes_searched() << std::endl
740 << "Nodes/second: " << nps() << std::endl
741 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
743 p.do_move(ss[0].pv[0], u);
744 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
745 << std::endl << std::endl;
747 return rml.get_move_score(0);
751 // root_search() is the function which searches the root node. It is
752 // similar to search_pv except that it uses a different move ordering
753 // scheme (perhaps we should try to use this at internal PV nodes, too?)
754 // and prints some information to the standard output.
756 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
758 Value alpha = -VALUE_INFINITE;
759 Value beta = VALUE_INFINITE, value;
760 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
762 // Loop through all the moves in the root move list
763 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
770 RootMoveNumber = i + 1;
773 // Remember the node count before the move is searched. The node counts
774 // are used to sort the root moves at the next iteration.
775 nodes = nodes_searched();
777 // Pick the next root move, and print the move and the move number to
778 // the standard output.
779 move = ss[0].currentMove = rml.get_move(i);
780 if (current_search_time() >= 1000)
781 std::cout << "info currmove " << move
782 << " currmovenumber " << i + 1 << std::endl;
784 // Decide search depth for this move
786 ext = extension(pos, move, true, pos.move_is_check(move), false, false, &dangerous);
787 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
789 // Make the move, and search it
790 pos.do_move(move, u, dcCandidates);
794 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
795 // If the value has dropped a lot compared to the last iteration,
796 // set the boolean variable Problem to true. This variable is used
797 // for time managment: When Problem is true, we try to complete the
798 // current iteration before playing a move.
799 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
801 if (Problem && StopOnPonderhit)
802 StopOnPonderhit = false;
806 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
809 // Fail high! Set the boolean variable FailHigh to true, and
810 // re-search the move with a big window. The variable FailHigh is
811 // used for time managment: We try to avoid aborting the search
812 // prematurely during a fail high research.
814 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
818 pos.undo_move(move, u);
820 // Finished searching the move. If AbortSearch is true, the search
821 // was aborted because the user interrupted the search or because we
822 // ran out of time. In this case, the return value of the search cannot
823 // be trusted, and we break out of the loop without updating the best
828 // Remember the node count for this move. The node counts are used to
829 // sort the root moves at the next iteration.
830 rml.set_move_nodes(i, nodes_searched() - nodes);
832 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
834 if (value <= alpha && i >= MultiPV)
835 rml.set_move_score(i, -VALUE_INFINITE);
841 rml.set_move_score(i, value);
843 rml.set_move_pv(i, ss[0].pv);
847 // We record how often the best move has been changed in each
848 // iteration. This information is used for time managment: When
849 // the best move changes frequently, we allocate some more time.
851 BestMoveChangesByIteration[Iteration]++;
853 // Print search information to the standard output:
854 std::cout << "info depth " << Iteration
855 << " score " << value_to_string(value)
856 << " time " << current_search_time()
857 << " nodes " << nodes_searched()
861 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
862 std::cout << ss[0].pv[j] << " ";
864 std::cout << std::endl;
867 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
872 // Reset the global variable Problem to false if the value isn't too
873 // far below the final value from the last iteration.
874 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
880 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
883 std::cout << "info multipv " << j + 1
884 << " score " << value_to_string(rml.get_move_score(j))
885 << " depth " << ((j <= i)? Iteration : Iteration - 1)
886 << " time " << current_search_time()
887 << " nodes " << nodes_searched()
891 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
892 std::cout << rml.get_move_pv(j, k) << " ";
894 std::cout << std::endl;
896 alpha = rml.get_move_score(Min(i, MultiPV-1));
904 // search_pv() is the main search function for PV nodes.
906 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
907 Depth depth, int ply, int threadID) {
909 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
910 assert(beta > alpha && beta <= VALUE_INFINITE);
911 assert(ply >= 0 && ply < PLY_MAX);
912 assert(threadID >= 0 && threadID < ActiveThreads);
914 // Initialize, and make an early exit in case of an aborted search,
915 // an instant draw, maximum ply reached, etc.
916 if (AbortSearch || thread_should_stop(threadID))
920 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
922 init_node(pos, ss, ply, threadID);
929 if (ply >= PLY_MAX - 1)
930 return evaluate(pos, ei, threadID);
932 // Mate distance pruning
933 Value oldAlpha = alpha;
934 alpha = Max(value_mated_in(ply), alpha);
935 beta = Min(value_mate_in(ply+1), beta);
939 // Transposition table lookup. At PV nodes, we don't use the TT for
940 // pruning, but only for move ordering.
941 const TTEntry* tte = TT.retrieve(pos);
942 Move ttMove = (tte ? tte->move() : MOVE_NONE);
944 // Go with internal iterative deepening if we don't have a TT move
945 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
947 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
948 ttMove = ss[ply].pv[ply];
951 // Initialize a MovePicker object for the current position, and prepare
952 // to search all moves
953 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
955 Move move, movesSearched[256];
957 Value value, bestValue = -VALUE_INFINITE;
958 Bitboard dcCandidates = mp.discovered_check_candidates();
959 bool isCheck = pos.is_check();
960 bool mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
962 // Loop through all legal moves until no moves remain or a beta cutoff
965 && (move = mp.get_next_move()) != MOVE_NONE
966 && !thread_should_stop(threadID))
968 assert(move_is_ok(move));
970 bool singleReply = (isCheck && mp.number_of_moves() == 1);
971 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
972 bool moveIsCapture = pos.move_is_capture(move);
974 movesSearched[moveCount++] = ss[ply].currentMove = move;
977 ss[ply].currentMoveCaptureValue = pos.midgame_value_of_piece_on(move_to(move));
978 else if (move_is_ep(move))
979 ss[ply].currentMoveCaptureValue = PawnValueMidgame;
981 ss[ply].currentMoveCaptureValue = Value(0);
983 // Decide the new search depth
985 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat, &dangerous);
986 Depth newDepth = depth - OnePly + ext;
988 // Make and search the move
990 pos.do_move(move, u, dcCandidates);
992 if (moveCount == 1) // The first move in list is the PV
993 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
996 // Try to reduce non-pv search depth by one ply if move seems not problematic,
997 // if the move fails high will be re-searched at full depth.
998 if ( depth >= 2*OnePly
999 && moveCount >= LMRPVMoves
1002 && !move_promotion(move)
1003 && !move_is_castle(move)
1004 && !move_is_killer(move, ss[ply]))
1006 ss[ply].reduction = OnePly;
1007 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1010 value = alpha + 1; // Just to trigger next condition
1012 if (value > alpha) // Go with full depth pv search
1014 ss[ply].reduction = Depth(0);
1015 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1016 if (value > alpha && value < beta)
1018 // When the search fails high at ply 1 while searching the first
1019 // move at the root, set the flag failHighPly1. This is used for
1020 // time managment: We don't want to stop the search early in
1021 // such cases, because resolving the fail high at ply 1 could
1022 // result in a big drop in score at the root.
1023 if (ply == 1 && RootMoveNumber == 1)
1024 Threads[threadID].failHighPly1 = true;
1026 // A fail high occurred. Re-search at full window (pv search)
1027 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1028 Threads[threadID].failHighPly1 = false;
1032 pos.undo_move(move, u);
1034 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1037 if (value > bestValue)
1044 if (value == value_mate_in(ply + 1))
1045 ss[ply].mateKiller = move;
1047 // If we are at ply 1, and we are searching the first root move at
1048 // ply 0, set the 'Problem' variable if the score has dropped a lot
1049 // (from the computer's point of view) since the previous iteration:
1050 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1055 if ( ActiveThreads > 1
1057 && depth >= MinimumSplitDepth
1059 && idle_thread_exists(threadID)
1061 && !thread_should_stop(threadID)
1062 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1063 &moveCount, &mp, dcCandidates, threadID, true))
1067 // All legal moves have been searched. A special case: If there were
1068 // no legal moves, it must be mate or stalemate:
1070 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1072 // If the search is not aborted, update the transposition table,
1073 // history counters, and killer moves.
1074 if (AbortSearch || thread_should_stop(threadID))
1077 if (bestValue <= oldAlpha)
1078 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1080 else if (bestValue >= beta)
1082 Move m = ss[ply].pv[ply];
1083 if (ok_to_history(pos, m)) // Only non capture moves are considered
1085 update_history(pos, m, depth, movesSearched, moveCount);
1086 update_killers(m, ss[ply]);
1088 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1091 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1097 // search() is the search function for zero-width nodes.
1099 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1100 int ply, bool allowNullmove, int threadID) {
1102 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1103 assert(ply >= 0 && ply < PLY_MAX);
1104 assert(threadID >= 0 && threadID < ActiveThreads);
1108 // Initialize, and make an early exit in case of an aborted search,
1109 // an instant draw, maximum ply reached, etc.
1110 if (AbortSearch || thread_should_stop(threadID))
1114 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1116 init_node(pos, ss, ply, threadID);
1121 if (ply >= PLY_MAX - 1)
1122 return evaluate(pos, ei, threadID);
1124 // Mate distance pruning
1125 if (value_mated_in(ply) >= beta)
1128 if (value_mate_in(ply + 1) < beta)
1131 // Transposition table lookup
1132 const TTEntry* tte = TT.retrieve(pos);
1133 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1135 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1137 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1138 return value_from_tt(tte->value(), ply);
1141 Value approximateEval = quick_evaluate(pos);
1142 bool mateThreat = false;
1143 bool nullDrivenIID = false;
1144 bool isCheck = pos.is_check();
1150 && ok_to_do_nullmove(pos)
1151 && approximateEval >= beta - NullMoveMargin)
1153 ss[ply].currentMove = MOVE_NULL;
1156 pos.do_null_move(u);
1157 int R = (depth > 7 ? 4 : 3);
1159 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1161 // Check for a null capture artifact, if the value without the null capture
1162 // is above beta then there is a good possibility that this is a cut-node.
1163 // We will do an IID later to find a ttMove.
1164 if ( UseNullDrivenIID
1166 && depth > 6 * OnePly
1167 && ttMove == MOVE_NONE
1168 && ss[ply + 1].currentMove != MOVE_NONE
1169 && pos.move_is_capture(ss[ply + 1].currentMove)
1170 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1171 nullDrivenIID = true;
1173 pos.undo_null_move(u);
1175 if (nullValue >= beta)
1177 if (depth < 6 * OnePly)
1180 // Do zugzwang verification search
1181 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1185 // The null move failed low, which means that we may be faced with
1186 // some kind of threat. If the previous move was reduced, check if
1187 // the move that refuted the null move was somehow connected to the
1188 // move which was reduced. If a connection is found, return a fail
1189 // low score (which will cause the reduced move to fail high in the
1190 // parent node, which will trigger a re-search with full depth).
1191 if (nullValue == value_mated_in(ply + 2))
1194 nullDrivenIID = false;
1196 ss[ply].threatMove = ss[ply + 1].currentMove;
1197 if ( depth < ThreatDepth
1198 && ss[ply - 1].reduction
1199 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1203 // Null move search not allowed, try razoring
1204 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1205 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1207 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1212 // Go with internal iterative deepening if we don't have a TT move
1213 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1214 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1216 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1217 ttMove = ss[ply].pv[ply];
1219 else if (nullDrivenIID)
1221 // The null move failed low due to a suspicious capture. Perhaps we
1222 // are facing a null capture artifact due to the side to move change
1223 // and this is a cut-node. So it's a good time to search for a ttMove.
1224 Move tm = ss[ply].threatMove;
1226 assert(tm != MOVE_NONE);
1227 assert(ttMove == MOVE_NONE);
1229 search(pos, ss, beta, depth/2, ply, false, threadID);
1230 ttMove = ss[ply].pv[ply];
1231 ss[ply].threatMove = tm;
1234 // Initialize a MovePicker object for the current position, and prepare
1235 // to search all moves:
1236 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1238 Move move, movesSearched[256];
1240 Value value, bestValue = -VALUE_INFINITE;
1241 Bitboard dcCandidates = mp.discovered_check_candidates();
1242 Value futilityValue = VALUE_NONE;
1243 bool useFutilityPruning = UseFutilityPruning
1244 && depth < SelectiveDepth
1247 // Loop through all legal moves until no moves remain or a beta cutoff
1249 while ( bestValue < beta
1250 && (move = mp.get_next_move()) != MOVE_NONE
1251 && !thread_should_stop(threadID))
1253 assert(move_is_ok(move));
1255 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1256 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1257 bool moveIsCapture = pos.move_is_capture(move);
1259 movesSearched[moveCount++] = ss[ply].currentMove = move;
1261 // Decide the new search depth
1263 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat, &dangerous);
1264 Depth newDepth = depth - OnePly + ext;
1267 if ( useFutilityPruning
1270 && !move_promotion(move))
1272 if ( moveCount >= 2 + int(depth)
1273 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1276 if (depth < 3 * OnePly && approximateEval < beta)
1278 if (futilityValue == VALUE_NONE)
1279 futilityValue = evaluate(pos, ei, threadID)
1280 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1282 if (futilityValue < beta)
1284 if (futilityValue > bestValue)
1285 bestValue = futilityValue;
1291 // Make and search the move
1293 pos.do_move(move, u, dcCandidates);
1295 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1296 // if the move fails high will be re-searched at full depth.
1297 if ( depth >= 2*OnePly
1298 && moveCount >= LMRNonPVMoves
1301 && !move_promotion(move)
1302 && !move_is_castle(move)
1303 && !move_is_killer(move, ss[ply]))
1305 ss[ply].reduction = OnePly;
1306 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1309 value = beta; // Just to trigger next condition
1311 if (value >= beta) // Go with full depth non-pv search
1313 ss[ply].reduction = Depth(0);
1314 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1316 pos.undo_move(move, u);
1318 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1321 if (value > bestValue)
1327 if (value == value_mate_in(ply + 1))
1328 ss[ply].mateKiller = move;
1332 if ( ActiveThreads > 1
1334 && depth >= MinimumSplitDepth
1336 && idle_thread_exists(threadID)
1338 && !thread_should_stop(threadID)
1339 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1340 &mp, dcCandidates, threadID, false))
1344 // All legal moves have been searched. A special case: If there were
1345 // no legal moves, it must be mate or stalemate.
1347 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1349 // If the search is not aborted, update the transposition table,
1350 // history counters, and killer moves.
1351 if (AbortSearch || thread_should_stop(threadID))
1354 if (bestValue < beta)
1355 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1358 Move m = ss[ply].pv[ply];
1359 if (ok_to_history(pos, m)) // Only non capture moves are considered
1361 update_history(pos, m, depth, movesSearched, moveCount);
1362 update_killers(m, ss[ply]);
1364 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1370 // qsearch() is the quiescence search function, which is called by the main
1371 // search function when the remaining depth is zero (or, to be more precise,
1372 // less than OnePly).
1374 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1375 Depth depth, int ply, int threadID) {
1377 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1378 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1380 assert(ply >= 0 && ply < PLY_MAX);
1381 assert(threadID >= 0 && threadID < ActiveThreads);
1385 // Initialize, and make an early exit in case of an aborted search,
1386 // an instant draw, maximum ply reached, etc.
1387 if (AbortSearch || thread_should_stop(threadID))
1390 init_node(pos, ss, ply, threadID);
1395 // Transposition table lookup
1396 const TTEntry* tte = TT.retrieve(pos);
1397 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1398 return value_from_tt(tte->value(), ply);
1400 // Evaluate the position statically
1401 Value staticValue = evaluate(pos, ei, threadID);
1403 if (ply == PLY_MAX - 1)
1406 // Initialize "stand pat score", and return it immediately if it is
1408 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1410 if (bestValue >= beta)
1413 if (bestValue > alpha)
1416 // Initialize a MovePicker object for the current position, and prepare
1417 // to search the moves. Because the depth is <= 0 here, only captures,
1418 // queen promotions and checks (only if depth == 0) will be generated.
1419 MovePicker mp = MovePicker(pos, false, MOVE_NONE, EmptySearchStack, depth, &ei);
1422 Bitboard dcCandidates = mp.discovered_check_candidates();
1423 bool isCheck = pos.is_check();
1424 bool pvNode = (beta - alpha != 1);
1425 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1427 // Loop through the moves until no moves remain or a beta cutoff
1429 while ( alpha < beta
1430 && (move = mp.get_next_move()) != MOVE_NONE)
1432 assert(move_is_ok(move));
1435 ss[ply].currentMove = move;
1438 if ( UseQSearchFutilityPruning
1442 && !move_promotion(move)
1443 && !pos.move_is_check(move, dcCandidates)
1444 && !pos.move_is_passed_pawn_push(move))
1446 Value futilityValue = staticValue
1447 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1448 pos.endgame_value_of_piece_on(move_to(move)))
1450 + ei.futilityMargin;
1452 if (futilityValue < alpha)
1454 if (futilityValue > bestValue)
1455 bestValue = futilityValue;
1460 // Don't search captures and checks with negative SEE values
1462 && !move_promotion(move)
1463 && (pos.midgame_value_of_piece_on(move_from(move)) >
1464 pos.midgame_value_of_piece_on(move_to(move)))
1465 && pos.see(move) < 0)
1468 // Make and search the move.
1470 pos.do_move(move, u, dcCandidates);
1471 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1472 pos.undo_move(move, u);
1474 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1477 if (value > bestValue)
1488 // All legal moves have been searched. A special case: If we're in check
1489 // and no legal moves were found, it is checkmate:
1490 if (pos.is_check() && moveCount == 0) // Mate!
1491 return value_mated_in(ply);
1493 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1495 // Update transposition table
1496 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1498 // Update killers only for good check moves
1499 Move m = ss[ply].currentMove;
1500 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1502 // Wrong to update history when depth is <= 0
1503 update_killers(m, ss[ply]);
1509 // sp_search() is used to search from a split point. This function is called
1510 // by each thread working at the split point. It is similar to the normal
1511 // search() function, but simpler. Because we have already probed the hash
1512 // table, done a null move search, and searched the first move before
1513 // splitting, we don't have to repeat all this work in sp_search(). We
1514 // also don't need to store anything to the hash table here: This is taken
1515 // care of after we return from the split point.
1517 void sp_search(SplitPoint *sp, int threadID) {
1519 assert(threadID >= 0 && threadID < ActiveThreads);
1520 assert(ActiveThreads > 1);
1522 Position pos = Position(sp->pos);
1523 SearchStack *ss = sp->sstack[threadID];
1526 bool isCheck = pos.is_check();
1527 bool useFutilityPruning = UseFutilityPruning
1528 && sp->depth < SelectiveDepth
1531 while ( sp->bestValue < sp->beta
1532 && !thread_should_stop(threadID)
1533 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1535 assert(move_is_ok(move));
1537 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1538 bool moveIsCapture = pos.move_is_capture(move);
1540 lock_grab(&(sp->lock));
1541 int moveCount = ++sp->moves;
1542 lock_release(&(sp->lock));
1544 ss[sp->ply].currentMove = move;
1546 // Decide the new search depth.
1548 Depth ext = extension(pos, move, false, moveIsCheck, false, false, &dangerous);
1549 Depth newDepth = sp->depth - OnePly + ext;
1552 if ( useFutilityPruning
1555 && !move_promotion(move)
1556 && moveCount >= 2 + int(sp->depth)
1557 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1560 // Make and search the move.
1562 pos.do_move(move, u, sp->dcCandidates);
1564 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1565 // if the move fails high will be re-searched at full depth.
1567 && moveCount >= LMRNonPVMoves
1569 && !move_promotion(move)
1570 && !move_is_castle(move)
1571 && !move_is_killer(move, ss[sp->ply]))
1573 ss[sp->ply].reduction = OnePly;
1574 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1577 value = sp->beta; // Just to trigger next condition
1579 if (value >= sp->beta) // Go with full depth non-pv search
1581 ss[sp->ply].reduction = Depth(0);
1582 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1584 pos.undo_move(move, u);
1586 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1588 if (thread_should_stop(threadID))
1592 lock_grab(&(sp->lock));
1593 if (value > sp->bestValue && !thread_should_stop(threadID))
1595 sp->bestValue = value;
1596 if (sp->bestValue >= sp->beta)
1598 sp_update_pv(sp->parentSstack, ss, sp->ply);
1599 for (int i = 0; i < ActiveThreads; i++)
1600 if (i != threadID && (i == sp->master || sp->slaves[i]))
1601 Threads[i].stop = true;
1603 sp->finished = true;
1606 lock_release(&(sp->lock));
1609 lock_grab(&(sp->lock));
1611 // If this is the master thread and we have been asked to stop because of
1612 // a beta cutoff higher up in the tree, stop all slave threads:
1613 if (sp->master == threadID && thread_should_stop(threadID))
1614 for (int i = 0; i < ActiveThreads; i++)
1616 Threads[i].stop = true;
1619 sp->slaves[threadID] = 0;
1621 lock_release(&(sp->lock));
1625 // sp_search_pv() is used to search from a PV split point. This function
1626 // is called by each thread working at the split point. It is similar to
1627 // the normal search_pv() function, but simpler. Because we have already
1628 // probed the hash table and searched the first move before splitting, we
1629 // don't have to repeat all this work in sp_search_pv(). We also don't
1630 // need to store anything to the hash table here: This is taken care of
1631 // after we return from the split point.
1633 void sp_search_pv(SplitPoint *sp, int threadID) {
1635 assert(threadID >= 0 && threadID < ActiveThreads);
1636 assert(ActiveThreads > 1);
1638 Position pos = Position(sp->pos);
1639 SearchStack *ss = sp->sstack[threadID];
1643 while ( sp->alpha < sp->beta
1644 && !thread_should_stop(threadID)
1645 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1647 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1648 bool moveIsCapture = pos.move_is_capture(move);
1650 assert(move_is_ok(move));
1652 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1653 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1655 lock_grab(&(sp->lock));
1656 int moveCount = ++sp->moves;
1657 lock_release(&(sp->lock));
1659 ss[sp->ply].currentMove = move;
1661 // Decide the new search depth.
1663 Depth ext = extension(pos, move, true, moveIsCheck, false, false, &dangerous);
1664 Depth newDepth = sp->depth - OnePly + ext;
1666 // Make and search the move.
1668 pos.do_move(move, u, sp->dcCandidates);
1670 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1671 // if the move fails high will be re-searched at full depth.
1673 && moveCount >= LMRPVMoves
1675 && !move_promotion(move)
1676 && !move_is_castle(move)
1677 && !move_is_killer(move, ss[sp->ply]))
1679 ss[sp->ply].reduction = OnePly;
1680 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1683 value = sp->alpha + 1; // Just to trigger next condition
1685 if (value > sp->alpha) // Go with full depth non-pv search
1687 ss[sp->ply].reduction = Depth(0);
1688 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1690 if (value > sp->alpha && value < sp->beta)
1692 // When the search fails high at ply 1 while searching the first
1693 // move at the root, set the flag failHighPly1. This is used for
1694 // time managment: We don't want to stop the search early in
1695 // such cases, because resolving the fail high at ply 1 could
1696 // result in a big drop in score at the root.
1697 if (sp->ply == 1 && RootMoveNumber == 1)
1698 Threads[threadID].failHighPly1 = true;
1700 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1701 Threads[threadID].failHighPly1 = false;
1704 pos.undo_move(move, u);
1706 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1708 if (thread_should_stop(threadID))
1712 lock_grab(&(sp->lock));
1713 if (value > sp->bestValue && !thread_should_stop(threadID))
1715 sp->bestValue = value;
1716 if (value > sp->alpha)
1719 sp_update_pv(sp->parentSstack, ss, sp->ply);
1720 if (value == value_mate_in(sp->ply + 1))
1721 ss[sp->ply].mateKiller = move;
1723 if(value >= sp->beta)
1725 for(int i = 0; i < ActiveThreads; i++)
1726 if(i != threadID && (i == sp->master || sp->slaves[i]))
1727 Threads[i].stop = true;
1729 sp->finished = true;
1732 // If we are at ply 1, and we are searching the first root move at
1733 // ply 0, set the 'Problem' variable if the score has dropped a lot
1734 // (from the computer's point of view) since the previous iteration:
1735 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1738 lock_release(&(sp->lock));
1741 lock_grab(&(sp->lock));
1743 // If this is the master thread and we have been asked to stop because of
1744 // a beta cutoff higher up in the tree, stop all slave threads:
1745 if (sp->master == threadID && thread_should_stop(threadID))
1746 for (int i = 0; i < ActiveThreads; i++)
1748 Threads[i].stop = true;
1751 sp->slaves[threadID] = 0;
1753 lock_release(&(sp->lock));
1757 /// The RootMove class
1761 RootMove::RootMove() {
1762 nodes = cumulativeNodes = 0ULL;
1765 // RootMove::operator<() is the comparison function used when
1766 // sorting the moves. A move m1 is considered to be better
1767 // than a move m2 if it has a higher score, or if the moves
1768 // have equal score but m1 has the higher node count.
1770 bool RootMove::operator<(const RootMove& m) {
1772 if (score != m.score)
1773 return (score < m.score);
1775 return nodes <= m.nodes;
1778 /// The RootMoveList class
1782 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1784 MoveStack mlist[MaxRootMoves];
1785 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1787 // Generate all legal moves
1788 int lm_count = generate_legal_moves(pos, mlist);
1790 // Add each move to the moves[] array
1791 for (int i = 0; i < lm_count; i++)
1793 bool includeMove = includeAllMoves;
1795 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1796 includeMove = (searchMoves[k] == mlist[i].move);
1800 // Find a quick score for the move
1802 SearchStack ss[PLY_MAX_PLUS_2];
1804 moves[count].move = mlist[i].move;
1805 moves[count].nodes = 0ULL;
1806 pos.do_move(moves[count].move, u);
1807 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1809 pos.undo_move(moves[count].move, u);
1810 moves[count].pv[0] = moves[i].move;
1811 moves[count].pv[1] = MOVE_NONE; // FIXME
1819 // Simple accessor methods for the RootMoveList class
1821 inline Move RootMoveList::get_move(int moveNum) const {
1822 return moves[moveNum].move;
1825 inline Value RootMoveList::get_move_score(int moveNum) const {
1826 return moves[moveNum].score;
1829 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1830 moves[moveNum].score = score;
1833 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1834 moves[moveNum].nodes = nodes;
1835 moves[moveNum].cumulativeNodes += nodes;
1838 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1840 for(j = 0; pv[j] != MOVE_NONE; j++)
1841 moves[moveNum].pv[j] = pv[j];
1842 moves[moveNum].pv[j] = MOVE_NONE;
1845 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1846 return moves[moveNum].pv[i];
1849 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1850 return moves[moveNum].cumulativeNodes;
1853 inline int RootMoveList::move_count() const {
1858 // RootMoveList::scan_for_easy_move() is called at the end of the first
1859 // iteration, and is used to detect an "easy move", i.e. a move which appears
1860 // to be much bester than all the rest. If an easy move is found, the move
1861 // is returned, otherwise the function returns MOVE_NONE. It is very
1862 // important that this function is called at the right moment: The code
1863 // assumes that the first iteration has been completed and the moves have
1864 // been sorted. This is done in RootMoveList c'tor.
1866 Move RootMoveList::scan_for_easy_move() const {
1873 // moves are sorted so just consider the best and the second one
1874 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1880 // RootMoveList::sort() sorts the root move list at the beginning of a new
1883 inline void RootMoveList::sort() {
1885 sort_multipv(count - 1); // all items
1889 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1890 // list by their scores and depths. It is used to order the different PVs
1891 // correctly in MultiPV mode.
1893 void RootMoveList::sort_multipv(int n) {
1895 for (int i = 1; i <= n; i++)
1897 RootMove rm = moves[i];
1899 for (j = i; j > 0 && moves[j-1] < rm; j--)
1900 moves[j] = moves[j-1];
1906 // init_search_stack() initializes a search stack at the beginning of a
1907 // new search from the root.
1908 void init_search_stack(SearchStack& ss) {
1910 ss.pv[0] = MOVE_NONE;
1911 ss.pv[1] = MOVE_NONE;
1912 ss.currentMove = MOVE_NONE;
1913 ss.threatMove = MOVE_NONE;
1914 ss.reduction = Depth(0);
1915 for (int j = 0; j < KILLER_MAX; j++)
1916 ss.killers[j] = MOVE_NONE;
1919 void init_search_stack(SearchStack ss[]) {
1921 for (int i = 0; i < 3; i++)
1923 ss[i].pv[i] = MOVE_NONE;
1924 ss[i].pv[i+1] = MOVE_NONE;
1925 ss[i].currentMove = MOVE_NONE;
1926 ss[i].threatMove = MOVE_NONE;
1927 ss[i].reduction = Depth(0);
1928 for (int j = 0; j < KILLER_MAX; j++)
1929 ss[i].killers[j] = MOVE_NONE;
1934 // init_node() is called at the beginning of all the search functions
1935 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1936 // stack object corresponding to the current node. Once every
1937 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1938 // for user input and checks whether it is time to stop the search.
1940 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1941 assert(ply >= 0 && ply < PLY_MAX);
1942 assert(threadID >= 0 && threadID < ActiveThreads);
1944 Threads[threadID].nodes++;
1948 if(NodesSincePoll >= NodesBetweenPolls) {
1953 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1954 ss[ply+2].mateKiller = MOVE_NONE;
1955 ss[ply].threatMove = MOVE_NONE;
1956 ss[ply].reduction = Depth(0);
1957 ss[ply].currentMoveCaptureValue = Value(0);
1958 for (int j = 0; j < KILLER_MAX; j++)
1959 ss[ply+2].killers[j] = MOVE_NONE;
1961 if(Threads[threadID].printCurrentLine)
1962 print_current_line(ss, ply, threadID);
1966 // update_pv() is called whenever a search returns a value > alpha. It
1967 // updates the PV in the SearchStack object corresponding to the current
1970 void update_pv(SearchStack ss[], int ply) {
1971 assert(ply >= 0 && ply < PLY_MAX);
1973 ss[ply].pv[ply] = ss[ply].currentMove;
1975 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1976 ss[ply].pv[p] = ss[ply+1].pv[p];
1977 ss[ply].pv[p] = MOVE_NONE;
1981 // sp_update_pv() is a variant of update_pv for use at split points. The
1982 // difference between the two functions is that sp_update_pv also updates
1983 // the PV at the parent node.
1985 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1986 assert(ply >= 0 && ply < PLY_MAX);
1988 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1990 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1991 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1992 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1996 // connected_moves() tests whether two moves are 'connected' in the sense
1997 // that the first move somehow made the second move possible (for instance
1998 // if the moving piece is the same in both moves). The first move is
1999 // assumed to be the move that was made to reach the current position, while
2000 // the second move is assumed to be a move from the current position.
2002 bool connected_moves(const Position &pos, Move m1, Move m2) {
2003 Square f1, t1, f2, t2;
2005 assert(move_is_ok(m1));
2006 assert(move_is_ok(m2));
2011 // Case 1: The moving piece is the same in both moves.
2017 // Case 2: The destination square for m2 was vacated by m1.
2023 // Case 3: Moving through the vacated square:
2024 if(piece_is_slider(pos.piece_on(f2)) &&
2025 bit_is_set(squares_between(f2, t2), f1))
2028 // Case 4: The destination square for m2 is attacked by the moving piece
2030 if(pos.piece_attacks_square(t1, t2))
2033 // Case 5: Discovered check, checking piece is the piece moved in m1:
2034 if(piece_is_slider(pos.piece_on(t1)) &&
2035 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2037 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2039 Bitboard occ = pos.occupied_squares();
2040 Color us = pos.side_to_move();
2041 Square ksq = pos.king_square(us);
2042 clear_bit(&occ, f2);
2043 if(pos.type_of_piece_on(t1) == BISHOP) {
2044 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2047 else if(pos.type_of_piece_on(t1) == ROOK) {
2048 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2052 assert(pos.type_of_piece_on(t1) == QUEEN);
2053 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2062 // move_is_killer() checks if the given move is among the
2063 // killer moves of that ply.
2065 bool move_is_killer(Move m, const SearchStack& ss) {
2067 const Move* k = ss.killers;
2068 for (int i = 0; i < KILLER_MAX; i++, k++)
2076 // extension() decides whether a move should be searched with normal depth,
2077 // or with extended depth. Certain classes of moves (checking moves, in
2078 // particular) are searched with bigger depth than ordinary moves and in
2079 // any case are marked as 'dangerous'. Note that also if a move is not
2080 // extended, as example because the corresponding UCI option is set to zero,
2081 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2083 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
2084 bool singleReply, bool mateThreat, bool* dangerous) {
2086 Depth result = Depth(0);
2087 *dangerous = check || singleReply || mateThreat;
2090 result += CheckExtension[pvNode];
2093 result += SingleReplyExtension[pvNode];
2096 result += MateThreatExtension[pvNode];
2098 if (pos.move_is_pawn_push_to_7th(m))
2100 result += PawnPushTo7thExtension[pvNode];
2103 if (pos.move_is_passed_pawn_push(m))
2105 result += PassedPawnExtension[pvNode];
2109 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
2110 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2111 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2112 && !move_promotion(m))
2114 result += PawnEndgameExtension[pvNode];
2119 && pos.move_is_capture(m)
2120 && pos.type_of_piece_on(move_to(m)) != PAWN
2127 return Min(result, OnePly);
2131 // ok_to_do_nullmove() looks at the current position and decides whether
2132 // doing a 'null move' should be allowed. In order to avoid zugzwang
2133 // problems, null moves are not allowed when the side to move has very
2134 // little material left. Currently, the test is a bit too simple: Null
2135 // moves are avoided only when the side to move has only pawns left. It's
2136 // probably a good idea to avoid null moves in at least some more
2137 // complicated endgames, e.g. KQ vs KR. FIXME
2139 bool ok_to_do_nullmove(const Position &pos) {
2140 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2146 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2147 // non-tactical moves late in the move list close to the leaves are
2148 // candidates for pruning.
2150 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2151 Square mfrom, mto, tfrom, tto;
2153 assert(move_is_ok(m));
2154 assert(threat == MOVE_NONE || move_is_ok(threat));
2155 assert(!move_promotion(m));
2156 assert(!pos.move_is_check(m));
2157 assert(!pos.move_is_capture(m));
2158 assert(!pos.move_is_passed_pawn_push(m));
2159 assert(d >= OnePly);
2161 mfrom = move_from(m);
2163 tfrom = move_from(threat);
2164 tto = move_to(threat);
2166 // Case 1: Castling moves are never pruned.
2167 if (move_is_castle(m))
2170 // Case 2: Don't prune moves which move the threatened piece
2171 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2174 // Case 3: If the threatened piece has value less than or equal to the
2175 // value of the threatening piece, don't prune move which defend it.
2176 if ( !PruneDefendingMoves
2177 && threat != MOVE_NONE
2178 && pos.type_of_piece_on(tto) != NO_PIECE_TYPE
2179 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2180 || pos.type_of_piece_on(tfrom) == KING)
2181 && pos.move_attacks_square(m, tto))
2184 // Case 4: Don't prune moves with good history.
2185 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2188 // Case 5: If the moving piece in the threatened move is a slider, don't
2189 // prune safe moves which block its ray.
2190 if ( !PruneBlockingMoves
2191 && threat != MOVE_NONE
2192 && piece_is_slider(pos.piece_on(tfrom))
2193 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2200 // ok_to_use_TT() returns true if a transposition table score
2201 // can be used at a given point in search.
2203 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2205 Value v = value_from_tt(tte->value(), ply);
2207 return ( tte->depth() >= depth
2208 || v >= Max(value_mate_in(100), beta)
2209 || v < Min(value_mated_in(100), beta))
2211 && ( (is_lower_bound(tte->type()) && v >= beta)
2212 || (is_upper_bound(tte->type()) && v < beta));
2216 // ok_to_history() returns true if a move m can be stored
2217 // in history. Should be a non capturing move nor a promotion.
2219 bool ok_to_history(const Position& pos, Move m) {
2221 return !pos.move_is_capture(m) && !move_promotion(m);
2225 // update_history() registers a good move that produced a beta-cutoff
2226 // in history and marks as failures all the other moves of that ply.
2228 void update_history(const Position& pos, Move m, Depth depth,
2229 Move movesSearched[], int moveCount) {
2231 H.success(pos.piece_on(move_from(m)), m, depth);
2233 for (int i = 0; i < moveCount - 1; i++)
2235 assert(m != movesSearched[i]);
2236 if (ok_to_history(pos, movesSearched[i]))
2237 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2242 // update_killers() add a good move that produced a beta-cutoff
2243 // among the killer moves of that ply.
2245 void update_killers(Move m, SearchStack& ss) {
2247 if (m == ss.killers[0])
2250 for (int i = KILLER_MAX - 1; i > 0; i--)
2251 ss.killers[i] = ss.killers[i - 1];
2256 // fail_high_ply_1() checks if some thread is currently resolving a fail
2257 // high at ply 1 at the node below the first root node. This information
2258 // is used for time managment.
2260 bool fail_high_ply_1() {
2261 for(int i = 0; i < ActiveThreads; i++)
2262 if(Threads[i].failHighPly1)
2268 // current_search_time() returns the number of milliseconds which have passed
2269 // since the beginning of the current search.
2271 int current_search_time() {
2272 return get_system_time() - SearchStartTime;
2276 // nps() computes the current nodes/second count.
2279 int t = current_search_time();
2280 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2284 // poll() performs two different functions: It polls for user input, and it
2285 // looks at the time consumed so far and decides if it's time to abort the
2290 static int lastInfoTime;
2291 int t = current_search_time();
2296 // We are line oriented, don't read single chars
2297 std::string command;
2298 if (!std::getline(std::cin, command))
2301 if (command == "quit")
2304 PonderSearch = false;
2307 else if(command == "stop")
2310 PonderSearch = false;
2312 else if(command == "ponderhit")
2315 // Print search information
2319 else if (lastInfoTime > t)
2320 // HACK: Must be a new search where we searched less than
2321 // NodesBetweenPolls nodes during the first second of search.
2324 else if (t - lastInfoTime >= 1000)
2331 if (dbg_show_hit_rate)
2332 dbg_print_hit_rate();
2334 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2335 << " time " << t << " hashfull " << TT.full() << std::endl;
2336 lock_release(&IOLock);
2337 if (ShowCurrentLine)
2338 Threads[0].printCurrentLine = true;
2340 // Should we stop the search?
2344 bool overTime = t > AbsoluteMaxSearchTime
2345 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2346 || ( !FailHigh && !fail_high_ply_1() && !Problem
2347 && t > 6*(MaxSearchTime + ExtraSearchTime));
2349 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2350 || (ExactMaxTime && t >= ExactMaxTime)
2351 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2356 // ponderhit() is called when the program is pondering (i.e. thinking while
2357 // it's the opponent's turn to move) in order to let the engine know that
2358 // it correctly predicted the opponent's move.
2361 int t = current_search_time();
2362 PonderSearch = false;
2363 if(Iteration >= 2 &&
2364 (!InfiniteSearch && (StopOnPonderhit ||
2365 t > AbsoluteMaxSearchTime ||
2366 (RootMoveNumber == 1 &&
2367 t > MaxSearchTime + ExtraSearchTime) ||
2368 (!FailHigh && !fail_high_ply_1() && !Problem &&
2369 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2374 // print_current_line() prints the current line of search for a given
2375 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2377 void print_current_line(SearchStack ss[], int ply, int threadID) {
2378 assert(ply >= 0 && ply < PLY_MAX);
2379 assert(threadID >= 0 && threadID < ActiveThreads);
2381 if(!Threads[threadID].idle) {
2383 std::cout << "info currline " << (threadID + 1);
2384 for(int p = 0; p < ply; p++)
2385 std::cout << " " << ss[p].currentMove;
2386 std::cout << std::endl;
2387 lock_release(&IOLock);
2389 Threads[threadID].printCurrentLine = false;
2390 if(threadID + 1 < ActiveThreads)
2391 Threads[threadID + 1].printCurrentLine = true;
2395 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2396 // while the program is pondering. The point is to work around a wrinkle in
2397 // the UCI protocol: When pondering, the engine is not allowed to give a
2398 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2399 // We simply wait here until one of these commands is sent, and return,
2400 // after which the bestmove and pondermove will be printed (in id_loop()).
2402 void wait_for_stop_or_ponderhit() {
2403 std::string command;
2406 if(!std::getline(std::cin, command))
2409 if(command == "quit") {
2410 OpeningBook.close();
2415 else if(command == "ponderhit" || command == "stop")
2421 // idle_loop() is where the threads are parked when they have no work to do.
2422 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2423 // object for which the current thread is the master.
2425 void idle_loop(int threadID, SplitPoint *waitSp) {
2426 assert(threadID >= 0 && threadID < THREAD_MAX);
2428 Threads[threadID].running = true;
2431 if(AllThreadsShouldExit && threadID != 0)
2434 // If we are not thinking, wait for a condition to be signaled instead
2435 // of wasting CPU time polling for work:
2436 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2437 #if !defined(_MSC_VER)
2438 pthread_mutex_lock(&WaitLock);
2439 if(Idle || threadID >= ActiveThreads)
2440 pthread_cond_wait(&WaitCond, &WaitLock);
2441 pthread_mutex_unlock(&WaitLock);
2443 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2447 // If this thread has been assigned work, launch a search:
2448 if(Threads[threadID].workIsWaiting) {
2449 Threads[threadID].workIsWaiting = false;
2450 if(Threads[threadID].splitPoint->pvNode)
2451 sp_search_pv(Threads[threadID].splitPoint, threadID);
2453 sp_search(Threads[threadID].splitPoint, threadID);
2454 Threads[threadID].idle = true;
2457 // If this thread is the master of a split point and all threads have
2458 // finished their work at this split point, return from the idle loop:
2459 if(waitSp != NULL && waitSp->cpus == 0)
2463 Threads[threadID].running = false;
2467 // init_split_point_stack() is called during program initialization, and
2468 // initializes all split point objects.
2470 void init_split_point_stack() {
2471 for(int i = 0; i < THREAD_MAX; i++)
2472 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2473 SplitPointStack[i][j].parent = NULL;
2474 lock_init(&(SplitPointStack[i][j].lock), NULL);
2479 // destroy_split_point_stack() is called when the program exits, and
2480 // destroys all locks in the precomputed split point objects.
2482 void destroy_split_point_stack() {
2483 for(int i = 0; i < THREAD_MAX; i++)
2484 for(int j = 0; j < MaxActiveSplitPoints; j++)
2485 lock_destroy(&(SplitPointStack[i][j].lock));
2489 // thread_should_stop() checks whether the thread with a given threadID has
2490 // been asked to stop, directly or indirectly. This can happen if a beta
2491 // cutoff has occured in thre thread's currently active split point, or in
2492 // some ancestor of the current split point.
2494 bool thread_should_stop(int threadID) {
2495 assert(threadID >= 0 && threadID < ActiveThreads);
2499 if(Threads[threadID].stop)
2501 if(ActiveThreads <= 2)
2503 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2505 Threads[threadID].stop = true;
2512 // thread_is_available() checks whether the thread with threadID "slave" is
2513 // available to help the thread with threadID "master" at a split point. An
2514 // obvious requirement is that "slave" must be idle. With more than two
2515 // threads, this is not by itself sufficient: If "slave" is the master of
2516 // some active split point, it is only available as a slave to the other
2517 // threads which are busy searching the split point at the top of "slave"'s
2518 // split point stack (the "helpful master concept" in YBWC terminology).
2520 bool thread_is_available(int slave, int master) {
2521 assert(slave >= 0 && slave < ActiveThreads);
2522 assert(master >= 0 && master < ActiveThreads);
2523 assert(ActiveThreads > 1);
2525 if(!Threads[slave].idle || slave == master)
2528 if(Threads[slave].activeSplitPoints == 0)
2529 // No active split points means that the thread is available as a slave
2530 // for any other thread.
2533 if(ActiveThreads == 2)
2536 // Apply the "helpful master" concept if possible.
2537 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2544 // idle_thread_exists() tries to find an idle thread which is available as
2545 // a slave for the thread with threadID "master".
2547 bool idle_thread_exists(int master) {
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))
2558 // split() does the actual work of distributing the work at a node between
2559 // several threads at PV nodes. If it does not succeed in splitting the
2560 // node (because no idle threads are available, or because we have no unused
2561 // split point objects), the function immediately returns false. If
2562 // splitting is possible, a SplitPoint object is initialized with all the
2563 // data that must be copied to the helper threads (the current position and
2564 // search stack, alpha, beta, the search depth, etc.), and we tell our
2565 // helper threads that they have been assigned work. This will cause them
2566 // to instantly leave their idle loops and call sp_search_pv(). When all
2567 // threads have returned from sp_search_pv (or, equivalently, when
2568 // splitPoint->cpus becomes 0), split() returns true.
2570 bool split(const Position &p, SearchStack *sstck, int ply,
2571 Value *alpha, Value *beta, Value *bestValue,
2572 Depth depth, int *moves,
2573 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2575 assert(sstck != NULL);
2576 assert(ply >= 0 && ply < PLY_MAX);
2577 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2578 assert(!pvNode || *alpha < *beta);
2579 assert(*beta <= VALUE_INFINITE);
2580 assert(depth > Depth(0));
2581 assert(master >= 0 && master < ActiveThreads);
2582 assert(ActiveThreads > 1);
2584 SplitPoint *splitPoint;
2589 // If no other thread is available to help us, or if we have too many
2590 // active split points, don't split:
2591 if(!idle_thread_exists(master) ||
2592 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2593 lock_release(&MPLock);
2597 // Pick the next available split point object from the split point stack:
2598 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2599 Threads[master].activeSplitPoints++;
2601 // Initialize the split point object:
2602 splitPoint->parent = Threads[master].splitPoint;
2603 splitPoint->finished = false;
2604 splitPoint->ply = ply;
2605 splitPoint->depth = depth;
2606 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2607 splitPoint->beta = *beta;
2608 splitPoint->pvNode = pvNode;
2609 splitPoint->dcCandidates = dcCandidates;
2610 splitPoint->bestValue = *bestValue;
2611 splitPoint->master = master;
2612 splitPoint->mp = mp;
2613 splitPoint->moves = *moves;
2614 splitPoint->cpus = 1;
2615 splitPoint->pos.copy(p);
2616 splitPoint->parentSstack = sstck;
2617 for(i = 0; i < ActiveThreads; i++)
2618 splitPoint->slaves[i] = 0;
2620 // Copy the current position and the search stack to the master thread:
2621 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2622 Threads[master].splitPoint = splitPoint;
2624 // Make copies of the current position and search stack for each thread:
2625 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2627 if(thread_is_available(i, master)) {
2628 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2629 Threads[i].splitPoint = splitPoint;
2630 splitPoint->slaves[i] = 1;
2634 // Tell the threads that they have work to do. This will make them leave
2636 for(i = 0; i < ActiveThreads; i++)
2637 if(i == master || splitPoint->slaves[i]) {
2638 Threads[i].workIsWaiting = true;
2639 Threads[i].idle = false;
2640 Threads[i].stop = false;
2643 lock_release(&MPLock);
2645 // Everything is set up. The master thread enters the idle loop, from
2646 // which it will instantly launch a search, because its workIsWaiting
2647 // slot is 'true'. We send the split point as a second parameter to the
2648 // idle loop, which means that the main thread will return from the idle
2649 // loop when all threads have finished their work at this split point
2650 // (i.e. when // splitPoint->cpus == 0).
2651 idle_loop(master, splitPoint);
2653 // We have returned from the idle loop, which means that all threads are
2654 // finished. Update alpha, beta and bestvalue, and return:
2656 if(pvNode) *alpha = splitPoint->alpha;
2657 *beta = splitPoint->beta;
2658 *bestValue = splitPoint->bestValue;
2659 Threads[master].stop = false;
2660 Threads[master].idle = false;
2661 Threads[master].activeSplitPoints--;
2662 Threads[master].splitPoint = splitPoint->parent;
2663 lock_release(&MPLock);
2669 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2670 // to start a new search from the root.
2672 void wake_sleeping_threads() {
2673 if(ActiveThreads > 1) {
2674 for(int i = 1; i < ActiveThreads; i++) {
2675 Threads[i].idle = true;
2676 Threads[i].workIsWaiting = false;
2678 #if !defined(_MSC_VER)
2679 pthread_mutex_lock(&WaitLock);
2680 pthread_cond_broadcast(&WaitCond);
2681 pthread_mutex_unlock(&WaitLock);
2683 for(int i = 1; i < THREAD_MAX; i++)
2684 SetEvent(SitIdleEvent[i]);
2690 // init_thread() is the function which is called when a new thread is
2691 // launched. It simply calls the idle_loop() function with the supplied
2692 // threadID. There are two versions of this function; one for POSIX threads
2693 // and one for Windows threads.
2695 #if !defined(_MSC_VER)
2697 void *init_thread(void *threadID) {
2698 idle_loop(*(int *)threadID, NULL);
2704 DWORD WINAPI init_thread(LPVOID threadID) {
2705 idle_loop(*(int *)threadID, NULL);