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