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