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