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