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