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