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