]> git.sesse.net Git - stockfish/blob - src/search.cpp
Revert per-thread history tables
[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
147   // search 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   // The main transposition table
193   TranspositionTable TT;
194
195
196   /// Variables initialized by UCI options
197
198   // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
199   int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
200
201   // Depth limit for use of dynamic threat detection
202   Depth ThreatDepth; // heavy SMP read access
203
204   // Last seconds noise filtering (LSN)
205   bool UseLSNFiltering;
206   bool looseOnTime = false;
207   int LSNTime; // In milliseconds
208   Value LSNValue;
209
210   // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
211   // There is heavy SMP read access on these arrays
212   Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
213   Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
214
215   // Iteration counters
216   int Iteration;
217   BetaCounterType BetaCounter; // has per-thread internal data
218
219   // Scores and number of times the best move changed for each iteration
220   IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
221   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
222
223   // MultiPV mode
224   int MultiPV;
225
226   // Time managment variables
227   int SearchStartTime;
228   int MaxNodes, MaxDepth;
229   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
230   Move EasyMove;
231   int RootMoveNumber;
232   bool InfiniteSearch;
233   bool PonderSearch;
234   bool StopOnPonderhit;
235   bool AbortSearch; // heavy SMP read access
236   bool Quit;
237   bool FailHigh;
238   bool FailLow;
239   bool Problem;
240   bool PonderingEnabled;
241   int ExactMaxTime;
242
243   // Show current line?
244   bool ShowCurrentLine;
245
246   // Log file
247   bool UseLogFile;
248   std::ofstream LogFile;
249
250   // MP related variables
251   int ActiveThreads = 1;
252   Depth MinimumSplitDepth;
253   int MaxThreadsPerSplitPoint;
254   Thread Threads[THREAD_MAX];
255   Lock MPLock;
256   Lock IOLock;
257   bool AllThreadsShouldExit = false;
258   const int MaxActiveSplitPoints = 8;
259   SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
260   bool Idle = true;
261
262 #if !defined(_MSC_VER)
263   pthread_cond_t WaitCond;
264   pthread_mutex_t WaitLock;
265 #else
266   HANDLE SitIdleEvent[THREAD_MAX];
267 #endif
268
269   // Node counters, used only by thread[0] but try to keep in different
270   // cache lines (64 bytes each) from the heavy SMP read accessed variables.
271   int NodesSincePoll;
272   int NodesBetweenPolls = 30000;
273
274   // History table
275   History H;
276
277
278   /// Functions
279
280   Value id_loop(const Position& pos, Move searchMoves[]);
281   Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
282   Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
283   Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
284   Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
285   void sp_search(SplitPoint* sp, int threadID);
286   void sp_search_pv(SplitPoint* sp, int threadID);
287   void init_node(SearchStack ss[], int ply, int threadID);
288   void update_pv(SearchStack ss[], int ply);
289   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
290   bool connected_moves(const Position& pos, Move m1, Move m2);
291   bool value_is_mate(Value value);
292   bool move_is_killer(Move m, const SearchStack& ss);
293   Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
294   bool ok_to_do_nullmove(const Position& pos);
295   bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
296   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
297   bool ok_to_history(const Position& pos, Move m);
298   void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
299   void update_killers(Move m, SearchStack& ss);
300
301   bool fail_high_ply_1();
302   int current_search_time();
303   int nps();
304   void poll();
305   void ponderhit();
306   void print_current_line(SearchStack ss[], int ply, int threadID);
307   void wait_for_stop_or_ponderhit();
308
309   void idle_loop(int threadID, SplitPoint* waitSp);
310   void init_split_point_stack();
311   void destroy_split_point_stack();
312   bool thread_should_stop(int threadID);
313   bool thread_is_available(int slave, int master);
314   bool idle_thread_exists(int master);
315   bool split(const Position& pos, SearchStack* ss, int ply,
316              Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
317              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
318   void wake_sleeping_threads();
319
320 #if !defined(_MSC_VER)
321   void *init_thread(void *threadID);
322 #else
323   DWORD WINAPI init_thread(LPVOID threadID);
324 #endif
325
326 }
327
328
329 ////
330 //// Functions
331 ////
332
333 /// think() is the external interface to Stockfish's search, and is called when
334 /// the program receives the UCI 'go' command. It initializes various
335 /// search-related global variables, and calls root_search(). It returns false
336 /// when a quit command is received during the search.
337
338 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
339            int time[], int increment[], int movesToGo, int maxDepth,
340            int maxNodes, int maxTime, Move searchMoves[]) {
341
342   // Look for a book move
343   if (!infinite && !ponder && get_option_value_bool("OwnBook"))
344   {
345       Move bookMove;
346       if (get_option_value_string("Book File") != OpeningBook.file_name())
347           OpeningBook.open("book.bin");
348
349       bookMove = OpeningBook.get_move(pos);
350       if (bookMove != MOVE_NONE)
351       {
352           std::cout << "bestmove " << bookMove << std::endl;
353           return true;
354       }
355   }
356
357   // Initialize global search variables
358   Idle = false;
359   SearchStartTime = get_system_time();
360   EasyMove = MOVE_NONE;
361   for (int i = 0; i < THREAD_MAX; i++)
362   {
363       Threads[i].nodes = 0ULL;
364       Threads[i].failHighPly1 = false;
365   }
366   NodesSincePoll = 0;
367   InfiniteSearch = infinite;
368   PonderSearch = ponder;
369   StopOnPonderhit = false;
370   AbortSearch = false;
371   Quit = false;
372   FailHigh = false;
373   FailLow = false;
374   Problem = false;
375   ExactMaxTime = maxTime;
376
377   // Read UCI option values
378   TT.set_size(get_option_value_int("Hash"));
379   if (button_was_pressed("Clear Hash"))
380       TT.clear();
381
382   PonderingEnabled = get_option_value_bool("Ponder");
383   MultiPV = get_option_value_int("MultiPV");
384
385   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
386   CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
387
388   SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
389   SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
390
391   PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
392   PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
393
394   PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
395   PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
396
397   PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
398   PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
399
400   MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
401   MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
402
403   LMRPVMoves    = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
404   LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
405   ThreatDepth   = get_option_value_int("Threat Depth") * OnePly;
406
407   Chess960 = get_option_value_bool("UCI_Chess960");
408   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
409   UseLogFile = get_option_value_bool("Use Search Log");
410   if (UseLogFile)
411       LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
412
413   UseLSNFiltering = get_option_value_bool("LSN filtering");
414   LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
415   LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
416
417   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
418   MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
419
420   read_weights(pos.side_to_move());
421
422   int newActiveThreads = get_option_value_int("Threads");
423   if (newActiveThreads != ActiveThreads)
424   {
425       ActiveThreads = newActiveThreads;
426       init_eval(ActiveThreads);
427   }
428
429   // Wake up sleeping threads
430   wake_sleeping_threads();
431
432   for (int i = 1; i < ActiveThreads; i++)
433       assert(thread_is_available(i, 0));
434
435   // Set thinking time
436   int myTime = time[side_to_move];
437   int myIncrement = increment[side_to_move];
438
439   if (!movesToGo) // Sudden death time control
440   {
441       if (myIncrement)
442       {
443           MaxSearchTime = myTime / 30 + myIncrement;
444           AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
445       } else { // Blitz game without increment
446           MaxSearchTime = myTime / 30;
447           AbsoluteMaxSearchTime = myTime / 8;
448       }
449   }
450   else // (x moves) / (y minutes)
451   {
452       if (movesToGo == 1)
453       {
454           MaxSearchTime = myTime / 2;
455           AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
456       } else {
457           MaxSearchTime = myTime / Min(movesToGo, 20);
458           AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
459       }
460   }
461
462   if (PonderingEnabled)
463   {
464       MaxSearchTime += MaxSearchTime / 4;
465       MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
466   }
467
468   // Fixed depth or fixed number of nodes?
469   MaxDepth = maxDepth;
470   if (MaxDepth)
471       InfiniteSearch = true; // HACK
472
473   MaxNodes = maxNodes;
474   if (MaxNodes)
475   {
476       NodesBetweenPolls = Min(MaxNodes, 30000);
477       InfiniteSearch = true; // HACK
478   }
479   else
480       NodesBetweenPolls = 30000;
481
482
483   // Write information to search log file
484   if (UseLogFile)
485       LogFile << "Searching: " << pos.to_fen() << std::endl
486               << "infinite: "  << infinite
487               << " ponder: "   << ponder
488               << " time: "     << myTime
489               << " increment: " << myIncrement
490               << " moves to go: " << movesToGo << std::endl;
491
492
493   // We're ready to start thinking. Call the iterative deepening loop function
494   if (!looseOnTime)
495   {
496       Value v = id_loop(pos, searchMoves);
497       looseOnTime = (   UseLSNFiltering
498                      && myTime < LSNTime
499                      && myIncrement == 0
500                      && v < -LSNValue);
501   }
502   else
503   {
504       looseOnTime = false; // reset for next match
505       while (SearchStartTime + myTime + 1000 > get_system_time())
506           ; // wait here
507       id_loop(pos, searchMoves); // to fail gracefully
508   }
509
510   if (UseLogFile)
511       LogFile.close();
512
513   Idle = true;
514   return !Quit;
515 }
516
517
518 /// init_threads() is called during startup.  It launches all helper threads,
519 /// and initializes the split point stack and the global locks and condition
520 /// objects.
521
522 void init_threads() {
523
524   volatile int i;
525
526 #if !defined(_MSC_VER)
527   pthread_t pthread[1];
528 #endif
529
530   for (i = 0; i < THREAD_MAX; i++)
531       Threads[i].activeSplitPoints = 0;
532
533   // Initialize global locks
534   lock_init(&MPLock, NULL);
535   lock_init(&IOLock, NULL);
536
537   init_split_point_stack();
538
539 #if !defined(_MSC_VER)
540   pthread_mutex_init(&WaitLock, NULL);
541   pthread_cond_init(&WaitCond, NULL);
542 #else
543   for (i = 0; i < THREAD_MAX; i++)
544       SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
545 #endif
546
547   // All threads except the main thread should be initialized to idle state
548   for (i = 1; i < THREAD_MAX; i++)
549   {
550       Threads[i].stop = false;
551       Threads[i].workIsWaiting = false;
552       Threads[i].idle = true;
553       Threads[i].running = false;
554   }
555
556   // Launch the helper threads
557   for(i = 1; i < THREAD_MAX; i++)
558   {
559 #if !defined(_MSC_VER)
560       pthread_create(pthread, NULL, init_thread, (void*)(&i));
561 #else
562       DWORD iID[1];
563       CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
564 #endif
565
566       // Wait until the thread has finished launching
567       while (!Threads[i].running);
568   }
569 }
570
571
572 /// stop_threads() is called when the program exits.  It makes all the
573 /// helper threads exit cleanly.
574
575 void stop_threads() {
576
577   ActiveThreads = THREAD_MAX;  // HACK
578   Idle = false;  // HACK
579   wake_sleeping_threads();
580   AllThreadsShouldExit = true;
581   for (int i = 1; i < THREAD_MAX; i++)
582   {
583       Threads[i].stop = true;
584       while(Threads[i].running);
585   }
586   destroy_split_point_stack();
587 }
588
589
590 /// nodes_searched() returns the total number of nodes searched so far in
591 /// the current search.
592
593 int64_t nodes_searched() {
594
595   int64_t result = 0ULL;
596   for (int i = 0; i < ActiveThreads; i++)
597       result += Threads[i].nodes;
598   return result;
599 }
600
601
602 // SearchStack::init() initializes a search stack. Used at the beginning of a
603 // new search from the root.
604 void SearchStack::init(int ply) {
605
606   pv[ply] = pv[ply + 1] = MOVE_NONE;
607   currentMove = threatMove = MOVE_NONE;
608   reduction = Depth(0);
609 }
610
611 void SearchStack::initKillers() {
612
613   mateKiller = MOVE_NONE;
614   for (int i = 0; i < KILLER_MAX; i++)
615       killers[i] = MOVE_NONE;
616 }
617
618 namespace {
619
620   // id_loop() is the main iterative deepening loop.  It calls root_search
621   // repeatedly with increasing depth until the allocated thinking time has
622   // been consumed, the user stops the search, or the maximum search depth is
623   // reached.
624
625   Value id_loop(const Position& pos, Move searchMoves[]) {
626
627     Position p(pos);
628     SearchStack ss[PLY_MAX_PLUS_2];
629
630     // searchMoves are verified, copied, scored and sorted
631     RootMoveList rml(p, searchMoves);
632
633     // Initialize
634     TT.new_search();
635     H.clear();
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 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
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, 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_is_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, 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, 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_is_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))
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_is_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, 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, 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_is_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_is_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_is_promotion(move)
1668           &&  moveCount >= 2 + int(sp->depth)
1669           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
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_is_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_is_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
2054     assert(ply >= 0 && ply < PLY_MAX);
2055     assert(threadID >= 0 && threadID < ActiveThreads);
2056
2057     Threads[threadID].nodes++;
2058
2059     if (threadID == 0)
2060     {
2061         NodesSincePoll++;
2062         if (NodesSincePoll >= NodesBetweenPolls)
2063         {
2064             poll();
2065             NodesSincePoll = 0;
2066         }
2067     }
2068     ss[ply].init(ply);
2069     ss[ply+2].initKillers();
2070
2071     if (Threads[threadID].printCurrentLine)
2072         print_current_line(ss, ply, threadID);
2073   }
2074
2075
2076   // update_pv() is called whenever a search returns a value > alpha.  It
2077   // updates the PV in the SearchStack object corresponding to the current
2078   // node.
2079
2080   void update_pv(SearchStack ss[], int ply) {
2081     assert(ply >= 0 && ply < PLY_MAX);
2082
2083     ss[ply].pv[ply] = ss[ply].currentMove;
2084     int p;
2085     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2086       ss[ply].pv[p] = ss[ply+1].pv[p];
2087     ss[ply].pv[p] = MOVE_NONE;
2088   }
2089
2090
2091   // sp_update_pv() is a variant of update_pv for use at split points.  The
2092   // difference between the two functions is that sp_update_pv also updates
2093   // the PV at the parent node.
2094
2095   void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2096     assert(ply >= 0 && ply < PLY_MAX);
2097
2098     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2099     int p;
2100     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2101       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2102     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2103   }
2104
2105
2106   // connected_moves() tests whether two moves are 'connected' in the sense
2107   // that the first move somehow made the second move possible (for instance
2108   // if the moving piece is the same in both moves).  The first move is
2109   // assumed to be the move that was made to reach the current position, while
2110   // the second move is assumed to be a move from the current position.
2111
2112   bool connected_moves(const Position& pos, Move m1, Move m2) {
2113     Square f1, t1, f2, t2;
2114
2115     assert(move_is_ok(m1));
2116     assert(move_is_ok(m2));
2117
2118     if (m2 == MOVE_NONE)
2119         return false;
2120
2121     // Case 1: The moving piece is the same in both moves
2122     f2 = move_from(m2);
2123     t1 = move_to(m1);
2124     if (f2 == t1)
2125         return true;
2126
2127     // Case 2: The destination square for m2 was vacated by m1
2128     t2 = move_to(m2);
2129     f1 = move_from(m1);
2130     if (t2 == f1)
2131         return true;
2132
2133     // Case 3: Moving through the vacated square
2134     if (   piece_is_slider(pos.piece_on(f2))
2135         && bit_is_set(squares_between(f2, t2), f1))
2136       return true;
2137
2138     // Case 4: The destination square for m2 is attacked by the moving piece in m1
2139     if (pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2140         return true;
2141
2142     // Case 5: Discovered check, checking piece is the piece moved in m1
2143     if (   piece_is_slider(pos.piece_on(t1))
2144         && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2145         && !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())), t2))
2146     {
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         {
2153             if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2154                 return true;
2155         }
2156         else if (pos.type_of_piece_on(t1) == ROOK)
2157         {
2158             if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2159                 return true;
2160         }
2161         else
2162         {
2163             assert(pos.type_of_piece_on(t1) == QUEEN);
2164             if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2165                 return true;
2166         }
2167     }
2168     return false;
2169   }
2170
2171
2172   // value_is_mate() checks if the given value is a mate one
2173   // eventually compensated for the ply.
2174
2175   bool value_is_mate(Value value) {
2176
2177     assert(abs(value) <= VALUE_INFINITE);
2178
2179     return   value <= value_mated_in(PLY_MAX)
2180           || value >= value_mate_in(PLY_MAX);
2181   }
2182
2183
2184   // move_is_killer() checks if the given move is among the
2185   // killer moves of that ply.
2186
2187   bool move_is_killer(Move m, const SearchStack& ss) {
2188
2189       const Move* k = ss.killers;
2190       for (int i = 0; i < KILLER_MAX; i++, k++)
2191           if (*k == m)
2192               return true;
2193
2194       return false;
2195   }
2196
2197
2198   // extension() decides whether a move should be searched with normal depth,
2199   // or with extended depth.  Certain classes of moves (checking moves, in
2200   // particular) are searched with bigger depth than ordinary moves and in
2201   // any case are marked as 'dangerous'. Note that also if a move is not
2202   // extended, as example because the corresponding UCI option is set to zero,
2203   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2204
2205   Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2206                   bool singleReply, bool mateThreat, bool* dangerous) {
2207
2208     assert(m != MOVE_NONE);
2209
2210     Depth result = Depth(0);
2211     *dangerous = check || singleReply || mateThreat;
2212
2213     if (check)
2214         result += CheckExtension[pvNode];
2215
2216     if (singleReply)
2217         result += SingleReplyExtension[pvNode];
2218
2219     if (mateThreat)
2220         result += MateThreatExtension[pvNode];
2221
2222     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2223     {
2224         if (pos.move_is_pawn_push_to_7th(m))
2225         {
2226             result += PawnPushTo7thExtension[pvNode];
2227             *dangerous = true;
2228         }
2229         if (pos.move_is_passed_pawn_push(m))
2230         {
2231             result += PassedPawnExtension[pvNode];
2232             *dangerous = true;
2233         }
2234     }
2235
2236     if (   capture
2237         && pos.type_of_piece_on(move_to(m)) != PAWN
2238         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2239             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2240         && !move_is_promotion(m)
2241         && !move_is_ep(m))
2242     {
2243         result += PawnEndgameExtension[pvNode];
2244         *dangerous = true;
2245     }
2246
2247     if (   pvNode
2248         && capture
2249         && pos.type_of_piece_on(move_to(m)) != PAWN
2250         && pos.see(m) >= 0)
2251     {
2252         result += OnePly/2;
2253         *dangerous = true;
2254     }
2255
2256     return Min(result, OnePly);
2257   }
2258
2259
2260   // ok_to_do_nullmove() looks at the current position and decides whether
2261   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2262   // problems, null moves are not allowed when the side to move has very
2263   // little material left.  Currently, the test is a bit too simple:  Null
2264   // moves are avoided only when the side to move has only pawns left.  It's
2265   // probably a good idea to avoid null moves in at least some more
2266   // complicated endgames, e.g. KQ vs KR.  FIXME
2267
2268   bool ok_to_do_nullmove(const Position& pos) {
2269
2270     return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2271   }
2272
2273
2274   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2275   // non-tactical moves late in the move list close to the leaves are
2276   // candidates for pruning.
2277
2278   bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2279
2280     assert(move_is_ok(m));
2281     assert(threat == MOVE_NONE || move_is_ok(threat));
2282     assert(!move_is_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     Square mfrom, mto, tfrom, tto;
2289
2290     mfrom = move_from(m);
2291     mto = move_to(m);
2292     tfrom = move_from(threat);
2293     tto = move_to(threat);
2294
2295     // Case 1: Castling moves are never pruned
2296     if (move_is_castle(m))
2297         return false;
2298
2299     // Case 2: Don't prune moves which move the threatened piece
2300     if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2301         return false;
2302
2303     // Case 3: If the threatened piece has value less than or equal to the
2304     // value of the threatening piece, don't prune move which defend it.
2305     if (   !PruneDefendingMoves
2306         && threat != MOVE_NONE
2307         && pos.move_is_capture(threat)
2308         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2309             || pos.type_of_piece_on(tfrom) == KING)
2310         && pos.move_attacks_square(m, tto))
2311         return false;
2312
2313     // Case 4: Don't prune moves with good history
2314     if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2315         return false;
2316
2317     // Case 5: If the moving piece in the threatened move is a slider, don't
2318     // prune safe moves which block its ray.
2319     if (  !PruneBlockingMoves
2320         && threat != MOVE_NONE
2321         && piece_is_slider(pos.piece_on(tfrom))
2322         && bit_is_set(squares_between(tfrom, tto), mto)
2323         && pos.see(m) >= 0)
2324         return false;
2325
2326     return true;
2327   }
2328
2329
2330   // ok_to_use_TT() returns true if a transposition table score
2331   // can be used at a given point in search.
2332
2333   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2334
2335     Value v = value_from_tt(tte->value(), ply);
2336
2337     return   (   tte->depth() >= depth
2338               || v >= Max(value_mate_in(100), beta)
2339               || v < Min(value_mated_in(100), beta))
2340
2341           && (   (is_lower_bound(tte->type()) && v >= beta)
2342               || (is_upper_bound(tte->type()) && v < beta));
2343   }
2344
2345
2346   // ok_to_history() returns true if a move m can be stored
2347   // in history. Should be a non capturing move nor a promotion.
2348
2349   bool ok_to_history(const Position& pos, Move m) {
2350
2351     return !pos.move_is_capture(m) && !move_is_promotion(m);
2352   }
2353
2354
2355   // update_history() registers a good move that produced a beta-cutoff
2356   // in history and marks as failures all the other moves of that ply.
2357
2358   void update_history(const Position& pos, Move m, Depth depth,
2359                       Move movesSearched[], int moveCount) {
2360
2361     H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2362
2363     for (int i = 0; i < moveCount - 1; i++)
2364     {
2365         assert(m != movesSearched[i]);
2366         if (ok_to_history(pos, movesSearched[i]))
2367             H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2368     }
2369   }
2370
2371
2372   // update_killers() add a good move that produced a beta-cutoff
2373   // among the killer moves of that ply.
2374
2375   void update_killers(Move m, SearchStack& ss) {
2376
2377     if (m == ss.killers[0])
2378         return;
2379
2380     for (int i = KILLER_MAX - 1; i > 0; i--)
2381         ss.killers[i] = ss.killers[i - 1];
2382
2383     ss.killers[0] = m;
2384   }
2385
2386   // fail_high_ply_1() checks if some thread is currently resolving a fail
2387   // high at ply 1 at the node below the first root node.  This information
2388   // is used for time managment.
2389
2390   bool fail_high_ply_1() {
2391
2392     for(int i = 0; i < ActiveThreads; i++)
2393         if (Threads[i].failHighPly1)
2394             return true;
2395
2396     return false;
2397   }
2398
2399
2400   // current_search_time() returns the number of milliseconds which have passed
2401   // since the beginning of the current search.
2402
2403   int current_search_time() {
2404     return get_system_time() - SearchStartTime;
2405   }
2406
2407
2408   // nps() computes the current nodes/second count.
2409
2410   int nps() {
2411     int t = current_search_time();
2412     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2413   }
2414
2415
2416   // poll() performs two different functions:  It polls for user input, and it
2417   // looks at the time consumed so far and decides if it's time to abort the
2418   // search.
2419
2420   void poll() {
2421
2422     static int lastInfoTime;
2423     int t = current_search_time();
2424
2425     //  Poll for input
2426     if (Bioskey())
2427     {
2428         // We are line oriented, don't read single chars
2429         std::string command;
2430         if (!std::getline(std::cin, command))
2431             command = "quit";
2432
2433         if (command == "quit")
2434         {
2435             AbortSearch = true;
2436             PonderSearch = false;
2437             Quit = true;
2438             return;
2439         }
2440         else if (command == "stop")
2441         {
2442             AbortSearch = true;
2443             PonderSearch = false;
2444         }
2445         else if (command == "ponderhit")
2446             ponderhit();
2447     }
2448     // Print search information
2449     if (t < 1000)
2450         lastInfoTime = 0;
2451
2452     else if (lastInfoTime > t)
2453         // HACK: Must be a new search where we searched less than
2454         // NodesBetweenPolls nodes during the first second of search.
2455         lastInfoTime = 0;
2456
2457     else if (t - lastInfoTime >= 1000)
2458     {
2459         lastInfoTime = t;
2460         lock_grab(&IOLock);
2461         if (dbg_show_mean)
2462             dbg_print_mean();
2463
2464         if (dbg_show_hit_rate)
2465             dbg_print_hit_rate();
2466
2467         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2468                   << " time " << t << " hashfull " << TT.full() << std::endl;
2469         lock_release(&IOLock);
2470         if (ShowCurrentLine)
2471             Threads[0].printCurrentLine = true;
2472     }
2473     // Should we stop the search?
2474     if (PonderSearch)
2475         return;
2476
2477     bool overTime =     t > AbsoluteMaxSearchTime
2478                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2479                      || (  !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2480                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2481
2482     if (   (Iteration >= 3 && (!InfiniteSearch && overTime))
2483         || (ExactMaxTime && t >= ExactMaxTime)
2484         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2485         AbortSearch = true;
2486   }
2487
2488
2489   // ponderhit() is called when the program is pondering (i.e. thinking while
2490   // it's the opponent's turn to move) in order to let the engine know that
2491   // it correctly predicted the opponent's move.
2492
2493   void ponderhit() {
2494
2495     int t = current_search_time();
2496     PonderSearch = false;
2497     if (Iteration >= 3 &&
2498        (!InfiniteSearch && (StopOnPonderhit ||
2499                             t > AbsoluteMaxSearchTime ||
2500                             (RootMoveNumber == 1 &&
2501                              t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2502                             (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2503                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2504       AbortSearch = true;
2505   }
2506
2507
2508   // print_current_line() prints the current line of search for a given
2509   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2510
2511   void print_current_line(SearchStack ss[], int ply, int threadID) {
2512
2513     assert(ply >= 0 && ply < PLY_MAX);
2514     assert(threadID >= 0 && threadID < ActiveThreads);
2515
2516     if (!Threads[threadID].idle)
2517     {
2518         lock_grab(&IOLock);
2519         std::cout << "info currline " << (threadID + 1);
2520         for (int p = 0; p < ply; p++)
2521             std::cout << " " << ss[p].currentMove;
2522
2523         std::cout << std::endl;
2524         lock_release(&IOLock);
2525     }
2526     Threads[threadID].printCurrentLine = false;
2527     if (threadID + 1 < ActiveThreads)
2528         Threads[threadID + 1].printCurrentLine = true;
2529   }
2530
2531
2532   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2533   // while the program is pondering.  The point is to work around a wrinkle in
2534   // the UCI protocol:  When pondering, the engine is not allowed to give a
2535   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2536   // We simply wait here until one of these commands is sent, and return,
2537   // after which the bestmove and pondermove will be printed (in id_loop()).
2538
2539   void wait_for_stop_or_ponderhit() {
2540
2541     std::string command;
2542
2543     while (true)
2544     {
2545         if (!std::getline(std::cin, command))
2546             command = "quit";
2547
2548         if (command == "quit")
2549         {
2550             Quit = true;
2551             break;
2552         }
2553         else if (command == "ponderhit" || command == "stop")
2554             break;
2555     }
2556   }
2557
2558
2559   // idle_loop() is where the threads are parked when they have no work to do.
2560   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2561   // object for which the current thread is the master.
2562
2563   void idle_loop(int threadID, SplitPoint* waitSp) {
2564     assert(threadID >= 0 && threadID < THREAD_MAX);
2565
2566     Threads[threadID].running = true;
2567
2568     while(true) {
2569       if(AllThreadsShouldExit && threadID != 0)
2570         break;
2571
2572       // If we are not thinking, wait for a condition to be signaled instead
2573       // of wasting CPU time polling for work:
2574       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2575 #if !defined(_MSC_VER)
2576         pthread_mutex_lock(&WaitLock);
2577         if(Idle || threadID >= ActiveThreads)
2578           pthread_cond_wait(&WaitCond, &WaitLock);
2579         pthread_mutex_unlock(&WaitLock);
2580 #else
2581         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2582 #endif
2583       }
2584
2585       // If this thread has been assigned work, launch a search
2586       if(Threads[threadID].workIsWaiting) {
2587         Threads[threadID].workIsWaiting = false;
2588         if(Threads[threadID].splitPoint->pvNode)
2589           sp_search_pv(Threads[threadID].splitPoint, threadID);
2590         else
2591           sp_search(Threads[threadID].splitPoint, threadID);
2592         Threads[threadID].idle = true;
2593       }
2594
2595       // If this thread is the master of a split point and all threads have
2596       // finished their work at this split point, return from the idle loop.
2597       if(waitSp != NULL && waitSp->cpus == 0)
2598         return;
2599     }
2600
2601     Threads[threadID].running = false;
2602   }
2603
2604
2605   // init_split_point_stack() is called during program initialization, and
2606   // initializes all split point objects.
2607
2608   void init_split_point_stack() {
2609     for(int i = 0; i < THREAD_MAX; i++)
2610       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2611         SplitPointStack[i][j].parent = NULL;
2612         lock_init(&(SplitPointStack[i][j].lock), NULL);
2613       }
2614   }
2615
2616
2617   // destroy_split_point_stack() is called when the program exits, and
2618   // destroys all locks in the precomputed split point objects.
2619
2620   void destroy_split_point_stack() {
2621     for(int i = 0; i < THREAD_MAX; i++)
2622       for(int j = 0; j < MaxActiveSplitPoints; j++)
2623         lock_destroy(&(SplitPointStack[i][j].lock));
2624   }
2625
2626
2627   // thread_should_stop() checks whether the thread with a given threadID has
2628   // been asked to stop, directly or indirectly.  This can happen if a beta
2629   // cutoff has occured in thre thread's currently active split point, or in
2630   // some ancestor of the current split point.
2631
2632   bool thread_should_stop(int threadID) {
2633     assert(threadID >= 0 && threadID < ActiveThreads);
2634
2635     SplitPoint* sp;
2636
2637     if(Threads[threadID].stop)
2638       return true;
2639     if(ActiveThreads <= 2)
2640       return false;
2641     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2642       if(sp->finished) {
2643         Threads[threadID].stop = true;
2644         return true;
2645       }
2646     return false;
2647   }
2648
2649
2650   // thread_is_available() checks whether the thread with threadID "slave" is
2651   // available to help the thread with threadID "master" at a split point.  An
2652   // obvious requirement is that "slave" must be idle.  With more than two
2653   // threads, this is not by itself sufficient:  If "slave" is the master of
2654   // some active split point, it is only available as a slave to the other
2655   // threads which are busy searching the split point at the top of "slave"'s
2656   // split point stack (the "helpful master concept" in YBWC terminology).
2657
2658   bool thread_is_available(int slave, int master) {
2659     assert(slave >= 0 && slave < ActiveThreads);
2660     assert(master >= 0 && master < ActiveThreads);
2661     assert(ActiveThreads > 1);
2662
2663     if(!Threads[slave].idle || slave == master)
2664       return false;
2665
2666     if(Threads[slave].activeSplitPoints == 0)
2667       // No active split points means that the thread is available as a slave
2668       // for any other thread.
2669       return true;
2670
2671     if(ActiveThreads == 2)
2672       return true;
2673
2674     // Apply the "helpful master" concept if possible.
2675     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2676       return true;
2677
2678     return false;
2679   }
2680
2681
2682   // idle_thread_exists() tries to find an idle thread which is available as
2683   // a slave for the thread with threadID "master".
2684
2685   bool idle_thread_exists(int master) {
2686     assert(master >= 0 && master < ActiveThreads);
2687     assert(ActiveThreads > 1);
2688
2689     for(int i = 0; i < ActiveThreads; i++)
2690       if(thread_is_available(i, master))
2691         return true;
2692     return false;
2693   }
2694
2695
2696   // split() does the actual work of distributing the work at a node between
2697   // several threads at PV nodes.  If it does not succeed in splitting the
2698   // node (because no idle threads are available, or because we have no unused
2699   // split point objects), the function immediately returns false.  If
2700   // splitting is possible, a SplitPoint object is initialized with all the
2701   // data that must be copied to the helper threads (the current position and
2702   // search stack, alpha, beta, the search depth, etc.), and we tell our
2703   // helper threads that they have been assigned work.  This will cause them
2704   // to instantly leave their idle loops and call sp_search_pv().  When all
2705   // threads have returned from sp_search_pv (or, equivalently, when
2706   // splitPoint->cpus becomes 0), split() returns true.
2707
2708   bool split(const Position& p, SearchStack* sstck, int ply,
2709              Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2710              MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2711
2712     assert(p.is_ok());
2713     assert(sstck != NULL);
2714     assert(ply >= 0 && ply < PLY_MAX);
2715     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2716     assert(!pvNode || *alpha < *beta);
2717     assert(*beta <= VALUE_INFINITE);
2718     assert(depth > Depth(0));
2719     assert(master >= 0 && master < ActiveThreads);
2720     assert(ActiveThreads > 1);
2721
2722     SplitPoint* splitPoint;
2723     int i;
2724
2725     lock_grab(&MPLock);
2726
2727     // If no other thread is available to help us, or if we have too many
2728     // active split points, don't split.
2729     if(!idle_thread_exists(master) ||
2730        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2731       lock_release(&MPLock);
2732       return false;
2733     }
2734
2735     // Pick the next available split point object from the split point stack
2736     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2737     Threads[master].activeSplitPoints++;
2738
2739     // Initialize the split point object
2740     splitPoint->parent = Threads[master].splitPoint;
2741     splitPoint->finished = false;
2742     splitPoint->ply = ply;
2743     splitPoint->depth = depth;
2744     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2745     splitPoint->beta = *beta;
2746     splitPoint->pvNode = pvNode;
2747     splitPoint->dcCandidates = dcCandidates;
2748     splitPoint->bestValue = *bestValue;
2749     splitPoint->master = master;
2750     splitPoint->mp = mp;
2751     splitPoint->moves = *moves;
2752     splitPoint->cpus = 1;
2753     splitPoint->pos.copy(p);
2754     splitPoint->parentSstack = sstck;
2755     for(i = 0; i < ActiveThreads; i++)
2756       splitPoint->slaves[i] = 0;
2757
2758     // Copy the current position and the search stack to the master thread
2759     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2760     Threads[master].splitPoint = splitPoint;
2761
2762     // Make copies of the current position and search stack for each thread
2763     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2764         i++)
2765       if(thread_is_available(i, master)) {
2766         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2767         Threads[i].splitPoint = splitPoint;
2768         splitPoint->slaves[i] = 1;
2769         splitPoint->cpus++;
2770       }
2771
2772     // Tell the threads that they have work to do.  This will make them leave
2773     // their idle loop.
2774     for(i = 0; i < ActiveThreads; i++)
2775       if(i == master || splitPoint->slaves[i]) {
2776         Threads[i].workIsWaiting = true;
2777         Threads[i].idle = false;
2778         Threads[i].stop = false;
2779       }
2780
2781     lock_release(&MPLock);
2782
2783     // Everything is set up.  The master thread enters the idle loop, from
2784     // which it will instantly launch a search, because its workIsWaiting
2785     // slot is 'true'.  We send the split point as a second parameter to the
2786     // idle loop, which means that the main thread will return from the idle
2787     // loop when all threads have finished their work at this split point
2788     // (i.e. when // splitPoint->cpus == 0).
2789     idle_loop(master, splitPoint);
2790
2791     // We have returned from the idle loop, which means that all threads are
2792     // finished. Update alpha, beta and bestvalue, and return.
2793     lock_grab(&MPLock);
2794     if(pvNode) *alpha = splitPoint->alpha;
2795     *beta = splitPoint->beta;
2796     *bestValue = splitPoint->bestValue;
2797     Threads[master].stop = false;
2798     Threads[master].idle = false;
2799     Threads[master].activeSplitPoints--;
2800     Threads[master].splitPoint = splitPoint->parent;
2801     lock_release(&MPLock);
2802
2803     return true;
2804   }
2805
2806
2807   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2808   // to start a new search from the root.
2809
2810   void wake_sleeping_threads() {
2811     if(ActiveThreads > 1) {
2812       for(int i = 1; i < ActiveThreads; i++) {
2813         Threads[i].idle = true;
2814         Threads[i].workIsWaiting = false;
2815       }
2816 #if !defined(_MSC_VER)
2817       pthread_mutex_lock(&WaitLock);
2818       pthread_cond_broadcast(&WaitCond);
2819       pthread_mutex_unlock(&WaitLock);
2820 #else
2821       for(int i = 1; i < THREAD_MAX; i++)
2822         SetEvent(SitIdleEvent[i]);
2823 #endif
2824     }
2825   }
2826
2827
2828   // init_thread() is the function which is called when a new thread is
2829   // launched.  It simply calls the idle_loop() function with the supplied
2830   // threadID.  There are two versions of this function; one for POSIX threads
2831   // and one for Windows threads.
2832
2833 #if !defined(_MSC_VER)
2834
2835   void *init_thread(void *threadID) {
2836     idle_loop(*(int *)threadID, NULL);
2837     return NULL;
2838   }
2839
2840 #else
2841
2842   DWORD WINAPI init_thread(LPVOID threadID) {
2843     idle_loop(*(int *)threadID, NULL);
2844     return NULL;
2845   }
2846
2847 #endif
2848
2849 }