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