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