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