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