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