]> git.sesse.net Git - stockfish/blob - src/search.cpp
Retire update_history() Inline the only caller site
[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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iomanip>
25 #include <iostream>
26 #include <sstream>
27 #include <vector>
28
29 #include "book.h"
30 #include "evaluate.h"
31 #include "history.h"
32 #include "misc.h"
33 #include "movegen.h"
34 #include "movepick.h"
35 #include "search.h"
36 #include "timeman.h"
37 #include "thread.h"
38 #include "tt.h"
39 #include "ucioption.h"
40
41 namespace Search {
42
43   volatile SignalsType Signals;
44   LimitsType Limits;
45   std::vector<Move> SearchMoves;
46   Position RootPosition;
47 }
48
49 using std::cout;
50 using std::endl;
51 using std::string;
52 using namespace Search;
53
54 namespace {
55
56   // Set to true to force running with one thread. Used for debugging
57   const bool FakeSplit = false;
58
59   // Different node types, used as template parameter
60   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
61
62   // RootMove struct is used for moves at the root of the tree. For each root
63   // move we store a score, a node count, and a PV (really a refutation in the
64   // case of moves which fail low). Score is normally set at -VALUE_INFINITE for
65   // all non-pv moves.
66   struct RootMove {
67
68     RootMove(){}
69     RootMove(Move m) {
70       nodes = 0;
71       score = prevScore = -VALUE_INFINITE;
72       pv.push_back(m);
73       pv.push_back(MOVE_NONE);
74     }
75
76     bool operator<(const RootMove& m) const { return score < m.score; }
77     bool operator==(const Move& m) const { return pv[0] == m; }
78
79     void extract_pv_from_tt(Position& pos);
80     void insert_pv_in_tt(Position& pos);
81
82     int64_t nodes;
83     Value score;
84     Value prevScore;
85     std::vector<Move> pv;
86   };
87
88
89   /// Constants
90
91   // Lookup table to check if a Piece is a slider and its access function
92   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
93   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
94
95   // Maximum depth for razoring
96   const Depth RazorDepth = 4 * ONE_PLY;
97
98   // Dynamic razoring margin based on depth
99   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
100
101   // Maximum depth for use of dynamic threat detection when null move fails low
102   const Depth ThreatDepth = 5 * ONE_PLY;
103
104   // Minimum depth for use of internal iterative deepening
105   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
106
107   // At Non-PV nodes we do an internal iterative deepening search
108   // when the static evaluation is bigger then beta - IIDMargin.
109   const Value IIDMargin = Value(0x100);
110
111   // Minimum depth for use of singular extension
112   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
113
114   // Futility margin for quiescence search
115   const Value FutilityMarginQS = Value(0x80);
116
117   // Futility lookup tables (initialized at startup) and their access functions
118   Value FutilityMargins[16][64]; // [depth][moveNumber]
119   int FutilityMoveCounts[32];    // [depth]
120
121   inline Value futility_margin(Depth d, int mn) {
122
123     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
124                            : 2 * VALUE_INFINITE;
125   }
126
127   inline int futility_move_count(Depth d) {
128
129     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
130   }
131
132   // Reduction lookup tables (initialized at startup) and their access function
133   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
134
135   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
136
137     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
138   }
139
140   // Easy move margin. An easy move candidate must be at least this much
141   // better than the second best move.
142   const Value EasyMoveMargin = Value(0x150);
143
144
145   /// Namespace variables
146
147   std::vector<RootMove> RootMoves;
148   size_t MultiPV, UCIMultiPV, PVIdx;
149   TimeManager TimeMgr;
150   int BestMoveChanges;
151   int SkillLevel;
152   bool SkillLevelEnabled;
153   History H;
154
155
156   /// Local functions
157
158   template <NodeType NT>
159   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
160
161   template <NodeType NT>
162   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
163
164   void id_loop(Position& pos);
165   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
166   bool connected_moves(const Position& pos, Move m1, Move m2);
167   Value value_to_tt(Value v, int ply);
168   Value value_from_tt(Value v, int ply);
169   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
170   bool connected_threat(const Position& pos, Move m, Move threat);
171   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
172   Move do_skill_level();
173   int elapsed_time(bool reset = false);
174   string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
175   void pv_info_to_log(Position& pos, int depth, Value score, int time, Move pv[]);
176   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta);
177
178   // MovePickerExt class template extends MovePicker and allows to choose at
179   // compile time the proper moves source according to the type of node. In the
180   // default case we simply create and use a standard MovePicker object.
181   template<bool SpNode> struct MovePickerExt : public MovePicker {
182
183     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
184                   : MovePicker(p, ttm, d, h, ss, b) {}
185   };
186
187   // In case of a SpNode we use split point's shared MovePicker object as moves source
188   template<> struct MovePickerExt<true> : public MovePicker {
189
190     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
191                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
192
193     Move get_next_move() { return mp->get_next_move(); }
194     MovePicker* mp;
195   };
196
197   // Overload operator<<() to make it easier to print moves in a coordinate
198   // notation compatible with UCI protocol.
199   std::ostream& operator<<(std::ostream& os, Move m) {
200
201     bool chess960 = (os.iword(0) != 0); // See set960()
202     return os << move_to_uci(m, chess960);
203   }
204
205   // When formatting a move for std::cout we must know if we are in Chess960 or
206   // not. To keep using the handy operator<<() on the move the trick is to embed
207   // this flag in the stream itself. Function-like named enum set960 is used as
208   // a custom manipulator and the stream internal general-purpose array, accessed
209   // through ios_base::iword(), is used to pass the flag to the move's operator<<
210   // that will read it to properly format castling moves.
211   enum set960 {};
212
213   std::ostream& operator<<(std::ostream& os, const set960& f) {
214
215     os.iword(0) = f;
216     return os;
217   }
218
219   // is_dangerous() checks whether a move belongs to some classes of known
220   // 'dangerous' moves so that we avoid to prune it.
221   FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
222
223     // Test for a pawn pushed to 7th or a passed pawn move
224     if (type_of(pos.piece_on(move_from(m))) == PAWN)
225     {
226         Color c = pos.side_to_move();
227         if (   relative_rank(c, move_to(m)) == RANK_7
228             || pos.pawn_is_passed(c, move_to(m)))
229             return true;
230     }
231
232     // Test for a capture that triggers a pawn endgame
233     if (   captureOrPromotion
234         && type_of(pos.piece_on(move_to(m))) != PAWN
235         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
236             - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
237         && !is_special(m))
238         return true;
239
240     return false;
241   }
242
243 } // namespace
244
245
246 /// Search::init() is called during startup to initialize various lookup tables
247
248 void Search::init() {
249
250   int d;  // depth (ONE_PLY == 2)
251   int hd; // half depth (ONE_PLY == 1)
252   int mc; // moveCount
253
254   // Init reductions array
255   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
256   {
257       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
258       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
259       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
260       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
261   }
262
263   // Init futility margins array
264   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
265       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
266
267   // Init futility move count array
268   for (d = 0; d < 32; d++)
269       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
270 }
271
272
273 /// Search::perft() is our utility to verify move generation. All the leaf nodes
274 /// up to the given depth are generated and counted and the sum returned.
275
276 int64_t Search::perft(Position& pos, Depth depth) {
277
278   StateInfo st;
279   int64_t sum = 0;
280
281   MoveList<MV_LEGAL> ml(pos);
282
283   // At the last ply just return the number of moves (leaf nodes)
284   if (depth <= ONE_PLY)
285       return ml.size();
286
287   CheckInfo ci(pos);
288   for ( ; !ml.end(); ++ml)
289   {
290       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
291       sum += perft(pos, depth - ONE_PLY);
292       pos.undo_move(ml.move());
293   }
294   return sum;
295 }
296
297
298 /// Search::think() is the external interface to Stockfish's search, and is
299 /// called by the main thread when the program receives the UCI 'go' command. It
300 /// searches from RootPosition and at the end prints the "bestmove" to output.
301
302 void Search::think() {
303
304   static Book book; // Defined static to initialize the PRNG only once
305
306   Position& pos = RootPosition;
307   elapsed_time(true);
308   TimeMgr.init(Limits, pos.startpos_ply_counter());
309   TT.new_search();
310   H.clear();
311   RootMoves.clear();
312
313   // Populate RootMoves with all the legal moves (default) or, if a SearchMoves
314   // is given, with the subset of legal moves to search.
315   for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
316       if (   SearchMoves.empty()
317           || std::count(SearchMoves.begin(), SearchMoves.end(), ml.move()))
318           RootMoves.push_back(RootMove(ml.move()));
319
320   // Set output stream mode: normal or chess960. Castling notation is different
321   cout << set960(pos.is_chess960());
322
323   if (Options["OwnBook"].value<bool>())
324   {
325       if (Options["Book File"].value<string>() != book.name())
326           book.open(Options["Book File"].value<string>());
327
328       Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
329
330       if (   bookMove != MOVE_NONE
331           && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
332       {
333           std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
334           goto finish;
335       }
336   }
337
338   // Read UCI options: GUI could change UCI parameters during the game
339   read_evaluation_uci_options(pos.side_to_move());
340   Threads.read_uci_options();
341
342   TT.set_size(Options["Hash"].value<int>());
343   if (Options["Clear Hash"].value<bool>())
344   {
345       Options["Clear Hash"].set_value("false");
346       TT.clear();
347   }
348
349   UCIMultiPV = Options["MultiPV"].value<size_t>();
350   SkillLevel = Options["Skill Level"].value<int>();
351
352   // Do we have to play with skill handicap? In this case enable MultiPV that
353   // we will use behind the scenes to retrieve a set of possible moves.
354   SkillLevelEnabled = (SkillLevel < 20);
355   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
356
357   if (Options["Use Search Log"].value<bool>())
358   {
359       Log log(Options["Search Log Filename"].value<string>());
360       log << "\nSearching: "  << pos.to_fen()
361           << "\ninfinite: "   << Limits.infinite
362           << " ponder: "      << Limits.ponder
363           << " time: "        << Limits.time
364           << " increment: "   << Limits.increment
365           << " moves to go: " << Limits.movesToGo
366           << endl;
367   }
368
369   for (int i = 0; i < Threads.size(); i++)
370   {
371       Threads[i].maxPly = 0;
372       Threads[i].wake_up();
373   }
374
375   // Set best timer interval to avoid lagging under time pressure. Timer is
376   // used to check for remaining available thinking time.
377   if (TimeMgr.available_time())
378       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
379   else
380       Threads.set_timer(100);
381
382   // We're ready to start searching. Call the iterative deepening loop function
383   id_loop(pos);
384
385   // Stop timer and send all the slaves to sleep, if not already sleeping
386   Threads.set_timer(0);
387   Threads.set_size(1);
388
389   if (Options["Use Search Log"].value<bool>())
390   {
391       int e = elapsed_time();
392
393       Log log(Options["Search Log Filename"].value<string>());
394       log << "Nodes: "          << pos.nodes_searched()
395           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
396           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
397
398       StateInfo st;
399       pos.do_move(RootMoves[0].pv[0], st);
400       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
401       pos.undo_move(RootMoves[0].pv[0]);
402   }
403
404 finish:
405
406   // When we reach max depth we arrive here even without a StopRequest, but if
407   // we are pondering or in infinite search, we shouldn't print the best move
408   // before we are told to do so.
409   if (!Signals.stop && (Limits.ponder || Limits.infinite))
410       Threads.wait_for_stop_or_ponderhit();
411
412   // Could be MOVE_NONE when searching on a stalemate position
413   cout << "bestmove " << RootMoves[0].pv[0];
414
415   // UCI protol is not clear on allowing sending an empty ponder move, instead
416   // it is clear that ponder move is optional. So skip it if empty.
417   if (RootMoves[0].pv[1] != MOVE_NONE)
418       cout << " ponder " << RootMoves[0].pv[1];
419
420   cout << endl;
421 }
422
423
424 namespace {
425
426   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
427   // with increasing depth until the allocated thinking time has been consumed,
428   // user stops the search, or the maximum search depth is reached.
429
430   void id_loop(Position& pos) {
431
432     Stack ss[PLY_MAX_PLUS_2];
433     int depth, prevBestMoveChanges;
434     Value bestValue, alpha, beta, delta;
435     bool bestMoveNeverChanged = true;
436     Move skillBest = MOVE_NONE;
437
438     memset(ss, 0, 4 * sizeof(Stack));
439     depth = BestMoveChanges = 0;
440     bestValue = delta = -VALUE_INFINITE;
441     ss->currentMove = MOVE_NULL; // Hack to skip update gains
442
443     // Handle the special case of a mate/stalemate position
444     if (RootMoves.empty())
445     {
446         cout << "info depth 0"
447              << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
448
449         RootMoves.push_back(MOVE_NONE);
450         return;
451     }
452
453     // Iterative deepening loop until requested to stop or target depth reached
454     while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
455     {
456         // Save last iteration's scores before first PV line is searched and all
457         // the move scores but the (new) PV are set to -VALUE_INFINITE.
458         for (size_t i = 0; i < RootMoves.size(); i++)
459             RootMoves[i].prevScore = RootMoves[i].score;
460
461         prevBestMoveChanges = BestMoveChanges;
462         BestMoveChanges = 0;
463
464         // MultiPV loop. We perform a full root search for each PV line
465         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
466         {
467             // Set aspiration window default width
468             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
469             {
470                 delta = Value(16);
471                 alpha = RootMoves[PVIdx].prevScore - delta;
472                 beta  = RootMoves[PVIdx].prevScore + delta;
473             }
474             else
475             {
476                 alpha = -VALUE_INFINITE;
477                 beta  =  VALUE_INFINITE;
478             }
479
480             // Start with a small aspiration window and, in case of fail high/low,
481             // research with bigger window until not failing high/low anymore.
482             do {
483                 // Search starts from ss+1 to allow referencing (ss-1). This is
484                 // needed by update gains and ss copy when splitting at Root.
485                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
486
487                 // Bring to front the best move. It is critical that sorting is
488                 // done with a stable algorithm because all the values but the first
489                 // and eventually the new best one are set to -VALUE_INFINITE and
490                 // we want to keep the same order for all the moves but the new
491                 // PV that goes to the front. Note that in case of MultiPV search
492                 // the already searched PV lines are preserved.
493                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
494
495                 // In case we have found an exact score and we are going to leave
496                 // the fail high/low loop then reorder the PV moves, otherwise
497                 // leave the last PV move in its position so to be searched again.
498                 // Of course this is needed only in MultiPV search.
499                 if (PVIdx && bestValue > alpha && bestValue < beta)
500                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
501
502                 // Write PV back to transposition table in case the relevant
503                 // entries have been overwritten during the search.
504                 for (size_t i = 0; i <= PVIdx; i++)
505                     RootMoves[i].insert_pv_in_tt(pos);
506
507                 // If search has been stopped exit the aspiration window loop.
508                 // Sorting and writing PV back to TT is safe becuase RootMoves
509                 // is still valid, although refers to  previous iteration.
510                 if (Signals.stop)
511                     break;
512
513                 // Send full PV info to GUI if we are going to leave the loop or
514                 // if we have a fail high/low and we are deep in the search.
515                 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
516                     pv_info_to_uci(pos, depth, alpha, beta);
517
518                 // In case of failing high/low increase aspiration window and
519                 // research, otherwise exit the fail high/low loop.
520                 if (bestValue >= beta)
521                 {
522                     beta += delta;
523                     delta += delta / 2;
524                 }
525                 else if (bestValue <= alpha)
526                 {
527                     Signals.failedLowAtRoot = true;
528                     Signals.stopOnPonderhit = false;
529
530                     alpha -= delta;
531                     delta += delta / 2;
532                 }
533                 else
534                     break;
535
536                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
537
538             } while (abs(bestValue) < VALUE_KNOWN_WIN);
539         }
540
541         // Skills: Do we need to pick now the best move ?
542         if (SkillLevelEnabled && depth == 1 + SkillLevel)
543             skillBest = do_skill_level();
544
545         if (Options["Use Search Log"].value<bool>())
546              pv_info_to_log(pos, depth, bestValue, elapsed_time(), &RootMoves[0].pv[0]);
547
548         // Filter out startup noise when monitoring best move stability
549         if (depth > 2 && BestMoveChanges)
550             bestMoveNeverChanged = false;
551
552         // Do we have time for the next iteration? Can we stop searching now?
553         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
554         {
555             bool stop = false; // Local variable, not the volatile Signals.stop
556
557             // Take in account some extra time if the best move has changed
558             if (depth > 4 && depth < 50)
559                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
560
561             // Stop search if most of available time is already consumed. We
562             // probably don't have enough time to search the first move at the
563             // next iteration anyway.
564             if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
565                 stop = true;
566
567             // Stop search early if one move seems to be much better than others
568             if (   depth >= 10
569                 && !stop
570                 && (   bestMoveNeverChanged
571                     || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
572             {
573                 Value rBeta = bestValue - EasyMoveMargin;
574                 (ss+1)->excludedMove = RootMoves[0].pv[0];
575                 (ss+1)->skipNullMove = true;
576                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
577                 (ss+1)->skipNullMove = false;
578                 (ss+1)->excludedMove = MOVE_NONE;
579
580                 if (v < rBeta)
581                     stop = true;
582             }
583
584             if (stop)
585             {
586                 // If we are allowed to ponder do not stop the search now but
587                 // keep pondering until GUI sends "ponderhit" or "stop".
588                 if (Limits.ponder)
589                     Signals.stopOnPonderhit = true;
590                 else
591                     Signals.stop = true;
592             }
593         }
594     }
595
596     // When using skills swap best PV line with the sub-optimal one
597     if (SkillLevelEnabled)
598     {
599         if (skillBest == MOVE_NONE) // Still unassigned ?
600             skillBest = do_skill_level();
601
602         std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
603     }
604   }
605
606
607   // search<>() is the main search function for both PV and non-PV nodes and for
608   // normal and SplitPoint nodes. When called just after a split point the search
609   // is simpler because we have already probed the hash table, done a null move
610   // search, and searched the first move before splitting, we don't have to repeat
611   // all this work again. We also don't need to store anything to the hash table
612   // here: This is taken care of after we return from the split point.
613
614   template <NodeType NT>
615   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
616
617     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
618     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
619     const bool RootNode = (NT == Root || NT == SplitPointRoot);
620
621     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
622     assert(beta > alpha && beta <= VALUE_INFINITE);
623     assert(PvNode || alpha == beta - 1);
624     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
625
626     Move movesSearched[MAX_MOVES];
627     int64_t nodes;
628     StateInfo st;
629     const TTEntry *tte;
630     Key posKey;
631     Move ttMove, move, excludedMove, threatMove;
632     Depth ext, newDepth;
633     ValueType vt;
634     Value bestValue, value, oldAlpha;
635     Value refinedValue, nullValue, futilityBase, futilityValue;
636     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
637     bool captureOrPromotion, dangerous, doFullDepthSearch;
638     int moveCount = 0, playedMoveCount = 0;
639     Thread& thread = Threads[pos.thread()];
640     SplitPoint* sp = NULL;
641
642     refinedValue = bestValue = value = -VALUE_INFINITE;
643     oldAlpha = alpha;
644     inCheck = pos.in_check();
645     ss->ply = (ss-1)->ply + 1;
646
647     // Used to send selDepth info to GUI
648     if (PvNode && thread.maxPly < ss->ply)
649         thread.maxPly = ss->ply;
650
651     // Step 1. Initialize node
652     if (!SpNode)
653     {
654         ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
655         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
656         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
657     }
658     else
659     {
660         sp = ss->sp;
661         tte = NULL;
662         ttMove = excludedMove = MOVE_NONE;
663         threatMove = sp->threatMove;
664         goto split_point_start;
665     }
666
667     // Step 2. Check for aborted search and immediate draw
668     if ((   Signals.stop
669          || pos.is_draw<false>()
670          || ss->ply > PLY_MAX) && !RootNode)
671         return VALUE_DRAW;
672
673     // Step 3. Mate distance pruning
674     if (!RootNode)
675     {
676         alpha = std::max(value_mated_in(ss->ply), alpha);
677         beta = std::min(value_mate_in(ss->ply+1), beta);
678         if (alpha >= beta)
679             return alpha;
680     }
681
682     // Step 4. Transposition table lookup
683     // We don't want the score of a partial search to overwrite a previous full search
684     // TT value, so we use a different position key in case of an excluded move.
685     excludedMove = ss->excludedMove;
686     posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
687     tte = TT.probe(posKey);
688     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
689
690     // At PV nodes we check for exact scores, while at non-PV nodes we check for
691     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
692     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
693     // we should also update RootMoveList to avoid bogus output.
694     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
695                                     : can_return_tt(tte, depth, beta, ss->ply)))
696     {
697         TT.refresh(tte);
698         ss->bestMove = move = ttMove; // Can be MOVE_NONE
699         value = value_from_tt(tte->value(), ss->ply);
700
701         if (   value >= beta
702             && move
703             && !pos.is_capture_or_promotion(move)
704             && move != ss->killers[0])
705         {
706             ss->killers[1] = ss->killers[0];
707             ss->killers[0] = move;
708         }
709         return value;
710     }
711
712     // Step 5. Evaluate the position statically and update parent's gain statistics
713     if (inCheck)
714         ss->eval = ss->evalMargin = VALUE_NONE;
715     else if (tte)
716     {
717         assert(tte->static_value() != VALUE_NONE);
718
719         ss->eval = tte->static_value();
720         ss->evalMargin = tte->static_value_margin();
721         refinedValue = refine_eval(tte, ss->eval, ss->ply);
722     }
723     else
724     {
725         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
726         TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
727     }
728
729     // Update gain for the parent non-capture move given the static position
730     // evaluation before and after the move.
731     if (   (move = (ss-1)->currentMove) != MOVE_NULL
732         && (ss-1)->eval != VALUE_NONE
733         && ss->eval != VALUE_NONE
734         && pos.captured_piece_type() == PIECE_TYPE_NONE
735         && !is_special(move))
736     {
737         Square to = move_to(move);
738         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
739     }
740
741     // Step 6. Razoring (is omitted in PV nodes)
742     if (   !PvNode
743         &&  depth < RazorDepth
744         && !inCheck
745         &&  refinedValue + razor_margin(depth) < beta
746         &&  ttMove == MOVE_NONE
747         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
748         && !pos.has_pawn_on_7th(pos.side_to_move()))
749     {
750         Value rbeta = beta - razor_margin(depth);
751         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
752         if (v < rbeta)
753             // Logically we should return (v + razor_margin(depth)), but
754             // surprisingly this did slightly weaker in tests.
755             return v;
756     }
757
758     // Step 7. Static null move pruning (is omitted in PV nodes)
759     // We're betting that the opponent doesn't have a move that will reduce
760     // the score by more than futility_margin(depth) if we do a null move.
761     if (   !PvNode
762         && !ss->skipNullMove
763         &&  depth < RazorDepth
764         && !inCheck
765         &&  refinedValue - futility_margin(depth, 0) >= beta
766         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
767         &&  pos.non_pawn_material(pos.side_to_move()))
768         return refinedValue - futility_margin(depth, 0);
769
770     // Step 8. Null move search with verification search (is omitted in PV nodes)
771     if (   !PvNode
772         && !ss->skipNullMove
773         &&  depth > ONE_PLY
774         && !inCheck
775         &&  refinedValue >= beta
776         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
777         &&  pos.non_pawn_material(pos.side_to_move()))
778     {
779         ss->currentMove = MOVE_NULL;
780
781         // Null move dynamic reduction based on depth
782         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
783
784         // Null move dynamic reduction based on value
785         if (refinedValue - PawnValueMidgame > beta)
786             R++;
787
788         pos.do_null_move<true>(st);
789         (ss+1)->skipNullMove = true;
790         nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
791                                               : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
792         (ss+1)->skipNullMove = false;
793         pos.do_null_move<false>(st);
794
795         if (nullValue >= beta)
796         {
797             // Do not return unproven mate scores
798             if (nullValue >= VALUE_MATE_IN_PLY_MAX)
799                 nullValue = beta;
800
801             if (depth < 6 * ONE_PLY)
802                 return nullValue;
803
804             // Do verification search at high depths
805             ss->skipNullMove = true;
806             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
807             ss->skipNullMove = false;
808
809             if (v >= beta)
810                 return nullValue;
811         }
812         else
813         {
814             // The null move failed low, which means that we may be faced with
815             // some kind of threat. If the previous move was reduced, check if
816             // the move that refuted the null move was somehow connected to the
817             // move which was reduced. If a connection is found, return a fail
818             // low score (which will cause the reduced move to fail high in the
819             // parent node, which will trigger a re-search with full depth).
820             threatMove = (ss+1)->bestMove;
821
822             if (   depth < ThreatDepth
823                 && (ss-1)->reduction
824                 && threatMove != MOVE_NONE
825                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
826                 return beta - 1;
827         }
828     }
829
830     // Step 9. ProbCut (is omitted in PV nodes)
831     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
832     // and a reduced search returns a value much above beta, we can (almost) safely
833     // prune the previous move.
834     if (   !PvNode
835         &&  depth >= RazorDepth + ONE_PLY
836         && !inCheck
837         && !ss->skipNullMove
838         &&  excludedMove == MOVE_NONE
839         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX)
840     {
841         Value rbeta = beta + 200;
842         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
843
844         assert(rdepth >= ONE_PLY);
845
846         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
847         CheckInfo ci(pos);
848
849         while ((move = mp.get_next_move()) != MOVE_NONE)
850             if (pos.pl_move_is_legal(move, ci.pinned))
851             {
852                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
853                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
854                 pos.undo_move(move);
855                 if (value >= rbeta)
856                     return value;
857             }
858     }
859
860     // Step 10. Internal iterative deepening
861     if (   depth >= IIDDepth[PvNode]
862         && ttMove == MOVE_NONE
863         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
864     {
865         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
866
867         ss->skipNullMove = true;
868         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
869         ss->skipNullMove = false;
870
871         tte = TT.probe(posKey);
872         ttMove = tte ? tte->move() : MOVE_NONE;
873     }
874
875 split_point_start: // At split points actual search starts from here
876
877     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
878     CheckInfo ci(pos);
879     ss->bestMove = MOVE_NONE;
880     futilityBase = ss->eval + ss->evalMargin;
881     singularExtensionNode =   !RootNode
882                            && !SpNode
883                            && depth >= SingularExtensionDepth[PvNode]
884                            && ttMove != MOVE_NONE
885                            && !excludedMove // Recursive singular search is not allowed
886                            && (tte->type() & VALUE_TYPE_LOWER)
887                            && tte->depth() >= depth - 3 * ONE_PLY;
888     if (SpNode)
889     {
890         lock_grab(&(sp->lock));
891         bestValue = sp->bestValue;
892         moveCount = sp->moveCount;
893
894         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
895     }
896
897     // Step 11. Loop through moves
898     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
899     while (   bestValue < beta
900            && (move = mp.get_next_move()) != MOVE_NONE
901            && !thread.cutoff_occurred())
902     {
903       assert(is_ok(move));
904
905       if (move == excludedMove)
906           continue;
907
908       // At root obey the "searchmoves" option and skip moves not listed in Root
909       // Move List, as a consequence any illegal move is also skipped. In MultiPV
910       // mode we also skip PV moves which have been already searched.
911       if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
912           continue;
913
914       // At PV and SpNode nodes we want all moves to be legal since the beginning
915       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
916           continue;
917
918       if (SpNode)
919       {
920           moveCount = ++sp->moveCount;
921           lock_release(&(sp->lock));
922       }
923       else
924           moveCount++;
925
926       if (RootNode)
927       {
928           // This is used by time management
929           Signals.firstRootMove = (moveCount == 1);
930
931           nodes = pos.nodes_searched();
932
933           if (pos.thread() == 0 && elapsed_time() > 2000)
934               cout << "info depth " << depth / ONE_PLY
935                    << " currmove " << move
936                    << " currmovenumber " << moveCount + PVIdx << endl;
937       }
938
939       isPvMove = (PvNode && moveCount <= 1);
940       captureOrPromotion = pos.is_capture_or_promotion(move);
941       givesCheck = pos.move_gives_check(move, ci);
942       dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
943       ext = DEPTH_ZERO;
944
945       // Step 12. Extend checks and, in PV nodes, also dangerous moves
946       if (PvNode && dangerous)
947           ext = ONE_PLY;
948
949       else if (givesCheck && pos.see_sign(move) >= 0)
950           ext = PvNode ? ONE_PLY : ONE_PLY / 2;
951
952       // Singular extension search. If all moves but one fail low on a search of
953       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
954       // is singular and should be extended. To verify this we do a reduced search
955       // on all the other moves but the ttMove, if result is lower than ttValue minus
956       // a margin then we extend ttMove.
957       if (   singularExtensionNode
958           && !ext
959           && move == ttMove
960           && pos.pl_move_is_legal(move, ci.pinned))
961       {
962           Value ttValue = value_from_tt(tte->value(), ss->ply);
963
964           if (abs(ttValue) < VALUE_KNOWN_WIN)
965           {
966               Value rBeta = ttValue - int(depth);
967               ss->excludedMove = move;
968               ss->skipNullMove = true;
969               value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
970               ss->skipNullMove = false;
971               ss->excludedMove = MOVE_NONE;
972               ss->bestMove = MOVE_NONE;
973               if (value < rBeta)
974                   ext = ONE_PLY;
975           }
976       }
977
978       // Update current move (this must be done after singular extension search)
979       newDepth = depth - ONE_PLY + ext;
980
981       // Step 13. Futility pruning (is omitted in PV nodes)
982       if (   !PvNode
983           && !captureOrPromotion
984           && !inCheck
985           && !dangerous
986           &&  move != ttMove
987           && !is_castle(move)
988           && (bestValue > VALUE_MATED_IN_PLY_MAX || bestValue == -VALUE_INFINITE))
989       {
990           // Move count based pruning
991           if (   moveCount >= futility_move_count(depth)
992               && (!threatMove || !connected_threat(pos, move, threatMove)))
993           {
994               if (SpNode)
995                   lock_grab(&(sp->lock));
996
997               continue;
998           }
999
1000           // Value based pruning
1001           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1002           // but fixing this made program slightly weaker.
1003           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1004           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
1005                          + H.gain(pos.piece_on(move_from(move)), move_to(move));
1006
1007           if (futilityValue < beta)
1008           {
1009               if (SpNode)
1010                   lock_grab(&(sp->lock));
1011
1012               continue;
1013           }
1014
1015           // Prune moves with negative SEE at low depths
1016           if (   predictedDepth < 2 * ONE_PLY
1017               && pos.see_sign(move) < 0)
1018           {
1019               if (SpNode)
1020                   lock_grab(&(sp->lock));
1021
1022               continue;
1023           }
1024       }
1025
1026       // Check for legality only before to do the move
1027       if (!pos.pl_move_is_legal(move, ci.pinned))
1028       {
1029           moveCount--;
1030           continue;
1031       }
1032
1033       ss->currentMove = move;
1034       if (!SpNode && !captureOrPromotion)
1035           movesSearched[playedMoveCount++] = move;
1036
1037       // Step 14. Make the move
1038       pos.do_move(move, st, ci, givesCheck);
1039
1040       // Step 15. Reduced depth search (LMR). If the move fails high will be
1041       // re-searched at full depth.
1042       if (   depth > 3 * ONE_PLY
1043           && !isPvMove
1044           && !captureOrPromotion
1045           && !dangerous
1046           && !is_castle(move)
1047           &&  ss->killers[0] != move
1048           &&  ss->killers[1] != move)
1049       {
1050           ss->reduction = reduction<PvNode>(depth, moveCount);
1051           Depth d = newDepth - ss->reduction;
1052           alpha = SpNode ? sp->alpha : alpha;
1053
1054           value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1055                               : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1056
1057           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1058           ss->reduction = DEPTH_ZERO;
1059       }
1060       else
1061           doFullDepthSearch = !isPvMove;
1062
1063       // Step 16. Full depth search, when LMR is skipped or fails high
1064       if (doFullDepthSearch)
1065       {
1066           alpha = SpNode ? sp->alpha : alpha;
1067           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1068                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1069       }
1070
1071       // Only for PV nodes do a full PV search on the first move or after a fail
1072       // high, in the latter case search only if value < beta, otherwise let the
1073       // parent node to fail low with value <= alpha and to try another move.
1074       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1075           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1076                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1077
1078       // Step 17. Undo move
1079       pos.undo_move(move);
1080
1081       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1082
1083       // Step 18. Check for new best move
1084       if (SpNode)
1085       {
1086           lock_grab(&(sp->lock));
1087           bestValue = sp->bestValue;
1088           alpha = sp->alpha;
1089       }
1090
1091       // Finished searching the move. If StopRequest is true, the search
1092       // was aborted because the user interrupted the search or because we
1093       // ran out of time. In this case, the return value of the search cannot
1094       // be trusted, and we don't update the best move and/or PV.
1095       if (RootNode && !Signals.stop)
1096       {
1097           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
1098           rm.nodes += pos.nodes_searched() - nodes;
1099
1100           // PV move or new best move ?
1101           if (isPvMove || value > alpha)
1102           {
1103               rm.score = value;
1104               rm.extract_pv_from_tt(pos);
1105
1106               // We record how often the best move has been changed in each
1107               // iteration. This information is used for time management: When
1108               // the best move changes frequently, we allocate some more time.
1109               if (!isPvMove && MultiPV == 1)
1110                   BestMoveChanges++;
1111           }
1112           else
1113               // All other moves but the PV are set to the lowest value, this
1114               // is not a problem when sorting becuase sort is stable and move
1115               // position in the list is preserved, just the PV is pushed up.
1116               rm.score = -VALUE_INFINITE;
1117
1118       }
1119
1120       if (value > bestValue)
1121       {
1122           bestValue = value;
1123           ss->bestMove = move;
1124
1125           if (   PvNode
1126               && value > alpha
1127               && value < beta) // We want always alpha < beta
1128               alpha = value;
1129
1130           if (SpNode && !thread.cutoff_occurred())
1131           {
1132               sp->bestValue = value;
1133               sp->ss->bestMove = move;
1134               sp->alpha = alpha;
1135               sp->is_betaCutoff = (value >= beta);
1136           }
1137       }
1138
1139       // Step 19. Check for split
1140       if (   !SpNode
1141           && depth >= Threads.min_split_depth()
1142           && bestValue < beta
1143           && Threads.available_slave_exists(pos.thread())
1144           && !Signals.stop
1145           && !thread.cutoff_occurred())
1146           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1147                                                threatMove, moveCount, &mp, NT);
1148     }
1149
1150     // Step 20. Check for mate and stalemate
1151     // All legal moves have been searched and if there are no legal moves, it
1152     // must be mate or stalemate. Note that we can have a false positive in
1153     // case of StopRequest or thread.cutoff_occurred() are set, but this is
1154     // harmless because return value is discarded anyhow in the parent nodes.
1155     // If we are in a singular extension search then return a fail low score.
1156     if (!moveCount)
1157         return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1158
1159     // If we have pruned all the moves without searching return a fail-low score
1160     if (bestValue == -VALUE_INFINITE)
1161     {
1162         assert(!playedMoveCount);
1163
1164         bestValue = alpha;
1165     }
1166
1167     // Step 21. Update tables
1168     // Update transposition table entry, killers and history
1169     if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1170     {
1171         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1172         vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1173              : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1174
1175         TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1176
1177         // Update killers and history for non capture cut-off moves
1178         if (bestValue >= beta && !pos.is_capture_or_promotion(move))
1179         {
1180             if (move != ss->killers[0])
1181             {
1182                 ss->killers[1] = ss->killers[0];
1183                 ss->killers[0] = move;
1184             }
1185
1186             // Increase history value of the cut-off move
1187             Value bonus = Value(int(depth) * int(depth));
1188             H.add(pos.piece_on(move_from(move)), move_to(move), bonus);
1189
1190             // Decrease history of all the other played non-capture moves
1191             for (int i = 0; i < playedMoveCount - 1; i++)
1192             {
1193                 Move m = movesSearched[i];
1194                 H.add(pos.piece_on(move_from(m)), move_to(m), -bonus);
1195             }
1196         }
1197     }
1198
1199     if (SpNode)
1200     {
1201         // Here we have the lock still grabbed
1202         sp->is_slave[pos.thread()] = false;
1203         sp->nodes += pos.nodes_searched();
1204         lock_release(&(sp->lock));
1205     }
1206
1207     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1208
1209     return bestValue;
1210   }
1211
1212
1213   // qsearch() is the quiescence search function, which is called by the main
1214   // search function when the remaining depth is zero (or, to be more precise,
1215   // less than ONE_PLY).
1216
1217   template <NodeType NT>
1218   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1219
1220     const bool PvNode = (NT == PV);
1221
1222     assert(NT == PV || NT == NonPV);
1223     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1224     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1225     assert(PvNode || alpha == beta - 1);
1226     assert(depth <= 0);
1227     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1228
1229     StateInfo st;
1230     Move ttMove, move;
1231     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1232     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1233     const TTEntry* tte;
1234     Depth ttDepth;
1235     ValueType vt;
1236     Value oldAlpha = alpha;
1237
1238     ss->bestMove = ss->currentMove = MOVE_NONE;
1239     ss->ply = (ss-1)->ply + 1;
1240
1241     // Check for an instant draw or maximum ply reached
1242     if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1243         return VALUE_DRAW;
1244
1245     // Decide whether or not to include checks, this fixes also the type of
1246     // TT entry depth that we are going to use. Note that in qsearch we use
1247     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1248     inCheck = pos.in_check();
1249     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1250
1251     // Transposition table lookup. At PV nodes, we don't use the TT for
1252     // pruning, but only for move ordering.
1253     tte = TT.probe(pos.get_key());
1254     ttMove = (tte ? tte->move() : MOVE_NONE);
1255
1256     if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1257     {
1258         ss->bestMove = ttMove; // Can be MOVE_NONE
1259         return value_from_tt(tte->value(), ss->ply);
1260     }
1261
1262     // Evaluate the position statically
1263     if (inCheck)
1264     {
1265         bestValue = futilityBase = -VALUE_INFINITE;
1266         ss->eval = evalMargin = VALUE_NONE;
1267         enoughMaterial = false;
1268     }
1269     else
1270     {
1271         if (tte)
1272         {
1273             assert(tte->static_value() != VALUE_NONE);
1274
1275             evalMargin = tte->static_value_margin();
1276             ss->eval = bestValue = tte->static_value();
1277         }
1278         else
1279             ss->eval = bestValue = evaluate(pos, evalMargin);
1280
1281         // Stand pat. Return immediately if static value is at least beta
1282         if (bestValue >= beta)
1283         {
1284             if (!tte)
1285                 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1286
1287             return bestValue;
1288         }
1289
1290         if (PvNode && bestValue > alpha)
1291             alpha = bestValue;
1292
1293         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1294         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1295     }
1296
1297     // Initialize a MovePicker object for the current position, and prepare
1298     // to search the moves. Because the depth is <= 0 here, only captures,
1299     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1300     // be generated.
1301     MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1302     CheckInfo ci(pos);
1303
1304     // Loop through the moves until no moves remain or a beta cutoff occurs
1305     while (   bestValue < beta
1306            && (move = mp.get_next_move()) != MOVE_NONE)
1307     {
1308       assert(is_ok(move));
1309
1310       givesCheck = pos.move_gives_check(move, ci);
1311
1312       // Futility pruning
1313       if (   !PvNode
1314           && !inCheck
1315           && !givesCheck
1316           &&  move != ttMove
1317           &&  enoughMaterial
1318           && !is_promotion(move)
1319           && !pos.is_passed_pawn_push(move))
1320       {
1321           futilityValue =  futilityBase
1322                          + PieceValueEndgame[pos.piece_on(move_to(move))]
1323                          + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1324
1325           if (futilityValue < beta)
1326           {
1327               if (futilityValue > bestValue)
1328                   bestValue = futilityValue;
1329
1330               continue;
1331           }
1332
1333           // Prune moves with negative or equal SEE
1334           if (   futilityBase < beta
1335               && depth < DEPTH_ZERO
1336               && pos.see(move) <= 0)
1337               continue;
1338       }
1339
1340       // Detect non-capture evasions that are candidate to be pruned
1341       evasionPrunable =   !PvNode
1342                        && inCheck
1343                        && bestValue > VALUE_MATED_IN_PLY_MAX
1344                        && !pos.is_capture(move)
1345                        && !pos.can_castle(pos.side_to_move());
1346
1347       // Don't search moves with negative SEE values
1348       if (   !PvNode
1349           && (!inCheck || evasionPrunable)
1350           &&  move != ttMove
1351           && !is_promotion(move)
1352           &&  pos.see_sign(move) < 0)
1353           continue;
1354
1355       // Don't search useless checks
1356       if (   !PvNode
1357           && !inCheck
1358           &&  givesCheck
1359           &&  move != ttMove
1360           && !pos.is_capture_or_promotion(move)
1361           &&  ss->eval + PawnValueMidgame / 4 < beta
1362           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1363       {
1364           if (ss->eval + PawnValueMidgame / 4 > bestValue)
1365               bestValue = ss->eval + PawnValueMidgame / 4;
1366
1367           continue;
1368       }
1369
1370       // Check for legality only before to do the move
1371       if (!pos.pl_move_is_legal(move, ci.pinned))
1372           continue;
1373
1374       ss->currentMove = move;
1375
1376       // Make and search the move
1377       pos.do_move(move, st, ci, givesCheck);
1378       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1379       pos.undo_move(move);
1380
1381       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1382
1383       // New best move?
1384       if (value > bestValue)
1385       {
1386           bestValue = value;
1387           ss->bestMove = move;
1388
1389           if (   PvNode
1390               && value > alpha
1391               && value < beta) // We want always alpha < beta
1392               alpha = value;
1393        }
1394     }
1395
1396     // All legal moves have been searched. A special case: If we're in check
1397     // and no legal moves were found, it is checkmate.
1398     if (inCheck && bestValue == -VALUE_INFINITE)
1399         return value_mated_in(ss->ply);
1400
1401     // Update transposition table
1402     move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1403     vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1404          : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1405
1406     TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1407
1408     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1409
1410     return bestValue;
1411   }
1412
1413
1414   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1415   // bestValue is updated only when returning false because in that case move
1416   // will be pruned.
1417
1418   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1419   {
1420     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1421     Square from, to, ksq, victimSq;
1422     Piece pc;
1423     Color them;
1424     Value futilityValue, bv = *bestValue;
1425
1426     from = move_from(move);
1427     to = move_to(move);
1428     them = flip(pos.side_to_move());
1429     ksq = pos.king_square(them);
1430     kingAtt = pos.attacks_from<KING>(ksq);
1431     pc = pos.piece_on(from);
1432
1433     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1434     oldAtt = pos.attacks_from(pc, from, occ);
1435     newAtt = pos.attacks_from(pc,   to, occ);
1436
1437     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1438     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1439
1440     if (!(b && (b & (b - 1))))
1441         return true;
1442
1443     // Rule 2. Queen contact check is very dangerous
1444     if (   type_of(pc) == QUEEN
1445         && bit_is_set(kingAtt, to))
1446         return true;
1447
1448     // Rule 3. Creating new double threats with checks
1449     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1450
1451     while (b)
1452     {
1453         victimSq = pop_1st_bit(&b);
1454         futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1455
1456         // Note that here we generate illegal "double move"!
1457         if (   futilityValue >= beta
1458             && pos.see_sign(make_move(from, victimSq)) >= 0)
1459             return true;
1460
1461         if (futilityValue > bv)
1462             bv = futilityValue;
1463     }
1464
1465     // Update bestValue only if check is not dangerous (because we will prune the move)
1466     *bestValue = bv;
1467     return false;
1468   }
1469
1470
1471   // connected_moves() tests whether two moves are 'connected' in the sense
1472   // that the first move somehow made the second move possible (for instance
1473   // if the moving piece is the same in both moves). The first move is assumed
1474   // to be the move that was made to reach the current position, while the
1475   // second move is assumed to be a move from the current position.
1476
1477   bool connected_moves(const Position& pos, Move m1, Move m2) {
1478
1479     Square f1, t1, f2, t2;
1480     Piece p1, p2;
1481     Square ksq;
1482
1483     assert(is_ok(m1));
1484     assert(is_ok(m2));
1485
1486     // Case 1: The moving piece is the same in both moves
1487     f2 = move_from(m2);
1488     t1 = move_to(m1);
1489     if (f2 == t1)
1490         return true;
1491
1492     // Case 2: The destination square for m2 was vacated by m1
1493     t2 = move_to(m2);
1494     f1 = move_from(m1);
1495     if (t2 == f1)
1496         return true;
1497
1498     // Case 3: Moving through the vacated square
1499     p2 = pos.piece_on(f2);
1500     if (   piece_is_slider(p2)
1501         && bit_is_set(squares_between(f2, t2), f1))
1502       return true;
1503
1504     // Case 4: The destination square for m2 is defended by the moving piece in m1
1505     p1 = pos.piece_on(t1);
1506     if (bit_is_set(pos.attacks_from(p1, t1), t2))
1507         return true;
1508
1509     // Case 5: Discovered check, checking piece is the piece moved in m1
1510     ksq = pos.king_square(pos.side_to_move());
1511     if (    piece_is_slider(p1)
1512         &&  bit_is_set(squares_between(t1, ksq), f2))
1513     {
1514         Bitboard occ = pos.occupied_squares();
1515         clear_bit(&occ, f2);
1516         if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1517             return true;
1518     }
1519     return false;
1520   }
1521
1522
1523   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1524   // "plies to mate from the current ply".  Non-mate scores are unchanged.
1525   // The function is called before storing a value to the transposition table.
1526
1527   Value value_to_tt(Value v, int ply) {
1528
1529     if (v >= VALUE_MATE_IN_PLY_MAX)
1530       return v + ply;
1531
1532     if (v <= VALUE_MATED_IN_PLY_MAX)
1533       return v - ply;
1534
1535     return v;
1536   }
1537
1538
1539   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1540   // the transposition table to a mate score corrected for the current ply.
1541
1542   Value value_from_tt(Value v, int ply) {
1543
1544     if (v >= VALUE_MATE_IN_PLY_MAX)
1545       return v - ply;
1546
1547     if (v <= VALUE_MATED_IN_PLY_MAX)
1548       return v + ply;
1549
1550     return v;
1551   }
1552
1553
1554   // connected_threat() tests whether it is safe to forward prune a move or if
1555   // is somehow connected to the threat move returned by null search.
1556
1557   bool connected_threat(const Position& pos, Move m, Move threat) {
1558
1559     assert(is_ok(m));
1560     assert(is_ok(threat));
1561     assert(!pos.is_capture_or_promotion(m));
1562     assert(!pos.is_passed_pawn_push(m));
1563
1564     Square mfrom, mto, tfrom, tto;
1565
1566     mfrom = move_from(m);
1567     mto = move_to(m);
1568     tfrom = move_from(threat);
1569     tto = move_to(threat);
1570
1571     // Case 1: Don't prune moves which move the threatened piece
1572     if (mfrom == tto)
1573         return true;
1574
1575     // Case 2: If the threatened piece has value less than or equal to the
1576     // value of the threatening piece, don't prune moves which defend it.
1577     if (   pos.is_capture(threat)
1578         && (   PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1579             || type_of(pos.piece_on(tfrom)) == KING)
1580         && pos.move_attacks_square(m, tto))
1581         return true;
1582
1583     // Case 3: If the moving piece in the threatened move is a slider, don't
1584     // prune safe moves which block its ray.
1585     if (   piece_is_slider(pos.piece_on(tfrom))
1586         && bit_is_set(squares_between(tfrom, tto), mto)
1587         && pos.see_sign(m) >= 0)
1588         return true;
1589
1590     return false;
1591   }
1592
1593
1594   // can_return_tt() returns true if a transposition table score can be used to
1595   // cut-off at a given point in search.
1596
1597   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1598
1599     Value v = value_from_tt(tte->value(), ply);
1600
1601     return   (   tte->depth() >= depth
1602               || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1603               || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1604
1605           && (   ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1606               || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1607   }
1608
1609
1610   // refine_eval() returns the transposition table score if possible, otherwise
1611   // falls back on static position evaluation.
1612
1613   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1614
1615       assert(tte);
1616
1617       Value v = value_from_tt(tte->value(), ply);
1618
1619       if (   ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1620           || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1621           return v;
1622
1623       return defaultEval;
1624   }
1625
1626
1627   // current_search_time() returns the number of milliseconds which have passed
1628   // since the beginning of the current search.
1629
1630   int elapsed_time(bool reset) {
1631
1632     static int searchStartTime;
1633
1634     if (reset)
1635         searchStartTime = get_system_time();
1636
1637     return get_system_time() - searchStartTime;
1638   }
1639
1640
1641   // score_to_uci() converts a value to a string suitable for use with the UCI
1642   // protocol specifications:
1643   //
1644   // cp <x>     The score from the engine's point of view in centipawns.
1645   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1646   //            use negative values for y.
1647
1648   string score_to_uci(Value v, Value alpha, Value beta) {
1649
1650     std::stringstream s;
1651
1652     if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1653         s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1654     else
1655         s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1656
1657     s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1658
1659     return s.str();
1660   }
1661
1662
1663   // pv_info_to_uci() sends search info to GUI. UCI protocol requires to send all
1664   // the PV lines also if are still to be searched and so refer to the previous
1665   // search score.
1666
1667   void pv_info_to_uci(const Position& pos, int depth, Value alpha, Value beta) {
1668
1669     int t = elapsed_time();
1670     int selDepth = 0;
1671
1672     for (int i = 0; i < Threads.size(); i++)
1673         if (Threads[i].maxPly > selDepth)
1674             selDepth = Threads[i].maxPly;
1675
1676     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1677     {
1678         bool updated = (i <= PVIdx);
1679
1680         if (depth == 1 && !updated)
1681             continue;
1682
1683         int d = (updated ? depth : depth - 1);
1684         Value s = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1685
1686         cout << "info"
1687              << " depth " << d
1688              << " seldepth " << selDepth
1689              << (i == PVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
1690              << " nodes " << pos.nodes_searched()
1691              << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1692              << " time " << t
1693              << " multipv " << i + 1 << " pv";
1694
1695         for (int j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1696             cout <<  " " << RootMoves[i].pv[j];
1697
1698         cout << endl;
1699     }
1700   }
1701
1702
1703   // pv_info_to_log() writes human-readable search information to the log file
1704   // (which is created when the UCI parameter "Use Search Log" is "true"). It
1705   // uses the two below helpers to pretty format time and score respectively.
1706
1707   string time_to_string(int millisecs) {
1708
1709     const int MSecMinute = 1000 * 60;
1710     const int MSecHour   = 1000 * 60 * 60;
1711
1712     int hours = millisecs / MSecHour;
1713     int minutes =  (millisecs % MSecHour) / MSecMinute;
1714     int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1715
1716     std::stringstream s;
1717
1718     if (hours)
1719         s << hours << ':';
1720
1721     s << std::setfill('0') << std::setw(2) << minutes << ':'
1722                            << std::setw(2) << seconds;
1723     return s.str();
1724   }
1725
1726   string score_to_string(Value v) {
1727
1728     std::stringstream s;
1729
1730     if (v >= VALUE_MATE_IN_PLY_MAX)
1731         s << "#" << (VALUE_MATE - v + 1) / 2;
1732     else if (v <= VALUE_MATED_IN_PLY_MAX)
1733         s << "-#" << (VALUE_MATE + v) / 2;
1734     else
1735         s << std::setprecision(2) << std::fixed << std::showpos
1736           << float(v) / PawnValueMidgame;
1737
1738     return s.str();
1739   }
1740
1741   void pv_info_to_log(Position& pos, int depth, Value value, int time, Move pv[]) {
1742
1743     const int64_t K = 1000;
1744     const int64_t M = 1000000;
1745
1746     StateInfo state[PLY_MAX_PLUS_2], *st = state;
1747     Move* m = pv;
1748     string san, padding;
1749     size_t length;
1750     std::stringstream s;
1751
1752     s << set960(pos.is_chess960())
1753       << std::setw(2) << depth
1754       << std::setw(8) << score_to_string(value)
1755       << std::setw(8) << time_to_string(time);
1756
1757     if (pos.nodes_searched() < M)
1758         s << std::setw(8) << pos.nodes_searched() / 1 << "  ";
1759
1760     else if (pos.nodes_searched() < K * M)
1761         s << std::setw(7) << pos.nodes_searched() / K << "K  ";
1762
1763     else
1764         s << std::setw(7) << pos.nodes_searched() / M << "M  ";
1765
1766     padding = string(s.str().length(), ' ');
1767     length = padding.length();
1768
1769     while (*m != MOVE_NONE)
1770     {
1771         san = move_to_san(pos, *m);
1772
1773         if (length + san.length() > 80)
1774         {
1775             s << "\n" + padding;
1776             length = padding.length();
1777         }
1778
1779         s << san << ' ';
1780         length += san.length() + 1;
1781
1782         pos.do_move(*m++, *st++);
1783     }
1784
1785     while (m != pv)
1786         pos.undo_move(*--m);
1787
1788     Log l(Options["Search Log Filename"].value<string>());
1789     l << s.str() << endl;
1790   }
1791
1792
1793   // When playing with strength handicap choose best move among the MultiPV set
1794   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1795
1796   Move do_skill_level() {
1797
1798     assert(MultiPV > 1);
1799
1800     static RKISS rk;
1801
1802     // PRNG sequence should be not deterministic
1803     for (int i = abs(get_system_time() % 50); i > 0; i--)
1804         rk.rand<unsigned>();
1805
1806     // RootMoves are already sorted by score in descending order
1807     size_t size = std::min(MultiPV, RootMoves.size());
1808     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1809     int weakness = 120 - 2 * SkillLevel;
1810     int max_s = -VALUE_INFINITE;
1811     Move best = MOVE_NONE;
1812
1813     // Choose best move. For each move score we add two terms both dependent on
1814     // weakness, one deterministic and bigger for weaker moves, and one random,
1815     // then we choose the move with the resulting highest score.
1816     for (size_t i = 0; i < size; i++)
1817     {
1818         int s = RootMoves[i].score;
1819
1820         // Don't allow crazy blunders even at very low skills
1821         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1822             break;
1823
1824         // This is our magic formula
1825         s += (  weakness * int(RootMoves[0].score - s)
1826               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1827
1828         if (s > max_s)
1829         {
1830             max_s = s;
1831             best = RootMoves[i].pv[0];
1832         }
1833     }
1834     return best;
1835   }
1836
1837
1838   // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1839   // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1840   // allow to always have a ponder move even when we fail high at root and also a
1841   // long PV to print that is important for position analysis.
1842
1843   void RootMove::extract_pv_from_tt(Position& pos) {
1844
1845     StateInfo state[PLY_MAX_PLUS_2], *st = state;
1846     TTEntry* tte;
1847     int ply = 1;
1848     Move m = pv[0];
1849
1850     assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1851
1852     pv.clear();
1853     pv.push_back(m);
1854     pos.do_move(m, *st++);
1855
1856     while (   (tte = TT.probe(pos.get_key())) != NULL
1857            && tte->move() != MOVE_NONE
1858            && pos.is_pseudo_legal(tte->move())
1859            && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
1860            && ply < PLY_MAX
1861            && (!pos.is_draw<false>() || ply < 2))
1862     {
1863         pv.push_back(tte->move());
1864         pos.do_move(tte->move(), *st++);
1865         ply++;
1866     }
1867     pv.push_back(MOVE_NONE);
1868
1869     do pos.undo_move(pv[--ply]); while (ply);
1870   }
1871
1872
1873   // insert_pv_in_tt() is called at the end of a search iteration, and inserts
1874   // the PV back into the TT. This makes sure the old PV moves are searched
1875   // first, even if the old TT entries have been overwritten.
1876
1877   void RootMove::insert_pv_in_tt(Position& pos) {
1878
1879     StateInfo state[PLY_MAX_PLUS_2], *st = state;
1880     TTEntry* tte;
1881     Key k;
1882     Value v, m = VALUE_NONE;
1883     int ply = 0;
1884
1885     assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1886
1887     do {
1888         k = pos.get_key();
1889         tte = TT.probe(k);
1890
1891         // Don't overwrite existing correct entries
1892         if (!tte || tte->move() != pv[ply])
1893         {
1894             v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1895             TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
1896         }
1897         pos.do_move(pv[ply], *st++);
1898
1899     } while (pv[++ply] != MOVE_NONE);
1900
1901     do pos.undo_move(pv[--ply]); while (ply);
1902   }
1903
1904 } // namespace
1905
1906
1907 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1908 /// The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
1909 /// for which the thread is the master.
1910
1911 void Thread::idle_loop(SplitPoint* sp) {
1912
1913   while (true)
1914   {
1915       // If we are not searching, wait for a condition to be signaled
1916       // instead of wasting CPU time polling for work.
1917       while (   do_sleep
1918              || do_terminate
1919              || (Threads.use_sleeping_threads() && !is_searching))
1920       {
1921           assert((!sp && threadID) || Threads.use_sleeping_threads());
1922
1923           if (do_terminate)
1924           {
1925               assert(!sp);
1926               return;
1927           }
1928
1929           // Grab the lock to avoid races with Thread::wake_up()
1930           lock_grab(&sleepLock);
1931
1932           // If we are master and all slaves have finished don't go to sleep
1933           if (sp && Threads.split_point_finished(sp))
1934           {
1935               lock_release(&sleepLock);
1936               break;
1937           }
1938
1939           // Do sleep after retesting sleep conditions under lock protection, in
1940           // particular we need to avoid a deadlock in case a master thread has,
1941           // in the meanwhile, allocated us and sent the wake_up() call before we
1942           // had the chance to grab the lock.
1943           if (do_sleep || !is_searching)
1944               cond_wait(&sleepCond, &sleepLock);
1945
1946           lock_release(&sleepLock);
1947       }
1948
1949       // If this thread has been assigned work, launch a search
1950       if (is_searching)
1951       {
1952           assert(!do_terminate);
1953
1954           // Copy split point position and search stack and call search()
1955           Stack ss[PLY_MAX_PLUS_2];
1956           SplitPoint* tsp = splitPoint;
1957           Position pos(*tsp->pos, threadID);
1958
1959           memcpy(ss, tsp->ss - 1, 4 * sizeof(Stack));
1960           (ss+1)->sp = tsp;
1961
1962           if (tsp->nodeType == Root)
1963               search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1964           else if (tsp->nodeType == PV)
1965               search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1966           else if (tsp->nodeType == NonPV)
1967               search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
1968           else
1969               assert(false);
1970
1971           assert(is_searching);
1972
1973           is_searching = false;
1974
1975           // Wake up master thread so to allow it to return from the idle loop in
1976           // case we are the last slave of the split point.
1977           if (   Threads.use_sleeping_threads()
1978               && threadID != tsp->master
1979               && !Threads[tsp->master].is_searching)
1980               Threads[tsp->master].wake_up();
1981       }
1982
1983       // If this thread is the master of a split point and all slaves have
1984       // finished their work at this split point, return from the idle loop.
1985       if (sp && Threads.split_point_finished(sp))
1986       {
1987           // Because sp->is_slave[] is reset under lock protection,
1988           // be sure sp->lock has been released before to return.
1989           lock_grab(&(sp->lock));
1990           lock_release(&(sp->lock));
1991           return;
1992       }
1993   }
1994 }
1995
1996
1997 /// do_timer_event() is called by the timer thread when the timer triggers. It
1998 /// is used to print debug info and, more important, to detect when we are out of
1999 /// available time and so stop the search.
2000
2001 void do_timer_event() {
2002
2003   static int lastInfoTime;
2004   int e = elapsed_time();
2005
2006   if (get_system_time() - lastInfoTime >= 1000 || !lastInfoTime)
2007   {
2008       lastInfoTime = get_system_time();
2009
2010       dbg_print_mean();
2011       dbg_print_hit_rate();
2012   }
2013
2014   if (Limits.ponder)
2015       return;
2016
2017   bool stillAtFirstMove =    Signals.firstRootMove
2018                          && !Signals.failedLowAtRoot
2019                          &&  e > TimeMgr.available_time();
2020
2021   bool noMoreTime =   e > TimeMgr.maximum_time()
2022                    || stillAtFirstMove;
2023
2024   if (   (Limits.useTimeManagement() && noMoreTime)
2025       || (Limits.maxTime && e >= Limits.maxTime)
2026          /* missing nodes limit */ ) // FIXME
2027       Signals.stop = true;
2028 }