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