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;
177 // Iteration counter:
180 // Scores and number of times the best move changed for each iteration:
181 Value ValueByIteration[PLY_MAX_PLUS_2];
182 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
187 // Time managment variables
189 int MaxNodes, MaxDepth;
190 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
191 Move BestRootMove, PonderMove, EasyMove;
195 bool StopOnPonderhit;
200 bool PonderingEnabled;
203 // Show current line?
204 bool ShowCurrentLine = false;
207 bool UseLogFile = false;
208 std::ofstream LogFile;
210 // MP related variables
211 Depth MinimumSplitDepth = 4*OnePly;
212 int MaxThreadsPerSplitPoint = 4;
213 Thread Threads[THREAD_MAX];
215 bool AllThreadsShouldExit = false;
216 const int MaxActiveSplitPoints = 8;
217 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
220 #if !defined(_MSC_VER)
221 pthread_cond_t WaitCond;
222 pthread_mutex_t WaitLock;
224 HANDLE SitIdleEvent[THREAD_MAX];
230 Value id_loop(const Position &pos, Move searchMoves[]);
231 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
232 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
233 Depth depth, int ply, int threadID);
234 Value search(Position &pos, SearchStack ss[], Value beta,
235 Depth depth, int ply, bool allowNullmove, int threadID);
236 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
237 Depth depth, int ply, int threadID);
238 void sp_search(SplitPoint *sp, int threadID);
239 void sp_search_pv(SplitPoint *sp, int threadID);
240 void init_search_stack(SearchStack ss[]);
241 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
242 void update_pv(SearchStack ss[], int ply);
243 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
244 bool connected_moves(const Position &pos, Move m1, Move m2);
245 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
246 bool singleReply, bool mateThreat);
247 bool ok_to_do_nullmove(const Position &pos);
248 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
249 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
250 bool ok_to_history(const Position &pos, Move m);
251 void update_history(const Position& pos, Move m, Depth depth,
252 Move movesSearched[], int moveCount);
254 bool fail_high_ply_1();
255 int current_search_time();
259 void print_current_line(SearchStack ss[], int ply, int threadID);
260 void wait_for_stop_or_ponderhit();
262 void idle_loop(int threadID, SplitPoint *waitSp);
263 void init_split_point_stack();
264 void destroy_split_point_stack();
265 bool thread_should_stop(int threadID);
266 bool thread_is_available(int slave, int master);
267 bool idle_thread_exists(int master);
268 bool split(const Position &pos, SearchStack *ss, int ply,
269 Value *alpha, Value *beta, Value *bestValue, Depth depth,
270 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
272 void wake_sleeping_threads();
274 #if !defined(_MSC_VER)
275 void *init_thread(void *threadID);
277 DWORD WINAPI init_thread(LPVOID threadID);
284 //// Global variables
287 // The main transposition table
288 TranspositionTable TT = TranspositionTable(TTDefaultSize);
291 // Number of active threads:
292 int ActiveThreads = 1;
294 // Locks. In principle, there is no need for IOLock to be a global variable,
295 // but it could turn out to be useful for debugging.
298 History H; // Should be made local?
305 /// think() is the external interface to Stockfish's search, and is called when
306 /// the program receives the UCI 'go' command. It initializes various
307 /// search-related global variables, and calls root_search()
309 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
310 int time[], int increment[], int movesToGo, int maxDepth,
311 int maxNodes, int maxTime, Move searchMoves[]) {
313 // Look for a book move
314 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
317 if (get_option_value_string("Book File") != OpeningBook.file_name())
320 OpeningBook.open("book.bin");
322 bookMove = OpeningBook.get_move(pos);
323 if (bookMove != MOVE_NONE)
325 std::cout << "bestmove " << bookMove << std::endl;
330 // Initialize global search variables
332 SearchStartTime = get_system_time();
333 BestRootMove = MOVE_NONE;
334 PonderMove = MOVE_NONE;
335 EasyMove = MOVE_NONE;
336 for (int i = 0; i < THREAD_MAX; i++)
338 Threads[i].nodes = 0ULL;
339 Threads[i].failHighPly1 = false;
342 InfiniteSearch = infinite;
343 PonderSearch = ponder;
344 StopOnPonderhit = false;
349 ExactMaxTime = maxTime;
351 // Read UCI option values
352 TT.set_size(get_option_value_int("Hash"));
353 if (button_was_pressed("Clear Hash"))
356 PonderingEnabled = get_option_value_bool("Ponder");
357 MultiPV = get_option_value_int("MultiPV");
359 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
360 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
362 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
363 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
365 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
366 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
368 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
369 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
371 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
372 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
374 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
375 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
377 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
378 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
379 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
380 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
382 Chess960 = get_option_value_bool("UCI_Chess960");
383 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
384 UseLogFile = get_option_value_bool("Use Search Log");
386 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
388 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
389 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
391 FutilityMargin0 = value_from_centipawns(get_option_value_int("Futility Margin 0"));
392 FutilityMargin1 = value_from_centipawns(get_option_value_int("Futility Margin 1"));
393 FutilityMargin2 = value_from_centipawns(get_option_value_int("Futility Margin 2"));
395 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
396 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
398 UseLSNFiltering = get_option_value_bool("LSN filtering");
399 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
400 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
402 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
403 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
405 read_weights(pos.side_to_move());
407 int newActiveThreads = get_option_value_int("Threads");
408 if (newActiveThreads != ActiveThreads)
410 ActiveThreads = newActiveThreads;
411 init_eval(ActiveThreads);
414 // Wake up sleeping threads:
415 wake_sleeping_threads();
417 for (int i = 1; i < ActiveThreads; i++)
418 assert(thread_is_available(i, 0));
420 // Set thinking time:
421 int myTime = time[side_to_move];
422 int myIncrement = increment[side_to_move];
423 int oppTime = time[1 - side_to_move];
425 TimeAdvantage = myTime - oppTime;
427 if (!movesToGo) // Sudden death time control
431 MaxSearchTime = myTime / 30 + myIncrement;
432 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
433 } else { // Blitz game without increment
434 MaxSearchTime = myTime / 40;
435 AbsoluteMaxSearchTime = myTime / 8;
438 else // (x moves) / (y minutes)
442 MaxSearchTime = myTime / 2;
443 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
445 MaxSearchTime = myTime / Min(movesToGo, 20);
446 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
450 if (PonderingEnabled)
452 MaxSearchTime += MaxSearchTime / 4;
453 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
456 // Fixed depth or fixed number of nodes?
459 InfiniteSearch = true; // HACK
464 NodesBetweenPolls = Min(MaxNodes, 30000);
465 InfiniteSearch = true; // HACK
468 NodesBetweenPolls = 30000;
471 // Write information to search log file:
473 LogFile << "Searching: " << pos.to_fen() << std::endl
474 << "infinite: " << infinite
475 << " ponder: " << ponder
476 << " time: " << myTime
477 << " increment: " << myIncrement
478 << " moves to go: " << movesToGo << std::endl;
481 // We're ready to start thinking. Call the iterative deepening loop
485 Value v = id_loop(pos, searchMoves);
486 looseOnTime = ( UseLSNFiltering
493 looseOnTime = false; // reset for next match
494 while (SearchStartTime + myTime + 1000 > get_system_time())
496 id_loop(pos, searchMoves); // to fail gracefully
513 /// init_threads() is called during startup. It launches all helper threads,
514 /// and initializes the split point stack and the global locks and condition
517 void init_threads() {
521 #if !defined(_MSC_VER)
522 pthread_t pthread[1];
525 for (i = 0; i < THREAD_MAX; i++)
526 Threads[i].activeSplitPoints = 0;
528 // Initialize global locks:
529 lock_init(&MPLock, NULL);
530 lock_init(&IOLock, NULL);
532 init_split_point_stack();
534 #if !defined(_MSC_VER)
535 pthread_mutex_init(&WaitLock, NULL);
536 pthread_cond_init(&WaitCond, NULL);
538 for (i = 0; i < THREAD_MAX; i++)
539 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
542 // All threads except the main thread should be initialized to idle state
543 for (i = 1; i < THREAD_MAX; i++)
545 Threads[i].stop = false;
546 Threads[i].workIsWaiting = false;
547 Threads[i].idle = true;
548 Threads[i].running = false;
551 // Launch the helper threads
552 for(i = 1; i < THREAD_MAX; i++)
554 #if !defined(_MSC_VER)
555 pthread_create(pthread, NULL, init_thread, (void*)(&i));
558 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
561 // Wait until the thread has finished launching:
562 while (!Threads[i].running);
567 /// stop_threads() is called when the program exits. It makes all the
568 /// helper threads exit cleanly.
570 void stop_threads() {
572 ActiveThreads = THREAD_MAX; // HACK
573 Idle = false; // HACK
574 wake_sleeping_threads();
575 AllThreadsShouldExit = true;
576 for (int i = 1; i < THREAD_MAX; i++)
578 Threads[i].stop = true;
579 while(Threads[i].running);
581 destroy_split_point_stack();
585 /// nodes_searched() returns the total number of nodes searched so far in
586 /// the current search.
588 int64_t nodes_searched() {
590 int64_t result = 0ULL;
591 for (int i = 0; i < ActiveThreads; i++)
592 result += Threads[i].nodes;
599 // id_loop() is the main iterative deepening loop. It calls root_search
600 // repeatedly with increasing depth until the allocated thinking time has
601 // been consumed, the user stops the search, or the maximum search depth is
604 Value id_loop(const Position &pos, Move searchMoves[]) {
607 SearchStack ss[PLY_MAX_PLUS_2];
609 // searchMoves are verified, copied, scored and sorted
610 RootMoveList rml(p, searchMoves);
615 init_search_stack(ss);
617 ValueByIteration[0] = Value(0);
618 ValueByIteration[1] = rml.get_move_score(0);
621 EasyMove = rml.scan_for_easy_move();
623 // Iterative deepening loop
624 while (!AbortSearch && Iteration < PLY_MAX)
626 // Initialize iteration
629 BestMoveChangesByIteration[Iteration] = 0;
633 std::cout << "info depth " << Iteration << std::endl;
635 // Search to the current depth
636 ValueByIteration[Iteration] = root_search(p, ss, rml);
638 // Erase the easy move if it differs from the new best move
639 if (ss[0].pv[0] != EasyMove)
640 EasyMove = MOVE_NONE;
647 bool stopSearch = false;
649 // Stop search early if there is only a single legal move:
650 if (Iteration >= 6 && rml.move_count() == 1)
653 // Stop search early when the last two iterations returned a mate score
655 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
656 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
659 // Stop search early if one move seems to be much better than the rest
660 int64_t nodes = nodes_searched();
662 && EasyMove == ss[0].pv[0]
663 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
664 && current_search_time() > MaxSearchTime / 16)
665 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
666 && current_search_time() > MaxSearchTime / 32)))
669 // Add some extra time if the best move has changed during the last two iterations
670 if (Iteration > 5 && Iteration <= 50)
671 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
672 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
674 // If we need some more and we are in time advantage take it
675 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
676 ExtraSearchTime += MaxSearchTime / 2;
678 // Stop search if most of MaxSearchTime is consumed at the end of the
679 // iteration. We probably don't have enough time to search the first
680 // move at the next iteration anyway.
681 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
689 StopOnPonderhit = true;
692 // Write PV to transposition table, in case the relevant entries have
693 // been overwritten during the search:
694 TT.insert_pv(p, ss[0].pv);
696 if (MaxDepth && Iteration >= MaxDepth)
702 // If we are pondering, we shouldn't print the best move before we
705 wait_for_stop_or_ponderhit();
707 // Print final search statistics
708 std::cout << "info nodes " << nodes_searched()
710 << " time " << current_search_time()
711 << " hashfull " << TT.full() << std::endl;
713 // Print the best move and the ponder move to the standard output
714 std::cout << "bestmove " << ss[0].pv[0];
715 if (ss[0].pv[1] != MOVE_NONE)
716 std::cout << " ponder " << ss[0].pv[1];
718 std::cout << std::endl;
723 LogFile << "Nodes: " << nodes_searched() << std::endl
724 << "Nodes/second: " << nps() << std::endl
725 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
727 p.do_move(ss[0].pv[0], u);
728 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
729 << std::endl << std::endl;
731 return rml.get_move_score(0);
735 // root_search() is the function which searches the root node. It is
736 // similar to search_pv except that it uses a different move ordering
737 // scheme (perhaps we should try to use this at internal PV nodes, too?)
738 // and prints some information to the standard output.
740 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
742 Value alpha = -VALUE_INFINITE;
743 Value beta = VALUE_INFINITE, value;
744 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
746 // Loop through all the moves in the root move list
747 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
754 RootMoveNumber = i + 1;
757 // Remember the node count before the move is searched. The node counts
758 // are used to sort the root moves at the next iteration.
759 nodes = nodes_searched();
761 // Pick the next root move, and print the move and the move number to
762 // the standard output.
763 move = ss[0].currentMove = rml.get_move(i);
764 if (current_search_time() >= 1000)
765 std::cout << "info currmove " << move
766 << " currmovenumber " << i + 1 << std::endl;
768 // Decide search depth for this move
769 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
770 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
772 // Make the move, and search it
773 pos.do_move(move, u, dcCandidates);
777 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
778 // If the value has dropped a lot compared to the last iteration,
779 // set the boolean variable Problem to true. This variable is used
780 // for time managment: When Problem is true, we try to complete the
781 // current iteration before playing a move.
782 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
784 if (Problem && StopOnPonderhit)
785 StopOnPonderhit = false;
789 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
792 // Fail high! Set the boolean variable FailHigh to true, and
793 // re-search the move with a big window. The variable FailHigh is
794 // used for time managment: We try to avoid aborting the search
795 // prematurely during a fail high research.
797 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
801 pos.undo_move(move, u);
803 // Finished searching the move. If AbortSearch is true, the search
804 // was aborted because the user interrupted the search or because we
805 // ran out of time. In this case, the return value of the search cannot
806 // be trusted, and we break out of the loop without updating the best
811 // Remember the node count for this move. The node counts are used to
812 // sort the root moves at the next iteration.
813 rml.set_move_nodes(i, nodes_searched() - nodes);
815 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
817 if (value <= alpha && i >= MultiPV)
818 rml.set_move_score(i, -VALUE_INFINITE);
824 rml.set_move_score(i, value);
826 rml.set_move_pv(i, ss[0].pv);
830 // We record how often the best move has been changed in each
831 // iteration. This information is used for time managment: When
832 // the best move changes frequently, we allocate some more time.
834 BestMoveChangesByIteration[Iteration]++;
836 // Print search information to the standard output:
837 std::cout << "info depth " << Iteration
838 << " score " << value_to_string(value)
839 << " time " << current_search_time()
840 << " nodes " << nodes_searched()
844 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
845 std::cout << ss[0].pv[j] << " ";
847 std::cout << std::endl;
850 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
855 // Reset the global variable Problem to false if the value isn't too
856 // far below the final value from the last iteration.
857 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
863 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
866 std::cout << "info multipv " << j + 1
867 << " score " << value_to_string(rml.get_move_score(j))
868 << " depth " << ((j <= i)? Iteration : Iteration - 1)
869 << " time " << current_search_time()
870 << " nodes " << nodes_searched()
874 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
875 std::cout << rml.get_move_pv(j, k) << " ";
877 std::cout << std::endl;
879 alpha = rml.get_move_score(Min(i, MultiPV-1));
887 // search_pv() is the main search function for PV nodes.
889 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
890 Depth depth, int ply, int threadID) {
892 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
893 assert(beta > alpha && beta <= VALUE_INFINITE);
894 assert(ply >= 0 && ply < PLY_MAX);
895 assert(threadID >= 0 && threadID < ActiveThreads);
897 // Initialize, and make an early exit in case of an aborted search,
898 // an instant draw, maximum ply reached, etc.
899 if (AbortSearch || thread_should_stop(threadID))
903 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
905 init_node(pos, ss, ply, threadID);
912 if (ply >= PLY_MAX - 1)
913 return evaluate(pos, ei, threadID);
915 // Mate distance pruning
916 Value oldAlpha = alpha;
917 alpha = Max(value_mated_in(ply), alpha);
918 beta = Min(value_mate_in(ply+1), beta);
922 // Transposition table lookup. At PV nodes, we don't use the TT for
923 // pruning, but only for move ordering.
924 const TTEntry* tte = TT.retrieve(pos);
925 Move ttMove = (tte ? tte->move() : MOVE_NONE);
927 // Go with internal iterative deepening if we don't have a TT move
928 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
930 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
931 ttMove = ss[ply].pv[ply];
934 // Initialize a MovePicker object for the current position, and prepare
935 // to search all moves
936 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
937 ss[ply].killer1, ss[ply].killer2, depth);
939 Move move, movesSearched[256];
941 Value value, bestValue = -VALUE_INFINITE;
942 Bitboard dcCandidates = mp.discovered_check_candidates();
943 bool isCheck = pos.is_check();
944 bool mateThreat = MateThreatExtension[1] > Depth(0)
945 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
947 // Loop through all legal moves until no moves remain or a beta cutoff
950 && (move = mp.get_next_move()) != MOVE_NONE
951 && !thread_should_stop(threadID))
953 assert(move_is_ok(move));
955 bool singleReply = (isCheck && mp.number_of_moves() == 1);
956 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
957 bool moveIsCapture = pos.move_is_capture(move);
958 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
960 movesSearched[moveCount++] = ss[ply].currentMove = move;
963 ss[ply].currentMoveCaptureValue = pos.midgame_value_of_piece_on(move_to(move));
964 else if (move_is_ep(move))
965 ss[ply].currentMoveCaptureValue = PawnValueMidgame;
967 ss[ply].currentMoveCaptureValue = Value(0);
969 // Decide the new search depth
970 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
971 Depth newDepth = depth - OnePly + ext;
973 // Make and search the move
975 pos.do_move(move, u, dcCandidates);
977 if (moveCount == 1) // The first move in list is the PV
978 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
981 // Try to reduce non-pv search depth by one ply if move seems not problematic,
982 // if the move fails high will be re-searched at full depth.
983 if ( depth >= 2*OnePly
985 && moveCount >= LMRPVMoves
987 && !move_promotion(move)
988 && !moveIsPassedPawnPush
989 && !move_is_castle(move)
990 && move != ss[ply].killer1
991 && move != ss[ply].killer2)
993 ss[ply].reduction = OnePly;
994 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
997 value = alpha + 1; // Just to trigger next condition
999 if (value > alpha) // Go with full depth pv search
1001 ss[ply].reduction = Depth(0);
1002 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1003 if (value > alpha && value < beta)
1005 // When the search fails high at ply 1 while searching the first
1006 // move at the root, set the flag failHighPly1. This is used for
1007 // time managment: We don't want to stop the search early in
1008 // such cases, because resolving the fail high at ply 1 could
1009 // result in a big drop in score at the root.
1010 if (ply == 1 && RootMoveNumber == 1)
1011 Threads[threadID].failHighPly1 = true;
1013 // A fail high occurred. Re-search at full window (pv search)
1014 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1015 Threads[threadID].failHighPly1 = false;
1019 pos.undo_move(move, u);
1021 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1024 if (value > bestValue)
1031 if (value == value_mate_in(ply + 1))
1032 ss[ply].mateKiller = move;
1034 // If we are at ply 1, and we are searching the first root move at
1035 // ply 0, set the 'Problem' variable if the score has dropped a lot
1036 // (from the computer's point of view) since the previous iteration:
1037 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1042 if ( ActiveThreads > 1
1044 && depth >= MinimumSplitDepth
1046 && idle_thread_exists(threadID)
1048 && !thread_should_stop(threadID)
1049 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1050 &moveCount, &mp, dcCandidates, threadID, true))
1054 // All legal moves have been searched. A special case: If there were
1055 // no legal moves, it must be mate or stalemate:
1057 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1059 // If the search is not aborted, update the transposition table,
1060 // history counters, and killer moves.
1061 if (AbortSearch || thread_should_stop(threadID))
1064 if (bestValue <= oldAlpha)
1065 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1067 else if (bestValue >= beta)
1069 Move m = ss[ply].pv[ply];
1070 if (ok_to_history(pos, m)) // Only non capture moves are considered
1072 update_history(pos, m, depth, movesSearched, moveCount);
1073 if (m != ss[ply].killer1)
1075 ss[ply].killer2 = ss[ply].killer1;
1076 ss[ply].killer1 = m;
1079 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1082 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1088 // search() is the search function for zero-width nodes.
1090 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1091 int ply, bool allowNullmove, int threadID) {
1093 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1094 assert(ply >= 0 && ply < PLY_MAX);
1095 assert(threadID >= 0 && threadID < ActiveThreads);
1099 // Initialize, and make an early exit in case of an aborted search,
1100 // an instant draw, maximum ply reached, etc.
1101 if (AbortSearch || thread_should_stop(threadID))
1105 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1107 init_node(pos, ss, ply, threadID);
1112 if (ply >= PLY_MAX - 1)
1113 return evaluate(pos, ei, threadID);
1115 // Mate distance pruning
1116 if (value_mated_in(ply) >= beta)
1119 if (value_mate_in(ply + 1) < beta)
1122 // Transposition table lookup
1123 const TTEntry* tte = TT.retrieve(pos);
1124 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1126 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1128 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1129 return value_from_tt(tte->value(), ply);
1132 Value approximateEval = quick_evaluate(pos);
1133 bool mateThreat = false;
1134 bool isCheck = pos.is_check();
1139 && ok_to_do_nullmove(pos)
1140 && approximateEval >= beta - NullMoveMargin)
1142 ss[ply].currentMove = MOVE_NULL;
1145 pos.do_null_move(u);
1146 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1147 pos.undo_null_move(u);
1149 if (nullValue >= beta)
1151 if (depth < 6 * OnePly)
1154 // Do zugzwang verification search
1155 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1159 // The null move failed low, which means that we may be faced with
1160 // some kind of threat. If the previous move was reduced, check if
1161 // the move that refuted the null move was somehow connected to the
1162 // move which was reduced. If a connection is found, return a fail
1163 // low score (which will cause the reduced move to fail high in the
1164 // parent node, which will trigger a re-search with full depth).
1165 if (nullValue == value_mated_in(ply + 2))
1168 ss[ply].threatMove = ss[ply + 1].currentMove;
1169 if ( depth < ThreatDepth
1170 && ss[ply - 1].reduction
1171 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1175 // Null move search not allowed, try razoring
1176 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1177 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1179 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1184 // Go with internal iterative deepening if we don't have a TT move
1185 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1186 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1188 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1189 ttMove = ss[ply].pv[ply];
1192 // Initialize a MovePicker object for the current position, and prepare
1193 // to search all moves:
1194 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1195 ss[ply].killer1, ss[ply].killer2, depth);
1197 Move move, movesSearched[256];
1199 Value value, bestValue = -VALUE_INFINITE;
1200 Bitboard dcCandidates = mp.discovered_check_candidates();
1201 Value futilityValue = VALUE_NONE;
1202 bool useFutilityPruning = UseFutilityPruning
1203 && depth < SelectiveDepth
1206 // Loop through all legal moves until no moves remain or a beta cutoff
1208 while ( bestValue < beta
1209 && (move = mp.get_next_move()) != MOVE_NONE
1210 && !thread_should_stop(threadID))
1212 assert(move_is_ok(move));
1214 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1215 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1216 bool moveIsCapture = pos.move_is_capture(move);
1217 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1219 movesSearched[moveCount++] = ss[ply].currentMove = move;
1221 // Decide the new search depth
1222 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1223 Depth newDepth = depth - OnePly + ext;
1226 if ( useFutilityPruning
1229 && !moveIsPassedPawnPush
1230 && !move_promotion(move))
1232 if ( moveCount >= 2 + int(depth)
1233 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1236 if (depth < 3 * OnePly && approximateEval < beta)
1238 if (futilityValue == VALUE_NONE)
1239 futilityValue = evaluate(pos, ei, threadID)
1240 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1242 if (futilityValue < beta)
1244 if (futilityValue > bestValue)
1245 bestValue = futilityValue;
1251 // Make and search the move
1253 pos.do_move(move, u, dcCandidates);
1255 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1256 // if the move fails high will be re-searched at full depth.
1257 if ( depth >= 2*OnePly
1259 && moveCount >= LMRNonPVMoves
1261 && !move_promotion(move)
1262 && !moveIsPassedPawnPush
1263 && !move_is_castle(move)
1264 && move != ss[ply].killer1
1265 && move != ss[ply].killer2)
1267 ss[ply].reduction = OnePly;
1268 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1271 value = beta; // Just to trigger next condition
1273 if (value >= beta) // Go with full depth non-pv search
1275 ss[ply].reduction = Depth(0);
1276 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1278 pos.undo_move(move, u);
1280 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1283 if (value > bestValue)
1289 if (value == value_mate_in(ply + 1))
1290 ss[ply].mateKiller = move;
1294 if ( ActiveThreads > 1
1296 && depth >= MinimumSplitDepth
1298 && idle_thread_exists(threadID)
1300 && !thread_should_stop(threadID)
1301 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1302 &mp, dcCandidates, threadID, false))
1306 // All legal moves have been searched. A special case: If there were
1307 // no legal moves, it must be mate or stalemate.
1309 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1311 // If the search is not aborted, update the transposition table,
1312 // history counters, and killer moves.
1313 if (AbortSearch || thread_should_stop(threadID))
1316 if (bestValue < beta)
1317 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1320 Move m = ss[ply].pv[ply];
1321 if (ok_to_history(pos, m)) // Only non capture moves are considered
1323 update_history(pos, m, depth, movesSearched, moveCount);
1324 if (m != ss[ply].killer1)
1326 ss[ply].killer2 = ss[ply].killer1;
1327 ss[ply].killer1 = m;
1330 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1336 // qsearch() is the quiescence search function, which is called by the main
1337 // search function when the remaining depth is zero (or, to be more precise,
1338 // less than OnePly).
1340 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1341 Depth depth, int ply, int threadID) {
1343 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1344 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1346 assert(ply >= 0 && ply < PLY_MAX);
1347 assert(threadID >= 0 && threadID < ActiveThreads);
1351 // Initialize, and make an early exit in case of an aborted search,
1352 // an instant draw, maximum ply reached, etc.
1353 if (AbortSearch || thread_should_stop(threadID))
1356 init_node(pos, ss, ply, threadID);
1361 // Transposition table lookup
1362 const TTEntry* tte = TT.retrieve(pos);
1363 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1364 return value_from_tt(tte->value(), ply);
1366 // Evaluate the position statically
1367 Value staticValue = evaluate(pos, ei, threadID);
1369 if (ply == PLY_MAX - 1)
1372 // Initialize "stand pat score", and return it immediately if it is
1374 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1376 if (bestValue >= beta)
1379 if (bestValue > alpha)
1382 // Initialize a MovePicker object for the current position, and prepare
1383 // to search the moves. Because the depth is <= 0 here, only captures,
1384 // queen promotions and checks (only if depth == 0) will be generated.
1385 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1389 Bitboard dcCandidates = mp.discovered_check_candidates();
1390 bool isCheck = pos.is_check();
1392 // Loop through the moves until no moves remain or a beta cutoff
1394 while ( alpha < beta
1395 && (move = mp.get_next_move()) != MOVE_NONE)
1397 assert(move_is_ok(move));
1399 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1400 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1403 ss[ply].currentMove = move;
1406 if ( UseQSearchFutilityPruning
1409 && !move_promotion(move)
1410 && !moveIsPassedPawnPush
1411 && beta - alpha == 1
1412 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1414 Value futilityValue = staticValue
1415 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1416 pos.endgame_value_of_piece_on(move_to(move)))
1418 + ei.futilityMargin;
1420 if (futilityValue < alpha)
1422 if (futilityValue > bestValue)
1423 bestValue = futilityValue;
1428 // Don't search captures and checks with negative SEE values.
1430 && !move_promotion(move)
1431 && (pos.midgame_value_of_piece_on(move_from(move)) >
1432 pos.midgame_value_of_piece_on(move_to(move)))
1433 && pos.see(move) < 0)
1436 // Make and search the move.
1438 pos.do_move(move, u, dcCandidates);
1439 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1440 pos.undo_move(move, u);
1442 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1445 if (value > bestValue)
1456 // All legal moves have been searched. A special case: If we're in check
1457 // and no legal moves were found, it is checkmate:
1458 if (pos.is_check() && moveCount == 0) // Mate!
1459 return value_mated_in(ply);
1461 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1463 // Update transposition table
1464 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1470 // sp_search() is used to search from a split point. This function is called
1471 // by each thread working at the split point. It is similar to the normal
1472 // search() function, but simpler. Because we have already probed the hash
1473 // table, done a null move search, and searched the first move before
1474 // splitting, we don't have to repeat all this work in sp_search(). We
1475 // also don't need to store anything to the hash table here: This is taken
1476 // care of after we return from the split point.
1478 void sp_search(SplitPoint *sp, int threadID) {
1480 assert(threadID >= 0 && threadID < ActiveThreads);
1481 assert(ActiveThreads > 1);
1483 Position pos = Position(sp->pos);
1484 SearchStack *ss = sp->sstack[threadID];
1487 bool isCheck = pos.is_check();
1488 bool useFutilityPruning = UseFutilityPruning
1489 && sp->depth < SelectiveDepth
1492 while ( sp->bestValue < sp->beta
1493 && !thread_should_stop(threadID)
1494 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1496 assert(move_is_ok(move));
1498 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1499 bool moveIsCapture = pos.move_is_capture(move);
1500 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1502 lock_grab(&(sp->lock));
1503 int moveCount = ++sp->moves;
1504 lock_release(&(sp->lock));
1506 ss[sp->ply].currentMove = move;
1508 // Decide the new search depth.
1509 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1510 Depth newDepth = sp->depth - OnePly + ext;
1513 if ( useFutilityPruning
1516 && !moveIsPassedPawnPush
1517 && !move_promotion(move)
1518 && moveCount >= 2 + int(sp->depth)
1519 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1522 // Make and search the move.
1524 pos.do_move(move, u, sp->dcCandidates);
1526 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1527 // if the move fails high will be re-searched at full depth.
1528 if ( ext == Depth(0)
1529 && moveCount >= LMRNonPVMoves
1531 && !moveIsPassedPawnPush
1532 && !move_promotion(move)
1533 && !move_is_castle(move)
1534 && move != ss[sp->ply].killer1
1535 && move != ss[sp->ply].killer2)
1537 ss[sp->ply].reduction = OnePly;
1538 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1541 value = sp->beta; // Just to trigger next condition
1543 if (value >= sp->beta) // Go with full depth non-pv search
1545 ss[sp->ply].reduction = Depth(0);
1546 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1548 pos.undo_move(move, u);
1550 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1552 if (thread_should_stop(threadID))
1556 lock_grab(&(sp->lock));
1557 if (value > sp->bestValue && !thread_should_stop(threadID))
1559 sp->bestValue = value;
1560 if (sp->bestValue >= sp->beta)
1562 sp_update_pv(sp->parentSstack, ss, sp->ply);
1563 for (int i = 0; i < ActiveThreads; i++)
1564 if (i != threadID && (i == sp->master || sp->slaves[i]))
1565 Threads[i].stop = true;
1567 sp->finished = true;
1570 lock_release(&(sp->lock));
1573 lock_grab(&(sp->lock));
1575 // If this is the master thread and we have been asked to stop because of
1576 // a beta cutoff higher up in the tree, stop all slave threads:
1577 if (sp->master == threadID && thread_should_stop(threadID))
1578 for (int i = 0; i < ActiveThreads; i++)
1580 Threads[i].stop = true;
1583 sp->slaves[threadID] = 0;
1585 lock_release(&(sp->lock));
1589 // sp_search_pv() is used to search from a PV split point. This function
1590 // is called by each thread working at the split point. It is similar to
1591 // the normal search_pv() function, but simpler. Because we have already
1592 // probed the hash table and searched the first move before splitting, we
1593 // don't have to repeat all this work in sp_search_pv(). We also don't
1594 // need to store anything to the hash table here: This is taken care of
1595 // after we return from the split point.
1597 void sp_search_pv(SplitPoint *sp, int threadID) {
1599 assert(threadID >= 0 && threadID < ActiveThreads);
1600 assert(ActiveThreads > 1);
1602 Position pos = Position(sp->pos);
1603 SearchStack *ss = sp->sstack[threadID];
1607 while ( sp->alpha < sp->beta
1608 && !thread_should_stop(threadID)
1609 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1611 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1612 bool moveIsCapture = pos.move_is_capture(move);
1613 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1615 assert(move_is_ok(move));
1617 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1618 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1620 lock_grab(&(sp->lock));
1621 int moveCount = ++sp->moves;
1622 lock_release(&(sp->lock));
1624 ss[sp->ply].currentMove = move;
1626 // Decide the new search depth.
1627 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1628 Depth newDepth = sp->depth - OnePly + ext;
1630 // Make and search the move.
1632 pos.do_move(move, u, sp->dcCandidates);
1634 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1635 // if the move fails high will be re-searched at full depth.
1636 if ( ext == Depth(0)
1637 && moveCount >= LMRPVMoves
1639 && !moveIsPassedPawnPush
1640 && !move_promotion(move)
1641 && !move_is_castle(move)
1642 && move != ss[sp->ply].killer1
1643 && move != ss[sp->ply].killer2)
1645 ss[sp->ply].reduction = OnePly;
1646 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1649 value = sp->alpha + 1; // Just to trigger next condition
1651 if (value > sp->alpha) // Go with full depth non-pv search
1653 ss[sp->ply].reduction = Depth(0);
1654 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1656 if (value > sp->alpha && value < sp->beta)
1658 // When the search fails high at ply 1 while searching the first
1659 // move at the root, set the flag failHighPly1. This is used for
1660 // time managment: We don't want to stop the search early in
1661 // such cases, because resolving the fail high at ply 1 could
1662 // result in a big drop in score at the root.
1663 if (sp->ply == 1 && RootMoveNumber == 1)
1664 Threads[threadID].failHighPly1 = true;
1666 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1667 Threads[threadID].failHighPly1 = false;
1670 pos.undo_move(move, u);
1672 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1674 if (thread_should_stop(threadID))
1678 lock_grab(&(sp->lock));
1679 if (value > sp->bestValue && !thread_should_stop(threadID))
1681 sp->bestValue = value;
1682 if (value > sp->alpha)
1685 sp_update_pv(sp->parentSstack, ss, sp->ply);
1686 if (value == value_mate_in(sp->ply + 1))
1687 ss[sp->ply].mateKiller = move;
1689 if(value >= sp->beta)
1691 for(int i = 0; i < ActiveThreads; i++)
1692 if(i != threadID && (i == sp->master || sp->slaves[i]))
1693 Threads[i].stop = true;
1695 sp->finished = true;
1698 // If we are at ply 1, and we are searching the first root move at
1699 // ply 0, set the 'Problem' variable if the score has dropped a lot
1700 // (from the computer's point of view) since the previous iteration:
1701 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1704 lock_release(&(sp->lock));
1707 lock_grab(&(sp->lock));
1709 // If this is the master thread and we have been asked to stop because of
1710 // a beta cutoff higher up in the tree, stop all slave threads:
1711 if (sp->master == threadID && thread_should_stop(threadID))
1712 for (int i = 0; i < ActiveThreads; i++)
1714 Threads[i].stop = true;
1717 sp->slaves[threadID] = 0;
1719 lock_release(&(sp->lock));
1723 /// The RootMove class
1727 RootMove::RootMove() {
1728 nodes = cumulativeNodes = 0ULL;
1731 // RootMove::operator<() is the comparison function used when
1732 // sorting the moves. A move m1 is considered to be better
1733 // than a move m2 if it has a higher score, or if the moves
1734 // have equal score but m1 has the higher node count.
1736 bool RootMove::operator<(const RootMove& m) {
1738 if (score != m.score)
1739 return (score < m.score);
1741 return nodes <= m.nodes;
1744 /// The RootMoveList class
1748 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1750 MoveStack mlist[MaxRootMoves];
1751 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1753 // Generate all legal moves
1754 int lm_count = generate_legal_moves(pos, mlist);
1756 // Add each move to the moves[] array
1757 for (int i = 0; i < lm_count; i++)
1759 bool includeMove = includeAllMoves;
1761 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1762 includeMove = (searchMoves[k] == mlist[i].move);
1766 // Find a quick score for the move
1768 SearchStack ss[PLY_MAX_PLUS_2];
1770 moves[count].move = mlist[i].move;
1771 moves[count].nodes = 0ULL;
1772 pos.do_move(moves[count].move, u);
1773 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1775 pos.undo_move(moves[count].move, u);
1776 moves[count].pv[0] = moves[i].move;
1777 moves[count].pv[1] = MOVE_NONE; // FIXME
1785 // Simple accessor methods for the RootMoveList class
1787 inline Move RootMoveList::get_move(int moveNum) const {
1788 return moves[moveNum].move;
1791 inline Value RootMoveList::get_move_score(int moveNum) const {
1792 return moves[moveNum].score;
1795 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1796 moves[moveNum].score = score;
1799 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1800 moves[moveNum].nodes = nodes;
1801 moves[moveNum].cumulativeNodes += nodes;
1804 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1806 for(j = 0; pv[j] != MOVE_NONE; j++)
1807 moves[moveNum].pv[j] = pv[j];
1808 moves[moveNum].pv[j] = MOVE_NONE;
1811 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1812 return moves[moveNum].pv[i];
1815 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1816 return moves[moveNum].cumulativeNodes;
1819 inline int RootMoveList::move_count() const {
1824 // RootMoveList::scan_for_easy_move() is called at the end of the first
1825 // iteration, and is used to detect an "easy move", i.e. a move which appears
1826 // to be much bester than all the rest. If an easy move is found, the move
1827 // is returned, otherwise the function returns MOVE_NONE. It is very
1828 // important that this function is called at the right moment: The code
1829 // assumes that the first iteration has been completed and the moves have
1830 // been sorted. This is done in RootMoveList c'tor.
1832 Move RootMoveList::scan_for_easy_move() const {
1839 // moves are sorted so just consider the best and the second one
1840 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1846 // RootMoveList::sort() sorts the root move list at the beginning of a new
1849 inline void RootMoveList::sort() {
1851 sort_multipv(count - 1); // all items
1855 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1856 // list by their scores and depths. It is used to order the different PVs
1857 // correctly in MultiPV mode.
1859 void RootMoveList::sort_multipv(int n) {
1861 for (int i = 1; i <= n; i++)
1863 RootMove rm = moves[i];
1865 for (j = i; j > 0 && moves[j-1] < rm; j--)
1866 moves[j] = moves[j-1];
1872 // init_search_stack() initializes a search stack at the beginning of a
1873 // new search from the root.
1875 void init_search_stack(SearchStack ss[]) {
1876 for(int i = 0; i < 3; i++) {
1877 ss[i].pv[i] = MOVE_NONE;
1878 ss[i].pv[i+1] = MOVE_NONE;
1879 ss[i].currentMove = MOVE_NONE;
1880 ss[i].mateKiller = MOVE_NONE;
1881 ss[i].killer1 = MOVE_NONE;
1882 ss[i].killer2 = MOVE_NONE;
1883 ss[i].threatMove = MOVE_NONE;
1884 ss[i].reduction = Depth(0);
1889 // init_node() is called at the beginning of all the search functions
1890 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1891 // stack object corresponding to the current node. Once every
1892 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1893 // for user input and checks whether it is time to stop the search.
1895 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1896 assert(ply >= 0 && ply < PLY_MAX);
1897 assert(threadID >= 0 && threadID < ActiveThreads);
1899 Threads[threadID].nodes++;
1903 if(NodesSincePoll >= NodesBetweenPolls) {
1909 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1910 ss[ply+2].mateKiller = MOVE_NONE;
1911 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1912 ss[ply].threatMove = MOVE_NONE;
1913 ss[ply].reduction = Depth(0);
1914 ss[ply].currentMoveCaptureValue = Value(0);
1916 if(Threads[threadID].printCurrentLine)
1917 print_current_line(ss, ply, threadID);
1921 // update_pv() is called whenever a search returns a value > alpha. It
1922 // updates the PV in the SearchStack object corresponding to the current
1925 void update_pv(SearchStack ss[], int ply) {
1926 assert(ply >= 0 && ply < PLY_MAX);
1928 ss[ply].pv[ply] = ss[ply].currentMove;
1930 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1931 ss[ply].pv[p] = ss[ply+1].pv[p];
1932 ss[ply].pv[p] = MOVE_NONE;
1936 // sp_update_pv() is a variant of update_pv for use at split points. The
1937 // difference between the two functions is that sp_update_pv also updates
1938 // the PV at the parent node.
1940 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1941 assert(ply >= 0 && ply < PLY_MAX);
1943 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1945 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1946 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1947 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1951 // connected_moves() tests whether two moves are 'connected' in the sense
1952 // that the first move somehow made the second move possible (for instance
1953 // if the moving piece is the same in both moves). The first move is
1954 // assumed to be the move that was made to reach the current position, while
1955 // the second move is assumed to be a move from the current position.
1957 bool connected_moves(const Position &pos, Move m1, Move m2) {
1958 Square f1, t1, f2, t2;
1960 assert(move_is_ok(m1));
1961 assert(move_is_ok(m2));
1966 // Case 1: The moving piece is the same in both moves.
1972 // Case 2: The destination square for m2 was vacated by m1.
1978 // Case 3: Moving through the vacated square:
1979 if(piece_is_slider(pos.piece_on(f2)) &&
1980 bit_is_set(squares_between(f2, t2), f1))
1983 // Case 4: The destination square for m2 is attacked by the moving piece
1985 if(pos.piece_attacks_square(t1, t2))
1988 // Case 5: Discovered check, checking piece is the piece moved in m1:
1989 if(piece_is_slider(pos.piece_on(t1)) &&
1990 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1992 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1994 Bitboard occ = pos.occupied_squares();
1995 Color us = pos.side_to_move();
1996 Square ksq = pos.king_square(us);
1997 clear_bit(&occ, f2);
1998 if(pos.type_of_piece_on(t1) == BISHOP) {
1999 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2002 else if(pos.type_of_piece_on(t1) == ROOK) {
2003 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2007 assert(pos.type_of_piece_on(t1) == QUEEN);
2008 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2017 // extension() decides whether a move should be searched with normal depth,
2018 // or with extended depth. Certain classes of moves (checking moves, in
2019 // particular) are searched with bigger depth than ordinary moves.
2021 Depth extension(const Position &pos, Move m, bool pvNode,
2022 bool check, bool singleReply, bool mateThreat) {
2024 Depth result = Depth(0);
2027 result += CheckExtension[pvNode];
2030 result += SingleReplyExtension[pvNode];
2032 if (pos.move_is_pawn_push_to_7th(m))
2033 result += PawnPushTo7thExtension[pvNode];
2035 if (pos.move_is_passed_pawn_push(m))
2036 result += PassedPawnExtension[pvNode];
2039 result += MateThreatExtension[pvNode];
2041 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
\r
2042 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
\r
2043 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
\r
2044 && !move_promotion(m))
2045 result += PawnEndgameExtension[pvNode];
2048 && pos.move_is_capture(m)
2049 && pos.type_of_piece_on(move_to(m)) != PAWN
2053 return Min(result, OnePly);
2057 // ok_to_do_nullmove() looks at the current position and decides whether
2058 // doing a 'null move' should be allowed. In order to avoid zugzwang
2059 // problems, null moves are not allowed when the side to move has very
2060 // little material left. Currently, the test is a bit too simple: Null
2061 // moves are avoided only when the side to move has only pawns left. It's
2062 // probably a good idea to avoid null moves in at least some more
2063 // complicated endgames, e.g. KQ vs KR. FIXME
2065 bool ok_to_do_nullmove(const Position &pos) {
2066 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2072 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2073 // non-tactical moves late in the move list close to the leaves are
2074 // candidates for pruning.
2076 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2077 Square mfrom, mto, tfrom, tto;
2079 assert(move_is_ok(m));
2080 assert(threat == MOVE_NONE || move_is_ok(threat));
2081 assert(!move_promotion(m));
2082 assert(!pos.move_is_check(m));
2083 assert(!pos.move_is_capture(m));
2084 assert(!pos.move_is_passed_pawn_push(m));
2085 assert(d >= OnePly);
2087 mfrom = move_from(m);
2089 tfrom = move_from(threat);
2090 tto = move_to(threat);
2092 // Case 1: Castling moves are never pruned.
2093 if(move_is_castle(m))
2096 // Case 2: Don't prune moves which move the threatened piece
2097 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2100 // Case 3: If the threatened piece has value less than or equal to the
2101 // value of the threatening piece, don't prune move which defend it.
2102 if(!PruneDefendingMoves && threat != MOVE_NONE
2103 && (piece_value_midgame(pos.piece_on(tfrom))
2104 >= piece_value_midgame(pos.piece_on(tto)))
2105 && pos.move_attacks_square(m, tto))
2108 // Case 4: Don't prune moves with good history.
2109 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2112 // Case 5: If the moving piece in the threatened move is a slider, don't
2113 // prune safe moves which block its ray.
2114 if(!PruneBlockingMoves && threat != MOVE_NONE
2115 && piece_is_slider(pos.piece_on(tfrom))
2116 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2123 // ok_to_use_TT() returns true if a transposition table score
2124 // can be used at a given point in search.
2126 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2128 Value v = value_from_tt(tte->value(), ply);
2130 return ( tte->depth() >= depth
2131 || v >= Max(value_mate_in(100), beta)
2132 || v < Min(value_mated_in(100), beta))
2134 && ( (is_lower_bound(tte->type()) && v >= beta)
2135 || (is_upper_bound(tte->type()) && v < beta));
2139 // ok_to_history() returns true if a move m can be stored
2140 // in history. Should be a non capturing move.
2142 bool ok_to_history(const Position& pos, Move m) {
2144 return pos.square_is_empty(move_to(m))
2145 && !move_promotion(m)
2150 // update_history() registers a good move that produced a beta-cutoff
2151 // in history and marks as failures all the other moves of that ply.
2153 void update_history(const Position& pos, Move m, Depth depth,
2154 Move movesSearched[], int moveCount) {
2156 H.success(pos.piece_on(move_from(m)), m, depth);
2158 for (int i = 0; i < moveCount - 1; i++)
2159 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2160 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2163 // fail_high_ply_1() checks if some thread is currently resolving a fail
2164 // high at ply 1 at the node below the first root node. This information
2165 // is used for time managment.
2167 bool fail_high_ply_1() {
2168 for(int i = 0; i < ActiveThreads; i++)
2169 if(Threads[i].failHighPly1)
2175 // current_search_time() returns the number of milliseconds which have passed
2176 // since the beginning of the current search.
2178 int current_search_time() {
2179 return get_system_time() - SearchStartTime;
2183 // nps() computes the current nodes/second count.
2186 int t = current_search_time();
2187 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2191 // poll() performs two different functions: It polls for user input, and it
2192 // looks at the time consumed so far and decides if it's time to abort the
2197 static int lastInfoTime;
2198 int t = current_search_time();
2203 // We are line oriented, don't read single chars
2204 std::string command;
2205 if (!std::getline(std::cin, command))
2208 if (command == "quit")
2211 PonderSearch = false;
2214 else if(command == "stop")
2217 PonderSearch = false;
2219 else if(command == "ponderhit")
2222 // Print search information
2226 else if (lastInfoTime > t)
2227 // HACK: Must be a new search where we searched less than
2228 // NodesBetweenPolls nodes during the first second of search.
2231 else if (t - lastInfoTime >= 1000)
2238 if (dbg_show_hit_rate)
2239 dbg_print_hit_rate();
2241 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2242 << " time " << t << " hashfull " << TT.full() << std::endl;
2243 lock_release(&IOLock);
2244 if (ShowCurrentLine)
2245 Threads[0].printCurrentLine = true;
2247 // Should we stop the search?
2251 bool overTime = t > AbsoluteMaxSearchTime
2252 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2253 || ( !FailHigh && !fail_high_ply_1() && !Problem
2254 && t > 6*(MaxSearchTime + ExtraSearchTime));
2256 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2257 || (ExactMaxTime && t >= ExactMaxTime)
2258 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2263 // ponderhit() is called when the program is pondering (i.e. thinking while
2264 // it's the opponent's turn to move) in order to let the engine know that
2265 // it correctly predicted the opponent's move.
2268 int t = current_search_time();
2269 PonderSearch = false;
2270 if(Iteration >= 2 &&
2271 (!InfiniteSearch && (StopOnPonderhit ||
2272 t > AbsoluteMaxSearchTime ||
2273 (RootMoveNumber == 1 &&
2274 t > MaxSearchTime + ExtraSearchTime) ||
2275 (!FailHigh && !fail_high_ply_1() && !Problem &&
2276 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2281 // print_current_line() prints the current line of search for a given
2282 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2284 void print_current_line(SearchStack ss[], int ply, int threadID) {
2285 assert(ply >= 0 && ply < PLY_MAX);
2286 assert(threadID >= 0 && threadID < ActiveThreads);
2288 if(!Threads[threadID].idle) {
2290 std::cout << "info currline " << (threadID + 1);
2291 for(int p = 0; p < ply; p++)
2292 std::cout << " " << ss[p].currentMove;
2293 std::cout << std::endl;
2294 lock_release(&IOLock);
2296 Threads[threadID].printCurrentLine = false;
2297 if(threadID + 1 < ActiveThreads)
2298 Threads[threadID + 1].printCurrentLine = true;
2302 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2303 // while the program is pondering. The point is to work around a wrinkle in
2304 // the UCI protocol: When pondering, the engine is not allowed to give a
2305 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2306 // We simply wait here until one of these commands is sent, and return,
2307 // after which the bestmove and pondermove will be printed (in id_loop()).
2309 void wait_for_stop_or_ponderhit() {
2310 std::string command;
2313 if(!std::getline(std::cin, command))
2316 if(command == "quit") {
2317 OpeningBook.close();
2322 else if(command == "ponderhit" || command == "stop")
2328 // idle_loop() is where the threads are parked when they have no work to do.
2329 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2330 // object for which the current thread is the master.
2332 void idle_loop(int threadID, SplitPoint *waitSp) {
2333 assert(threadID >= 0 && threadID < THREAD_MAX);
2335 Threads[threadID].running = true;
2338 if(AllThreadsShouldExit && threadID != 0)
2341 // If we are not thinking, wait for a condition to be signaled instead
2342 // of wasting CPU time polling for work:
2343 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2344 #if !defined(_MSC_VER)
2345 pthread_mutex_lock(&WaitLock);
2346 if(Idle || threadID >= ActiveThreads)
2347 pthread_cond_wait(&WaitCond, &WaitLock);
2348 pthread_mutex_unlock(&WaitLock);
2350 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2354 // If this thread has been assigned work, launch a search:
2355 if(Threads[threadID].workIsWaiting) {
2356 Threads[threadID].workIsWaiting = false;
2357 if(Threads[threadID].splitPoint->pvNode)
2358 sp_search_pv(Threads[threadID].splitPoint, threadID);
2360 sp_search(Threads[threadID].splitPoint, threadID);
2361 Threads[threadID].idle = true;
2364 // If this thread is the master of a split point and all threads have
2365 // finished their work at this split point, return from the idle loop:
2366 if(waitSp != NULL && waitSp->cpus == 0)
2370 Threads[threadID].running = false;
2374 // init_split_point_stack() is called during program initialization, and
2375 // initializes all split point objects.
2377 void init_split_point_stack() {
2378 for(int i = 0; i < THREAD_MAX; i++)
2379 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2380 SplitPointStack[i][j].parent = NULL;
2381 lock_init(&(SplitPointStack[i][j].lock), NULL);
2386 // destroy_split_point_stack() is called when the program exits, and
2387 // destroys all locks in the precomputed split point objects.
2389 void destroy_split_point_stack() {
2390 for(int i = 0; i < THREAD_MAX; i++)
2391 for(int j = 0; j < MaxActiveSplitPoints; j++)
2392 lock_destroy(&(SplitPointStack[i][j].lock));
2396 // thread_should_stop() checks whether the thread with a given threadID has
2397 // been asked to stop, directly or indirectly. This can happen if a beta
2398 // cutoff has occured in thre thread's currently active split point, or in
2399 // some ancestor of the current split point.
2401 bool thread_should_stop(int threadID) {
2402 assert(threadID >= 0 && threadID < ActiveThreads);
2406 if(Threads[threadID].stop)
2408 if(ActiveThreads <= 2)
2410 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2412 Threads[threadID].stop = true;
2419 // thread_is_available() checks whether the thread with threadID "slave" is
2420 // available to help the thread with threadID "master" at a split point. An
2421 // obvious requirement is that "slave" must be idle. With more than two
2422 // threads, this is not by itself sufficient: If "slave" is the master of
2423 // some active split point, it is only available as a slave to the other
2424 // threads which are busy searching the split point at the top of "slave"'s
2425 // split point stack (the "helpful master concept" in YBWC terminology).
2427 bool thread_is_available(int slave, int master) {
2428 assert(slave >= 0 && slave < ActiveThreads);
2429 assert(master >= 0 && master < ActiveThreads);
2430 assert(ActiveThreads > 1);
2432 if(!Threads[slave].idle || slave == master)
2435 if(Threads[slave].activeSplitPoints == 0)
2436 // No active split points means that the thread is available as a slave
2437 // for any other thread.
2440 if(ActiveThreads == 2)
2443 // Apply the "helpful master" concept if possible.
2444 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2451 // idle_thread_exists() tries to find an idle thread which is available as
2452 // a slave for the thread with threadID "master".
2454 bool idle_thread_exists(int master) {
2455 assert(master >= 0 && master < ActiveThreads);
2456 assert(ActiveThreads > 1);
2458 for(int i = 0; i < ActiveThreads; i++)
2459 if(thread_is_available(i, master))
2465 // split() does the actual work of distributing the work at a node between
2466 // several threads at PV nodes. If it does not succeed in splitting the
2467 // node (because no idle threads are available, or because we have no unused
2468 // split point objects), the function immediately returns false. If
2469 // splitting is possible, a SplitPoint object is initialized with all the
2470 // data that must be copied to the helper threads (the current position and
2471 // search stack, alpha, beta, the search depth, etc.), and we tell our
2472 // helper threads that they have been assigned work. This will cause them
2473 // to instantly leave their idle loops and call sp_search_pv(). When all
2474 // threads have returned from sp_search_pv (or, equivalently, when
2475 // splitPoint->cpus becomes 0), split() returns true.
2477 bool split(const Position &p, SearchStack *sstck, int ply,
2478 Value *alpha, Value *beta, Value *bestValue,
2479 Depth depth, int *moves,
2480 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2482 assert(sstck != NULL);
2483 assert(ply >= 0 && ply < PLY_MAX);
2484 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2485 assert(!pvNode || *alpha < *beta);
2486 assert(*beta <= VALUE_INFINITE);
2487 assert(depth > Depth(0));
2488 assert(master >= 0 && master < ActiveThreads);
2489 assert(ActiveThreads > 1);
2491 SplitPoint *splitPoint;
2496 // If no other thread is available to help us, or if we have too many
2497 // active split points, don't split:
2498 if(!idle_thread_exists(master) ||
2499 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2500 lock_release(&MPLock);
2504 // Pick the next available split point object from the split point stack:
2505 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2506 Threads[master].activeSplitPoints++;
2508 // Initialize the split point object:
2509 splitPoint->parent = Threads[master].splitPoint;
2510 splitPoint->finished = false;
2511 splitPoint->ply = ply;
2512 splitPoint->depth = depth;
2513 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2514 splitPoint->beta = *beta;
2515 splitPoint->pvNode = pvNode;
2516 splitPoint->dcCandidates = dcCandidates;
2517 splitPoint->bestValue = *bestValue;
2518 splitPoint->master = master;
2519 splitPoint->mp = mp;
2520 splitPoint->moves = *moves;
2521 splitPoint->cpus = 1;
2522 splitPoint->pos.copy(p);
2523 splitPoint->parentSstack = sstck;
2524 for(i = 0; i < ActiveThreads; i++)
2525 splitPoint->slaves[i] = 0;
2527 // Copy the current position and the search stack to the master thread:
2528 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2529 Threads[master].splitPoint = splitPoint;
2531 // Make copies of the current position and search stack for each thread:
2532 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2534 if(thread_is_available(i, master)) {
2535 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2536 Threads[i].splitPoint = splitPoint;
2537 splitPoint->slaves[i] = 1;
2541 // Tell the threads that they have work to do. This will make them leave
2543 for(i = 0; i < ActiveThreads; i++)
2544 if(i == master || splitPoint->slaves[i]) {
2545 Threads[i].workIsWaiting = true;
2546 Threads[i].idle = false;
2547 Threads[i].stop = false;
2550 lock_release(&MPLock);
2552 // Everything is set up. The master thread enters the idle loop, from
2553 // which it will instantly launch a search, because its workIsWaiting
2554 // slot is 'true'. We send the split point as a second parameter to the
2555 // idle loop, which means that the main thread will return from the idle
2556 // loop when all threads have finished their work at this split point
2557 // (i.e. when // splitPoint->cpus == 0).
2558 idle_loop(master, splitPoint);
2560 // We have returned from the idle loop, which means that all threads are
2561 // finished. Update alpha, beta and bestvalue, and return:
2563 if(pvNode) *alpha = splitPoint->alpha;
2564 *beta = splitPoint->beta;
2565 *bestValue = splitPoint->bestValue;
2566 Threads[master].stop = false;
2567 Threads[master].idle = false;
2568 Threads[master].activeSplitPoints--;
2569 Threads[master].splitPoint = splitPoint->parent;
2570 lock_release(&MPLock);
2576 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2577 // to start a new search from the root.
2579 void wake_sleeping_threads() {
2580 if(ActiveThreads > 1) {
2581 for(int i = 1; i < ActiveThreads; i++) {
2582 Threads[i].idle = true;
2583 Threads[i].workIsWaiting = false;
2585 #if !defined(_MSC_VER)
2586 pthread_mutex_lock(&WaitLock);
2587 pthread_cond_broadcast(&WaitCond);
2588 pthread_mutex_unlock(&WaitLock);
2590 for(int i = 1; i < THREAD_MAX; i++)
2591 SetEvent(SitIdleEvent[i]);
2597 // init_thread() is the function which is called when a new thread is
2598 // launched. It simply calls the idle_loop() function with the supplied
2599 // threadID. There are two versions of this function; one for POSIX threads
2600 // and one for Windows threads.
2602 #if !defined(_MSC_VER)
2604 void *init_thread(void *threadID) {
2605 idle_loop(*(int *)threadID, NULL);
2611 DWORD WINAPI init_thread(LPVOID threadID) {
2612 idle_loop(*(int *)threadID, NULL);