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