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