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