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