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