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