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