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