]> git.sesse.net Git - stockfish/blob - src/search.cpp
09b483cfc4143ec056b1ced25620245f9a925672
[stockfish] / src / search.cpp
1 /*
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-2009 Marco Costalba
5
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.
10
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.
15
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/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cstring>
27 #include <fstream>
28 #include <iostream>
29 #include <sstream>
30
31 #include "book.h"
32 #include "evaluate.h"
33 #include "history.h"
34 #include "misc.h"
35 #include "movegen.h"
36 #include "movepick.h"
37 #include "lock.h"
38 #include "san.h"
39 #include "search.h"
40 #include "thread.h"
41 #include "tt.h"
42 #include "ucioption.h"
43
44 using std::cout;
45 using std::endl;
46
47 ////
48 //// Local definitions
49 ////
50
51 namespace {
52
53   /// Types
54
55   // IterationInfoType stores search results for each iteration
56   //
57   // Because we use relatively small (dynamic) aspiration window,
58   // there happens many fail highs and fail lows in root. And
59   // because we don't do researches in those cases, "value" stored
60   // here is not necessarily exact. Instead in case of fail high/low
61   // we guess what the right value might be and store our guess
62   // as a "speculated value" and then move on. Speculated values are
63   // used just to calculate aspiration window width, so also if are
64   // not exact is not big a problem.
65
66   struct IterationInfoType {
67
68     IterationInfoType(Value v = Value(0), Value sv = Value(0))
69     : value(v), speculatedValue(sv) {}
70
71     Value value, speculatedValue;
72   };
73
74
75   // The BetaCounterType class is used to order moves at ply one.
76   // Apart for the first one that has its score, following moves
77   // normally have score -VALUE_INFINITE, so are ordered according
78   // to the number of beta cutoffs occurred under their subtree during
79   // the last iteration. The counters are per thread variables to avoid
80   // concurrent accessing under SMP case.
81
82   struct BetaCounterType {
83
84     BetaCounterType();
85     void clear();
86     void add(Color us, Depth d, int threadID);
87     void read(Color us, int64_t& our, int64_t& their);
88   };
89
90
91   // The RootMove class is used for moves at the root at the tree. For each
92   // root move, we store a score, a node count, and a PV (really a refutation
93   // in the case of moves which fail low).
94
95   struct RootMove {
96
97     RootMove() { nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL; }
98
99     // RootMove::operator<() is the comparison function used when
100     // sorting the moves. A move m1 is considered to be better
101     // than a move m2 if it has a higher score, or if the moves
102     // have equal score but m1 has the higher node count.
103     bool operator<(const RootMove& m) const {
104
105         return score != m.score ? score < m.score : theirBeta <= m.theirBeta;
106     }
107
108     Move move;
109     Value score;
110     int64_t nodes, cumulativeNodes, ourBeta, theirBeta;
111     Move pv[PLY_MAX_PLUS_2];
112   };
113
114
115   // The RootMoveList class is essentially an array of RootMove objects, with
116   // a handful of methods for accessing the data in the individual moves.
117
118   class RootMoveList {
119
120   public:
121     RootMoveList(Position& pos, Move searchMoves[]);
122
123     int move_count() const { return count; }
124     Move get_move(int moveNum) const { return moves[moveNum].move; }
125     Value get_move_score(int moveNum) const { return moves[moveNum].score; }
126     void set_move_score(int moveNum, Value score) { moves[moveNum].score = score; }
127     Move get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; }
128     int64_t get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; }
129
130     void set_move_nodes(int moveNum, int64_t nodes);
131     void set_beta_counters(int moveNum, int64_t our, int64_t their);
132     void set_move_pv(int moveNum, const Move pv[]);
133     void sort();
134     void sort_multipv(int n);
135
136   private:
137     static const int MaxRootMoves = 500;
138     RootMove moves[MaxRootMoves];
139     int count;
140   };
141
142
143   /// Constants
144
145   // Search depth at iteration 1
146   const Depth InitialDepth = OnePly;
147
148   // Depth limit for selective search
149   const Depth SelectiveDepth = 7 * OnePly;
150
151   // Use internal iterative deepening?
152   const bool UseIIDAtPVNodes = true;
153   const bool UseIIDAtNonPVNodes = true;
154
155   // Internal iterative deepening margin. At Non-PV moves, when
156   // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
157   // search when the static evaluation is at most IIDMargin below beta.
158   const Value IIDMargin = Value(0x100);
159
160   // Easy move margin. An easy move candidate must be at least this much
161   // better than the second best move.
162   const Value EasyMoveMargin = Value(0x200);
163
164   // Problem margin. If the score of the first move at iteration N+1 has
165   // dropped by more than this since iteration N, the boolean variable
166   // "Problem" is set to true, which will make the program spend some extra
167   // time looking for a better move.
168   const Value ProblemMargin = Value(0x28);
169
170   // No problem margin. If the boolean "Problem" is true, and a new move
171   // is found at the root which is less than NoProblemMargin worse than the
172   // best move from the previous iteration, Problem is set back to false.
173   const Value NoProblemMargin = Value(0x14);
174
175   // Null move margin. A null move search will not be done if the approximate
176   // evaluation of the position is more than NullMoveMargin below beta.
177   const Value NullMoveMargin = Value(0x300);
178
179   // If the TT move is at least SingleReplyMargin better then the
180   // remaining ones we will extend it.
181   const Value SingleReplyMargin = Value(0x20);
182
183   // Margins for futility pruning in the quiescence search, and at frontier
184   // and near frontier nodes.
185   const Value FutilityMarginQS = Value(0x80);
186
187   // Each move futility margin is decreased
188   const Value IncrementalFutilityMargin = Value(0x8);
189
190   // Depth limit for razoring
191   const Depth RazorDepth = 4 * OnePly;
192
193   // Remaining depth:                 1 ply         1.5 ply       2 ply         2.5 ply       3 ply         3.5 ply
194   const Value RazorMargins[6]     = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
195
196   // Remaining depth:                 1 ply         1.5 ply       2 ply         2.5 ply       3 ply         3.5 ply
197   const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
198
199
200   /// Variables initialized by UCI options
201
202   // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
203   int LMRPVMoves, LMRNonPVMoves;
204
205   // Depth limit for use of dynamic threat detection
206   Depth ThreatDepth;
207
208   // Last seconds noise filtering (LSN)
209   const bool UseLSNFiltering = true;
210   const int LSNTime = 4000; // In milliseconds
211   const Value LSNValue = value_from_centipawns(200);
212   bool loseOnTime = false;
213
214   // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
215   Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
216   Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
217
218   // Iteration counters
219   int Iteration;
220   BetaCounterType BetaCounter;
221
222   // Scores and number of times the best move changed for each iteration
223   IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
224   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
225
226   // MultiPV mode
227   int MultiPV;
228
229   // Time managment variables
230   int RootMoveNumber;
231   int SearchStartTime;
232   int MaxNodes, MaxDepth;
233   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
234   bool InfiniteSearch, PonderSearch, StopOnPonderhit;
235   bool AbortSearch, Quit;
236   bool FailHigh, FailLow, Problem;
237
238   // Show current line?
239   bool ShowCurrentLine;
240
241   // Log file
242   bool UseLogFile;
243   std::ofstream LogFile;
244
245   // MP related variables
246   int ActiveThreads = 1;
247   Depth MinimumSplitDepth;
248   int MaxThreadsPerSplitPoint;
249   Thread Threads[THREAD_MAX];
250   Lock MPLock;
251   Lock IOLock;
252   bool AllThreadsShouldExit = false;
253   SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
254   bool Idle = true;
255
256 #if !defined(_MSC_VER)
257   pthread_cond_t WaitCond;
258   pthread_mutex_t WaitLock;
259 #else
260   HANDLE SitIdleEvent[THREAD_MAX];
261 #endif
262
263   // Node counters, used only by thread[0] but try to keep in different
264   // cache lines (64 bytes each) from the heavy SMP read accessed variables.
265   int NodesSincePoll;
266   int NodesBetweenPolls = 30000;
267
268   // History table
269   History H;
270
271
272   /// Functions
273
274   Value id_loop(const Position& pos, Move searchMoves[]);
275   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
276   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
277   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
278   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
279   void sp_search(SplitPoint* sp, int threadID);
280   void sp_search_pv(SplitPoint* sp, int threadID);
281   void init_node(SearchStack ss[], int ply, int threadID);
282   void update_pv(SearchStack ss[], int ply);
283   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
284   bool connected_moves(const Position& pos, Move m1, Move m2);
285   bool value_is_mate(Value value);
286   bool move_is_killer(Move m, const SearchStack& ss);
287   Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
288   bool ok_to_do_nullmove(const Position& pos);
289   bool ok_to_prune(const Position& pos, Move m, Move threat);
290   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
291   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
292   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
293   void update_killers(Move m, SearchStack& ss);
294
295   bool fail_high_ply_1();
296   int current_search_time();
297   int nps();
298   void poll();
299   void ponderhit();
300   void print_current_line(SearchStack ss[], int ply, int threadID);
301   void wait_for_stop_or_ponderhit();
302   void init_ss_array(SearchStack ss[]);
303
304   void idle_loop(int threadID, SplitPoint* waitSp);
305   void init_split_point_stack();
306   void destroy_split_point_stack();
307   bool thread_should_stop(int threadID);
308   bool thread_is_available(int slave, int master);
309   bool idle_thread_exists(int master);
310   bool split(const Position& pos, SearchStack* ss, int ply,
311              Value *alpha, Value *beta, Value *bestValue,
312              const Value futilityValue, Depth depth, int *moves,
313              MovePicker *mp, int master, bool pvNode);
314   void wake_sleeping_threads();
315
316 #if !defined(_MSC_VER)
317   void *init_thread(void *threadID);
318 #else
319   DWORD WINAPI init_thread(LPVOID threadID);
320 #endif
321
322 }
323
324
325 ////
326 //// Functions
327 ////
328
329
330 /// perft() is our utility to verify move generation is bug free. All the legal
331 /// moves up to given depth are generated and counted and the sum returned.
332
333 int perft(Position& pos, Depth depth)
334 {
335     Move move;
336     int sum = 0;
337     MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
338
339     // If we are at the last ply we don't need to do and undo
340     // the moves, just to count them.
341     if (depth <= OnePly) // Replace with '<' to test also qsearch
342     {
343         while (mp.get_next_move()) sum++;
344         return sum;
345     }
346
347     // Loop through all legal moves
348     CheckInfo ci(pos);
349     while ((move = mp.get_next_move()) != MOVE_NONE)
350     {
351         StateInfo st;
352         pos.do_move(move, st, ci, pos.move_is_check(move, ci));
353         sum += perft(pos, depth - OnePly);
354         pos.undo_move(move);
355     }
356     return sum;
357 }
358
359
360 /// think() is the external interface to Stockfish's search, and is called when
361 /// the program receives the UCI 'go' command. It initializes various
362 /// search-related global variables, and calls root_search(). It returns false
363 /// when a quit command is received during the search.
364
365 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
366            int time[], int increment[], int movesToGo, int maxDepth,
367            int maxNodes, int maxTime, Move searchMoves[]) {
368
369   // Look for a book move
370   if (!infinite && !ponder && get_option_value_bool("OwnBook"))
371   {
372       Move bookMove;
373       if (get_option_value_string("Book File") != OpeningBook.file_name())
374           OpeningBook.open(get_option_value_string("Book File"));
375
376       bookMove = OpeningBook.get_move(pos);
377       if (bookMove != MOVE_NONE)
378       {
379           cout << "bestmove " << bookMove << endl;
380           return true;
381       }
382   }
383
384   // Initialize global search variables
385   Idle = StopOnPonderhit = AbortSearch = Quit = false;
386   FailHigh = FailLow = Problem = false;
387   SearchStartTime = get_system_time();
388   ExactMaxTime = maxTime;
389   NodesSincePoll = 0;
390   InfiniteSearch = infinite;
391   PonderSearch = ponder;
392
393   for (int i = 0; i < THREAD_MAX; i++)
394   {
395       Threads[i].nodes = 0ULL;
396       Threads[i].failHighPly1 = false;
397   }
398
399   if (button_was_pressed("New Game"))
400       loseOnTime = false; // Reset at the beginning of a new game
401
402   // Read UCI option values
403   TT.set_size(get_option_value_int("Hash"));
404   if (button_was_pressed("Clear Hash"))
405       TT.clear();
406
407   bool PonderingEnabled = get_option_value_bool("Ponder");
408   MultiPV = get_option_value_int("MultiPV");
409
410   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
411   CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
412
413   SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
414   SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
415
416   PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
417   PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
418
419   PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
420   PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
421
422   PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
423   PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
424
425   MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
426   MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
427
428   LMRPVMoves    = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
429   LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
430   ThreatDepth   = get_option_value_int("Threat Depth") * OnePly;
431
432   Chess960 = get_option_value_bool("UCI_Chess960");
433   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
434   UseLogFile = get_option_value_bool("Use Search Log");
435   if (UseLogFile)
436       LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
437
438   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
439   MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
440
441   read_weights(pos.side_to_move());
442
443   // Set the number of active threads
444   int newActiveThreads = get_option_value_int("Threads");
445   if (newActiveThreads != ActiveThreads)
446   {
447       ActiveThreads = newActiveThreads;
448       init_eval(ActiveThreads);
449   }
450
451   // Wake up sleeping threads
452   wake_sleeping_threads();
453
454   for (int i = 1; i < ActiveThreads; i++)
455       assert(thread_is_available(i, 0));
456
457   // Set thinking time
458   int myTime = time[side_to_move];
459   int myIncrement = increment[side_to_move];
460
461   if (!movesToGo) // Sudden death time control
462   {
463       if (myIncrement)
464       {
465           MaxSearchTime = myTime / 30 + myIncrement;
466           AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
467       }
468       else // Blitz game without increment
469       {
470           MaxSearchTime = myTime / 30;
471           AbsoluteMaxSearchTime = myTime / 8;
472       }
473   }
474   else // (x moves) / (y minutes)
475   {
476       if (movesToGo == 1)
477       {
478           MaxSearchTime = myTime / 2;
479           AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
480       }
481       else
482       {
483           MaxSearchTime = myTime / Min(movesToGo, 20);
484           AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
485       }
486   }
487
488   if (PonderingEnabled)
489   {
490       MaxSearchTime += MaxSearchTime / 4;
491       MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
492   }
493
494   // Fixed depth or fixed number of nodes?
495   MaxDepth = maxDepth;
496   if (MaxDepth)
497       InfiniteSearch = true; // HACK
498
499   MaxNodes = maxNodes;
500   if (MaxNodes)
501   {
502       NodesBetweenPolls = Min(MaxNodes, 30000);
503       InfiniteSearch = true; // HACK
504   }
505   else if (myTime && myTime < 1000)
506       NodesBetweenPolls = 1000;
507   else if (myTime && myTime < 5000)
508       NodesBetweenPolls = 5000;
509   else
510       NodesBetweenPolls = 30000;
511
512   // Write information to search log file
513   if (UseLogFile)
514       LogFile << "Searching: " << pos.to_fen() << endl
515               << "infinite: "  << infinite
516               << " ponder: "   << ponder
517               << " time: "     << myTime
518               << " increment: " << myIncrement
519               << " moves to go: " << movesToGo << endl;
520
521   // LSN filtering. Used only for developing purpose. Disabled by default.
522   if (   UseLSNFiltering
523       && loseOnTime)
524   {
525       // Step 2. If after last move we decided to lose on time, do it now!
526        while (SearchStartTime + myTime + 1000 > get_system_time())
527            /* wait here */;
528   }
529
530   // We're ready to start thinking. Call the iterative deepening loop function
531   Value v = id_loop(pos, searchMoves);
532
533
534   if (UseLSNFiltering)
535   {
536       // Step 1. If this is sudden death game and our position is hopeless,
537       // decide to lose on time.
538       if (   !loseOnTime // If we already lost on time, go to step 3.
539           && myTime < LSNTime
540           && myIncrement == 0
541           && movesToGo == 0
542           && v < -LSNValue)
543       {
544           loseOnTime = true;
545       }
546       else if (loseOnTime)
547       {
548           // Step 3. Now after stepping over the time limit, reset flag for next match.
549           loseOnTime = false;
550       }
551   }
552
553   if (UseLogFile)
554       LogFile.close();
555
556   Idle = true;
557   return !Quit;
558 }
559
560
561 /// init_threads() is called during startup. It launches all helper threads,
562 /// and initializes the split point stack and the global locks and condition
563 /// objects.
564
565 void init_threads() {
566
567   volatile int i;
568
569 #if !defined(_MSC_VER)
570   pthread_t pthread[1];
571 #endif
572
573   for (i = 0; i < THREAD_MAX; i++)
574       Threads[i].activeSplitPoints = 0;
575
576   // Initialize global locks
577   lock_init(&MPLock, NULL);
578   lock_init(&IOLock, NULL);
579
580   init_split_point_stack();
581
582 #if !defined(_MSC_VER)
583   pthread_mutex_init(&WaitLock, NULL);
584   pthread_cond_init(&WaitCond, NULL);
585 #else
586   for (i = 0; i < THREAD_MAX; i++)
587       SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
588 #endif
589
590   // All threads except the main thread should be initialized to idle state
591   for (i = 1; i < THREAD_MAX; i++)
592   {
593       Threads[i].stop = false;
594       Threads[i].workIsWaiting = false;
595       Threads[i].idle = true;
596       Threads[i].running = false;
597   }
598
599   // Launch the helper threads
600   for (i = 1; i < THREAD_MAX; i++)
601   {
602 #if !defined(_MSC_VER)
603       pthread_create(pthread, NULL, init_thread, (void*)(&i));
604 #else
605       DWORD iID[1];
606       CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
607 #endif
608
609       // Wait until the thread has finished launching
610       while (!Threads[i].running);
611   }
612 }
613
614
615 /// stop_threads() is called when the program exits. It makes all the
616 /// helper threads exit cleanly.
617
618 void stop_threads() {
619
620   ActiveThreads = THREAD_MAX;  // HACK
621   Idle = false;  // HACK
622   wake_sleeping_threads();
623   AllThreadsShouldExit = true;
624   for (int i = 1; i < THREAD_MAX; i++)
625   {
626       Threads[i].stop = true;
627       while (Threads[i].running);
628   }
629   destroy_split_point_stack();
630 }
631
632
633 /// nodes_searched() returns the total number of nodes searched so far in
634 /// the current search.
635
636 int64_t nodes_searched() {
637
638   int64_t result = 0ULL;
639   for (int i = 0; i < ActiveThreads; i++)
640       result += Threads[i].nodes;
641   return result;
642 }
643
644
645 // SearchStack::init() initializes a search stack. Used at the beginning of a
646 // new search from the root.
647 void SearchStack::init(int ply) {
648
649   pv[ply] = pv[ply + 1] = MOVE_NONE;
650   currentMove = threatMove = MOVE_NONE;
651   reduction = Depth(0);
652 }
653
654 void SearchStack::initKillers() {
655
656   mateKiller = MOVE_NONE;
657   for (int i = 0; i < KILLER_MAX; i++)
658       killers[i] = MOVE_NONE;
659 }
660
661 namespace {
662
663   // id_loop() is the main iterative deepening loop. It calls root_search
664   // repeatedly with increasing depth until the allocated thinking time has
665   // been consumed, the user stops the search, or the maximum search depth is
666   // reached.
667
668   Value id_loop(const Position& pos, Move searchMoves[]) {
669
670     Position p(pos);
671     SearchStack ss[PLY_MAX_PLUS_2];
672
673     // searchMoves are verified, copied, scored and sorted
674     RootMoveList rml(p, searchMoves);
675
676     if (rml.move_count() == 0)
677     {
678         if (PonderSearch)
679             wait_for_stop_or_ponderhit();
680
681         return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
682     }
683
684     // Print RootMoveList c'tor startup scoring to the standard output,
685     // so that we print information also for iteration 1.
686     cout << "info depth " << 1 << "\ninfo depth " << 1
687          << " score " << value_to_string(rml.get_move_score(0))
688          << " time " << current_search_time()
689          << " nodes " << nodes_searched()
690          << " nps " << nps()
691          << " pv " << rml.get_move(0) << "\n";
692
693     // Initialize
694     TT.new_search();
695     H.clear();
696     init_ss_array(ss);
697     IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
698     Iteration = 1;
699
700     // Is one move significantly better than others after initial scoring ?
701     Move EasyMove = MOVE_NONE;
702     if (   rml.move_count() == 1
703         || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
704         EasyMove = rml.get_move(0);
705
706     // Iterative deepening loop
707     while (Iteration < PLY_MAX)
708     {
709         // Initialize iteration
710         rml.sort();
711         Iteration++;
712         BestMoveChangesByIteration[Iteration] = 0;
713         if (Iteration <= 5)
714             ExtraSearchTime = 0;
715
716         cout << "info depth " << Iteration << endl;
717
718         // Calculate dynamic search window based on previous iterations
719         Value alpha, beta;
720
721         if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
722         {
723             int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
724             int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
725
726             int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
727
728             alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
729             beta  = Min(IterationInfo[Iteration - 1].value + delta,  VALUE_INFINITE);
730         }
731         else
732         {
733             alpha = - VALUE_INFINITE;
734             beta  =   VALUE_INFINITE;
735         }
736
737         // Search to the current depth
738         Value value = root_search(p, ss, rml, alpha, beta);
739
740         // Write PV to transposition table, in case the relevant entries have
741         // been overwritten during the search.
742         TT.insert_pv(p, ss[0].pv);
743
744         if (AbortSearch)
745             break; // Value cannot be trusted. Break out immediately!
746
747         //Save info about search result
748         Value speculatedValue;
749         bool fHigh = false;
750         bool fLow = false;
751         Value delta = value - IterationInfo[Iteration - 1].value;
752
753         if (value >= beta)
754         {
755             assert(delta > 0);
756
757             fHigh = true;
758             speculatedValue = value + delta;
759             BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
760         }
761         else if (value <= alpha)
762         {
763             assert(value == alpha);
764             assert(delta < 0);
765
766             fLow = true;
767             speculatedValue = value + delta;
768             BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
769         } else
770             speculatedValue = value;
771
772         speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
773         IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
774
775         // Drop the easy move if it differs from the new best move
776         if (ss[0].pv[0] != EasyMove)
777             EasyMove = MOVE_NONE;
778
779         Problem = false;
780
781         if (!InfiniteSearch)
782         {
783             // Time to stop?
784             bool stopSearch = false;
785
786             // Stop search early if there is only a single legal move,
787             // we search up to Iteration 6 anyway to get a proper score.
788             if (Iteration >= 6 && rml.move_count() == 1)
789                 stopSearch = true;
790
791             // Stop search early when the last two iterations returned a mate score
792             if (  Iteration >= 6
793                 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
794                 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
795                 stopSearch = true;
796
797             // Stop search early if one move seems to be much better than the rest
798             int64_t nodes = nodes_searched();
799             if (   Iteration >= 8
800                 && !fLow
801                 && !fHigh
802                 && EasyMove == ss[0].pv[0]
803                 && (  (   rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
804                        && current_search_time() > MaxSearchTime / 16)
805                     ||(   rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
806                        && current_search_time() > MaxSearchTime / 32)))
807                 stopSearch = true;
808
809             // Add some extra time if the best move has changed during the last two iterations
810             if (Iteration > 5 && Iteration <= 50)
811                 ExtraSearchTime = BestMoveChangesByIteration[Iteration]   * (MaxSearchTime / 2)
812                                 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
813
814             // Stop search if most of MaxSearchTime is consumed at the end of the
815             // iteration. We probably don't have enough time to search the first
816             // move at the next iteration anyway.
817             if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
818                 stopSearch = true;
819
820             if (stopSearch)
821             {
822                 if (!PonderSearch)
823                     break;
824                 else
825                     StopOnPonderhit = true;
826             }
827         }
828
829         if (MaxDepth && Iteration >= MaxDepth)
830             break;
831     }
832
833     rml.sort();
834
835     // If we are pondering, we shouldn't print the best move before we
836     // are told to do so
837     if (PonderSearch)
838         wait_for_stop_or_ponderhit();
839     else
840         // Print final search statistics
841         cout << "info nodes " << nodes_searched()
842              << " nps " << nps()
843              << " time " << current_search_time()
844              << " hashfull " << TT.full() << endl;
845
846     // Print the best move and the ponder move to the standard output
847     if (ss[0].pv[0] == MOVE_NONE)
848     {
849         ss[0].pv[0] = rml.get_move(0);
850         ss[0].pv[1] = MOVE_NONE;
851     }
852     cout << "bestmove " << ss[0].pv[0];
853     if (ss[0].pv[1] != MOVE_NONE)
854         cout << " ponder " << ss[0].pv[1];
855
856     cout << endl;
857
858     if (UseLogFile)
859     {
860         if (dbg_show_mean)
861             dbg_print_mean(LogFile);
862
863         if (dbg_show_hit_rate)
864             dbg_print_hit_rate(LogFile);
865
866         LogFile << "\nNodes: " << nodes_searched()
867                 << "\nNodes/second: " << nps()
868                 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
869
870         StateInfo st;
871         p.do_move(ss[0].pv[0], st);
872         LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
873     }
874     return rml.get_move_score(0);
875   }
876
877
878   // root_search() is the function which searches the root node. It is
879   // similar to search_pv except that it uses a different move ordering
880   // scheme and prints some information to the standard output.
881
882   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta) {
883
884     Value oldAlpha = alpha;
885     Value value;
886     CheckInfo ci(pos);
887
888     // Loop through all the moves in the root move list
889     for (int i = 0; i <  rml.move_count() && !AbortSearch; i++)
890     {
891         if (alpha >= beta)
892         {
893             // We failed high, invalidate and skip next moves, leave node-counters
894             // and beta-counters as they are and quickly return, we will try to do
895             // a research at the next iteration with a bigger aspiration window.
896             rml.set_move_score(i, -VALUE_INFINITE);
897             continue;
898         }
899         int64_t nodes;
900         Move move;
901         StateInfo st;
902         Depth ext, newDepth;
903
904         RootMoveNumber = i + 1;
905         FailHigh = false;
906
907         // Save the current node count before the move is searched
908         nodes = nodes_searched();
909
910         // Reset beta cut-off counters
911         BetaCounter.clear();
912
913         // Pick the next root move, and print the move and the move number to
914         // the standard output.
915         move = ss[0].currentMove = rml.get_move(i);
916
917         if (current_search_time() >= 1000)
918             cout << "info currmove " << move
919                  << " currmovenumber " << RootMoveNumber << endl;
920
921         // Decide search depth for this move
922         bool moveIsCheck = pos.move_is_check(move);
923         bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
924         bool dangerous;
925         ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
926         newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
927
928         // Make the move, and search it
929         pos.do_move(move, st, ci, moveIsCheck);
930
931         if (i < MultiPV)
932         {
933             // Aspiration window is disabled in multi-pv case
934             if (MultiPV > 1)
935                 alpha = -VALUE_INFINITE;
936
937             value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
938
939             // If the value has dropped a lot compared to the last iteration,
940             // set the boolean variable Problem to true. This variable is used
941             // for time managment: When Problem is true, we try to complete the
942             // current iteration before playing a move.
943             Problem = (   Iteration >= 2
944                        && value <= IterationInfo[Iteration - 1].value - ProblemMargin);
945
946             if (Problem && StopOnPonderhit)
947                 StopOnPonderhit = false;
948         }
949         else
950         {
951             // Try to reduce non-pv search depth by one ply if move seems not problematic,
952             // if the move fails high will be re-searched at full depth.
953             if (   newDepth >= 3*OnePly
954                 && i >= MultiPV + LMRPVMoves
955                 && !dangerous
956                 && !captureOrPromotion
957                 && !move_is_castle(move))
958             {
959                 ss[0].reduction = OnePly;
960                 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
961             } else
962                 value = alpha + 1; // Just to trigger next condition
963
964             if (value > alpha)
965             {
966                 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
967
968                 if (value > alpha)
969                 {
970                     // Fail high! Set the boolean variable FailHigh to true, and
971                     // re-search the move using a PV search. The variable FailHigh
972                     // is used for time managment: We try to avoid aborting the
973                     // search prematurely during a fail high research.
974                     FailHigh = true;
975                     value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
976                 }
977             }
978         }
979
980         pos.undo_move(move);
981
982         // Finished searching the move. If AbortSearch is true, the search
983         // was aborted because the user interrupted the search or because we
984         // ran out of time. In this case, the return value of the search cannot
985         // be trusted, and we break out of the loop without updating the best
986         // move and/or PV.
987         if (AbortSearch)
988             break;
989
990         // Remember beta-cutoff and searched nodes counts for this move. The
991         // info is used to sort the root moves at the next iteration.
992         int64_t our, their;
993         BetaCounter.read(pos.side_to_move(), our, their);
994         rml.set_beta_counters(i, our, their);
995         rml.set_move_nodes(i, nodes_searched() - nodes);
996
997         assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
998
999         if (value <= alpha && i >= MultiPV)
1000             rml.set_move_score(i, -VALUE_INFINITE);
1001         else
1002         {
1003             // PV move or new best move!
1004
1005             // Update PV
1006             rml.set_move_score(i, value);
1007             update_pv(ss, 0);
1008             TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1009             rml.set_move_pv(i, ss[0].pv);
1010
1011             if (MultiPV == 1)
1012             {
1013                 // We record how often the best move has been changed in each
1014                 // iteration. This information is used for time managment: When
1015                 // the best move changes frequently, we allocate some more time.
1016                 if (i > 0)
1017                     BestMoveChangesByIteration[Iteration]++;
1018
1019                 // Print search information to the standard output
1020                 cout << "info depth " << Iteration
1021                      << " score " << value_to_string(value)
1022                      << ((value >= beta) ? " lowerbound" :
1023                         ((value <= alpha)? " upperbound" : ""))
1024                      << " time "  << current_search_time()
1025                      << " nodes " << nodes_searched()
1026                      << " nps "   << nps()
1027                      << " pv ";
1028
1029                 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1030                     cout << ss[0].pv[j] << " ";
1031
1032                 cout << endl;
1033
1034                 if (UseLogFile)
1035                 {
1036                     ValueType type =  (value >= beta  ? VALUE_TYPE_LOWER
1037                                     : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1038
1039                     LogFile << pretty_pv(pos, current_search_time(), Iteration,
1040                                          nodes_searched(), value, type, ss[0].pv) << endl;
1041                 }
1042                 if (value > alpha)
1043                     alpha = value;
1044
1045                 // Reset the global variable Problem to false if the value isn't too
1046                 // far below the final value from the last iteration.
1047                 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1048                     Problem = false;
1049             }
1050             else // MultiPV > 1
1051             {
1052                 rml.sort_multipv(i);
1053                 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1054                 {
1055                     cout << "info multipv " << j + 1
1056                          << " score " << value_to_string(rml.get_move_score(j))
1057                          << " depth " << ((j <= i)? Iteration : Iteration - 1)
1058                          << " time " << current_search_time()
1059                          << " nodes " << nodes_searched()
1060                          << " nps " << nps()
1061                          << " pv ";
1062
1063                     for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1064                         cout << rml.get_move_pv(j, k) << " ";
1065
1066                     cout << endl;
1067                 }
1068                 alpha = rml.get_move_score(Min(i, MultiPV-1));
1069             }
1070         } // PV move or new best move
1071
1072         assert(alpha >= oldAlpha);
1073
1074         FailLow = (alpha == oldAlpha);
1075     }
1076     return alpha;
1077   }
1078
1079
1080   // search_pv() is the main search function for PV nodes.
1081
1082   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1083                   Depth depth, int ply, int threadID) {
1084
1085     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1086     assert(beta > alpha && beta <= VALUE_INFINITE);
1087     assert(ply >= 0 && ply < PLY_MAX);
1088     assert(threadID >= 0 && threadID < ActiveThreads);
1089
1090     Move movesSearched[256];
1091     EvalInfo ei;
1092     StateInfo st;
1093     const TTEntry* tte;
1094     Move ttMove, move;
1095     Depth ext, newDepth;
1096     Value oldAlpha, value;
1097     bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1098     int moveCount = 0;
1099     Value bestValue = -VALUE_INFINITE;
1100
1101     if (depth < OnePly)
1102         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1103
1104     // Initialize, and make an early exit in case of an aborted search,
1105     // an instant draw, maximum ply reached, etc.
1106     init_node(ss, ply, threadID);
1107
1108     // After init_node() that calls poll()
1109     if (AbortSearch || thread_should_stop(threadID))
1110         return Value(0);
1111
1112     if (pos.is_draw())
1113         return VALUE_DRAW;
1114
1115     if (ply >= PLY_MAX - 1)
1116         return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1117
1118     // Mate distance pruning
1119     oldAlpha = alpha;
1120     alpha = Max(value_mated_in(ply), alpha);
1121     beta = Min(value_mate_in(ply+1), beta);
1122     if (alpha >= beta)
1123         return alpha;
1124
1125     // Transposition table lookup. At PV nodes, we don't use the TT for
1126     // pruning, but only for move ordering. This is to avoid problems in
1127     // the following areas:
1128     //
1129     // * Repetition draw detection
1130     // * Fifty move rule detection
1131     // * Searching for a mate
1132     // * Printing of full PV line
1133     //
1134     tte = TT.retrieve(pos.get_key());
1135     ttMove = (tte ? tte->move() : MOVE_NONE);
1136
1137     // Go with internal iterative deepening if we don't have a TT move
1138     if (   UseIIDAtPVNodes
1139         && depth >= 5*OnePly
1140         && ttMove == MOVE_NONE)
1141     {
1142         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1143         ttMove = ss[ply].pv[ply];
1144         tte = TT.retrieve(pos.get_key());
1145     }
1146
1147     // Initialize a MovePicker object for the current position, and prepare
1148     // to search all moves
1149     isCheck = pos.is_check();
1150     mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1151     CheckInfo ci(pos);
1152     MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1153
1154     // Loop through all legal moves until no moves remain or a beta cutoff
1155     // occurs.
1156     while (   alpha < beta
1157            && (move = mp.get_next_move()) != MOVE_NONE
1158            && !thread_should_stop(threadID))
1159     {
1160       assert(move_is_ok(move));
1161
1162       singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1163       moveIsCheck = pos.move_is_check(move, ci);
1164       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1165
1166       // Decide the new search depth
1167       ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1168
1169       // Singular extension search. We extend the TT move if its value is much better than
1170       // its siblings. To verify this we do a reduced search on all the other moves but the
1171       // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1172       if (   depth >= 6 * OnePly
1173           && tte
1174           && move == tte->move()
1175           && ext < OnePly
1176           && is_lower_bound(tte->type())
1177           && tte->depth() >= depth - 3 * OnePly)
1178       {
1179           Value ttValue = value_from_tt(tte->value(), ply);
1180
1181           if (abs(ttValue) < VALUE_KNOWN_WIN)
1182           {
1183               Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1184
1185               if (excValue < ttValue - SingleReplyMargin)
1186                   ext = OnePly;
1187           }
1188       }
1189
1190       newDepth = depth - OnePly + ext;
1191
1192       // Update current move
1193       movesSearched[moveCount++] = ss[ply].currentMove = move;
1194
1195       // Make and search the move
1196       pos.do_move(move, st, ci, moveIsCheck);
1197
1198       if (moveCount == 1) // The first move in list is the PV
1199           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1200       else
1201       {
1202         // Try to reduce non-pv search depth by one ply if move seems not problematic,
1203         // if the move fails high will be re-searched at full depth.
1204         if (    depth >= 3*OnePly
1205             &&  moveCount >= LMRPVMoves
1206             && !dangerous
1207             && !captureOrPromotion
1208             && !move_is_castle(move)
1209             && !move_is_killer(move, ss[ply]))
1210         {
1211             ss[ply].reduction = OnePly;
1212             value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1213         }
1214         else
1215             value = alpha + 1; // Just to trigger next condition
1216
1217         if (value > alpha) // Go with full depth non-pv search
1218         {
1219             ss[ply].reduction = Depth(0);
1220             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1221             if (value > alpha && value < beta)
1222             {
1223                 // When the search fails high at ply 1 while searching the first
1224                 // move at the root, set the flag failHighPly1. This is used for
1225                 // time managment:  We don't want to stop the search early in
1226                 // such cases, because resolving the fail high at ply 1 could
1227                 // result in a big drop in score at the root.
1228                 if (ply == 1 && RootMoveNumber == 1)
1229                     Threads[threadID].failHighPly1 = true;
1230
1231                 // A fail high occurred. Re-search at full window (pv search)
1232                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1233                 Threads[threadID].failHighPly1 = false;
1234           }
1235         }
1236       }
1237       pos.undo_move(move);
1238
1239       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1240
1241       // New best move?
1242       if (value > bestValue)
1243       {
1244           bestValue = value;
1245           if (value > alpha)
1246           {
1247               alpha = value;
1248               update_pv(ss, ply);
1249               if (value == value_mate_in(ply + 1))
1250                   ss[ply].mateKiller = move;
1251           }
1252           // If we are at ply 1, and we are searching the first root move at
1253           // ply 0, set the 'Problem' variable if the score has dropped a lot
1254           // (from the computer's point of view) since the previous iteration.
1255           if (   ply == 1
1256               && Iteration >= 2
1257               && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1258               Problem = true;
1259       }
1260
1261       // Split?
1262       if (   ActiveThreads > 1
1263           && bestValue < beta
1264           && depth >= MinimumSplitDepth
1265           && Iteration <= 99
1266           && idle_thread_exists(threadID)
1267           && !AbortSearch
1268           && !thread_should_stop(threadID)
1269           && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1270                    depth, &moveCount, &mp, threadID, true))
1271           break;
1272     }
1273
1274     // All legal moves have been searched.  A special case: If there were
1275     // no legal moves, it must be mate or stalemate.
1276     if (moveCount == 0)
1277         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1278
1279     // If the search is not aborted, update the transposition table,
1280     // history counters, and killer moves.
1281     if (AbortSearch || thread_should_stop(threadID))
1282         return bestValue;
1283
1284     if (bestValue <= oldAlpha)
1285         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1286
1287     else if (bestValue >= beta)
1288     {
1289         BetaCounter.add(pos.side_to_move(), depth, threadID);
1290         move = ss[ply].pv[ply];
1291         if (!pos.move_is_capture_or_promotion(move))
1292         {
1293             update_history(pos, move, depth, movesSearched, moveCount);
1294             update_killers(move, ss[ply]);
1295         }
1296         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1297     }
1298     else
1299         TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1300
1301     return bestValue;
1302   }
1303
1304
1305   // search() is the search function for zero-width nodes.
1306
1307   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1308                int ply, bool allowNullmove, int threadID, Move excludedMove) {
1309
1310     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1311     assert(ply >= 0 && ply < PLY_MAX);
1312     assert(threadID >= 0 && threadID < ActiveThreads);
1313
1314     Move movesSearched[256];
1315     EvalInfo ei;
1316     StateInfo st;
1317     const TTEntry* tte;
1318     Move ttMove, move;
1319     Depth ext, newDepth;
1320     Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1321     bool isCheck, useFutilityPruning, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1322     bool mateThreat = false;
1323     int moveCount = 0;
1324     Value bestValue = -VALUE_INFINITE;
1325
1326     if (depth < OnePly)
1327         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1328
1329     // Initialize, and make an early exit in case of an aborted search,
1330     // an instant draw, maximum ply reached, etc.
1331     init_node(ss, ply, threadID);
1332
1333     // After init_node() that calls poll()
1334     if (AbortSearch || thread_should_stop(threadID))
1335         return Value(0);
1336
1337     if (pos.is_draw())
1338         return VALUE_DRAW;
1339
1340     if (ply >= PLY_MAX - 1)
1341         return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1342
1343     // Mate distance pruning
1344     if (value_mated_in(ply) >= beta)
1345         return beta;
1346
1347     if (value_mate_in(ply + 1) < beta)
1348         return beta - 1;
1349
1350     // We don't want the score of a partial search to overwrite a previous full search
1351     // TT value, so we use a different position key in case of an excluded move exsists.
1352     Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1353
1354     // Transposition table lookup
1355     tte = TT.retrieve(posKey);
1356     ttMove = (tte ? tte->move() : MOVE_NONE);
1357
1358     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1359     {
1360         ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1361         return value_from_tt(tte->value(), ply);
1362     }
1363
1364     approximateEval = refine_eval(tte, quick_evaluate(pos), ply);
1365     isCheck = pos.is_check();
1366
1367     // Null move search
1368     if (    allowNullmove
1369         &&  depth > OnePly
1370         && !isCheck
1371         && !value_is_mate(beta)
1372         &&  ok_to_do_nullmove(pos)
1373         &&  approximateEval >= beta - NullMoveMargin)
1374     {
1375         ss[ply].currentMove = MOVE_NULL;
1376
1377         pos.do_null_move(st);
1378
1379         // Null move dynamic reduction based on depth
1380         int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1381
1382         // Null move dynamic reduction based on value
1383         if (approximateEval - beta > PawnValueMidgame)
1384             R++;
1385
1386         nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1387
1388         pos.undo_null_move();
1389
1390         if (nullValue >= beta)
1391         {
1392             if (depth < 6 * OnePly)
1393                 return beta;
1394
1395             // Do zugzwang verification search
1396             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1397             if (v >= beta)
1398                 return beta;
1399         } else {
1400             // The null move failed low, which means that we may be faced with
1401             // some kind of threat. If the previous move was reduced, check if
1402             // the move that refuted the null move was somehow connected to the
1403             // move which was reduced. If a connection is found, return a fail
1404             // low score (which will cause the reduced move to fail high in the
1405             // parent node, which will trigger a re-search with full depth).
1406             if (nullValue == value_mated_in(ply + 2))
1407                 mateThreat = true;
1408
1409             ss[ply].threatMove = ss[ply + 1].currentMove;
1410             if (   depth < ThreatDepth
1411                 && ss[ply - 1].reduction
1412                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1413                 return beta - 1;
1414         }
1415     }
1416     // Null move search not allowed, try razoring
1417     else if (   !value_is_mate(beta)
1418              && depth < RazorDepth
1419              && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1420              && ss[ply - 1].currentMove != MOVE_NULL
1421              && ttMove == MOVE_NONE
1422              && !pos.has_pawn_on_7th(pos.side_to_move()))
1423     {
1424         Value rbeta = beta - RazorMargins[int(depth) - 2];
1425         Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1426         if (v < rbeta)
1427           return v;
1428     }
1429
1430     // Go with internal iterative deepening if we don't have a TT move
1431     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1432         !isCheck && evaluate(pos, ei, threadID) >= beta - IIDMargin)
1433     {
1434         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1435         ttMove = ss[ply].pv[ply];
1436         tte = TT.retrieve(pos.get_key());
1437     }
1438
1439     // Initialize a MovePicker object for the current position, and prepare
1440     // to search all moves.
1441     MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1442     CheckInfo ci(pos);
1443     futilityValue = VALUE_NONE;
1444     useFutilityPruning = depth < SelectiveDepth && !isCheck;
1445
1446     // Calculate depth dependant futility pruning parameters
1447     const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1448     const int FutilityValueMargin = 112 * bitScanReverse32(int(depth) * int(depth) / 2);
1449
1450     // Avoid calling evaluate() if we already have the score in TT
1451     if (tte && (tte->type() & VALUE_TYPE_EVAL))
1452         futilityValue = value_from_tt(tte->value(), ply) + FutilityValueMargin;
1453
1454     // Loop through all legal moves until no moves remain or a beta cutoff occurs
1455     while (   bestValue < beta
1456            && (move = mp.get_next_move()) != MOVE_NONE
1457            && !thread_should_stop(threadID))
1458     {
1459       assert(move_is_ok(move));
1460
1461       if (move == excludedMove)
1462           continue;
1463
1464       singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1465       moveIsCheck = pos.move_is_check(move, ci);
1466       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1467
1468       // Decide the new search depth
1469       ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1470
1471       // Singular extension search. We extend the TT move if its value is much better than
1472       // its siblings. To verify this we do a reduced search on all the other moves but the
1473       // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1474       if (   depth >= 8 * OnePly
1475           && tte
1476           && move == tte->move()
1477           && !excludedMove // Do not allow recursive single-reply search
1478           && ext < OnePly
1479           && is_lower_bound(tte->type())
1480           && tte->depth() >= depth - 3 * OnePly)
1481       {
1482           Value ttValue = value_from_tt(tte->value(), ply);
1483
1484           if (abs(ttValue) < VALUE_KNOWN_WIN)
1485           {
1486               Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1487
1488               if (excValue < ttValue - SingleReplyMargin)
1489                   ext = OnePly;
1490           }
1491       }
1492
1493       newDepth = depth - OnePly + ext;
1494
1495       // Update current move
1496       movesSearched[moveCount++] = ss[ply].currentMove = move;
1497
1498       // Futility pruning
1499       if (    useFutilityPruning
1500           && !dangerous
1501           && !captureOrPromotion
1502           &&  move != ttMove)
1503       {
1504           // Move count based pruning
1505           if (   moveCount >= FutilityMoveCountMargin
1506               && ok_to_prune(pos, move, ss[ply].threatMove)
1507               && bestValue > value_mated_in(PLY_MAX))
1508               continue;
1509
1510           // Value based pruning
1511           if (futilityValue == VALUE_NONE)
1512               futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1513
1514           futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1515
1516           if (futilityValueScaled < beta)
1517           {
1518               if (futilityValueScaled > bestValue)
1519                   bestValue = futilityValueScaled;
1520               continue;
1521           }
1522       }
1523
1524       // Make and search the move
1525       pos.do_move(move, st, ci, moveIsCheck);
1526
1527       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1528       // if the move fails high will be re-searched at full depth.
1529       if (    depth >= 3*OnePly
1530           &&  moveCount >= LMRNonPVMoves
1531           && !dangerous
1532           && !captureOrPromotion
1533           && !move_is_castle(move)
1534           && !move_is_killer(move, ss[ply]))
1535       {
1536           ss[ply].reduction = OnePly;
1537           value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1538       }
1539       else
1540           value = beta; // Just to trigger next condition
1541
1542       if (value >= beta) // Go with full depth non-pv search
1543       {
1544           ss[ply].reduction = Depth(0);
1545           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1546       }
1547       pos.undo_move(move);
1548
1549       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1550
1551       // New best move?
1552       if (value > bestValue)
1553       {
1554           bestValue = value;
1555           if (value >= beta)
1556               update_pv(ss, ply);
1557
1558           if (value == value_mate_in(ply + 1))
1559               ss[ply].mateKiller = move;
1560       }
1561
1562       // Split?
1563       if (   ActiveThreads > 1
1564           && bestValue < beta
1565           && depth >= MinimumSplitDepth
1566           && Iteration <= 99
1567           && idle_thread_exists(threadID)
1568           && !AbortSearch
1569           && !thread_should_stop(threadID)
1570           && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue,
1571                    depth, &moveCount, &mp, threadID, false))
1572           break;
1573     }
1574
1575     // All legal moves have been searched.  A special case: If there were
1576     // no legal moves, it must be mate or stalemate.
1577     if (moveCount == 0)
1578         return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1579
1580     // If the search is not aborted, update the transposition table,
1581     // history counters, and killer moves.
1582     if (AbortSearch || thread_should_stop(threadID))
1583         return bestValue;
1584
1585     if (bestValue < beta)
1586         TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1587     else
1588     {
1589         BetaCounter.add(pos.side_to_move(), depth, threadID);
1590         move = ss[ply].pv[ply];
1591         if (!pos.move_is_capture_or_promotion(move))
1592         {
1593             update_history(pos, move, depth, movesSearched, moveCount);
1594             update_killers(move, ss[ply]);
1595         }
1596         TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1597     }
1598
1599     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1600
1601     return bestValue;
1602   }
1603
1604
1605   // qsearch() is the quiescence search function, which is called by the main
1606   // search function when the remaining depth is zero (or, to be more precise,
1607   // less than OnePly).
1608
1609   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1610                 Depth depth, int ply, int threadID) {
1611
1612     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1613     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1614     assert(depth <= 0);
1615     assert(ply >= 0 && ply < PLY_MAX);
1616     assert(threadID >= 0 && threadID < ActiveThreads);
1617
1618     EvalInfo ei;
1619     StateInfo st;
1620     Move ttMove, move;
1621     Value staticValue, bestValue, value, futilityValue;
1622     bool isCheck, enoughMaterial, moveIsCheck;
1623     const TTEntry* tte = NULL;
1624     int moveCount = 0;
1625     bool pvNode = (beta - alpha != 1);
1626
1627     // Initialize, and make an early exit in case of an aborted search,
1628     // an instant draw, maximum ply reached, etc.
1629     init_node(ss, ply, threadID);
1630
1631     // After init_node() that calls poll()
1632     if (AbortSearch || thread_should_stop(threadID))
1633         return Value(0);
1634
1635     if (pos.is_draw())
1636         return VALUE_DRAW;
1637
1638     // Transposition table lookup, only when not in PV
1639     if (!pvNode)
1640     {
1641         tte = TT.retrieve(pos.get_key());
1642         if (tte && ok_to_use_TT(tte, depth, beta, ply))
1643         {
1644             assert(tte->type() != VALUE_TYPE_EVAL);
1645
1646             return value_from_tt(tte->value(), ply);
1647         }
1648     }
1649     ttMove = (tte ? tte->move() : MOVE_NONE);
1650
1651     isCheck = pos.is_check();
1652     ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1653
1654     // Evaluate the position statically
1655     if (isCheck)
1656         staticValue = -VALUE_INFINITE;
1657
1658     else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1659     {
1660         // Use the cached evaluation score if possible
1661         assert(ei.futilityMargin == Value(0));
1662
1663         staticValue = value_from_tt(tte->value(), ply);
1664     }
1665     else
1666         staticValue = evaluate(pos, ei, threadID);
1667
1668     if (ply >= PLY_MAX - 1)
1669         return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1670
1671     // Initialize "stand pat score", and return it immediately if it is
1672     // at least beta.
1673     bestValue = staticValue;
1674
1675     if (bestValue >= beta)
1676     {
1677         // Store the score to avoid a future costly evaluation() call
1678         if (!isCheck && !tte && ei.futilityMargin == 0)
1679             TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1680
1681         return bestValue;
1682     }
1683
1684     if (bestValue > alpha)
1685         alpha = bestValue;
1686
1687     // Initialize a MovePicker object for the current position, and prepare
1688     // to search the moves.  Because the depth is <= 0 here, only captures,
1689     // queen promotions and checks (only if depth == 0) will be generated.
1690     MovePicker mp = MovePicker(pos, ttMove, depth, H);
1691     CheckInfo ci(pos);
1692     enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1693
1694     // Loop through the moves until no moves remain or a beta cutoff
1695     // occurs.
1696     while (   alpha < beta
1697            && (move = mp.get_next_move()) != MOVE_NONE)
1698     {
1699       assert(move_is_ok(move));
1700
1701       moveCount++;
1702       ss[ply].currentMove = move;
1703
1704       moveIsCheck = pos.move_is_check(move, ci);
1705
1706       // Futility pruning
1707       if (   enoughMaterial
1708           && !isCheck
1709           && !pvNode
1710           && !moveIsCheck
1711           &&  move != ttMove
1712           && !move_is_promotion(move)
1713           && !pos.move_is_passed_pawn_push(move))
1714       {
1715           futilityValue =  staticValue
1716                          + Max(pos.midgame_value_of_piece_on(move_to(move)),
1717                                pos.endgame_value_of_piece_on(move_to(move)))
1718                          + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1719                          + FutilityMarginQS
1720                          + ei.futilityMargin;
1721
1722           if (futilityValue < alpha)
1723           {
1724               if (futilityValue > bestValue)
1725                   bestValue = futilityValue;
1726               continue;
1727           }
1728       }
1729
1730       // Don't search captures and checks with negative SEE values
1731       if (   !isCheck
1732           &&  move != ttMove
1733           && !move_is_promotion(move)
1734           &&  pos.see_sign(move) < 0)
1735           continue;
1736
1737       // Make and search the move
1738       pos.do_move(move, st, ci, moveIsCheck);
1739       value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1740       pos.undo_move(move);
1741
1742       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1743
1744       // New best move?
1745       if (value > bestValue)
1746       {
1747           bestValue = value;
1748           if (value > alpha)
1749           {
1750               alpha = value;
1751               update_pv(ss, ply);
1752           }
1753        }
1754     }
1755
1756     // All legal moves have been searched.  A special case: If we're in check
1757     // and no legal moves were found, it is checkmate.
1758     if (!moveCount && pos.is_check()) // Mate!
1759         return value_mated_in(ply);
1760
1761     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1762
1763     // Update transposition table
1764     move = ss[ply].pv[ply];
1765     if (!pvNode)
1766     {
1767         // If bestValue isn't changed it means it is still the static evaluation of
1768         // the node, so keep this info to avoid a future costly evaluation() call.
1769         ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1770         Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1771
1772         if (bestValue < beta)
1773             TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1774         else
1775             TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1776     }
1777
1778     // Update killers only for good check moves
1779     if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1780         update_killers(move, ss[ply]);
1781
1782     return bestValue;
1783   }
1784
1785
1786   // sp_search() is used to search from a split point.  This function is called
1787   // by each thread working at the split point.  It is similar to the normal
1788   // search() function, but simpler.  Because we have already probed the hash
1789   // table, done a null move search, and searched the first move before
1790   // splitting, we don't have to repeat all this work in sp_search().  We
1791   // also don't need to store anything to the hash table here:  This is taken
1792   // care of after we return from the split point.
1793
1794   void sp_search(SplitPoint* sp, int threadID) {
1795
1796     assert(threadID >= 0 && threadID < ActiveThreads);
1797     assert(ActiveThreads > 1);
1798
1799     Position pos = Position(sp->pos);
1800     CheckInfo ci(pos);
1801     SearchStack* ss = sp->sstack[threadID];
1802     Value value;
1803     Move move;
1804     bool isCheck = pos.is_check();
1805     bool useFutilityPruning =     sp->depth < SelectiveDepth
1806                               && !isCheck;
1807
1808     const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1809     const int FutilityValueMargin = 112 * bitScanReverse32(int(sp->depth) * int(sp->depth) / 2);
1810
1811     while (    sp->bestValue < sp->beta
1812            && !thread_should_stop(threadID)
1813            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1814     {
1815       assert(move_is_ok(move));
1816
1817       bool moveIsCheck = pos.move_is_check(move, ci);
1818       bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1819
1820       lock_grab(&(sp->lock));
1821       int moveCount = ++sp->moves;
1822       lock_release(&(sp->lock));
1823
1824       ss[sp->ply].currentMove = move;
1825
1826       // Decide the new search depth.
1827       bool dangerous;
1828       Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1829       Depth newDepth = sp->depth - OnePly + ext;
1830
1831       // Prune?
1832       if (    useFutilityPruning
1833           && !dangerous
1834           && !captureOrPromotion)
1835       {
1836           // Move count based pruning
1837           if (   moveCount >= FutilityMoveCountMargin
1838               && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1839               && sp->bestValue > value_mated_in(PLY_MAX))
1840               continue;
1841
1842           // Value based pruning
1843           if (sp->futilityValue == VALUE_NONE)
1844           {
1845               EvalInfo ei;
1846               sp->futilityValue = evaluate(pos, ei, threadID) + FutilityValueMargin;
1847           }
1848
1849           Value futilityValueScaled = sp->futilityValue - moveCount * IncrementalFutilityMargin;
1850
1851           if (futilityValueScaled < sp->beta)
1852           {
1853               if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1854               {
1855                   lock_grab(&(sp->lock));
1856                   if (futilityValueScaled > sp->bestValue)
1857                       sp->bestValue = futilityValueScaled;
1858                   lock_release(&(sp->lock));
1859               }
1860               continue;
1861           }
1862       }
1863
1864       // Make and search the move.
1865       StateInfo st;
1866       pos.do_move(move, st, ci, moveIsCheck);
1867
1868       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1869       // if the move fails high will be re-searched at full depth.
1870       if (   !dangerous
1871           &&  moveCount >= LMRNonPVMoves
1872           && !captureOrPromotion
1873           && !move_is_castle(move)
1874           && !move_is_killer(move, ss[sp->ply]))
1875       {
1876           ss[sp->ply].reduction = OnePly;
1877           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1878       }
1879       else
1880           value = sp->beta; // Just to trigger next condition
1881
1882       if (value >= sp->beta) // Go with full depth non-pv search
1883       {
1884           ss[sp->ply].reduction = Depth(0);
1885           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1886       }
1887       pos.undo_move(move);
1888
1889       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1890
1891       if (thread_should_stop(threadID))
1892           break;
1893
1894       // New best move?
1895       if (value > sp->bestValue) // Less then 2% of cases
1896       {
1897           lock_grab(&(sp->lock));
1898           if (value > sp->bestValue && !thread_should_stop(threadID))
1899           {
1900               sp->bestValue = value;
1901               if (sp->bestValue >= sp->beta)
1902               {
1903                   sp_update_pv(sp->parentSstack, ss, sp->ply);
1904                   for (int i = 0; i < ActiveThreads; i++)
1905                       if (i != threadID && (i == sp->master || sp->slaves[i]))
1906                           Threads[i].stop = true;
1907
1908                   sp->finished = true;
1909               }
1910           }
1911           lock_release(&(sp->lock));
1912       }
1913     }
1914
1915     lock_grab(&(sp->lock));
1916
1917     // If this is the master thread and we have been asked to stop because of
1918     // a beta cutoff higher up in the tree, stop all slave threads.
1919     if (sp->master == threadID && thread_should_stop(threadID))
1920         for (int i = 0; i < ActiveThreads; i++)
1921             if (sp->slaves[i])
1922                 Threads[i].stop = true;
1923
1924     sp->cpus--;
1925     sp->slaves[threadID] = 0;
1926
1927     lock_release(&(sp->lock));
1928   }
1929
1930
1931   // sp_search_pv() is used to search from a PV split point.  This function
1932   // is called by each thread working at the split point.  It is similar to
1933   // the normal search_pv() function, but simpler.  Because we have already
1934   // probed the hash table and searched the first move before splitting, we
1935   // don't have to repeat all this work in sp_search_pv().  We also don't
1936   // need to store anything to the hash table here: This is taken care of
1937   // after we return from the split point.
1938
1939   void sp_search_pv(SplitPoint* sp, int threadID) {
1940
1941     assert(threadID >= 0 && threadID < ActiveThreads);
1942     assert(ActiveThreads > 1);
1943
1944     Position pos = Position(sp->pos);
1945     CheckInfo ci(pos);
1946     SearchStack* ss = sp->sstack[threadID];
1947     Value value;
1948     Move move;
1949
1950     while (    sp->alpha < sp->beta
1951            && !thread_should_stop(threadID)
1952            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1953     {
1954       bool moveIsCheck = pos.move_is_check(move, ci);
1955       bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1956
1957       assert(move_is_ok(move));
1958
1959       lock_grab(&(sp->lock));
1960       int moveCount = ++sp->moves;
1961       lock_release(&(sp->lock));
1962
1963       ss[sp->ply].currentMove = move;
1964
1965       // Decide the new search depth.
1966       bool dangerous;
1967       Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1968       Depth newDepth = sp->depth - OnePly + ext;
1969
1970       // Make and search the move.
1971       StateInfo st;
1972       pos.do_move(move, st, ci, moveIsCheck);
1973
1974       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1975       // if the move fails high will be re-searched at full depth.
1976       if (   !dangerous
1977           &&  moveCount >= LMRPVMoves
1978           && !captureOrPromotion
1979           && !move_is_castle(move)
1980           && !move_is_killer(move, ss[sp->ply]))
1981       {
1982           ss[sp->ply].reduction = OnePly;
1983           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1984       }
1985       else
1986           value = sp->alpha + 1; // Just to trigger next condition
1987
1988       if (value > sp->alpha) // Go with full depth non-pv search
1989       {
1990           ss[sp->ply].reduction = Depth(0);
1991           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1992
1993           if (value > sp->alpha && value < sp->beta)
1994           {
1995               // When the search fails high at ply 1 while searching the first
1996               // move at the root, set the flag failHighPly1.  This is used for
1997               // time managment: We don't want to stop the search early in
1998               // such cases, because resolving the fail high at ply 1 could
1999               // result in a big drop in score at the root.
2000               if (sp->ply == 1 && RootMoveNumber == 1)
2001                   Threads[threadID].failHighPly1 = true;
2002
2003               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
2004               Threads[threadID].failHighPly1 = false;
2005         }
2006       }
2007       pos.undo_move(move);
2008
2009       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2010
2011       if (thread_should_stop(threadID))
2012           break;
2013
2014       // New best move?
2015       lock_grab(&(sp->lock));
2016       if (value > sp->bestValue && !thread_should_stop(threadID))
2017       {
2018           sp->bestValue = value;
2019           if (value > sp->alpha)
2020           {
2021               sp->alpha = value;
2022               sp_update_pv(sp->parentSstack, ss, sp->ply);
2023               if (value == value_mate_in(sp->ply + 1))
2024                   ss[sp->ply].mateKiller = move;
2025
2026               if (value >= sp->beta)
2027               {
2028                   for (int i = 0; i < ActiveThreads; i++)
2029                       if (i != threadID && (i == sp->master || sp->slaves[i]))
2030                           Threads[i].stop = true;
2031
2032                   sp->finished = true;
2033               }
2034         }
2035         // If we are at ply 1, and we are searching the first root move at
2036         // ply 0, set the 'Problem' variable if the score has dropped a lot
2037         // (from the computer's point of view) since the previous iteration.
2038         if (   sp->ply == 1
2039             && Iteration >= 2
2040             && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2041             Problem = true;
2042       }
2043       lock_release(&(sp->lock));
2044     }
2045
2046     lock_grab(&(sp->lock));
2047
2048     // If this is the master thread and we have been asked to stop because of
2049     // a beta cutoff higher up in the tree, stop all slave threads.
2050     if (sp->master == threadID && thread_should_stop(threadID))
2051         for (int i = 0; i < ActiveThreads; i++)
2052             if (sp->slaves[i])
2053                 Threads[i].stop = true;
2054
2055     sp->cpus--;
2056     sp->slaves[threadID] = 0;
2057
2058     lock_release(&(sp->lock));
2059   }
2060
2061   /// The BetaCounterType class
2062
2063   BetaCounterType::BetaCounterType() { clear(); }
2064
2065   void BetaCounterType::clear() {
2066
2067     for (int i = 0; i < THREAD_MAX; i++)
2068         Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2069   }
2070
2071   void BetaCounterType::add(Color us, Depth d, int threadID) {
2072
2073     // Weighted count based on depth
2074     Threads[threadID].betaCutOffs[us] += unsigned(d);
2075   }
2076
2077   void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2078
2079     our = their = 0UL;
2080     for (int i = 0; i < THREAD_MAX; i++)
2081     {
2082         our += Threads[i].betaCutOffs[us];
2083         their += Threads[i].betaCutOffs[opposite_color(us)];
2084     }
2085   }
2086
2087
2088   /// The RootMoveList class
2089
2090   // RootMoveList c'tor
2091
2092   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2093
2094     MoveStack mlist[MaxRootMoves];
2095     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2096
2097     // Generate all legal moves
2098     MoveStack* last = generate_moves(pos, mlist);
2099
2100     // Add each move to the moves[] array
2101     for (MoveStack* cur = mlist; cur != last; cur++)
2102     {
2103         bool includeMove = includeAllMoves;
2104
2105         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2106             includeMove = (searchMoves[k] == cur->move);
2107
2108         if (!includeMove)
2109             continue;
2110
2111         // Find a quick score for the move
2112         StateInfo st;
2113         SearchStack ss[PLY_MAX_PLUS_2];
2114         init_ss_array(ss);
2115
2116         moves[count].move = cur->move;
2117         pos.do_move(moves[count].move, st);
2118         moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2119         pos.undo_move(moves[count].move);
2120         moves[count].pv[0] = moves[count].move;
2121         moves[count].pv[1] = MOVE_NONE;
2122         count++;
2123     }
2124     sort();
2125   }
2126
2127
2128   // RootMoveList simple methods definitions
2129
2130   void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2131
2132     moves[moveNum].nodes = nodes;
2133     moves[moveNum].cumulativeNodes += nodes;
2134   }
2135
2136   void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2137
2138     moves[moveNum].ourBeta = our;
2139     moves[moveNum].theirBeta = their;
2140   }
2141
2142   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2143
2144     int j;
2145
2146     for (j = 0; pv[j] != MOVE_NONE; j++)
2147         moves[moveNum].pv[j] = pv[j];
2148
2149     moves[moveNum].pv[j] = MOVE_NONE;
2150   }
2151
2152
2153   // RootMoveList::sort() sorts the root move list at the beginning of a new
2154   // iteration.
2155
2156   void RootMoveList::sort() {
2157
2158     sort_multipv(count - 1); // Sort all items
2159   }
2160
2161
2162   // RootMoveList::sort_multipv() sorts the first few moves in the root move
2163   // list by their scores and depths. It is used to order the different PVs
2164   // correctly in MultiPV mode.
2165
2166   void RootMoveList::sort_multipv(int n) {
2167
2168     int i,j;
2169
2170     for (i = 1; i <= n; i++)
2171     {
2172         RootMove rm = moves[i];
2173         for (j = i; j > 0 && moves[j - 1] < rm; j--)
2174             moves[j] = moves[j - 1];
2175
2176         moves[j] = rm;
2177     }
2178   }
2179
2180
2181   // init_node() is called at the beginning of all the search functions
2182   // (search(), search_pv(), qsearch(), and so on) and initializes the
2183   // search stack object corresponding to the current node. Once every
2184   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2185   // for user input and checks whether it is time to stop the search.
2186
2187   void init_node(SearchStack ss[], int ply, int threadID) {
2188
2189     assert(ply >= 0 && ply < PLY_MAX);
2190     assert(threadID >= 0 && threadID < ActiveThreads);
2191
2192     Threads[threadID].nodes++;
2193
2194     if (threadID == 0)
2195     {
2196         NodesSincePoll++;
2197         if (NodesSincePoll >= NodesBetweenPolls)
2198         {
2199             poll();
2200             NodesSincePoll = 0;
2201         }
2202     }
2203     ss[ply].init(ply);
2204     ss[ply + 2].initKillers();
2205
2206     if (Threads[threadID].printCurrentLine)
2207         print_current_line(ss, ply, threadID);
2208   }
2209
2210
2211   // update_pv() is called whenever a search returns a value > alpha.
2212   // It updates the PV in the SearchStack object corresponding to the
2213   // current node.
2214
2215   void update_pv(SearchStack ss[], int ply) {
2216
2217     assert(ply >= 0 && ply < PLY_MAX);
2218
2219     int p;
2220
2221     ss[ply].pv[ply] = ss[ply].currentMove;
2222
2223     for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2224         ss[ply].pv[p] = ss[ply + 1].pv[p];
2225
2226     ss[ply].pv[p] = MOVE_NONE;
2227   }
2228
2229
2230   // sp_update_pv() is a variant of update_pv for use at split points. The
2231   // difference between the two functions is that sp_update_pv also updates
2232   // the PV at the parent node.
2233
2234   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2235
2236     assert(ply >= 0 && ply < PLY_MAX);
2237
2238     int p;
2239
2240     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2241
2242     for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2243         ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2244
2245     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2246   }
2247
2248
2249   // connected_moves() tests whether two moves are 'connected' in the sense
2250   // that the first move somehow made the second move possible (for instance
2251   // if the moving piece is the same in both moves). The first move is assumed
2252   // to be the move that was made to reach the current position, while the
2253   // second move is assumed to be a move from the current position.
2254
2255   bool connected_moves(const Position& pos, Move m1, Move m2) {
2256
2257     Square f1, t1, f2, t2;
2258     Piece p;
2259
2260     assert(move_is_ok(m1));
2261     assert(move_is_ok(m2));
2262
2263     if (m2 == MOVE_NONE)
2264         return false;
2265
2266     // Case 1: The moving piece is the same in both moves
2267     f2 = move_from(m2);
2268     t1 = move_to(m1);
2269     if (f2 == t1)
2270         return true;
2271
2272     // Case 2: The destination square for m2 was vacated by m1
2273     t2 = move_to(m2);
2274     f1 = move_from(m1);
2275     if (t2 == f1)
2276         return true;
2277
2278     // Case 3: Moving through the vacated square
2279     if (   piece_is_slider(pos.piece_on(f2))
2280         && bit_is_set(squares_between(f2, t2), f1))
2281       return true;
2282
2283     // Case 4: The destination square for m2 is defended by the moving piece in m1
2284     p = pos.piece_on(t1);
2285     if (bit_is_set(pos.attacks_from(p, t1), t2))
2286         return true;
2287
2288     // Case 5: Discovered check, checking piece is the piece moved in m1
2289     if (    piece_is_slider(p)
2290         &&  bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2291         && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2292     {
2293         // discovered_check_candidates() works also if the Position's side to
2294         // move is the opposite of the checking piece.
2295         Color them = opposite_color(pos.side_to_move());
2296         Bitboard dcCandidates = pos.discovered_check_candidates(them);
2297
2298         if (bit_is_set(dcCandidates, f2))
2299             return true;
2300     }
2301     return false;
2302   }
2303
2304
2305   // value_is_mate() checks if the given value is a mate one
2306   // eventually compensated for the ply.
2307
2308   bool value_is_mate(Value value) {
2309
2310     assert(abs(value) <= VALUE_INFINITE);
2311
2312     return   value <= value_mated_in(PLY_MAX)
2313           || value >= value_mate_in(PLY_MAX);
2314   }
2315
2316
2317   // move_is_killer() checks if the given move is among the
2318   // killer moves of that ply.
2319
2320   bool move_is_killer(Move m, const SearchStack& ss) {
2321
2322       const Move* k = ss.killers;
2323       for (int i = 0; i < KILLER_MAX; i++, k++)
2324           if (*k == m)
2325               return true;
2326
2327       return false;
2328   }
2329
2330
2331   // extension() decides whether a move should be searched with normal depth,
2332   // or with extended depth. Certain classes of moves (checking moves, in
2333   // particular) are searched with bigger depth than ordinary moves and in
2334   // any case are marked as 'dangerous'. Note that also if a move is not
2335   // extended, as example because the corresponding UCI option is set to zero,
2336   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2337
2338   Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2339                   bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2340
2341     assert(m != MOVE_NONE);
2342
2343     Depth result = Depth(0);
2344     *dangerous = moveIsCheck | singleEvasion | mateThreat;
2345
2346     if (*dangerous)
2347     {
2348         if (moveIsCheck)
2349             result += CheckExtension[pvNode];
2350
2351         if (singleEvasion)
2352             result += SingleEvasionExtension[pvNode];
2353
2354         if (mateThreat)
2355             result += MateThreatExtension[pvNode];
2356     }
2357
2358     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2359     {
2360         Color c = pos.side_to_move();
2361         if (relative_rank(c, move_to(m)) == RANK_7)
2362         {
2363             result += PawnPushTo7thExtension[pvNode];
2364             *dangerous = true;
2365         }
2366         if (pos.pawn_is_passed(c, move_to(m)))
2367         {
2368             result += PassedPawnExtension[pvNode];
2369             *dangerous = true;
2370         }
2371     }
2372
2373     if (   captureOrPromotion
2374         && pos.type_of_piece_on(move_to(m)) != PAWN
2375         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2376             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2377         && !move_is_promotion(m)
2378         && !move_is_ep(m))
2379     {
2380         result += PawnEndgameExtension[pvNode];
2381         *dangerous = true;
2382     }
2383
2384     if (   pvNode
2385         && captureOrPromotion
2386         && pos.type_of_piece_on(move_to(m)) != PAWN
2387         && pos.see_sign(m) >= 0)
2388     {
2389         result += OnePly/2;
2390         *dangerous = true;
2391     }
2392
2393     return Min(result, OnePly);
2394   }
2395
2396
2397   // ok_to_do_nullmove() looks at the current position and decides whether
2398   // doing a 'null move' should be allowed. In order to avoid zugzwang
2399   // problems, null moves are not allowed when the side to move has very
2400   // little material left. Currently, the test is a bit too simple: Null
2401   // moves are avoided only when the side to move has only pawns left.
2402   // It's probably a good idea to avoid null moves in at least some more
2403   // complicated endgames, e.g. KQ vs KR.  FIXME
2404
2405   bool ok_to_do_nullmove(const Position& pos) {
2406
2407     return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2408   }
2409
2410
2411   // ok_to_prune() tests whether it is safe to forward prune a move. Only
2412   // non-tactical moves late in the move list close to the leaves are
2413   // candidates for pruning.
2414
2415   bool ok_to_prune(const Position& pos, Move m, Move threat) {
2416
2417     assert(move_is_ok(m));
2418     assert(threat == MOVE_NONE || move_is_ok(threat));
2419     assert(!pos.move_is_check(m));
2420     assert(!pos.move_is_capture_or_promotion(m));
2421     assert(!pos.move_is_passed_pawn_push(m));
2422
2423     Square mfrom, mto, tfrom, tto;
2424
2425     // Prune if there isn't any threat move and
2426     // is not a castling move (common case).
2427     if (threat == MOVE_NONE && !move_is_castle(m))
2428         return true;
2429
2430     mfrom = move_from(m);
2431     mto = move_to(m);
2432     tfrom = move_from(threat);
2433     tto = move_to(threat);
2434
2435     // Case 1: Castling moves are never pruned
2436     if (move_is_castle(m))
2437         return false;
2438
2439     // Case 2: Don't prune moves which move the threatened piece
2440     if (mfrom == tto)
2441         return false;
2442
2443     // Case 3: If the threatened piece has value less than or equal to the
2444     // value of the threatening piece, don't prune move which defend it.
2445     if (   pos.move_is_capture(threat)
2446         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2447             || pos.type_of_piece_on(tfrom) == KING)
2448         && pos.move_attacks_square(m, tto))
2449         return false;
2450
2451     // Case 4: If the moving piece in the threatened move is a slider, don't
2452     // prune safe moves which block its ray.
2453     if (   piece_is_slider(pos.piece_on(tfrom))
2454         && bit_is_set(squares_between(tfrom, tto), mto)
2455         && pos.see_sign(m) >= 0)
2456         return false;
2457
2458     return true;
2459   }
2460
2461
2462   // ok_to_use_TT() returns true if a transposition table score
2463   // can be used at a given point in search.
2464
2465   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2466
2467     Value v = value_from_tt(tte->value(), ply);
2468
2469     return   (   tte->depth() >= depth
2470               || v >= Max(value_mate_in(PLY_MAX), beta)
2471               || v < Min(value_mated_in(PLY_MAX), beta))
2472
2473           && (   (is_lower_bound(tte->type()) && v >= beta)
2474               || (is_upper_bound(tte->type()) && v < beta));
2475   }
2476
2477
2478   // refine_eval() returns the transposition table score if
2479   // possible otherwise falls back on static position evaluation.
2480
2481   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2482
2483       if (!tte)
2484           return defaultEval;
2485
2486       Value v = value_from_tt(tte->value(), ply);
2487
2488       if (   (is_lower_bound(tte->type()) && v >= defaultEval)
2489           || (is_upper_bound(tte->type()) && v < defaultEval))
2490           return v;
2491
2492       return defaultEval;
2493   }
2494
2495   // update_history() registers a good move that produced a beta-cutoff
2496   // in history and marks as failures all the other moves of that ply.
2497
2498   void update_history(const Position& pos, Move move, Depth depth,
2499                       Move movesSearched[], int moveCount) {
2500
2501     Move m;
2502
2503     H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2504
2505     for (int i = 0; i < moveCount - 1; i++)
2506     {
2507         m = movesSearched[i];
2508
2509         assert(m != move);
2510
2511         if (!pos.move_is_capture_or_promotion(m))
2512             H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2513     }
2514   }
2515
2516
2517   // update_killers() add a good move that produced a beta-cutoff
2518   // among the killer moves of that ply.
2519
2520   void update_killers(Move m, SearchStack& ss) {
2521
2522     if (m == ss.killers[0])
2523         return;
2524
2525     for (int i = KILLER_MAX - 1; i > 0; i--)
2526         ss.killers[i] = ss.killers[i - 1];
2527
2528     ss.killers[0] = m;
2529   }
2530
2531
2532   // fail_high_ply_1() checks if some thread is currently resolving a fail
2533   // high at ply 1 at the node below the first root node.  This information
2534   // is used for time management.
2535
2536   bool fail_high_ply_1() {
2537
2538     for (int i = 0; i < ActiveThreads; i++)
2539         if (Threads[i].failHighPly1)
2540             return true;
2541
2542     return false;
2543   }
2544
2545
2546   // current_search_time() returns the number of milliseconds which have passed
2547   // since the beginning of the current search.
2548
2549   int current_search_time() {
2550
2551     return get_system_time() - SearchStartTime;
2552   }
2553
2554
2555   // nps() computes the current nodes/second count.
2556
2557   int nps() {
2558
2559     int t = current_search_time();
2560     return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2561   }
2562
2563
2564   // poll() performs two different functions: It polls for user input, and it
2565   // looks at the time consumed so far and decides if it's time to abort the
2566   // search.
2567
2568   void poll() {
2569
2570     static int lastInfoTime;
2571     int t = current_search_time();
2572
2573     //  Poll for input
2574     if (Bioskey())
2575     {
2576         // We are line oriented, don't read single chars
2577         std::string command;
2578
2579         if (!std::getline(std::cin, command))
2580             command = "quit";
2581
2582         if (command == "quit")
2583         {
2584             AbortSearch = true;
2585             PonderSearch = false;
2586             Quit = true;
2587             return;
2588         }
2589         else if (command == "stop")
2590         {
2591             AbortSearch = true;
2592             PonderSearch = false;
2593         }
2594         else if (command == "ponderhit")
2595             ponderhit();
2596     }
2597
2598     // Print search information
2599     if (t < 1000)
2600         lastInfoTime = 0;
2601
2602     else if (lastInfoTime > t)
2603         // HACK: Must be a new search where we searched less than
2604         // NodesBetweenPolls nodes during the first second of search.
2605         lastInfoTime = 0;
2606
2607     else if (t - lastInfoTime >= 1000)
2608     {
2609         lastInfoTime = t;
2610         lock_grab(&IOLock);
2611
2612         if (dbg_show_mean)
2613             dbg_print_mean();
2614
2615         if (dbg_show_hit_rate)
2616             dbg_print_hit_rate();
2617
2618         cout << "info nodes " << nodes_searched() << " nps " << nps()
2619              << " time " << t << " hashfull " << TT.full() << endl;
2620
2621         lock_release(&IOLock);
2622
2623         if (ShowCurrentLine)
2624             Threads[0].printCurrentLine = true;
2625     }
2626
2627     // Should we stop the search?
2628     if (PonderSearch)
2629         return;
2630
2631     bool stillAtFirstMove =    RootMoveNumber == 1
2632                            && !FailLow
2633                            &&  t > MaxSearchTime + ExtraSearchTime;
2634
2635     bool noProblemFound =   !FailHigh
2636                          && !FailLow
2637                          && !fail_high_ply_1()
2638                          && !Problem
2639                          &&  t > 6 * (MaxSearchTime + ExtraSearchTime);
2640
2641     bool noMoreTime =   t > AbsoluteMaxSearchTime
2642                      || stillAtFirstMove //FIXME: We are not checking any problem flags, BUG?
2643                      || noProblemFound;
2644
2645     if (   (Iteration >= 3 && !InfiniteSearch && noMoreTime)
2646         || (ExactMaxTime && t >= ExactMaxTime)
2647         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2648         AbortSearch = true;
2649   }
2650
2651
2652   // ponderhit() is called when the program is pondering (i.e. thinking while
2653   // it's the opponent's turn to move) in order to let the engine know that
2654   // it correctly predicted the opponent's move.
2655
2656   void ponderhit() {
2657
2658     int t = current_search_time();
2659     PonderSearch = false;
2660
2661     bool stillAtFirstMove =    RootMoveNumber == 1
2662                            && !FailLow
2663                            &&  t > MaxSearchTime + ExtraSearchTime;
2664
2665     bool noProblemFound =   !FailHigh
2666                          && !FailLow
2667                          && !fail_high_ply_1()
2668                          && !Problem
2669                          &&  t > 6 * (MaxSearchTime + ExtraSearchTime);
2670
2671     bool noMoreTime =   t > AbsoluteMaxSearchTime
2672                      || stillAtFirstMove
2673                      || noProblemFound;
2674
2675     if (Iteration >= 3 && !InfiniteSearch && (noMoreTime || StopOnPonderhit))
2676         AbortSearch = true;
2677   }
2678
2679
2680   // print_current_line() prints the current line of search for a given
2681   // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2682
2683   void print_current_line(SearchStack ss[], int ply, int threadID) {
2684
2685     assert(ply >= 0 && ply < PLY_MAX);
2686     assert(threadID >= 0 && threadID < ActiveThreads);
2687
2688     if (!Threads[threadID].idle)
2689     {
2690         lock_grab(&IOLock);
2691         cout << "info currline " << (threadID + 1);
2692         for (int p = 0; p < ply; p++)
2693             cout << " " << ss[p].currentMove;
2694
2695         cout << endl;
2696         lock_release(&IOLock);
2697     }
2698     Threads[threadID].printCurrentLine = false;
2699     if (threadID + 1 < ActiveThreads)
2700         Threads[threadID + 1].printCurrentLine = true;
2701   }
2702
2703
2704   // init_ss_array() does a fast reset of the first entries of a SearchStack array
2705
2706   void init_ss_array(SearchStack ss[]) {
2707
2708     for (int i = 0; i < 3; i++)
2709     {
2710         ss[i].init(i);
2711         ss[i].initKillers();
2712     }
2713   }
2714
2715
2716   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2717   // while the program is pondering. The point is to work around a wrinkle in
2718   // the UCI protocol: When pondering, the engine is not allowed to give a
2719   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2720   // We simply wait here until one of these commands is sent, and return,
2721   // after which the bestmove and pondermove will be printed (in id_loop()).
2722
2723   void wait_for_stop_or_ponderhit() {
2724
2725     std::string command;
2726
2727     while (true)
2728     {
2729         if (!std::getline(std::cin, command))
2730             command = "quit";
2731
2732         if (command == "quit")
2733         {
2734             Quit = true;
2735             break;
2736         }
2737         else if (command == "ponderhit" || command == "stop")
2738             break;
2739     }
2740   }
2741
2742
2743   // idle_loop() is where the threads are parked when they have no work to do.
2744   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2745   // object for which the current thread is the master.
2746
2747   void idle_loop(int threadID, SplitPoint* waitSp) {
2748
2749     assert(threadID >= 0 && threadID < THREAD_MAX);
2750
2751     Threads[threadID].running = true;
2752
2753     while (true)
2754     {
2755         if (AllThreadsShouldExit && threadID != 0)
2756             break;
2757
2758         // If we are not thinking, wait for a condition to be signaled
2759         // instead of wasting CPU time polling for work.
2760         while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2761         {
2762
2763 #if !defined(_MSC_VER)
2764             pthread_mutex_lock(&WaitLock);
2765             if (Idle || threadID >= ActiveThreads)
2766                 pthread_cond_wait(&WaitCond, &WaitLock);
2767
2768             pthread_mutex_unlock(&WaitLock);
2769 #else
2770             WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2771 #endif
2772         }
2773
2774       // If this thread has been assigned work, launch a search
2775       if (Threads[threadID].workIsWaiting)
2776       {
2777           Threads[threadID].workIsWaiting = false;
2778           if (Threads[threadID].splitPoint->pvNode)
2779               sp_search_pv(Threads[threadID].splitPoint, threadID);
2780           else
2781               sp_search(Threads[threadID].splitPoint, threadID);
2782
2783           Threads[threadID].idle = true;
2784       }
2785
2786       // If this thread is the master of a split point and all threads have
2787       // finished their work at this split point, return from the idle loop.
2788       if (waitSp != NULL && waitSp->cpus == 0)
2789           return;
2790     }
2791
2792     Threads[threadID].running = false;
2793   }
2794
2795
2796   // init_split_point_stack() is called during program initialization, and
2797   // initializes all split point objects.
2798
2799   void init_split_point_stack() {
2800
2801     for (int i = 0; i < THREAD_MAX; i++)
2802         for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2803         {
2804             SplitPointStack[i][j].parent = NULL;
2805             lock_init(&(SplitPointStack[i][j].lock), NULL);
2806         }
2807   }
2808
2809
2810   // destroy_split_point_stack() is called when the program exits, and
2811   // destroys all locks in the precomputed split point objects.
2812
2813   void destroy_split_point_stack() {
2814
2815     for (int i = 0; i < THREAD_MAX; i++)
2816         for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2817             lock_destroy(&(SplitPointStack[i][j].lock));
2818   }
2819
2820
2821   // thread_should_stop() checks whether the thread with a given threadID has
2822   // been asked to stop, directly or indirectly. This can happen if a beta
2823   // cutoff has occurred in the thread's currently active split point, or in
2824   // some ancestor of the current split point.
2825
2826   bool thread_should_stop(int threadID) {
2827
2828     assert(threadID >= 0 && threadID < ActiveThreads);
2829
2830     SplitPoint* sp;
2831
2832     if (Threads[threadID].stop)
2833         return true;
2834     if (ActiveThreads <= 2)
2835         return false;
2836     for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2837         if (sp->finished)
2838         {
2839             Threads[threadID].stop = true;
2840             return true;
2841         }
2842     return false;
2843   }
2844
2845
2846   // thread_is_available() checks whether the thread with threadID "slave" is
2847   // available to help the thread with threadID "master" at a split point. An
2848   // obvious requirement is that "slave" must be idle. With more than two
2849   // threads, this is not by itself sufficient:  If "slave" is the master of
2850   // some active split point, it is only available as a slave to the other
2851   // threads which are busy searching the split point at the top of "slave"'s
2852   // split point stack (the "helpful master concept" in YBWC terminology).
2853
2854   bool thread_is_available(int slave, int master) {
2855
2856     assert(slave >= 0 && slave < ActiveThreads);
2857     assert(master >= 0 && master < ActiveThreads);
2858     assert(ActiveThreads > 1);
2859
2860     if (!Threads[slave].idle || slave == master)
2861         return false;
2862
2863     if (Threads[slave].activeSplitPoints == 0)
2864         // No active split points means that the thread is available as
2865         // a slave for any other thread.
2866         return true;
2867
2868     if (ActiveThreads == 2)
2869         return true;
2870
2871     // Apply the "helpful master" concept if possible
2872     if (SplitPointStack[slave][Threads[slave].activeSplitPoints - 1].slaves[master])
2873         return true;
2874
2875     return false;
2876   }
2877
2878
2879   // idle_thread_exists() tries to find an idle thread which is available as
2880   // a slave for the thread with threadID "master".
2881
2882   bool idle_thread_exists(int master) {
2883
2884     assert(master >= 0 && master < ActiveThreads);
2885     assert(ActiveThreads > 1);
2886
2887     for (int i = 0; i < ActiveThreads; i++)
2888         if (thread_is_available(i, master))
2889             return true;
2890
2891     return false;
2892   }
2893
2894
2895   // split() does the actual work of distributing the work at a node between
2896   // several threads at PV nodes. If it does not succeed in splitting the
2897   // node (because no idle threads are available, or because we have no unused
2898   // split point objects), the function immediately returns false. If
2899   // splitting is possible, a SplitPoint object is initialized with all the
2900   // data that must be copied to the helper threads (the current position and
2901   // search stack, alpha, beta, the search depth, etc.), and we tell our
2902   // helper threads that they have been assigned work. This will cause them
2903   // to instantly leave their idle loops and call sp_search_pv(). When all
2904   // threads have returned from sp_search_pv (or, equivalently, when
2905   // splitPoint->cpus becomes 0), split() returns true.
2906
2907   bool split(const Position& p, SearchStack* sstck, int ply,
2908              Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2909              Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2910
2911     assert(p.is_ok());
2912     assert(sstck != NULL);
2913     assert(ply >= 0 && ply < PLY_MAX);
2914     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2915     assert(!pvNode || *alpha < *beta);
2916     assert(*beta <= VALUE_INFINITE);
2917     assert(depth > Depth(0));
2918     assert(master >= 0 && master < ActiveThreads);
2919     assert(ActiveThreads > 1);
2920
2921     SplitPoint* splitPoint;
2922     int i;
2923
2924     lock_grab(&MPLock);
2925
2926     // If no other thread is available to help us, or if we have too many
2927     // active split points, don't split.
2928     if (   !idle_thread_exists(master)
2929         || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2930     {
2931         lock_release(&MPLock);
2932         return false;
2933     }
2934
2935     // Pick the next available split point object from the split point stack
2936     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2937     Threads[master].activeSplitPoints++;
2938
2939     // Initialize the split point object and copy current position
2940     splitPoint->parent = Threads[master].splitPoint;
2941     splitPoint->finished = false;
2942     splitPoint->ply = ply;
2943     splitPoint->depth = depth;
2944     splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2945     splitPoint->beta = *beta;
2946     splitPoint->pvNode = pvNode;
2947     splitPoint->bestValue = *bestValue;
2948     splitPoint->futilityValue = futilityValue;
2949     splitPoint->master = master;
2950     splitPoint->mp = mp;
2951     splitPoint->moves = *moves;
2952     splitPoint->cpus = 1;
2953     splitPoint->pos.copy(p);
2954     splitPoint->parentSstack = sstck;
2955     for (i = 0; i < ActiveThreads; i++)
2956         splitPoint->slaves[i] = 0;
2957
2958     // Copy the current search stack to the master thread
2959     memcpy(splitPoint->sstack[master], sstck, (ply+1) * sizeof(SearchStack));
2960     Threads[master].splitPoint = splitPoint;
2961
2962     // Make copies of the current position and search stack for each thread
2963     for (i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2964         if (thread_is_available(i, master))
2965         {
2966             memcpy(splitPoint->sstack[i], sstck, (ply+1) * sizeof(SearchStack));
2967             Threads[i].splitPoint = splitPoint;
2968             splitPoint->slaves[i] = 1;
2969             splitPoint->cpus++;
2970         }
2971
2972     // Tell the threads that they have work to do. This will make them leave
2973     // their idle loop.
2974     for (i = 0; i < ActiveThreads; i++)
2975         if (i == master || splitPoint->slaves[i])
2976         {
2977             Threads[i].workIsWaiting = true;
2978             Threads[i].idle = false;
2979             Threads[i].stop = false;
2980         }
2981
2982     lock_release(&MPLock);
2983
2984     // Everything is set up. The master thread enters the idle loop, from
2985     // which it will instantly launch a search, because its workIsWaiting
2986     // slot is 'true'.  We send the split point as a second parameter to the
2987     // idle loop, which means that the main thread will return from the idle
2988     // loop when all threads have finished their work at this split point
2989     // (i.e. when splitPoint->cpus == 0).
2990     idle_loop(master, splitPoint);
2991
2992     // We have returned from the idle loop, which means that all threads are
2993     // finished. Update alpha, beta and bestValue, and return.
2994     lock_grab(&MPLock);
2995
2996     if (pvNode)
2997         *alpha = splitPoint->alpha;
2998
2999     *beta = splitPoint->beta;
3000     *bestValue = splitPoint->bestValue;
3001     Threads[master].stop = false;
3002     Threads[master].idle = false;
3003     Threads[master].activeSplitPoints--;
3004     Threads[master].splitPoint = splitPoint->parent;
3005
3006     lock_release(&MPLock);
3007     return true;
3008   }
3009
3010
3011   // wake_sleeping_threads() wakes up all sleeping threads when it is time
3012   // to start a new search from the root.
3013
3014   void wake_sleeping_threads() {
3015
3016     if (ActiveThreads > 1)
3017     {
3018         for (int i = 1; i < ActiveThreads; i++)
3019         {
3020             Threads[i].idle = true;
3021             Threads[i].workIsWaiting = false;
3022         }
3023
3024 #if !defined(_MSC_VER)
3025       pthread_mutex_lock(&WaitLock);
3026       pthread_cond_broadcast(&WaitCond);
3027       pthread_mutex_unlock(&WaitLock);
3028 #else
3029       for (int i = 1; i < THREAD_MAX; i++)
3030           SetEvent(SitIdleEvent[i]);
3031 #endif
3032     }
3033   }
3034
3035
3036   // init_thread() is the function which is called when a new thread is
3037   // launched. It simply calls the idle_loop() function with the supplied
3038   // threadID. There are two versions of this function; one for POSIX
3039   // threads and one for Windows threads.
3040
3041 #if !defined(_MSC_VER)
3042
3043   void* init_thread(void *threadID) {
3044
3045     idle_loop(*(int*)threadID, NULL);
3046     return NULL;
3047   }
3048
3049 #else
3050
3051   DWORD WINAPI init_thread(LPVOID threadID) {
3052
3053     idle_loop(*(int*)threadID, NULL);
3054     return NULL;
3055   }
3056
3057 #endif
3058
3059 }