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