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