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