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