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