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