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