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