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