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