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