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 // Internal iterative deepening margin. At Non-PV moves, when
110 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
111 // when the static evaluation is at most IIDMargin below beta.
112 const Value IIDMargin = Value(0x100);
115 const bool UseEasyMove = true;
117 // Easy move margin. An easy move candidate must be at least this much
118 // better than the second best move.
119 const Value EasyMoveMargin = Value(0x200);
121 // Problem margin. If the score of the first move at iteration N+1 has
122 // dropped by more than this since iteration N, the boolean variable
123 // "Problem" is set to true, which will make the program spend some extra
124 // time looking for a better move.
125 const Value ProblemMargin = Value(0x28);
127 // No problem margin. If the boolean "Problem" is true, and a new move
128 // is found at the root which is less than NoProblemMargin worse than the
129 // best move from the previous iteration, Problem is set back to false.
130 const Value NoProblemMargin = Value(0x14);
132 // Null move margin. A null move search will not be done if the approximate
133 // evaluation of the position is more than NullMoveMargin below beta.
134 const Value NullMoveMargin = Value(0x300);
136 // Pruning criterions. See the code and comments in ok_to_prune() to
137 // understand their precise meaning.
138 const bool PruneEscapeMoves = false;
139 const bool PruneDefendingMoves = false;
140 const bool PruneBlockingMoves = false;
142 // Use futility pruning?
143 bool UseQSearchFutilityPruning = true;
144 bool UseFutilityPruning = true;
146 // Margins for futility pruning in the quiescence search, at frontier
147 // nodes, and at pre-frontier nodes
148 Value FutilityMargin0 = Value(0x80);
149 Value FutilityMargin1 = Value(0x100);
150 Value FutilityMargin2 = Value(0x300);
153 Depth RazorDepth = 4*OnePly;
154 Value RazorMargin = Value(0x300);
156 // Last seconds noise filtering (LSN)
157 bool UseLSNFiltering = false;
158 bool looseOnTime = false;
159 int LSNTime = 4 * 1000; // In milliseconds
160 Value LSNValue = Value(0x200);
162 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
163 Depth CheckExtension[2] = {OnePly, OnePly};
164 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
165 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
166 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
167 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
168 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
170 // Search depth at iteration 1
171 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
175 int NodesBetweenPolls = 30000;
181 // Scores and number of times the best move changed for each iteration:
182 Value ValueByIteration[PLY_MAX_PLUS_2];
183 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
188 // Time managment variables
190 int MaxNodes, MaxDepth;
191 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
192 Move BestRootMove, PonderMove, EasyMove;
196 bool StopOnPonderhit;
201 bool PonderingEnabled;
204 // Show current line?
205 bool ShowCurrentLine = false;
208 bool UseLogFile = false;
209 std::ofstream LogFile;
211 // MP related variables
212 Depth MinimumSplitDepth = 4*OnePly;
213 int MaxThreadsPerSplitPoint = 4;
214 Thread Threads[THREAD_MAX];
216 bool AllThreadsShouldExit = false;
217 const int MaxActiveSplitPoints = 8;
218 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
221 #if !defined(_MSC_VER)
222 pthread_cond_t WaitCond;
223 pthread_mutex_t WaitLock;
225 HANDLE SitIdleEvent[THREAD_MAX];
231 Value id_loop(const Position &pos, Move searchMoves[]);
232 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
233 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
234 Depth depth, int ply, int threadID);
235 Value search(Position &pos, SearchStack ss[], Value beta,
236 Depth depth, int ply, bool allowNullmove, int threadID);
237 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
238 Depth depth, int ply, int threadID);
239 void sp_search(SplitPoint *sp, int threadID);
240 void sp_search_pv(SplitPoint *sp, int threadID);
241 void init_search_stack(SearchStack ss[]);
242 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
243 void update_pv(SearchStack ss[], int ply);
244 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
245 bool connected_moves(const Position &pos, Move m1, Move m2);
246 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
247 bool singleReply, bool mateThreat);
248 bool ok_to_do_nullmove(const Position &pos);
249 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
250 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
251 bool ok_to_history(const Position &pos, Move m);
252 void update_history(const Position& pos, Move m, Depth depth,
253 Move movesSearched[], int moveCount);
255 bool fail_high_ply_1();
256 int current_search_time();
260 void print_current_line(SearchStack ss[], int ply, int threadID);
261 void wait_for_stop_or_ponderhit();
263 void idle_loop(int threadID, SplitPoint *waitSp);
264 void init_split_point_stack();
265 void destroy_split_point_stack();
266 bool thread_should_stop(int threadID);
267 bool thread_is_available(int slave, int master);
268 bool idle_thread_exists(int master);
269 bool split(const Position &pos, SearchStack *ss, int ply,
270 Value *alpha, Value *beta, Value *bestValue, Depth depth,
271 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
273 void wake_sleeping_threads();
275 #if !defined(_MSC_VER)
276 void *init_thread(void *threadID);
278 DWORD WINAPI init_thread(LPVOID threadID);
285 //// Global variables
288 // The main transposition table
289 TranspositionTable TT = TranspositionTable(TTDefaultSize);
292 // Number of active threads:
293 int ActiveThreads = 1;
295 // Locks. In principle, there is no need for IOLock to be a global variable,
296 // but it could turn out to be useful for debugging.
299 History H; // Should be made local?
306 /// think() is the external interface to Stockfish's search, and is called when
307 /// the program receives the UCI 'go' command. It initializes various
308 /// search-related global variables, and calls root_search()
310 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
311 int time[], int increment[], int movesToGo, int maxDepth,
312 int maxNodes, int maxTime, Move searchMoves[]) {
314 // Look for a book move
315 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
318 if (get_option_value_string("Book File") != OpeningBook.file_name())
321 OpeningBook.open("book.bin");
323 bookMove = OpeningBook.get_move(pos);
324 if (bookMove != MOVE_NONE)
326 std::cout << "bestmove " << bookMove << std::endl;
331 // Initialize global search variables
333 SearchStartTime = get_system_time();
334 BestRootMove = MOVE_NONE;
335 PonderMove = MOVE_NONE;
336 EasyMove = MOVE_NONE;
337 for (int i = 0; i < THREAD_MAX; i++)
339 Threads[i].nodes = 0ULL;
340 Threads[i].failHighPly1 = false;
343 InfiniteSearch = infinite;
344 PonderSearch = ponder;
345 StopOnPonderhit = false;
350 ExactMaxTime = maxTime;
352 // Read UCI option values
353 TT.set_size(get_option_value_int("Hash"));
354 if (button_was_pressed("Clear Hash"))
357 PonderingEnabled = get_option_value_bool("Ponder");
358 MultiPV = get_option_value_int("MultiPV");
360 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
361 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
363 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
364 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
366 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
367 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
369 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
370 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
372 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
373 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
375 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
376 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
378 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
379 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
380 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
381 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
383 Chess960 = get_option_value_bool("UCI_Chess960");
384 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
385 UseLogFile = get_option_value_bool("Use Search Log");
387 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
389 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
390 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
392 FutilityMargin0 = value_from_centipawns(get_option_value_int("Futility Margin 0"));
393 FutilityMargin1 = value_from_centipawns(get_option_value_int("Futility Margin 1"));
394 FutilityMargin2 = value_from_centipawns(get_option_value_int("Futility Margin 2"));
396 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
397 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
399 UseLSNFiltering = get_option_value_bool("LSN filtering");
400 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
401 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
403 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
404 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
406 read_weights(pos.side_to_move());
408 int newActiveThreads = get_option_value_int("Threads");
409 if (newActiveThreads != ActiveThreads)
411 ActiveThreads = newActiveThreads;
412 init_eval(ActiveThreads);
415 // Wake up sleeping threads:
416 wake_sleeping_threads();
418 for (int i = 1; i < ActiveThreads; i++)
419 assert(thread_is_available(i, 0));
421 // Set thinking time:
422 int myTime = time[side_to_move];
423 int myIncrement = increment[side_to_move];
424 int oppTime = time[1 - side_to_move];
426 TimeAdvantage = myTime - oppTime;
428 if (!movesToGo) // Sudden death time control
432 MaxSearchTime = myTime / 30 + myIncrement;
433 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
434 } else { // Blitz game without increment
435 MaxSearchTime = myTime / 40;
436 AbsoluteMaxSearchTime = myTime / 8;
439 else // (x moves) / (y minutes)
443 MaxSearchTime = myTime / 2;
444 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
446 MaxSearchTime = myTime / Min(movesToGo, 20);
447 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
451 if (PonderingEnabled)
453 MaxSearchTime += MaxSearchTime / 4;
454 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
457 // Fixed depth or fixed number of nodes?
460 InfiniteSearch = true; // HACK
465 NodesBetweenPolls = Min(MaxNodes, 30000);
466 InfiniteSearch = true; // HACK
469 NodesBetweenPolls = 30000;
472 // Write information to search log file:
474 LogFile << "Searching: " << pos.to_fen() << std::endl
475 << "infinite: " << infinite
476 << " ponder: " << ponder
477 << " time: " << myTime
478 << " increment: " << myIncrement
479 << " moves to go: " << movesToGo << std::endl;
482 // We're ready to start thinking. Call the iterative deepening loop
486 Value v = id_loop(pos, searchMoves);
487 looseOnTime = ( UseLSNFiltering
494 looseOnTime = false; // reset for next match
495 while (SearchStartTime + myTime + 1000 > get_system_time())
497 id_loop(pos, searchMoves); // to fail gracefully
514 /// init_threads() is called during startup. It launches all helper threads,
515 /// and initializes the split point stack and the global locks and condition
518 void init_threads() {
522 #if !defined(_MSC_VER)
523 pthread_t pthread[1];
526 for (i = 0; i < THREAD_MAX; i++)
527 Threads[i].activeSplitPoints = 0;
529 // Initialize global locks:
530 lock_init(&MPLock, NULL);
531 lock_init(&IOLock, NULL);
533 init_split_point_stack();
535 #if !defined(_MSC_VER)
536 pthread_mutex_init(&WaitLock, NULL);
537 pthread_cond_init(&WaitCond, NULL);
539 for (i = 0; i < THREAD_MAX; i++)
540 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
543 // All threads except the main thread should be initialized to idle state
544 for (i = 1; i < THREAD_MAX; i++)
546 Threads[i].stop = false;
547 Threads[i].workIsWaiting = false;
548 Threads[i].idle = true;
549 Threads[i].running = false;
552 // Launch the helper threads
553 for(i = 1; i < THREAD_MAX; i++)
555 #if !defined(_MSC_VER)
556 pthread_create(pthread, NULL, init_thread, (void*)(&i));
559 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
562 // Wait until the thread has finished launching:
563 while (!Threads[i].running);
568 /// stop_threads() is called when the program exits. It makes all the
569 /// helper threads exit cleanly.
571 void stop_threads() {
573 ActiveThreads = THREAD_MAX; // HACK
574 Idle = false; // HACK
575 wake_sleeping_threads();
576 AllThreadsShouldExit = true;
577 for (int i = 1; i < THREAD_MAX; i++)
579 Threads[i].stop = true;
580 while(Threads[i].running);
582 destroy_split_point_stack();
586 /// nodes_searched() returns the total number of nodes searched so far in
587 /// the current search.
589 int64_t nodes_searched() {
591 int64_t result = 0ULL;
592 for (int i = 0; i < ActiveThreads; i++)
593 result += Threads[i].nodes;
600 // id_loop() is the main iterative deepening loop. It calls root_search
601 // repeatedly with increasing depth until the allocated thinking time has
602 // been consumed, the user stops the search, or the maximum search depth is
605 Value id_loop(const Position &pos, Move searchMoves[]) {
608 SearchStack ss[PLY_MAX_PLUS_2];
610 // searchMoves are verified, copied, scored and sorted
611 RootMoveList rml(p, searchMoves);
616 init_search_stack(ss);
618 ValueByIteration[0] = Value(0);
619 ValueByIteration[1] = rml.get_move_score(0);
621 LastIterations = false;
623 EasyMove = rml.scan_for_easy_move();
625 // Iterative deepening loop
626 while (!AbortSearch && Iteration < PLY_MAX)
628 // Initialize iteration
631 BestMoveChangesByIteration[Iteration] = 0;
635 std::cout << "info depth " << Iteration << std::endl;
637 // Search to the current depth
638 ValueByIteration[Iteration] = root_search(p, ss, rml);
640 // Erase the easy move if it differs from the new best move
641 if (ss[0].pv[0] != EasyMove)
642 EasyMove = MOVE_NONE;
649 bool stopSearch = false;
651 // Stop search early if there is only a single legal move:
652 if (Iteration >= 6 && rml.move_count() == 1)
655 // Stop search early when the last two iterations returned a mate score
657 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
658 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
661 // Stop search early if one move seems to be much better than the rest
662 int64_t nodes = nodes_searched();
664 && EasyMove == ss[0].pv[0]
665 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
666 && current_search_time() > MaxSearchTime / 16)
667 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
668 && current_search_time() > MaxSearchTime / 32)))
671 // Add some extra time if the best move has changed during the last two iterations
672 if (Iteration > 5 && Iteration <= 50)
673 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
674 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
676 // If we need some more and we are in time advantage take it
677 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
678 ExtraSearchTime += MaxSearchTime / 2;
680 // Try to guess if the current iteration is the last one or the last two
681 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
683 // Stop search if most of MaxSearchTime is consumed at the end of the
684 // iteration. We probably don't have enough time to search the first
685 // move at the next iteration anyway.
686 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
694 StopOnPonderhit = true;
697 // Write PV to transposition table, in case the relevant entries have
698 // been overwritten during the search:
699 TT.insert_pv(p, ss[0].pv);
701 if (MaxDepth && Iteration >= MaxDepth)
707 // If we are pondering, we shouldn't print the best move before we
710 wait_for_stop_or_ponderhit();
712 // Print final search statistics
713 std::cout << "info nodes " << nodes_searched()
715 << " time " << current_search_time()
716 << " hashfull " << TT.full() << std::endl;
718 // Print the best move and the ponder move to the standard output
719 std::cout << "bestmove " << ss[0].pv[0];
720 if (ss[0].pv[1] != MOVE_NONE)
721 std::cout << " ponder " << ss[0].pv[1];
723 std::cout << std::endl;
728 LogFile << "Nodes: " << nodes_searched() << std::endl
729 << "Nodes/second: " << nps() << std::endl
730 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
732 p.do_move(ss[0].pv[0], u);
733 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
734 << std::endl << std::endl;
736 return rml.get_move_score(0);
740 // root_search() is the function which searches the root node. It is
741 // similar to search_pv except that it uses a different move ordering
742 // scheme (perhaps we should try to use this at internal PV nodes, too?)
743 // and prints some information to the standard output.
745 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
747 Value alpha = -VALUE_INFINITE;
748 Value beta = VALUE_INFINITE, value;
749 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
751 // Loop through all the moves in the root move list
752 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
759 RootMoveNumber = i + 1;
762 // Remember the node count before the move is searched. The node counts
763 // are used to sort the root moves at the next iteration.
764 nodes = nodes_searched();
766 // Pick the next root move, and print the move and the move number to
767 // the standard output.
768 move = ss[0].currentMove = rml.get_move(i);
769 if (current_search_time() >= 1000)
770 std::cout << "info currmove " << move
771 << " currmovenumber " << i + 1 << std::endl;
773 // Decide search depth for this move
774 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
775 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
777 // Make the move, and search it
778 pos.do_move(move, u, dcCandidates);
782 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
783 // If the value has dropped a lot compared to the last iteration,
784 // set the boolean variable Problem to true. This variable is used
785 // for time managment: When Problem is true, we try to complete the
786 // current iteration before playing a move.
787 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
789 if (Problem && StopOnPonderhit)
790 StopOnPonderhit = false;
794 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
797 // Fail high! Set the boolean variable FailHigh to true, and
798 // re-search the move with a big window. The variable FailHigh is
799 // used for time managment: We try to avoid aborting the search
800 // prematurely during a fail high research.
802 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
806 pos.undo_move(move, u);
808 // Finished searching the move. If AbortSearch is true, the search
809 // was aborted because the user interrupted the search or because we
810 // ran out of time. In this case, the return value of the search cannot
811 // be trusted, and we break out of the loop without updating the best
816 // Remember the node count for this move. The node counts are used to
817 // sort the root moves at the next iteration.
818 rml.set_move_nodes(i, nodes_searched() - nodes);
820 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
822 if (value <= alpha && i >= MultiPV)
823 rml.set_move_score(i, -VALUE_INFINITE);
829 rml.set_move_score(i, value);
831 rml.set_move_pv(i, ss[0].pv);
835 // We record how often the best move has been changed in each
836 // iteration. This information is used for time managment: When
837 // the best move changes frequently, we allocate some more time.
839 BestMoveChangesByIteration[Iteration]++;
841 // Print search information to the standard output:
842 std::cout << "info depth " << Iteration
843 << " score " << value_to_string(value)
844 << " time " << current_search_time()
845 << " nodes " << nodes_searched()
849 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
850 std::cout << ss[0].pv[j] << " ";
852 std::cout << std::endl;
855 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
860 // Reset the global variable Problem to false if the value isn't too
861 // far below the final value from the last iteration.
862 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
868 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
871 std::cout << "info multipv " << j + 1
872 << " score " << value_to_string(rml.get_move_score(j))
873 << " depth " << ((j <= i)? Iteration : Iteration - 1)
874 << " time " << current_search_time()
875 << " nodes " << nodes_searched()
879 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
880 std::cout << rml.get_move_pv(j, k) << " ";
882 std::cout << std::endl;
884 alpha = rml.get_move_score(Min(i, MultiPV-1));
892 // search_pv() is the main search function for PV nodes.
894 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
895 Depth depth, int ply, int threadID) {
897 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
898 assert(beta > alpha && beta <= VALUE_INFINITE);
899 assert(ply >= 0 && ply < PLY_MAX);
900 assert(threadID >= 0 && threadID < ActiveThreads);
902 // Initialize, and make an early exit in case of an aborted search,
903 // an instant draw, maximum ply reached, etc.
904 if (AbortSearch || thread_should_stop(threadID))
908 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
910 init_node(pos, ss, ply, threadID);
917 if (ply >= PLY_MAX - 1)
918 return evaluate(pos, ei, threadID);
920 // Mate distance pruning
921 Value oldAlpha = alpha;
922 alpha = Max(value_mated_in(ply), alpha);
923 beta = Min(value_mate_in(ply+1), beta);
927 // Transposition table lookup. At PV nodes, we don't use the TT for
928 // pruning, but only for move ordering.
929 const TTEntry* tte = TT.retrieve(pos);
930 Move ttMove = (tte ? tte->move() : MOVE_NONE);
932 // Go with internal iterative deepening if we don't have a TT move
933 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
935 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
936 ttMove = ss[ply].pv[ply];
939 // Initialize a MovePicker object for the current position, and prepare
940 // to search all moves
941 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
942 ss[ply].killer1, ss[ply].killer2, depth);
944 Move move, movesSearched[256];
946 Value value, bestValue = -VALUE_INFINITE;
947 Bitboard dcCandidates = mp.discovered_check_candidates();
948 bool isCheck = pos.is_check();
949 bool mateThreat = MateThreatExtension[1] > Depth(0)
950 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
952 // Loop through all legal moves until no moves remain or a beta cutoff
955 && (move = mp.get_next_move()) != MOVE_NONE
956 && !thread_should_stop(threadID))
958 assert(move_is_ok(move));
960 bool singleReply = (isCheck && mp.number_of_moves() == 1);
961 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
962 bool moveIsCapture = pos.move_is_capture(move);
963 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
965 movesSearched[moveCount++] = ss[ply].currentMove = move;
968 ss[ply].currentMoveCaptureValue = pos.midgame_value_of_piece_on(move_to(move));
969 else if (move_is_ep(move))
970 ss[ply].currentMoveCaptureValue = PawnValueMidgame;
972 ss[ply].currentMoveCaptureValue = Value(0);
974 // Decide the new search depth
975 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
976 Depth newDepth = depth - OnePly + ext;
978 // Make and search the move
980 pos.do_move(move, u, dcCandidates);
982 if (moveCount == 1) // The first move in list is the PV
983 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
986 // Try to reduce non-pv search depth by one ply if move seems not problematic,
987 // if the move fails high will be re-searched at full depth.
988 if ( depth >= 2*OnePly
990 && moveCount >= LMRPVMoves
992 && !move_promotion(move)
993 && !moveIsPassedPawnPush
994 && !move_is_castle(move)
995 && move != ss[ply].killer1
996 && move != ss[ply].killer2)
998 ss[ply].reduction = OnePly;
999 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1002 value = alpha + 1; // Just to trigger next condition
1004 if (value > alpha) // Go with full depth pv search
1006 ss[ply].reduction = Depth(0);
1007 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1008 if (value > alpha && value < beta)
1010 // When the search fails high at ply 1 while searching the first
1011 // move at the root, set the flag failHighPly1. This is used for
1012 // time managment: We don't want to stop the search early in
1013 // such cases, because resolving the fail high at ply 1 could
1014 // result in a big drop in score at the root.
1015 if (ply == 1 && RootMoveNumber == 1)
1016 Threads[threadID].failHighPly1 = true;
1018 // A fail high occurred. Re-search at full window (pv search)
1019 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1020 Threads[threadID].failHighPly1 = false;
1024 pos.undo_move(move, u);
1026 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1029 if (value > bestValue)
1036 if (value == value_mate_in(ply + 1))
1037 ss[ply].mateKiller = move;
1039 // If we are at ply 1, and we are searching the first root move at
1040 // ply 0, set the 'Problem' variable if the score has dropped a lot
1041 // (from the computer's point of view) since the previous iteration:
1042 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1047 if ( ActiveThreads > 1
1049 && depth >= MinimumSplitDepth
1051 && idle_thread_exists(threadID)
1053 && !thread_should_stop(threadID)
1054 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1055 &moveCount, &mp, dcCandidates, threadID, true))
1059 // All legal moves have been searched. A special case: If there were
1060 // no legal moves, it must be mate or stalemate:
1062 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1064 // If the search is not aborted, update the transposition table,
1065 // history counters, and killer moves.
1066 if (AbortSearch || thread_should_stop(threadID))
1069 if (bestValue <= oldAlpha)
1070 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1072 else if (bestValue >= beta)
1074 Move m = ss[ply].pv[ply];
1075 if (ok_to_history(pos, m)) // Only non capture moves are considered
1077 update_history(pos, m, depth, movesSearched, moveCount);
1078 if (m != ss[ply].killer1)
1080 ss[ply].killer2 = ss[ply].killer1;
1081 ss[ply].killer1 = m;
1084 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1087 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1093 // search() is the search function for zero-width nodes.
1095 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1096 int ply, bool allowNullmove, int threadID) {
1098 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1099 assert(ply >= 0 && ply < PLY_MAX);
1100 assert(threadID >= 0 && threadID < ActiveThreads);
1104 // Initialize, and make an early exit in case of an aborted search,
1105 // an instant draw, maximum ply reached, etc.
1106 if (AbortSearch || thread_should_stop(threadID))
1110 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1112 init_node(pos, ss, ply, threadID);
1117 if (ply >= PLY_MAX - 1)
1118 return evaluate(pos, ei, threadID);
1120 // Mate distance pruning
1121 if (value_mated_in(ply) >= beta)
1124 if (value_mate_in(ply + 1) < beta)
1127 // Transposition table lookup
1128 const TTEntry* tte = TT.retrieve(pos);
1129 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1131 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1133 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1134 return value_from_tt(tte->value(), ply);
1137 Value approximateEval = quick_evaluate(pos);
1138 bool mateThreat = false;
1139 bool isCheck = pos.is_check();
1144 && ok_to_do_nullmove(pos)
1145 && approximateEval >= beta - NullMoveMargin)
1147 ss[ply].currentMove = MOVE_NULL;
1150 pos.do_null_move(u);
1151 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1152 pos.undo_null_move(u);
1154 if (nullValue >= beta)
1156 if (depth < 6 * OnePly)
1159 // Do zugzwang verification search
1160 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1164 // The null move failed low, which means that we may be faced with
1165 // some kind of threat. If the previous move was reduced, check if
1166 // the move that refuted the null move was somehow connected to the
1167 // move which was reduced. If a connection is found, return a fail
1168 // low score (which will cause the reduced move to fail high in the
1169 // parent node, which will trigger a re-search with full depth).
1170 if (nullValue == value_mated_in(ply + 2))
1173 ss[ply].threatMove = ss[ply + 1].currentMove;
1174 if ( depth < ThreatDepth
1175 && ss[ply - 1].reduction
1176 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1180 // Null move search not allowed, try razoring
1181 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1182 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1184 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1189 // Go with internal iterative deepening if we don't have a TT move
1190 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1191 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1193 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1194 ttMove = ss[ply].pv[ply];
1197 // Initialize a MovePicker object for the current position, and prepare
1198 // to search all moves:
1199 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1200 ss[ply].killer1, ss[ply].killer2, depth);
1202 Move move, movesSearched[256];
1204 Value value, bestValue = -VALUE_INFINITE;
1205 Bitboard dcCandidates = mp.discovered_check_candidates();
1206 Value futilityValue = VALUE_NONE;
1207 bool useFutilityPruning = UseFutilityPruning
1208 && depth < SelectiveDepth
1211 // Loop through all legal moves until no moves remain or a beta cutoff
1213 while ( bestValue < beta
1214 && (move = mp.get_next_move()) != MOVE_NONE
1215 && !thread_should_stop(threadID))
1217 assert(move_is_ok(move));
1219 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1220 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1221 bool moveIsCapture = pos.move_is_capture(move);
1222 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1224 movesSearched[moveCount++] = ss[ply].currentMove = move;
1226 // Decide the new search depth
1227 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1228 Depth newDepth = depth - OnePly + ext;
1231 if ( useFutilityPruning
1234 && !moveIsPassedPawnPush
1235 && !move_promotion(move))
1237 if ( moveCount >= 2 + int(depth)
1238 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1241 if (depth < 3 * OnePly && approximateEval < beta)
1243 if (futilityValue == VALUE_NONE)
1244 futilityValue = evaluate(pos, ei, threadID)
1245 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1247 if (futilityValue < beta)
1249 if (futilityValue > bestValue)
1250 bestValue = futilityValue;
1256 // Make and search the move
1258 pos.do_move(move, u, dcCandidates);
1260 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1261 // if the move fails high will be re-searched at full depth.
1262 if ( depth >= 2*OnePly
1264 && moveCount >= LMRNonPVMoves
1266 && !move_promotion(move)
1267 && !moveIsPassedPawnPush
1268 && !move_is_castle(move)
1269 && move != ss[ply].killer1
1270 && move != ss[ply].killer2)
1272 ss[ply].reduction = OnePly;
1273 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1276 value = beta; // Just to trigger next condition
1278 if (value >= beta) // Go with full depth non-pv search
1280 ss[ply].reduction = Depth(0);
1281 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1283 pos.undo_move(move, u);
1285 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1288 if (value > bestValue)
1294 if (value == value_mate_in(ply + 1))
1295 ss[ply].mateKiller = move;
1299 if ( ActiveThreads > 1
1301 && depth >= MinimumSplitDepth
1303 && idle_thread_exists(threadID)
1305 && !thread_should_stop(threadID)
1306 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1307 &mp, dcCandidates, threadID, false))
1311 // All legal moves have been searched. A special case: If there were
1312 // no legal moves, it must be mate or stalemate.
1314 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1316 // If the search is not aborted, update the transposition table,
1317 // history counters, and killer moves.
1318 if (AbortSearch || thread_should_stop(threadID))
1321 if (bestValue < beta)
1322 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1325 Move m = ss[ply].pv[ply];
1326 if (ok_to_history(pos, m)) // Only non capture moves are considered
1328 update_history(pos, m, depth, movesSearched, moveCount);
1329 if (m != ss[ply].killer1)
1331 ss[ply].killer2 = ss[ply].killer1;
1332 ss[ply].killer1 = m;
1335 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1341 // qsearch() is the quiescence search function, which is called by the main
1342 // search function when the remaining depth is zero (or, to be more precise,
1343 // less than OnePly).
1345 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1346 Depth depth, int ply, int threadID) {
1348 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1349 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1351 assert(ply >= 0 && ply < PLY_MAX);
1352 assert(threadID >= 0 && threadID < ActiveThreads);
1356 // Initialize, and make an early exit in case of an aborted search,
1357 // an instant draw, maximum ply reached, etc.
1358 if (AbortSearch || thread_should_stop(threadID))
1361 init_node(pos, ss, ply, threadID);
1366 // Transposition table lookup
1367 const TTEntry* tte = TT.retrieve(pos);
1368 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1369 return value_from_tt(tte->value(), ply);
1371 // Evaluate the position statically
1372 Value staticValue = evaluate(pos, ei, threadID);
1374 if (ply == PLY_MAX - 1)
1377 // Initialize "stand pat score", and return it immediately if it is
1379 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1381 if (bestValue >= beta)
1384 if (bestValue > alpha)
1387 // Initialize a MovePicker object for the current position, and prepare
1388 // to search the moves. Because the depth is <= 0 here, only captures,
1389 // queen promotions and checks (only if depth == 0) will be generated.
1390 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1394 Bitboard dcCandidates = mp.discovered_check_candidates();
1395 bool isCheck = pos.is_check();
1397 // Loop through the moves until no moves remain or a beta cutoff
1399 while ( alpha < beta
1400 && (move = mp.get_next_move()) != MOVE_NONE)
1402 assert(move_is_ok(move));
1404 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1405 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1408 ss[ply].currentMove = move;
1411 if ( UseQSearchFutilityPruning
1414 && !move_promotion(move)
1415 && !moveIsPassedPawnPush
1416 && beta - alpha == 1
1417 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1419 Value futilityValue = staticValue
1420 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1421 pos.endgame_value_of_piece_on(move_to(move)))
1423 + ei.futilityMargin;
1425 if (futilityValue < alpha)
1427 if (futilityValue > bestValue)
1428 bestValue = futilityValue;
1433 // Don't search captures and checks with negative SEE values.
1435 && !move_promotion(move)
1436 && (pos.midgame_value_of_piece_on(move_from(move)) >
1437 pos.midgame_value_of_piece_on(move_to(move)))
1438 && pos.see(move) < 0)
1441 // Make and search the move.
1443 pos.do_move(move, u, dcCandidates);
1444 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1445 pos.undo_move(move, u);
1447 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1450 if (value > bestValue)
1461 // All legal moves have been searched. A special case: If we're in check
1462 // and no legal moves were found, it is checkmate:
1463 if (pos.is_check() && moveCount == 0) // Mate!
1464 return value_mated_in(ply);
1466 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1468 // Update transposition table
1469 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1475 // sp_search() is used to search from a split point. This function is called
1476 // by each thread working at the split point. It is similar to the normal
1477 // search() function, but simpler. Because we have already probed the hash
1478 // table, done a null move search, and searched the first move before
1479 // splitting, we don't have to repeat all this work in sp_search(). We
1480 // also don't need to store anything to the hash table here: This is taken
1481 // care of after we return from the split point.
1483 void sp_search(SplitPoint *sp, int threadID) {
1485 assert(threadID >= 0 && threadID < ActiveThreads);
1486 assert(ActiveThreads > 1);
1488 Position pos = Position(sp->pos);
1489 SearchStack *ss = sp->sstack[threadID];
1492 bool isCheck = pos.is_check();
1493 bool useFutilityPruning = UseFutilityPruning
1494 && sp->depth < SelectiveDepth
1497 while ( sp->bestValue < sp->beta
1498 && !thread_should_stop(threadID)
1499 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1501 assert(move_is_ok(move));
1503 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1504 bool moveIsCapture = pos.move_is_capture(move);
1505 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1507 lock_grab(&(sp->lock));
1508 int moveCount = ++sp->moves;
1509 lock_release(&(sp->lock));
1511 ss[sp->ply].currentMove = move;
1513 // Decide the new search depth.
1514 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1515 Depth newDepth = sp->depth - OnePly + ext;
1518 if ( useFutilityPruning
1521 && !moveIsPassedPawnPush
1522 && !move_promotion(move)
1523 && moveCount >= 2 + int(sp->depth)
1524 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1527 // Make and search the move.
1529 pos.do_move(move, u, sp->dcCandidates);
1531 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1532 // if the move fails high will be re-searched at full depth.
1533 if ( ext == Depth(0)
1534 && moveCount >= LMRNonPVMoves
1536 && !moveIsPassedPawnPush
1537 && !move_promotion(move)
1538 && !move_is_castle(move)
1539 && move != ss[sp->ply].killer1
1540 && move != ss[sp->ply].killer2)
1542 ss[sp->ply].reduction = OnePly;
1543 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1546 value = sp->beta; // Just to trigger next condition
1548 if (value >= sp->beta) // Go with full depth non-pv search
1550 ss[sp->ply].reduction = Depth(0);
1551 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1553 pos.undo_move(move, u);
1555 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1557 if (thread_should_stop(threadID))
1561 lock_grab(&(sp->lock));
1562 if (value > sp->bestValue && !thread_should_stop(threadID))
1564 sp->bestValue = value;
1565 if (sp->bestValue >= sp->beta)
1567 sp_update_pv(sp->parentSstack, ss, sp->ply);
1568 for (int i = 0; i < ActiveThreads; i++)
1569 if (i != threadID && (i == sp->master || sp->slaves[i]))
1570 Threads[i].stop = true;
1572 sp->finished = true;
1575 lock_release(&(sp->lock));
1578 lock_grab(&(sp->lock));
1580 // If this is the master thread and we have been asked to stop because of
1581 // a beta cutoff higher up in the tree, stop all slave threads:
1582 if (sp->master == threadID && thread_should_stop(threadID))
1583 for (int i = 0; i < ActiveThreads; i++)
1585 Threads[i].stop = true;
1588 sp->slaves[threadID] = 0;
1590 lock_release(&(sp->lock));
1594 // sp_search_pv() is used to search from a PV split point. This function
1595 // is called by each thread working at the split point. It is similar to
1596 // the normal search_pv() function, but simpler. Because we have already
1597 // probed the hash table and searched the first move before splitting, we
1598 // don't have to repeat all this work in sp_search_pv(). We also don't
1599 // need to store anything to the hash table here: This is taken care of
1600 // after we return from the split point.
1602 void sp_search_pv(SplitPoint *sp, int threadID) {
1604 assert(threadID >= 0 && threadID < ActiveThreads);
1605 assert(ActiveThreads > 1);
1607 Position pos = Position(sp->pos);
1608 SearchStack *ss = sp->sstack[threadID];
1612 while ( sp->alpha < sp->beta
1613 && !thread_should_stop(threadID)
1614 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1616 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1617 bool moveIsCapture = pos.move_is_capture(move);
1618 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1620 assert(move_is_ok(move));
1622 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1623 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1625 lock_grab(&(sp->lock));
1626 int moveCount = ++sp->moves;
1627 lock_release(&(sp->lock));
1629 ss[sp->ply].currentMove = move;
1631 // Decide the new search depth.
1632 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1633 Depth newDepth = sp->depth - OnePly + ext;
1635 // Make and search the move.
1637 pos.do_move(move, u, sp->dcCandidates);
1639 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1640 // if the move fails high will be re-searched at full depth.
1641 if ( ext == Depth(0)
1642 && moveCount >= LMRPVMoves
1644 && !moveIsPassedPawnPush
1645 && !move_promotion(move)
1646 && !move_is_castle(move)
1647 && move != ss[sp->ply].killer1
1648 && move != ss[sp->ply].killer2)
1650 ss[sp->ply].reduction = OnePly;
1651 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1654 value = sp->alpha + 1; // Just to trigger next condition
1656 if (value > sp->alpha) // Go with full depth non-pv search
1658 ss[sp->ply].reduction = Depth(0);
1659 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1661 if (value > sp->alpha && value < sp->beta)
1663 // When the search fails high at ply 1 while searching the first
1664 // move at the root, set the flag failHighPly1. This is used for
1665 // time managment: We don't want to stop the search early in
1666 // such cases, because resolving the fail high at ply 1 could
1667 // result in a big drop in score at the root.
1668 if (sp->ply == 1 && RootMoveNumber == 1)
1669 Threads[threadID].failHighPly1 = true;
1671 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1672 Threads[threadID].failHighPly1 = false;
1675 pos.undo_move(move, u);
1677 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1679 if (thread_should_stop(threadID))
1683 lock_grab(&(sp->lock));
1684 if (value > sp->bestValue && !thread_should_stop(threadID))
1686 sp->bestValue = value;
1687 if (value > sp->alpha)
1690 sp_update_pv(sp->parentSstack, ss, sp->ply);
1691 if (value == value_mate_in(sp->ply + 1))
1692 ss[sp->ply].mateKiller = move;
1694 if(value >= sp->beta)
1696 for(int i = 0; i < ActiveThreads; i++)
1697 if(i != threadID && (i == sp->master || sp->slaves[i]))
1698 Threads[i].stop = true;
1700 sp->finished = true;
1703 // If we are at ply 1, and we are searching the first root move at
1704 // ply 0, set the 'Problem' variable if the score has dropped a lot
1705 // (from the computer's point of view) since the previous iteration:
1706 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1709 lock_release(&(sp->lock));
1712 lock_grab(&(sp->lock));
1714 // If this is the master thread and we have been asked to stop because of
1715 // a beta cutoff higher up in the tree, stop all slave threads:
1716 if (sp->master == threadID && thread_should_stop(threadID))
1717 for (int i = 0; i < ActiveThreads; i++)
1719 Threads[i].stop = true;
1722 sp->slaves[threadID] = 0;
1724 lock_release(&(sp->lock));
1728 /// The RootMove class
1732 RootMove::RootMove() {
1733 nodes = cumulativeNodes = 0ULL;
1736 // RootMove::operator<() is the comparison function used when
1737 // sorting the moves. A move m1 is considered to be better
1738 // than a move m2 if it has a higher score, or if the moves
1739 // have equal score but m1 has the higher node count.
1741 bool RootMove::operator<(const RootMove& m) {
1743 if (score != m.score)
1744 return (score < m.score);
1746 return nodes <= m.nodes;
1749 /// The RootMoveList class
1753 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1755 MoveStack mlist[MaxRootMoves];
1756 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1758 // Generate all legal moves
1759 int lm_count = generate_legal_moves(pos, mlist);
1761 // Add each move to the moves[] array
1762 for (int i = 0; i < lm_count; i++)
1764 bool includeMove = includeAllMoves;
1766 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1767 includeMove = (searchMoves[k] == mlist[i].move);
1771 // Find a quick score for the move
1773 SearchStack ss[PLY_MAX_PLUS_2];
1775 moves[count].move = mlist[i].move;
1776 moves[count].nodes = 0ULL;
1777 pos.do_move(moves[count].move, u);
1778 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1780 pos.undo_move(moves[count].move, u);
1781 moves[count].pv[0] = moves[i].move;
1782 moves[count].pv[1] = MOVE_NONE; // FIXME
1790 // Simple accessor methods for the RootMoveList class
1792 inline Move RootMoveList::get_move(int moveNum) const {
1793 return moves[moveNum].move;
1796 inline Value RootMoveList::get_move_score(int moveNum) const {
1797 return moves[moveNum].score;
1800 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1801 moves[moveNum].score = score;
1804 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1805 moves[moveNum].nodes = nodes;
1806 moves[moveNum].cumulativeNodes += nodes;
1809 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1811 for(j = 0; pv[j] != MOVE_NONE; j++)
1812 moves[moveNum].pv[j] = pv[j];
1813 moves[moveNum].pv[j] = MOVE_NONE;
1816 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1817 return moves[moveNum].pv[i];
1820 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1821 return moves[moveNum].cumulativeNodes;
1824 inline int RootMoveList::move_count() const {
1829 // RootMoveList::scan_for_easy_move() is called at the end of the first
1830 // iteration, and is used to detect an "easy move", i.e. a move which appears
1831 // to be much bester than all the rest. If an easy move is found, the move
1832 // is returned, otherwise the function returns MOVE_NONE. It is very
1833 // important that this function is called at the right moment: The code
1834 // assumes that the first iteration has been completed and the moves have
1835 // been sorted. This is done in RootMoveList c'tor.
1837 Move RootMoveList::scan_for_easy_move() const {
1844 // moves are sorted so just consider the best and the second one
1845 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1851 // RootMoveList::sort() sorts the root move list at the beginning of a new
1854 inline void RootMoveList::sort() {
1856 sort_multipv(count - 1); // all items
1860 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1861 // list by their scores and depths. It is used to order the different PVs
1862 // correctly in MultiPV mode.
1864 void RootMoveList::sort_multipv(int n) {
1866 for (int i = 1; i <= n; i++)
1868 RootMove rm = moves[i];
1870 for (j = i; j > 0 && moves[j-1] < rm; j--)
1871 moves[j] = moves[j-1];
1877 // init_search_stack() initializes a search stack at the beginning of a
1878 // new search from the root.
1880 void init_search_stack(SearchStack ss[]) {
1881 for(int i = 0; i < 3; i++) {
1882 ss[i].pv[i] = MOVE_NONE;
1883 ss[i].pv[i+1] = MOVE_NONE;
1884 ss[i].currentMove = MOVE_NONE;
1885 ss[i].mateKiller = MOVE_NONE;
1886 ss[i].killer1 = MOVE_NONE;
1887 ss[i].killer2 = MOVE_NONE;
1888 ss[i].threatMove = MOVE_NONE;
1889 ss[i].reduction = Depth(0);
1894 // init_node() is called at the beginning of all the search functions
1895 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1896 // stack object corresponding to the current node. Once every
1897 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1898 // for user input and checks whether it is time to stop the search.
1900 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1901 assert(ply >= 0 && ply < PLY_MAX);
1902 assert(threadID >= 0 && threadID < ActiveThreads);
1904 Threads[threadID].nodes++;
1908 if(NodesSincePoll >= NodesBetweenPolls) {
1914 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1915 ss[ply+2].mateKiller = MOVE_NONE;
1916 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1917 ss[ply].threatMove = MOVE_NONE;
1918 ss[ply].reduction = Depth(0);
1919 ss[ply].currentMoveCaptureValue = Value(0);
1921 if(Threads[threadID].printCurrentLine)
1922 print_current_line(ss, ply, threadID);
1926 // update_pv() is called whenever a search returns a value > alpha. It
1927 // updates the PV in the SearchStack object corresponding to the current
1930 void update_pv(SearchStack ss[], int ply) {
1931 assert(ply >= 0 && ply < PLY_MAX);
1933 ss[ply].pv[ply] = ss[ply].currentMove;
1935 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1936 ss[ply].pv[p] = ss[ply+1].pv[p];
1937 ss[ply].pv[p] = MOVE_NONE;
1941 // sp_update_pv() is a variant of update_pv for use at split points. The
1942 // difference between the two functions is that sp_update_pv also updates
1943 // the PV at the parent node.
1945 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1946 assert(ply >= 0 && ply < PLY_MAX);
1948 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1950 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1951 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1952 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1956 // connected_moves() tests whether two moves are 'connected' in the sense
1957 // that the first move somehow made the second move possible (for instance
1958 // if the moving piece is the same in both moves). The first move is
1959 // assumed to be the move that was made to reach the current position, while
1960 // the second move is assumed to be a move from the current position.
1962 bool connected_moves(const Position &pos, Move m1, Move m2) {
1963 Square f1, t1, f2, t2;
1965 assert(move_is_ok(m1));
1966 assert(move_is_ok(m2));
1971 // Case 1: The moving piece is the same in both moves.
1977 // Case 2: The destination square for m2 was vacated by m1.
1983 // Case 3: Moving through the vacated square:
1984 if(piece_is_slider(pos.piece_on(f2)) &&
1985 bit_is_set(squares_between(f2, t2), f1))
1988 // Case 4: The destination square for m2 is attacked by the moving piece
1990 if(pos.piece_attacks_square(t1, t2))
1993 // Case 5: Discovered check, checking piece is the piece moved in m1:
1994 if(piece_is_slider(pos.piece_on(t1)) &&
1995 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1997 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1999 Bitboard occ = pos.occupied_squares();
2000 Color us = pos.side_to_move();
2001 Square ksq = pos.king_square(us);
2002 clear_bit(&occ, f2);
2003 if(pos.type_of_piece_on(t1) == BISHOP) {
2004 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2007 else if(pos.type_of_piece_on(t1) == ROOK) {
2008 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2012 assert(pos.type_of_piece_on(t1) == QUEEN);
2013 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2022 // extension() decides whether a move should be searched with normal depth,
2023 // or with extended depth. Certain classes of moves (checking moves, in
2024 // particular) are searched with bigger depth than ordinary moves.
2026 Depth extension(const Position &pos, Move m, bool pvNode,
2027 bool check, bool singleReply, bool mateThreat) {
2029 Depth result = Depth(0);
2032 result += CheckExtension[pvNode];
2035 result += SingleReplyExtension[pvNode];
2037 if (pos.move_is_pawn_push_to_7th(m))
2038 result += PawnPushTo7thExtension[pvNode];
2040 if (pos.move_is_passed_pawn_push(m))
2041 result += PassedPawnExtension[pvNode];
2044 result += MateThreatExtension[pvNode];
2046 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
\r
2047 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
\r
2048 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
\r
2049 && !move_promotion(m))
2050 result += PawnEndgameExtension[pvNode];
2053 && pos.move_is_capture(m)
2054 && pos.type_of_piece_on(move_to(m)) != PAWN
2058 return Min(result, OnePly);
2062 // ok_to_do_nullmove() looks at the current position and decides whether
2063 // doing a 'null move' should be allowed. In order to avoid zugzwang
2064 // problems, null moves are not allowed when the side to move has very
2065 // little material left. Currently, the test is a bit too simple: Null
2066 // moves are avoided only when the side to move has only pawns left. It's
2067 // probably a good idea to avoid null moves in at least some more
2068 // complicated endgames, e.g. KQ vs KR. FIXME
2070 bool ok_to_do_nullmove(const Position &pos) {
2071 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2077 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2078 // non-tactical moves late in the move list close to the leaves are
2079 // candidates for pruning.
2081 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2082 Square mfrom, mto, tfrom, tto;
2084 assert(move_is_ok(m));
2085 assert(threat == MOVE_NONE || move_is_ok(threat));
2086 assert(!move_promotion(m));
2087 assert(!pos.move_is_check(m));
2088 assert(!pos.move_is_capture(m));
2089 assert(!pos.move_is_passed_pawn_push(m));
2090 assert(d >= OnePly);
2092 mfrom = move_from(m);
2094 tfrom = move_from(threat);
2095 tto = move_to(threat);
2097 // Case 1: Castling moves are never pruned.
2098 if(move_is_castle(m))
2101 // Case 2: Don't prune moves which move the threatened piece
2102 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2105 // Case 3: If the threatened piece has value less than or equal to the
2106 // value of the threatening piece, don't prune move which defend it.
2107 if(!PruneDefendingMoves && threat != MOVE_NONE
2108 && (piece_value_midgame(pos.piece_on(tfrom))
2109 >= piece_value_midgame(pos.piece_on(tto)))
2110 && pos.move_attacks_square(m, tto))
2113 // Case 4: Don't prune moves with good history.
2114 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2117 // Case 5: If the moving piece in the threatened move is a slider, don't
2118 // prune safe moves which block its ray.
2119 if(!PruneBlockingMoves && threat != MOVE_NONE
2120 && piece_is_slider(pos.piece_on(tfrom))
2121 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2128 // ok_to_use_TT() returns true if a transposition table score
2129 // can be used at a given point in search.
2131 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2133 Value v = value_from_tt(tte->value(), ply);
2135 return ( tte->depth() >= depth
2136 || v >= Max(value_mate_in(100), beta)
2137 || v < Min(value_mated_in(100), beta))
2139 && ( (is_lower_bound(tte->type()) && v >= beta)
2140 || (is_upper_bound(tte->type()) && v < beta));
2144 // ok_to_history() returns true if a move m can be stored
2145 // in history. Should be a non capturing move.
2147 bool ok_to_history(const Position& pos, Move m) {
2149 return pos.square_is_empty(move_to(m))
2150 && !move_promotion(m)
2155 // update_history() registers a good move that produced a beta-cutoff
2156 // in history and marks as failures all the other moves of that ply.
2158 void update_history(const Position& pos, Move m, Depth depth,
2159 Move movesSearched[], int moveCount) {
2161 H.success(pos.piece_on(move_from(m)), m, depth);
2163 for (int i = 0; i < moveCount - 1; i++)
2164 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2165 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2168 // fail_high_ply_1() checks if some thread is currently resolving a fail
2169 // high at ply 1 at the node below the first root node. This information
2170 // is used for time managment.
2172 bool fail_high_ply_1() {
2173 for(int i = 0; i < ActiveThreads; i++)
2174 if(Threads[i].failHighPly1)
2180 // current_search_time() returns the number of milliseconds which have passed
2181 // since the beginning of the current search.
2183 int current_search_time() {
2184 return get_system_time() - SearchStartTime;
2188 // nps() computes the current nodes/second count.
2191 int t = current_search_time();
2192 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2196 // poll() performs two different functions: It polls for user input, and it
2197 // looks at the time consumed so far and decides if it's time to abort the
2202 static int lastInfoTime;
2203 int t = current_search_time();
2208 // We are line oriented, don't read single chars
2209 std::string command;
2210 if (!std::getline(std::cin, command))
2213 if (command == "quit")
2216 PonderSearch = false;
2219 else if(command == "stop")
2222 PonderSearch = false;
2224 else if(command == "ponderhit")
2227 // Print search information
2231 else if (lastInfoTime > t)
2232 // HACK: Must be a new search where we searched less than
2233 // NodesBetweenPolls nodes during the first second of search.
2236 else if (t - lastInfoTime >= 1000)
2243 if (dbg_show_hit_rate)
2244 dbg_print_hit_rate();
2246 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2247 << " time " << t << " hashfull " << TT.full() << std::endl;
2248 lock_release(&IOLock);
2249 if (ShowCurrentLine)
2250 Threads[0].printCurrentLine = true;
2252 // Should we stop the search?
2256 bool overTime = t > AbsoluteMaxSearchTime
2257 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2258 || ( !FailHigh && !fail_high_ply_1() && !Problem
2259 && t > 6*(MaxSearchTime + ExtraSearchTime));
2261 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2262 || (ExactMaxTime && t >= ExactMaxTime)
2263 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2268 // ponderhit() is called when the program is pondering (i.e. thinking while
2269 // it's the opponent's turn to move) in order to let the engine know that
2270 // it correctly predicted the opponent's move.
2273 int t = current_search_time();
2274 PonderSearch = false;
2275 if(Iteration >= 2 &&
2276 (!InfiniteSearch && (StopOnPonderhit ||
2277 t > AbsoluteMaxSearchTime ||
2278 (RootMoveNumber == 1 &&
2279 t > MaxSearchTime + ExtraSearchTime) ||
2280 (!FailHigh && !fail_high_ply_1() && !Problem &&
2281 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2286 // print_current_line() prints the current line of search for a given
2287 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2289 void print_current_line(SearchStack ss[], int ply, int threadID) {
2290 assert(ply >= 0 && ply < PLY_MAX);
2291 assert(threadID >= 0 && threadID < ActiveThreads);
2293 if(!Threads[threadID].idle) {
2295 std::cout << "info currline " << (threadID + 1);
2296 for(int p = 0; p < ply; p++)
2297 std::cout << " " << ss[p].currentMove;
2298 std::cout << std::endl;
2299 lock_release(&IOLock);
2301 Threads[threadID].printCurrentLine = false;
2302 if(threadID + 1 < ActiveThreads)
2303 Threads[threadID + 1].printCurrentLine = true;
2307 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2308 // while the program is pondering. The point is to work around a wrinkle in
2309 // the UCI protocol: When pondering, the engine is not allowed to give a
2310 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2311 // We simply wait here until one of these commands is sent, and return,
2312 // after which the bestmove and pondermove will be printed (in id_loop()).
2314 void wait_for_stop_or_ponderhit() {
2315 std::string command;
2318 if(!std::getline(std::cin, command))
2321 if(command == "quit") {
2322 OpeningBook.close();
2327 else if(command == "ponderhit" || command == "stop")
2333 // idle_loop() is where the threads are parked when they have no work to do.
2334 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2335 // object for which the current thread is the master.
2337 void idle_loop(int threadID, SplitPoint *waitSp) {
2338 assert(threadID >= 0 && threadID < THREAD_MAX);
2340 Threads[threadID].running = true;
2343 if(AllThreadsShouldExit && threadID != 0)
2346 // If we are not thinking, wait for a condition to be signaled instead
2347 // of wasting CPU time polling for work:
2348 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2349 #if !defined(_MSC_VER)
2350 pthread_mutex_lock(&WaitLock);
2351 if(Idle || threadID >= ActiveThreads)
2352 pthread_cond_wait(&WaitCond, &WaitLock);
2353 pthread_mutex_unlock(&WaitLock);
2355 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2359 // If this thread has been assigned work, launch a search:
2360 if(Threads[threadID].workIsWaiting) {
2361 Threads[threadID].workIsWaiting = false;
2362 if(Threads[threadID].splitPoint->pvNode)
2363 sp_search_pv(Threads[threadID].splitPoint, threadID);
2365 sp_search(Threads[threadID].splitPoint, threadID);
2366 Threads[threadID].idle = true;
2369 // If this thread is the master of a split point and all threads have
2370 // finished their work at this split point, return from the idle loop:
2371 if(waitSp != NULL && waitSp->cpus == 0)
2375 Threads[threadID].running = false;
2379 // init_split_point_stack() is called during program initialization, and
2380 // initializes all split point objects.
2382 void init_split_point_stack() {
2383 for(int i = 0; i < THREAD_MAX; i++)
2384 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2385 SplitPointStack[i][j].parent = NULL;
2386 lock_init(&(SplitPointStack[i][j].lock), NULL);
2391 // destroy_split_point_stack() is called when the program exits, and
2392 // destroys all locks in the precomputed split point objects.
2394 void destroy_split_point_stack() {
2395 for(int i = 0; i < THREAD_MAX; i++)
2396 for(int j = 0; j < MaxActiveSplitPoints; j++)
2397 lock_destroy(&(SplitPointStack[i][j].lock));
2401 // thread_should_stop() checks whether the thread with a given threadID has
2402 // been asked to stop, directly or indirectly. This can happen if a beta
2403 // cutoff has occured in thre thread's currently active split point, or in
2404 // some ancestor of the current split point.
2406 bool thread_should_stop(int threadID) {
2407 assert(threadID >= 0 && threadID < ActiveThreads);
2411 if(Threads[threadID].stop)
2413 if(ActiveThreads <= 2)
2415 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2417 Threads[threadID].stop = true;
2424 // thread_is_available() checks whether the thread with threadID "slave" is
2425 // available to help the thread with threadID "master" at a split point. An
2426 // obvious requirement is that "slave" must be idle. With more than two
2427 // threads, this is not by itself sufficient: If "slave" is the master of
2428 // some active split point, it is only available as a slave to the other
2429 // threads which are busy searching the split point at the top of "slave"'s
2430 // split point stack (the "helpful master concept" in YBWC terminology).
2432 bool thread_is_available(int slave, int master) {
2433 assert(slave >= 0 && slave < ActiveThreads);
2434 assert(master >= 0 && master < ActiveThreads);
2435 assert(ActiveThreads > 1);
2437 if(!Threads[slave].idle || slave == master)
2440 if(Threads[slave].activeSplitPoints == 0)
2441 // No active split points means that the thread is available as a slave
2442 // for any other thread.
2445 if(ActiveThreads == 2)
2448 // Apply the "helpful master" concept if possible.
2449 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2456 // idle_thread_exists() tries to find an idle thread which is available as
2457 // a slave for the thread with threadID "master".
2459 bool idle_thread_exists(int master) {
2460 assert(master >= 0 && master < ActiveThreads);
2461 assert(ActiveThreads > 1);
2463 for(int i = 0; i < ActiveThreads; i++)
2464 if(thread_is_available(i, master))
2470 // split() does the actual work of distributing the work at a node between
2471 // several threads at PV nodes. If it does not succeed in splitting the
2472 // node (because no idle threads are available, or because we have no unused
2473 // split point objects), the function immediately returns false. If
2474 // splitting is possible, a SplitPoint object is initialized with all the
2475 // data that must be copied to the helper threads (the current position and
2476 // search stack, alpha, beta, the search depth, etc.), and we tell our
2477 // helper threads that they have been assigned work. This will cause them
2478 // to instantly leave their idle loops and call sp_search_pv(). When all
2479 // threads have returned from sp_search_pv (or, equivalently, when
2480 // splitPoint->cpus becomes 0), split() returns true.
2482 bool split(const Position &p, SearchStack *sstck, int ply,
2483 Value *alpha, Value *beta, Value *bestValue,
2484 Depth depth, int *moves,
2485 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2487 assert(sstck != NULL);
2488 assert(ply >= 0 && ply < PLY_MAX);
2489 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2490 assert(!pvNode || *alpha < *beta);
2491 assert(*beta <= VALUE_INFINITE);
2492 assert(depth > Depth(0));
2493 assert(master >= 0 && master < ActiveThreads);
2494 assert(ActiveThreads > 1);
2496 SplitPoint *splitPoint;
2501 // If no other thread is available to help us, or if we have too many
2502 // active split points, don't split:
2503 if(!idle_thread_exists(master) ||
2504 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2505 lock_release(&MPLock);
2509 // Pick the next available split point object from the split point stack:
2510 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2511 Threads[master].activeSplitPoints++;
2513 // Initialize the split point object:
2514 splitPoint->parent = Threads[master].splitPoint;
2515 splitPoint->finished = false;
2516 splitPoint->ply = ply;
2517 splitPoint->depth = depth;
2518 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2519 splitPoint->beta = *beta;
2520 splitPoint->pvNode = pvNode;
2521 splitPoint->dcCandidates = dcCandidates;
2522 splitPoint->bestValue = *bestValue;
2523 splitPoint->master = master;
2524 splitPoint->mp = mp;
2525 splitPoint->moves = *moves;
2526 splitPoint->cpus = 1;
2527 splitPoint->pos.copy(p);
2528 splitPoint->parentSstack = sstck;
2529 for(i = 0; i < ActiveThreads; i++)
2530 splitPoint->slaves[i] = 0;
2532 // Copy the current position and the search stack to the master thread:
2533 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2534 Threads[master].splitPoint = splitPoint;
2536 // Make copies of the current position and search stack for each thread:
2537 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2539 if(thread_is_available(i, master)) {
2540 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2541 Threads[i].splitPoint = splitPoint;
2542 splitPoint->slaves[i] = 1;
2546 // Tell the threads that they have work to do. This will make them leave
2548 for(i = 0; i < ActiveThreads; i++)
2549 if(i == master || splitPoint->slaves[i]) {
2550 Threads[i].workIsWaiting = true;
2551 Threads[i].idle = false;
2552 Threads[i].stop = false;
2555 lock_release(&MPLock);
2557 // Everything is set up. The master thread enters the idle loop, from
2558 // which it will instantly launch a search, because its workIsWaiting
2559 // slot is 'true'. We send the split point as a second parameter to the
2560 // idle loop, which means that the main thread will return from the idle
2561 // loop when all threads have finished their work at this split point
2562 // (i.e. when // splitPoint->cpus == 0).
2563 idle_loop(master, splitPoint);
2565 // We have returned from the idle loop, which means that all threads are
2566 // finished. Update alpha, beta and bestvalue, and return:
2568 if(pvNode) *alpha = splitPoint->alpha;
2569 *beta = splitPoint->beta;
2570 *bestValue = splitPoint->bestValue;
2571 Threads[master].stop = false;
2572 Threads[master].idle = false;
2573 Threads[master].activeSplitPoints--;
2574 Threads[master].splitPoint = splitPoint->parent;
2575 lock_release(&MPLock);
2581 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2582 // to start a new search from the root.
2584 void wake_sleeping_threads() {
2585 if(ActiveThreads > 1) {
2586 for(int i = 1; i < ActiveThreads; i++) {
2587 Threads[i].idle = true;
2588 Threads[i].workIsWaiting = false;
2590 #if !defined(_MSC_VER)
2591 pthread_mutex_lock(&WaitLock);
2592 pthread_cond_broadcast(&WaitCond);
2593 pthread_mutex_unlock(&WaitLock);
2595 for(int i = 1; i < THREAD_MAX; i++)
2596 SetEvent(SitIdleEvent[i]);
2602 // init_thread() is the function which is called when a new thread is
2603 // launched. It simply calls the idle_loop() function with the supplied
2604 // threadID. There are two versions of this function; one for POSIX threads
2605 // and one for Windows threads.
2607 #if !defined(_MSC_VER)
2609 void *init_thread(void *threadID) {
2610 idle_loop(*(int *)threadID, NULL);
2616 DWORD WINAPI init_thread(LPVOID threadID) {
2617 idle_loop(*(int *)threadID, NULL);