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