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