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