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