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