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