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