]> git.sesse.net Git - stockfish/blob - src/search.cpp
Introduce notation.h
[stockfish] / src / search.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iostream>
25 #include <sstream>
26
27 #include "book.h"
28 #include "evaluate.h"
29 #include "history.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "notation.h"
33 #include "search.h"
34 #include "timeman.h"
35 #include "thread.h"
36 #include "tt.h"
37 #include "ucioption.h"
38
39 namespace Search {
40
41   volatile SignalsType Signals;
42   LimitsType Limits;
43   std::vector<RootMove> RootMoves;
44   Position RootPosition;
45   Time SearchTime;
46 }
47
48 using std::string;
49 using std::cout;
50 using std::endl;
51 using Eval::evaluate;
52 using namespace Search;
53
54 // For some reason argument-dependent lookup (ADL) doesn't work for Android's
55 // STLPort, so explicitly qualify following functions.
56 using std::count;
57 using std::find;
58
59 namespace {
60
61   // Set to true to force running with one thread. Used for debugging
62   const bool FakeSplit = false;
63
64   // Different node types, used as template parameter
65   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
66
67   // Lookup table to check if a Piece is a slider and its access function
68   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
69   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
70
71   // Maximum depth for razoring
72   const Depth RazorDepth = 4 * ONE_PLY;
73
74   // Dynamic razoring margin based on depth
75   inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
76
77   // Maximum depth for use of dynamic threat detection when null move fails low
78   const Depth ThreatDepth = 5 * ONE_PLY;
79
80   // Minimum depth for use of internal iterative deepening
81   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
82
83   // At Non-PV nodes we do an internal iterative deepening search
84   // when the static evaluation is bigger then beta - IIDMargin.
85   const Value IIDMargin = Value(256);
86
87   // Minimum depth for use of singular extension
88   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
89
90   // Futility margin for quiescence search
91   const Value FutilityMarginQS = Value(128);
92
93   // Futility lookup tables (initialized at startup) and their access functions
94   Value FutilityMargins[16][64]; // [depth][moveNumber]
95   int FutilityMoveCounts[32];    // [depth]
96
97   inline Value futility_margin(Depth d, int mn) {
98
99     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
100                            : 2 * VALUE_INFINITE;
101   }
102
103   inline int futility_move_count(Depth d) {
104
105     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
106   }
107
108   // Reduction lookup tables (initialized at startup) and their access function
109   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
110
111   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
112
113     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
114   }
115
116   // Easy move margin. An easy move candidate must be at least this much better
117   // than the second best move.
118   const Value EasyMoveMargin = Value(0x150);
119
120   // This is the minimum interval in msec between two check_time() calls
121   const int TimerResolution = 5;
122
123
124   size_t MultiPV, UCIMultiPV, PVIdx;
125   TimeManager TimeMgr;
126   int BestMoveChanges;
127   int SkillLevel;
128   bool SkillLevelEnabled, Chess960;
129   History H;
130
131
132   template <NodeType NT>
133   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
134
135   template <NodeType NT>
136   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
137
138   void id_loop(Position& pos);
139   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
140   bool connected_moves(const Position& pos, Move m1, Move m2);
141   Value value_to_tt(Value v, int ply);
142   Value value_from_tt(Value v, int ply);
143   bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
144   bool connected_threat(const Position& pos, Move m, Move threat);
145   Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
146   Move do_skill_level();
147   string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
148
149   // MovePickerExt class template extends MovePicker and allows to choose at
150   // compile time the proper moves source according to the type of node. In the
151   // default case we simply create and use a standard MovePicker object.
152   template<bool SpNode> struct MovePickerExt : public MovePicker {
153
154     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
155                   : MovePicker(p, ttm, d, h, ss, b) {}
156   };
157
158   // In case of a SpNode we use split point's shared MovePicker object as moves source
159   template<> struct MovePickerExt<true> : public MovePicker {
160
161     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, Stack* ss, Value b)
162                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
163
164     Move next_move() { return mp->next_move(); }
165     MovePicker* mp;
166   };
167
168   // is_dangerous() checks whether a move belongs to some classes of known
169   // 'dangerous' moves so that we avoid to prune it.
170   FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
171
172     // Castle move?
173     if (type_of(m) == CASTLE)
174         return true;
175
176     // Passed pawn move?
177     if (   type_of(pos.piece_moved(m)) == PAWN
178         && pos.pawn_is_passed(pos.side_to_move(), to_sq(m)))
179         return true;
180
181     // Entering a pawn endgame?
182     if (    captureOrPromotion
183         &&  type_of(pos.piece_on(to_sq(m))) != PAWN
184         &&  type_of(m) == NORMAL
185         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
186             - PieceValueMidgame[pos.piece_on(to_sq(m))] == VALUE_ZERO))
187         return true;
188
189     return false;
190   }
191
192 } // namespace
193
194
195 /// Search::init() is called during startup to initialize various lookup tables
196
197 void Search::init() {
198
199   int d;  // depth (ONE_PLY == 2)
200   int hd; // half depth (ONE_PLY == 1)
201   int mc; // moveCount
202
203   // Init reductions array
204   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
205   {
206       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
207       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
208       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
209       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
210   }
211
212   // Init futility margins array
213   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
214       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
215
216   // Init futility move count array
217   for (d = 0; d < 32; d++)
218       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
219 }
220
221
222 /// Search::perft() is our utility to verify move generation. All the leaf nodes
223 /// up to the given depth are generated and counted and the sum returned.
224
225 int64_t Search::perft(Position& pos, Depth depth) {
226
227   StateInfo st;
228   int64_t cnt = 0;
229
230   MoveList<LEGAL> ml(pos);
231
232   // At the last ply just return the number of moves (leaf nodes)
233   if (depth == ONE_PLY)
234       return ml.size();
235
236   CheckInfo ci(pos);
237   for ( ; !ml.end(); ++ml)
238   {
239       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
240       cnt += perft(pos, depth - ONE_PLY);
241       pos.undo_move(ml.move());
242   }
243   return cnt;
244 }
245
246
247 /// Search::think() is the external interface to Stockfish's search, and is
248 /// called by the main thread when the program receives the UCI 'go' command. It
249 /// searches from RootPosition and at the end prints the "bestmove" to output.
250
251 void Search::think() {
252
253   static Book book; // Defined static to initialize the PRNG only once
254
255   Position& pos = RootPosition;
256   Chess960 = pos.is_chess960();
257   Eval::RootColor = pos.side_to_move();
258   TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
259   TT.new_search();
260   H.clear();
261
262   if (RootMoves.empty())
263   {
264       cout << "info depth 0 score "
265            << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
266
267       RootMoves.push_back(MOVE_NONE);
268       goto finalize;
269   }
270
271   if (Options["OwnBook"] && !Limits.infinite)
272   {
273       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
274
275       if (bookMove && count(RootMoves.begin(), RootMoves.end(), bookMove))
276       {
277           std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), bookMove));
278           goto finalize;
279       }
280   }
281
282   UCIMultiPV = Options["MultiPV"];
283   SkillLevel = Options["Skill Level"];
284
285   // Do we have to play with skill handicap? In this case enable MultiPV that
286   // we will use behind the scenes to retrieve a set of possible moves.
287   SkillLevelEnabled = (SkillLevel < 20);
288   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
289
290   if (Options["Use Search Log"])
291   {
292       Log log(Options["Search Log Filename"]);
293       log << "\nSearching: "  << pos.to_fen()
294           << "\ninfinite: "   << Limits.infinite
295           << " ponder: "      << Limits.ponder
296           << " time: "        << Limits.time[pos.side_to_move()]
297           << " increment: "   << Limits.inc[pos.side_to_move()]
298           << " moves to go: " << Limits.movestogo
299           << endl;
300   }
301
302   Threads.wake_up();
303
304   // Set best timer interval to avoid lagging under time pressure. Timer is
305   // used to check for remaining available thinking time.
306   if (Limits.use_time_management())
307       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
308   else
309       Threads.set_timer(100);
310
311   // We're ready to start searching. Call the iterative deepening loop function
312   id_loop(pos);
313
314   Threads.set_timer(0); // Stop timer
315   Threads.sleep();
316
317   if (Options["Use Search Log"])
318   {
319       int e = SearchTime.elapsed();
320
321       Log log(Options["Search Log Filename"]);
322       log << "Nodes: "          << pos.nodes_searched()
323           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
324           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
325
326       StateInfo st;
327       pos.do_move(RootMoves[0].pv[0], st);
328       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
329       pos.undo_move(RootMoves[0].pv[0]);
330   }
331
332 finalize:
333
334   // When we reach max depth we arrive here even without Signals.stop is raised,
335   // but if we are pondering or in infinite search, we shouldn't print the best
336   // move before we are told to do so.
337   if (!Signals.stop && (Limits.ponder || Limits.infinite))
338       pos.this_thread()->wait_for_stop_or_ponderhit();
339
340   // Best move could be MOVE_NONE when searching on a stalemate position
341   cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
342        << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
343 }
344
345
346 namespace {
347
348   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
349   // with increasing depth until the allocated thinking time has been consumed,
350   // user stops the search, or the maximum search depth is reached.
351
352   void id_loop(Position& pos) {
353
354     Stack ss[MAX_PLY_PLUS_2];
355     int depth, prevBestMoveChanges;
356     Value bestValue, alpha, beta, delta;
357     bool bestMoveNeverChanged = true;
358     Move skillBest = MOVE_NONE;
359
360     memset(ss, 0, 4 * sizeof(Stack));
361     depth = BestMoveChanges = 0;
362     bestValue = delta = -VALUE_INFINITE;
363     ss->currentMove = MOVE_NULL; // Hack to skip update gains
364
365     // Iterative deepening loop until requested to stop or target depth reached
366     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
367     {
368         // Save last iteration's scores before first PV line is searched and all
369         // the move scores but the (new) PV are set to -VALUE_INFINITE.
370         for (size_t i = 0; i < RootMoves.size(); i++)
371             RootMoves[i].prevScore = RootMoves[i].score;
372
373         prevBestMoveChanges = BestMoveChanges;
374         BestMoveChanges = 0;
375
376         // MultiPV loop. We perform a full root search for each PV line
377         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
378         {
379             // Set aspiration window default width
380             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
381             {
382                 delta = Value(16);
383                 alpha = RootMoves[PVIdx].prevScore - delta;
384                 beta  = RootMoves[PVIdx].prevScore + delta;
385             }
386             else
387             {
388                 alpha = -VALUE_INFINITE;
389                 beta  =  VALUE_INFINITE;
390             }
391
392             // Start with a small aspiration window and, in case of fail high/low,
393             // research with bigger window until not failing high/low anymore.
394             do {
395                 // Search starts from ss+1 to allow referencing (ss-1). This is
396                 // needed by update gains and ss copy when splitting at Root.
397                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
398
399                 // Bring to front the best move. It is critical that sorting is
400                 // done with a stable algorithm because all the values but the first
401                 // and eventually the new best one are set to -VALUE_INFINITE and
402                 // we want to keep the same order for all the moves but the new
403                 // PV that goes to the front. Note that in case of MultiPV search
404                 // the already searched PV lines are preserved.
405                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
406
407                 // In case we have found an exact score and we are going to leave
408                 // the fail high/low loop then reorder the PV moves, otherwise
409                 // leave the last PV move in its position so to be searched again.
410                 // Of course this is needed only in MultiPV search.
411                 if (PVIdx && bestValue > alpha && bestValue < beta)
412                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
413
414                 // Write PV back to transposition table in case the relevant
415                 // entries have been overwritten during the search.
416                 for (size_t i = 0; i <= PVIdx; i++)
417                     RootMoves[i].insert_pv_in_tt(pos);
418
419                 // If search has been stopped exit the aspiration window loop.
420                 // Sorting and writing PV back to TT is safe becuase RootMoves
421                 // is still valid, although refers to previous iteration.
422                 if (Signals.stop)
423                     break;
424
425                 // Send full PV info to GUI if we are going to leave the loop or
426                 // if we have a fail high/low and we are deep in the search.
427                 if ((bestValue > alpha && bestValue < beta) || SearchTime.elapsed() > 2000)
428                     cout << uci_pv(pos, depth, alpha, beta) << endl;
429
430                 // In case of failing high/low increase aspiration window and
431                 // research, otherwise exit the fail high/low loop.
432                 if (bestValue >= beta)
433                 {
434                     beta += delta;
435                     delta += delta / 2;
436                 }
437                 else if (bestValue <= alpha)
438                 {
439                     Signals.failedLowAtRoot = true;
440                     Signals.stopOnPonderhit = false;
441
442                     alpha -= delta;
443                     delta += delta / 2;
444                 }
445                 else
446                     break;
447
448                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
449
450             } while (abs(bestValue) < VALUE_KNOWN_WIN);
451         }
452
453         // Skills: Do we need to pick now the best move ?
454         if (SkillLevelEnabled && depth == 1 + SkillLevel)
455             skillBest = do_skill_level();
456
457         if (!Signals.stop && Options["Use Search Log"])
458         {
459             Log log(Options["Search Log Filename"]);
460             log << pretty_pv(pos, depth, bestValue, SearchTime.elapsed(), &RootMoves[0].pv[0])
461                 << endl;
462         }
463
464         // Filter out startup noise when monitoring best move stability
465         if (depth > 2 && BestMoveChanges)
466             bestMoveNeverChanged = false;
467
468         // Do we have time for the next iteration? Can we stop searching now?
469         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
470         {
471             bool stop = false; // Local variable, not the volatile Signals.stop
472
473             // Take in account some extra time if the best move has changed
474             if (depth > 4 && depth < 50)
475                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
476
477             // Stop search if most of available time is already consumed. We
478             // probably don't have enough time to search the first move at the
479             // next iteration anyway.
480             if (SearchTime.elapsed() > (TimeMgr.available_time() * 62) / 100)
481                 stop = true;
482
483             // Stop search early if one move seems to be much better than others
484             if (    depth >= 12
485                 && !stop
486                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
487                     || SearchTime.elapsed() > (TimeMgr.available_time() * 40) / 100))
488             {
489                 Value rBeta = bestValue - EasyMoveMargin;
490                 (ss+1)->excludedMove = RootMoves[0].pv[0];
491                 (ss+1)->skipNullMove = true;
492                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
493                 (ss+1)->skipNullMove = false;
494                 (ss+1)->excludedMove = MOVE_NONE;
495
496                 if (v < rBeta)
497                     stop = true;
498             }
499
500             if (stop)
501             {
502                 // If we are allowed to ponder do not stop the search now but
503                 // keep pondering until GUI sends "ponderhit" or "stop".
504                 if (Limits.ponder)
505                     Signals.stopOnPonderhit = true;
506                 else
507                     Signals.stop = true;
508             }
509         }
510     }
511
512     // When using skills swap best PV line with the sub-optimal one
513     if (SkillLevelEnabled)
514     {
515         if (skillBest == MOVE_NONE) // Still unassigned ?
516             skillBest = do_skill_level();
517
518         std::swap(RootMoves[0], *find(RootMoves.begin(), RootMoves.end(), skillBest));
519     }
520   }
521
522
523   // search<>() is the main search function for both PV and non-PV nodes and for
524   // normal and SplitPoint nodes. When called just after a split point the search
525   // is simpler because we have already probed the hash table, done a null move
526   // search, and searched the first move before splitting, we don't have to repeat
527   // all this work again. We also don't need to store anything to the hash table
528   // here: This is taken care of after we return from the split point.
529
530   template <NodeType NT>
531   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
532
533     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
534     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
535     const bool RootNode = (NT == Root || NT == SplitPointRoot);
536
537     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
538     assert((alpha == beta - 1) || PvNode);
539     assert(depth > DEPTH_ZERO);
540
541     Move movesSearched[64];
542     StateInfo st;
543     const TTEntry *tte;
544     Key posKey;
545     Move ttMove, move, excludedMove, bestMove, threatMove;
546     Depth ext, newDepth;
547     Bound bt;
548     Value bestValue, value, oldAlpha, ttValue;
549     Value refinedValue, nullValue, futilityBase, futilityValue;
550     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
551     bool captureOrPromotion, dangerous, doFullDepthSearch;
552     int moveCount = 0, playedMoveCount = 0;
553     Thread* thisThread = pos.this_thread();
554     SplitPoint* sp = NULL;
555
556     refinedValue = bestValue = value = -VALUE_INFINITE;
557     oldAlpha = alpha;
558     inCheck = pos.in_check();
559     ss->ply = (ss-1)->ply + 1;
560
561     // Used to send selDepth info to GUI
562     if (PvNode && thisThread->maxPly < ss->ply)
563         thisThread->maxPly = ss->ply;
564
565     // Step 1. Initialize node
566     if (SpNode)
567     {
568         tte = NULL;
569         ttMove = excludedMove = MOVE_NONE;
570         ttValue = VALUE_ZERO;
571         sp = ss->sp;
572         bestMove = sp->bestMove;
573         threatMove = sp->threatMove;
574         bestValue = sp->bestValue;
575         moveCount = sp->moveCount; // Lock must be held here
576
577         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
578
579         goto split_point_start;
580     }
581     else
582     {
583         ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
584         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
585         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
586
587     }
588
589     // Step 2. Check for aborted search and immediate draw
590     // Enforce node limit here. FIXME: This only works with 1 search thread.
591     if (Limits.nodes && pos.nodes_searched() >= Limits.nodes)
592         Signals.stop = true;
593
594     if ((   Signals.stop
595          || pos.is_draw<false>()
596          || ss->ply > MAX_PLY) && !RootNode)
597         return VALUE_DRAW;
598
599     // Step 3. Mate distance pruning. Even if we mate at the next move our score
600     // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
601     // a shorter mate was found upward in the tree then there is no need to search
602     // further, we will never beat current alpha. Same logic but with reversed signs
603     // applies also in the opposite condition of being mated instead of giving mate,
604     // in this case return a fail-high score.
605     if (!RootNode)
606     {
607         alpha = std::max(mated_in(ss->ply), alpha);
608         beta = std::min(mate_in(ss->ply+1), beta);
609         if (alpha >= beta)
610             return alpha;
611     }
612
613     // Step 4. Transposition table lookup
614     // We don't want the score of a partial search to overwrite a previous full search
615     // TT value, so we use a different position key in case of an excluded move.
616     excludedMove = ss->excludedMove;
617     posKey = excludedMove ? pos.exclusion_key() : pos.key();
618     tte = TT.probe(posKey);
619     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
620     ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_ZERO;
621
622     // At PV nodes we check for exact scores, while at non-PV nodes we check for
623     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
624     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
625     // we should also update RootMoveList to avoid bogus output.
626     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
627                                     : can_return_tt(tte, depth, ttValue, beta)))
628     {
629         TT.refresh(tte);
630         ss->currentMove = ttMove; // Can be MOVE_NONE
631
632         if (    ttValue >= beta
633             &&  ttMove
634             && !pos.is_capture_or_promotion(ttMove)
635             &&  ttMove != ss->killers[0])
636         {
637             ss->killers[1] = ss->killers[0];
638             ss->killers[0] = ttMove;
639         }
640         return ttValue;
641     }
642
643     // Step 5. Evaluate the position statically and update parent's gain statistics
644     if (inCheck)
645         ss->eval = ss->evalMargin = VALUE_NONE;
646     else if (tte)
647     {
648         assert(tte->static_value() != VALUE_NONE);
649
650         ss->eval = tte->static_value();
651         ss->evalMargin = tte->static_value_margin();
652         refinedValue = refine_eval(tte, ttValue, ss->eval);
653     }
654     else
655     {
656         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
657         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
658     }
659
660     // Update gain for the parent non-capture move given the static position
661     // evaluation before and after the move.
662     if (    (move = (ss-1)->currentMove) != MOVE_NULL
663         &&  (ss-1)->eval != VALUE_NONE
664         &&  ss->eval != VALUE_NONE
665         && !pos.captured_piece_type()
666         &&  type_of(move) == NORMAL)
667     {
668         Square to = to_sq(move);
669         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
670     }
671
672     // Step 6. Razoring (is omitted in PV nodes)
673     if (   !PvNode
674         &&  depth < RazorDepth
675         && !inCheck
676         &&  refinedValue + razor_margin(depth) < beta
677         &&  ttMove == MOVE_NONE
678         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
679         && !pos.pawn_on_7th(pos.side_to_move()))
680     {
681         Value rbeta = beta - razor_margin(depth);
682         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
683         if (v < rbeta)
684             // Logically we should return (v + razor_margin(depth)), but
685             // surprisingly this did slightly weaker in tests.
686             return v;
687     }
688
689     // Step 7. Static null move pruning (is omitted in PV nodes)
690     // We're betting that the opponent doesn't have a move that will reduce
691     // the score by more than futility_margin(depth) if we do a null move.
692     if (   !PvNode
693         && !ss->skipNullMove
694         &&  depth < RazorDepth
695         && !inCheck
696         &&  refinedValue - futility_margin(depth, 0) >= beta
697         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
698         &&  pos.non_pawn_material(pos.side_to_move()))
699         return refinedValue - futility_margin(depth, 0);
700
701     // Step 8. Null move search with verification search (is omitted in PV nodes)
702     if (   !PvNode
703         && !ss->skipNullMove
704         &&  depth > ONE_PLY
705         && !inCheck
706         &&  refinedValue >= beta
707         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
708         &&  pos.non_pawn_material(pos.side_to_move()))
709     {
710         ss->currentMove = MOVE_NULL;
711
712         // Null move dynamic reduction based on depth
713         Depth R = 3 * ONE_PLY + depth / 4;
714
715         // Null move dynamic reduction based on value
716         if (refinedValue - PawnValueMidgame > beta)
717             R += ONE_PLY;
718
719         pos.do_null_move<true>(st);
720         (ss+1)->skipNullMove = true;
721         nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
722                                       : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
723         (ss+1)->skipNullMove = false;
724         pos.do_null_move<false>(st);
725
726         if (nullValue >= beta)
727         {
728             // Do not return unproven mate scores
729             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
730                 nullValue = beta;
731
732             if (depth < 6 * ONE_PLY)
733                 return nullValue;
734
735             // Do verification search at high depths
736             ss->skipNullMove = true;
737             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
738             ss->skipNullMove = false;
739
740             if (v >= beta)
741                 return nullValue;
742         }
743         else
744         {
745             // The null move failed low, which means that we may be faced with
746             // some kind of threat. If the previous move was reduced, check if
747             // the move that refuted the null move was somehow connected to the
748             // move which was reduced. If a connection is found, return a fail
749             // low score (which will cause the reduced move to fail high in the
750             // parent node, which will trigger a re-search with full depth).
751             threatMove = (ss+1)->currentMove;
752
753             if (   depth < ThreatDepth
754                 && (ss-1)->reduction
755                 && threatMove != MOVE_NONE
756                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
757                 return beta - 1;
758         }
759     }
760
761     // Step 9. ProbCut (is omitted in PV nodes)
762     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
763     // and a reduced search returns a value much above beta, we can (almost) safely
764     // prune the previous move.
765     if (   !PvNode
766         &&  depth >= RazorDepth + ONE_PLY
767         && !inCheck
768         && !ss->skipNullMove
769         &&  excludedMove == MOVE_NONE
770         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
771     {
772         Value rbeta = beta + 200;
773         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
774
775         assert(rdepth >= ONE_PLY);
776         assert((ss-1)->currentMove != MOVE_NONE);
777         assert((ss-1)->currentMove != MOVE_NULL);
778
779         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
780         CheckInfo ci(pos);
781
782         while ((move = mp.next_move()) != MOVE_NONE)
783             if (pos.pl_move_is_legal(move, ci.pinned))
784             {
785                 ss->currentMove = move;
786                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
787                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
788                 pos.undo_move(move);
789                 if (value >= rbeta)
790                     return value;
791             }
792     }
793
794     // Step 10. Internal iterative deepening
795     if (   depth >= IIDDepth[PvNode]
796         && ttMove == MOVE_NONE
797         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
798     {
799         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
800
801         ss->skipNullMove = true;
802         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
803         ss->skipNullMove = false;
804
805         tte = TT.probe(posKey);
806         ttMove = tte ? tte->move() : MOVE_NONE;
807     }
808
809 split_point_start: // At split points actual search starts from here
810
811     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
812     CheckInfo ci(pos);
813     futilityBase = ss->eval + ss->evalMargin;
814     singularExtensionNode =   !RootNode
815                            && !SpNode
816                            &&  depth >= SingularExtensionDepth[PvNode]
817                            &&  ttMove != MOVE_NONE
818                            && !excludedMove // Recursive singular search is not allowed
819                            && (tte->type() & BOUND_LOWER)
820                            &&  tte->depth() >= depth - 3 * ONE_PLY;
821
822     // Step 11. Loop through moves
823     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
824     while (    bestValue < beta
825            && (move = mp.next_move()) != MOVE_NONE
826            && !thisThread->cutoff_occurred()
827            && !Signals.stop)
828     {
829       assert(is_ok(move));
830
831       if (move == excludedMove)
832           continue;
833
834       // At root obey the "searchmoves" option and skip moves not listed in Root
835       // Move List, as a consequence any illegal move is also skipped. In MultiPV
836       // mode we also skip PV moves which have been already searched.
837       if (RootNode && !count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
838           continue;
839
840       // At PV and SpNode nodes we want all moves to be legal since the beginning
841       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
842           continue;
843
844       if (SpNode)
845       {
846           moveCount = ++sp->moveCount;
847           lock_release(sp->lock);
848       }
849       else
850           moveCount++;
851
852       if (RootNode)
853       {
854           Signals.firstRootMove = (moveCount == 1);
855
856           if (thisThread == Threads.main_thread() && SearchTime.elapsed() > 2000)
857               cout << "info depth " << depth / ONE_PLY
858                    << " currmove " << move_to_uci(move, Chess960)
859                    << " currmovenumber " << moveCount + PVIdx << endl;
860       }
861
862       isPvMove = (PvNode && moveCount <= 1);
863       captureOrPromotion = pos.is_capture_or_promotion(move);
864       givesCheck = pos.move_gives_check(move, ci);
865       dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
866       ext = DEPTH_ZERO;
867
868       // Step 12. Extend checks and, in PV nodes, also dangerous moves
869       if (PvNode && dangerous)
870           ext = ONE_PLY;
871
872       else if (givesCheck && pos.see_sign(move) >= 0)
873           ext = ONE_PLY / 2;
874
875       // Singular extension search. If all moves but one fail low on a search of
876       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
877       // is singular and should be extended. To verify this we do a reduced search
878       // on all the other moves but the ttMove, if result is lower than ttValue minus
879       // a margin then we extend ttMove.
880       if (    singularExtensionNode
881           && !ext
882           &&  move == ttMove
883           &&  pos.pl_move_is_legal(move, ci.pinned)
884           &&  abs(ttValue) < VALUE_KNOWN_WIN)
885       {
886           Value rBeta = ttValue - int(depth);
887           ss->excludedMove = move;
888           ss->skipNullMove = true;
889           value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
890           ss->skipNullMove = false;
891           ss->excludedMove = MOVE_NONE;
892
893           if (value < rBeta)
894               ext = ONE_PLY;
895       }
896
897       // Update current move (this must be done after singular extension search)
898       newDepth = depth - ONE_PLY + ext;
899
900       // Step 13. Futility pruning (is omitted in PV nodes)
901       if (   !PvNode
902           && !captureOrPromotion
903           && !inCheck
904           && !dangerous
905           &&  move != ttMove
906           && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
907       {
908           // Move count based pruning
909           if (   moveCount >= futility_move_count(depth)
910               && (!threatMove || !connected_threat(pos, move, threatMove)))
911           {
912               if (SpNode)
913                   lock_grab(sp->lock);
914
915               continue;
916           }
917
918           // Value based pruning
919           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
920           // but fixing this made program slightly weaker.
921           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
922           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
923                          + H.gain(pos.piece_moved(move), to_sq(move));
924
925           if (futilityValue < beta)
926           {
927               if (SpNode)
928                   lock_grab(sp->lock);
929
930               continue;
931           }
932
933           // Prune moves with negative SEE at low depths
934           if (   predictedDepth < 2 * ONE_PLY
935               && pos.see_sign(move) < 0)
936           {
937               if (SpNode)
938                   lock_grab(sp->lock);
939
940               continue;
941           }
942       }
943
944       // Check for legality only before to do the move
945       if (!pos.pl_move_is_legal(move, ci.pinned))
946       {
947           moveCount--;
948           continue;
949       }
950
951       ss->currentMove = move;
952       if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
953           movesSearched[playedMoveCount++] = move;
954
955       // Step 14. Make the move
956       pos.do_move(move, st, ci, givesCheck);
957
958       // Step 15. Reduced depth search (LMR). If the move fails high will be
959       // re-searched at full depth.
960       if (    depth > 3 * ONE_PLY
961           && !isPvMove
962           && !captureOrPromotion
963           && !dangerous
964           &&  ss->killers[0] != move
965           &&  ss->killers[1] != move)
966       {
967           ss->reduction = reduction<PvNode>(depth, moveCount);
968           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
969           alpha = SpNode ? sp->alpha : alpha;
970
971           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
972
973           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
974           ss->reduction = DEPTH_ZERO;
975       }
976       else
977           doFullDepthSearch = !isPvMove;
978
979       // Step 16. Full depth search, when LMR is skipped or fails high
980       if (doFullDepthSearch)
981       {
982           alpha = SpNode ? sp->alpha : alpha;
983           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
984                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
985       }
986
987       // Only for PV nodes do a full PV search on the first move or after a fail
988       // high, in the latter case search only if value < beta, otherwise let the
989       // parent node to fail low with value <= alpha and to try another move.
990       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
991           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
992                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
993
994       // Step 17. Undo move
995       pos.undo_move(move);
996
997       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
998
999       // Step 18. Check for new best move
1000       if (SpNode)
1001       {
1002           lock_grab(sp->lock);
1003           bestValue = sp->bestValue;
1004           alpha = sp->alpha;
1005       }
1006
1007       // Finished searching the move. If Signals.stop is true, the search
1008       // was aborted because the user interrupted the search or because we
1009       // ran out of time. In this case, the return value of the search cannot
1010       // be trusted, and we don't update the best move and/or PV.
1011       if (RootNode && !Signals.stop)
1012       {
1013           RootMove& rm = *find(RootMoves.begin(), RootMoves.end(), move);
1014
1015           // PV move or new best move ?
1016           if (isPvMove || value > alpha)
1017           {
1018               rm.score = value;
1019               rm.extract_pv_from_tt(pos);
1020
1021               // We record how often the best move has been changed in each
1022               // iteration. This information is used for time management: When
1023               // the best move changes frequently, we allocate some more time.
1024               if (!isPvMove && MultiPV == 1)
1025                   BestMoveChanges++;
1026           }
1027           else
1028               // All other moves but the PV are set to the lowest value, this
1029               // is not a problem when sorting becuase sort is stable and move
1030               // position in the list is preserved, just the PV is pushed up.
1031               rm.score = -VALUE_INFINITE;
1032
1033       }
1034
1035       if (value > bestValue)
1036       {
1037           bestValue = value;
1038           bestMove = move;
1039
1040           if (   PvNode
1041               && value > alpha
1042               && value < beta) // We want always alpha < beta
1043               alpha = value;
1044
1045           if (SpNode && !thisThread->cutoff_occurred())
1046           {
1047               sp->bestValue = value;
1048               sp->bestMove = move;
1049               sp->alpha = alpha;
1050
1051               if (value >= beta)
1052                   sp->cutoff = true;
1053           }
1054       }
1055
1056       // Step 19. Check for split
1057       if (   !SpNode
1058           &&  depth >= Threads.min_split_depth()
1059           &&  bestValue < beta
1060           &&  Threads.available_slave_exists(thisThread)
1061           && !Signals.stop
1062           && !thisThread->cutoff_occurred())
1063           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1064                                                depth, threatMove, moveCount, &mp, NT);
1065     }
1066
1067     // Step 20. Check for mate and stalemate
1068     // All legal moves have been searched and if there are no legal moves, it
1069     // must be mate or stalemate. Note that we can have a false positive in
1070     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1071     // harmless because return value is discarded anyhow in the parent nodes.
1072     // If we are in a singular extension search then return a fail low score.
1073     if (!moveCount)
1074         return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1075
1076     // If we have pruned all the moves without searching return a fail-low score
1077     if (bestValue == -VALUE_INFINITE)
1078     {
1079         assert(!playedMoveCount);
1080
1081         bestValue = oldAlpha;
1082     }
1083
1084     // Step 21. Update tables
1085     // Update transposition table entry, killers and history
1086     if (!SpNode && !Signals.stop && !thisThread->cutoff_occurred())
1087     {
1088         move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1089         bt   = bestValue <= oldAlpha ? BOUND_UPPER
1090              : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1091
1092         TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1093
1094         // Update killers and history for non capture cut-off moves
1095         if (    bestValue >= beta
1096             && !pos.is_capture_or_promotion(move)
1097             && !inCheck)
1098         {
1099             if (move != ss->killers[0])
1100             {
1101                 ss->killers[1] = ss->killers[0];
1102                 ss->killers[0] = move;
1103             }
1104
1105             // Increase history value of the cut-off move
1106             Value bonus = Value(int(depth) * int(depth));
1107             H.add(pos.piece_moved(move), to_sq(move), bonus);
1108
1109             // Decrease history of all the other played non-capture moves
1110             for (int i = 0; i < playedMoveCount - 1; i++)
1111             {
1112                 Move m = movesSearched[i];
1113                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1114             }
1115         }
1116     }
1117
1118     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1119
1120     return bestValue;
1121   }
1122
1123
1124   // qsearch() is the quiescence search function, which is called by the main
1125   // search function when the remaining depth is zero (or, to be more precise,
1126   // less than ONE_PLY).
1127
1128   template <NodeType NT>
1129   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1130
1131     const bool PvNode = (NT == PV);
1132
1133     assert(NT == PV || NT == NonPV);
1134     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1135     assert((alpha == beta - 1) || PvNode);
1136     assert(depth <= DEPTH_ZERO);
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           &&  type_of(move) != PROMOTION
1229           && !pos.is_passed_pawn_push(move))
1230       {
1231           futilityValue =  futilityBase
1232                          + PieceValueEndgame[pos.piece_on(to_sq(move))]
1233                          + (type_of(move) == ENPASSANT ? 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           &&  type_of(move) != PROMOTION
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 (!more_than_one(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_lsb(&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) && (between_bb(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         && (between_bb(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         && (between_bb(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   // When playing with strength handicap choose best move among the MultiPV set
1514   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1515
1516   Move do_skill_level() {
1517
1518     assert(MultiPV > 1);
1519
1520     static RKISS rk;
1521
1522     // PRNG sequence should be not deterministic
1523     for (int i = Time::current_time().msec() % 50; i > 0; i--)
1524         rk.rand<unsigned>();
1525
1526     // RootMoves are already sorted by score in descending order
1527     size_t size = std::min(MultiPV, RootMoves.size());
1528     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMidgame);
1529     int weakness = 120 - 2 * SkillLevel;
1530     int max_s = -VALUE_INFINITE;
1531     Move best = MOVE_NONE;
1532
1533     // Choose best move. For each move score we add two terms both dependent on
1534     // weakness, one deterministic and bigger for weaker moves, and one random,
1535     // then we choose the move with the resulting highest score.
1536     for (size_t i = 0; i < size; i++)
1537     {
1538         int s = RootMoves[i].score;
1539
1540         // Don't allow crazy blunders even at very low skills
1541         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1542             break;
1543
1544         // This is our magic formula
1545         s += (  weakness * int(RootMoves[0].score - s)
1546               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1547
1548         if (s > max_s)
1549         {
1550             max_s = s;
1551             best = RootMoves[i].pv[0];
1552         }
1553     }
1554     return best;
1555   }
1556
1557
1558   // uci_pv() formats PV information according to UCI protocol. UCI requires
1559   // to send all the PV lines also if are still to be searched and so refer to
1560   // the previous search score.
1561
1562   string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1563
1564     std::stringstream s;
1565     int t = SearchTime.elapsed();
1566     int selDepth = 0;
1567
1568     for (int i = 0; i < Threads.size(); i++)
1569         if (Threads[i].maxPly > selDepth)
1570             selDepth = Threads[i].maxPly;
1571
1572     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1573     {
1574         bool updated = (i <= PVIdx);
1575
1576         if (depth == 1 && !updated)
1577             continue;
1578
1579         int d = (updated ? depth : depth - 1);
1580         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1581
1582         if (s.rdbuf()->in_avail())
1583             s << "\n";
1584
1585         s << "info depth " << d
1586           << " seldepth " << selDepth
1587           << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1588           << " nodes " << pos.nodes_searched()
1589           << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1590           << " time " << t
1591           << " multipv " << i + 1
1592           << " pv";
1593
1594         for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1595             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1596     }
1597
1598     return s.str();
1599   }
1600
1601 } // namespace
1602
1603
1604 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1605 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1606 /// allow to always have a ponder move even when we fail high at root, and a
1607 /// long PV to print that is important for position analysis.
1608
1609 void RootMove::extract_pv_from_tt(Position& pos) {
1610
1611   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1612   TTEntry* tte;
1613   int ply = 1;
1614   Move m = pv[0];
1615
1616   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1617
1618   pv.clear();
1619   pv.push_back(m);
1620   pos.do_move(m, *st++);
1621
1622   while (   (tte = TT.probe(pos.key())) != NULL
1623          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1624          && pos.is_pseudo_legal(m)
1625          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1626          && ply < MAX_PLY
1627          && (!pos.is_draw<false>() || ply < 2))
1628   {
1629       pv.push_back(m);
1630       pos.do_move(m, *st++);
1631       ply++;
1632   }
1633   pv.push_back(MOVE_NONE);
1634
1635   do pos.undo_move(pv[--ply]); while (ply);
1636 }
1637
1638
1639 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1640 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1641 /// first, even if the old TT entries have been overwritten.
1642
1643 void RootMove::insert_pv_in_tt(Position& pos) {
1644
1645   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1646   TTEntry* tte;
1647   Key k;
1648   Value v, m = VALUE_NONE;
1649   int ply = 0;
1650
1651   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1652
1653   do {
1654       k = pos.key();
1655       tte = TT.probe(k);
1656
1657       // Don't overwrite existing correct entries
1658       if (!tte || tte->move() != pv[ply])
1659       {
1660           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1661           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1662       }
1663       pos.do_move(pv[ply], *st++);
1664
1665   } while (pv[++ply] != MOVE_NONE);
1666
1667   do pos.undo_move(pv[--ply]); while (ply);
1668 }
1669
1670
1671 /// Thread::idle_loop() is where the thread is parked when it has no work to do.
1672 /// The parameter 'master_sp', if non-NULL, is a pointer to an active SplitPoint
1673 /// object for which the thread is the master.
1674
1675 void Thread::idle_loop(SplitPoint* sp_master) {
1676
1677   // If this thread is the master of a split point and all slaves have
1678   // finished their work at this split point, return from the idle loop.
1679   while (!sp_master || sp_master->slavesMask)
1680   {
1681       // If we are not searching, wait for a condition to be signaled
1682       // instead of wasting CPU time polling for work.
1683       while (   do_sleep
1684              || do_exit
1685              || (!is_searching && Threads.use_sleeping_threads()))
1686       {
1687           if (do_exit)
1688           {
1689               assert(!sp_master);
1690               return;
1691           }
1692
1693           // Grab the lock to avoid races with Thread::wake_up()
1694           lock_grab(sleepLock);
1695
1696           // If we are master and all slaves have finished don't go to sleep
1697           if (sp_master && !sp_master->slavesMask)
1698           {
1699               lock_release(sleepLock);
1700               break;
1701           }
1702
1703           // Do sleep after retesting sleep conditions under lock protection, in
1704           // particular we need to avoid a deadlock in case a master thread has,
1705           // in the meanwhile, allocated us and sent the wake_up() call before we
1706           // had the chance to grab the lock.
1707           if (do_sleep || !is_searching)
1708               cond_wait(sleepCond, sleepLock);
1709
1710           lock_release(sleepLock);
1711       }
1712
1713       // If this thread has been assigned work, launch a search
1714       if (is_searching)
1715       {
1716           assert(!do_sleep && !do_exit);
1717
1718           lock_grab(Threads.splitLock);
1719
1720           assert(is_searching);
1721           SplitPoint* sp = curSplitPoint;
1722
1723           lock_release(Threads.splitLock);
1724
1725           Stack ss[MAX_PLY_PLUS_2];
1726           Position pos(*sp->pos, this);
1727
1728           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1729           (ss+1)->sp = sp;
1730
1731           lock_grab(sp->lock);
1732
1733           if (sp->nodeType == Root)
1734               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1735           else if (sp->nodeType == PV)
1736               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1737           else if (sp->nodeType == NonPV)
1738               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1739           else
1740               assert(false);
1741
1742           assert(is_searching);
1743
1744           is_searching = false;
1745           sp->slavesMask &= ~(1ULL << idx);
1746           sp->nodes += pos.nodes_searched();
1747
1748           // Wake up master thread so to allow it to return from the idle loop in
1749           // case we are the last slave of the split point.
1750           if (    Threads.use_sleeping_threads()
1751               &&  this != sp->master
1752               && !sp->master->is_searching)
1753               sp->master->wake_up();
1754
1755           // After releasing the lock we cannot access anymore any SplitPoint
1756           // related data in a safe way becuase it could have been released under
1757           // our feet by the sp master. Also accessing other Thread objects is
1758           // unsafe because if we are exiting there is a chance are already freed.
1759           lock_release(sp->lock);
1760       }
1761   }
1762 }
1763
1764
1765 /// check_time() is called by the timer thread when the timer triggers. It is
1766 /// used to print debug info and, more important, to detect when we are out of
1767 /// available time and so stop the search.
1768
1769 void check_time() {
1770
1771   static Time lastInfoTime = Time::current_time();
1772
1773   if (lastInfoTime.elapsed() >= 1000)
1774   {
1775       lastInfoTime.restart();
1776       dbg_print();
1777   }
1778
1779   if (Limits.ponder)
1780       return;
1781
1782   int e = SearchTime.elapsed();
1783   bool stillAtFirstMove =    Signals.firstRootMove
1784                          && !Signals.failedLowAtRoot
1785                          &&  e > TimeMgr.available_time();
1786
1787   bool noMoreTime =   e > TimeMgr.maximum_time() - 2 * TimerResolution
1788                    || stillAtFirstMove;
1789
1790   if (   (Limits.use_time_management() && noMoreTime)
1791       || (Limits.movetime && e >= Limits.movetime))
1792       Signals.stop = true;
1793 }