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 LogFile << "Nodes: " << nodes_searched() << std::endl
734 << "Nodes/second: " << nps() << std::endl
735 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
737 p.do_move(ss[0].pv[0], u);
738 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
739 << std::endl << std::endl;
741 return rml.get_move_score(0);
745 // root_search() is the function which searches the root node. It is
746 // similar to search_pv except that it uses a different move ordering
747 // scheme (perhaps we should try to use this at internal PV nodes, too?)
748 // and prints some information to the standard output.
750 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
752 Value alpha = -VALUE_INFINITE;
753 Value beta = VALUE_INFINITE, value;
754 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
756 // Loop through all the moves in the root move list
757 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
764 RootMoveNumber = i + 1;
767 // Remember the node count before the move is searched. The node counts
768 // are used to sort the root moves at the next iteration.
769 nodes = nodes_searched();
771 // Pick the next root move, and print the move and the move number to
772 // the standard output.
773 move = ss[0].currentMove = rml.get_move(i);
774 if (current_search_time() >= 1000)
775 std::cout << "info currmove " << move
776 << " currmovenumber " << i + 1 << std::endl;
778 // Decide search depth for this move
780 ext = extension(pos, move, true, pos.move_is_check(move), false, false, &dangerous);
781 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
783 // Make the move, and search it
784 pos.do_move(move, u, dcCandidates);
788 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
789 // If the value has dropped a lot compared to the last iteration,
790 // set the boolean variable Problem to true. This variable is used
791 // for time managment: When Problem is true, we try to complete the
792 // current iteration before playing a move.
793 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
795 if (Problem && StopOnPonderhit)
796 StopOnPonderhit = false;
800 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
803 // Fail high! Set the boolean variable FailHigh to true, and
804 // re-search the move with a big window. The variable FailHigh is
805 // used for time managment: We try to avoid aborting the search
806 // prematurely during a fail high research.
808 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
812 pos.undo_move(move, u);
814 // Finished searching the move. If AbortSearch is true, the search
815 // was aborted because the user interrupted the search or because we
816 // ran out of time. In this case, the return value of the search cannot
817 // be trusted, and we break out of the loop without updating the best
822 // Remember the node count for this move. The node counts are used to
823 // sort the root moves at the next iteration.
824 rml.set_move_nodes(i, nodes_searched() - nodes);
826 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
828 if (value <= alpha && i >= MultiPV)
829 rml.set_move_score(i, -VALUE_INFINITE);
835 rml.set_move_score(i, value);
837 rml.set_move_pv(i, ss[0].pv);
841 // We record how often the best move has been changed in each
842 // iteration. This information is used for time managment: When
843 // the best move changes frequently, we allocate some more time.
845 BestMoveChangesByIteration[Iteration]++;
847 // Print search information to the standard output:
848 std::cout << "info depth " << Iteration
849 << " score " << value_to_string(value)
850 << " time " << current_search_time()
851 << " nodes " << nodes_searched()
855 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
856 std::cout << ss[0].pv[j] << " ";
858 std::cout << std::endl;
861 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
866 // Reset the global variable Problem to false if the value isn't too
867 // far below the final value from the last iteration.
868 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
874 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
877 std::cout << "info multipv " << j + 1
878 << " score " << value_to_string(rml.get_move_score(j))
879 << " depth " << ((j <= i)? Iteration : Iteration - 1)
880 << " time " << current_search_time()
881 << " nodes " << nodes_searched()
885 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
886 std::cout << rml.get_move_pv(j, k) << " ";
888 std::cout << std::endl;
890 alpha = rml.get_move_score(Min(i, MultiPV-1));
898 // search_pv() is the main search function for PV nodes.
900 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
901 Depth depth, int ply, int threadID) {
903 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
904 assert(beta > alpha && beta <= VALUE_INFINITE);
905 assert(ply >= 0 && ply < PLY_MAX);
906 assert(threadID >= 0 && threadID < ActiveThreads);
908 // Initialize, and make an early exit in case of an aborted search,
909 // an instant draw, maximum ply reached, etc.
910 if (AbortSearch || thread_should_stop(threadID))
914 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
916 init_node(pos, ss, ply, threadID);
923 if (ply >= PLY_MAX - 1)
924 return evaluate(pos, ei, threadID);
926 // Mate distance pruning
927 Value oldAlpha = alpha;
928 alpha = Max(value_mated_in(ply), alpha);
929 beta = Min(value_mate_in(ply+1), beta);
933 // Transposition table lookup. At PV nodes, we don't use the TT for
934 // pruning, but only for move ordering.
935 const TTEntry* tte = TT.retrieve(pos);
936 Move ttMove = (tte ? tte->move() : MOVE_NONE);
938 // Go with internal iterative deepening if we don't have a TT move
939 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
941 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
942 ttMove = ss[ply].pv[ply];
945 // Initialize a MovePicker object for the current position, and prepare
946 // to search all moves
947 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
949 Move move, movesSearched[256];
951 Value value, bestValue = -VALUE_INFINITE;
952 Bitboard dcCandidates = mp.discovered_check_candidates();
953 bool isCheck = pos.is_check();
954 bool mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
956 // Loop through all legal moves until no moves remain or a beta cutoff
959 && (move = mp.get_next_move()) != MOVE_NONE
960 && !thread_should_stop(threadID))
962 assert(move_is_ok(move));
964 bool singleReply = (isCheck && mp.number_of_moves() == 1);
965 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
966 bool moveIsCapture = pos.move_is_capture(move);
968 movesSearched[moveCount++] = ss[ply].currentMove = move;
971 ss[ply].currentMoveCaptureValue = pos.midgame_value_of_piece_on(move_to(move));
972 else if (move_is_ep(move))
973 ss[ply].currentMoveCaptureValue = PawnValueMidgame;
975 ss[ply].currentMoveCaptureValue = Value(0);
977 // Decide the new search depth
979 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat, &dangerous);
980 Depth newDepth = depth - OnePly + ext;
982 // Make and search the move
984 pos.do_move(move, u, dcCandidates);
986 if (moveCount == 1) // The first move in list is the PV
987 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
990 // Try to reduce non-pv search depth by one ply if move seems not problematic,
991 // if the move fails high will be re-searched at full depth.
992 if ( depth >= 2*OnePly
993 && moveCount >= LMRPVMoves
996 && !move_promotion(move)
997 && !move_is_castle(move)
998 && !move_is_killer(move, ss[ply]))
1000 ss[ply].reduction = OnePly;
1001 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1004 value = alpha + 1; // Just to trigger next condition
1006 if (value > alpha) // Go with full depth pv search
1008 ss[ply].reduction = Depth(0);
1009 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1010 if (value > alpha && value < beta)
1012 // When the search fails high at ply 1 while searching the first
1013 // move at the root, set the flag failHighPly1. This is used for
1014 // time managment: We don't want to stop the search early in
1015 // such cases, because resolving the fail high at ply 1 could
1016 // result in a big drop in score at the root.
1017 if (ply == 1 && RootMoveNumber == 1)
1018 Threads[threadID].failHighPly1 = true;
1020 // A fail high occurred. Re-search at full window (pv search)
1021 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1022 Threads[threadID].failHighPly1 = false;
1026 pos.undo_move(move, u);
1028 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1031 if (value > bestValue)
1038 if (value == value_mate_in(ply + 1))
1039 ss[ply].mateKiller = move;
1041 // If we are at ply 1, and we are searching the first root move at
1042 // ply 0, set the 'Problem' variable if the score has dropped a lot
1043 // (from the computer's point of view) since the previous iteration:
1044 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1049 if ( ActiveThreads > 1
1051 && depth >= MinimumSplitDepth
1053 && idle_thread_exists(threadID)
1055 && !thread_should_stop(threadID)
1056 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1057 &moveCount, &mp, dcCandidates, threadID, true))
1061 // All legal moves have been searched. A special case: If there were
1062 // no legal moves, it must be mate or stalemate:
1064 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1066 // If the search is not aborted, update the transposition table,
1067 // history counters, and killer moves.
1068 if (AbortSearch || thread_should_stop(threadID))
1071 if (bestValue <= oldAlpha)
1072 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1074 else if (bestValue >= beta)
1076 Move m = ss[ply].pv[ply];
1077 if (ok_to_history(pos, m)) // Only non capture moves are considered
1079 update_history(pos, m, depth, movesSearched, moveCount);
1080 update_killers(m, ss[ply]);
1082 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1085 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1091 // search() is the search function for zero-width nodes.
1093 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1094 int ply, bool allowNullmove, int threadID) {
1096 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1097 assert(ply >= 0 && ply < PLY_MAX);
1098 assert(threadID >= 0 && threadID < ActiveThreads);
1102 // Initialize, and make an early exit in case of an aborted search,
1103 // an instant draw, maximum ply reached, etc.
1104 if (AbortSearch || thread_should_stop(threadID))
1108 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1110 init_node(pos, ss, ply, threadID);
1115 if (ply >= PLY_MAX - 1)
1116 return evaluate(pos, ei, threadID);
1118 // Mate distance pruning
1119 if (value_mated_in(ply) >= beta)
1122 if (value_mate_in(ply + 1) < beta)
1125 // Transposition table lookup
1126 const TTEntry* tte = TT.retrieve(pos);
1127 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1129 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1131 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1132 return value_from_tt(tte->value(), ply);
1135 Value approximateEval = quick_evaluate(pos);
1136 bool mateThreat = false;
1137 bool nullDrivenIID = false;
1138 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 int R = (depth > 7 ? 4 : 3);
1153 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1155 // Check for a null capture artifact, if the value without the null capture
1156 // is above beta then there is a good possibility that this is a cut-node.
1157 // We will do an IID later to find a ttMove.
1158 if ( UseNullDrivenIID
1160 && depth > 6 * OnePly
1161 && ttMove == MOVE_NONE
1162 && ss[ply + 1].currentMove != MOVE_NONE
1163 && pos.move_is_capture(ss[ply + 1].currentMove)
1164 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1165 nullDrivenIID = true;
1167 pos.undo_null_move(u);
1169 if (nullValue >= beta)
1171 if (depth < 6 * OnePly)
1174 // Do zugzwang verification search
1175 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1179 // The null move failed low, which means that we may be faced with
1180 // some kind of threat. If the previous move was reduced, check if
1181 // the move that refuted the null move was somehow connected to the
1182 // move which was reduced. If a connection is found, return a fail
1183 // low score (which will cause the reduced move to fail high in the
1184 // parent node, which will trigger a re-search with full depth).
1185 if (nullValue == value_mated_in(ply + 2))
1188 nullDrivenIID = false;
1190 ss[ply].threatMove = ss[ply + 1].currentMove;
1191 if ( depth < ThreatDepth
1192 && ss[ply - 1].reduction
1193 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1197 // Null move search not allowed, try razoring
1198 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1199 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1201 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1206 // Go with internal iterative deepening if we don't have a TT move
1207 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1208 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1210 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1211 ttMove = ss[ply].pv[ply];
1213 else if (nullDrivenIID)
1215 // The null move failed low due to a suspicious capture. Perhaps we
1216 // are facing a null capture artifact due to the side to move change
1217 // and this is a cut-node. So it's a good time to search for a ttMove.
1218 Move tm = ss[ply].threatMove;
1220 assert(tm != MOVE_NONE);
1221 assert(ttMove == MOVE_NONE);
1223 search(pos, ss, beta, depth/2, ply, false, threadID);
1224 ttMove = ss[ply].pv[ply];
1225 ss[ply].threatMove = tm;
1228 // Initialize a MovePicker object for the current position, and prepare
1229 // to search all moves:
1230 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1232 Move move, movesSearched[256];
1234 Value value, bestValue = -VALUE_INFINITE;
1235 Bitboard dcCandidates = mp.discovered_check_candidates();
1236 Value futilityValue = VALUE_NONE;
1237 bool useFutilityPruning = UseFutilityPruning
1238 && depth < SelectiveDepth
1241 // Loop through all legal moves until no moves remain or a beta cutoff
1243 while ( bestValue < beta
1244 && (move = mp.get_next_move()) != MOVE_NONE
1245 && !thread_should_stop(threadID))
1247 assert(move_is_ok(move));
1249 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1250 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1251 bool moveIsCapture = pos.move_is_capture(move);
1253 movesSearched[moveCount++] = ss[ply].currentMove = move;
1255 // Decide the new search depth
1257 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat, &dangerous);
1258 Depth newDepth = depth - OnePly + ext;
1261 if ( useFutilityPruning
1264 && !move_promotion(move))
1266 if ( moveCount >= 2 + int(depth)
1267 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1270 if (depth < 3 * OnePly && approximateEval < beta)
1272 if (futilityValue == VALUE_NONE)
1273 futilityValue = evaluate(pos, ei, threadID)
1274 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1276 if (futilityValue < beta)
1278 if (futilityValue > bestValue)
1279 bestValue = futilityValue;
1285 // Make and search the move
1287 pos.do_move(move, u, dcCandidates);
1289 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1290 // if the move fails high will be re-searched at full depth.
1291 if ( depth >= 2*OnePly
1292 && moveCount >= LMRNonPVMoves
1295 && !move_promotion(move)
1296 && !move_is_castle(move)
1297 && !move_is_killer(move, ss[ply]))
1299 ss[ply].reduction = OnePly;
1300 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1303 value = beta; // Just to trigger next condition
1305 if (value >= beta) // Go with full depth non-pv search
1307 ss[ply].reduction = Depth(0);
1308 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1310 pos.undo_move(move, u);
1312 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1315 if (value > bestValue)
1321 if (value == value_mate_in(ply + 1))
1322 ss[ply].mateKiller = move;
1326 if ( ActiveThreads > 1
1328 && depth >= MinimumSplitDepth
1330 && idle_thread_exists(threadID)
1332 && !thread_should_stop(threadID)
1333 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1334 &mp, dcCandidates, threadID, false))
1338 // All legal moves have been searched. A special case: If there were
1339 // no legal moves, it must be mate or stalemate.
1341 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1343 // If the search is not aborted, update the transposition table,
1344 // history counters, and killer moves.
1345 if (AbortSearch || thread_should_stop(threadID))
1348 if (bestValue < beta)
1349 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1352 Move m = ss[ply].pv[ply];
1353 if (ok_to_history(pos, m)) // Only non capture moves are considered
1355 update_history(pos, m, depth, movesSearched, moveCount);
1356 update_killers(m, ss[ply]);
1358 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1364 // qsearch() is the quiescence search function, which is called by the main
1365 // search function when the remaining depth is zero (or, to be more precise,
1366 // less than OnePly).
1368 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1369 Depth depth, int ply, int threadID) {
1371 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1372 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1374 assert(ply >= 0 && ply < PLY_MAX);
1375 assert(threadID >= 0 && threadID < ActiveThreads);
1379 // Initialize, and make an early exit in case of an aborted search,
1380 // an instant draw, maximum ply reached, etc.
1381 if (AbortSearch || thread_should_stop(threadID))
1384 init_node(pos, ss, ply, threadID);
1389 // Transposition table lookup
1390 const TTEntry* tte = TT.retrieve(pos);
1391 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1392 return value_from_tt(tte->value(), ply);
1394 // Evaluate the position statically
1395 Value staticValue = evaluate(pos, ei, threadID);
1397 if (ply == PLY_MAX - 1)
1400 // Initialize "stand pat score", and return it immediately if it is
1402 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1404 if (bestValue >= beta)
1407 if (bestValue > alpha)
1410 // Initialize a MovePicker object for the current position, and prepare
1411 // to search the moves. Because the depth is <= 0 here, only captures,
1412 // queen promotions and checks (only if depth == 0) will be generated.
1413 MovePicker mp = MovePicker(pos, false, MOVE_NONE, EmptySearchStack, depth, &ei);
1416 Bitboard dcCandidates = mp.discovered_check_candidates();
1417 bool isCheck = pos.is_check();
1418 bool pvNode = (beta - alpha != 1);
1419 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1421 // Loop through the moves until no moves remain or a beta cutoff
1423 while ( alpha < beta
1424 && (move = mp.get_next_move()) != MOVE_NONE)
1426 assert(move_is_ok(move));
1429 ss[ply].currentMove = move;
1432 if ( UseQSearchFutilityPruning
1436 && !move_promotion(move)
1437 && !pos.move_is_check(move, dcCandidates)
1438 && !pos.move_is_passed_pawn_push(move))
1440 Value futilityValue = staticValue
1441 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1442 pos.endgame_value_of_piece_on(move_to(move)))
1444 + ei.futilityMargin;
1446 if (futilityValue < alpha)
1448 if (futilityValue > bestValue)
1449 bestValue = futilityValue;
1454 // Don't search captures and checks with negative SEE values
1456 && !move_promotion(move)
1457 && (pos.midgame_value_of_piece_on(move_from(move)) >
1458 pos.midgame_value_of_piece_on(move_to(move)))
1459 && pos.see(move) < 0)
1462 // Make and search the move.
1464 pos.do_move(move, u, dcCandidates);
1465 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1466 pos.undo_move(move, u);
1468 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1471 if (value > bestValue)
1482 // All legal moves have been searched. A special case: If we're in check
1483 // and no legal moves were found, it is checkmate:
1484 if (pos.is_check() && moveCount == 0) // Mate!
1485 return value_mated_in(ply);
1487 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1489 // Update transposition table
1490 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1492 // Update killers only for good check moves
1493 Move m = ss[ply].currentMove;
1494 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1496 // Wrong to update history when depth is <= 0
1497 update_killers(m, ss[ply]);
1503 // sp_search() is used to search from a split point. This function is called
1504 // by each thread working at the split point. It is similar to the normal
1505 // search() function, but simpler. Because we have already probed the hash
1506 // table, done a null move search, and searched the first move before
1507 // splitting, we don't have to repeat all this work in sp_search(). We
1508 // also don't need to store anything to the hash table here: This is taken
1509 // care of after we return from the split point.
1511 void sp_search(SplitPoint *sp, int threadID) {
1513 assert(threadID >= 0 && threadID < ActiveThreads);
1514 assert(ActiveThreads > 1);
1516 Position pos = Position(sp->pos);
1517 SearchStack *ss = sp->sstack[threadID];
1520 bool isCheck = pos.is_check();
1521 bool useFutilityPruning = UseFutilityPruning
1522 && sp->depth < SelectiveDepth
1525 while ( sp->bestValue < sp->beta
1526 && !thread_should_stop(threadID)
1527 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1529 assert(move_is_ok(move));
1531 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1532 bool moveIsCapture = pos.move_is_capture(move);
1534 lock_grab(&(sp->lock));
1535 int moveCount = ++sp->moves;
1536 lock_release(&(sp->lock));
1538 ss[sp->ply].currentMove = move;
1540 // Decide the new search depth.
1542 Depth ext = extension(pos, move, false, moveIsCheck, false, false, &dangerous);
1543 Depth newDepth = sp->depth - OnePly + ext;
1546 if ( useFutilityPruning
1549 && !move_promotion(move)
1550 && moveCount >= 2 + int(sp->depth)
1551 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1554 // Make and search the move.
1556 pos.do_move(move, u, sp->dcCandidates);
1558 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1559 // if the move fails high will be re-searched at full depth.
1561 && moveCount >= LMRNonPVMoves
1563 && !move_promotion(move)
1564 && !move_is_castle(move)
1565 && !move_is_killer(move, ss[sp->ply]))
1567 ss[sp->ply].reduction = OnePly;
1568 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1571 value = sp->beta; // Just to trigger next condition
1573 if (value >= sp->beta) // Go with full depth non-pv search
1575 ss[sp->ply].reduction = Depth(0);
1576 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1578 pos.undo_move(move, u);
1580 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1582 if (thread_should_stop(threadID))
1586 lock_grab(&(sp->lock));
1587 if (value > sp->bestValue && !thread_should_stop(threadID))
1589 sp->bestValue = value;
1590 if (sp->bestValue >= sp->beta)
1592 sp_update_pv(sp->parentSstack, ss, sp->ply);
1593 for (int i = 0; i < ActiveThreads; i++)
1594 if (i != threadID && (i == sp->master || sp->slaves[i]))
1595 Threads[i].stop = true;
1597 sp->finished = true;
1600 lock_release(&(sp->lock));
1603 lock_grab(&(sp->lock));
1605 // If this is the master thread and we have been asked to stop because of
1606 // a beta cutoff higher up in the tree, stop all slave threads:
1607 if (sp->master == threadID && thread_should_stop(threadID))
1608 for (int i = 0; i < ActiveThreads; i++)
1610 Threads[i].stop = true;
1613 sp->slaves[threadID] = 0;
1615 lock_release(&(sp->lock));
1619 // sp_search_pv() is used to search from a PV split point. This function
1620 // is called by each thread working at the split point. It is similar to
1621 // the normal search_pv() function, but simpler. Because we have already
1622 // probed the hash table and searched the first move before splitting, we
1623 // don't have to repeat all this work in sp_search_pv(). We also don't
1624 // need to store anything to the hash table here: This is taken care of
1625 // after we return from the split point.
1627 void sp_search_pv(SplitPoint *sp, int threadID) {
1629 assert(threadID >= 0 && threadID < ActiveThreads);
1630 assert(ActiveThreads > 1);
1632 Position pos = Position(sp->pos);
1633 SearchStack *ss = sp->sstack[threadID];
1637 while ( sp->alpha < sp->beta
1638 && !thread_should_stop(threadID)
1639 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1641 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1642 bool moveIsCapture = pos.move_is_capture(move);
1644 assert(move_is_ok(move));
1646 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1647 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1649 lock_grab(&(sp->lock));
1650 int moveCount = ++sp->moves;
1651 lock_release(&(sp->lock));
1653 ss[sp->ply].currentMove = move;
1655 // Decide the new search depth.
1657 Depth ext = extension(pos, move, true, moveIsCheck, false, false, &dangerous);
1658 Depth newDepth = sp->depth - OnePly + ext;
1660 // Make and search the move.
1662 pos.do_move(move, u, sp->dcCandidates);
1664 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1665 // if the move fails high will be re-searched at full depth.
1667 && moveCount >= LMRPVMoves
1669 && !move_promotion(move)
1670 && !move_is_castle(move)
1671 && !move_is_killer(move, ss[sp->ply]))
1673 ss[sp->ply].reduction = OnePly;
1674 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1677 value = sp->alpha + 1; // Just to trigger next condition
1679 if (value > sp->alpha) // Go with full depth non-pv search
1681 ss[sp->ply].reduction = Depth(0);
1682 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1684 if (value > sp->alpha && value < sp->beta)
1686 // When the search fails high at ply 1 while searching the first
1687 // move at the root, set the flag failHighPly1. This is used for
1688 // time managment: We don't want to stop the search early in
1689 // such cases, because resolving the fail high at ply 1 could
1690 // result in a big drop in score at the root.
1691 if (sp->ply == 1 && RootMoveNumber == 1)
1692 Threads[threadID].failHighPly1 = true;
1694 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1695 Threads[threadID].failHighPly1 = false;
1698 pos.undo_move(move, u);
1700 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1702 if (thread_should_stop(threadID))
1706 lock_grab(&(sp->lock));
1707 if (value > sp->bestValue && !thread_should_stop(threadID))
1709 sp->bestValue = value;
1710 if (value > sp->alpha)
1713 sp_update_pv(sp->parentSstack, ss, sp->ply);
1714 if (value == value_mate_in(sp->ply + 1))
1715 ss[sp->ply].mateKiller = move;
1717 if(value >= sp->beta)
1719 for(int i = 0; i < ActiveThreads; i++)
1720 if(i != threadID && (i == sp->master || sp->slaves[i]))
1721 Threads[i].stop = true;
1723 sp->finished = true;
1726 // If we are at ply 1, and we are searching the first root move at
1727 // ply 0, set the 'Problem' variable if the score has dropped a lot
1728 // (from the computer's point of view) since the previous iteration:
1729 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1732 lock_release(&(sp->lock));
1735 lock_grab(&(sp->lock));
1737 // If this is the master thread and we have been asked to stop because of
1738 // a beta cutoff higher up in the tree, stop all slave threads:
1739 if (sp->master == threadID && thread_should_stop(threadID))
1740 for (int i = 0; i < ActiveThreads; i++)
1742 Threads[i].stop = true;
1745 sp->slaves[threadID] = 0;
1747 lock_release(&(sp->lock));
1751 /// The RootMove class
1755 RootMove::RootMove() {
1756 nodes = cumulativeNodes = 0ULL;
1759 // RootMove::operator<() is the comparison function used when
1760 // sorting the moves. A move m1 is considered to be better
1761 // than a move m2 if it has a higher score, or if the moves
1762 // have equal score but m1 has the higher node count.
1764 bool RootMove::operator<(const RootMove& m) {
1766 if (score != m.score)
1767 return (score < m.score);
1769 return nodes <= m.nodes;
1772 /// The RootMoveList class
1776 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1778 MoveStack mlist[MaxRootMoves];
1779 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1781 // Generate all legal moves
1782 int lm_count = generate_legal_moves(pos, mlist);
1784 // Add each move to the moves[] array
1785 for (int i = 0; i < lm_count; i++)
1787 bool includeMove = includeAllMoves;
1789 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1790 includeMove = (searchMoves[k] == mlist[i].move);
1794 // Find a quick score for the move
1796 SearchStack ss[PLY_MAX_PLUS_2];
1798 moves[count].move = mlist[i].move;
1799 moves[count].nodes = 0ULL;
1800 pos.do_move(moves[count].move, u);
1801 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1803 pos.undo_move(moves[count].move, u);
1804 moves[count].pv[0] = moves[i].move;
1805 moves[count].pv[1] = MOVE_NONE; // FIXME
1813 // Simple accessor methods for the RootMoveList class
1815 inline Move RootMoveList::get_move(int moveNum) const {
1816 return moves[moveNum].move;
1819 inline Value RootMoveList::get_move_score(int moveNum) const {
1820 return moves[moveNum].score;
1823 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1824 moves[moveNum].score = score;
1827 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1828 moves[moveNum].nodes = nodes;
1829 moves[moveNum].cumulativeNodes += nodes;
1832 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1834 for(j = 0; pv[j] != MOVE_NONE; j++)
1835 moves[moveNum].pv[j] = pv[j];
1836 moves[moveNum].pv[j] = MOVE_NONE;
1839 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1840 return moves[moveNum].pv[i];
1843 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1844 return moves[moveNum].cumulativeNodes;
1847 inline int RootMoveList::move_count() const {
1852 // RootMoveList::scan_for_easy_move() is called at the end of the first
1853 // iteration, and is used to detect an "easy move", i.e. a move which appears
1854 // to be much bester than all the rest. If an easy move is found, the move
1855 // is returned, otherwise the function returns MOVE_NONE. It is very
1856 // important that this function is called at the right moment: The code
1857 // assumes that the first iteration has been completed and the moves have
1858 // been sorted. This is done in RootMoveList c'tor.
1860 Move RootMoveList::scan_for_easy_move() const {
1867 // moves are sorted so just consider the best and the second one
1868 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1874 // RootMoveList::sort() sorts the root move list at the beginning of a new
1877 inline void RootMoveList::sort() {
1879 sort_multipv(count - 1); // all items
1883 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1884 // list by their scores and depths. It is used to order the different PVs
1885 // correctly in MultiPV mode.
1887 void RootMoveList::sort_multipv(int n) {
1889 for (int i = 1; i <= n; i++)
1891 RootMove rm = moves[i];
1893 for (j = i; j > 0 && moves[j-1] < rm; j--)
1894 moves[j] = moves[j-1];
1900 // init_search_stack() initializes a search stack at the beginning of a
1901 // new search from the root.
1902 void init_search_stack(SearchStack& ss) {
1904 ss.pv[0] = MOVE_NONE;
1905 ss.pv[1] = MOVE_NONE;
1906 ss.currentMove = MOVE_NONE;
1907 ss.threatMove = MOVE_NONE;
1908 ss.reduction = Depth(0);
1909 for (int j = 0; j < KILLER_MAX; j++)
1910 ss.killers[j] = MOVE_NONE;
1913 void init_search_stack(SearchStack ss[]) {
1915 for (int i = 0; i < 3; i++)
1917 ss[i].pv[i] = MOVE_NONE;
1918 ss[i].pv[i+1] = MOVE_NONE;
1919 ss[i].currentMove = MOVE_NONE;
1920 ss[i].threatMove = MOVE_NONE;
1921 ss[i].reduction = Depth(0);
1922 for (int j = 0; j < KILLER_MAX; j++)
1923 ss[i].killers[j] = MOVE_NONE;
1928 // init_node() is called at the beginning of all the search functions
1929 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1930 // stack object corresponding to the current node. Once every
1931 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1932 // for user input and checks whether it is time to stop the search.
1934 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1935 assert(ply >= 0 && ply < PLY_MAX);
1936 assert(threadID >= 0 && threadID < ActiveThreads);
1938 Threads[threadID].nodes++;
1942 if(NodesSincePoll >= NodesBetweenPolls) {
1947 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1948 ss[ply+2].mateKiller = MOVE_NONE;
1949 ss[ply].threatMove = MOVE_NONE;
1950 ss[ply].reduction = Depth(0);
1951 ss[ply].currentMoveCaptureValue = Value(0);
1952 for (int j = 0; j < KILLER_MAX; j++)
1953 ss[ply+2].killers[j] = MOVE_NONE;
1955 if(Threads[threadID].printCurrentLine)
1956 print_current_line(ss, ply, threadID);
1960 // update_pv() is called whenever a search returns a value > alpha. It
1961 // updates the PV in the SearchStack object corresponding to the current
1964 void update_pv(SearchStack ss[], int ply) {
1965 assert(ply >= 0 && ply < PLY_MAX);
1967 ss[ply].pv[ply] = ss[ply].currentMove;
1969 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1970 ss[ply].pv[p] = ss[ply+1].pv[p];
1971 ss[ply].pv[p] = MOVE_NONE;
1975 // sp_update_pv() is a variant of update_pv for use at split points. The
1976 // difference between the two functions is that sp_update_pv also updates
1977 // the PV at the parent node.
1979 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1980 assert(ply >= 0 && ply < PLY_MAX);
1982 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1984 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1985 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1986 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1990 // connected_moves() tests whether two moves are 'connected' in the sense
1991 // that the first move somehow made the second move possible (for instance
1992 // if the moving piece is the same in both moves). The first move is
1993 // assumed to be the move that was made to reach the current position, while
1994 // the second move is assumed to be a move from the current position.
1996 bool connected_moves(const Position &pos, Move m1, Move m2) {
1997 Square f1, t1, f2, t2;
1999 assert(move_is_ok(m1));
2000 assert(move_is_ok(m2));
2005 // Case 1: The moving piece is the same in both moves.
2011 // Case 2: The destination square for m2 was vacated by m1.
2017 // Case 3: Moving through the vacated square:
2018 if(piece_is_slider(pos.piece_on(f2)) &&
2019 bit_is_set(squares_between(f2, t2), f1))
2022 // Case 4: The destination square for m2 is attacked by the moving piece
2024 if(pos.piece_attacks_square(t1, t2))
2027 // Case 5: Discovered check, checking piece is the piece moved in m1:
2028 if(piece_is_slider(pos.piece_on(t1)) &&
2029 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2031 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2033 Bitboard occ = pos.occupied_squares();
2034 Color us = pos.side_to_move();
2035 Square ksq = pos.king_square(us);
2036 clear_bit(&occ, f2);
2037 if(pos.type_of_piece_on(t1) == BISHOP) {
2038 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2041 else if(pos.type_of_piece_on(t1) == ROOK) {
2042 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2046 assert(pos.type_of_piece_on(t1) == QUEEN);
2047 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2056 // move_is_killer() checks if the given move is among the
2057 // killer moves of that ply.
2059 bool move_is_killer(Move m, const SearchStack& ss) {
2061 const Move* k = ss.killers;
2062 for (int i = 0; i < KILLER_MAX; i++, k++)
2070 // extension() decides whether a move should be searched with normal depth,
2071 // or with extended depth. Certain classes of moves (checking moves, in
2072 // particular) are searched with bigger depth than ordinary moves and in
2073 // any case are marked as 'dangerous'. Note that also if a move is not
2074 // extended, as example because the corresponding UCI option is set to zero,
2075 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2077 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
2078 bool singleReply, bool mateThreat, bool* dangerous) {
2080 Depth result = Depth(0);
2081 *dangerous = check || singleReply || mateThreat;
2084 result += CheckExtension[pvNode];
2087 result += SingleReplyExtension[pvNode];
2090 result += MateThreatExtension[pvNode];
2092 if (pos.move_is_pawn_push_to_7th(m))
2094 result += PawnPushTo7thExtension[pvNode];
2097 if (pos.move_is_passed_pawn_push(m))
2099 result += PassedPawnExtension[pvNode];
2103 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
2104 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2105 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2106 && !move_promotion(m))
2108 result += PawnEndgameExtension[pvNode];
2113 && pos.move_is_capture(m)
2114 && pos.type_of_piece_on(move_to(m)) != PAWN
2121 return Min(result, OnePly);
2125 // ok_to_do_nullmove() looks at the current position and decides whether
2126 // doing a 'null move' should be allowed. In order to avoid zugzwang
2127 // problems, null moves are not allowed when the side to move has very
2128 // little material left. Currently, the test is a bit too simple: Null
2129 // moves are avoided only when the side to move has only pawns left. It's
2130 // probably a good idea to avoid null moves in at least some more
2131 // complicated endgames, e.g. KQ vs KR. FIXME
2133 bool ok_to_do_nullmove(const Position &pos) {
2134 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2140 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2141 // non-tactical moves late in the move list close to the leaves are
2142 // candidates for pruning.
2144 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2145 Square mfrom, mto, tfrom, tto;
2147 assert(move_is_ok(m));
2148 assert(threat == MOVE_NONE || move_is_ok(threat));
2149 assert(!move_promotion(m));
2150 assert(!pos.move_is_check(m));
2151 assert(!pos.move_is_capture(m));
2152 assert(!pos.move_is_passed_pawn_push(m));
2153 assert(d >= OnePly);
2155 mfrom = move_from(m);
2157 tfrom = move_from(threat);
2158 tto = move_to(threat);
2160 // Case 1: Castling moves are never pruned.
2161 if (move_is_castle(m))
2164 // Case 2: Don't prune moves which move the threatened piece
2165 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2168 // Case 3: If the threatened piece has value less than or equal to the
2169 // value of the threatening piece, don't prune move which defend it.
2170 if ( !PruneDefendingMoves
2171 && threat != MOVE_NONE
2172 && pos.type_of_piece_on(tto) != NO_PIECE_TYPE
2173 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2174 || pos.type_of_piece_on(tfrom) == KING)
2175 && pos.move_attacks_square(m, tto))
2178 // Case 4: Don't prune moves with good history.
2179 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2182 // Case 5: If the moving piece in the threatened move is a slider, don't
2183 // prune safe moves which block its ray.
2184 if ( !PruneBlockingMoves
2185 && threat != MOVE_NONE
2186 && piece_is_slider(pos.piece_on(tfrom))
2187 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2194 // ok_to_use_TT() returns true if a transposition table score
2195 // can be used at a given point in search.
2197 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2199 Value v = value_from_tt(tte->value(), ply);
2201 return ( tte->depth() >= depth
2202 || v >= Max(value_mate_in(100), beta)
2203 || v < Min(value_mated_in(100), beta))
2205 && ( (is_lower_bound(tte->type()) && v >= beta)
2206 || (is_upper_bound(tte->type()) && v < beta));
2210 // ok_to_history() returns true if a move m can be stored
2211 // in history. Should be a non capturing move nor a promotion.
2213 bool ok_to_history(const Position& pos, Move m) {
2215 return !pos.move_is_capture(m) && !move_promotion(m);
2219 // update_history() registers a good move that produced a beta-cutoff
2220 // in history and marks as failures all the other moves of that ply.
2222 void update_history(const Position& pos, Move m, Depth depth,
2223 Move movesSearched[], int moveCount) {
2225 H.success(pos.piece_on(move_from(m)), m, depth);
2227 for (int i = 0; i < moveCount - 1; i++)
2229 assert(m != movesSearched[i]);
2230 if (ok_to_history(pos, movesSearched[i]))
2231 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2236 // update_killers() add a good move that produced a beta-cutoff
2237 // among the killer moves of that ply.
2239 void update_killers(Move m, SearchStack& ss) {
2241 if (m == ss.killers[0])
2244 for (int i = KILLER_MAX - 1; i > 0; i--)
2245 ss.killers[i] = ss.killers[i - 1];
2250 // fail_high_ply_1() checks if some thread is currently resolving a fail
2251 // high at ply 1 at the node below the first root node. This information
2252 // is used for time managment.
2254 bool fail_high_ply_1() {
2255 for(int i = 0; i < ActiveThreads; i++)
2256 if(Threads[i].failHighPly1)
2262 // current_search_time() returns the number of milliseconds which have passed
2263 // since the beginning of the current search.
2265 int current_search_time() {
2266 return get_system_time() - SearchStartTime;
2270 // nps() computes the current nodes/second count.
2273 int t = current_search_time();
2274 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2278 // poll() performs two different functions: It polls for user input, and it
2279 // looks at the time consumed so far and decides if it's time to abort the
2284 static int lastInfoTime;
2285 int t = current_search_time();
2290 // We are line oriented, don't read single chars
2291 std::string command;
2292 if (!std::getline(std::cin, command))
2295 if (command == "quit")
2298 PonderSearch = false;
2301 else if(command == "stop")
2304 PonderSearch = false;
2306 else if(command == "ponderhit")
2309 // Print search information
2313 else if (lastInfoTime > t)
2314 // HACK: Must be a new search where we searched less than
2315 // NodesBetweenPolls nodes during the first second of search.
2318 else if (t - lastInfoTime >= 1000)
2325 if (dbg_show_hit_rate)
2326 dbg_print_hit_rate();
2328 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2329 << " time " << t << " hashfull " << TT.full() << std::endl;
2330 lock_release(&IOLock);
2331 if (ShowCurrentLine)
2332 Threads[0].printCurrentLine = true;
2334 // Should we stop the search?
2338 bool overTime = t > AbsoluteMaxSearchTime
2339 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2340 || ( !FailHigh && !fail_high_ply_1() && !Problem
2341 && t > 6*(MaxSearchTime + ExtraSearchTime));
2343 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2344 || (ExactMaxTime && t >= ExactMaxTime)
2345 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2350 // ponderhit() is called when the program is pondering (i.e. thinking while
2351 // it's the opponent's turn to move) in order to let the engine know that
2352 // it correctly predicted the opponent's move.
2355 int t = current_search_time();
2356 PonderSearch = false;
2357 if(Iteration >= 2 &&
2358 (!InfiniteSearch && (StopOnPonderhit ||
2359 t > AbsoluteMaxSearchTime ||
2360 (RootMoveNumber == 1 &&
2361 t > MaxSearchTime + ExtraSearchTime) ||
2362 (!FailHigh && !fail_high_ply_1() && !Problem &&
2363 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2368 // print_current_line() prints the current line of search for a given
2369 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2371 void print_current_line(SearchStack ss[], int ply, int threadID) {
2372 assert(ply >= 0 && ply < PLY_MAX);
2373 assert(threadID >= 0 && threadID < ActiveThreads);
2375 if(!Threads[threadID].idle) {
2377 std::cout << "info currline " << (threadID + 1);
2378 for(int p = 0; p < ply; p++)
2379 std::cout << " " << ss[p].currentMove;
2380 std::cout << std::endl;
2381 lock_release(&IOLock);
2383 Threads[threadID].printCurrentLine = false;
2384 if(threadID + 1 < ActiveThreads)
2385 Threads[threadID + 1].printCurrentLine = true;
2389 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2390 // while the program is pondering. The point is to work around a wrinkle in
2391 // the UCI protocol: When pondering, the engine is not allowed to give a
2392 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2393 // We simply wait here until one of these commands is sent, and return,
2394 // after which the bestmove and pondermove will be printed (in id_loop()).
2396 void wait_for_stop_or_ponderhit() {
2397 std::string command;
2400 if(!std::getline(std::cin, command))
2403 if(command == "quit") {
2404 OpeningBook.close();
2409 else if(command == "ponderhit" || command == "stop")
2415 // idle_loop() is where the threads are parked when they have no work to do.
2416 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2417 // object for which the current thread is the master.
2419 void idle_loop(int threadID, SplitPoint *waitSp) {
2420 assert(threadID >= 0 && threadID < THREAD_MAX);
2422 Threads[threadID].running = true;
2425 if(AllThreadsShouldExit && threadID != 0)
2428 // If we are not thinking, wait for a condition to be signaled instead
2429 // of wasting CPU time polling for work:
2430 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2431 #if !defined(_MSC_VER)
2432 pthread_mutex_lock(&WaitLock);
2433 if(Idle || threadID >= ActiveThreads)
2434 pthread_cond_wait(&WaitCond, &WaitLock);
2435 pthread_mutex_unlock(&WaitLock);
2437 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2441 // If this thread has been assigned work, launch a search:
2442 if(Threads[threadID].workIsWaiting) {
2443 Threads[threadID].workIsWaiting = false;
2444 if(Threads[threadID].splitPoint->pvNode)
2445 sp_search_pv(Threads[threadID].splitPoint, threadID);
2447 sp_search(Threads[threadID].splitPoint, threadID);
2448 Threads[threadID].idle = true;
2451 // If this thread is the master of a split point and all threads have
2452 // finished their work at this split point, return from the idle loop:
2453 if(waitSp != NULL && waitSp->cpus == 0)
2457 Threads[threadID].running = false;
2461 // init_split_point_stack() is called during program initialization, and
2462 // initializes all split point objects.
2464 void init_split_point_stack() {
2465 for(int i = 0; i < THREAD_MAX; i++)
2466 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2467 SplitPointStack[i][j].parent = NULL;
2468 lock_init(&(SplitPointStack[i][j].lock), NULL);
2473 // destroy_split_point_stack() is called when the program exits, and
2474 // destroys all locks in the precomputed split point objects.
2476 void destroy_split_point_stack() {
2477 for(int i = 0; i < THREAD_MAX; i++)
2478 for(int j = 0; j < MaxActiveSplitPoints; j++)
2479 lock_destroy(&(SplitPointStack[i][j].lock));
2483 // thread_should_stop() checks whether the thread with a given threadID has
2484 // been asked to stop, directly or indirectly. This can happen if a beta
2485 // cutoff has occured in thre thread's currently active split point, or in
2486 // some ancestor of the current split point.
2488 bool thread_should_stop(int threadID) {
2489 assert(threadID >= 0 && threadID < ActiveThreads);
2493 if(Threads[threadID].stop)
2495 if(ActiveThreads <= 2)
2497 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2499 Threads[threadID].stop = true;
2506 // thread_is_available() checks whether the thread with threadID "slave" is
2507 // available to help the thread with threadID "master" at a split point. An
2508 // obvious requirement is that "slave" must be idle. With more than two
2509 // threads, this is not by itself sufficient: If "slave" is the master of
2510 // some active split point, it is only available as a slave to the other
2511 // threads which are busy searching the split point at the top of "slave"'s
2512 // split point stack (the "helpful master concept" in YBWC terminology).
2514 bool thread_is_available(int slave, int master) {
2515 assert(slave >= 0 && slave < ActiveThreads);
2516 assert(master >= 0 && master < ActiveThreads);
2517 assert(ActiveThreads > 1);
2519 if(!Threads[slave].idle || slave == master)
2522 if(Threads[slave].activeSplitPoints == 0)
2523 // No active split points means that the thread is available as a slave
2524 // for any other thread.
2527 if(ActiveThreads == 2)
2530 // Apply the "helpful master" concept if possible.
2531 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2538 // idle_thread_exists() tries to find an idle thread which is available as
2539 // a slave for the thread with threadID "master".
2541 bool idle_thread_exists(int master) {
2542 assert(master >= 0 && master < ActiveThreads);
2543 assert(ActiveThreads > 1);
2545 for(int i = 0; i < ActiveThreads; i++)
2546 if(thread_is_available(i, master))
2552 // split() does the actual work of distributing the work at a node between
2553 // several threads at PV nodes. If it does not succeed in splitting the
2554 // node (because no idle threads are available, or because we have no unused
2555 // split point objects), the function immediately returns false. If
2556 // splitting is possible, a SplitPoint object is initialized with all the
2557 // data that must be copied to the helper threads (the current position and
2558 // search stack, alpha, beta, the search depth, etc.), and we tell our
2559 // helper threads that they have been assigned work. This will cause them
2560 // to instantly leave their idle loops and call sp_search_pv(). When all
2561 // threads have returned from sp_search_pv (or, equivalently, when
2562 // splitPoint->cpus becomes 0), split() returns true.
2564 bool split(const Position &p, SearchStack *sstck, int ply,
2565 Value *alpha, Value *beta, Value *bestValue,
2566 Depth depth, int *moves,
2567 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2569 assert(sstck != NULL);
2570 assert(ply >= 0 && ply < PLY_MAX);
2571 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2572 assert(!pvNode || *alpha < *beta);
2573 assert(*beta <= VALUE_INFINITE);
2574 assert(depth > Depth(0));
2575 assert(master >= 0 && master < ActiveThreads);
2576 assert(ActiveThreads > 1);
2578 SplitPoint *splitPoint;
2583 // If no other thread is available to help us, or if we have too many
2584 // active split points, don't split:
2585 if(!idle_thread_exists(master) ||
2586 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2587 lock_release(&MPLock);
2591 // Pick the next available split point object from the split point stack:
2592 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2593 Threads[master].activeSplitPoints++;
2595 // Initialize the split point object:
2596 splitPoint->parent = Threads[master].splitPoint;
2597 splitPoint->finished = false;
2598 splitPoint->ply = ply;
2599 splitPoint->depth = depth;
2600 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2601 splitPoint->beta = *beta;
2602 splitPoint->pvNode = pvNode;
2603 splitPoint->dcCandidates = dcCandidates;
2604 splitPoint->bestValue = *bestValue;
2605 splitPoint->master = master;
2606 splitPoint->mp = mp;
2607 splitPoint->moves = *moves;
2608 splitPoint->cpus = 1;
2609 splitPoint->pos.copy(p);
2610 splitPoint->parentSstack = sstck;
2611 for(i = 0; i < ActiveThreads; i++)
2612 splitPoint->slaves[i] = 0;
2614 // Copy the current position and the search stack to the master thread:
2615 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2616 Threads[master].splitPoint = splitPoint;
2618 // Make copies of the current position and search stack for each thread:
2619 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2621 if(thread_is_available(i, master)) {
2622 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2623 Threads[i].splitPoint = splitPoint;
2624 splitPoint->slaves[i] = 1;
2628 // Tell the threads that they have work to do. This will make them leave
2630 for(i = 0; i < ActiveThreads; i++)
2631 if(i == master || splitPoint->slaves[i]) {
2632 Threads[i].workIsWaiting = true;
2633 Threads[i].idle = false;
2634 Threads[i].stop = false;
2637 lock_release(&MPLock);
2639 // Everything is set up. The master thread enters the idle loop, from
2640 // which it will instantly launch a search, because its workIsWaiting
2641 // slot is 'true'. We send the split point as a second parameter to the
2642 // idle loop, which means that the main thread will return from the idle
2643 // loop when all threads have finished their work at this split point
2644 // (i.e. when // splitPoint->cpus == 0).
2645 idle_loop(master, splitPoint);
2647 // We have returned from the idle loop, which means that all threads are
2648 // finished. Update alpha, beta and bestvalue, and return:
2650 if(pvNode) *alpha = splitPoint->alpha;
2651 *beta = splitPoint->beta;
2652 *bestValue = splitPoint->bestValue;
2653 Threads[master].stop = false;
2654 Threads[master].idle = false;
2655 Threads[master].activeSplitPoints--;
2656 Threads[master].splitPoint = splitPoint->parent;
2657 lock_release(&MPLock);
2663 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2664 // to start a new search from the root.
2666 void wake_sleeping_threads() {
2667 if(ActiveThreads > 1) {
2668 for(int i = 1; i < ActiveThreads; i++) {
2669 Threads[i].idle = true;
2670 Threads[i].workIsWaiting = false;
2672 #if !defined(_MSC_VER)
2673 pthread_mutex_lock(&WaitLock);
2674 pthread_cond_broadcast(&WaitCond);
2675 pthread_mutex_unlock(&WaitLock);
2677 for(int i = 1; i < THREAD_MAX; i++)
2678 SetEvent(SitIdleEvent[i]);
2684 // init_thread() is the function which is called when a new thread is
2685 // launched. It simply calls the idle_loop() function with the supplied
2686 // threadID. There are two versions of this function; one for POSIX threads
2687 // and one for Windows threads.
2689 #if !defined(_MSC_VER)
2691 void *init_thread(void *threadID) {
2692 idle_loop(*(int *)threadID, NULL);
2698 DWORD WINAPI init_thread(LPVOID threadID) {
2699 idle_loop(*(int *)threadID, NULL);