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