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