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