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