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