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