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