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