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