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