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