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