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