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