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