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