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")) {
316 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
318 OpeningBook.open("book.bin");
320 bookMove = OpeningBook.get_move(pos);
321 if(bookMove != MOVE_NONE) {
322 std::cout << "bestmove " << bookMove << std::endl;
327 // Initialize global search variables:
329 SearchStartTime = get_system_time();
330 BestRootMove = MOVE_NONE;
331 PonderMove = MOVE_NONE;
332 EasyMove = MOVE_NONE;
333 for(int i = 0; i < THREAD_MAX; i++) {
334 Threads[i].nodes = 0ULL;
335 Threads[i].failHighPly1 = false;
338 InfiniteSearch = infinite;
339 PonderSearch = ponder;
340 StopOnPonderhit = false;
345 ExactMaxTime = maxTime;
347 // Read UCI option values:
348 TT.set_size(get_option_value_int("Hash"));
349 if(button_was_pressed("Clear Hash"))
351 PonderingEnabled = get_option_value_bool("Ponder");
352 MultiPV = get_option_value_int("MultiPV");
354 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
356 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
357 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
358 SingleReplyExtension[0] =
359 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
360 PawnPushTo7thExtension[1] =
361 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
362 PawnPushTo7thExtension[0] =
363 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
364 PassedPawnExtension[1] =
365 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
366 PassedPawnExtension[0] =
367 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
368 PawnEndgameExtension[1] =
369 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
370 PawnEndgameExtension[0] =
371 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
372 MateThreatExtension[1] =
373 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
374 MateThreatExtension[0] =
375 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(),
387 std::ios::out | std::ios::app);
389 UseQSearchFutilityPruning =
390 get_option_value_bool("Futility Pruning (Quiescence Search)");
392 get_option_value_bool("Futility Pruning (Main Search)");
395 value_from_centipawns(get_option_value_int("Futility Margin 0"));
397 value_from_centipawns(get_option_value_int("Futility Margin 1"));
399 value_from_centipawns(get_option_value_int("Futility Margin 2"));
401 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
402 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
404 UseLSNFiltering = get_option_value_bool("LSN filtering");
405 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
406 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
408 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
409 MaxThreadsPerSplitPoint =
410 get_option_value_int("Maximum Number of Threads per Split Point");
412 read_weights(pos.side_to_move());
414 int newActiveThreads = get_option_value_int("Threads");
415 if(newActiveThreads != ActiveThreads) {
416 ActiveThreads = newActiveThreads;
417 init_eval(ActiveThreads);
420 // Wake up sleeping threads:
421 wake_sleeping_threads();
423 for(int i = 1; i < ActiveThreads; i++)
424 assert(thread_is_available(i, 0));
426 // Set thinking time:
427 int myTime = time[side_to_move];
428 int myIncrement = increment[side_to_move];
429 int oppTime = time[1 - side_to_move];
431 TimeAdvantage = myTime - oppTime;
433 if(!movesToGo) { // Sudden death time control
435 MaxSearchTime = myTime / 30 + myIncrement;
436 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
438 else { // Blitz game without increment
439 MaxSearchTime = myTime / 40;
440 AbsoluteMaxSearchTime = myTime / 8;
443 else { // (x moves) / (y minutes)
445 MaxSearchTime = myTime / 2;
446 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
449 MaxSearchTime = myTime / Min(movesToGo, 20);
450 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
453 if(PonderingEnabled) {
454 MaxSearchTime += MaxSearchTime / 4;
455 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
458 // Fixed depth or fixed number of nodes?
461 InfiniteSearch = true; // HACK
465 NodesBetweenPolls = Min(MaxNodes, 30000);
466 InfiniteSearch = true; // HACK
469 NodesBetweenPolls = 30000;
472 // Write information to search log file:
474 LogFile << "Searching: " << pos.to_fen() << '\n';
475 LogFile << "infinite: " << infinite << " ponder: " << ponder
476 << " time: " << myTime << " increment: " << myIncrement
477 << " moves to go: " << movesToGo << '\n';
480 // We're ready to start thinking. Call the iterative deepening loop
484 Value v = id_loop(pos, searchMoves);
485 looseOnTime = ( UseLSNFiltering
492 looseOnTime = false; // reset for next match
493 while (SearchStartTime + myTime + 1000 > get_system_time())
495 id_loop(pos, searchMoves); // to fail gracefully
512 /// init_threads() is called during startup. It launches all helper threads,
513 /// and initializes the split point stack and the global locks and condition
516 void init_threads() {
518 #if !defined(_MSC_VER)
519 pthread_t pthread[1];
522 for(i = 0; i < THREAD_MAX; i++)
523 Threads[i].activeSplitPoints = 0;
525 // Initialize global locks:
526 lock_init(&MPLock, NULL);
527 lock_init(&IOLock, NULL);
529 init_split_point_stack();
531 #if !defined(_MSC_VER)
532 pthread_mutex_init(&WaitLock, NULL);
533 pthread_cond_init(&WaitCond, NULL);
535 for(i = 0; i < THREAD_MAX; i++)
536 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
539 // All threads except the main thread should be initialized to idle state:
540 for(i = 1; i < THREAD_MAX; i++) {
541 Threads[i].stop = false;
542 Threads[i].workIsWaiting = false;
543 Threads[i].idle = true;
544 Threads[i].running = false;
547 // Launch the helper threads:
548 for(i = 1; i < THREAD_MAX; i++) {
549 #if !defined(_MSC_VER)
550 pthread_create(pthread, NULL, init_thread, (void*)(&i));
554 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
558 // Wait until the thread has finished launching:
559 while(!Threads[i].running);
564 /// stop_threads() is called when the program exits. It makes all the
565 /// helper threads exit cleanly.
567 void stop_threads() {
568 ActiveThreads = THREAD_MAX; // HACK
569 Idle = false; // HACK
570 wake_sleeping_threads();
571 AllThreadsShouldExit = true;
572 for(int i = 1; i < THREAD_MAX; i++) {
573 Threads[i].stop = true;
574 while(Threads[i].running);
576 destroy_split_point_stack();
580 /// nodes_searched() returns the total number of nodes searched so far in
581 /// the current search.
583 int64_t nodes_searched() {
584 int64_t result = 0ULL;
585 for(int i = 0; i < ActiveThreads; i++)
586 result += Threads[i].nodes;
593 // id_loop() is the main iterative deepening loop. It calls root_search
594 // repeatedly with increasing depth until the allocated thinking time has
595 // been consumed, the user stops the search, or the maximum search depth is
598 Value id_loop(const Position &pos, Move searchMoves[]) {
600 SearchStack ss[PLY_MAX_PLUS_2];
602 // searchMoves are verified, copied, scored and sorted
603 RootMoveList rml(p, searchMoves);
608 init_search_stack(ss);
610 ValueByIteration[0] = Value(0);
611 ValueByIteration[1] = rml.get_move_score(0);
614 EasyMove = rml.scan_for_easy_move();
616 // Iterative deepening loop
617 while(!AbortSearch && Iteration < PLY_MAX) {
619 // Initialize iteration
622 BestMoveChangesByIteration[Iteration] = 0;
626 std::cout << "info depth " << Iteration << std::endl;
628 // Search to the current depth
629 ValueByIteration[Iteration] = root_search(p, ss, rml);
631 // Erase the easy move if it differs from the new best move
632 if(ss[0].pv[0] != EasyMove)
633 EasyMove = MOVE_NONE;
637 if(!InfiniteSearch) {
639 bool stopSearch = false;
641 // Stop search early if there is only a single legal move:
642 if(Iteration >= 6 && rml.move_count() == 1)
645 // Stop search early when the last two iterations returned a mate
648 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
649 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
652 // Stop search early if one move seems to be much better than the
654 int64_t nodes = nodes_searched();
655 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
656 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
657 current_search_time() > MaxSearchTime / 16) ||
658 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
659 current_search_time() > MaxSearchTime / 32)))
662 // Add some extra time if the best move has changed during the last
664 if(Iteration > 5 && Iteration <= 50)
666 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
667 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
669 // If we need some more and we are in time advantage take it.
670 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
671 ExtraSearchTime += MaxSearchTime / 2;
673 // Stop search if most of MaxSearchTime is consumed at the end of the
674 // iteration. We probably don't have enough time to search the first
675 // move at the next iteration anyway.
676 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
683 StopOnPonderhit = true;
687 // Write PV to transposition table, in case the relevant entries have
688 // been overwritten during the search:
689 TT.insert_pv(p, ss[0].pv);
691 if(MaxDepth && Iteration >= MaxDepth)
697 // If we are pondering, we shouldn't print the best move before we
700 wait_for_stop_or_ponderhit();
702 // Print final search statistics
703 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
704 << " time " << current_search_time()
705 << " hashfull " << TT.full() << std::endl;
707 // Print the best move and the ponder move to the standard output:
708 std::cout << "bestmove " << ss[0].pv[0];
709 if(ss[0].pv[1] != MOVE_NONE)
710 std::cout << " ponder " << ss[0].pv[1];
711 std::cout << std::endl;
715 LogFile << "Nodes: " << nodes_searched() << '\n';
716 LogFile << "Nodes/second: " << nps() << '\n';
717 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
718 p.do_move(ss[0].pv[0], u);
719 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
720 LogFile << std::endl;
722 return rml.get_move_score(0);
726 // root_search() is the function which searches the root node. It is
727 // similar to search_pv except that it uses a different move ordering
728 // scheme (perhaps we should try to use this at internal PV nodes, too?)
729 // and prints some information to the standard output.
731 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
732 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
733 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
735 // Loop through all the moves in the root move list:
736 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
742 RootMoveNumber = i + 1;
745 // Remember the node count before the move is searched. The node counts
746 // are used to sort the root moves at the next iteration.
747 nodes = nodes_searched();
749 // Pick the next root move, and print the move and the move number to
750 // the standard output:
751 move = ss[0].currentMove = rml.get_move(i);
752 if(current_search_time() >= 1000)
753 std::cout << "info currmove " << move
754 << " currmovenumber " << i + 1 << std::endl;
756 // Decide search depth for this move:
757 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
758 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
760 // Make the move, and search it.
761 pos.do_move(move, u, dcCandidates);
764 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
765 // If the value has dropped a lot compared to the last iteration,
766 // set the boolean variable Problem to true. This variable is used
767 // for time managment: When Problem is true, we try to complete the
768 // current iteration before playing a move.
769 Problem = (Iteration >= 2 &&
770 value <= ValueByIteration[Iteration-1] - ProblemMargin);
771 if(Problem && StopOnPonderhit)
772 StopOnPonderhit = false;
775 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
777 // Fail high! Set the boolean variable FailHigh to true, and
778 // re-search the move with a big window. The variable FailHigh is
779 // used for time managment: We try to avoid aborting the search
780 // prematurely during a fail high research.
782 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
786 pos.undo_move(move, u);
788 // Finished searching the move. If AbortSearch is true, the search
789 // was aborted because the user interrupted the search or because we
790 // ran out of time. In this case, the return value of the search cannot
791 // be trusted, and we break out of the loop without updating the best
796 // Remember the node count for this move. The node counts are used to
797 // sort the root moves at the next iteration.
798 rml.set_move_nodes(i, nodes_searched() - nodes);
800 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
802 if(value <= alpha && i >= MultiPV)
803 rml.set_move_score(i, -VALUE_INFINITE);
808 rml.set_move_score(i, value);
810 rml.set_move_pv(i, ss[0].pv);
813 // We record how often the best move has been changed in each
814 // iteration. This information is used for time managment: When
815 // the best move changes frequently, we allocate some more time.
817 BestMoveChangesByIteration[Iteration]++;
819 // Print search information to the standard output:
820 std::cout << "info depth " << Iteration
821 << " score " << value_to_string(value)
822 << " time " << current_search_time()
823 << " nodes " << nodes_searched()
826 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
827 std::cout << ss[0].pv[j] << " ";
828 std::cout << std::endl;
831 LogFile << pretty_pv(pos, current_search_time(), Iteration,
832 nodes_searched(), value, ss[0].pv)
837 // Reset the global variable Problem to false if the value isn't too
838 // far below the final value from the last iteration.
839 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
842 else { // MultiPV > 1
844 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
846 std::cout << "info multipv " << j + 1
847 << " score " << value_to_string(rml.get_move_score(j))
848 << " depth " << ((j <= i)? Iteration : Iteration - 1)
849 << " time " << current_search_time()
850 << " nodes " << nodes_searched()
853 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
854 std::cout << rml.get_move_pv(j, k) << " ";
855 std::cout << std::endl;
857 alpha = rml.get_move_score(Min(i, MultiPV-1));
865 // search_pv() is the main search function for PV nodes.
867 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
868 Depth depth, int ply, int threadID) {
870 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
871 assert(beta > alpha && beta <= VALUE_INFINITE);
872 assert(ply >= 0 && ply < PLY_MAX);
873 assert(threadID >= 0 && threadID < ActiveThreads);
877 // Initialize, and make an early exit in case of an aborted search,
878 // an instant draw, maximum ply reached, etc.
879 Value oldAlpha = alpha;
881 if (AbortSearch || thread_should_stop(threadID))
885 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
887 init_node(pos, ss, ply, threadID);
892 if (ply >= PLY_MAX - 1)
893 return evaluate(pos, ei, threadID);
895 // Mate distance pruning
896 alpha = Max(value_mated_in(ply), alpha);
897 beta = Min(value_mate_in(ply+1), beta);
901 // Transposition table lookup. At PV nodes, we don't use the TT for
902 // pruning, but only for move ordering.
903 const TTEntry* tte = TT.retrieve(pos);
905 Move ttMove = (tte ? tte->move() : MOVE_NONE);
907 // Go with internal iterative deepening if we don't have a TT move
908 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
910 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
911 ttMove = ss[ply].pv[ply];
914 // Initialize a MovePicker object for the current position, and prepare
915 // to search all moves:
916 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
917 ss[ply].killer1, ss[ply].killer2, depth);
919 Move move, movesSearched[256];
921 Value value, bestValue = -VALUE_INFINITE;
922 Bitboard dcCandidates = mp.discovered_check_candidates();
923 bool mateThreat = MateThreatExtension[1] > Depth(0)
924 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
926 // Loop through all legal moves until no moves remain or a beta cutoff
929 && (move = mp.get_next_move()) != MOVE_NONE
930 && !thread_should_stop(threadID))
932 assert(move_is_ok(move));
934 bool lastMinuteSurprise = (depth <= OnePly && mp.current_move_type() == MovePicker::PH_GOOD_CAPTURES);
935 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
936 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
937 bool moveIsCapture = pos.move_is_capture(move);
938 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
940 movesSearched[moveCount++] = ss[ply].currentMove = move;
942 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
943 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
945 // Decide the new search depth
946 Depth ext = extension(pos, move, true, moveIsCheck, singleReply || lastMinuteSurprise, mateThreat);
947 Depth newDepth = depth - OnePly + ext;
949 // Make and search the move
951 pos.do_move(move, u, dcCandidates);
953 if (moveCount == 1) // The first move in list is the PV
954 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
957 // Try to reduce non-pv search depth by one ply if move seems not problematic,
958 // if the move fails high will be re-searched at full depth.
959 if ( depth >= 2*OnePly
961 && moveCount >= LMRPVMoves
963 && !move_promotion(move)
964 && !moveIsPassedPawnPush
965 && !move_is_castle(move)
966 && move != ss[ply].killer1
967 && move != ss[ply].killer2)
969 ss[ply].reduction = OnePly;
970 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
973 value = alpha + 1; // Just to trigger next condition
975 if (value > alpha) // Go with full depth pv search
977 ss[ply].reduction = Depth(0);
978 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
979 if (value > alpha && value < beta)
981 // When the search fails high at ply 1 while searching the first
982 // move at the root, set the flag failHighPly1. This is used for
983 // time managment: We don't want to stop the search early in
984 // such cases, because resolving the fail high at ply 1 could
985 // result in a big drop in score at the root.
986 if (ply == 1 && RootMoveNumber == 1)
987 Threads[threadID].failHighPly1 = true;
989 // A fail high occurred. Re-search at full window (pv search)
990 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
991 Threads[threadID].failHighPly1 = false;
995 pos.undo_move(move, u);
997 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1000 if (value > bestValue)
1007 if (value == value_mate_in(ply + 1))
1008 ss[ply].mateKiller = move;
1010 // If we are at ply 1, and we are searching the first root move at
1011 // ply 0, set the 'Problem' variable if the score has dropped a lot
1012 // (from the computer's point of view) since the previous iteration:
1013 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1018 if ( ActiveThreads > 1
1020 && depth >= MinimumSplitDepth
1022 && idle_thread_exists(threadID)
1024 && !thread_should_stop(threadID)
1025 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1026 &moveCount, &mp, dcCandidates, threadID, true))
1030 // All legal moves have been searched. A special case: If there were
1031 // no legal moves, it must be mate or stalemate:
1033 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1035 // If the search is not aborted, update the transposition table,
1036 // history counters, and killer moves.
1037 if (AbortSearch || thread_should_stop(threadID))
1040 if (bestValue <= oldAlpha)
1041 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1043 else if (bestValue >= beta)
1045 Move m = ss[ply].pv[ply];
1046 if (ok_to_history(pos, m)) // Only non capture moves are considered
1048 update_history(pos, m, depth, movesSearched, moveCount);
1049 if (m != ss[ply].killer1)
1051 ss[ply].killer2 = ss[ply].killer1;
1052 ss[ply].killer1 = m;
1055 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1058 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1064 // search() is the search function for zero-width nodes.
1066 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1067 int ply, bool allowNullmove, int threadID) {
1069 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1070 assert(ply >= 0 && ply < PLY_MAX);
1071 assert(threadID >= 0 && threadID < ActiveThreads);
1075 // Initialize, and make an early exit in case of an aborted search,
1076 // an instant draw, maximum ply reached, etc.
1077 if (AbortSearch || thread_should_stop(threadID))
1081 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1083 init_node(pos, ss, ply, threadID);
1088 if (ply >= PLY_MAX - 1)
1089 return evaluate(pos, ei, threadID);
1091 // Mate distance pruning
1092 if (value_mated_in(ply) >= beta)
1095 if (value_mate_in(ply + 1) < beta)
1098 // Transposition table lookup
1099 const TTEntry* tte = TT.retrieve(pos);
1101 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1103 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1105 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1106 return value_from_tt(tte->value(), ply);
1109 Value approximateEval = quick_evaluate(pos);
1110 bool mateThreat = false;
1115 && ok_to_do_nullmove(pos)
1116 && approximateEval >= beta - NullMoveMargin)
1118 ss[ply].currentMove = MOVE_NULL;
1121 pos.do_null_move(u);
1122 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1123 pos.undo_null_move(u);
1125 if (nullValue >= beta)
1127 if (depth < 6 * OnePly)
1130 // Do zugzwang verification search
1131 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1135 // The null move failed low, which means that we may be faced with
1136 // some kind of threat. If the previous move was reduced, check if
1137 // the move that refuted the null move was somehow connected to the
1138 // move which was reduced. If a connection is found, return a fail
1139 // low score (which will cause the reduced move to fail high in the
1140 // parent node, which will trigger a re-search with full depth).
1141 if (nullValue == value_mated_in(ply + 2))
1144 ss[ply].threatMove = ss[ply + 1].currentMove;
1145 if ( depth < ThreatDepth
1146 && ss[ply - 1].reduction
1147 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1151 // Null move search not allowed, try razoring
1152 else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth)
1153 ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly))
1155 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1160 // Go with internal iterative deepening if we don't have a TT move
1161 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1162 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1164 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1165 ttMove = ss[ply].pv[ply];
1168 // Initialize a MovePicker object for the current position, and prepare
1169 // to search all moves:
1170 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1171 ss[ply].killer1, ss[ply].killer2, depth);
1173 Move move, movesSearched[256];
1175 Value value, bestValue = -VALUE_INFINITE;
1176 Bitboard dcCandidates = mp.discovered_check_candidates();
1177 Value futilityValue = VALUE_NONE;
1178 bool isCheck = pos.is_check();
1179 bool useFutilityPruning = UseFutilityPruning
1180 && depth < SelectiveDepth
1183 // Loop through all legal moves until no moves remain or a beta cutoff
1185 while ( bestValue < beta
1186 && (move = mp.get_next_move()) != MOVE_NONE
1187 && !thread_should_stop(threadID))
1189 assert(move_is_ok(move));
1191 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1192 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1193 bool moveIsCapture = pos.move_is_capture(move);
1194 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1196 movesSearched[moveCount++] = ss[ply].currentMove = move;
1198 // Decide the new search depth
1199 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1200 Depth newDepth = depth - OnePly + ext;
1203 if ( useFutilityPruning
1206 && !moveIsPassedPawnPush
1207 && !move_promotion(move))
1209 if ( moveCount >= 2 + int(depth)
1210 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1213 if (depth < 3 * OnePly && approximateEval < beta)
1215 if (futilityValue == VALUE_NONE)
1216 futilityValue = evaluate(pos, ei, threadID)
1217 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1219 if (futilityValue < beta)
1221 if (futilityValue > bestValue)
1222 bestValue = futilityValue;
1228 // Make and search the move
1230 pos.do_move(move, u, dcCandidates);
1232 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1233 // if the move fails high will be re-searched at full depth.
1234 if ( depth >= 2*OnePly
1236 && moveCount >= LMRNonPVMoves
1238 && !move_promotion(move)
1239 && !moveIsPassedPawnPush
1240 && !move_is_castle(move)
1241 && move != ss[ply].killer1
1242 && move != ss[ply].killer2)
1244 ss[ply].reduction = OnePly;
1245 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1248 value = beta; // Just to trigger next condition
1250 if (value >= beta) // Go with full depth non-pv search
1252 ss[ply].reduction = Depth(0);
1253 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1255 pos.undo_move(move, u);
1257 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1260 if (value > bestValue)
1266 if (value == value_mate_in(ply + 1))
1267 ss[ply].mateKiller = move;
1271 if ( ActiveThreads > 1
1273 && depth >= MinimumSplitDepth
1275 && idle_thread_exists(threadID)
1277 && !thread_should_stop(threadID)
1278 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1279 &mp, dcCandidates, threadID, false))
1283 // All legal moves have been searched. A special case: If there were
1284 // no legal moves, it must be mate or stalemate:
1286 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1288 // If the search is not aborted, update the transposition table,
1289 // history counters, and killer moves.
1290 if (AbortSearch || thread_should_stop(threadID))
1293 if (bestValue < beta)
1294 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1297 Move m = ss[ply].pv[ply];
1298 if (ok_to_history(pos, m)) // Only non capture moves are considered
1300 update_history(pos, m, depth, movesSearched, moveCount);
1301 if (m != ss[ply].killer1)
1303 ss[ply].killer2 = ss[ply].killer1;
1304 ss[ply].killer1 = m;
1307 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1313 // qsearch() is the quiescence search function, which is called by the main
1314 // search function when the remaining depth is zero (or, to be more precise,
1315 // less than OnePly).
1317 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1318 Depth depth, int ply, int threadID) {
1320 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1321 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1323 assert(ply >= 0 && ply < PLY_MAX);
1324 assert(threadID >= 0 && threadID < ActiveThreads);
1328 // Initialize, and make an early exit in case of an aborted search,
1329 // an instant draw, maximum ply reached, etc.
1330 if (AbortSearch || thread_should_stop(threadID))
1333 init_node(pos, ss, ply, threadID);
1338 // Transposition table lookup
1339 const TTEntry* tte = TT.retrieve(pos);
1340 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1341 return value_from_tt(tte->value(), ply);
1343 // Evaluate the position statically:
1344 Value staticValue = evaluate(pos, ei, threadID);
1346 if (ply == PLY_MAX - 1)
1349 // Initialize "stand pat score", and return it immediately if it is
1351 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1353 if (bestValue >= beta)
1356 if (bestValue > alpha)
1359 // Initialize a MovePicker object for the current position, and prepare
1360 // to search the moves. Because the depth is <= 0 here, only captures,
1361 // queen promotions and checks (only if depth == 0) will be generated.
1362 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1366 Bitboard dcCandidates = mp.discovered_check_candidates();
1367 bool isCheck = pos.is_check();
1369 // Loop through the moves until no moves remain or a beta cutoff
1371 while ( alpha < beta
1372 && (move = mp.get_next_move()) != MOVE_NONE)
1374 assert(move_is_ok(move));
1376 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1377 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1380 ss[ply].currentMove = move;
1383 if ( UseQSearchFutilityPruning
1386 && !move_promotion(move)
1387 && !moveIsPassedPawnPush
1388 && beta - alpha == 1
1389 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1391 Value futilityValue = staticValue
1392 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1393 pos.endgame_value_of_piece_on(move_to(move)))
1395 + ei.futilityMargin;
1397 if (futilityValue < alpha)
1399 if (futilityValue > bestValue)
1400 bestValue = futilityValue;
1405 // Don't search captures and checks with negative SEE values.
1407 && !move_promotion(move)
1408 && (pos.midgame_value_of_piece_on(move_from(move)) >
1409 pos.midgame_value_of_piece_on(move_to(move)))
1410 && pos.see(move) < 0)
1413 // Make and search the move.
1415 pos.do_move(move, u, dcCandidates);
1416 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1417 pos.undo_move(move, u);
1419 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1422 if (value > bestValue)
1433 // All legal moves have been searched. A special case: If we're in check
1434 // and no legal moves were found, it is checkmate:
1435 if (pos.is_check() && moveCount == 0) // Mate!
1436 return value_mated_in(ply);
1438 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1440 // Update transposition table
1441 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1447 // sp_search() is used to search from a split point. This function is called
1448 // by each thread working at the split point. It is similar to the normal
1449 // search() function, but simpler. Because we have already probed the hash
1450 // table, done a null move search, and searched the first move before
1451 // splitting, we don't have to repeat all this work in sp_search(). We
1452 // also don't need to store anything to the hash table here: This is taken
1453 // care of after we return from the split point.
1455 void sp_search(SplitPoint *sp, int threadID) {
1457 assert(threadID >= 0 && threadID < ActiveThreads);
1458 assert(ActiveThreads > 1);
1460 Position pos = Position(sp->pos);
1461 SearchStack *ss = sp->sstack[threadID];
1464 bool isCheck = pos.is_check();
1465 bool useFutilityPruning = UseFutilityPruning
1466 && sp->depth < SelectiveDepth
1469 while ( sp->bestValue < sp->beta
1470 && !thread_should_stop(threadID)
1471 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1473 assert(move_is_ok(move));
1475 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1476 bool moveIsCapture = pos.move_is_capture(move);
1477 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1479 lock_grab(&(sp->lock));
1480 int moveCount = ++sp->moves;
1481 lock_release(&(sp->lock));
1483 ss[sp->ply].currentMove = move;
1485 // Decide the new search depth.
1486 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1487 Depth newDepth = sp->depth - OnePly + ext;
1490 if ( useFutilityPruning
1493 && !moveIsPassedPawnPush
1494 && !move_promotion(move)
1495 && moveCount >= 2 + int(sp->depth)
1496 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1499 // Make and search the move.
1501 pos.do_move(move, u, sp->dcCandidates);
1503 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1504 // if the move fails high will be re-searched at full depth.
1505 if ( ext == Depth(0)
1506 && moveCount >= LMRNonPVMoves
1508 && !moveIsPassedPawnPush
1509 && !move_promotion(move)
1510 && !move_is_castle(move)
1511 && move != ss[sp->ply].killer1
1512 && move != ss[sp->ply].killer2)
1514 ss[sp->ply].reduction = OnePly;
1515 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1518 value = sp->beta; // Just to trigger next condition
1520 if (value >= sp->beta) // Go with full depth non-pv search
1522 ss[sp->ply].reduction = Depth(0);
1523 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1525 pos.undo_move(move, u);
1527 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1529 if (thread_should_stop(threadID))
1533 lock_grab(&(sp->lock));
1534 if (value > sp->bestValue && !thread_should_stop(threadID))
1536 sp->bestValue = value;
1537 if (sp->bestValue >= sp->beta)
1539 sp_update_pv(sp->parentSstack, ss, sp->ply);
1540 for (int i = 0; i < ActiveThreads; i++)
1541 if (i != threadID && (i == sp->master || sp->slaves[i]))
1542 Threads[i].stop = true;
1544 sp->finished = true;
1547 lock_release(&(sp->lock));
1550 lock_grab(&(sp->lock));
1552 // If this is the master thread and we have been asked to stop because of
1553 // a beta cutoff higher up in the tree, stop all slave threads:
1554 if (sp->master == threadID && thread_should_stop(threadID))
1555 for (int i = 0; i < ActiveThreads; i++)
1557 Threads[i].stop = true;
1560 sp->slaves[threadID] = 0;
1562 lock_release(&(sp->lock));
1566 // sp_search_pv() is used to search from a PV split point. This function
1567 // is called by each thread working at the split point. It is similar to
1568 // the normal search_pv() function, but simpler. Because we have already
1569 // probed the hash table and searched the first move before splitting, we
1570 // don't have to repeat all this work in sp_search_pv(). We also don't
1571 // need to store anything to the hash table here: This is taken care of
1572 // after we return from the split point.
1574 void sp_search_pv(SplitPoint *sp, int threadID) {
1576 assert(threadID >= 0 && threadID < ActiveThreads);
1577 assert(ActiveThreads > 1);
1579 Position pos = Position(sp->pos);
1580 SearchStack *ss = sp->sstack[threadID];
1584 while ( sp->alpha < sp->beta
1585 && !thread_should_stop(threadID)
1586 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1588 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1589 bool moveIsCapture = pos.move_is_capture(move);
1590 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1592 assert(move_is_ok(move));
1594 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1595 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1597 lock_grab(&(sp->lock));
1598 int moveCount = ++sp->moves;
1599 lock_release(&(sp->lock));
1601 ss[sp->ply].currentMove = move;
1603 // Decide the new search depth.
1604 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1605 Depth newDepth = sp->depth - OnePly + ext;
1607 // Make and search the move.
1609 pos.do_move(move, u, sp->dcCandidates);
1611 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1612 // if the move fails high will be re-searched at full depth.
1613 if ( ext == Depth(0)
1614 && moveCount >= LMRPVMoves
1616 && !moveIsPassedPawnPush
1617 && !move_promotion(move)
1618 && !move_is_castle(move)
1619 && move != ss[sp->ply].killer1
1620 && move != ss[sp->ply].killer2)
1622 ss[sp->ply].reduction = OnePly;
1623 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1626 value = sp->alpha + 1; // Just to trigger next condition
1628 if (value > sp->alpha) // Go with full depth non-pv search
1630 ss[sp->ply].reduction = Depth(0);
1631 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1633 if (value > sp->alpha && value < sp->beta)
1635 // When the search fails high at ply 1 while searching the first
1636 // move at the root, set the flag failHighPly1. This is used for
1637 // time managment: We don't want to stop the search early in
1638 // such cases, because resolving the fail high at ply 1 could
1639 // result in a big drop in score at the root.
1640 if (sp->ply == 1 && RootMoveNumber == 1)
1641 Threads[threadID].failHighPly1 = true;
1643 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1644 Threads[threadID].failHighPly1 = false;
1647 pos.undo_move(move, u);
1649 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1651 if (thread_should_stop(threadID))
1655 lock_grab(&(sp->lock));
1656 if (value > sp->bestValue && !thread_should_stop(threadID))
1658 sp->bestValue = value;
1659 if (value > sp->alpha)
1662 sp_update_pv(sp->parentSstack, ss, sp->ply);
1663 if (value == value_mate_in(sp->ply + 1))
1664 ss[sp->ply].mateKiller = move;
1666 if(value >= sp->beta)
1668 for(int i = 0; i < ActiveThreads; i++)
1669 if(i != threadID && (i == sp->master || sp->slaves[i]))
1670 Threads[i].stop = true;
1672 sp->finished = true;
1675 // If we are at ply 1, and we are searching the first root move at
1676 // ply 0, set the 'Problem' variable if the score has dropped a lot
1677 // (from the computer's point of view) since the previous iteration:
1678 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1681 lock_release(&(sp->lock));
1684 lock_grab(&(sp->lock));
1686 // If this is the master thread and we have been asked to stop because of
1687 // a beta cutoff higher up in the tree, stop all slave threads:
1688 if (sp->master == threadID && thread_should_stop(threadID))
1689 for (int i = 0; i < ActiveThreads; i++)
1691 Threads[i].stop = true;
1694 sp->slaves[threadID] = 0;
1696 lock_release(&(sp->lock));
1700 /// The RootMove class
1704 RootMove::RootMove() {
1705 nodes = cumulativeNodes = 0ULL;
1708 // RootMove::operator<() is the comparison function used when
1709 // sorting the moves. A move m1 is considered to be better
1710 // than a move m2 if it has a higher score, or if the moves
1711 // have equal score but m1 has the higher node count.
1713 bool RootMove::operator<(const RootMove& m) {
1715 if (score != m.score)
1716 return (score < m.score);
1718 return nodes <= m.nodes;
1721 /// The RootMoveList class
1725 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1727 MoveStack mlist[MaxRootMoves];
1728 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1730 // Generate all legal moves
1731 int lm_count = generate_legal_moves(pos, mlist);
1733 // Add each move to the moves[] array
1734 for (int i = 0; i < lm_count; i++)
1736 bool includeMove = includeAllMoves;
1738 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1739 includeMove = (searchMoves[k] == mlist[i].move);
1743 // Find a quick score for the move
1745 SearchStack ss[PLY_MAX_PLUS_2];
1747 moves[count].move = mlist[i].move;
1748 moves[count].nodes = 0ULL;
1749 pos.do_move(moves[count].move, u);
1750 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1752 pos.undo_move(moves[count].move, u);
1753 moves[count].pv[0] = moves[i].move;
1754 moves[count].pv[1] = MOVE_NONE; // FIXME
1762 // Simple accessor methods for the RootMoveList class
1764 inline Move RootMoveList::get_move(int moveNum) const {
1765 return moves[moveNum].move;
1768 inline Value RootMoveList::get_move_score(int moveNum) const {
1769 return moves[moveNum].score;
1772 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1773 moves[moveNum].score = score;
1776 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1777 moves[moveNum].nodes = nodes;
1778 moves[moveNum].cumulativeNodes += nodes;
1781 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1783 for(j = 0; pv[j] != MOVE_NONE; j++)
1784 moves[moveNum].pv[j] = pv[j];
1785 moves[moveNum].pv[j] = MOVE_NONE;
1788 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1789 return moves[moveNum].pv[i];
1792 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1793 return moves[moveNum].cumulativeNodes;
1796 inline int RootMoveList::move_count() const {
1801 // RootMoveList::scan_for_easy_move() is called at the end of the first
1802 // iteration, and is used to detect an "easy move", i.e. a move which appears
1803 // to be much bester than all the rest. If an easy move is found, the move
1804 // is returned, otherwise the function returns MOVE_NONE. It is very
1805 // important that this function is called at the right moment: The code
1806 // assumes that the first iteration has been completed and the moves have
1807 // been sorted. This is done in RootMoveList c'tor.
1809 Move RootMoveList::scan_for_easy_move() const {
1816 // moves are sorted so just consider the best and the second one
1817 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1823 // RootMoveList::sort() sorts the root move list at the beginning of a new
1826 inline void RootMoveList::sort() {
1828 sort_multipv(count - 1); // all items
1832 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1833 // list by their scores and depths. It is used to order the different PVs
1834 // correctly in MultiPV mode.
1836 void RootMoveList::sort_multipv(int n) {
1838 for (int i = 1; i <= n; i++)
1840 RootMove rm = moves[i];
1842 for (j = i; j > 0 && moves[j-1] < rm; j--)
1843 moves[j] = moves[j-1];
1849 // init_search_stack() initializes a search stack at the beginning of a
1850 // new search from the root.
1852 void init_search_stack(SearchStack ss[]) {
1853 for(int i = 0; i < 3; i++) {
1854 ss[i].pv[i] = MOVE_NONE;
1855 ss[i].pv[i+1] = MOVE_NONE;
1856 ss[i].currentMove = MOVE_NONE;
1857 ss[i].mateKiller = MOVE_NONE;
1858 ss[i].killer1 = MOVE_NONE;
1859 ss[i].killer2 = MOVE_NONE;
1860 ss[i].threatMove = MOVE_NONE;
1861 ss[i].reduction = Depth(0);
1866 // init_node() is called at the beginning of all the search functions
1867 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1868 // stack object corresponding to the current node. Once every
1869 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1870 // for user input and checks whether it is time to stop the search.
1872 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1873 assert(ply >= 0 && ply < PLY_MAX);
1874 assert(threadID >= 0 && threadID < ActiveThreads);
1876 Threads[threadID].nodes++;
1880 if(NodesSincePoll >= NodesBetweenPolls) {
1886 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1887 ss[ply+2].mateKiller = MOVE_NONE;
1888 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1889 ss[ply].threatMove = MOVE_NONE;
1890 ss[ply].reduction = Depth(0);
1891 ss[ply].currentMoveCaptureValue = Value(0);
1893 if(Threads[threadID].printCurrentLine)
1894 print_current_line(ss, ply, threadID);
1898 // update_pv() is called whenever a search returns a value > alpha. It
1899 // updates the PV in the SearchStack object corresponding to the current
1902 void update_pv(SearchStack ss[], int ply) {
1903 assert(ply >= 0 && ply < PLY_MAX);
1905 ss[ply].pv[ply] = ss[ply].currentMove;
1907 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1908 ss[ply].pv[p] = ss[ply+1].pv[p];
1909 ss[ply].pv[p] = MOVE_NONE;
1913 // sp_update_pv() is a variant of update_pv for use at split points. The
1914 // difference between the two functions is that sp_update_pv also updates
1915 // the PV at the parent node.
1917 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1918 assert(ply >= 0 && ply < PLY_MAX);
1920 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1922 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1923 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1924 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1928 // connected_moves() tests whether two moves are 'connected' in the sense
1929 // that the first move somehow made the second move possible (for instance
1930 // if the moving piece is the same in both moves). The first move is
1931 // assumed to be the move that was made to reach the current position, while
1932 // the second move is assumed to be a move from the current position.
1934 bool connected_moves(const Position &pos, Move m1, Move m2) {
1935 Square f1, t1, f2, t2;
1937 assert(move_is_ok(m1));
1938 assert(move_is_ok(m2));
1943 // Case 1: The moving piece is the same in both moves.
1949 // Case 2: The destination square for m2 was vacated by m1.
1955 // Case 3: Moving through the vacated square:
1956 if(piece_is_slider(pos.piece_on(f2)) &&
1957 bit_is_set(squares_between(f2, t2), f1))
1960 // Case 4: The destination square for m2 is attacked by the moving piece
1962 if(pos.piece_attacks_square(t1, t2))
1965 // Case 5: Discovered check, checking piece is the piece moved in m1:
1966 if(piece_is_slider(pos.piece_on(t1)) &&
1967 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1969 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1971 Bitboard occ = pos.occupied_squares();
1972 Color us = pos.side_to_move();
1973 Square ksq = pos.king_square(us);
1974 clear_bit(&occ, f2);
1975 if(pos.type_of_piece_on(t1) == BISHOP) {
1976 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1979 else if(pos.type_of_piece_on(t1) == ROOK) {
1980 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1984 assert(pos.type_of_piece_on(t1) == QUEEN);
1985 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1994 // extension() decides whether a move should be searched with normal depth,
1995 // or with extended depth. Certain classes of moves (checking moves, in
1996 // particular) are searched with bigger depth than ordinary moves.
1998 Depth extension(const Position &pos, Move m, bool pvNode,
1999 bool check, bool singleReply, bool mateThreat) {
2001 Depth result = Depth(0);
2004 result += CheckExtension[pvNode];
2007 result += SingleReplyExtension[pvNode];
2009 if (pos.move_is_pawn_push_to_7th(m))
2010 result += PawnPushTo7thExtension[pvNode];
2012 if (pos.move_is_passed_pawn_push(m))
2013 result += PassedPawnExtension[pvNode];
2016 result += MateThreatExtension[pvNode];
2018 if ( pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
\r
2019 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
\r
2020 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
\r
2021 && !move_promotion(m))
2022 result += PawnEndgameExtension[pvNode];
2025 && pos.move_is_capture(m)
2026 && pos.type_of_piece_on(move_to(m)) != PAWN
2030 return Min(result, OnePly);
2034 // ok_to_do_nullmove() looks at the current position and decides whether
2035 // doing a 'null move' should be allowed. In order to avoid zugzwang
2036 // problems, null moves are not allowed when the side to move has very
2037 // little material left. Currently, the test is a bit too simple: Null
2038 // moves are avoided only when the side to move has only pawns left. It's
2039 // probably a good idea to avoid null moves in at least some more
2040 // complicated endgames, e.g. KQ vs KR. FIXME
2042 bool ok_to_do_nullmove(const Position &pos) {
2043 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2049 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2050 // non-tactical moves late in the move list close to the leaves are
2051 // candidates for pruning.
2053 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2054 Square mfrom, mto, tfrom, tto;
2056 assert(move_is_ok(m));
2057 assert(threat == MOVE_NONE || move_is_ok(threat));
2058 assert(!move_promotion(m));
2059 assert(!pos.move_is_check(m));
2060 assert(!pos.move_is_capture(m));
2061 assert(!pos.move_is_passed_pawn_push(m));
2062 assert(d >= OnePly);
2064 mfrom = move_from(m);
2066 tfrom = move_from(threat);
2067 tto = move_to(threat);
2069 // Case 1: Castling moves are never pruned.
2070 if(move_is_castle(m))
2073 // Case 2: Don't prune moves which move the threatened piece
2074 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2077 // Case 3: If the threatened piece has value less than or equal to the
2078 // value of the threatening piece, don't prune move which defend it.
2079 if(!PruneDefendingMoves && threat != MOVE_NONE
2080 && (piece_value_midgame(pos.piece_on(tfrom))
2081 >= piece_value_midgame(pos.piece_on(tto)))
2082 && pos.move_attacks_square(m, tto))
2085 // Case 4: Don't prune moves with good history.
2086 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2089 // Case 5: If the moving piece in the threatened move is a slider, don't
2090 // prune safe moves which block its ray.
2091 if(!PruneBlockingMoves && threat != MOVE_NONE
2092 && piece_is_slider(pos.piece_on(tfrom))
2093 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2100 // ok_to_use_TT() returns true if a transposition table score
2101 // can be used at a given point in search.
2103 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2105 Value v = value_from_tt(tte->value(), ply);
2107 return ( tte->depth() >= depth
2108 || v >= Max(value_mate_in(100), beta)
2109 || v < Min(value_mated_in(100), beta))
2111 && ( (is_lower_bound(tte->type()) && v >= beta)
2112 || (is_upper_bound(tte->type()) && v < beta));
2116 // ok_to_history() returns true if a move m can be stored
2117 // in history. Should be a non capturing move.
2119 bool ok_to_history(const Position& pos, Move m) {
2121 return pos.square_is_empty(move_to(m))
2122 && !move_promotion(m)
2127 // update_history() registers a good move that produced a beta-cutoff
2128 // in history and marks as failures all the other moves of that ply.
2130 void update_history(const Position& pos, Move m, Depth depth,
2131 Move movesSearched[], int moveCount) {
2133 H.success(pos.piece_on(move_from(m)), m, depth);
2135 for (int i = 0; i < moveCount - 1; i++)
2136 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2137 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2140 // fail_high_ply_1() checks if some thread is currently resolving a fail
2141 // high at ply 1 at the node below the first root node. This information
2142 // is used for time managment.
2144 bool fail_high_ply_1() {
2145 for(int i = 0; i < ActiveThreads; i++)
2146 if(Threads[i].failHighPly1)
2152 // current_search_time() returns the number of milliseconds which have passed
2153 // since the beginning of the current search.
2155 int current_search_time() {
2156 return get_system_time() - SearchStartTime;
2160 // nps() computes the current nodes/second count.
2163 int t = current_search_time();
2164 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2168 // poll() performs two different functions: It polls for user input, and it
2169 // looks at the time consumed so far and decides if it's time to abort the
2174 static int lastInfoTime;
2175 int t = current_search_time();
2180 // We are line oriented, don't read single chars
2181 std::string command;
2182 if (!std::getline(std::cin, command))
2185 if (command == "quit")
2188 PonderSearch = false;
2191 else if(command == "stop")
2194 PonderSearch = false;
2196 else if(command == "ponderhit")
2199 // Print search information
2203 else if (lastInfoTime > t)
2204 // HACK: Must be a new search where we searched less than
2205 // NodesBetweenPolls nodes during the first second of search.
2208 else if (t - lastInfoTime >= 1000)
2215 if (dbg_show_hit_rate)
2216 dbg_print_hit_rate();
2218 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2219 << " time " << t << " hashfull " << TT.full() << std::endl;
2220 lock_release(&IOLock);
2221 if (ShowCurrentLine)
2222 Threads[0].printCurrentLine = true;
2224 // Should we stop the search?
2228 bool overTime = t > AbsoluteMaxSearchTime
2229 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2230 || ( !FailHigh && !fail_high_ply_1() && !Problem
2231 && t > 6*(MaxSearchTime + ExtraSearchTime));
2233 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2234 || (ExactMaxTime && t >= ExactMaxTime)
2235 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2240 // ponderhit() is called when the program is pondering (i.e. thinking while
2241 // it's the opponent's turn to move) in order to let the engine know that
2242 // it correctly predicted the opponent's move.
2245 int t = current_search_time();
2246 PonderSearch = false;
2247 if(Iteration >= 2 &&
2248 (!InfiniteSearch && (StopOnPonderhit ||
2249 t > AbsoluteMaxSearchTime ||
2250 (RootMoveNumber == 1 &&
2251 t > MaxSearchTime + ExtraSearchTime) ||
2252 (!FailHigh && !fail_high_ply_1() && !Problem &&
2253 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2258 // print_current_line() prints the current line of search for a given
2259 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2261 void print_current_line(SearchStack ss[], int ply, int threadID) {
2262 assert(ply >= 0 && ply < PLY_MAX);
2263 assert(threadID >= 0 && threadID < ActiveThreads);
2265 if(!Threads[threadID].idle) {
2267 std::cout << "info currline " << (threadID + 1);
2268 for(int p = 0; p < ply; p++)
2269 std::cout << " " << ss[p].currentMove;
2270 std::cout << std::endl;
2271 lock_release(&IOLock);
2273 Threads[threadID].printCurrentLine = false;
2274 if(threadID + 1 < ActiveThreads)
2275 Threads[threadID + 1].printCurrentLine = true;
2279 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2280 // while the program is pondering. The point is to work around a wrinkle in
2281 // the UCI protocol: When pondering, the engine is not allowed to give a
2282 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2283 // We simply wait here until one of these commands is sent, and return,
2284 // after which the bestmove and pondermove will be printed (in id_loop()).
2286 void wait_for_stop_or_ponderhit() {
2287 std::string command;
2290 if(!std::getline(std::cin, command))
2293 if(command == "quit") {
2294 OpeningBook.close();
2299 else if(command == "ponderhit" || command == "stop")
2305 // idle_loop() is where the threads are parked when they have no work to do.
2306 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2307 // object for which the current thread is the master.
2309 void idle_loop(int threadID, SplitPoint *waitSp) {
2310 assert(threadID >= 0 && threadID < THREAD_MAX);
2312 Threads[threadID].running = true;
2315 if(AllThreadsShouldExit && threadID != 0)
2318 // If we are not thinking, wait for a condition to be signaled instead
2319 // of wasting CPU time polling for work:
2320 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2321 #if !defined(_MSC_VER)
2322 pthread_mutex_lock(&WaitLock);
2323 if(Idle || threadID >= ActiveThreads)
2324 pthread_cond_wait(&WaitCond, &WaitLock);
2325 pthread_mutex_unlock(&WaitLock);
2327 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2331 // If this thread has been assigned work, launch a search:
2332 if(Threads[threadID].workIsWaiting) {
2333 Threads[threadID].workIsWaiting = false;
2334 if(Threads[threadID].splitPoint->pvNode)
2335 sp_search_pv(Threads[threadID].splitPoint, threadID);
2337 sp_search(Threads[threadID].splitPoint, threadID);
2338 Threads[threadID].idle = true;
2341 // If this thread is the master of a split point and all threads have
2342 // finished their work at this split point, return from the idle loop:
2343 if(waitSp != NULL && waitSp->cpus == 0)
2347 Threads[threadID].running = false;
2351 // init_split_point_stack() is called during program initialization, and
2352 // initializes all split point objects.
2354 void init_split_point_stack() {
2355 for(int i = 0; i < THREAD_MAX; i++)
2356 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2357 SplitPointStack[i][j].parent = NULL;
2358 lock_init(&(SplitPointStack[i][j].lock), NULL);
2363 // destroy_split_point_stack() is called when the program exits, and
2364 // destroys all locks in the precomputed split point objects.
2366 void destroy_split_point_stack() {
2367 for(int i = 0; i < THREAD_MAX; i++)
2368 for(int j = 0; j < MaxActiveSplitPoints; j++)
2369 lock_destroy(&(SplitPointStack[i][j].lock));
2373 // thread_should_stop() checks whether the thread with a given threadID has
2374 // been asked to stop, directly or indirectly. This can happen if a beta
2375 // cutoff has occured in thre thread's currently active split point, or in
2376 // some ancestor of the current split point.
2378 bool thread_should_stop(int threadID) {
2379 assert(threadID >= 0 && threadID < ActiveThreads);
2383 if(Threads[threadID].stop)
2385 if(ActiveThreads <= 2)
2387 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2389 Threads[threadID].stop = true;
2396 // thread_is_available() checks whether the thread with threadID "slave" is
2397 // available to help the thread with threadID "master" at a split point. An
2398 // obvious requirement is that "slave" must be idle. With more than two
2399 // threads, this is not by itself sufficient: If "slave" is the master of
2400 // some active split point, it is only available as a slave to the other
2401 // threads which are busy searching the split point at the top of "slave"'s
2402 // split point stack (the "helpful master concept" in YBWC terminology).
2404 bool thread_is_available(int slave, int master) {
2405 assert(slave >= 0 && slave < ActiveThreads);
2406 assert(master >= 0 && master < ActiveThreads);
2407 assert(ActiveThreads > 1);
2409 if(!Threads[slave].idle || slave == master)
2412 if(Threads[slave].activeSplitPoints == 0)
2413 // No active split points means that the thread is available as a slave
2414 // for any other thread.
2417 if(ActiveThreads == 2)
2420 // Apply the "helpful master" concept if possible.
2421 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2428 // idle_thread_exists() tries to find an idle thread which is available as
2429 // a slave for the thread with threadID "master".
2431 bool idle_thread_exists(int master) {
2432 assert(master >= 0 && master < ActiveThreads);
2433 assert(ActiveThreads > 1);
2435 for(int i = 0; i < ActiveThreads; i++)
2436 if(thread_is_available(i, master))
2442 // split() does the actual work of distributing the work at a node between
2443 // several threads at PV nodes. If it does not succeed in splitting the
2444 // node (because no idle threads are available, or because we have no unused
2445 // split point objects), the function immediately returns false. If
2446 // splitting is possible, a SplitPoint object is initialized with all the
2447 // data that must be copied to the helper threads (the current position and
2448 // search stack, alpha, beta, the search depth, etc.), and we tell our
2449 // helper threads that they have been assigned work. This will cause them
2450 // to instantly leave their idle loops and call sp_search_pv(). When all
2451 // threads have returned from sp_search_pv (or, equivalently, when
2452 // splitPoint->cpus becomes 0), split() returns true.
2454 bool split(const Position &p, SearchStack *sstck, int ply,
2455 Value *alpha, Value *beta, Value *bestValue,
2456 Depth depth, int *moves,
2457 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2459 assert(sstck != NULL);
2460 assert(ply >= 0 && ply < PLY_MAX);
2461 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2462 assert(!pvNode || *alpha < *beta);
2463 assert(*beta <= VALUE_INFINITE);
2464 assert(depth > Depth(0));
2465 assert(master >= 0 && master < ActiveThreads);
2466 assert(ActiveThreads > 1);
2468 SplitPoint *splitPoint;
2473 // If no other thread is available to help us, or if we have too many
2474 // active split points, don't split:
2475 if(!idle_thread_exists(master) ||
2476 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2477 lock_release(&MPLock);
2481 // Pick the next available split point object from the split point stack:
2482 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2483 Threads[master].activeSplitPoints++;
2485 // Initialize the split point object:
2486 splitPoint->parent = Threads[master].splitPoint;
2487 splitPoint->finished = false;
2488 splitPoint->ply = ply;
2489 splitPoint->depth = depth;
2490 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2491 splitPoint->beta = *beta;
2492 splitPoint->pvNode = pvNode;
2493 splitPoint->dcCandidates = dcCandidates;
2494 splitPoint->bestValue = *bestValue;
2495 splitPoint->master = master;
2496 splitPoint->mp = mp;
2497 splitPoint->moves = *moves;
2498 splitPoint->cpus = 1;
2499 splitPoint->pos.copy(p);
2500 splitPoint->parentSstack = sstck;
2501 for(i = 0; i < ActiveThreads; i++)
2502 splitPoint->slaves[i] = 0;
2504 // Copy the current position and the search stack to the master thread:
2505 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2506 Threads[master].splitPoint = splitPoint;
2508 // Make copies of the current position and search stack for each thread:
2509 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2511 if(thread_is_available(i, master)) {
2512 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2513 Threads[i].splitPoint = splitPoint;
2514 splitPoint->slaves[i] = 1;
2518 // Tell the threads that they have work to do. This will make them leave
2520 for(i = 0; i < ActiveThreads; i++)
2521 if(i == master || splitPoint->slaves[i]) {
2522 Threads[i].workIsWaiting = true;
2523 Threads[i].idle = false;
2524 Threads[i].stop = false;
2527 lock_release(&MPLock);
2529 // Everything is set up. The master thread enters the idle loop, from
2530 // which it will instantly launch a search, because its workIsWaiting
2531 // slot is 'true'. We send the split point as a second parameter to the
2532 // idle loop, which means that the main thread will return from the idle
2533 // loop when all threads have finished their work at this split point
2534 // (i.e. when // splitPoint->cpus == 0).
2535 idle_loop(master, splitPoint);
2537 // We have returned from the idle loop, which means that all threads are
2538 // finished. Update alpha, beta and bestvalue, and return:
2540 if(pvNode) *alpha = splitPoint->alpha;
2541 *beta = splitPoint->beta;
2542 *bestValue = splitPoint->bestValue;
2543 Threads[master].stop = false;
2544 Threads[master].idle = false;
2545 Threads[master].activeSplitPoints--;
2546 Threads[master].splitPoint = splitPoint->parent;
2547 lock_release(&MPLock);
2553 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2554 // to start a new search from the root.
2556 void wake_sleeping_threads() {
2557 if(ActiveThreads > 1) {
2558 for(int i = 1; i < ActiveThreads; i++) {
2559 Threads[i].idle = true;
2560 Threads[i].workIsWaiting = false;
2562 #if !defined(_MSC_VER)
2563 pthread_mutex_lock(&WaitLock);
2564 pthread_cond_broadcast(&WaitCond);
2565 pthread_mutex_unlock(&WaitLock);
2567 for(int i = 1; i < THREAD_MAX; i++)
2568 SetEvent(SitIdleEvent[i]);
2574 // init_thread() is the function which is called when a new thread is
2575 // launched. It simply calls the idle_loop() function with the supplied
2576 // threadID. There are two versions of this function; one for POSIX threads
2577 // and one for Windows threads.
2579 #if !defined(_MSC_VER)
2581 void *init_thread(void *threadID) {
2582 idle_loop(*(int *)threadID, NULL);
2588 DWORD WINAPI init_thread(LPVOID threadID) {
2589 idle_loop(*(int *)threadID, NULL);