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