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