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