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