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