2 Glaurung, a UCI chess playing engine.
3 Copyright (C) 2004-2008 Tord Romstad
5 Glaurung is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Glaurung is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
38 #include "ucioption.h"
42 //// Local definitions
49 // The RootMove class is used for moves at the root at the tree. For each
50 // root move, we store a score, a node count, and a PV (really a refutation
51 // in the case of moves which fail low).
56 bool operator<(const RootMove&); // used to sort
60 int64_t nodes, cumulativeNodes;
61 Move pv[PLY_MAX_PLUS_2];
65 // The RootMoveList class is essentially an array of RootMove objects, with
66 // a handful of methods for accessing the data in the individual moves.
71 RootMoveList(Position &pos, Move searchMoves[]);
72 Move get_move(int moveNum) const;
73 Value get_move_score(int moveNum) const;
74 void set_move_score(int moveNum, Value score);
75 void set_move_nodes(int moveNum, int64_t nodes);
76 void set_move_pv(int moveNum, const Move pv[]);
77 Move get_move_pv(int moveNum, int i) const;
78 int64_t get_move_cumulative_nodes(int moveNum) const;
79 int move_count() const;
80 Move scan_for_easy_move() const;
82 void sort_multipv(int n);
85 static const int MaxRootMoves = 500;
86 RootMove moves[MaxRootMoves];
91 /// Constants and variables
93 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
96 int LMRNonPVMoves = 4;
98 // Depth limit for use of dynamic threat detection:
99 Depth ThreatDepth = 5*OnePly;
101 // Depth limit for selective search:
102 Depth SelectiveDepth = 7*OnePly;
104 // Use internal iterative deepening?
105 const bool UseIIDAtPVNodes = true;
106 const bool UseIIDAtNonPVNodes = false;
108 // Internal iterative deepening margin. At Non-PV moves, when
109 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
110 // when the static evaluation is at most IIDMargin below beta.
111 const Value IIDMargin = Value(0x100);
114 const bool UseEasyMove = true;
116 // Easy move margin. An easy move candidate must be at least this much
117 // better than the second best move.
118 const Value EasyMoveMargin = Value(0x200);
120 // Problem margin. If the score of the first move at iteration N+1 has
121 // dropped by more than this since iteration N, the boolean variable
122 // "Problem" is set to true, which will make the program spend some extra
123 // time looking for a better move.
124 const Value ProblemMargin = Value(0x28);
126 // No problem margin. If the boolean "Problem" is true, and a new move
127 // is found at the root which is less than NoProblemMargin worse than the
128 // best move from the previous iteration, Problem is set back to false.
129 const Value NoProblemMargin = Value(0x14);
131 // Null move margin. A null move search will not be done if the approximate
132 // evaluation of the position is more than NullMoveMargin below beta.
133 const Value NullMoveMargin = Value(0x300);
135 // Pruning criterions. See the code and comments in ok_to_prune() to
136 // understand their precise meaning.
137 const bool PruneEscapeMoves = false;
138 const bool PruneDefendingMoves = false;
139 const bool PruneBlockingMoves = false;
141 // Use futility pruning?
142 bool UseQSearchFutilityPruning = true;
143 bool UseFutilityPruning = true;
145 // Margins for futility pruning in the quiescence search, at frontier
146 // nodes, and at pre-frontier nodes:
147 Value FutilityMargin0 = Value(0x80);
148 Value FutilityMargin1 = Value(0x100);
149 Value FutilityMargin2 = Value(0x300);
152 Depth RazorDepth = 4*OnePly;
153 Value RazorMargin = Value(0x300);
155 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
156 Depth CheckExtension[2] = {OnePly, OnePly};
157 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
158 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
159 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
160 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
161 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
163 // Search depth at iteration 1:
164 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
168 int NodesBetweenPolls = 30000;
170 // Iteration counter:
173 // Scores and number of times the best move changed for each iteration:
174 Value ValueByIteration[PLY_MAX_PLUS_2];
175 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
180 // Time managment variables
182 int MaxNodes, MaxDepth;
183 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage;
184 Move BestRootMove, PonderMove, EasyMove;
188 bool StopOnPonderhit;
193 bool PonderingEnabled;
196 // Show current line?
197 bool ShowCurrentLine = false;
200 bool UseLogFile = false;
201 std::ofstream LogFile;
203 // MP related variables
204 Depth MinimumSplitDepth = 4*OnePly;
205 int MaxThreadsPerSplitPoint = 4;
206 Thread Threads[THREAD_MAX];
208 bool AllThreadsShouldExit = false;
209 const int MaxActiveSplitPoints = 8;
210 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
213 #if !defined(_MSC_VER)
214 pthread_cond_t WaitCond;
215 pthread_mutex_t WaitLock;
217 HANDLE SitIdleEvent[THREAD_MAX];
223 void id_loop(const Position &pos, Move searchMoves[]);
224 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
225 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
226 Depth depth, int ply, int threadID);
227 Value search(Position &pos, SearchStack ss[], Value beta,
228 Depth depth, int ply, bool allowNullmove, int threadID);
229 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
230 Depth depth, int ply, int threadID);
231 void sp_search(SplitPoint *sp, int threadID);
232 void sp_search_pv(SplitPoint *sp, int threadID);
233 void init_search_stack(SearchStack ss[]);
234 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
235 void update_pv(SearchStack ss[], int ply);
236 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
237 bool connected_moves(const Position &pos, Move m1, Move m2);
238 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
239 bool singleReply, bool mateThreat);
240 bool ok_to_do_nullmove(const Position &pos);
241 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
242 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
243 bool ok_to_history(const Position &pos, Move m);
244 void update_history(const Position& pos, Move m, Depth depth,
245 Move movesSearched[], int moveCount);
247 bool fail_high_ply_1();
248 int current_search_time();
252 void print_current_line(SearchStack ss[], int ply, int threadID);
253 void wait_for_stop_or_ponderhit();
255 void idle_loop(int threadID, SplitPoint *waitSp);
256 void init_split_point_stack();
257 void destroy_split_point_stack();
258 bool thread_should_stop(int threadID);
259 bool thread_is_available(int slave, int master);
260 bool idle_thread_exists(int master);
261 bool split(const Position &pos, SearchStack *ss, int ply,
262 Value *alpha, Value *beta, Value *bestValue, Depth depth,
263 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
265 void wake_sleeping_threads();
267 #if !defined(_MSC_VER)
268 void *init_thread(void *threadID);
270 DWORD WINAPI init_thread(LPVOID threadID);
277 //// Global variables
280 // The main transposition table
281 TranspositionTable TT = TranspositionTable(TTDefaultSize);
284 // Number of active threads:
285 int ActiveThreads = 1;
287 // Locks. In principle, there is no need for IOLock to be a global variable,
288 // but it could turn out to be useful for debugging.
291 History H; // Should be made local?
298 /// think() is the external interface to Glaurung's search, and is called when
299 /// the program receives the UCI 'go' command. It initializes various
300 /// search-related global variables, and calls root_search()
302 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
303 int time[], int increment[], int movesToGo, int maxDepth,
304 int maxNodes, int maxTime, Move searchMoves[]) {
306 // Look for a book move:
307 if(!infinite && !ponder && get_option_value_bool("OwnBook")) {
309 if(get_option_value_string("Book File") != OpeningBook.file_name()) {
311 OpeningBook.open("book.bin");
313 bookMove = OpeningBook.get_move(pos);
314 if(bookMove != MOVE_NONE) {
315 std::cout << "bestmove " << bookMove << std::endl;
320 // Initialize global search variables:
322 SearchStartTime = get_system_time();
323 BestRootMove = MOVE_NONE;
324 PonderMove = MOVE_NONE;
325 EasyMove = MOVE_NONE;
326 for(int i = 0; i < THREAD_MAX; i++) {
327 Threads[i].nodes = 0ULL;
328 Threads[i].failHighPly1 = false;
331 InfiniteSearch = infinite;
332 PonderSearch = ponder;
333 StopOnPonderhit = false;
338 ExactMaxTime = maxTime;
340 // Read UCI option values:
341 TT.set_size(get_option_value_int("Hash"));
342 if(button_was_pressed("Clear Hash"))
344 PonderingEnabled = get_option_value_bool("Ponder");
345 MultiPV = get_option_value_int("MultiPV");
347 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
349 Depth(get_option_value_int("Check Extension (non-PV nodes)"));
350 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
351 SingleReplyExtension[0] =
352 Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
353 PawnPushTo7thExtension[1] =
354 Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
355 PawnPushTo7thExtension[0] =
356 Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
357 PassedPawnExtension[1] =
358 Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
359 PassedPawnExtension[0] =
360 Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
361 PawnEndgameExtension[1] =
362 Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
363 PawnEndgameExtension[0] =
364 Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
365 MateThreatExtension[1] =
366 Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
367 MateThreatExtension[0] =
368 Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
370 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
371 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
372 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
373 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
375 Chess960 = get_option_value_bool("UCI_Chess960");
376 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
377 UseLogFile = get_option_value_bool("Use Search Log");
379 LogFile.open(get_option_value_string("Search Log Filename").c_str(),
380 std::ios::out | std::ios::app);
382 UseQSearchFutilityPruning =
383 get_option_value_bool("Futility Pruning (Quiescence Search)");
385 get_option_value_bool("Futility Pruning (Main Search)");
388 value_from_centipawns(get_option_value_int("Futility Margin 0"));
390 value_from_centipawns(get_option_value_int("Futility Margin 1"));
392 value_from_centipawns(get_option_value_int("Futility Margin 2"));
394 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
395 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
397 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
398 MaxThreadsPerSplitPoint =
399 get_option_value_int("Maximum Number of Threads per Split Point");
401 read_weights(pos.side_to_move());
403 int newActiveThreads = get_option_value_int("Threads");
404 if(newActiveThreads != ActiveThreads) {
405 ActiveThreads = newActiveThreads;
406 init_eval(ActiveThreads);
409 // Wake up sleeping threads:
410 wake_sleeping_threads();
412 for(int i = 1; i < ActiveThreads; i++)
413 assert(thread_is_available(i, 0));
415 // Set thinking time:
416 int myTime = time[side_to_move];
417 int myIncrement = increment[side_to_move];
418 int oppTime = time[1 - side_to_move];
420 TimeAdvantage = myTime - oppTime;
422 if(!movesToGo) { // Sudden death time control
424 MaxSearchTime = myTime / 30 + myIncrement;
425 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
427 else { // Blitz game without increment
428 MaxSearchTime = myTime / 40;
429 AbsoluteMaxSearchTime = myTime / 8;
432 else { // (x moves) / (y minutes)
434 MaxSearchTime = myTime / 2;
435 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
438 MaxSearchTime = myTime / Min(movesToGo, 20);
439 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
442 if(PonderingEnabled) {
443 MaxSearchTime += MaxSearchTime / 4;
444 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
447 // Fixed depth or fixed number of nodes?
450 InfiniteSearch = true; // HACK
454 NodesBetweenPolls = Min(MaxNodes, 30000);
455 InfiniteSearch = true; // HACK
458 NodesBetweenPolls = 30000;
461 // Write information to search log file:
463 LogFile << "Searching: " << pos.to_fen() << '\n';
464 LogFile << "infinite: " << infinite << " ponder: " << ponder
465 << " time: " << myTime << " increment: " << myIncrement
466 << " moves to go: " << movesToGo << '\n';
469 // We're ready to start thinking. Call the iterative deepening loop
471 id_loop(pos, searchMoves);
487 /// init_threads() is called during startup. It launches all helper threads,
488 /// and initializes the split point stack and the global locks and condition
491 void init_threads() {
493 #if !defined(_MSC_VER)
494 pthread_t pthread[1];
497 for(i = 0; i < THREAD_MAX; i++)
498 Threads[i].activeSplitPoints = 0;
500 // Initialize global locks:
501 lock_init(&MPLock, NULL);
502 lock_init(&IOLock, NULL);
504 init_split_point_stack();
506 #if !defined(_MSC_VER)
507 pthread_mutex_init(&WaitLock, NULL);
508 pthread_cond_init(&WaitCond, NULL);
510 for(i = 0; i < THREAD_MAX; i++)
511 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
514 // All threads except the main thread should be initialized to idle state:
515 for(i = 1; i < THREAD_MAX; i++) {
516 Threads[i].stop = false;
517 Threads[i].workIsWaiting = false;
518 Threads[i].idle = true;
519 Threads[i].running = false;
522 // Launch the helper threads:
523 for(i = 1; i < THREAD_MAX; i++) {
524 #if !defined(_MSC_VER)
525 pthread_create(pthread, NULL, init_thread, (void*)(&i));
529 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
533 // Wait until the thread has finished launching:
534 while(!Threads[i].running);
539 /// stop_threads() is called when the program exits. It makes all the
540 /// helper threads exit cleanly.
542 void stop_threads() {
543 ActiveThreads = THREAD_MAX; // HACK
544 Idle = false; // HACK
545 wake_sleeping_threads();
546 AllThreadsShouldExit = true;
547 for(int i = 1; i < THREAD_MAX; i++) {
548 Threads[i].stop = true;
549 while(Threads[i].running);
551 destroy_split_point_stack();
555 /// nodes_searched() returns the total number of nodes searched so far in
556 /// the current search.
558 int64_t nodes_searched() {
559 int64_t result = 0ULL;
560 for(int i = 0; i < ActiveThreads; i++)
561 result += Threads[i].nodes;
568 // id_loop() is the main iterative deepening loop. It calls root_search
569 // repeatedly with increasing depth until the allocated thinking time has
570 // been consumed, the user stops the search, or the maximum search depth is
573 void id_loop(const Position &pos, Move searchMoves[]) {
575 SearchStack ss[PLY_MAX_PLUS_2];
577 // searchMoves are verified, copied, scored and sorted
578 RootMoveList rml(p, searchMoves);
583 init_search_stack(ss);
585 ValueByIteration[0] = Value(0);
586 ValueByIteration[1] = rml.get_move_score(0);
589 EasyMove = rml.scan_for_easy_move();
591 // Iterative deepening loop
592 while(!AbortSearch && Iteration < PLY_MAX) {
594 // Initialize iteration
597 BestMoveChangesByIteration[Iteration] = 0;
601 std::cout << "info depth " << Iteration << std::endl;
603 // Search to the current depth
604 ValueByIteration[Iteration] = root_search(p, ss, rml);
606 // Erase the easy move if it differs from the new best move
607 if(ss[0].pv[0] != EasyMove)
608 EasyMove = MOVE_NONE;
612 if(!InfiniteSearch) {
614 bool stopSearch = false;
616 // Stop search early if there is only a single legal move:
617 if(Iteration >= 6 && rml.move_count() == 1)
620 // Stop search early when the last two iterations returned a mate
623 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
624 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
627 // Stop search early if one move seems to be much better than the
629 int64_t nodes = nodes_searched();
630 if(Iteration >= 8 && EasyMove == ss[0].pv[0] &&
631 ((rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100 &&
632 current_search_time() > MaxSearchTime / 16) ||
633 (rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100 &&
634 current_search_time() > MaxSearchTime / 32)))
637 // Add some extra time if the best move has changed during the last
639 if(Iteration > 5 && Iteration <= 50)
641 BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) +
642 BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
644 // If we need some more and we are in time advantage take it.
645 if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime)
646 ExtraSearchTime += MaxSearchTime / 2;
648 // Stop search if most of MaxSearchTime is consumed at the end of the
649 // iteration. We probably don't have enough time to search the first
650 // move at the next iteration anyway.
651 if(current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
658 StopOnPonderhit = true;
662 // Write PV to transposition table, in case the relevant entries have
663 // been overwritten during the search:
664 TT.insert_pv(p, ss[0].pv);
666 if(MaxDepth && Iteration >= MaxDepth)
672 // If we are pondering, we shouldn't print the best move before we
675 wait_for_stop_or_ponderhit();
677 // Print final search statistics
678 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
679 << " time " << current_search_time()
680 << " hashfull " << TT.full() << std::endl;
682 // Print the best move and the ponder move to the standard output:
683 std::cout << "bestmove " << ss[0].pv[0];
684 if(ss[0].pv[1] != MOVE_NONE)
685 std::cout << " ponder " << ss[0].pv[1];
686 std::cout << std::endl;
690 LogFile << "Nodes: " << nodes_searched() << '\n';
691 LogFile << "Nodes/second: " << nps() << '\n';
692 LogFile << "Best move: " << move_to_san(p, ss[0].pv[0]) << '\n';
693 p.do_move(ss[0].pv[0], u);
694 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n';
695 LogFile << std::endl;
700 // root_search() is the function which searches the root node. It is
701 // similar to search_pv except that it uses a different move ordering
702 // scheme (perhaps we should try to use this at internal PV nodes, too?)
703 // and prints some information to the standard output.
705 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
706 Value alpha = -VALUE_INFINITE, beta = VALUE_INFINITE, value;
707 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
709 // Loop through all the moves in the root move list:
710 for(int i = 0; i < rml.move_count() && !AbortSearch; i++) {
716 RootMoveNumber = i + 1;
719 // Remember the node count before the move is searched. The node counts
720 // are used to sort the root moves at the next iteration.
721 nodes = nodes_searched();
723 // Pick the next root move, and print the move and the move number to
724 // the standard output:
725 move = ss[0].currentMove = rml.get_move(i);
726 if(current_search_time() >= 1000)
727 std::cout << "info currmove " << move
728 << " currmovenumber " << i + 1 << std::endl;
730 // Decide search depth for this move:
731 ext = extension(pos, move, true, pos.move_is_check(move), false, false);
732 newDepth = (Iteration-2)*OnePly + ext + InitialDepth;
734 // Make the move, and search it.
735 pos.do_move(move, u, dcCandidates);
738 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
739 // If the value has dropped a lot compared to the last iteration,
740 // set the boolean variable Problem to true. This variable is used
741 // for time managment: When Problem is true, we try to complete the
742 // current iteration before playing a move.
743 Problem = (Iteration >= 2 &&
744 value <= ValueByIteration[Iteration-1] - ProblemMargin);
745 if(Problem && StopOnPonderhit)
746 StopOnPonderhit = false;
749 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
751 // Fail high! Set the boolean variable FailHigh to true, and
752 // re-search the move with a big window. The variable FailHigh is
753 // used for time managment: We try to avoid aborting the search
754 // prematurely during a fail high research.
756 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
760 pos.undo_move(move, u);
762 // Finished searching the move. If AbortSearch is true, the search
763 // was aborted because the user interrupted the search or because we
764 // ran out of time. In this case, the return value of the search cannot
765 // be trusted, and we break out of the loop without updating the best
770 // Remember the node count for this move. The node counts are used to
771 // sort the root moves at the next iteration.
772 rml.set_move_nodes(i, nodes_searched() - nodes);
774 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
776 if(value <= alpha && i >= MultiPV)
777 rml.set_move_score(i, -VALUE_INFINITE);
782 rml.set_move_score(i, value);
784 rml.set_move_pv(i, ss[0].pv);
787 // We record how often the best move has been changed in each
788 // iteration. This information is used for time managment: When
789 // the best move changes frequently, we allocate some more time.
791 BestMoveChangesByIteration[Iteration]++;
793 // Print search information to the standard output:
794 std::cout << "info depth " << Iteration
795 << " score " << value_to_string(value)
796 << " time " << current_search_time()
797 << " nodes " << nodes_searched()
800 for(int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
801 std::cout << ss[0].pv[j] << " ";
802 std::cout << std::endl;
805 LogFile << pretty_pv(pos, current_search_time(), Iteration,
806 nodes_searched(), value, ss[0].pv)
811 // Reset the global variable Problem to false if the value isn't too
812 // far below the final value from the last iteration.
813 if(value > ValueByIteration[Iteration - 1] - NoProblemMargin)
816 else { // MultiPV > 1
818 for(int j = 0; j < Min(MultiPV, rml.move_count()); j++) {
820 std::cout << "info multipv " << j + 1
821 << " score " << value_to_string(rml.get_move_score(j))
822 << " depth " << ((j <= i)? Iteration : Iteration - 1)
823 << " time " << current_search_time()
824 << " nodes " << nodes_searched()
827 for(k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
828 std::cout << rml.get_move_pv(j, k) << " ";
829 std::cout << std::endl;
831 alpha = rml.get_move_score(Min(i, MultiPV-1));
839 // search_pv() is the main search function for PV nodes.
841 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
842 Depth depth, int ply, int threadID) {
844 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
845 assert(beta > alpha && beta <= VALUE_INFINITE);
846 assert(ply >= 0 && ply < PLY_MAX);
847 assert(threadID >= 0 && threadID < ActiveThreads);
851 // Initialize, and make an early exit in case of an aborted search,
852 // an instant draw, maximum ply reached, etc.
853 Value oldAlpha = alpha;
855 if (AbortSearch || thread_should_stop(threadID))
859 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
861 init_node(pos, ss, ply, threadID);
866 if (ply >= PLY_MAX - 1)
867 return evaluate(pos, ei, threadID);
869 // Mate distance pruning
870 alpha = Max(value_mated_in(ply), alpha);
871 beta = Min(value_mate_in(ply+1), beta);
875 // Transposition table lookup. At PV nodes, we don't use the TT for
876 // pruning, but only for move ordering.
877 const TTEntry* tte = TT.retrieve(pos);
879 Move ttMove = (tte ? tte->move() : MOVE_NONE);
881 // Go with internal iterative deepening if we don't have a TT move
882 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
884 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
885 ttMove = ss[ply].pv[ply];
888 // Initialize a MovePicker object for the current position, and prepare
889 // to search all moves:
890 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller,
891 ss[ply].killer1, ss[ply].killer2, depth);
893 Move move, movesSearched[256];
895 Value value, bestValue = -VALUE_INFINITE;
896 Bitboard dcCandidates = mp.discovered_check_candidates();
897 bool mateThreat = MateThreatExtension[1] > Depth(0)
898 && pos.has_mate_threat(opposite_color(pos.side_to_move()));
900 // Loop through all legal moves until no moves remain or a beta cutoff
903 && (move = mp.get_next_move()) != MOVE_NONE
904 && !thread_should_stop(threadID))
906 assert(move_is_ok(move));
908 bool singleReply = (pos.is_check() && mp.number_of_moves() == 1);
909 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
910 bool moveIsCapture = pos.move_is_capture(move);
911 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
913 movesSearched[moveCount++] = ss[ply].currentMove = move;
915 ss[ply].currentMoveCaptureValue = move_is_ep(move) ?
916 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
918 // Decide the new search depth
919 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat);
920 Depth newDepth = depth - OnePly + ext;
922 // Make and search the move
924 pos.do_move(move, u, dcCandidates);
926 if (moveCount == 1) // The first move in list is the PV
927 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
930 // Try to reduce non-pv search depth by one ply if move seems not problematic,
931 // if the move fails high will be re-searched at full depth.
932 if ( depth >= 2*OnePly
934 && moveCount >= LMRPVMoves
936 && !move_promotion(move)
937 && !moveIsPassedPawnPush
938 && !move_is_castle(move)
939 && move != ss[ply].killer1
940 && move != ss[ply].killer2)
942 ss[ply].reduction = OnePly;
943 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
946 value = alpha + 1; // Just to trigger next condition
948 if (value > alpha) // Go with full depth pv search
950 ss[ply].reduction = Depth(0);
951 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
952 if (value > alpha && value < beta)
954 // When the search fails high at ply 1 while searching the first
955 // move at the root, set the flag failHighPly1. This is used for
956 // time managment: We don't want to stop the search early in
957 // such cases, because resolving the fail high at ply 1 could
958 // result in a big drop in score at the root.
959 if (ply == 1 && RootMoveNumber == 1)
960 Threads[threadID].failHighPly1 = true;
962 // A fail high occurred. Re-search at full window (pv search)
963 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
964 Threads[threadID].failHighPly1 = false;
968 pos.undo_move(move, u);
970 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
973 if (value > bestValue)
980 if (value == value_mate_in(ply + 1))
981 ss[ply].mateKiller = move;
983 // If we are at ply 1, and we are searching the first root move at
984 // ply 0, set the 'Problem' variable if the score has dropped a lot
985 // (from the computer's point of view) since the previous iteration:
986 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
991 if ( ActiveThreads > 1
993 && depth >= MinimumSplitDepth
995 && idle_thread_exists(threadID)
997 && !thread_should_stop(threadID)
998 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
999 &moveCount, &mp, dcCandidates, threadID, true))
1003 // All legal moves have been searched. A special case: If there were
1004 // no legal moves, it must be mate or stalemate:
1006 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1008 // If the search is not aborted, update the transposition table,
1009 // history counters, and killer moves.
1010 if (AbortSearch || thread_should_stop(threadID))
1013 if (bestValue <= oldAlpha)
1014 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1016 else if (bestValue >= beta)
1018 Move m = ss[ply].pv[ply];
1019 if (ok_to_history(pos, m)) // Only non capture moves are considered
1021 update_history(pos, m, depth, movesSearched, moveCount);
1022 if (m != ss[ply].killer1)
1024 ss[ply].killer2 = ss[ply].killer1;
1025 ss[ply].killer1 = m;
1028 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1031 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1037 // search() is the search function for zero-width nodes.
1039 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1040 int ply, bool allowNullmove, int threadID) {
1042 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1043 assert(ply >= 0 && ply < PLY_MAX);
1044 assert(threadID >= 0 && threadID < ActiveThreads);
1048 // Initialize, and make an early exit in case of an aborted search,
1049 // an instant draw, maximum ply reached, etc.
1050 if (AbortSearch || thread_should_stop(threadID))
1054 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1056 init_node(pos, ss, ply, threadID);
1061 if (ply >= PLY_MAX - 1)
1062 return evaluate(pos, ei, threadID);
1064 // Mate distance pruning
1065 if (value_mated_in(ply) >= beta)
1068 if (value_mate_in(ply + 1) < beta)
1071 // Transposition table lookup
1072 const TTEntry* tte = TT.retrieve(pos);
1074 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1076 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1078 ss[ply].currentMove = ttMove; // can be MOVE_NONE ?
1079 return value_from_tt(tte->value(), ply);
1082 Value approximateEval = quick_evaluate(pos);
1083 bool mateThreat = false;
1088 && ok_to_do_nullmove(pos)
1089 && approximateEval >= beta - NullMoveMargin)
1091 ss[ply].currentMove = MOVE_NULL;
1094 pos.do_null_move(u);
1095 Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID);
1096 pos.undo_null_move(u);
1098 if (nullValue >= beta)
1100 if (depth < 6 * OnePly)
1103 // Do zugzwang verification search
1104 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1108 // The null move failed low, which means that we may be faced with
1109 // some kind of threat. If the previous move was reduced, check if
1110 // the move that refuted the null move was somehow connected to the
1111 // move which was reduced. If a connection is found, return a fail
1112 // low score (which will cause the reduced move to fail high in the
1113 // parent node, which will trigger a re-search with full depth).
1114 if (nullValue == value_mated_in(ply + 2))
1117 ss[ply].threatMove = ss[ply + 1].currentMove;
1118 if ( depth < ThreatDepth
1119 && ss[ply - 1].reduction
1120 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1124 // Null move search not allowed, try razoring
1125 else if ( depth < RazorDepth
1126 && approximateEval < beta - RazorMargin
1127 && evaluate(pos, ei, threadID) < beta - RazorMargin)
1129 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1134 // Go with internal iterative deepening if we don't have a TT move
1135 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1136 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1138 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1139 ttMove = ss[ply].pv[ply];
1142 // Initialize a MovePicker object for the current position, and prepare
1143 // to search all moves:
1144 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller,
1145 ss[ply].killer1, ss[ply].killer2, depth);
1147 Move move, movesSearched[256];
1149 Value value, bestValue = -VALUE_INFINITE;
1150 Bitboard dcCandidates = mp.discovered_check_candidates();
1151 Value futilityValue = VALUE_NONE;
1152 bool isCheck = pos.is_check();
1153 bool useFutilityPruning = UseFutilityPruning
1154 && depth < SelectiveDepth
1157 // Loop through all legal moves until no moves remain or a beta cutoff
1159 while ( bestValue < beta
1160 && (move = mp.get_next_move()) != MOVE_NONE
1161 && !thread_should_stop(threadID))
1163 assert(move_is_ok(move));
1165 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1166 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1167 bool moveIsCapture = pos.move_is_capture(move);
1168 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1170 movesSearched[moveCount++] = ss[ply].currentMove = move;
1172 // Decide the new search depth
1173 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat);
1174 Depth newDepth = depth - OnePly + ext;
1177 if ( useFutilityPruning
1180 && !moveIsPassedPawnPush
1181 && !move_promotion(move))
1183 if ( moveCount >= 2 + int(depth)
1184 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1187 if (depth < 3 * OnePly && approximateEval < beta)
1189 if (futilityValue == VALUE_NONE)
1190 futilityValue = evaluate(pos, ei, threadID)
1191 + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2);
1193 if (futilityValue < beta)
1195 if (futilityValue > bestValue)
1196 bestValue = futilityValue;
1202 // Make and search the move
1204 pos.do_move(move, u, dcCandidates);
1206 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1207 // if the move fails high will be re-searched at full depth.
1208 if ( depth >= 2*OnePly
1210 && moveCount >= LMRNonPVMoves
1212 && !move_promotion(move)
1213 && !moveIsPassedPawnPush
1214 && !move_is_castle(move)
1215 && move != ss[ply].killer1
1216 && move != ss[ply].killer2)
1218 ss[ply].reduction = OnePly;
1219 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1222 value = beta; // Just to trigger next condition
1224 if (value >= beta) // Go with full depth non-pv search
1226 ss[ply].reduction = Depth(0);
1227 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1229 pos.undo_move(move, u);
1231 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1234 if (value > bestValue)
1240 if (value == value_mate_in(ply + 1))
1241 ss[ply].mateKiller = move;
1245 if ( ActiveThreads > 1
1247 && depth >= MinimumSplitDepth
1249 && idle_thread_exists(threadID)
1251 && !thread_should_stop(threadID)
1252 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1253 &mp, dcCandidates, threadID, false))
1257 // All legal moves have been searched. A special case: If there were
1258 // no legal moves, it must be mate or stalemate:
1260 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1262 // If the search is not aborted, update the transposition table,
1263 // history counters, and killer moves.
1264 if (AbortSearch || thread_should_stop(threadID))
1267 if (bestValue < beta)
1268 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1271 Move m = ss[ply].pv[ply];
1272 if (ok_to_history(pos, m)) // Only non capture moves are considered
1274 update_history(pos, m, depth, movesSearched, moveCount);
1275 if (m != ss[ply].killer1)
1277 ss[ply].killer2 = ss[ply].killer1;
1278 ss[ply].killer1 = m;
1281 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1287 // qsearch() is the quiescence search function, which is called by the main
1288 // search function when the remaining depth is zero (or, to be more precise,
1289 // less than OnePly).
1291 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1292 Depth depth, int ply, int threadID) {
1294 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1295 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1297 assert(ply >= 0 && ply < PLY_MAX);
1298 assert(threadID >= 0 && threadID < ActiveThreads);
1302 // Initialize, and make an early exit in case of an aborted search,
1303 // an instant draw, maximum ply reached, etc.
1304 if (AbortSearch || thread_should_stop(threadID))
1307 init_node(pos, ss, ply, threadID);
1312 // Transposition table lookup
1313 const TTEntry* tte = TT.retrieve(pos);
1314 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1315 return value_from_tt(tte->value(), ply);
1317 // Evaluate the position statically:
1318 Value staticValue = evaluate(pos, ei, threadID);
1320 if (ply == PLY_MAX - 1)
1323 // Initialize "stand pat score", and return it immediately if it is
1325 Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue);
1327 if (bestValue >= beta)
1330 if (bestValue > alpha)
1333 // Initialize a MovePicker object for the current position, and prepare
1334 // to search the moves. Because the depth is <= 0 here, only captures,
1335 // queen promotions and checks (only if depth == 0) will be generated.
1336 MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE,
1340 Bitboard dcCandidates = mp.discovered_check_candidates();
1341 bool isCheck = pos.is_check();
1343 // Loop through the moves until no moves remain or a beta cutoff
1345 while ( alpha < beta
1346 && (move = mp.get_next_move()) != MOVE_NONE)
1348 assert(move_is_ok(move));
1350 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1351 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1354 ss[ply].currentMove = move;
1357 if ( UseQSearchFutilityPruning
1360 && !move_promotion(move)
1361 && !moveIsPassedPawnPush
1362 && beta - alpha == 1
1363 && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame)
1365 Value futilityValue = staticValue
1366 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1367 pos.endgame_value_of_piece_on(move_to(move)))
1369 + ei.futilityMargin;
1371 if (futilityValue < alpha)
1373 if (futilityValue > bestValue)
1374 bestValue = futilityValue;
1379 // Don't search captures and checks with negative SEE values.
1381 && !move_promotion(move)
1382 && (pos.midgame_value_of_piece_on(move_from(move)) >
1383 pos.midgame_value_of_piece_on(move_to(move)))
1384 && pos.see(move) < 0)
1387 // Make and search the move.
1389 pos.do_move(move, u, dcCandidates);
1390 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1391 pos.undo_move(move, u);
1393 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1396 if (value > bestValue)
1407 // All legal moves have been searched. A special case: If we're in check
1408 // and no legal moves were found, it is checkmate:
1409 if (pos.is_check() && moveCount == 0) // Mate!
1410 return value_mated_in(ply);
1412 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1414 // Update transposition table
1415 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1421 // sp_search() is used to search from a split point. This function is called
1422 // by each thread working at the split point. It is similar to the normal
1423 // search() function, but simpler. Because we have already probed the hash
1424 // table, done a null move search, and searched the first move before
1425 // splitting, we don't have to repeat all this work in sp_search(). We
1426 // also don't need to store anything to the hash table here: This is taken
1427 // care of after we return from the split point.
1429 void sp_search(SplitPoint *sp, int threadID) {
1431 assert(threadID >= 0 && threadID < ActiveThreads);
1432 assert(ActiveThreads > 1);
1434 Position pos = Position(sp->pos);
1435 SearchStack *ss = sp->sstack[threadID];
1438 bool isCheck = pos.is_check();
1439 bool useFutilityPruning = UseFutilityPruning
1440 && sp->depth < SelectiveDepth
1443 while ( sp->bestValue < sp->beta
1444 && !thread_should_stop(threadID)
1445 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1447 assert(move_is_ok(move));
1449 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1450 bool moveIsCapture = pos.move_is_capture(move);
1451 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1453 lock_grab(&(sp->lock));
1454 int moveCount = ++sp->moves;
1455 lock_release(&(sp->lock));
1457 ss[sp->ply].currentMove = move;
1459 // Decide the new search depth.
1460 Depth ext = extension(pos, move, false, moveIsCheck, false, false);
1461 Depth newDepth = sp->depth - OnePly + ext;
1464 if ( useFutilityPruning
1467 && !moveIsPassedPawnPush
1468 && !move_promotion(move)
1469 && moveCount >= 2 + int(sp->depth)
1470 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1473 // Make and search the move.
1475 pos.do_move(move, u, sp->dcCandidates);
1477 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1478 // if the move fails high will be re-searched at full depth.
1479 if ( ext == Depth(0)
1480 && moveCount >= LMRNonPVMoves
1482 && !moveIsPassedPawnPush
1483 && !move_promotion(move)
1484 && !move_is_castle(move)
1485 && move != ss[sp->ply].killer1
1486 && move != ss[sp->ply].killer2)
1488 ss[sp->ply].reduction = OnePly;
1489 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1492 value = sp->beta; // Just to trigger next condition
1494 if (value >= sp->beta) // Go with full depth non-pv search
1496 ss[sp->ply].reduction = Depth(0);
1497 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1499 pos.undo_move(move, u);
1501 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1503 if (thread_should_stop(threadID))
1507 lock_grab(&(sp->lock));
1508 if (value > sp->bestValue && !thread_should_stop(threadID))
1510 sp->bestValue = value;
1511 if (sp->bestValue >= sp->beta)
1513 sp_update_pv(sp->parentSstack, ss, sp->ply);
1514 for (int i = 0; i < ActiveThreads; i++)
1515 if (i != threadID && (i == sp->master || sp->slaves[i]))
1516 Threads[i].stop = true;
1518 sp->finished = true;
1521 lock_release(&(sp->lock));
1524 lock_grab(&(sp->lock));
1526 // If this is the master thread and we have been asked to stop because of
1527 // a beta cutoff higher up in the tree, stop all slave threads:
1528 if (sp->master == threadID && thread_should_stop(threadID))
1529 for (int i = 0; i < ActiveThreads; i++)
1531 Threads[i].stop = true;
1534 sp->slaves[threadID] = 0;
1536 lock_release(&(sp->lock));
1540 // sp_search_pv() is used to search from a PV split point. This function
1541 // is called by each thread working at the split point. It is similar to
1542 // the normal search_pv() function, but simpler. Because we have already
1543 // probed the hash table and searched the first move before splitting, we
1544 // don't have to repeat all this work in sp_search_pv(). We also don't
1545 // need to store anything to the hash table here: This is taken care of
1546 // after we return from the split point.
1548 void sp_search_pv(SplitPoint *sp, int threadID) {
1550 assert(threadID >= 0 && threadID < ActiveThreads);
1551 assert(ActiveThreads > 1);
1553 Position pos = Position(sp->pos);
1554 SearchStack *ss = sp->sstack[threadID];
1558 while ( sp->alpha < sp->beta
1559 && !thread_should_stop(threadID)
1560 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1562 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1563 bool moveIsCapture = pos.move_is_capture(move);
1564 bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move);
1566 assert(move_is_ok(move));
1568 ss[sp->ply].currentMoveCaptureValue = move_is_ep(move)?
1569 PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1571 lock_grab(&(sp->lock));
1572 int moveCount = ++sp->moves;
1573 lock_release(&(sp->lock));
1575 ss[sp->ply].currentMove = move;
1577 // Decide the new search depth.
1578 Depth ext = extension(pos, move, true, moveIsCheck, false, false);
1579 Depth newDepth = sp->depth - OnePly + ext;
1581 // Make and search the move.
1583 pos.do_move(move, u, sp->dcCandidates);
1585 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1586 // if the move fails high will be re-searched at full depth.
1587 if ( ext == Depth(0)
1588 && moveCount >= LMRPVMoves
1590 && !moveIsPassedPawnPush
1591 && !move_promotion(move)
1592 && !move_is_castle(move)
1593 && move != ss[sp->ply].killer1
1594 && move != ss[sp->ply].killer2)
1596 ss[sp->ply].reduction = OnePly;
1597 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1600 value = sp->alpha + 1; // Just to trigger next condition
1602 if (value > sp->alpha) // Go with full depth non-pv search
1604 ss[sp->ply].reduction = Depth(0);
1605 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1607 if (value > sp->alpha && value < sp->beta)
1609 // When the search fails high at ply 1 while searching the first
1610 // move at the root, set the flag failHighPly1. This is used for
1611 // time managment: We don't want to stop the search early in
1612 // such cases, because resolving the fail high at ply 1 could
1613 // result in a big drop in score at the root.
1614 if (sp->ply == 1 && RootMoveNumber == 1)
1615 Threads[threadID].failHighPly1 = true;
1617 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1618 Threads[threadID].failHighPly1 = false;
1621 pos.undo_move(move, u);
1623 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1625 if (thread_should_stop(threadID))
1629 lock_grab(&(sp->lock));
1630 if (value > sp->bestValue && !thread_should_stop(threadID))
1632 sp->bestValue = value;
1633 if (value > sp->alpha)
1636 sp_update_pv(sp->parentSstack, ss, sp->ply);
1637 if (value == value_mate_in(sp->ply + 1))
1638 ss[sp->ply].mateKiller = move;
1640 if(value >= sp->beta)
1642 for(int i = 0; i < ActiveThreads; i++)
1643 if(i != threadID && (i == sp->master || sp->slaves[i]))
1644 Threads[i].stop = true;
1646 sp->finished = true;
1649 // If we are at ply 1, and we are searching the first root move at
1650 // ply 0, set the 'Problem' variable if the score has dropped a lot
1651 // (from the computer's point of view) since the previous iteration:
1652 if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1655 lock_release(&(sp->lock));
1658 lock_grab(&(sp->lock));
1660 // If this is the master thread and we have been asked to stop because of
1661 // a beta cutoff higher up in the tree, stop all slave threads:
1662 if (sp->master == threadID && thread_should_stop(threadID))
1663 for (int i = 0; i < ActiveThreads; i++)
1665 Threads[i].stop = true;
1668 sp->slaves[threadID] = 0;
1670 lock_release(&(sp->lock));
1674 /// The RootMove class
1678 RootMove::RootMove() {
1679 nodes = cumulativeNodes = 0ULL;
1682 // RootMove::operator<() is the comparison function used when
1683 // sorting the moves. A move m1 is considered to be better
1684 // than a move m2 if it has a higher score, or if the moves
1685 // have equal score but m1 has the higher node count.
1687 bool RootMove::operator<(const RootMove& m) {
1689 if (score != m.score)
1690 return (score < m.score);
1692 return nodes <= m.nodes;
1695 /// The RootMoveList class
1699 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1701 MoveStack mlist[MaxRootMoves];
1702 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1704 // Generate all legal moves
1705 int lm_count = generate_legal_moves(pos, mlist);
1707 // Add each move to the moves[] array
1708 for (int i = 0; i < lm_count; i++)
1710 bool includeMove = includeAllMoves;
1712 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1713 includeMove = (searchMoves[k] == mlist[i].move);
1717 // Find a quick score for the move
1719 SearchStack ss[PLY_MAX_PLUS_2];
1721 moves[count].move = mlist[i].move;
1722 moves[count].nodes = 0ULL;
1723 pos.do_move(moves[count].move, u);
1724 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1726 pos.undo_move(moves[count].move, u);
1727 moves[count].pv[0] = moves[i].move;
1728 moves[count].pv[1] = MOVE_NONE; // FIXME
1736 // Simple accessor methods for the RootMoveList class
1738 inline Move RootMoveList::get_move(int moveNum) const {
1739 return moves[moveNum].move;
1742 inline Value RootMoveList::get_move_score(int moveNum) const {
1743 return moves[moveNum].score;
1746 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1747 moves[moveNum].score = score;
1750 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1751 moves[moveNum].nodes = nodes;
1752 moves[moveNum].cumulativeNodes += nodes;
1755 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1757 for(j = 0; pv[j] != MOVE_NONE; j++)
1758 moves[moveNum].pv[j] = pv[j];
1759 moves[moveNum].pv[j] = MOVE_NONE;
1762 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1763 return moves[moveNum].pv[i];
1766 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1767 return moves[moveNum].cumulativeNodes;
1770 inline int RootMoveList::move_count() const {
1775 // RootMoveList::scan_for_easy_move() is called at the end of the first
1776 // iteration, and is used to detect an "easy move", i.e. a move which appears
1777 // to be much bester than all the rest. If an easy move is found, the move
1778 // is returned, otherwise the function returns MOVE_NONE. It is very
1779 // important that this function is called at the right moment: The code
1780 // assumes that the first iteration has been completed and the moves have
1781 // been sorted. This is done in RootMoveList c'tor.
1783 Move RootMoveList::scan_for_easy_move() const {
1790 // moves are sorted so just consider the best and the second one
1791 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1797 // RootMoveList::sort() sorts the root move list at the beginning of a new
1800 inline void RootMoveList::sort() {
1802 sort_multipv(count - 1); // all items
1806 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1807 // list by their scores and depths. It is used to order the different PVs
1808 // correctly in MultiPV mode.
1810 void RootMoveList::sort_multipv(int n) {
1812 for (int i = 1; i <= n; i++)
1814 RootMove rm = moves[i];
1816 for (j = i; j > 0 && moves[j-1] < rm; j--)
1817 moves[j] = moves[j-1];
1823 // init_search_stack() initializes a search stack at the beginning of a
1824 // new search from the root.
1826 void init_search_stack(SearchStack ss[]) {
1827 for(int i = 0; i < 3; i++) {
1828 ss[i].pv[i] = MOVE_NONE;
1829 ss[i].pv[i+1] = MOVE_NONE;
1830 ss[i].currentMove = MOVE_NONE;
1831 ss[i].mateKiller = MOVE_NONE;
1832 ss[i].killer1 = MOVE_NONE;
1833 ss[i].killer2 = MOVE_NONE;
1834 ss[i].threatMove = MOVE_NONE;
1835 ss[i].reduction = Depth(0);
1840 // init_node() is called at the beginning of all the search functions
1841 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1842 // stack object corresponding to the current node. Once every
1843 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1844 // for user input and checks whether it is time to stop the search.
1846 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1847 assert(ply >= 0 && ply < PLY_MAX);
1848 assert(threadID >= 0 && threadID < ActiveThreads);
1850 Threads[threadID].nodes++;
1854 if(NodesSincePoll >= NodesBetweenPolls) {
1860 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
1861 ss[ply+2].mateKiller = MOVE_NONE;
1862 ss[ply+2].killer1 = ss[ply+2].killer2 = MOVE_NONE;
1863 ss[ply].threatMove = MOVE_NONE;
1864 ss[ply].reduction = Depth(0);
1865 ss[ply].currentMoveCaptureValue = Value(0);
1867 if(Threads[threadID].printCurrentLine)
1868 print_current_line(ss, ply, threadID);
1872 // update_pv() is called whenever a search returns a value > alpha. It
1873 // updates the PV in the SearchStack object corresponding to the current
1876 void update_pv(SearchStack ss[], int ply) {
1877 assert(ply >= 0 && ply < PLY_MAX);
1879 ss[ply].pv[ply] = ss[ply].currentMove;
1881 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1882 ss[ply].pv[p] = ss[ply+1].pv[p];
1883 ss[ply].pv[p] = MOVE_NONE;
1887 // sp_update_pv() is a variant of update_pv for use at split points. The
1888 // difference between the two functions is that sp_update_pv also updates
1889 // the PV at the parent node.
1891 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
1892 assert(ply >= 0 && ply < PLY_MAX);
1894 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
1896 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
1897 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
1898 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
1902 // connected_moves() tests whether two moves are 'connected' in the sense
1903 // that the first move somehow made the second move possible (for instance
1904 // if the moving piece is the same in both moves). The first move is
1905 // assumed to be the move that was made to reach the current position, while
1906 // the second move is assumed to be a move from the current position.
1908 bool connected_moves(const Position &pos, Move m1, Move m2) {
1909 Square f1, t1, f2, t2;
1911 assert(move_is_ok(m1));
1912 assert(move_is_ok(m2));
1917 // Case 1: The moving piece is the same in both moves.
1923 // Case 2: The destination square for m2 was vacated by m1.
1929 // Case 3: Moving through the vacated square:
1930 if(piece_is_slider(pos.piece_on(f2)) &&
1931 bit_is_set(squares_between(f2, t2), f1))
1934 // Case 4: The destination square for m2 is attacked by the moving piece
1936 if(pos.piece_attacks_square(t1, t2))
1939 // Case 5: Discovered check, checking piece is the piece moved in m1:
1940 if(piece_is_slider(pos.piece_on(t1)) &&
1941 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
1943 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
1945 Bitboard occ = pos.occupied_squares();
1946 Color us = pos.side_to_move();
1947 Square ksq = pos.king_square(us);
1948 clear_bit(&occ, f2);
1949 if(pos.type_of_piece_on(t1) == BISHOP) {
1950 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
1953 else if(pos.type_of_piece_on(t1) == ROOK) {
1954 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
1958 assert(pos.type_of_piece_on(t1) == QUEEN);
1959 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
1968 // extension() decides whether a move should be searched with normal depth,
1969 // or with extended depth. Certain classes of moves (checking moves, in
1970 // particular) are searched with bigger depth than ordinary moves.
1972 Depth extension(const Position &pos, Move m, bool pvNode,
1973 bool check, bool singleReply, bool mateThreat) {
1974 Depth result = Depth(0);
1977 result += CheckExtension[pvNode];
1979 result += SingleReplyExtension[pvNode];
1980 if(pos.move_is_pawn_push_to_7th(m))
1981 result += PawnPushTo7thExtension[pvNode];
1982 if(pos.move_is_passed_pawn_push(m))
1983 result += PassedPawnExtension[pvNode];
1985 result += MateThreatExtension[pvNode];
1986 if(pos.midgame_value_of_piece_on(move_to(m)) >= RookValueMidgame
1987 && (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1988 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
1989 && !move_promotion(m))
1990 result += PawnEndgameExtension[pvNode];
1991 if(pvNode && pos.move_is_capture(m)
1992 && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see(m) >= 0)
1995 return Min(result, OnePly);
1999 // ok_to_do_nullmove() looks at the current position and decides whether
2000 // doing a 'null move' should be allowed. In order to avoid zugzwang
2001 // problems, null moves are not allowed when the side to move has very
2002 // little material left. Currently, the test is a bit too simple: Null
2003 // moves are avoided only when the side to move has only pawns left. It's
2004 // probably a good idea to avoid null moves in at least some more
2005 // complicated endgames, e.g. KQ vs KR. FIXME
2007 bool ok_to_do_nullmove(const Position &pos) {
2008 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2014 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2015 // non-tactical moves late in the move list close to the leaves are
2016 // candidates for pruning.
2018 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2019 Square mfrom, mto, tfrom, tto;
2021 assert(move_is_ok(m));
2022 assert(threat == MOVE_NONE || move_is_ok(threat));
2023 assert(!move_promotion(m));
2024 assert(!pos.move_is_check(m));
2025 assert(!pos.move_is_capture(m));
2026 assert(!pos.move_is_passed_pawn_push(m));
2027 assert(d >= OnePly);
2029 mfrom = move_from(m);
2031 tfrom = move_from(threat);
2032 tto = move_to(threat);
2034 // Case 1: Castling moves are never pruned.
2035 if(move_is_castle(m))
2038 // Case 2: Don't prune moves which move the threatened piece
2039 if(!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2042 // Case 3: If the threatened piece has value less than or equal to the
2043 // value of the threatening piece, don't prune move which defend it.
2044 if(!PruneDefendingMoves && threat != MOVE_NONE
2045 && (piece_value_midgame(pos.piece_on(tfrom))
2046 >= piece_value_midgame(pos.piece_on(tto)))
2047 && pos.move_attacks_square(m, tto))
2050 // Case 4: Don't prune moves with good history.
2051 if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2054 // Case 5: If the moving piece in the threatened move is a slider, don't
2055 // prune safe moves which block its ray.
2056 if(!PruneBlockingMoves && threat != MOVE_NONE
2057 && piece_is_slider(pos.piece_on(tfrom))
2058 && bit_is_set(squares_between(tfrom, tto), mto) && pos.see(m) >= 0)
2065 // ok_to_use_TT() returns true if a transposition table score
2066 // can be used at a given point in search.
2068 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2070 Value v = value_from_tt(tte->value(), ply);
2072 return ( tte->depth() >= depth
2073 || v >= Max(value_mate_in(100), beta)
2074 || v < Min(value_mated_in(100), beta))
2076 && ( (is_lower_bound(tte->type()) && v >= beta)
2077 || (is_upper_bound(tte->type()) && v < beta));
2081 // ok_to_history() returns true if a move m can be stored
2082 // in history. Should be a non capturing move.
2084 bool ok_to_history(const Position& pos, Move m) {
2086 return pos.square_is_empty(move_to(m))
2087 && !move_promotion(m)
2092 // update_history() registers a good move that produced a beta-cutoff
2093 // in history and marks as failures all the other moves of that ply.
2095 void update_history(const Position& pos, Move m, Depth depth,
2096 Move movesSearched[], int moveCount) {
2098 H.success(pos.piece_on(move_from(m)), m, depth);
2100 for (int i = 0; i < moveCount - 1; i++)
2101 if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i])
2102 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2105 // fail_high_ply_1() checks if some thread is currently resolving a fail
2106 // high at ply 1 at the node below the first root node. This information
2107 // is used for time managment.
2109 bool fail_high_ply_1() {
2110 for(int i = 0; i < ActiveThreads; i++)
2111 if(Threads[i].failHighPly1)
2117 // current_search_time() returns the number of milliseconds which have passed
2118 // since the beginning of the current search.
2120 int current_search_time() {
2121 return get_system_time() - SearchStartTime;
2125 // nps() computes the current nodes/second count.
2128 int t = current_search_time();
2129 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2133 // poll() performs two different functions: It polls for user input, and it
2134 // looks at the time consumed so far and decides if it's time to abort the
2139 static int lastInfoTime;
2140 int t = current_search_time();
2145 // We are line oriented, don't read single chars
2146 std::string command;
2147 if (!std::getline(std::cin, command))
2150 if (command == "quit")
2153 PonderSearch = false;
2156 else if(command == "stop")
2159 PonderSearch = false;
2161 else if(command == "ponderhit")
2164 // Print search information
2168 else if (lastInfoTime > t)
2169 // HACK: Must be a new search where we searched less than
2170 // NodesBetweenPolls nodes during the first second of search.
2173 else if (t - lastInfoTime >= 1000)
2177 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2178 << " time " << t << " hashfull " << TT.full() << std::endl;
2179 lock_release(&IOLock);
2180 if (ShowCurrentLine)
2181 Threads[0].printCurrentLine = true;
2183 // Should we stop the search?
2187 bool overTime = t > AbsoluteMaxSearchTime
2188 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2189 || ( !FailHigh && !fail_high_ply_1() && !Problem
2190 && t > 6*(MaxSearchTime + ExtraSearchTime));
2192 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2193 || (ExactMaxTime && t >= ExactMaxTime)
2194 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2199 // ponderhit() is called when the program is pondering (i.e. thinking while
2200 // it's the opponent's turn to move) in order to let the engine know that
2201 // it correctly predicted the opponent's move.
2204 int t = current_search_time();
2205 PonderSearch = false;
2206 if(Iteration >= 2 &&
2207 (!InfiniteSearch && (StopOnPonderhit ||
2208 t > AbsoluteMaxSearchTime ||
2209 (RootMoveNumber == 1 &&
2210 t > MaxSearchTime + ExtraSearchTime) ||
2211 (!FailHigh && !fail_high_ply_1() && !Problem &&
2212 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2217 // print_current_line() prints the current line of search for a given
2218 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2220 void print_current_line(SearchStack ss[], int ply, int threadID) {
2221 assert(ply >= 0 && ply < PLY_MAX);
2222 assert(threadID >= 0 && threadID < ActiveThreads);
2224 if(!Threads[threadID].idle) {
2226 std::cout << "info currline " << (threadID + 1);
2227 for(int p = 0; p < ply; p++)
2228 std::cout << " " << ss[p].currentMove;
2229 std::cout << std::endl;
2230 lock_release(&IOLock);
2232 Threads[threadID].printCurrentLine = false;
2233 if(threadID + 1 < ActiveThreads)
2234 Threads[threadID + 1].printCurrentLine = true;
2238 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2239 // while the program is pondering. The point is to work around a wrinkle in
2240 // the UCI protocol: When pondering, the engine is not allowed to give a
2241 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2242 // We simply wait here until one of these commands is sent, and return,
2243 // after which the bestmove and pondermove will be printed (in id_loop()).
2245 void wait_for_stop_or_ponderhit() {
2246 std::string command;
2249 if(!std::getline(std::cin, command))
2252 if(command == "quit") {
2253 OpeningBook.close();
2258 else if(command == "ponderhit" || command == "stop")
2264 // idle_loop() is where the threads are parked when they have no work to do.
2265 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2266 // object for which the current thread is the master.
2268 void idle_loop(int threadID, SplitPoint *waitSp) {
2269 assert(threadID >= 0 && threadID < THREAD_MAX);
2271 Threads[threadID].running = true;
2274 if(AllThreadsShouldExit && threadID != 0)
2277 // If we are not thinking, wait for a condition to be signaled instead
2278 // of wasting CPU time polling for work:
2279 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2280 #if !defined(_MSC_VER)
2281 pthread_mutex_lock(&WaitLock);
2282 if(Idle || threadID >= ActiveThreads)
2283 pthread_cond_wait(&WaitCond, &WaitLock);
2284 pthread_mutex_unlock(&WaitLock);
2286 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2290 // If this thread has been assigned work, launch a search:
2291 if(Threads[threadID].workIsWaiting) {
2292 Threads[threadID].workIsWaiting = false;
2293 if(Threads[threadID].splitPoint->pvNode)
2294 sp_search_pv(Threads[threadID].splitPoint, threadID);
2296 sp_search(Threads[threadID].splitPoint, threadID);
2297 Threads[threadID].idle = true;
2300 // If this thread is the master of a split point and all threads have
2301 // finished their work at this split point, return from the idle loop:
2302 if(waitSp != NULL && waitSp->cpus == 0)
2306 Threads[threadID].running = false;
2310 // init_split_point_stack() is called during program initialization, and
2311 // initializes all split point objects.
2313 void init_split_point_stack() {
2314 for(int i = 0; i < THREAD_MAX; i++)
2315 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2316 SplitPointStack[i][j].parent = NULL;
2317 lock_init(&(SplitPointStack[i][j].lock), NULL);
2322 // destroy_split_point_stack() is called when the program exits, and
2323 // destroys all locks in the precomputed split point objects.
2325 void destroy_split_point_stack() {
2326 for(int i = 0; i < THREAD_MAX; i++)
2327 for(int j = 0; j < MaxActiveSplitPoints; j++)
2328 lock_destroy(&(SplitPointStack[i][j].lock));
2332 // thread_should_stop() checks whether the thread with a given threadID has
2333 // been asked to stop, directly or indirectly. This can happen if a beta
2334 // cutoff has occured in thre thread's currently active split point, or in
2335 // some ancestor of the current split point.
2337 bool thread_should_stop(int threadID) {
2338 assert(threadID >= 0 && threadID < ActiveThreads);
2342 if(Threads[threadID].stop)
2344 if(ActiveThreads <= 2)
2346 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2348 Threads[threadID].stop = true;
2355 // thread_is_available() checks whether the thread with threadID "slave" is
2356 // available to help the thread with threadID "master" at a split point. An
2357 // obvious requirement is that "slave" must be idle. With more than two
2358 // threads, this is not by itself sufficient: If "slave" is the master of
2359 // some active split point, it is only available as a slave to the other
2360 // threads which are busy searching the split point at the top of "slave"'s
2361 // split point stack (the "helpful master concept" in YBWC terminology).
2363 bool thread_is_available(int slave, int master) {
2364 assert(slave >= 0 && slave < ActiveThreads);
2365 assert(master >= 0 && master < ActiveThreads);
2366 assert(ActiveThreads > 1);
2368 if(!Threads[slave].idle || slave == master)
2371 if(Threads[slave].activeSplitPoints == 0)
2372 // No active split points means that the thread is available as a slave
2373 // for any other thread.
2376 if(ActiveThreads == 2)
2379 // Apply the "helpful master" concept if possible.
2380 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2387 // idle_thread_exists() tries to find an idle thread which is available as
2388 // a slave for the thread with threadID "master".
2390 bool idle_thread_exists(int master) {
2391 assert(master >= 0 && master < ActiveThreads);
2392 assert(ActiveThreads > 1);
2394 for(int i = 0; i < ActiveThreads; i++)
2395 if(thread_is_available(i, master))
2401 // split() does the actual work of distributing the work at a node between
2402 // several threads at PV nodes. If it does not succeed in splitting the
2403 // node (because no idle threads are available, or because we have no unused
2404 // split point objects), the function immediately returns false. If
2405 // splitting is possible, a SplitPoint object is initialized with all the
2406 // data that must be copied to the helper threads (the current position and
2407 // search stack, alpha, beta, the search depth, etc.), and we tell our
2408 // helper threads that they have been assigned work. This will cause them
2409 // to instantly leave their idle loops and call sp_search_pv(). When all
2410 // threads have returned from sp_search_pv (or, equivalently, when
2411 // splitPoint->cpus becomes 0), split() returns true.
2413 bool split(const Position &p, SearchStack *sstck, int ply,
2414 Value *alpha, Value *beta, Value *bestValue,
2415 Depth depth, int *moves,
2416 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2418 assert(sstck != NULL);
2419 assert(ply >= 0 && ply < PLY_MAX);
2420 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2421 assert(!pvNode || *alpha < *beta);
2422 assert(*beta <= VALUE_INFINITE);
2423 assert(depth > Depth(0));
2424 assert(master >= 0 && master < ActiveThreads);
2425 assert(ActiveThreads > 1);
2427 SplitPoint *splitPoint;
2432 // If no other thread is available to help us, or if we have too many
2433 // active split points, don't split:
2434 if(!idle_thread_exists(master) ||
2435 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2436 lock_release(&MPLock);
2440 // Pick the next available split point object from the split point stack:
2441 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2442 Threads[master].activeSplitPoints++;
2444 // Initialize the split point object:
2445 splitPoint->parent = Threads[master].splitPoint;
2446 splitPoint->finished = false;
2447 splitPoint->ply = ply;
2448 splitPoint->depth = depth;
2449 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2450 splitPoint->beta = *beta;
2451 splitPoint->pvNode = pvNode;
2452 splitPoint->dcCandidates = dcCandidates;
2453 splitPoint->bestValue = *bestValue;
2454 splitPoint->master = master;
2455 splitPoint->mp = mp;
2456 splitPoint->moves = *moves;
2457 splitPoint->cpus = 1;
2458 splitPoint->pos.copy(p);
2459 splitPoint->parentSstack = sstck;
2460 for(i = 0; i < ActiveThreads; i++)
2461 splitPoint->slaves[i] = 0;
2463 // Copy the current position and the search stack to the master thread:
2464 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2465 Threads[master].splitPoint = splitPoint;
2467 // Make copies of the current position and search stack for each thread:
2468 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2470 if(thread_is_available(i, master)) {
2471 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2472 Threads[i].splitPoint = splitPoint;
2473 splitPoint->slaves[i] = 1;
2477 // Tell the threads that they have work to do. This will make them leave
2479 for(i = 0; i < ActiveThreads; i++)
2480 if(i == master || splitPoint->slaves[i]) {
2481 Threads[i].workIsWaiting = true;
2482 Threads[i].idle = false;
2483 Threads[i].stop = false;
2486 lock_release(&MPLock);
2488 // Everything is set up. The master thread enters the idle loop, from
2489 // which it will instantly launch a search, because its workIsWaiting
2490 // slot is 'true'. We send the split point as a second parameter to the
2491 // idle loop, which means that the main thread will return from the idle
2492 // loop when all threads have finished their work at this split point
2493 // (i.e. when // splitPoint->cpus == 0).
2494 idle_loop(master, splitPoint);
2496 // We have returned from the idle loop, which means that all threads are
2497 // finished. Update alpha, beta and bestvalue, and return:
2499 if(pvNode) *alpha = splitPoint->alpha;
2500 *beta = splitPoint->beta;
2501 *bestValue = splitPoint->bestValue;
2502 Threads[master].stop = false;
2503 Threads[master].idle = false;
2504 Threads[master].activeSplitPoints--;
2505 Threads[master].splitPoint = splitPoint->parent;
2506 lock_release(&MPLock);
2512 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2513 // to start a new search from the root.
2515 void wake_sleeping_threads() {
2516 if(ActiveThreads > 1) {
2517 for(int i = 1; i < ActiveThreads; i++) {
2518 Threads[i].idle = true;
2519 Threads[i].workIsWaiting = false;
2521 #if !defined(_MSC_VER)
2522 pthread_mutex_lock(&WaitLock);
2523 pthread_cond_broadcast(&WaitCond);
2524 pthread_mutex_unlock(&WaitLock);
2526 for(int i = 1; i < THREAD_MAX; i++)
2527 SetEvent(SitIdleEvent[i]);
2533 // init_thread() is the function which is called when a new thread is
2534 // launched. It simply calls the idle_loop() function with the supplied
2535 // threadID. There are two versions of this function; one for POSIX threads
2536 // and one for Windows threads.
2538 #if !defined(_MSC_VER)
2540 void *init_thread(void *threadID) {
2541 idle_loop(*(int *)threadID, NULL);
2547 DWORD WINAPI init_thread(LPVOID threadID) {
2548 idle_loop(*(int *)threadID, NULL);