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);
899 // Initialize, and make an early exit in case of an aborted search,
900 // an instant draw, maximum ply reached, etc.
901 Value oldAlpha = alpha;
903 if (AbortSearch || thread_should_stop(threadID))
907 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
909 init_node(pos, ss, ply, threadID);
914 if (ply >= PLY_MAX - 1)
915 return evaluate(pos, ei, threadID);
917 // Mate distance pruning
918 alpha = Max(value_mated_in(ply), alpha);
919 beta = Min(value_mate_in(ply+1), beta);
923 // Transposition table lookup. At PV nodes, we don't use the TT for
924 // pruning, but only for move ordering.
925 const TTEntry* tte = TT.retrieve(pos);
927 Move ttMove = (tte ? tte->move() : MOVE_NONE);
929 // Go with internal iterative deepening if we don't have a TT move
930 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
932 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
933 ttMove = ss[ply].pv[ply];
936 // Initialize a MovePicker object for the current position, and prepare
937 // to search all moves:
938 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
939 ss[ply].killer1, ss[ply].killer2, depth);
941 Move move, movesSearched[256];
943 Value value, bestValue = -VALUE_INFINITE;
944 Bitboard dcCandidates = mp.discovered_check_candidates();
945 bool mateThreat = MateThreatExtension[1] > Depth(0)
946 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
948 // Loop through all legal moves until no moves remain or a beta cutoff
951 && (move = mp.get_next_move()) != MOVE_NONE
952 && !thread_should_stop(threadID))
954 assert(move_is_ok(move));
956 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
957 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
958 bool moveIsCapture = pos.move_is_capture(move);
959 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
961 movesSearched[moveCount++] = ss[ply].currentMove = move;
963 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
964 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
966 // Decide the new search depth
967 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
968 Depth newDepth = depth - OnePly + ext;
970 // Make and search the move
972 pos.do_move(move, u, dcCandidates);
974 if (moveCount == 1) // The first move in list is the PV
975 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
978 // Try to reduce non-pv search depth by one ply if move seems not problematic,
979 // if the move fails high will be re-searched at full depth.
980 if ( depth >= 2*OnePly
982 && moveCount >= LMRPVMoves
984 && !move_promotion(move)
985 && !moveIsPassedPawnPush
986 && !move_is_castle(move)
987 && move != ss[ply].killer1
988 && move != ss[ply].killer2)
990 ss[ply].reduction = OnePly;
991 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
994 value = alpha + 1; // Just to trigger next condition
996 if (value > alpha) // Go with full depth pv search
998 ss[ply].reduction = Depth(0);
999 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1000 if (value > alpha && value < beta)
1002 // When the search fails high at ply 1 while searching the first
1003 // move at the root, set the flag failHighPly1. This is used for
1004 // time managment: We don't want to stop the search early in
1005 // such cases, because resolving the fail high at ply 1 could
1006 // result in a big drop in score at the root.
1007 if (ply == 1 && RootMoveNumber == 1)
1008 Threads[threadID].failHighPly1 = true;
1010 // A fail high occurred. Re-search at full window (pv search)
1011 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1012 Threads[threadID].failHighPly1 = false;
1016 pos.undo_move(move, u);
1018 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1021 if (value > bestValue)
1028 if (value == value_mate_in(ply + 1))
1029 ss[ply].mateKiller = move;
1031 // If we are at ply 1, and we are searching the first root move at
1032 // ply 0, set the 'Problem' variable if the score has dropped a lot
1033 // (from the computer's point of view) since the previous iteration:
1034 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1039 if ( ActiveThreads > 1
1041 && depth >= MinimumSplitDepth
1043 && idle_thread_exists(threadID)
1045 && !thread_should_stop(threadID)
1046 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1047 &moveCount, &mp, dcCandidates, threadID, true))
1051 // All legal moves have been searched. A special case: If there were
1052 // no legal moves, it must be mate or stalemate:
1054 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1056 // If the search is not aborted, update the transposition table,
1057 // history counters, and killer moves.
1058 if (AbortSearch || thread_should_stop(threadID))
1061 if (bestValue <= oldAlpha)
1062 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1064 else if (bestValue >= beta)
1066 Move m = ss[ply].pv[ply];
1067 if (ok_to_history(pos, m)) // Only non capture moves are considered
1069 update_history(pos, m, depth, movesSearched, moveCount);
1070 if (m != ss[ply].killer1)
1072 ss[ply].killer2 = ss[ply].killer1;
1073 ss[ply].killer1 = m;
1076 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1079 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1085 // search() is the search function for zero-width nodes.
1087 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1088 int ply, bool allowNullmove, int threadID) {
1090 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1091 assert(ply >= 0 && ply < PLY_MAX);
1092 assert(threadID >= 0 && threadID < ActiveThreads);
1096 // Initialize, and make an early exit in case of an aborted search,
1097 // an instant draw, maximum ply reached, etc.
1098 if (AbortSearch || thread_should_stop(threadID))
1102 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1104 init_node(pos, ss, ply, threadID);
1109 if (ply >= PLY_MAX - 1)
1110 return evaluate(pos, ei, threadID);
1112 // Mate distance pruning
1113 if (value_mated_in(ply) >= beta)
1116 if (value_mate_in(ply + 1) < beta)
1119 // Transposition table lookup
1120 const TTEntry* tte = TT.retrieve(pos);
1122 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1124 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1126 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1127 return value_from_tt(tte->value(), ply);
1130 Value approximateEval = quick_evaluate(pos);
1131 bool mateThreat = false;
1136 && ok_to_do_nullmove(pos)
1137 && approximateEval >= beta - NullMoveMargin)
1139 ss[ply].currentMove = MOVE_NULL;
1142 pos.do_null_move(u);
1143 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1144 pos.undo_null_move(u);
1146 if (nullValue >= beta)
1148 if (depth < 6 * OnePly)
1151 // Do zugzwang verification search
1152 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1156 // The null move failed low, which means that we may be faced with
1157 // some kind of threat. If the previous move was reduced, check if
1158 // the move that refuted the null move was somehow connected to the
1159 // move which was reduced. If a connection is found, return a fail
1160 // low score (which will cause the reduced move to fail high in the
1161 // parent node, which will trigger a re-search with full depth).
1162 if (nullValue == value_mated_in(ply + 2))
1165 ss[ply].threatMove = ss[ply + 1].currentMove;
1166 if ( depth < ThreatDepth
1167 && ss[ply - 1].reduction
1168 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1172 // Null move search not allowed, try razoring
1173 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1174 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1176 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1181 // Go with internal iterative deepening if we don't have a TT move
1182 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1183 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1185 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1186 ttMove = ss[ply].pv[ply];
1189 // Initialize a MovePicker object for the current position, and prepare
1190 // to search all moves:
1191 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1192 ss[ply].killer1, ss[ply].killer2, depth);
1194 Move move, movesSearched[256];
1196 Value value, bestValue = -VALUE_INFINITE;
1197 Bitboard dcCandidates = mp.discovered_check_candidates();
1198 Value futilityValue = VALUE_NONE;
1199 bool isCheck = pos.is_check();
1200 bool useFutilityPruning = UseFutilityPruning
1201 && depth < SelectiveDepth
1204 // Loop through all legal moves until no moves remain or a beta cutoff
1206 while ( bestValue < beta
1207 && (move = mp.get_next_move()) != MOVE_NONE
1208 && !thread_should_stop(threadID))
1210 assert(move_is_ok(move));
1212 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1213 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1214 bool moveIsCapture = pos.move_is_capture(move);
1215 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1217 movesSearched[moveCount++] = ss[ply].currentMove = move;
1219 // Decide the new search depth
1220 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1221 Depth newDepth = depth - OnePly + ext;
1224 if ( useFutilityPruning
1227 && !moveIsPassedPawnPush
1228 && !move_promotion(move))
1230 if ( moveCount >= 2 + int(depth)
1231 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1234 if (depth < 3 * OnePly && approximateEval < beta)
1236 if (futilityValue == VALUE_NONE)
1237 futilityValue = evaluate(pos, ei, threadID)
1238 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1240 if (futilityValue < beta)
1242 if (futilityValue > bestValue)
1243 bestValue = futilityValue;
1249 // Make and search the move
1251 pos.do_move(move, u, dcCandidates);
1253 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1254 // if the move fails high will be re-searched at full depth.
1255 if ( depth >= 2*OnePly
1257 && moveCount >= LMRNonPVMoves
1259 && !move_promotion(move)
1260 && !moveIsPassedPawnPush
1261 && !move_is_castle(move)
1262 && move != ss[ply].killer1
1263 && move != ss[ply].killer2)
1265 ss[ply].reduction = OnePly;
1266 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1269 value = beta; // Just to trigger next condition
1271 if (value >= beta) // Go with full depth non-pv search
1273 ss[ply].reduction = Depth(0);
1274 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1276 pos.undo_move(move, u);
1278 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1281 if (value > bestValue)
1287 if (value == value_mate_in(ply + 1))
1288 ss[ply].mateKiller = move;
1292 if ( ActiveThreads > 1
1294 && depth >= MinimumSplitDepth
1296 && idle_thread_exists(threadID)
1298 && !thread_should_stop(threadID)
1299 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1300 &mp, dcCandidates, threadID, false))
1304 // All legal moves have been searched. A special case: If there were
1305 // no legal moves, it must be mate or stalemate:
1307 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1309 // If the search is not aborted, update the transposition table,
1310 // history counters, and killer moves.
1311 if (AbortSearch || thread_should_stop(threadID))
1314 if (bestValue < beta)
1315 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1318 Move m = ss[ply].pv[ply];
1319 if (ok_to_history(pos, m)) // Only non capture moves are considered
1321 update_history(pos, m, depth, movesSearched, moveCount);
1322 if (m != ss[ply].killer1)
1324 ss[ply].killer2 = ss[ply].killer1;
1325 ss[ply].killer1 = m;
1328 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1334 // qsearch() is the quiescence search function, which is called by the main
1335 // search function when the remaining depth is zero (or, to be more precise,
1336 // less than OnePly).
1338 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1339 Depth depth, int ply, int threadID) {
1341 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1342 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1344 assert(ply >= 0 && ply < PLY_MAX);
1345 assert(threadID >= 0 && threadID < ActiveThreads);
1349 // Initialize, and make an early exit in case of an aborted search,
1350 // an instant draw, maximum ply reached, etc.
1351 if (AbortSearch || thread_should_stop(threadID))
1354 init_node(pos, ss, ply, threadID);
1359 // Transposition table lookup
1360 const TTEntry* tte = TT.retrieve(pos);
1361 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1362 return value_from_tt(tte->value(), ply);
1364 // Evaluate the position statically:
1365 Value staticValue = evaluate(pos, ei, threadID);
1367 if (ply == PLY_MAX - 1)
1370 // Initialize "stand pat score", and return it immediately if it is
1372 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1374 if (bestValue >= beta)
1377 if (bestValue > alpha)
1380 // Initialize a MovePicker object for the current position, and prepare
1381 // to search the moves. Because the depth is <= 0 here, only captures,
1382 // queen promotions and checks (only if depth == 0) will be generated.
1383 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1387 Bitboard dcCandidates = mp.discovered_check_candidates();
1388 bool isCheck = pos.is_check();
1390 // Loop through the moves until no moves remain or a beta cutoff
1392 while ( alpha < beta
1393 && (move = mp.get_next_move()) != MOVE_NONE)
1395 assert(move_is_ok(move));
1397 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1398 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1401 ss[ply].currentMove = move;
1404 if ( UseQSearchFutilityPruning
1407 && !move_promotion(move)
1408 && !moveIsPassedPawnPush
1409 && beta - alpha == 1
1410 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1412 Value futilityValue = staticValue
1413 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1414 pos.endgame_value_of_piece_on(move_to(move)))
1416 + ei.futilityMargin;
1418 if (futilityValue < alpha)
1420 if (futilityValue > bestValue)
1421 bestValue = futilityValue;
1426 // Don't search captures and checks with negative SEE values.
1428 && !move_promotion(move)
1429 && (pos.midgame_value_of_piece_on(move_from(move)) >
1430 pos.midgame_value_of_piece_on(move_to(move)))
1431 && pos.see(move) < 0)
1434 // Make and search the move.
1436 pos.do_move(move, u, dcCandidates);
1437 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1438 pos.undo_move(move, u);
1440 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1443 if (value > bestValue)
1454 // All legal moves have been searched. A special case: If we're in check
1455 // and no legal moves were found, it is checkmate:
1456 if (pos.is_check() && moveCount == 0) // Mate!
1457 return value_mated_in(ply);
1459 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1461 // Update transposition table
1462 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1468 // sp_search() is used to search from a split point. This function is called
1469 // by each thread working at the split point. It is similar to the normal
1470 // search() function, but simpler. Because we have already probed the hash
1471 // table, done a null move search, and searched the first move before
1472 // splitting, we don't have to repeat all this work in sp_search(). We
1473 // also don't need to store anything to the hash table here: This is taken
1474 // care of after we return from the split point.
1476 void sp_search(SplitPoint *sp, int threadID) {
1478 assert(threadID >= 0 && threadID < ActiveThreads);
1479 assert(ActiveThreads > 1);
1481 Position pos = Position(sp->pos);
1482 SearchStack *ss = sp->sstack[threadID];
1485 bool isCheck = pos.is_check();
1486 bool useFutilityPruning = UseFutilityPruning
1487 && sp->depth < SelectiveDepth
1490 while ( sp->bestValue < sp->beta
1491 && !thread_should_stop(threadID)
1492 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1494 assert(move_is_ok(move));
1496 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1497 bool moveIsCapture = pos.move_is_capture(move);
1498 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1500 lock_grab(&(sp->lock));
1501 int moveCount = ++sp->moves;
1502 lock_release(&(sp->lock));
1504 ss[sp->ply].currentMove = move;
1506 // Decide the new search depth.
1507 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1508 Depth newDepth = sp->depth - OnePly + ext;
1511 if ( useFutilityPruning
1514 && !moveIsPassedPawnPush
1515 && !move_promotion(move)
1516 && moveCount >= 2 + int(sp->depth)
1517 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1520 // Make and search the move.
1522 pos.do_move(move, u, sp->dcCandidates);
1524 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1525 // if the move fails high will be re-searched at full depth.
1526 if ( ext == Depth(0)
1527 && moveCount >= LMRNonPVMoves
1529 && !moveIsPassedPawnPush
1530 && !move_promotion(move)
1531 && !move_is_castle(move)
1532 && move != ss[sp->ply].killer1
1533 && move != ss[sp->ply].killer2)
1535 ss[sp->ply].reduction = OnePly;
1536 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1539 value = sp->beta; // Just to trigger next condition
1541 if (value >= sp->beta) // Go with full depth non-pv search
1543 ss[sp->ply].reduction = Depth(0);
1544 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1546 pos.undo_move(move, u);
1548 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1550 if (thread_should_stop(threadID))
1554 lock_grab(&(sp->lock));
1555 if (value > sp->bestValue && !thread_should_stop(threadID))
1557 sp->bestValue = value;
1558 if (sp->bestValue >= sp->beta)
1560 sp_update_pv(sp->parentSstack, ss, sp->ply);
1561 for (int i = 0; i < ActiveThreads; i++)
1562 if (i != threadID && (i == sp->master || sp->slaves[i]))
1563 Threads[i].stop = true;
1565 sp->finished = true;
1568 lock_release(&(sp->lock));
1571 lock_grab(&(sp->lock));
1573 // If this is the master thread and we have been asked to stop because of
1574 // a beta cutoff higher up in the tree, stop all slave threads:
1575 if (sp->master == threadID && thread_should_stop(threadID))
1576 for (int i = 0; i < ActiveThreads; i++)
1578 Threads[i].stop = true;
1581 sp->slaves[threadID] = 0;
1583 lock_release(&(sp->lock));
1587 // sp_search_pv() is used to search from a PV split point. This function
1588 // is called by each thread working at the split point. It is similar to
1589 // the normal search_pv() function, but simpler. Because we have already
1590 // probed the hash table and searched the first move before splitting, we
1591 // don't have to repeat all this work in sp_search_pv(). We also don't
1592 // need to store anything to the hash table here: This is taken care of
1593 // after we return from the split point.
1595 void sp_search_pv(SplitPoint *sp, int threadID) {
1597 assert(threadID >= 0 && threadID < ActiveThreads);
1598 assert(ActiveThreads > 1);
1600 Position pos = Position(sp->pos);
1601 SearchStack *ss = sp->sstack[threadID];
1605 while ( sp->alpha < sp->beta
1606 && !thread_should_stop(threadID)
1607 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1609 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1610 bool moveIsCapture = pos.move_is_capture(move);
1611 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1613 assert(move_is_ok(move));
1615 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1616 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1618 lock_grab(&(sp->lock));
1619 int moveCount = ++sp->moves;
1620 lock_release(&(sp->lock));
1622 ss[sp->ply].currentMove = move;
1624 // Decide the new search depth.
1625 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1626 Depth newDepth = sp->depth - OnePly + ext;
1628 // Make and search the move.
1630 pos.do_move(move, u, sp->dcCandidates);
1632 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1633 // if the move fails high will be re-searched at full depth.
1634 if ( ext == Depth(0)
1635 && moveCount >= LMRPVMoves
1637 && !moveIsPassedPawnPush
1638 && !move_promotion(move)
1639 && !move_is_castle(move)
1640 && move != ss[sp->ply].killer1
1641 && move != ss[sp->ply].killer2)
1643 ss[sp->ply].reduction = OnePly;
1644 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1647 value = sp->alpha + 1; // Just to trigger next condition
1649 if (value > sp->alpha) // Go with full depth non-pv search
1651 ss[sp->ply].reduction = Depth(0);
1652 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1654 if (value > sp->alpha && value < sp->beta)
1656 // When the search fails high at ply 1 while searching the first
1657 // move at the root, set the flag failHighPly1. This is used for
1658 // time managment: We don't want to stop the search early in
1659 // such cases, because resolving the fail high at ply 1 could
1660 // result in a big drop in score at the root.
1661 if (sp->ply == 1 && RootMoveNumber == 1)
1662 Threads[threadID].failHighPly1 = true;
1664 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1665 Threads[threadID].failHighPly1 = false;
1668 pos.undo_move(move, u);
1670 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1672 if (thread_should_stop(threadID))
1676 lock_grab(&(sp->lock));
1677 if (value > sp->bestValue && !thread_should_stop(threadID))
1679 sp->bestValue = value;
1680 if (value > sp->alpha)
1683 sp_update_pv(sp->parentSstack, ss, sp->ply);
1684 if (value == value_mate_in(sp->ply + 1))
1685 ss[sp->ply].mateKiller = move;
1687 if(value >= sp->beta)
1689 for(int i = 0; i < ActiveThreads; i++)
1690 if(i != threadID && (i == sp->master || sp->slaves[i]))
1691 Threads[i].stop = true;
1693 sp->finished = true;
1696 // If we are at ply 1, and we are searching the first root move at
1697 // ply 0, set the 'Problem' variable if the score has dropped a lot
1698 // (from the computer's point of view) since the previous iteration:
1699 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1702 lock_release(&(sp->lock));
1705 lock_grab(&(sp->lock));
1707 // If this is the master thread and we have been asked to stop because of
1708 // a beta cutoff higher up in the tree, stop all slave threads:
1709 if (sp->master == threadID && thread_should_stop(threadID))
1710 for (int i = 0; i < ActiveThreads; i++)
1712 Threads[i].stop = true;
1715 sp->slaves[threadID] = 0;
1717 lock_release(&(sp->lock));
1721 /// The RootMove class
1725 RootMove::RootMove() {
1726 nodes = cumulativeNodes = 0ULL;
1729 // RootMove::operator<() is the comparison function used when
1730 // sorting the moves. A move m1 is considered to be better
1731 // than a move m2 if it has a higher score, or if the moves
1732 // have equal score but m1 has the higher node count.
1734 bool RootMove::operator<(const RootMove& m) {
1736 if (score != m.score)
1737 return (score < m.score);
1739 return nodes <= m.nodes;
1742 /// The RootMoveList class
1746 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1748 MoveStack mlist[MaxRootMoves];
1749 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1751 // Generate all legal moves
1752 int lm_count = generate_legal_moves(pos, mlist);
1754 // Add each move to the moves[] array
1755 for (int i = 0; i < lm_count; i++)
1757 bool includeMove = includeAllMoves;
1759 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1760 includeMove = (searchMoves[k] == mlist[i].move);
1764 // Find a quick score for the move
1766 SearchStack ss[PLY_MAX_PLUS_2];
1768 moves[count].move = mlist[i].move;
1769 moves[count].nodes = 0ULL;
1770 pos.do_move(moves[count].move, u);
1771 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1773 pos.undo_move(moves[count].move, u);
1774 moves[count].pv[0] = moves[i].move;
1775 moves[count].pv[1] = MOVE_NONE; // FIXME
1783 // Simple accessor methods for the RootMoveList class
1785 inline Move RootMoveList::get_move(int moveNum) const {
1786 return moves[moveNum].move;
1789 inline Value RootMoveList::get_move_score(int moveNum) const {
1790 return moves[moveNum].score;
1793 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1794 moves[moveNum].score = score;
1797 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1798 moves[moveNum].nodes = nodes;
1799 moves[moveNum].cumulativeNodes += nodes;
1802 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1804 for(j = 0; pv[j] != MOVE_NONE; j++)
1805 moves[moveNum].pv[j] = pv[j];
1806 moves[moveNum].pv[j] = MOVE_NONE;
1809 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1810 return moves[moveNum].pv[i];
1813 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1814 return moves[moveNum].cumulativeNodes;
1817 inline int RootMoveList::move_count() const {
1822 // RootMoveList::scan_for_easy_move() is called at the end of the first
1823 // iteration, and is used to detect an "easy move", i.e. a move which appears
1824 // to be much bester than all the rest. If an easy move is found, the move
1825 // is returned, otherwise the function returns MOVE_NONE. It is very
1826 // important that this function is called at the right moment: The code
1827 // assumes that the first iteration has been completed and the moves have
1828 // been sorted. This is done in RootMoveList c'tor.
1830 Move RootMoveList::scan_for_easy_move() const {
1837 // moves are sorted so just consider the best and the second one
1838 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1844 // RootMoveList::sort() sorts the root move list at the beginning of a new
1847 inline void RootMoveList::sort() {
1849 sort_multipv(count - 1); // all items
1853 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1854 // list by their scores and depths. It is used to order the different PVs
1855 // correctly in MultiPV mode.
1857 void RootMoveList::sort_multipv(int n) {
1859 for (int i = 1; i <= n; i++)
1861 RootMove rm = moves[i];
1863 for (j = i; j > 0 && moves[j-1] < rm; j--)
1864 moves[j] = moves[j-1];
1870 // init_search_stack() initializes a search stack at the beginning of a
1871 // new search from the root.
1873 void init_search_stack(SearchStack ss[]) {
1874 for(int i = 0; i < 3; i++) {
1875 ss[i].pv[i] = MOVE_NONE;
1876 ss[i].pv[i+1] = MOVE_NONE;
1877 ss[i].currentMove = MOVE_NONE;
1878 ss[i].mateKiller = MOVE_NONE;
1879 ss[i].killer1 = MOVE_NONE;
1880 ss[i].killer2 = MOVE_NONE;
1881 ss[i].threatMove = MOVE_NONE;
1882 ss[i].reduction = Depth(0);
1887 // init_node() is called at the beginning of all the search functions
1888 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1889 // stack object corresponding to the current node. Once every
1890 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1891 // for user input and checks whether it is time to stop the search.
1893 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1894 assert(ply >= 0 && ply < PLY_MAX);
1895 assert(threadID >= 0 && threadID < ActiveThreads);
1897 Threads[threadID].nodes++;
1901 if(NodesSincePoll >= NodesBetweenPolls) {
1907 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1908 ss[ply+2].mateKiller = MOVE_NONE;
1909 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1910 ss[ply].threatMove = MOVE_NONE;
1911 ss[ply].reduction = Depth(0);
1912 ss[ply].currentMoveCaptureValue = Value(0);
1914 if(Threads[threadID].printCurrentLine)
1915 print_current_line(ss, ply, threadID);
1919 // update_pv() is called whenever a search returns a value > alpha. It
1920 // updates the PV in the SearchStack object corresponding to the current
1923 void update_pv(SearchStack ss[], int ply) {
1924 assert(ply >= 0 && ply < PLY_MAX);
1926 ss[ply].pv[ply] = ss[ply].currentMove;
1928 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1929 ss[ply].pv[p] = ss[ply+1].pv[p];
1930 ss[ply].pv[p] = MOVE_NONE;
1934 // sp_update_pv() is a variant of update_pv for use at split points. The
1935 // difference between the two functions is that sp_update_pv also updates
1936 // the PV at the parent node.
1938 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1939 assert(ply >= 0 && ply < PLY_MAX);
1941 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1943 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1944 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1945 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1949 // connected_moves() tests whether two moves are 'connected' in the sense
1950 // that the first move somehow made the second move possible (for instance
1951 // if the moving piece is the same in both moves). The first move is
1952 // assumed to be the move that was made to reach the current position, while
1953 // the second move is assumed to be a move from the current position.
1955 bool connected_moves(const Position &pos, Move m1, Move m2) {
1956 Square f1, t1, f2, t2;
1958 assert(move_is_ok(m1));
1959 assert(move_is_ok(m2));
1964 // Case 1: The moving piece is the same in both moves.
1970 // Case 2: The destination square for m2 was vacated by m1.
1976 // Case 3: Moving through the vacated square:
1977 if(piece_is_slider(pos.piece_on(f2)) &&
1978 bit_is_set(squares_between(f2, t2), f1))
1981 // Case 4: The destination square for m2 is attacked by the moving piece
1983 if(pos.piece_attacks_square(t1, t2))
1986 // Case 5: Discovered check, checking piece is the piece moved in m1:
1987 if(piece_is_slider(pos.piece_on(t1)) &&
1988 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1990 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1992 Bitboard occ = pos.occupied_squares();
1993 Color us = pos.side_to_move();
1994 Square ksq = pos.king_square(us);
1995 clear_bit(&occ, f2);
1996 if(pos.type_of_piece_on(t1) == BISHOP) {
1997 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2000 else if(pos.type_of_piece_on(t1) == ROOK) {
2001 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2005 assert(pos.type_of_piece_on(t1) == QUEEN);
2006 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2015 // extension() decides whether a move should be searched with normal depth,
2016 // or with extended depth. Certain classes of moves (checking moves, in
2017 // particular) are searched with bigger depth than ordinary moves.
2019 Depth extension(const Position &pos, Move m, bool pvNode,
2020 bool check, bool singleReply, bool mateThreat) {
2022 Depth result = Depth(0);
2025 result += CheckExtension[pvNode];
2028 result += SingleReplyExtension[pvNode];
2030 if (pos.move_is_pawn_push_to_7th(m))
2031 result += PawnPushTo7thExtension[pvNode];
2033 if (pos.move_is_passed_pawn_push(m))
2034 result += PassedPawnExtension[pvNode];
2037 result += MateThreatExtension[pvNode];
2039 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
\r
2040 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
\r
2041 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
\r
2042 && !move_promotion(m))
2043 result += PawnEndgameExtension[pvNode];
2046 && pos.move_is_capture(m)
2047 && pos.type_of_piece_on(move_to(m)) != PAWN
2051 return Min(result, OnePly);
2055 // ok_to_do_nullmove() looks at the current position and decides whether
2056 // doing a 'null move' should be allowed. In order to avoid zugzwang
2057 // problems, null moves are not allowed when the side to move has very
2058 // little material left. Currently, the test is a bit too simple: Null
2059 // moves are avoided only when the side to move has only pawns left. It's
2060 // probably a good idea to avoid null moves in at least some more
2061 // complicated endgames, e.g. KQ vs KR. FIXME
2063 bool ok_to_do_nullmove(const Position &pos) {
2064 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2070 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2071 // non-tactical moves late in the move list close to the leaves are
2072 // candidates for pruning.
2074 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2075 Square mfrom, mto, tfrom, tto;
2077 assert(move_is_ok(m));
2078 assert(threat == MOVE_NONE || move_is_ok(threat));
2079 assert(!move_promotion(m));
2080 assert(!pos.move_is_check(m));
2081 assert(!pos.move_is_capture(m));
2082 assert(!pos.move_is_passed_pawn_push(m));
2083 assert(d >= OnePly);
2085 mfrom = move_from(m);
2087 tfrom = move_from(threat);
2088 tto = move_to(threat);
2090 // Case 1: Castling moves are never pruned.
2091 if(move_is_castle(m))
2094 // Case 2: Don't prune moves which move the threatened piece
2095 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2098 // Case 3: If the threatened piece has value less than or equal to the
2099 // value of the threatening piece, don't prune move which defend it.
2100 if(!PruneDefendingMoves && threat != MOVE_NONE
2101 && (piece_value_midgame(pos.piece_on(tfrom))
2102 >= piece_value_midgame(pos.piece_on(tto)))
2103 && pos.move_attacks_square(m, tto))
2106 // Case 4: Don't prune moves with good history.
2107 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2110 // Case 5: If the moving piece in the threatened move is a slider, don't
2111 // prune safe moves which block its ray.
2112 if(!PruneBlockingMoves && threat != MOVE_NONE
2113 && piece_is_slider(pos.piece_on(tfrom))
2114 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2121 // ok_to_use_TT() returns true if a transposition table score
2122 // can be used at a given point in search.
2124 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2126 Value v = value_from_tt(tte->value(), ply);
2128 return ( tte->depth() >= depth
2129 || v >= Max(value_mate_in(100), beta)
2130 || v < Min(value_mated_in(100), beta))
2132 && ( (is_lower_bound(tte->type()) && v >= beta)
2133 || (is_upper_bound(tte->type()) && v < beta));
2137 // ok_to_history() returns true if a move m can be stored
2138 // in history. Should be a non capturing move.
2140 bool ok_to_history(const Position& pos, Move m) {
2142 return pos.square_is_empty(move_to(m))
2143 && !move_promotion(m)
2148 // update_history() registers a good move that produced a beta-cutoff
2149 // in history and marks as failures all the other moves of that ply.
2151 void update_history(const Position& pos, Move m, Depth depth,
2152 Move movesSearched[], int moveCount) {
2154 H.success(pos.piece_on(move_from(m)), m, depth);
2156 for (int i = 0; i < moveCount - 1; i++)
2157 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2158 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2161 // fail_high_ply_1() checks if some thread is currently resolving a fail
2162 // high at ply 1 at the node below the first root node. This information
2163 // is used for time managment.
2165 bool fail_high_ply_1() {
2166 for(int i = 0; i < ActiveThreads; i++)
2167 if(Threads[i].failHighPly1)
2173 // current_search_time() returns the number of milliseconds which have passed
2174 // since the beginning of the current search.
2176 int current_search_time() {
2177 return get_system_time() - SearchStartTime;
2181 // nps() computes the current nodes/second count.
2184 int t = current_search_time();
2185 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2189 // poll() performs two different functions: It polls for user input, and it
2190 // looks at the time consumed so far and decides if it's time to abort the
2195 static int lastInfoTime;
2196 int t = current_search_time();
2201 // We are line oriented, don't read single chars
2202 std::string command;
2203 if (!std::getline(std::cin, command))
2206 if (command == "quit")
2209 PonderSearch = false;
2212 else if(command == "stop")
2215 PonderSearch = false;
2217 else if(command == "ponderhit")
2220 // Print search information
2224 else if (lastInfoTime > t)
2225 // HACK: Must be a new search where we searched less than
2226 // NodesBetweenPolls nodes during the first second of search.
2229 else if (t - lastInfoTime >= 1000)
2236 if (dbg_show_hit_rate)
2237 dbg_print_hit_rate();
2239 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2240 << " time " << t << " hashfull " << TT.full() << std::endl;
2241 lock_release(&IOLock);
2242 if (ShowCurrentLine)
2243 Threads[0].printCurrentLine = true;
2245 // Should we stop the search?
2249 bool overTime = t > AbsoluteMaxSearchTime
2250 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2251 || ( !FailHigh && !fail_high_ply_1() && !Problem
2252 && t > 6*(MaxSearchTime + ExtraSearchTime));
2254 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2255 || (ExactMaxTime && t >= ExactMaxTime)
2256 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2261 // ponderhit() is called when the program is pondering (i.e. thinking while
2262 // it's the opponent's turn to move) in order to let the engine know that
2263 // it correctly predicted the opponent's move.
2266 int t = current_search_time();
2267 PonderSearch = false;
2268 if(Iteration >= 2 &&
2269 (!InfiniteSearch && (StopOnPonderhit ||
2270 t > AbsoluteMaxSearchTime ||
2271 (RootMoveNumber == 1 &&
2272 t > MaxSearchTime + ExtraSearchTime) ||
2273 (!FailHigh && !fail_high_ply_1() && !Problem &&
2274 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2279 // print_current_line() prints the current line of search for a given
2280 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2282 void print_current_line(SearchStack ss[], int ply, int threadID) {
2283 assert(ply >= 0 && ply < PLY_MAX);
2284 assert(threadID >= 0 && threadID < ActiveThreads);
2286 if(!Threads[threadID].idle) {
2288 std::cout << "info currline " << (threadID + 1);
2289 for(int p = 0; p < ply; p++)
2290 std::cout << " " << ss[p].currentMove;
2291 std::cout << std::endl;
2292 lock_release(&IOLock);
2294 Threads[threadID].printCurrentLine = false;
2295 if(threadID + 1 < ActiveThreads)
2296 Threads[threadID + 1].printCurrentLine = true;
2300 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2301 // while the program is pondering. The point is to work around a wrinkle in
2302 // the UCI protocol: When pondering, the engine is not allowed to give a
2303 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2304 // We simply wait here until one of these commands is sent, and return,
2305 // after which the bestmove and pondermove will be printed (in id_loop()).
2307 void wait_for_stop_or_ponderhit() {
2308 std::string command;
2311 if(!std::getline(std::cin, command))
2314 if(command == "quit") {
2315 OpeningBook.close();
2320 else if(command == "ponderhit" || command == "stop")
2326 // idle_loop() is where the threads are parked when they have no work to do.
2327 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2328 // object for which the current thread is the master.
2330 void idle_loop(int threadID, SplitPoint *waitSp) {
2331 assert(threadID >= 0 && threadID < THREAD_MAX);
2333 Threads[threadID].running = true;
2336 if(AllThreadsShouldExit && threadID != 0)
2339 // If we are not thinking, wait for a condition to be signaled instead
2340 // of wasting CPU time polling for work:
2341 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2342 #if !defined(_MSC_VER)
2343 pthread_mutex_lock(&WaitLock);
2344 if(Idle || threadID >= ActiveThreads)
2345 pthread_cond_wait(&WaitCond, &WaitLock);
2346 pthread_mutex_unlock(&WaitLock);
2348 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2352 // If this thread has been assigned work, launch a search:
2353 if(Threads[threadID].workIsWaiting) {
2354 Threads[threadID].workIsWaiting = false;
2355 if(Threads[threadID].splitPoint->pvNode)
2356 sp_search_pv(Threads[threadID].splitPoint, threadID);
2358 sp_search(Threads[threadID].splitPoint, threadID);
2359 Threads[threadID].idle = true;
2362 // If this thread is the master of a split point and all threads have
2363 // finished their work at this split point, return from the idle loop:
2364 if(waitSp != NULL && waitSp->cpus == 0)
2368 Threads[threadID].running = false;
2372 // init_split_point_stack() is called during program initialization, and
2373 // initializes all split point objects.
2375 void init_split_point_stack() {
2376 for(int i = 0; i < THREAD_MAX; i++)
2377 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2378 SplitPointStack[i][j].parent = NULL;
2379 lock_init(&(SplitPointStack[i][j].lock), NULL);
2384 // destroy_split_point_stack() is called when the program exits, and
2385 // destroys all locks in the precomputed split point objects.
2387 void destroy_split_point_stack() {
2388 for(int i = 0; i < THREAD_MAX; i++)
2389 for(int j = 0; j < MaxActiveSplitPoints; j++)
2390 lock_destroy(&(SplitPointStack[i][j].lock));
2394 // thread_should_stop() checks whether the thread with a given threadID has
2395 // been asked to stop, directly or indirectly. This can happen if a beta
2396 // cutoff has occured in thre thread's currently active split point, or in
2397 // some ancestor of the current split point.
2399 bool thread_should_stop(int threadID) {
2400 assert(threadID >= 0 && threadID < ActiveThreads);
2404 if(Threads[threadID].stop)
2406 if(ActiveThreads <= 2)
2408 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2410 Threads[threadID].stop = true;
2417 // thread_is_available() checks whether the thread with threadID "slave" is
2418 // available to help the thread with threadID "master" at a split point. An
2419 // obvious requirement is that "slave" must be idle. With more than two
2420 // threads, this is not by itself sufficient: If "slave" is the master of
2421 // some active split point, it is only available as a slave to the other
2422 // threads which are busy searching the split point at the top of "slave"'s
2423 // split point stack (the "helpful master concept" in YBWC terminology).
2425 bool thread_is_available(int slave, int master) {
2426 assert(slave >= 0 && slave < ActiveThreads);
2427 assert(master >= 0 && master < ActiveThreads);
2428 assert(ActiveThreads > 1);
2430 if(!Threads[slave].idle || slave == master)
2433 if(Threads[slave].activeSplitPoints == 0)
2434 // No active split points means that the thread is available as a slave
2435 // for any other thread.
2438 if(ActiveThreads == 2)
2441 // Apply the "helpful master" concept if possible.
2442 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2449 // idle_thread_exists() tries to find an idle thread which is available as
2450 // a slave for the thread with threadID "master".
2452 bool idle_thread_exists(int master) {
2453 assert(master >= 0 && master < ActiveThreads);
2454 assert(ActiveThreads > 1);
2456 for(int i = 0; i < ActiveThreads; i++)
2457 if(thread_is_available(i, master))
2463 // split() does the actual work of distributing the work at a node between
2464 // several threads at PV nodes. If it does not succeed in splitting the
2465 // node (because no idle threads are available, or because we have no unused
2466 // split point objects), the function immediately returns false. If
2467 // splitting is possible, a SplitPoint object is initialized with all the
2468 // data that must be copied to the helper threads (the current position and
2469 // search stack, alpha, beta, the search depth, etc.), and we tell our
2470 // helper threads that they have been assigned work. This will cause them
2471 // to instantly leave their idle loops and call sp_search_pv(). When all
2472 // threads have returned from sp_search_pv (or, equivalently, when
2473 // splitPoint->cpus becomes 0), split() returns true.
2475 bool split(const Position &p, SearchStack *sstck, int ply,
2476 Value *alpha, Value *beta, Value *bestValue,
2477 Depth depth, int *moves,
2478 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2480 assert(sstck != NULL);
2481 assert(ply >= 0 && ply < PLY_MAX);
2482 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2483 assert(!pvNode || *alpha < *beta);
2484 assert(*beta <= VALUE_INFINITE);
2485 assert(depth > Depth(0));
2486 assert(master >= 0 && master < ActiveThreads);
2487 assert(ActiveThreads > 1);
2489 SplitPoint *splitPoint;
2494 // If no other thread is available to help us, or if we have too many
2495 // active split points, don't split:
2496 if(!idle_thread_exists(master) ||
2497 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2498 lock_release(&MPLock);
2502 // Pick the next available split point object from the split point stack:
2503 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2504 Threads[master].activeSplitPoints++;
2506 // Initialize the split point object:
2507 splitPoint->parent = Threads[master].splitPoint;
2508 splitPoint->finished = false;
2509 splitPoint->ply = ply;
2510 splitPoint->depth = depth;
2511 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2512 splitPoint->beta = *beta;
2513 splitPoint->pvNode = pvNode;
2514 splitPoint->dcCandidates = dcCandidates;
2515 splitPoint->bestValue = *bestValue;
2516 splitPoint->master = master;
2517 splitPoint->mp = mp;
2518 splitPoint->moves = *moves;
2519 splitPoint->cpus = 1;
2520 splitPoint->pos.copy(p);
2521 splitPoint->parentSstack = sstck;
2522 for(i = 0; i < ActiveThreads; i++)
2523 splitPoint->slaves[i] = 0;
2525 // Copy the current position and the search stack to the master thread:
2526 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2527 Threads[master].splitPoint = splitPoint;
2529 // Make copies of the current position and search stack for each thread:
2530 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2532 if(thread_is_available(i, master)) {
2533 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2534 Threads[i].splitPoint = splitPoint;
2535 splitPoint->slaves[i] = 1;
2539 // Tell the threads that they have work to do. This will make them leave
2541 for(i = 0; i < ActiveThreads; i++)
2542 if(i == master || splitPoint->slaves[i]) {
2543 Threads[i].workIsWaiting = true;
2544 Threads[i].idle = false;
2545 Threads[i].stop = false;
2548 lock_release(&MPLock);
2550 // Everything is set up. The master thread enters the idle loop, from
2551 // which it will instantly launch a search, because its workIsWaiting
2552 // slot is 'true'. We send the split point as a second parameter to the
2553 // idle loop, which means that the main thread will return from the idle
2554 // loop when all threads have finished their work at this split point
2555 // (i.e. when // splitPoint->cpus == 0).
2556 idle_loop(master, splitPoint);
2558 // We have returned from the idle loop, which means that all threads are
2559 // finished. Update alpha, beta and bestvalue, and return:
2561 if(pvNode) *alpha = splitPoint->alpha;
2562 *beta = splitPoint->beta;
2563 *bestValue = splitPoint->bestValue;
2564 Threads[master].stop = false;
2565 Threads[master].idle = false;
2566 Threads[master].activeSplitPoints--;
2567 Threads[master].splitPoint = splitPoint->parent;
2568 lock_release(&MPLock);
2574 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2575 // to start a new search from the root.
2577 void wake_sleeping_threads() {
2578 if(ActiveThreads > 1) {
2579 for(int i = 1; i < ActiveThreads; i++) {
2580 Threads[i].idle = true;
2581 Threads[i].workIsWaiting = false;
2583 #if !defined(_MSC_VER)
2584 pthread_mutex_lock(&WaitLock);
2585 pthread_cond_broadcast(&WaitCond);
2586 pthread_mutex_unlock(&WaitLock);
2588 for(int i = 1; i < THREAD_MAX; i++)
2589 SetEvent(SitIdleEvent[i]);
2595 // init_thread() is the function which is called when a new thread is
2596 // launched. It simply calls the idle_loop() function with the supplied
2597 // threadID. There are two versions of this function; one for POSIX threads
2598 // and one for Windows threads.
2600 #if !defined(_MSC_VER)
2602 void *init_thread(void *threadID) {
2603 idle_loop(*(int *)threadID, NULL);
2609 DWORD WINAPI init_thread(LPVOID threadID) {
2610 idle_loop(*(int *)threadID, NULL);