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