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