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