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