]> git.sesse.net Git - stockfish/blob - src/search.cpp
982f2a2cd279e26273476d955d75e2305857eef2
[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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cmath>
27 #include <cstring>
28 #include <fstream>
29 #include <iostream>
30 #include <sstream>
31 #include <vector>
32
33 #include "book.h"
34 #include "evaluate.h"
35 #include "history.h"
36 #include "misc.h"
37 #include "move.h"
38 #include "movegen.h"
39 #include "movepick.h"
40 #include "lock.h"
41 #include "search.h"
42 #include "timeman.h"
43 #include "thread.h"
44 #include "tt.h"
45 #include "ucioption.h"
46
47 using std::cout;
48 using std::endl;
49
50 ////
51 //// Local definitions
52 ////
53
54 namespace {
55
56   // Types
57   enum NodeType { NonPV, PV };
58
59   // Set to true to force running with one thread.
60   // Used for debugging SMP code.
61   const bool FakeSplit = false;
62
63   // Fast lookup table of sliding pieces indexed by Piece
64   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
65   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
66
67   // ThreadsManager class is used to handle all the threads related stuff in search,
68   // init, starting, parking and, the most important, launching a slave thread at a
69   // split point are what this class does. All the access to shared thread data is
70   // done through this class, so that we avoid using global variables instead.
71
72   class ThreadsManager {
73     /* As long as the single ThreadsManager object is defined as a global we don't
74        need to explicitly initialize to zero its data members because variables with
75        static storage duration are automatically set to zero before enter main()
76     */
77   public:
78     void init_threads();
79     void exit_threads();
80
81     int min_split_depth() const { return minimumSplitDepth; }
82     int active_threads() const { return activeThreads; }
83     void set_active_threads(int cnt) { activeThreads = cnt; }
84
85     void read_uci_options();
86     bool available_thread_exists(int master) const;
87     bool thread_is_available(int slave, int master) const;
88     bool cutoff_at_splitpoint(int threadID) const;
89     void wake_sleeping_thread(int threadID);
90     void idle_loop(int threadID, SplitPoint* sp);
91
92     template <bool Fake>
93     void split(Position& pos, SearchStack* ss, int ply, Value* alpha, const Value beta, Value* bestValue,
94                Depth depth, Move threatMove, bool mateThreat, int moveCount, MovePicker* mp, bool pvNode);
95
96   private:
97     Depth minimumSplitDepth;
98     int maxThreadsPerSplitPoint;
99     bool useSleepingThreads;
100     int activeThreads;
101     volatile bool allThreadsShouldExit;
102     Thread threads[MAX_THREADS];
103     Lock mpLock, sleepLock[MAX_THREADS];
104     WaitCondition sleepCond[MAX_THREADS];
105   };
106
107
108   // RootMove struct is used for moves at the root at the tree. For each root
109   // move, we store two scores, a node count, and a PV (really a refutation
110   // in the case of moves which fail low). Value pv_score is normally set at
111   // -VALUE_INFINITE for all non-pv moves, while non_pv_score is computed
112   // according to the order in which moves are returned by MovePicker.
113
114   struct RootMove {
115
116     RootMove();
117     RootMove(const RootMove& rm) { *this = rm; }
118     RootMove& operator=(const RootMove& rm);
119
120     // RootMove::operator<() is the comparison function used when
121     // sorting the moves. A move m1 is considered to be better
122     // than a move m2 if it has an higher pv_score, or if it has
123     // equal pv_score but m1 has the higher non_pv_score. In this
124     // way we are guaranteed that PV moves are always sorted as first.
125     bool operator<(const RootMove& m) const {
126       return pv_score != m.pv_score ? pv_score < m.pv_score
127                                     : non_pv_score < m.non_pv_score;
128     }
129
130     void extract_pv_from_tt(Position& pos);
131     void insert_pv_in_tt(Position& pos);
132     std::string pv_info_to_uci(Position& pos, int depth, Value alpha, Value beta, int pvLine);
133
134     int64_t nodes;
135     Value pv_score;
136     Value non_pv_score;
137     Move pv[PLY_MAX_PLUS_2];
138   };
139
140
141   // RootMoveList struct is essentially a std::vector<> of RootMove objects,
142   // with an handful of methods above the standard ones.
143
144   struct RootMoveList : public std::vector<RootMove> {
145
146     typedef std::vector<RootMove> Base;
147
148     void init(Position& pos, Move searchMoves[]);
149     void sort() { insertion_sort<RootMove, Base::iterator>(begin(), end()); }
150     void sort_multipv(int n) { insertion_sort<RootMove, Base::iterator>(begin(), begin() + n); }
151
152     int bestMoveChanges;
153   };
154
155
156   // When formatting a move for std::cout we must know if we are in Chess960
157   // or not. To keep using the handy operator<<() on the move the trick is to
158   // embed this flag in the stream itself. Function-like named enum set960 is
159   // used as a custom manipulator and the stream internal general-purpose array,
160   // accessed through ios_base::iword(), is used to pass the flag to the move's
161   // operator<<() that will use it to properly format castling moves.
162   enum set960 {};
163
164   std::ostream& operator<< (std::ostream& os, const set960& f) {
165
166     os.iword(0) = int(f);
167     return os;
168   }
169
170
171   // Overload operator << for moves to make it easier to print moves in
172   // coordinate notation compatible with UCI protocol.
173   std::ostream& operator<<(std::ostream& os, Move m) {
174
175     bool chess960 = (os.iword(0) != 0); // See set960()
176     return os << move_to_uci(m, chess960);
177   }
178
179
180   /// Adjustments
181
182   // Step 6. Razoring
183
184   // Maximum depth for razoring
185   const Depth RazorDepth = 4 * ONE_PLY;
186
187   // Dynamic razoring margin based on depth
188   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
189
190   // Maximum depth for use of dynamic threat detection when null move fails low
191   const Depth ThreatDepth = 5 * ONE_PLY;
192
193   // Step 9. Internal iterative deepening
194
195   // Minimum depth for use of internal iterative deepening
196   const Depth IIDDepth[2] = { 8 * ONE_PLY /* non-PV */, 5 * ONE_PLY /* PV */};
197
198   // At Non-PV nodes we do an internal iterative deepening search
199   // when the static evaluation is bigger then beta - IIDMargin.
200   const Value IIDMargin = Value(0x100);
201
202   // Step 11. Decide the new search depth
203
204   // Extensions. Configurable UCI options
205   // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
206   Depth CheckExtension[2], PawnPushTo7thExtension[2], PassedPawnExtension[2];
207   Depth PawnEndgameExtension[2], MateThreatExtension[2];
208
209   // Minimum depth for use of singular extension
210   const Depth SingularExtensionDepth[2] = { 8 * ONE_PLY /* non-PV */, 6 * ONE_PLY /* PV */};
211
212   // Step 12. Futility pruning
213
214   // Futility margin for quiescence search
215   const Value FutilityMarginQS = Value(0x80);
216
217   // Futility lookup tables (initialized at startup) and their getter functions
218   Value FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
219   int FutilityMoveCountArray[32]; // [depth]
220
221   inline Value futility_margin(Depth d, int mn) { return d < 7 * ONE_PLY ? FutilityMarginsMatrix[Max(d, 1)][Min(mn, 63)] : 2 * VALUE_INFINITE; }
222   inline int futility_move_count(Depth d) { return d < 16 * ONE_PLY ? FutilityMoveCountArray[d] : 512; }
223
224   // Step 14. Reduced search
225
226   // Reduction lookup tables (initialized at startup) and their getter functions
227   int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
228
229   template <NodeType PV>
230   inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / 2, 63)][Min(mn, 63)]; }
231
232   // Easy move margin. An easy move candidate must be at least this much
233   // better than the second best move.
234   const Value EasyMoveMargin = Value(0x200);
235
236
237   /// Namespace variables
238
239   // Book object
240   Book OpeningBook;
241
242   // Root move list
243   RootMoveList Rml;
244
245   // MultiPV mode
246   int MultiPV;
247
248   // Time management variables
249   int SearchStartTime, MaxNodes, MaxDepth, ExactMaxTime;
250   bool UseTimeManagement, InfiniteSearch, Pondering, StopOnPonderhit;
251   bool FirstRootMove, StopRequest, QuitRequest, AspirationFailLow;
252   TimeManager TimeMgr;
253
254   // Log file
255   bool UseLogFile;
256   std::ofstream LogFile;
257
258   // Multi-threads manager object
259   ThreadsManager ThreadsMgr;
260
261   // Node counters, used only by thread[0] but try to keep in different cache
262   // lines (64 bytes each) from the heavy multi-thread read accessed variables.
263   bool SendSearchedNodes;
264   int NodesSincePoll;
265   int NodesBetweenPolls = 30000;
266
267   // History table
268   History H;
269
270   /// Local functions
271
272   Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove);
273
274   template <NodeType PvNode, bool SpNode, bool Root>
275   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply);
276
277   template <NodeType PvNode>
278   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply);
279
280   template <NodeType PvNode>
281   inline Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
282
283       return depth < ONE_PLY ? qsearch<PvNode>(pos, ss, alpha, beta, DEPTH_ZERO, ply)
284                              : search<PvNode, false, false>(pos, ss, alpha, beta, depth, ply);
285   }
286
287   template <NodeType PvNode>
288   Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool mateThreat, bool* dangerous);
289
290   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
291   bool connected_moves(const Position& pos, Move m1, Move m2);
292   bool value_is_mate(Value value);
293   Value value_to_tt(Value v, int ply);
294   Value value_from_tt(Value v, int ply);
295   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
296   bool connected_threat(const Position& pos, Move m, Move threat);
297   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
298   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
299   void update_killers(Move m, Move killers[]);
300   void update_gains(const Position& pos, Move move, Value before, Value after);
301
302   int current_search_time();
303   std::string value_to_uci(Value v);
304   std::string speed_to_uci(int64_t nodes);
305   void poll(const Position& pos);
306   void wait_for_stop_or_ponderhit();
307
308 #if !defined(_MSC_VER)
309   void* init_thread(void* threadID);
310 #else
311   DWORD WINAPI init_thread(LPVOID threadID);
312 #endif
313
314
315   // MovePickerExt is an extended MovePicker used to choose at compile time
316   // the proper move source according to the type of node.
317   template<bool SpNode, bool Root> struct MovePickerExt;
318
319   // In Root nodes use RootMoveList Rml as source. Score and sort the root moves
320   // before to search them.
321   template<> struct MovePickerExt<false, true> : public MovePicker {
322
323     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
324                  : MovePicker(p, ttm, d, h, ss, b), firstCall(true) {
325       Move move;
326       Value score = VALUE_ZERO;
327
328       // Score root moves using the standard way used in main search, the moves
329       // are scored according to the order in which they are returned by MovePicker.
330       // This is the second order score that is used to compare the moves when
331       // the first order pv scores of both moves are equal.
332       while ((move = MovePicker::get_next_move()) != MOVE_NONE)
333           for (rm = Rml.begin(); rm != Rml.end(); ++rm)
334               if (rm->pv[0] == move)
335               {
336                   rm->non_pv_score = score--;
337                   break;
338               }
339
340       Rml.sort();
341       rm = Rml.begin();
342     }
343
344     Move get_next_move() {
345
346       if (!firstCall)
347           ++rm;
348       else
349           firstCall = false;
350
351       return rm != Rml.end() ? rm->pv[0] : MOVE_NONE;
352     }
353
354     RootMoveList::iterator rm;
355     bool firstCall;
356   };
357
358   // In SpNodes use split point's shared MovePicker object as move source
359   template<> struct MovePickerExt<true, false> : public MovePicker {
360
361     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h,
362                   SearchStack* ss, Value b) : MovePicker(p, ttm, d, h, ss, b),
363                   mp(ss->sp->mp) {}
364
365     Move get_next_move() { return mp->get_next_move(); }
366
367     RootMoveList::iterator rm; // Dummy, needed to compile
368     MovePicker* mp;
369   };
370
371   // Default case, create and use a MovePicker object as source
372   template<> struct MovePickerExt<false, false> : public MovePicker {
373
374     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h,
375                   SearchStack* ss, Value b) : MovePicker(p, ttm, d, h, ss, b) {}
376
377     RootMoveList::iterator rm; // Dummy, needed to compile
378   };
379
380 } // namespace
381
382
383 ////
384 //// Functions
385 ////
386
387 /// init_threads(), exit_threads() and nodes_searched() are helpers to
388 /// give accessibility to some TM methods from outside of current file.
389
390 void init_threads() { ThreadsMgr.init_threads(); }
391 void exit_threads() { ThreadsMgr.exit_threads(); }
392
393
394 /// init_search() is called during startup. It initializes various lookup tables
395
396 void init_search() {
397
398   int d;  // depth (ONE_PLY == 2)
399   int hd; // half depth (ONE_PLY == 1)
400   int mc; // moveCount
401
402   // Init reductions array
403   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
404   {
405       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
406       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
407       ReductionMatrix[PV][hd][mc]    = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
408       ReductionMatrix[NonPV][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
409   }
410
411   // Init futility margins array
412   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
413       FutilityMarginsMatrix[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
414
415   // Init futility move count array
416   for (d = 0; d < 32; d++)
417       FutilityMoveCountArray[d] = int(3.001 + 0.25 * pow(d, 2.0));
418 }
419
420
421 /// perft() is our utility to verify move generation is bug free. All the legal
422 /// moves up to given depth are generated and counted and the sum returned.
423
424 int64_t perft(Position& pos, Depth depth)
425 {
426     MoveStack mlist[MOVES_MAX];
427     StateInfo st;
428     Move m;
429     int64_t sum = 0;
430
431     // Generate all legal moves
432     MoveStack* last = generate<MV_LEGAL>(pos, mlist);
433
434     // If we are at the last ply we don't need to do and undo
435     // the moves, just to count them.
436     if (depth <= ONE_PLY)
437         return int(last - mlist);
438
439     // Loop through all legal moves
440     CheckInfo ci(pos);
441     for (MoveStack* cur = mlist; cur != last; cur++)
442     {
443         m = cur->move;
444         pos.do_move(m, st, ci, pos.move_is_check(m, ci));
445         sum += perft(pos, depth - ONE_PLY);
446         pos.undo_move(m);
447     }
448     return sum;
449 }
450
451
452 /// think() is the external interface to Stockfish's search, and is called when
453 /// the program receives the UCI 'go' command. It initializes various
454 /// search-related global variables, and calls id_loop(). It returns false
455 /// when a quit command is received during the search.
456
457 bool think(Position& pos, bool infinite, bool ponder, int time[], int increment[],
458            int movesToGo, int maxDepth, int maxNodes, int maxTime, Move searchMoves[]) {
459
460   // Initialize global search variables
461   StopOnPonderhit = StopRequest = QuitRequest = AspirationFailLow = SendSearchedNodes = false;
462   NodesSincePoll = 0;
463   SearchStartTime = get_system_time();
464   ExactMaxTime = maxTime;
465   MaxDepth = maxDepth;
466   MaxNodes = maxNodes;
467   InfiniteSearch = infinite;
468   Pondering = ponder;
469   UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
470
471   // Look for a book move, only during games, not tests
472   if (UseTimeManagement && Options["OwnBook"].value<bool>())
473   {
474       if (Options["Book File"].value<std::string>() != OpeningBook.name())
475           OpeningBook.open(Options["Book File"].value<std::string>());
476
477       Move bookMove = OpeningBook.get_move(pos, Options["Best Book Move"].value<bool>());
478       if (bookMove != MOVE_NONE)
479       {
480           if (Pondering)
481               wait_for_stop_or_ponderhit();
482
483           cout << "bestmove " << bookMove << endl;
484           return !QuitRequest;
485       }
486   }
487
488   // Read UCI option values
489   TT.set_size(Options["Hash"].value<int>());
490   if (Options["Clear Hash"].value<bool>())
491   {
492       Options["Clear Hash"].set_value("false");
493       TT.clear();
494   }
495
496   CheckExtension[1]         = Options["Check Extension (PV nodes)"].value<Depth>();
497   CheckExtension[0]         = Options["Check Extension (non-PV nodes)"].value<Depth>();
498   PawnPushTo7thExtension[1] = Options["Pawn Push to 7th Extension (PV nodes)"].value<Depth>();
499   PawnPushTo7thExtension[0] = Options["Pawn Push to 7th Extension (non-PV nodes)"].value<Depth>();
500   PassedPawnExtension[1]    = Options["Passed Pawn Extension (PV nodes)"].value<Depth>();
501   PassedPawnExtension[0]    = Options["Passed Pawn Extension (non-PV nodes)"].value<Depth>();
502   PawnEndgameExtension[1]   = Options["Pawn Endgame Extension (PV nodes)"].value<Depth>();
503   PawnEndgameExtension[0]   = Options["Pawn Endgame Extension (non-PV nodes)"].value<Depth>();
504   MateThreatExtension[1]    = Options["Mate Threat Extension (PV nodes)"].value<Depth>();
505   MateThreatExtension[0]    = Options["Mate Threat Extension (non-PV nodes)"].value<Depth>();
506   MultiPV                   = Options["MultiPV"].value<int>();
507   UseLogFile                = Options["Use Search Log"].value<bool>();
508
509   read_evaluation_uci_options(pos.side_to_move());
510
511   // Set the number of active threads
512   ThreadsMgr.read_uci_options();
513   init_eval(ThreadsMgr.active_threads());
514
515   // Wake up needed threads
516   for (int i = 1; i < ThreadsMgr.active_threads(); i++)
517       ThreadsMgr.wake_sleeping_thread(i);
518
519   // Set thinking time
520   int myTime = time[pos.side_to_move()];
521   int myIncrement = increment[pos.side_to_move()];
522   if (UseTimeManagement)
523       TimeMgr.init(myTime, myIncrement, movesToGo, pos.startpos_ply_counter());
524
525   // Set best NodesBetweenPolls interval to avoid lagging under
526   // heavy time pressure.
527   if (MaxNodes)
528       NodesBetweenPolls = Min(MaxNodes, 30000);
529   else if (myTime && myTime < 1000)
530       NodesBetweenPolls = 1000;
531   else if (myTime && myTime < 5000)
532       NodesBetweenPolls = 5000;
533   else
534       NodesBetweenPolls = 30000;
535
536   // Write search information to log file
537   if (UseLogFile)
538   {
539       std::string name = Options["Search Log Filename"].value<std::string>();
540       LogFile.open(name.c_str(), std::ios::out | std::ios::app);
541
542       LogFile << "\nSearching: "  << pos.to_fen()
543               << "\ninfinite: "   << infinite
544               << " ponder: "      << ponder
545               << " time: "        << myTime
546               << " increment: "   << myIncrement
547               << " moves to go: " << movesToGo
548               << endl;
549   }
550
551   // We're ready to start thinking. Call the iterative deepening loop function
552   Move ponderMove = MOVE_NONE;
553   Move bestMove = id_loop(pos, searchMoves, &ponderMove);
554
555   // Print final search statistics
556   cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
557
558   if (UseLogFile)
559   {
560       int t = current_search_time();
561
562       LogFile << "Nodes: "          << pos.nodes_searched()
563               << "\nNodes/second: " << (t > 0 ? int(pos.nodes_searched() * 1000 / t) : 0)
564               << "\nBest move: "    << move_to_san(pos, bestMove);
565
566       StateInfo st;
567       pos.do_move(bestMove, st);
568       LogFile << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
569       pos.undo_move(bestMove); // Return from think() with unchanged position
570       LogFile.close();
571   }
572
573   // This makes all the threads to go to sleep
574   ThreadsMgr.set_active_threads(1);
575
576   // If we are pondering or in infinite search, we shouldn't print the
577   // best move before we are told to do so.
578   if (!StopRequest && (Pondering || InfiniteSearch))
579       wait_for_stop_or_ponderhit();
580
581   // Could be MOVE_NONE when searching on a stalemate position
582   cout << "bestmove " << bestMove;
583
584   // UCI protol is not clear on allowing sending an empty ponder move, instead
585   // it is clear that ponder move is optional. So skip it if empty.
586   if (ponderMove != MOVE_NONE)
587       cout << " ponder " << ponderMove;
588
589   cout << endl;
590
591   return !QuitRequest;
592 }
593
594
595 namespace {
596
597   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
598   // with increasing depth until the allocated thinking time has been consumed,
599   // user stops the search, or the maximum search depth is reached.
600
601   Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove) {
602
603     SearchStack ss[PLY_MAX_PLUS_2];
604     Value bestValues[PLY_MAX_PLUS_2];
605     int bestMoveChanges[PLY_MAX_PLUS_2];
606     int depth, aspirationDelta;
607     Value value, alpha, beta;
608     Move bestMove, easyMove;
609
610     // Initialize stuff before a new search
611     memset(ss, 0, 4 * sizeof(SearchStack));
612     TT.new_search();
613     H.clear();
614     *ponderMove = bestMove = easyMove = MOVE_NONE;
615     depth = aspirationDelta = 0;
616     alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
617     ss->currentMove = MOVE_NULL; // Hack to skip update_gains()
618
619     // Moves to search are verified and copied
620     Rml.init(pos, searchMoves);
621
622     // Handle special case of searching on a mate/stalemate position
623     if (Rml.size() == 0)
624     {
625         cout << "info depth 0 score "
626              << value_to_uci(pos.is_check() ? -VALUE_MATE : VALUE_DRAW)
627              << endl;
628
629         return MOVE_NONE;
630     }
631
632     // Iterative deepening loop
633     while (++depth <= PLY_MAX && (!MaxDepth || depth <= MaxDepth) && !StopRequest)
634     {
635         Rml.bestMoveChanges = 0;
636         cout << set960(pos.is_chess960()) << "info depth " << depth << endl;
637
638         // Calculate dynamic aspiration window based on previous iterations
639         if (MultiPV == 1 && depth >= 5 && abs(bestValues[depth - 1]) < VALUE_KNOWN_WIN)
640         {
641             int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
642             int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
643
644             aspirationDelta = Min(Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
645             aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
646
647             alpha = Max(bestValues[depth - 1] - aspirationDelta, -VALUE_INFINITE);
648             beta  = Min(bestValues[depth - 1] + aspirationDelta,  VALUE_INFINITE);
649         }
650
651         // Start with a small aspiration window and, in case of fail high/low,
652         // research with bigger window until not failing high/low anymore.
653         do {
654             // Search starting from ss+1 to allow calling update_gains()
655             value = search<PV, false, true>(pos, ss+1, alpha, beta, depth * ONE_PLY, 0);
656
657             // Write PV back to transposition table in case the relevant entries
658             // have been overwritten during the search.
659             for (int i = 0; i < Min(MultiPV, (int)Rml.size()); i++)
660                 Rml[i].insert_pv_in_tt(pos);
661
662             // Value cannot be trusted. Break out immediately!
663             if (StopRequest)
664                 break;
665
666             assert(value >= alpha);
667
668             // In case of failing high/low increase aspiration window and research,
669             // otherwise exit the fail high/low loop.
670             if (value >= beta)
671             {
672                 beta = Min(beta + aspirationDelta, VALUE_INFINITE);
673                 aspirationDelta += aspirationDelta / 2;
674             }
675             else if (value <= alpha)
676             {
677                 AspirationFailLow = true;
678                 StopOnPonderhit = false;
679
680                 alpha = Max(alpha - aspirationDelta, -VALUE_INFINITE);
681                 aspirationDelta += aspirationDelta / 2;
682             }
683             else
684                 break;
685
686         } while (abs(value) < VALUE_KNOWN_WIN);
687
688         // Collect info about search result
689         bestMove = Rml[0].pv[0];
690         bestValues[depth] = value;
691         bestMoveChanges[depth] = Rml.bestMoveChanges;
692
693         // Send PV line to GUI and to log file
694         for (int i = 0; i < Min(MultiPV, (int)Rml.size()); i++)
695             cout << Rml[i].pv_info_to_uci(pos, depth, alpha, beta, i) << endl;
696
697         if (UseLogFile)
698             LogFile << pretty_pv(pos, depth, value, current_search_time(), Rml[0].pv) << endl;
699
700         // Init easyMove after first iteration or drop if differs from the best move
701         if (depth == 1 && (Rml.size() == 1 || Rml[0].pv_score > Rml[1].pv_score + EasyMoveMargin))
702             easyMove = bestMove;
703         else if (bestMove != easyMove)
704             easyMove = MOVE_NONE;
705
706         if (UseTimeManagement && !StopRequest)
707         {
708             // Time to stop?
709             bool noMoreTime = false;
710
711             // Stop search early when the last two iterations returned a mate score
712             if (   depth >= 5
713                 && abs(bestValues[depth])     >= abs(VALUE_MATE) - 100
714                 && abs(bestValues[depth - 1]) >= abs(VALUE_MATE) - 100)
715                 noMoreTime = true;
716
717             // Stop search early if one move seems to be much better than the
718             // others or if there is only a single legal move. In this latter
719             // case we search up to Iteration 8 anyway to get a proper score.
720             if (   depth >= 7
721                 && easyMove == bestMove
722                 && (   Rml.size() == 1
723                     ||(   Rml[0].nodes > (pos.nodes_searched() * 85) / 100
724                        && current_search_time() > TimeMgr.available_time() / 16)
725                     ||(   Rml[0].nodes > (pos.nodes_searched() * 98) / 100
726                        && current_search_time() > TimeMgr.available_time() / 32)))
727                 noMoreTime = true;
728
729             // Add some extra time if the best move has changed during the last two iterations
730             if (depth > 4 && depth < 50)
731                 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth-1]);
732
733             // Stop search if most of MaxSearchTime is consumed at the end of the
734             // iteration. We probably don't have enough time to search the first
735             // move at the next iteration anyway.
736             if (current_search_time() > (TimeMgr.available_time() * 80) / 128)
737                 noMoreTime = true;
738
739             if (noMoreTime)
740             {
741                 if (Pondering)
742                     StopOnPonderhit = true;
743                 else
744                     break;
745             }
746         }
747     }
748
749     *ponderMove = Rml[0].pv[1];
750     return bestMove;
751   }
752
753
754   // search<>() is the main search function for both PV and non-PV nodes and for
755   // normal and SplitPoint nodes. When called just after a split point the search
756   // is simpler because we have already probed the hash table, done a null move
757   // search, and searched the first move before splitting, we don't have to repeat
758   // all this work again. We also don't need to store anything to the hash table
759   // here: This is taken care of after we return from the split point.
760
761   template <NodeType PvNode, bool SpNode, bool Root>
762   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
763
764     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
765     assert(beta > alpha && beta <= VALUE_INFINITE);
766     assert(PvNode || alpha == beta - 1);
767     assert((Root || ply > 0) && ply < PLY_MAX);
768     assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
769
770     Move movesSearched[MOVES_MAX];
771     int64_t nodes;
772     StateInfo st;
773     const TTEntry *tte;
774     Key posKey;
775     Move ttMove, move, excludedMove, threatMove;
776     Depth ext, newDepth;
777     ValueType vt;
778     Value bestValue, value, oldAlpha;
779     Value refinedValue, nullValue, futilityBase, futilityValueScaled; // Non-PV specific
780     bool isPvMove, isCheck, singularExtensionNode, moveIsCheck, captureOrPromotion, dangerous;
781     bool mateThreat = false;
782     int moveCount = 0, playedMoveCount = 0;
783     int threadID = pos.thread();
784     SplitPoint* sp = NULL;
785
786     refinedValue = bestValue = value = -VALUE_INFINITE;
787     oldAlpha = alpha;
788     isCheck = pos.is_check();
789
790     if (SpNode)
791     {
792         sp = ss->sp;
793         tte = NULL;
794         ttMove = excludedMove = MOVE_NONE;
795         threatMove = sp->threatMove;
796         mateThreat = sp->mateThreat;
797         goto split_point_start;
798     }
799     else if (Root)
800         bestValue = alpha;
801
802     // Step 1. Initialize node and poll. Polling can abort search
803     ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
804     (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
805     (ss+2)->killers[0] = (ss+2)->killers[1] = (ss+2)->mateKiller = MOVE_NONE;
806
807     if (threadID == 0 && ++NodesSincePoll > NodesBetweenPolls)
808     {
809         NodesSincePoll = 0;
810         poll(pos);
811     }
812
813     // Step 2. Check for aborted search and immediate draw
814     if ((   StopRequest
815          || ThreadsMgr.cutoff_at_splitpoint(threadID)
816          || pos.is_draw()
817          || ply >= PLY_MAX - 1) && !Root)
818         return VALUE_DRAW;
819
820     // Step 3. Mate distance pruning
821     alpha = Max(value_mated_in(ply), alpha);
822     beta = Min(value_mate_in(ply+1), beta);
823     if (alpha >= beta)
824         return alpha;
825
826     // Step 4. Transposition table lookup
827     // We don't want the score of a partial search to overwrite a previous full search
828     // TT value, so we use a different position key in case of an excluded move.
829     excludedMove = ss->excludedMove;
830     posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
831
832     tte = TT.retrieve(posKey);
833     ttMove = tte ? tte->move() : MOVE_NONE;
834
835     // At PV nodes we check for exact scores, while at non-PV nodes we check for
836     // and return a fail high/low. Biggest advantage at probing at PV nodes is
837     // to have a smooth experience in analysis mode.
838     if (   !Root
839         && tte
840         && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
841                    : ok_to_use_TT(tte, depth, beta, ply)))
842     {
843         TT.refresh(tte);
844         ss->bestMove = ttMove; // Can be MOVE_NONE
845         return value_from_tt(tte->value(), ply);
846     }
847
848     // Step 5. Evaluate the position statically and
849     // update gain statistics of parent move.
850     if (isCheck)
851         ss->eval = ss->evalMargin = VALUE_NONE;
852     else if (tte)
853     {
854         assert(tte->static_value() != VALUE_NONE);
855
856         ss->eval = tte->static_value();
857         ss->evalMargin = tte->static_value_margin();
858         refinedValue = refine_eval(tte, ss->eval, ply);
859     }
860     else
861     {
862         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
863         TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
864     }
865
866     // Save gain for the parent non-capture move
867     update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
868
869     // Step 6. Razoring (is omitted in PV nodes)
870     if (   !PvNode
871         &&  depth < RazorDepth
872         && !isCheck
873         &&  refinedValue < beta - razor_margin(depth)
874         &&  ttMove == MOVE_NONE
875         && !value_is_mate(beta)
876         && !pos.has_pawn_on_7th(pos.side_to_move()))
877     {
878         Value rbeta = beta - razor_margin(depth);
879         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO, ply);
880         if (v < rbeta)
881             // Logically we should return (v + razor_margin(depth)), but
882             // surprisingly this did slightly weaker in tests.
883             return v;
884     }
885
886     // Step 7. Static null move pruning (is omitted in PV nodes)
887     // We're betting that the opponent doesn't have a move that will reduce
888     // the score by more than futility_margin(depth) if we do a null move.
889     if (   !PvNode
890         && !ss->skipNullMove
891         &&  depth < RazorDepth
892         && !isCheck
893         &&  refinedValue >= beta + futility_margin(depth, 0)
894         && !value_is_mate(beta)
895         &&  pos.non_pawn_material(pos.side_to_move()))
896         return refinedValue - futility_margin(depth, 0);
897
898     // Step 8. Null move search with verification search (is omitted in PV nodes)
899     if (   !PvNode
900         && !ss->skipNullMove
901         &&  depth > ONE_PLY
902         && !isCheck
903         &&  refinedValue >= beta
904         && !value_is_mate(beta)
905         &&  pos.non_pawn_material(pos.side_to_move()))
906     {
907         ss->currentMove = MOVE_NULL;
908
909         // Null move dynamic reduction based on depth
910         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
911
912         // Null move dynamic reduction based on value
913         if (refinedValue - beta > PawnValueMidgame)
914             R++;
915
916         pos.do_null_move(st);
917         (ss+1)->skipNullMove = true;
918         nullValue = -search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY, ply+1);
919         (ss+1)->skipNullMove = false;
920         pos.undo_null_move();
921
922         if (nullValue >= beta)
923         {
924             // Do not return unproven mate scores
925             if (nullValue >= value_mate_in(PLY_MAX))
926                 nullValue = beta;
927
928             if (depth < 6 * ONE_PLY)
929                 return nullValue;
930
931             // Do verification search at high depths
932             ss->skipNullMove = true;
933             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY, ply);
934             ss->skipNullMove = false;
935
936             if (v >= beta)
937                 return nullValue;
938         }
939         else
940         {
941             // The null move failed low, which means that we may be faced with
942             // some kind of threat. If the previous move was reduced, check if
943             // the move that refuted the null move was somehow connected to the
944             // move which was reduced. If a connection is found, return a fail
945             // low score (which will cause the reduced move to fail high in the
946             // parent node, which will trigger a re-search with full depth).
947             if (nullValue == value_mated_in(ply + 2))
948                 mateThreat = true;
949
950             threatMove = (ss+1)->bestMove;
951             if (   depth < ThreatDepth
952                 && (ss-1)->reduction
953                 && threatMove != MOVE_NONE
954                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
955                 return beta - 1;
956         }
957     }
958
959     // Step 9. Internal iterative deepening
960     if (   depth >= IIDDepth[PvNode]
961         && ttMove == MOVE_NONE
962         && (PvNode || (!isCheck && ss->eval >= beta - IIDMargin)))
963     {
964         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
965
966         ss->skipNullMove = true;
967         search<PvNode>(pos, ss, alpha, beta, d, ply);
968         ss->skipNullMove = false;
969
970         ttMove = ss->bestMove;
971         tte = TT.retrieve(posKey);
972     }
973
974     // Expensive mate threat detection (only for PV nodes)
975     if (PvNode)
976         mateThreat = pos.has_mate_threat();
977
978 split_point_start: // At split points actual search starts from here
979
980     // Initialize a MovePicker object for the current position
981     MovePickerExt<SpNode, Root> mp(pos, ttMove, depth, H, ss, (PvNode ? -VALUE_INFINITE : beta));
982     CheckInfo ci(pos);
983     ss->bestMove = MOVE_NONE;
984     futilityBase = ss->eval + ss->evalMargin;
985     singularExtensionNode =   !Root
986                            && !SpNode
987                            && depth >= SingularExtensionDepth[PvNode]
988                            && tte
989                            && tte->move()
990                            && !excludedMove // Do not allow recursive singular extension search
991                            && (tte->type() & VALUE_TYPE_LOWER)
992                            && tte->depth() >= depth - 3 * ONE_PLY;
993     if (SpNode)
994     {
995         lock_grab(&(sp->lock));
996         bestValue = sp->bestValue;
997     }
998
999     // Step 10. Loop through moves
1000     // Loop through all legal moves until no moves remain or a beta cutoff occurs
1001     while (   bestValue < beta
1002            && (move = mp.get_next_move()) != MOVE_NONE
1003            && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1004     {
1005       assert(move_is_ok(move));
1006
1007       if (SpNode)
1008       {
1009           moveCount = ++sp->moveCount;
1010           lock_release(&(sp->lock));
1011       }
1012       else if (move == excludedMove)
1013           continue;
1014       else
1015           moveCount++;
1016
1017       if (Root)
1018       {
1019           // This is used by time management
1020           FirstRootMove = (moveCount == 1);
1021
1022           // Save the current node count before the move is searched
1023           nodes = pos.nodes_searched();
1024
1025           // If it's time to send nodes info, do it here where we have the
1026           // correct accumulated node counts searched by each thread.
1027           if (SendSearchedNodes)
1028           {
1029               SendSearchedNodes = false;
1030               cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
1031           }
1032
1033           if (current_search_time() >= 1000)
1034               cout << "info currmove " << move
1035                    << " currmovenumber " << moveCount << endl;
1036       }
1037
1038       // At Root and at first iteration do a PV search on all the moves
1039       // to score root moves. Otherwise only the first one is the PV.
1040       isPvMove = (PvNode && moveCount <= (Root ? MultiPV + 1000 * (depth <= ONE_PLY) : 1));
1041       moveIsCheck = pos.move_is_check(move, ci);
1042       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1043
1044       // Step 11. Decide the new search depth
1045       ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, mateThreat, &dangerous);
1046
1047       // Singular extension search. If all moves but one fail low on a search of (alpha-s, beta-s),
1048       // and just one fails high on (alpha, beta), then that move is singular and should be extended.
1049       // To verify this we do a reduced search on all the other moves but the ttMove, if result is
1050       // lower than ttValue minus a margin then we extend ttMove.
1051       if (   singularExtensionNode
1052           && move == tte->move()
1053           && ext < ONE_PLY)
1054       {
1055           Value ttValue = value_from_tt(tte->value(), ply);
1056
1057           if (abs(ttValue) < VALUE_KNOWN_WIN)
1058           {
1059               Value b = ttValue - depth;
1060               ss->excludedMove = move;
1061               ss->skipNullMove = true;
1062               Value v = search<NonPV>(pos, ss, b - 1, b, depth / 2, ply);
1063               ss->skipNullMove = false;
1064               ss->excludedMove = MOVE_NONE;
1065               ss->bestMove = MOVE_NONE;
1066               if (v < b)
1067                   ext = ONE_PLY;
1068           }
1069       }
1070
1071       // Update current move (this must be done after singular extension search)
1072       ss->currentMove = move;
1073       newDepth = depth - ONE_PLY + ext;
1074
1075       // Step 12. Futility pruning (is omitted in PV nodes)
1076       if (   !PvNode
1077           && !captureOrPromotion
1078           && !isCheck
1079           && !dangerous
1080           &&  move != ttMove
1081           && !move_is_castle(move))
1082       {
1083           // Move count based pruning
1084           if (   moveCount >= futility_move_count(depth)
1085               && !(threatMove && connected_threat(pos, move, threatMove))
1086               && bestValue > value_mated_in(PLY_MAX)) // FIXME bestValue is racy
1087           {
1088               if (SpNode)
1089                   lock_grab(&(sp->lock));
1090
1091               continue;
1092           }
1093
1094           // Value based pruning
1095           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1096           // but fixing this made program slightly weaker.
1097           Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount);
1098           futilityValueScaled =  futilityBase + futility_margin(predictedDepth, moveCount)
1099                                + H.gain(pos.piece_on(move_from(move)), move_to(move));
1100
1101           if (futilityValueScaled < beta)
1102           {
1103               if (SpNode)
1104               {
1105                   lock_grab(&(sp->lock));
1106                   if (futilityValueScaled > sp->bestValue)
1107                       sp->bestValue = bestValue = futilityValueScaled;
1108               }
1109               else if (futilityValueScaled > bestValue)
1110                   bestValue = futilityValueScaled;
1111
1112               continue;
1113           }
1114
1115           // Prune moves with negative SEE at low depths
1116           if (   predictedDepth < 2 * ONE_PLY
1117               && bestValue > value_mated_in(PLY_MAX)
1118               && pos.see_sign(move) < 0)
1119           {
1120               if (SpNode)
1121                   lock_grab(&(sp->lock));
1122
1123               continue;
1124           }
1125       }
1126
1127       // Step 13. Make the move
1128       pos.do_move(move, st, ci, moveIsCheck);
1129
1130       if (!SpNode && !captureOrPromotion)
1131           movesSearched[playedMoveCount++] = move;
1132
1133       // Step extra. pv search (only in PV nodes)
1134       // The first move in list is the expected PV
1135       if (isPvMove)
1136       {
1137           // Aspiration window is disabled in multi-pv case
1138           if (Root && MultiPV > 1)
1139               alpha = -VALUE_INFINITE;
1140
1141           value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, ply+1);
1142       }
1143       else
1144       {
1145           // Step 14. Reduced depth search
1146           // If the move fails high will be re-searched at full depth.
1147           bool doFullDepthSearch = true;
1148
1149           if (    depth >= 3 * ONE_PLY
1150               && !captureOrPromotion
1151               && !dangerous
1152               && !move_is_castle(move)
1153               &&  ss->killers[0] != move
1154               &&  ss->killers[1] != move)
1155           {
1156               ss->reduction = reduction<PvNode>(depth, moveCount);
1157               if (ss->reduction)
1158               {
1159                   alpha = SpNode ? sp->alpha : alpha;
1160                   Depth d = newDepth - ss->reduction;
1161                   value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d, ply+1);
1162
1163                   doFullDepthSearch = (value > alpha);
1164               }
1165               ss->reduction = DEPTH_ZERO; // Restore original reduction
1166           }
1167
1168           // Step 15. Full depth search
1169           if (doFullDepthSearch)
1170           {
1171               alpha = SpNode ? sp->alpha : alpha;
1172               value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth, ply+1);
1173
1174               // Step extra. pv search (only in PV nodes)
1175               // Search only for possible new PV nodes, if instead value >= beta then
1176               // parent node fails low with value <= alpha and tries another move.
1177               if (PvNode && value > alpha && (Root || value < beta))
1178                   value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth, ply+1);
1179           }
1180       }
1181
1182       // Step 16. Undo move
1183       pos.undo_move(move);
1184
1185       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1186
1187       // Step 17. Check for new best move
1188       if (SpNode)
1189       {
1190           lock_grab(&(sp->lock));
1191           bestValue = sp->bestValue;
1192           alpha = sp->alpha;
1193       }
1194
1195       if (value > bestValue && !(SpNode && ThreadsMgr.cutoff_at_splitpoint(threadID)))
1196       {
1197           bestValue = value;
1198
1199           if (SpNode)
1200               sp->bestValue = value;
1201
1202           if (!Root && value > alpha)
1203           {
1204               if (PvNode && value < beta) // We want always alpha < beta
1205               {
1206                   alpha = value;
1207
1208                   if (SpNode)
1209                       sp->alpha = value;
1210               }
1211               else if (SpNode)
1212                   sp->betaCutoff = true;
1213
1214               if (value == value_mate_in(ply + 1))
1215                   ss->mateKiller = move;
1216
1217               ss->bestMove = move;
1218
1219               if (SpNode)
1220                   sp->ss->bestMove = move;
1221           }
1222       }
1223
1224       if (Root)
1225       {
1226           // Finished searching the move. If StopRequest is true, the search
1227           // was aborted because the user interrupted the search or because we
1228           // ran out of time. In this case, the return value of the search cannot
1229           // be trusted, and we break out of the loop without updating the best
1230           // move and/or PV.
1231           if (StopRequest)
1232               break;
1233
1234           // Remember searched nodes counts for this move
1235           mp.rm->nodes += pos.nodes_searched() - nodes;
1236
1237           // PV move or new best move ?
1238           if (isPvMove || value > alpha)
1239           {
1240               // Update PV
1241               ss->bestMove = move;
1242               mp.rm->pv_score = value;
1243               mp.rm->extract_pv_from_tt(pos);
1244
1245               // We record how often the best move has been changed in each
1246               // iteration. This information is used for time management: When
1247               // the best move changes frequently, we allocate some more time.
1248               if (!isPvMove && MultiPV == 1)
1249                   Rml.bestMoveChanges++;
1250
1251               Rml.sort_multipv(moveCount);
1252
1253               // Update alpha. In multi-pv we don't use aspiration window, so
1254               // set alpha equal to minimum score among the PV lines.
1255               if (MultiPV > 1)
1256                   alpha = Rml[Min(moveCount, MultiPV) - 1].pv_score; // FIXME why moveCount?
1257               else if (value > alpha)
1258                   alpha = value;
1259           }
1260           else
1261               mp.rm->pv_score = -VALUE_INFINITE;
1262
1263       } // Root
1264
1265       // Step 18. Check for split
1266       if (   !Root
1267           && !SpNode
1268           && depth >= ThreadsMgr.min_split_depth()
1269           && ThreadsMgr.active_threads() > 1
1270           && bestValue < beta
1271           && ThreadsMgr.available_thread_exists(threadID)
1272           && !StopRequest
1273           && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1274           ThreadsMgr.split<FakeSplit>(pos, ss, ply, &alpha, beta, &bestValue, depth,
1275                                       threatMove, mateThreat, moveCount, &mp, PvNode);
1276     }
1277
1278     // Step 19. Check for mate and stalemate
1279     // All legal moves have been searched and if there are
1280     // no legal moves, it must be mate or stalemate.
1281     // If one move was excluded return fail low score.
1282     if (!SpNode && !moveCount)
1283         return excludedMove ? oldAlpha : isCheck ? value_mated_in(ply) : VALUE_DRAW;
1284
1285     // Step 20. Update tables
1286     // If the search is not aborted, update the transposition table,
1287     // history counters, and killer moves.
1288     if (!SpNode && !StopRequest && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1289     {
1290         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1291         vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1292              : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1293
1294         TT.store(posKey, value_to_tt(bestValue, ply), vt, depth, move, ss->eval, ss->evalMargin);
1295
1296         // Update killers and history only for non capture moves that fails high
1297         if (    bestValue >= beta
1298             && !pos.move_is_capture_or_promotion(move))
1299         {
1300             update_history(pos, move, depth, movesSearched, playedMoveCount);
1301             update_killers(move, ss->killers);
1302         }
1303     }
1304
1305     if (SpNode)
1306     {
1307         // Here we have the lock still grabbed
1308         sp->slaves[threadID] = 0;
1309         sp->nodes += pos.nodes_searched();
1310         lock_release(&(sp->lock));
1311     }
1312
1313     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1314
1315     return bestValue;
1316   }
1317
1318   // qsearch() is the quiescence search function, which is called by the main
1319   // search function when the remaining depth is zero (or, to be more precise,
1320   // less than ONE_PLY).
1321
1322   template <NodeType PvNode>
1323   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth, int ply) {
1324
1325     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1326     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1327     assert(PvNode || alpha == beta - 1);
1328     assert(depth <= 0);
1329     assert(ply > 0 && ply < PLY_MAX);
1330     assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
1331
1332     StateInfo st;
1333     Move ttMove, move;
1334     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1335     bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1336     const TTEntry* tte;
1337     Depth ttDepth;
1338     Value oldAlpha = alpha;
1339
1340     ss->bestMove = ss->currentMove = MOVE_NONE;
1341
1342     // Check for an instant draw or maximum ply reached
1343     if (pos.is_draw() || ply >= PLY_MAX - 1)
1344         return VALUE_DRAW;
1345
1346     // Decide whether or not to include checks, this fixes also the type of
1347     // TT entry depth that we are going to use. Note that in qsearch we use
1348     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1349     isCheck = pos.is_check();
1350     ttDepth = (isCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1351
1352     // Transposition table lookup. At PV nodes, we don't use the TT for
1353     // pruning, but only for move ordering.
1354     tte = TT.retrieve(pos.get_key());
1355     ttMove = (tte ? tte->move() : MOVE_NONE);
1356
1357     if (!PvNode && tte && ok_to_use_TT(tte, ttDepth, beta, ply))
1358     {
1359         ss->bestMove = ttMove; // Can be MOVE_NONE
1360         return value_from_tt(tte->value(), ply);
1361     }
1362
1363     // Evaluate the position statically
1364     if (isCheck)
1365     {
1366         bestValue = futilityBase = -VALUE_INFINITE;
1367         ss->eval = evalMargin = VALUE_NONE;
1368         enoughMaterial = false;
1369     }
1370     else
1371     {
1372         if (tte)
1373         {
1374             assert(tte->static_value() != VALUE_NONE);
1375
1376             evalMargin = tte->static_value_margin();
1377             ss->eval = bestValue = tte->static_value();
1378         }
1379         else
1380             ss->eval = bestValue = evaluate(pos, evalMargin);
1381
1382         update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1383
1384         // Stand pat. Return immediately if static value is at least beta
1385         if (bestValue >= beta)
1386         {
1387             if (!tte)
1388                 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1389
1390             return bestValue;
1391         }
1392
1393         if (PvNode && bestValue > alpha)
1394             alpha = bestValue;
1395
1396         // Futility pruning parameters, not needed when in check
1397         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1398         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1399     }
1400
1401     // Initialize a MovePicker object for the current position, and prepare
1402     // to search the moves. Because the depth is <= 0 here, only captures,
1403     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1404     // be generated.
1405     MovePicker mp(pos, ttMove, depth, H);
1406     CheckInfo ci(pos);
1407
1408     // Loop through the moves until no moves remain or a beta cutoff occurs
1409     while (   alpha < beta
1410            && (move = mp.get_next_move()) != MOVE_NONE)
1411     {
1412       assert(move_is_ok(move));
1413
1414       moveIsCheck = pos.move_is_check(move, ci);
1415
1416       // Futility pruning
1417       if (   !PvNode
1418           && !isCheck
1419           && !moveIsCheck
1420           &&  move != ttMove
1421           &&  enoughMaterial
1422           && !move_is_promotion(move)
1423           && !pos.move_is_passed_pawn_push(move))
1424       {
1425           futilityValue =  futilityBase
1426                          + pos.endgame_value_of_piece_on(move_to(move))
1427                          + (move_is_ep(move) ? PawnValueEndgame : VALUE_ZERO);
1428
1429           if (futilityValue < alpha)
1430           {
1431               if (futilityValue > bestValue)
1432                   bestValue = futilityValue;
1433               continue;
1434           }
1435
1436           // Prune moves with negative or equal SEE
1437           if (   futilityBase < beta
1438               && depth < DEPTH_ZERO
1439               && pos.see(move) <= 0)
1440               continue;
1441       }
1442
1443       // Detect non-capture evasions that are candidate to be pruned
1444       evasionPrunable =   isCheck
1445                        && bestValue > value_mated_in(PLY_MAX)
1446                        && !pos.move_is_capture(move)
1447                        && !pos.can_castle(pos.side_to_move());
1448
1449       // Don't search moves with negative SEE values
1450       if (   !PvNode
1451           && (!isCheck || evasionPrunable)
1452           &&  move != ttMove
1453           && !move_is_promotion(move)
1454           &&  pos.see_sign(move) < 0)
1455           continue;
1456
1457       // Don't search useless checks
1458       if (   !PvNode
1459           && !isCheck
1460           &&  moveIsCheck
1461           &&  move != ttMove
1462           && !pos.move_is_capture_or_promotion(move)
1463           &&  ss->eval + PawnValueMidgame / 4 < beta
1464           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1465       {
1466           if (ss->eval + PawnValueMidgame / 4 > bestValue)
1467               bestValue = ss->eval + PawnValueMidgame / 4;
1468
1469           continue;
1470       }
1471
1472       // Update current move
1473       ss->currentMove = move;
1474
1475       // Make and search the move
1476       pos.do_move(move, st, ci, moveIsCheck);
1477       value = -qsearch<PvNode>(pos, ss+1, -beta, -alpha, depth-ONE_PLY, ply+1);
1478       pos.undo_move(move);
1479
1480       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1481
1482       // New best move?
1483       if (value > bestValue)
1484       {
1485           bestValue = value;
1486           if (value > alpha)
1487           {
1488               alpha = value;
1489               ss->bestMove = move;
1490           }
1491        }
1492     }
1493
1494     // All legal moves have been searched. A special case: If we're in check
1495     // and no legal moves were found, it is checkmate.
1496     if (isCheck && bestValue == -VALUE_INFINITE)
1497         return value_mated_in(ply);
1498
1499     // Update transposition table
1500     ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1501     TT.store(pos.get_key(), value_to_tt(bestValue, ply), vt, ttDepth, ss->bestMove, ss->eval, evalMargin);
1502
1503     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1504
1505     return bestValue;
1506   }
1507
1508
1509   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1510   // bestValue is updated only when returning false because in that case move
1511   // will be pruned.
1512
1513   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1514   {
1515     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1516     Square from, to, ksq, victimSq;
1517     Piece pc;
1518     Color them;
1519     Value futilityValue, bv = *bestValue;
1520
1521     from = move_from(move);
1522     to = move_to(move);
1523     them = opposite_color(pos.side_to_move());
1524     ksq = pos.king_square(them);
1525     kingAtt = pos.attacks_from<KING>(ksq);
1526     pc = pos.piece_on(from);
1527
1528     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1529     oldAtt = pos.attacks_from(pc, from, occ);
1530     newAtt = pos.attacks_from(pc,   to, occ);
1531
1532     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1533     b = kingAtt & ~pos.pieces_of_color(them) & ~newAtt & ~(1ULL << to);
1534
1535     if (!(b && (b & (b - 1))))
1536         return true;
1537
1538     // Rule 2. Queen contact check is very dangerous
1539     if (   type_of_piece(pc) == QUEEN
1540         && bit_is_set(kingAtt, to))
1541         return true;
1542
1543     // Rule 3. Creating new double threats with checks
1544     b = pos.pieces_of_color(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1545
1546     while (b)
1547     {
1548         victimSq = pop_1st_bit(&b);
1549         futilityValue = futilityBase + pos.endgame_value_of_piece_on(victimSq);
1550
1551         // Note that here we generate illegal "double move"!
1552         if (   futilityValue >= beta
1553             && pos.see_sign(make_move(from, victimSq)) >= 0)
1554             return true;
1555
1556         if (futilityValue > bv)
1557             bv = futilityValue;
1558     }
1559
1560     // Update bestValue only if check is not dangerous (because we will prune the move)
1561     *bestValue = bv;
1562     return false;
1563   }
1564
1565
1566   // connected_moves() tests whether two moves are 'connected' in the sense
1567   // that the first move somehow made the second move possible (for instance
1568   // if the moving piece is the same in both moves). The first move is assumed
1569   // to be the move that was made to reach the current position, while the
1570   // second move is assumed to be a move from the current position.
1571
1572   bool connected_moves(const Position& pos, Move m1, Move m2) {
1573
1574     Square f1, t1, f2, t2;
1575     Piece p;
1576
1577     assert(m1 && move_is_ok(m1));
1578     assert(m2 && move_is_ok(m2));
1579
1580     // Case 1: The moving piece is the same in both moves
1581     f2 = move_from(m2);
1582     t1 = move_to(m1);
1583     if (f2 == t1)
1584         return true;
1585
1586     // Case 2: The destination square for m2 was vacated by m1
1587     t2 = move_to(m2);
1588     f1 = move_from(m1);
1589     if (t2 == f1)
1590         return true;
1591
1592     // Case 3: Moving through the vacated square
1593     if (   piece_is_slider(pos.piece_on(f2))
1594         && bit_is_set(squares_between(f2, t2), f1))
1595       return true;
1596
1597     // Case 4: The destination square for m2 is defended by the moving piece in m1
1598     p = pos.piece_on(t1);
1599     if (bit_is_set(pos.attacks_from(p, t1), t2))
1600         return true;
1601
1602     // Case 5: Discovered check, checking piece is the piece moved in m1
1603     if (    piece_is_slider(p)
1604         &&  bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1605         && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1606     {
1607         // discovered_check_candidates() works also if the Position's side to
1608         // move is the opposite of the checking piece.
1609         Color them = opposite_color(pos.side_to_move());
1610         Bitboard dcCandidates = pos.discovered_check_candidates(them);
1611
1612         if (bit_is_set(dcCandidates, f2))
1613             return true;
1614     }
1615     return false;
1616   }
1617
1618
1619   // value_is_mate() checks if the given value is a mate one eventually
1620   // compensated for the ply.
1621
1622   bool value_is_mate(Value value) {
1623
1624     assert(abs(value) <= VALUE_INFINITE);
1625
1626     return   value <= value_mated_in(PLY_MAX)
1627           || value >= value_mate_in(PLY_MAX);
1628   }
1629
1630
1631   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1632   // "plies to mate from the current ply".  Non-mate scores are unchanged.
1633   // The function is called before storing a value to the transposition table.
1634
1635   Value value_to_tt(Value v, int ply) {
1636
1637     if (v >= value_mate_in(PLY_MAX))
1638       return v + ply;
1639
1640     if (v <= value_mated_in(PLY_MAX))
1641       return v - ply;
1642
1643     return v;
1644   }
1645
1646
1647   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1648   // the transposition table to a mate score corrected for the current ply.
1649
1650   Value value_from_tt(Value v, int ply) {
1651
1652     if (v >= value_mate_in(PLY_MAX))
1653       return v - ply;
1654
1655     if (v <= value_mated_in(PLY_MAX))
1656       return v + ply;
1657
1658     return v;
1659   }
1660
1661
1662   // extension() decides whether a move should be searched with normal depth,
1663   // or with extended depth. Certain classes of moves (checking moves, in
1664   // particular) are searched with bigger depth than ordinary moves and in
1665   // any case are marked as 'dangerous'. Note that also if a move is not
1666   // extended, as example because the corresponding UCI option is set to zero,
1667   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1668   template <NodeType PvNode>
1669   Depth extension(const Position& pos, Move m, bool captureOrPromotion,
1670                   bool moveIsCheck, bool mateThreat, bool* dangerous) {
1671
1672     assert(m != MOVE_NONE);
1673
1674     Depth result = DEPTH_ZERO;
1675     *dangerous = moveIsCheck | mateThreat;
1676
1677     if (*dangerous)
1678     {
1679         if (moveIsCheck && pos.see_sign(m) >= 0)
1680             result += CheckExtension[PvNode];
1681
1682         if (mateThreat)
1683             result += MateThreatExtension[PvNode];
1684     }
1685
1686     if (pos.type_of_piece_on(move_from(m)) == PAWN)
1687     {
1688         Color c = pos.side_to_move();
1689         if (relative_rank(c, move_to(m)) == RANK_7)
1690         {
1691             result += PawnPushTo7thExtension[PvNode];
1692             *dangerous = true;
1693         }
1694         if (pos.pawn_is_passed(c, move_to(m)))
1695         {
1696             result += PassedPawnExtension[PvNode];
1697             *dangerous = true;
1698         }
1699     }
1700
1701     if (   captureOrPromotion
1702         && pos.type_of_piece_on(move_to(m)) != PAWN
1703         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1704             - pos.midgame_value_of_piece_on(move_to(m)) == VALUE_ZERO)
1705         && !move_is_promotion(m)
1706         && !move_is_ep(m))
1707     {
1708         result += PawnEndgameExtension[PvNode];
1709         *dangerous = true;
1710     }
1711
1712     if (   PvNode
1713         && captureOrPromotion
1714         && pos.type_of_piece_on(move_to(m)) != PAWN
1715         && pos.see_sign(m) >= 0)
1716     {
1717         result += ONE_PLY / 2;
1718         *dangerous = true;
1719     }
1720
1721     return Min(result, ONE_PLY);
1722   }
1723
1724
1725   // connected_threat() tests whether it is safe to forward prune a move or if
1726   // is somehow connected to the threat move returned by null search.
1727
1728   bool connected_threat(const Position& pos, Move m, Move threat) {
1729
1730     assert(move_is_ok(m));
1731     assert(threat && move_is_ok(threat));
1732     assert(!pos.move_is_check(m));
1733     assert(!pos.move_is_capture_or_promotion(m));
1734     assert(!pos.move_is_passed_pawn_push(m));
1735
1736     Square mfrom, mto, tfrom, tto;
1737
1738     mfrom = move_from(m);
1739     mto = move_to(m);
1740     tfrom = move_from(threat);
1741     tto = move_to(threat);
1742
1743     // Case 1: Don't prune moves which move the threatened piece
1744     if (mfrom == tto)
1745         return true;
1746
1747     // Case 2: If the threatened piece has value less than or equal to the
1748     // value of the threatening piece, don't prune moves which defend it.
1749     if (   pos.move_is_capture(threat)
1750         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
1751             || pos.type_of_piece_on(tfrom) == KING)
1752         && pos.move_attacks_square(m, tto))
1753         return true;
1754
1755     // Case 3: If the moving piece in the threatened move is a slider, don't
1756     // prune safe moves which block its ray.
1757     if (   piece_is_slider(pos.piece_on(tfrom))
1758         && bit_is_set(squares_between(tfrom, tto), mto)
1759         && pos.see_sign(m) >= 0)
1760         return true;
1761
1762     return false;
1763   }
1764
1765
1766   // ok_to_use_TT() returns true if a transposition table score
1767   // can be used at a given point in search.
1768
1769   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1770
1771     Value v = value_from_tt(tte->value(), ply);
1772
1773     return   (   tte->depth() >= depth
1774               || v >= Max(value_mate_in(PLY_MAX), beta)
1775               || v < Min(value_mated_in(PLY_MAX), beta))
1776
1777           && (   ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1778               || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1779   }
1780
1781
1782   // refine_eval() returns the transposition table score if
1783   // possible otherwise falls back on static position evaluation.
1784
1785   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1786
1787       assert(tte);
1788
1789       Value v = value_from_tt(tte->value(), ply);
1790
1791       if (   ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1792           || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1793           return v;
1794
1795       return defaultEval;
1796   }
1797
1798
1799   // update_history() registers a good move that produced a beta-cutoff
1800   // in history and marks as failures all the other moves of that ply.
1801
1802   void update_history(const Position& pos, Move move, Depth depth,
1803                       Move movesSearched[], int moveCount) {
1804     Move m;
1805     Value bonus = Value(int(depth) * int(depth));
1806
1807     H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1808
1809     for (int i = 0; i < moveCount - 1; i++)
1810     {
1811         m = movesSearched[i];
1812
1813         assert(m != move);
1814
1815         H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1816     }
1817   }
1818
1819
1820   // update_killers() add a good move that produced a beta-cutoff
1821   // among the killer moves of that ply.
1822
1823   void update_killers(Move m, Move killers[]) {
1824
1825     if (m != killers[0])
1826     {
1827         killers[1] = killers[0];
1828         killers[0] = m;
1829     }
1830   }
1831
1832
1833   // update_gains() updates the gains table of a non-capture move given
1834   // the static position evaluation before and after the move.
1835
1836   void update_gains(const Position& pos, Move m, Value before, Value after) {
1837
1838     if (   m != MOVE_NULL
1839         && before != VALUE_NONE
1840         && after != VALUE_NONE
1841         && pos.captured_piece_type() == PIECE_TYPE_NONE
1842         && !move_is_special(m))
1843         H.update_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
1844   }
1845
1846   // current_search_time() returns the number of milliseconds which have passed
1847   // since the beginning of the current search.
1848
1849   int current_search_time() {
1850
1851     return get_system_time() - SearchStartTime;
1852   }
1853
1854
1855   // value_to_uci() converts a value to a string suitable for use with the UCI
1856   // protocol specifications:
1857   //
1858   // cp <x>     The score from the engine's point of view in centipawns.
1859   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1860   //            use negative values for y.
1861
1862   std::string value_to_uci(Value v) {
1863
1864     std::stringstream s;
1865
1866     if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1867       s << "cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1868     else
1869       s << "mate " << (v > 0 ? (VALUE_MATE - v + 1) / 2 : -(VALUE_MATE + v) / 2);
1870
1871     return s.str();
1872   }
1873
1874
1875   // speed_to_uci() returns a string with time stats of current search suitable
1876   // to be sent to UCI gui.
1877
1878   std::string speed_to_uci(int64_t nodes) {
1879
1880     std::stringstream s;
1881     int t = current_search_time();
1882
1883     s << " nodes " << nodes
1884       << " nps "   << (t > 0 ? int(nodes * 1000 / t) : 0)
1885       << " time "  << t;
1886
1887     return s.str();
1888   }
1889
1890
1891   // poll() performs two different functions: It polls for user input, and it
1892   // looks at the time consumed so far and decides if it's time to abort the
1893   // search.
1894
1895   void poll(const Position& pos) {
1896
1897     static int lastInfoTime;
1898     int t = current_search_time();
1899
1900     //  Poll for input
1901     if (input_available())
1902     {
1903         // We are line oriented, don't read single chars
1904         std::string command;
1905
1906         if (!std::getline(std::cin, command))
1907             command = "quit";
1908
1909         if (command == "quit")
1910         {
1911             // Quit the program as soon as possible
1912             Pondering = false;
1913             QuitRequest = StopRequest = true;
1914             return;
1915         }
1916         else if (command == "stop")
1917         {
1918             // Stop calculating as soon as possible, but still send the "bestmove"
1919             // and possibly the "ponder" token when finishing the search.
1920             Pondering = false;
1921             StopRequest = true;
1922         }
1923         else if (command == "ponderhit")
1924         {
1925             // The opponent has played the expected move. GUI sends "ponderhit" if
1926             // we were told to ponder on the same move the opponent has played. We
1927             // should continue searching but switching from pondering to normal search.
1928             Pondering = false;
1929
1930             if (StopOnPonderhit)
1931                 StopRequest = true;
1932         }
1933     }
1934
1935     // Print search information
1936     if (t < 1000)
1937         lastInfoTime = 0;
1938
1939     else if (lastInfoTime > t)
1940         // HACK: Must be a new search where we searched less than
1941         // NodesBetweenPolls nodes during the first second of search.
1942         lastInfoTime = 0;
1943
1944     else if (t - lastInfoTime >= 1000)
1945     {
1946         lastInfoTime = t;
1947
1948         if (dbg_show_mean)
1949             dbg_print_mean();
1950
1951         if (dbg_show_hit_rate)
1952             dbg_print_hit_rate();
1953
1954         // Send info on searched nodes as soon as we return to root
1955         SendSearchedNodes = true;
1956     }
1957
1958     // Should we stop the search?
1959     if (Pondering)
1960         return;
1961
1962     bool stillAtFirstMove =    FirstRootMove
1963                            && !AspirationFailLow
1964                            &&  t > TimeMgr.available_time();
1965
1966     bool noMoreTime =   t > TimeMgr.maximum_time()
1967                      || stillAtFirstMove;
1968
1969     if (   (UseTimeManagement && noMoreTime)
1970         || (ExactMaxTime && t >= ExactMaxTime)
1971         || (MaxNodes && pos.nodes_searched() >= MaxNodes)) // FIXME
1972         StopRequest = true;
1973   }
1974
1975
1976   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
1977   // while the program is pondering. The point is to work around a wrinkle in
1978   // the UCI protocol: When pondering, the engine is not allowed to give a
1979   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
1980   // We simply wait here until one of these commands is sent, and return,
1981   // after which the bestmove and pondermove will be printed.
1982
1983   void wait_for_stop_or_ponderhit() {
1984
1985     std::string command;
1986
1987     while (true)
1988     {
1989         // Wait for a command from stdin
1990         if (!std::getline(std::cin, command))
1991             command = "quit";
1992
1993         if (command == "quit")
1994         {
1995             QuitRequest = true;
1996             break;
1997         }
1998         else if (command == "ponderhit" || command == "stop")
1999             break;
2000     }
2001   }
2002
2003
2004   // init_thread() is the function which is called when a new thread is
2005   // launched. It simply calls the idle_loop() function with the supplied
2006   // threadID. There are two versions of this function; one for POSIX
2007   // threads and one for Windows threads.
2008
2009 #if !defined(_MSC_VER)
2010
2011   void* init_thread(void* threadID) {
2012
2013     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
2014     return NULL;
2015   }
2016
2017 #else
2018
2019   DWORD WINAPI init_thread(LPVOID threadID) {
2020
2021     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
2022     return 0;
2023   }
2024
2025 #endif
2026
2027
2028   /// The ThreadsManager class
2029
2030
2031   // read_uci_options() updates number of active threads and other internal
2032   // parameters according to the UCI options values. It is called before
2033   // to start a new search.
2034
2035   void ThreadsManager::read_uci_options() {
2036
2037     maxThreadsPerSplitPoint = Options["Maximum Number of Threads per Split Point"].value<int>();
2038     minimumSplitDepth       = Options["Minimum Split Depth"].value<int>() * ONE_PLY;
2039     useSleepingThreads      = Options["Use Sleeping Threads"].value<bool>();
2040     activeThreads           = Options["Threads"].value<int>();
2041   }
2042
2043
2044   // idle_loop() is where the threads are parked when they have no work to do.
2045   // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2046   // object for which the current thread is the master.
2047
2048   void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2049
2050     assert(threadID >= 0 && threadID < MAX_THREADS);
2051
2052     int i;
2053     bool allFinished = false;
2054
2055     while (true)
2056     {
2057         // Slave threads can exit as soon as AllThreadsShouldExit raises,
2058         // master should exit as last one.
2059         if (allThreadsShouldExit)
2060         {
2061             assert(!sp);
2062             threads[threadID].state = THREAD_TERMINATED;
2063             return;
2064         }
2065
2066         // If we are not thinking, wait for a condition to be signaled
2067         // instead of wasting CPU time polling for work.
2068         while (   threadID >= activeThreads || threads[threadID].state == THREAD_INITIALIZING
2069                || (useSleepingThreads && threads[threadID].state == THREAD_AVAILABLE))
2070         {
2071             assert(!sp || useSleepingThreads);
2072             assert(threadID != 0 || useSleepingThreads);
2073
2074             if (threads[threadID].state == THREAD_INITIALIZING)
2075                 threads[threadID].state = THREAD_AVAILABLE;
2076
2077             // Grab the lock to avoid races with wake_sleeping_thread()
2078             lock_grab(&sleepLock[threadID]);
2079
2080             // If we are master and all slaves have finished do not go to sleep
2081             for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2082             allFinished = (i == activeThreads);
2083
2084             if (allFinished || allThreadsShouldExit)
2085             {
2086                 lock_release(&sleepLock[threadID]);
2087                 break;
2088             }
2089
2090             // Do sleep here after retesting sleep conditions
2091             if (threadID >= activeThreads || threads[threadID].state == THREAD_AVAILABLE)
2092                 cond_wait(&sleepCond[threadID], &sleepLock[threadID]);
2093
2094             lock_release(&sleepLock[threadID]);
2095         }
2096
2097         // If this thread has been assigned work, launch a search
2098         if (threads[threadID].state == THREAD_WORKISWAITING)
2099         {
2100             assert(!allThreadsShouldExit);
2101
2102             threads[threadID].state = THREAD_SEARCHING;
2103
2104             // Copy SplitPoint position and search stack and call search()
2105             // with SplitPoint template parameter set to true.
2106             SearchStack ss[PLY_MAX_PLUS_2];
2107             SplitPoint* tsp = threads[threadID].splitPoint;
2108             Position pos(*tsp->pos, threadID);
2109
2110             memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2111             (ss+1)->sp = tsp;
2112
2113             if (tsp->pvNode)
2114                 search<PV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth, tsp->ply);
2115             else
2116                 search<NonPV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth, tsp->ply);
2117
2118             assert(threads[threadID].state == THREAD_SEARCHING);
2119
2120             threads[threadID].state = THREAD_AVAILABLE;
2121
2122             // Wake up master thread so to allow it to return from the idle loop in
2123             // case we are the last slave of the split point.
2124             if (useSleepingThreads && threadID != tsp->master && threads[tsp->master].state == THREAD_AVAILABLE)
2125                 wake_sleeping_thread(tsp->master);
2126         }
2127
2128         // If this thread is the master of a split point and all slaves have
2129         // finished their work at this split point, return from the idle loop.
2130         for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2131         allFinished = (i == activeThreads);
2132
2133         if (allFinished)
2134         {
2135             // Because sp->slaves[] is reset under lock protection,
2136             // be sure sp->lock has been released before to return.
2137             lock_grab(&(sp->lock));
2138             lock_release(&(sp->lock));
2139
2140             // In helpful master concept a master can help only a sub-tree, and
2141             // because here is all finished is not possible master is booked.
2142             assert(threads[threadID].state == THREAD_AVAILABLE);
2143
2144             threads[threadID].state = THREAD_SEARCHING;
2145             return;
2146         }
2147     }
2148   }
2149
2150
2151   // init_threads() is called during startup. It launches all helper threads,
2152   // and initializes the split point stack and the global locks and condition
2153   // objects.
2154
2155   void ThreadsManager::init_threads() {
2156
2157     int i, arg[MAX_THREADS];
2158     bool ok;
2159
2160     // Initialize global locks
2161     lock_init(&mpLock);
2162
2163     for (i = 0; i < MAX_THREADS; i++)
2164     {
2165         lock_init(&sleepLock[i]);
2166         cond_init(&sleepCond[i]);
2167     }
2168
2169     // Initialize splitPoints[] locks
2170     for (i = 0; i < MAX_THREADS; i++)
2171         for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2172             lock_init(&(threads[i].splitPoints[j].lock));
2173
2174     // Will be set just before program exits to properly end the threads
2175     allThreadsShouldExit = false;
2176
2177     // Threads will be put all threads to sleep as soon as created
2178     activeThreads = 1;
2179
2180     // All threads except the main thread should be initialized to THREAD_INITIALIZING
2181     threads[0].state = THREAD_SEARCHING;
2182     for (i = 1; i < MAX_THREADS; i++)
2183         threads[i].state = THREAD_INITIALIZING;
2184
2185     // Launch the helper threads
2186     for (i = 1; i < MAX_THREADS; i++)
2187     {
2188         arg[i] = i;
2189
2190 #if !defined(_MSC_VER)
2191         pthread_t pthread[1];
2192         ok = (pthread_create(pthread, NULL, init_thread, (void*)(&arg[i])) == 0);
2193         pthread_detach(pthread[0]);
2194 #else
2195         ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&arg[i]), 0, NULL) != NULL);
2196 #endif
2197         if (!ok)
2198         {
2199             cout << "Failed to create thread number " << i << endl;
2200             exit(EXIT_FAILURE);
2201         }
2202
2203         // Wait until the thread has finished launching and is gone to sleep
2204         while (threads[i].state == THREAD_INITIALIZING) {}
2205     }
2206   }
2207
2208
2209   // exit_threads() is called when the program exits. It makes all the
2210   // helper threads exit cleanly.
2211
2212   void ThreadsManager::exit_threads() {
2213
2214     allThreadsShouldExit = true; // Let the woken up threads to exit idle_loop()
2215
2216     // Wake up all the threads and waits for termination
2217     for (int i = 1; i < MAX_THREADS; i++)
2218     {
2219         wake_sleeping_thread(i);
2220         while (threads[i].state != THREAD_TERMINATED) {}
2221     }
2222
2223     // Now we can safely destroy the locks
2224     for (int i = 0; i < MAX_THREADS; i++)
2225         for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2226             lock_destroy(&(threads[i].splitPoints[j].lock));
2227
2228     lock_destroy(&mpLock);
2229
2230     // Now we can safely destroy the wait conditions
2231     for (int i = 0; i < MAX_THREADS; i++)
2232     {
2233         lock_destroy(&sleepLock[i]);
2234         cond_destroy(&sleepCond[i]);
2235     }
2236   }
2237
2238
2239   // cutoff_at_splitpoint() checks whether a beta cutoff has occurred in
2240   // the thread's currently active split point, or in some ancestor of
2241   // the current split point.
2242
2243   bool ThreadsManager::cutoff_at_splitpoint(int threadID) const {
2244
2245     assert(threadID >= 0 && threadID < activeThreads);
2246
2247     SplitPoint* sp = threads[threadID].splitPoint;
2248
2249     for ( ; sp && !sp->betaCutoff; sp = sp->parent) {}
2250     return sp != NULL;
2251   }
2252
2253
2254   // thread_is_available() checks whether the thread with threadID "slave" is
2255   // available to help the thread with threadID "master" at a split point. An
2256   // obvious requirement is that "slave" must be idle. With more than two
2257   // threads, this is not by itself sufficient:  If "slave" is the master of
2258   // some active split point, it is only available as a slave to the other
2259   // threads which are busy searching the split point at the top of "slave"'s
2260   // split point stack (the "helpful master concept" in YBWC terminology).
2261
2262   bool ThreadsManager::thread_is_available(int slave, int master) const {
2263
2264     assert(slave >= 0 && slave < activeThreads);
2265     assert(master >= 0 && master < activeThreads);
2266     assert(activeThreads > 1);
2267
2268     if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2269         return false;
2270
2271     // Make a local copy to be sure doesn't change under our feet
2272     int localActiveSplitPoints = threads[slave].activeSplitPoints;
2273
2274     // No active split points means that the thread is available as
2275     // a slave for any other thread.
2276     if (localActiveSplitPoints == 0 || activeThreads == 2)
2277         return true;
2278
2279     // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2280     // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2281     // could have been set to 0 by another thread leading to an out of bound access.
2282     if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
2283         return true;
2284
2285     return false;
2286   }
2287
2288
2289   // available_thread_exists() tries to find an idle thread which is available as
2290   // a slave for the thread with threadID "master".
2291
2292   bool ThreadsManager::available_thread_exists(int master) const {
2293
2294     assert(master >= 0 && master < activeThreads);
2295     assert(activeThreads > 1);
2296
2297     for (int i = 0; i < activeThreads; i++)
2298         if (thread_is_available(i, master))
2299             return true;
2300
2301     return false;
2302   }
2303
2304
2305   // split() does the actual work of distributing the work at a node between
2306   // several available threads. If it does not succeed in splitting the
2307   // node (because no idle threads are available, or because we have no unused
2308   // split point objects), the function immediately returns. If splitting is
2309   // possible, a SplitPoint object is initialized with all the data that must be
2310   // copied to the helper threads and we tell our helper threads that they have
2311   // been assigned work. This will cause them to instantly leave their idle loops and
2312   // call search().When all threads have returned from search() then split() returns.
2313
2314   template <bool Fake>
2315   void ThreadsManager::split(Position& pos, SearchStack* ss, int ply, Value* alpha,
2316                              const Value beta, Value* bestValue, Depth depth, Move threatMove,
2317                              bool mateThreat, int moveCount, MovePicker* mp, bool pvNode) {
2318     assert(pos.is_ok());
2319     assert(ply > 0 && ply < PLY_MAX);
2320     assert(*bestValue >= -VALUE_INFINITE);
2321     assert(*bestValue <= *alpha);
2322     assert(*alpha < beta);
2323     assert(beta <= VALUE_INFINITE);
2324     assert(depth > DEPTH_ZERO);
2325     assert(pos.thread() >= 0 && pos.thread() < activeThreads);
2326     assert(activeThreads > 1);
2327
2328     int i, master = pos.thread();
2329     Thread& masterThread = threads[master];
2330
2331     lock_grab(&mpLock);
2332
2333     // If no other thread is available to help us, or if we have too many
2334     // active split points, don't split.
2335     if (   !available_thread_exists(master)
2336         || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
2337     {
2338         lock_release(&mpLock);
2339         return;
2340     }
2341
2342     // Pick the next available split point object from the split point stack
2343     SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
2344
2345     // Initialize the split point object
2346     splitPoint.parent = masterThread.splitPoint;
2347     splitPoint.master = master;
2348     splitPoint.betaCutoff = false;
2349     splitPoint.ply = ply;
2350     splitPoint.depth = depth;
2351     splitPoint.threatMove = threatMove;
2352     splitPoint.mateThreat = mateThreat;
2353     splitPoint.alpha = *alpha;
2354     splitPoint.beta = beta;
2355     splitPoint.pvNode = pvNode;
2356     splitPoint.bestValue = *bestValue;
2357     splitPoint.mp = mp;
2358     splitPoint.moveCount = moveCount;
2359     splitPoint.pos = &pos;
2360     splitPoint.nodes = 0;
2361     splitPoint.ss = ss;
2362     for (i = 0; i < activeThreads; i++)
2363         splitPoint.slaves[i] = 0;
2364
2365     masterThread.splitPoint = &splitPoint;
2366
2367     // If we are here it means we are not available
2368     assert(masterThread.state != THREAD_AVAILABLE);
2369
2370     int workersCnt = 1; // At least the master is included
2371
2372     // Allocate available threads setting state to THREAD_BOOKED
2373     for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
2374         if (thread_is_available(i, master))
2375         {
2376             threads[i].state = THREAD_BOOKED;
2377             threads[i].splitPoint = &splitPoint;
2378             splitPoint.slaves[i] = 1;
2379             workersCnt++;
2380         }
2381
2382     assert(Fake || workersCnt > 1);
2383
2384     // We can release the lock because slave threads are already booked and master is not available
2385     lock_release(&mpLock);
2386
2387     // Tell the threads that they have work to do. This will make them leave
2388     // their idle loop.
2389     for (i = 0; i < activeThreads; i++)
2390         if (i == master || splitPoint.slaves[i])
2391         {
2392             assert(i == master || threads[i].state == THREAD_BOOKED);
2393
2394             threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2395
2396             if (useSleepingThreads && i != master)
2397                 wake_sleeping_thread(i);
2398         }
2399
2400     // Everything is set up. The master thread enters the idle loop, from
2401     // which it will instantly launch a search, because its state is
2402     // THREAD_WORKISWAITING.  We send the split point as a second parameter to the
2403     // idle loop, which means that the main thread will return from the idle
2404     // loop when all threads have finished their work at this split point.
2405     idle_loop(master, &splitPoint);
2406
2407     // We have returned from the idle loop, which means that all threads are
2408     // finished. Update alpha and bestValue, and return.
2409     lock_grab(&mpLock);
2410
2411     *alpha = splitPoint.alpha;
2412     *bestValue = splitPoint.bestValue;
2413     masterThread.activeSplitPoints--;
2414     masterThread.splitPoint = splitPoint.parent;
2415     pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);
2416
2417     lock_release(&mpLock);
2418   }
2419
2420
2421   // wake_sleeping_thread() wakes up the thread with the given threadID
2422   // when it is time to start a new search.
2423
2424   void ThreadsManager::wake_sleeping_thread(int threadID) {
2425
2426      lock_grab(&sleepLock[threadID]);
2427      cond_signal(&sleepCond[threadID]);
2428      lock_release(&sleepLock[threadID]);
2429   }
2430
2431
2432   /// RootMove and RootMoveList method's definitions
2433
2434   RootMove::RootMove() {
2435
2436     nodes = 0;
2437     pv_score = non_pv_score = -VALUE_INFINITE;
2438     pv[0] = MOVE_NONE;
2439   }
2440
2441   RootMove& RootMove::operator=(const RootMove& rm) {
2442
2443     const Move* src = rm.pv;
2444     Move* dst = pv;
2445
2446     // Avoid a costly full rm.pv[] copy
2447     do *dst++ = *src; while (*src++ != MOVE_NONE);
2448
2449     nodes = rm.nodes;
2450     pv_score = rm.pv_score;
2451     non_pv_score = rm.non_pv_score;
2452     return *this;
2453   }
2454
2455   // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2456   // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2457   // allow to always have a ponder move even when we fail high at root and also a
2458   // long PV to print that is important for position analysis.
2459
2460   void RootMove::extract_pv_from_tt(Position& pos) {
2461
2462     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2463     TTEntry* tte;
2464     int ply = 1;
2465
2466     assert(pv[0] != MOVE_NONE && move_is_legal(pos, pv[0]));
2467
2468     pos.do_move(pv[0], *st++);
2469
2470     while (   (tte = TT.retrieve(pos.get_key())) != NULL
2471            && tte->move() != MOVE_NONE
2472            && move_is_legal(pos, tte->move())
2473            && ply < PLY_MAX
2474            && (!pos.is_draw() || ply < 2))
2475     {
2476         pv[ply] = tte->move();
2477         pos.do_move(pv[ply++], *st++);
2478     }
2479     pv[ply] = MOVE_NONE;
2480
2481     do pos.undo_move(pv[--ply]); while (ply);
2482   }
2483
2484   // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2485   // the PV back into the TT. This makes sure the old PV moves are searched
2486   // first, even if the old TT entries have been overwritten.
2487
2488   void RootMove::insert_pv_in_tt(Position& pos) {
2489
2490     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2491     TTEntry* tte;
2492     Key k;
2493     Value v, m = VALUE_NONE;
2494     int ply = 0;
2495
2496     assert(pv[0] != MOVE_NONE && move_is_legal(pos, pv[0]));
2497
2498     do {
2499         k = pos.get_key();
2500         tte = TT.retrieve(k);
2501
2502         // Don't overwrite existing correct entries
2503         if (!tte || tte->move() != pv[ply])
2504         {
2505             v = (pos.is_check() ? VALUE_NONE : evaluate(pos, m));
2506             TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2507         }
2508         pos.do_move(pv[ply], *st++);
2509
2510     } while (pv[++ply] != MOVE_NONE);
2511
2512     do pos.undo_move(pv[--ply]); while (ply);
2513   }
2514
2515   // pv_info_to_uci() returns a string with information on the current PV line
2516   // formatted according to UCI specification. It is called at each iteration
2517   // or after a new pv is found.
2518
2519   std::string RootMove::pv_info_to_uci(Position& pos, int depth, Value alpha, Value beta, int pvLine) {
2520
2521     std::stringstream s, l;
2522     Move* m = pv;
2523
2524     while (*m != MOVE_NONE)
2525         l << *m++ << " ";
2526
2527     s << "info depth " << depth
2528       << " seldepth " << int(m - pv)
2529       << " multipv " << pvLine + 1
2530       << " score " << value_to_uci(pv_score)
2531       << (pv_score >= beta ? " lowerbound" : pv_score <= alpha ? " upperbound" : "")
2532       << speed_to_uci(pos.nodes_searched())
2533       << " pv "    << l.str();
2534
2535     return s.str();
2536   }
2537
2538
2539   void RootMoveList::init(Position& pos, Move searchMoves[]) {
2540
2541     MoveStack mlist[MOVES_MAX];
2542     Move* sm;
2543
2544     clear();
2545     bestMoveChanges = 0;
2546
2547     // Generate all legal moves and add them to RootMoveList
2548     MoveStack* last = generate<MV_LEGAL>(pos, mlist);
2549     for (MoveStack* cur = mlist; cur != last; cur++)
2550     {
2551         // If we have a searchMoves[] list then verify cur->move
2552         // is in the list before to add it.
2553         for (sm = searchMoves; *sm && *sm != cur->move; sm++) {}
2554
2555         if (searchMoves[0] && *sm != cur->move)
2556             continue;
2557
2558         RootMove rm;
2559         rm.pv[0] = cur->move;
2560         rm.pv[1] = MOVE_NONE;
2561         rm.pv_score = -VALUE_INFINITE;
2562         push_back(rm);
2563     }
2564   }
2565
2566 } // namespace