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