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