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