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