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