]> git.sesse.net Git - stockfish/blob - src/search.cpp
Reformat piece values arrays
[stockfish] / src / search.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iostream>
25 #include <sstream>
26
27 #include "book.h"
28 #include "evaluate.h"
29 #include "history.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "notation.h"
33 #include "search.h"
34 #include "timeman.h"
35 #include "thread.h"
36 #include "tt.h"
37 #include "ucioption.h"
38
39 namespace Search {
40
41   volatile SignalsType Signals;
42   LimitsType Limits;
43   std::vector<RootMove> RootMoves;
44   Position RootPosition;
45   Time SearchTime;
46 }
47
48 using std::string;
49 using std::cout;
50 using std::endl;
51 using Eval::evaluate;
52 using namespace Search;
53
54 namespace {
55
56   // Set to true to force running with one thread. Used for debugging
57   const bool FakeSplit = false;
58
59   // Different node types, used as template parameter
60   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
61
62   // Lookup table to check if a Piece is a slider and its access function
63   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
64   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
65
66   // Maximum depth for razoring
67   const Depth RazorDepth = 4 * ONE_PLY;
68
69   // Dynamic razoring margin based on depth
70   inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
71
72   // Maximum depth for use of dynamic threat detection when null move fails low
73   const Depth ThreatDepth = 5 * ONE_PLY;
74
75   // Minimum depth for use of internal iterative deepening
76   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
77
78   // At Non-PV nodes we do an internal iterative deepening search
79   // when the static evaluation is bigger then beta - IIDMargin.
80   const Value IIDMargin = Value(256);
81
82   // Minimum depth for use of singular extension
83   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
84
85   // Futility margin for quiescence search
86   const Value FutilityMarginQS = Value(128);
87
88   // Futility lookup tables (initialized at startup) and their access functions
89   Value FutilityMargins[16][64]; // [depth][moveNumber]
90   int FutilityMoveCounts[32];    // [depth]
91
92   inline Value futility_margin(Depth d, int mn) {
93
94     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
95                            : 2 * VALUE_INFINITE;
96   }
97
98   inline int futility_move_count(Depth d) {
99
100     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
101   }
102
103   // Reduction lookup tables (initialized at startup) and their access function
104   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
105
106   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
107
108     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
109   }
110
111   // Easy move margin. An easy move candidate must be at least this much better
112   // than the second best move.
113   const Value EasyMoveMargin = Value(0x150);
114
115   // This is the minimum interval in msec between two check_time() calls
116   const int TimerResolution = 5;
117
118
119   size_t MultiPV, UCIMultiPV, PVIdx;
120   TimeManager TimeMgr;
121   int BestMoveChanges;
122   int SkillLevel;
123   bool SkillLevelEnabled, Chess960;
124   History H;
125
126
127   template <NodeType NT>
128   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
129
130   template <NodeType NT>
131   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
132
133   void id_loop(Position& pos);
134   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
135   bool connected_moves(const Position& pos, Move m1, Move m2);
136   Value value_to_tt(Value v, int ply);
137   Value value_from_tt(Value v, int ply);
138   bool can_return_tt(const TTEntry* tte, Depth depth, Value ttValue, Value beta);
139   bool connected_threat(const Position& pos, Move m, Move threat);
140   Value refine_eval(const TTEntry* tte, Value ttValue, Value defaultEval);
141   Move do_skill_level();
142   string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
143
144   // is_dangerous() checks whether a move belongs to some classes of known
145   // 'dangerous' moves so that we avoid to prune it.
146   FORCE_INLINE bool is_dangerous(const Position& pos, Move m, bool captureOrPromotion) {
147
148     // Castle move?
149     if (type_of(m) == CASTLE)
150         return true;
151
152     // Passed pawn move?
153     if (   type_of(pos.piece_moved(m)) == PAWN
154         && pos.pawn_is_passed(pos.side_to_move(), to_sq(m)))
155         return true;
156
157     // Entering a pawn endgame?
158     if (    captureOrPromotion
159         &&  type_of(pos.piece_on(to_sq(m))) != PAWN
160         &&  type_of(m) == NORMAL
161         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
162             - PieceValue[Mg][pos.piece_on(to_sq(m))] == VALUE_ZERO))
163         return true;
164
165     return false;
166   }
167
168 } // namespace
169
170
171 /// Search::init() is called during startup to initialize various lookup tables
172
173 void Search::init() {
174
175   int d;  // depth (ONE_PLY == 2)
176   int hd; // half depth (ONE_PLY == 1)
177   int mc; // moveCount
178
179   // Init reductions array
180   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
181   {
182       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
183       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
184       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
185       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
186   }
187
188   // Init futility margins array
189   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
190       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
191
192   // Init futility move count array
193   for (d = 0; d < 32; d++)
194       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
195 }
196
197
198 /// Search::perft() is our utility to verify move generation. All the leaf nodes
199 /// up to the given depth are generated and counted and the sum returned.
200
201 size_t Search::perft(Position& pos, Depth depth) {
202
203   // At the last ply just return the number of legal moves (leaf nodes)
204   if (depth == ONE_PLY)
205       return MoveList<LEGAL>(pos).size();
206
207   StateInfo st;
208   size_t cnt = 0;
209   CheckInfo ci(pos);
210
211   for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
212   {
213       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
214       cnt += perft(pos, depth - ONE_PLY);
215       pos.undo_move(ml.move());
216   }
217
218   return cnt;
219 }
220
221
222 /// Search::think() is the external interface to Stockfish's search, and is
223 /// called by the main thread when the program receives the UCI 'go' command. It
224 /// searches from RootPosition and at the end prints the "bestmove" to output.
225
226 void Search::think() {
227
228   static Book book; // Defined static to initialize the PRNG only once
229
230   Position& pos = RootPosition;
231   Chess960 = pos.is_chess960();
232   Eval::RootColor = pos.side_to_move();
233   TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
234   TT.new_search();
235   H.clear();
236
237   if (RootMoves.empty())
238   {
239       cout << "info depth 0 score "
240            << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << endl;
241
242       RootMoves.push_back(MOVE_NONE);
243       goto finalize;
244   }
245
246   if (Options["OwnBook"] && !Limits.infinite)
247   {
248       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
249
250       if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
251       {
252           std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
253           goto finalize;
254       }
255   }
256
257   UCIMultiPV = Options["MultiPV"];
258   SkillLevel = Options["Skill Level"];
259
260   // Do we have to play with skill handicap? In this case enable MultiPV that
261   // we will use behind the scenes to retrieve a set of possible moves.
262   SkillLevelEnabled = (SkillLevel < 20);
263   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV);
264
265   if (Options["Use Search Log"])
266   {
267       Log log(Options["Search Log Filename"]);
268       log << "\nSearching: "  << pos.to_fen()
269           << "\ninfinite: "   << Limits.infinite
270           << " ponder: "      << Limits.ponder
271           << " time: "        << Limits.time[pos.side_to_move()]
272           << " increment: "   << Limits.inc[pos.side_to_move()]
273           << " moves to go: " << Limits.movestogo
274           << endl;
275   }
276
277   Threads.wake_up();
278
279   // Set best timer interval to avoid lagging under time pressure. Timer is
280   // used to check for remaining available thinking time.
281   if (Limits.use_time_management())
282       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
283   else
284       Threads.set_timer(100);
285
286   // We're ready to start searching. Call the iterative deepening loop function
287   id_loop(pos);
288
289   Threads.set_timer(0); // Stop timer
290   Threads.sleep();
291
292   if (Options["Use Search Log"])
293   {
294       int e = SearchTime.elapsed();
295
296       Log log(Options["Search Log Filename"]);
297       log << "Nodes: "          << pos.nodes_searched()
298           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
299           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
300
301       StateInfo st;
302       pos.do_move(RootMoves[0].pv[0], st);
303       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << endl;
304       pos.undo_move(RootMoves[0].pv[0]);
305   }
306
307 finalize:
308
309   // When we reach max depth we arrive here even without Signals.stop is raised,
310   // but if we are pondering or in infinite search, we shouldn't print the best
311   // move before we are told to do so.
312   if (!Signals.stop && (Limits.ponder || Limits.infinite))
313       pos.this_thread()->wait_for_stop_or_ponderhit();
314
315   // Best move could be MOVE_NONE when searching on a stalemate position
316   cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
317        << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << endl;
318 }
319
320
321 namespace {
322
323   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
324   // with increasing depth until the allocated thinking time has been consumed,
325   // user stops the search, or the maximum search depth is reached.
326
327   void id_loop(Position& pos) {
328
329     Stack ss[MAX_PLY_PLUS_2];
330     int depth, prevBestMoveChanges;
331     Value bestValue, alpha, beta, delta;
332     bool bestMoveNeverChanged = true;
333     Move skillBest = MOVE_NONE;
334
335     memset(ss, 0, 4 * sizeof(Stack));
336     depth = BestMoveChanges = 0;
337     bestValue = delta = -VALUE_INFINITE;
338     ss->currentMove = MOVE_NULL; // Hack to skip update gains
339
340     // Iterative deepening loop until requested to stop or target depth reached
341     while (!Signals.stop && ++depth <= MAX_PLY && (!Limits.depth || depth <= Limits.depth))
342     {
343         // Save last iteration's scores before first PV line is searched and all
344         // the move scores but the (new) PV are set to -VALUE_INFINITE.
345         for (size_t i = 0; i < RootMoves.size(); i++)
346             RootMoves[i].prevScore = RootMoves[i].score;
347
348         prevBestMoveChanges = BestMoveChanges;
349         BestMoveChanges = 0;
350
351         // MultiPV loop. We perform a full root search for each PV line
352         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
353         {
354             // Set aspiration window default width
355             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
356             {
357                 delta = Value(16);
358                 alpha = RootMoves[PVIdx].prevScore - delta;
359                 beta  = RootMoves[PVIdx].prevScore + delta;
360             }
361             else
362             {
363                 alpha = -VALUE_INFINITE;
364                 beta  =  VALUE_INFINITE;
365             }
366
367             // Start with a small aspiration window and, in case of fail high/low,
368             // research with bigger window until not failing high/low anymore.
369             do {
370                 // Search starts from ss+1 to allow referencing (ss-1). This is
371                 // needed by update gains and ss copy when splitting at Root.
372                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
373
374                 // Bring to front the best move. It is critical that sorting is
375                 // done with a stable algorithm because all the values but the first
376                 // and eventually the new best one are set to -VALUE_INFINITE and
377                 // we want to keep the same order for all the moves but the new
378                 // PV that goes to the front. Note that in case of MultiPV search
379                 // the already searched PV lines are preserved.
380                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
381
382                 // In case we have found an exact score and we are going to leave
383                 // the fail high/low loop then reorder the PV moves, otherwise
384                 // leave the last PV move in its position so to be searched again.
385                 // Of course this is needed only in MultiPV search.
386                 if (PVIdx && bestValue > alpha && bestValue < beta)
387                     sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
388
389                 // Write PV back to transposition table in case the relevant
390                 // entries have been overwritten during the search.
391                 for (size_t i = 0; i <= PVIdx; i++)
392                     RootMoves[i].insert_pv_in_tt(pos);
393
394                 // If search has been stopped exit the aspiration window loop.
395                 // Sorting and writing PV back to TT is safe becuase RootMoves
396                 // is still valid, although refers to previous iteration.
397                 if (Signals.stop)
398                     break;
399
400                 // Send full PV info to GUI if we are going to leave the loop or
401                 // if we have a fail high/low and we are deep in the search.
402                 if ((bestValue > alpha && bestValue < beta) || SearchTime.elapsed() > 2000)
403                     cout << uci_pv(pos, depth, alpha, beta) << endl;
404
405                 // In case of failing high/low increase aspiration window and
406                 // research, otherwise exit the fail high/low loop.
407                 if (bestValue >= beta)
408                 {
409                     beta += delta;
410                     delta += delta / 2;
411                 }
412                 else if (bestValue <= alpha)
413                 {
414                     Signals.failedLowAtRoot = true;
415                     Signals.stopOnPonderhit = false;
416
417                     alpha -= delta;
418                     delta += delta / 2;
419                 }
420                 else
421                     break;
422
423                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
424
425             } while (abs(bestValue) < VALUE_KNOWN_WIN);
426         }
427
428         // Skills: Do we need to pick now the best move ?
429         if (SkillLevelEnabled && depth == 1 + SkillLevel)
430             skillBest = do_skill_level();
431
432         if (!Signals.stop && Options["Use Search Log"])
433         {
434             Log log(Options["Search Log Filename"]);
435             log << pretty_pv(pos, depth, bestValue, SearchTime.elapsed(), &RootMoves[0].pv[0])
436                 << endl;
437         }
438
439         // Filter out startup noise when monitoring best move stability
440         if (depth > 2 && BestMoveChanges)
441             bestMoveNeverChanged = false;
442
443         // Do we have time for the next iteration? Can we stop searching now?
444         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.use_time_management())
445         {
446             bool stop = false; // Local variable, not the volatile Signals.stop
447
448             // Take in account some extra time if the best move has changed
449             if (depth > 4 && depth < 50)
450                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
451
452             // Stop search if most of available time is already consumed. We
453             // probably don't have enough time to search the first move at the
454             // next iteration anyway.
455             if (SearchTime.elapsed() > (TimeMgr.available_time() * 62) / 100)
456                 stop = true;
457
458             // Stop search early if one move seems to be much better than others
459             if (    depth >= 12
460                 && !stop
461                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
462                     || SearchTime.elapsed() > (TimeMgr.available_time() * 40) / 100))
463             {
464                 Value rBeta = bestValue - EasyMoveMargin;
465                 (ss+1)->excludedMove = RootMoves[0].pv[0];
466                 (ss+1)->skipNullMove = true;
467                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
468                 (ss+1)->skipNullMove = false;
469                 (ss+1)->excludedMove = MOVE_NONE;
470
471                 if (v < rBeta)
472                     stop = true;
473             }
474
475             if (stop)
476             {
477                 // If we are allowed to ponder do not stop the search now but
478                 // keep pondering until GUI sends "ponderhit" or "stop".
479                 if (Limits.ponder)
480                     Signals.stopOnPonderhit = true;
481                 else
482                     Signals.stop = true;
483             }
484         }
485     }
486
487     // When using skills swap best PV line with the sub-optimal one
488     if (SkillLevelEnabled)
489     {
490         if (skillBest == MOVE_NONE) // Still unassigned ?
491             skillBest = do_skill_level();
492
493         std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), skillBest));
494     }
495   }
496
497
498   // search<>() is the main search function for both PV and non-PV nodes and for
499   // normal and SplitPoint nodes. When called just after a split point the search
500   // is simpler because we have already probed the hash table, done a null move
501   // search, and searched the first move before splitting, we don't have to repeat
502   // all this work again. We also don't need to store anything to the hash table
503   // here: This is taken care of after we return from the split point.
504
505   template <NodeType NT>
506   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
507
508     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
509     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
510     const bool RootNode = (NT == Root || NT == SplitPointRoot);
511
512     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
513     assert((alpha == beta - 1) || PvNode);
514     assert(depth > DEPTH_ZERO);
515
516     Move movesSearched[64];
517     StateInfo st;
518     const TTEntry *tte;
519     Key posKey;
520     Move ttMove, move, excludedMove, bestMove, threatMove;
521     Depth ext, newDepth;
522     Bound bt;
523     Value bestValue, value, oldAlpha, ttValue;
524     Value refinedValue, nullValue, futilityBase, futilityValue;
525     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
526     bool captureOrPromotion, dangerous, doFullDepthSearch;
527     int moveCount = 0, playedMoveCount = 0;
528     Thread* thisThread = pos.this_thread();
529     SplitPoint* sp = NULL;
530
531     refinedValue = bestValue = value = -VALUE_INFINITE;
532     oldAlpha = alpha;
533     inCheck = pos.in_check();
534     ss->ply = (ss-1)->ply + 1;
535
536     // Used to send selDepth info to GUI
537     if (PvNode && thisThread->maxPly < ss->ply)
538         thisThread->maxPly = ss->ply;
539
540     // Step 1. Initialize node
541     if (SpNode)
542     {
543         tte = NULL;
544         ttMove = excludedMove = MOVE_NONE;
545         ttValue = VALUE_ZERO;
546         sp = ss->sp;
547         bestMove = sp->bestMove;
548         threatMove = sp->threatMove;
549         bestValue = sp->bestValue;
550         moveCount = sp->moveCount; // Lock must be held here
551
552         assert(bestValue > -VALUE_INFINITE && moveCount > 0);
553
554         goto split_point_start;
555     }
556     else
557     {
558         ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
559         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
560         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
561
562     }
563
564     // Step 2. Check for aborted search and immediate draw
565     // Enforce node limit here. FIXME: This only works with 1 search thread.
566     if (Limits.nodes && pos.nodes_searched() >= Limits.nodes)
567         Signals.stop = true;
568
569     if ((   Signals.stop
570          || pos.is_draw<false>()
571          || ss->ply > MAX_PLY) && !RootNode)
572         return VALUE_DRAW;
573
574     // Step 3. Mate distance pruning. Even if we mate at the next move our score
575     // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
576     // a shorter mate was found upward in the tree then there is no need to search
577     // further, we will never beat current alpha. Same logic but with reversed signs
578     // applies also in the opposite condition of being mated instead of giving mate,
579     // in this case return a fail-high score.
580     if (!RootNode)
581     {
582         alpha = std::max(mated_in(ss->ply), alpha);
583         beta = std::min(mate_in(ss->ply+1), beta);
584         if (alpha >= beta)
585             return alpha;
586     }
587
588     // Step 4. Transposition table lookup
589     // We don't want the score of a partial search to overwrite a previous full search
590     // TT value, so we use a different position key in case of an excluded move.
591     excludedMove = ss->excludedMove;
592     posKey = excludedMove ? pos.exclusion_key() : pos.key();
593     tte = TT.probe(posKey);
594     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
595     ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_ZERO;
596
597     // At PV nodes we check for exact scores, while at non-PV nodes we check for
598     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
599     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
600     // we should also update RootMoveList to avoid bogus output.
601     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == BOUND_EXACT
602                                     : can_return_tt(tte, depth, ttValue, beta)))
603     {
604         TT.refresh(tte);
605         ss->currentMove = ttMove; // Can be MOVE_NONE
606
607         if (    ttValue >= beta
608             &&  ttMove
609             && !pos.is_capture_or_promotion(ttMove)
610             &&  ttMove != ss->killers[0])
611         {
612             ss->killers[1] = ss->killers[0];
613             ss->killers[0] = ttMove;
614         }
615         return ttValue;
616     }
617
618     // Step 5. Evaluate the position statically and update parent's gain statistics
619     if (inCheck)
620         ss->eval = ss->evalMargin = VALUE_NONE;
621     else if (tte)
622     {
623         assert(tte->static_value() != VALUE_NONE);
624
625         ss->eval = tte->static_value();
626         ss->evalMargin = tte->static_value_margin();
627         refinedValue = refine_eval(tte, ttValue, ss->eval);
628     }
629     else
630     {
631         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
632         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
633     }
634
635     // Update gain for the parent non-capture move given the static position
636     // evaluation before and after the move.
637     if (    (move = (ss-1)->currentMove) != MOVE_NULL
638         &&  (ss-1)->eval != VALUE_NONE
639         &&  ss->eval != VALUE_NONE
640         && !pos.captured_piece_type()
641         &&  type_of(move) == NORMAL)
642     {
643         Square to = to_sq(move);
644         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
645     }
646
647     // Step 6. Razoring (is omitted in PV nodes)
648     if (   !PvNode
649         &&  depth < RazorDepth
650         && !inCheck
651         &&  refinedValue + razor_margin(depth) < beta
652         &&  ttMove == MOVE_NONE
653         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
654         && !pos.pawn_on_7th(pos.side_to_move()))
655     {
656         Value rbeta = beta - razor_margin(depth);
657         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
658         if (v < rbeta)
659             // Logically we should return (v + razor_margin(depth)), but
660             // surprisingly this did slightly weaker in tests.
661             return v;
662     }
663
664     // Step 7. Static null move pruning (is omitted in PV nodes)
665     // We're betting that the opponent doesn't have a move that will reduce
666     // the score by more than futility_margin(depth) if we do a null move.
667     if (   !PvNode
668         && !ss->skipNullMove
669         &&  depth < RazorDepth
670         && !inCheck
671         &&  refinedValue - futility_margin(depth, 0) >= beta
672         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
673         &&  pos.non_pawn_material(pos.side_to_move()))
674         return refinedValue - futility_margin(depth, 0);
675
676     // Step 8. Null move search with verification search (is omitted in PV nodes)
677     if (   !PvNode
678         && !ss->skipNullMove
679         &&  depth > ONE_PLY
680         && !inCheck
681         &&  refinedValue >= beta
682         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
683         &&  pos.non_pawn_material(pos.side_to_move()))
684     {
685         ss->currentMove = MOVE_NULL;
686
687         // Null move dynamic reduction based on depth
688         Depth R = 3 * ONE_PLY + depth / 4;
689
690         // Null move dynamic reduction based on value
691         if (refinedValue - PawnValueMg > beta)
692             R += ONE_PLY;
693
694         pos.do_null_move<true>(st);
695         (ss+1)->skipNullMove = true;
696         nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
697                                       : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
698         (ss+1)->skipNullMove = false;
699         pos.do_null_move<false>(st);
700
701         if (nullValue >= beta)
702         {
703             // Do not return unproven mate scores
704             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
705                 nullValue = beta;
706
707             if (depth < 6 * ONE_PLY)
708                 return nullValue;
709
710             // Do verification search at high depths
711             ss->skipNullMove = true;
712             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
713             ss->skipNullMove = false;
714
715             if (v >= beta)
716                 return nullValue;
717         }
718         else
719         {
720             // The null move failed low, which means that we may be faced with
721             // some kind of threat. If the previous move was reduced, check if
722             // the move that refuted the null move was somehow connected to the
723             // move which was reduced. If a connection is found, return a fail
724             // low score (which will cause the reduced move to fail high in the
725             // parent node, which will trigger a re-search with full depth).
726             threatMove = (ss+1)->currentMove;
727
728             if (   depth < ThreatDepth
729                 && (ss-1)->reduction
730                 && threatMove != MOVE_NONE
731                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
732                 return beta - 1;
733         }
734     }
735
736     // Step 9. ProbCut (is omitted in PV nodes)
737     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
738     // and a reduced search returns a value much above beta, we can (almost) safely
739     // prune the previous move.
740     if (   !PvNode
741         &&  depth >= RazorDepth + ONE_PLY
742         && !inCheck
743         && !ss->skipNullMove
744         &&  excludedMove == MOVE_NONE
745         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
746     {
747         Value rbeta = beta + 200;
748         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
749
750         assert(rdepth >= ONE_PLY);
751         assert((ss-1)->currentMove != MOVE_NONE);
752         assert((ss-1)->currentMove != MOVE_NULL);
753
754         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
755         CheckInfo ci(pos);
756
757         while ((move = mp.next_move<false>()) != MOVE_NONE)
758             if (pos.pl_move_is_legal(move, ci.pinned))
759             {
760                 ss->currentMove = move;
761                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
762                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
763                 pos.undo_move(move);
764                 if (value >= rbeta)
765                     return value;
766             }
767     }
768
769     // Step 10. Internal iterative deepening
770     if (   depth >= IIDDepth[PvNode]
771         && ttMove == MOVE_NONE
772         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
773     {
774         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
775
776         ss->skipNullMove = true;
777         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
778         ss->skipNullMove = false;
779
780         tte = TT.probe(posKey);
781         ttMove = tte ? tte->move() : MOVE_NONE;
782     }
783
784 split_point_start: // At split points actual search starts from here
785
786     MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
787     CheckInfo ci(pos);
788     futilityBase = ss->eval + ss->evalMargin;
789     singularExtensionNode =   !RootNode
790                            && !SpNode
791                            &&  depth >= SingularExtensionDepth[PvNode]
792                            &&  ttMove != MOVE_NONE
793                            && !excludedMove // Recursive singular search is not allowed
794                            && (tte->type() & BOUND_LOWER)
795                            &&  tte->depth() >= depth - 3 * ONE_PLY;
796
797     // Step 11. Loop through moves
798     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
799     while (    bestValue < beta
800            && (move = mp.next_move<SpNode>()) != MOVE_NONE
801            && !thisThread->cutoff_occurred()
802            && !Signals.stop)
803     {
804       assert(is_ok(move));
805
806       if (move == excludedMove)
807           continue;
808
809       // At root obey the "searchmoves" option and skip moves not listed in Root
810       // Move List, as a consequence any illegal move is also skipped. In MultiPV
811       // mode we also skip PV moves which have been already searched.
812       if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
813           continue;
814
815       // At PV and SpNode nodes we want all moves to be legal since the beginning
816       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
817           continue;
818
819       if (SpNode)
820       {
821           moveCount = ++sp->moveCount;
822           lock_release(sp->lock);
823       }
824       else
825           moveCount++;
826
827       if (RootNode)
828       {
829           Signals.firstRootMove = (moveCount == 1);
830
831           if (thisThread == Threads.main_thread() && SearchTime.elapsed() > 2000)
832               cout << "info depth " << depth / ONE_PLY
833                    << " currmove " << move_to_uci(move, Chess960)
834                    << " currmovenumber " << moveCount + PVIdx << endl;
835       }
836
837       isPvMove = (PvNode && moveCount <= 1);
838       captureOrPromotion = pos.is_capture_or_promotion(move);
839       givesCheck = pos.move_gives_check(move, ci);
840       dangerous = givesCheck || is_dangerous(pos, move, captureOrPromotion);
841       ext = DEPTH_ZERO;
842
843       // Step 12. Extend checks and, in PV nodes, also dangerous moves
844       if (PvNode && dangerous)
845           ext = ONE_PLY;
846
847       else if (givesCheck && pos.see_sign(move) >= 0)
848           ext = ONE_PLY / 2;
849
850       // Singular extension search. If all moves but one fail low on a search of
851       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
852       // is singular and should be extended. To verify this we do a reduced search
853       // on all the other moves but the ttMove, if result is lower than ttValue minus
854       // a margin then we extend ttMove.
855       if (    singularExtensionNode
856           && !ext
857           &&  move == ttMove
858           &&  pos.pl_move_is_legal(move, ci.pinned)
859           &&  abs(ttValue) < VALUE_KNOWN_WIN)
860       {
861           Value rBeta = ttValue - int(depth);
862           ss->excludedMove = move;
863           ss->skipNullMove = true;
864           value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
865           ss->skipNullMove = false;
866           ss->excludedMove = MOVE_NONE;
867
868           if (value < rBeta)
869               ext = ONE_PLY;
870       }
871
872       // Update current move (this must be done after singular extension search)
873       newDepth = depth - ONE_PLY + ext;
874
875       // Step 13. Futility pruning (is omitted in PV nodes)
876       if (   !PvNode
877           && !captureOrPromotion
878           && !inCheck
879           && !dangerous
880           &&  move != ttMove
881           && (bestValue > VALUE_MATED_IN_MAX_PLY || bestValue == -VALUE_INFINITE))
882       {
883           // Move count based pruning
884           if (   moveCount >= futility_move_count(depth)
885               && (!threatMove || !connected_threat(pos, move, threatMove)))
886           {
887               if (SpNode)
888                   lock_grab(sp->lock);
889
890               continue;
891           }
892
893           // Value based pruning
894           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
895           // but fixing this made program slightly weaker.
896           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
897           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
898                          + H.gain(pos.piece_moved(move), to_sq(move));
899
900           if (futilityValue < beta)
901           {
902               if (SpNode)
903                   lock_grab(sp->lock);
904
905               continue;
906           }
907
908           // Prune moves with negative SEE at low depths
909           if (   predictedDepth < 2 * ONE_PLY
910               && pos.see_sign(move) < 0)
911           {
912               if (SpNode)
913                   lock_grab(sp->lock);
914
915               continue;
916           }
917       }
918
919       // Check for legality only before to do the move
920       if (!pos.pl_move_is_legal(move, ci.pinned))
921       {
922           moveCount--;
923           continue;
924       }
925
926       ss->currentMove = move;
927       if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
928           movesSearched[playedMoveCount++] = move;
929
930       // Step 14. Make the move
931       pos.do_move(move, st, ci, givesCheck);
932
933       // Step 15. Reduced depth search (LMR). If the move fails high will be
934       // re-searched at full depth.
935       if (    depth > 3 * ONE_PLY
936           && !isPvMove
937           && !captureOrPromotion
938           && !dangerous
939           &&  ss->killers[0] != move
940           &&  ss->killers[1] != move)
941       {
942           ss->reduction = reduction<PvNode>(depth, moveCount);
943           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
944           alpha = SpNode ? sp->alpha : alpha;
945
946           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
947
948           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
949           ss->reduction = DEPTH_ZERO;
950       }
951       else
952           doFullDepthSearch = !isPvMove;
953
954       // Step 16. Full depth search, when LMR is skipped or fails high
955       if (doFullDepthSearch)
956       {
957           alpha = SpNode ? sp->alpha : alpha;
958           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
959                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
960       }
961
962       // Only for PV nodes do a full PV search on the first move or after a fail
963       // high, in the latter case search only if value < beta, otherwise let the
964       // parent node to fail low with value <= alpha and to try another move.
965       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
966           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
967                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
968
969       // Step 17. Undo move
970       pos.undo_move(move);
971
972       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
973
974       // Step 18. Check for new best move
975       if (SpNode)
976       {
977           lock_grab(sp->lock);
978           bestValue = sp->bestValue;
979           alpha = sp->alpha;
980       }
981
982       // Finished searching the move. If Signals.stop is true, the search
983       // was aborted because the user interrupted the search or because we
984       // ran out of time. In this case, the return value of the search cannot
985       // be trusted, and we don't update the best move and/or PV.
986       if (RootNode && !Signals.stop)
987       {
988           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
989
990           // PV move or new best move ?
991           if (isPvMove || value > alpha)
992           {
993               rm.score = value;
994               rm.extract_pv_from_tt(pos);
995
996               // We record how often the best move has been changed in each
997               // iteration. This information is used for time management: When
998               // the best move changes frequently, we allocate some more time.
999               if (!isPvMove && MultiPV == 1)
1000                   BestMoveChanges++;
1001           }
1002           else
1003               // All other moves but the PV are set to the lowest value, this
1004               // is not a problem when sorting becuase sort is stable and move
1005               // position in the list is preserved, just the PV is pushed up.
1006               rm.score = -VALUE_INFINITE;
1007
1008       }
1009
1010       if (value > bestValue)
1011       {
1012           bestValue = value;
1013           bestMove = move;
1014
1015           if (   PvNode
1016               && value > alpha
1017               && value < beta) // We want always alpha < beta
1018               alpha = value;
1019
1020           if (SpNode && !thisThread->cutoff_occurred())
1021           {
1022               sp->bestValue = value;
1023               sp->bestMove = move;
1024               sp->alpha = alpha;
1025
1026               if (value >= beta)
1027                   sp->cutoff = true;
1028           }
1029       }
1030
1031       // Step 19. Check for split
1032       if (   !SpNode
1033           &&  depth >= Threads.min_split_depth()
1034           &&  bestValue < beta
1035           &&  Threads.available_slave_exists(thisThread)
1036           && !Signals.stop
1037           && !thisThread->cutoff_occurred())
1038           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1039                                                depth, threatMove, moveCount, &mp, NT);
1040     }
1041
1042     // Step 20. Check for mate and stalemate
1043     // All legal moves have been searched and if there are no legal moves, it
1044     // must be mate or stalemate. Note that we can have a false positive in
1045     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1046     // harmless because return value is discarded anyhow in the parent nodes.
1047     // If we are in a singular extension search then return a fail low score.
1048     if (!moveCount)
1049         return excludedMove ? oldAlpha : inCheck ? mated_in(ss->ply) : VALUE_DRAW;
1050
1051     // If we have pruned all the moves without searching return a fail-low score
1052     if (bestValue == -VALUE_INFINITE)
1053     {
1054         assert(!playedMoveCount);
1055
1056         bestValue = oldAlpha;
1057     }
1058
1059     // Step 21. Update tables
1060     // Update transposition table entry, killers and history
1061     if (!SpNode && !Signals.stop && !thisThread->cutoff_occurred())
1062     {
1063         move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1064         bt   = bestValue <= oldAlpha ? BOUND_UPPER
1065              : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1066
1067         TT.store(posKey, value_to_tt(bestValue, ss->ply), bt, depth, move, ss->eval, ss->evalMargin);
1068
1069         // Update killers and history for non capture cut-off moves
1070         if (    bestValue >= beta
1071             && !pos.is_capture_or_promotion(move)
1072             && !inCheck)
1073         {
1074             if (move != ss->killers[0])
1075             {
1076                 ss->killers[1] = ss->killers[0];
1077                 ss->killers[0] = move;
1078             }
1079
1080             // Increase history value of the cut-off move
1081             Value bonus = Value(int(depth) * int(depth));
1082             H.add(pos.piece_moved(move), to_sq(move), bonus);
1083
1084             // Decrease history of all the other played non-capture moves
1085             for (int i = 0; i < playedMoveCount - 1; i++)
1086             {
1087                 Move m = movesSearched[i];
1088                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1089             }
1090         }
1091     }
1092
1093     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1094
1095     return bestValue;
1096   }
1097
1098
1099   // qsearch() is the quiescence search function, which is called by the main
1100   // search function when the remaining depth is zero (or, to be more precise,
1101   // less than ONE_PLY).
1102
1103   template <NodeType NT>
1104   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1105
1106     const bool PvNode = (NT == PV);
1107
1108     assert(NT == PV || NT == NonPV);
1109     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1110     assert((alpha == beta - 1) || PvNode);
1111     assert(depth <= DEPTH_ZERO);
1112
1113     StateInfo st;
1114     Move ttMove, move, bestMove;
1115     Value ttValue, bestValue, value, evalMargin, futilityValue, futilityBase;
1116     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1117     const TTEntry* tte;
1118     Depth ttDepth;
1119     Bound bt;
1120     Value oldAlpha = alpha;
1121
1122     ss->currentMove = bestMove = MOVE_NONE;
1123     ss->ply = (ss-1)->ply + 1;
1124
1125     // Check for an instant draw or maximum ply reached
1126     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1127         return VALUE_DRAW;
1128
1129     // Decide whether or not to include checks, this fixes also the type of
1130     // TT entry depth that we are going to use. Note that in qsearch we use
1131     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1132     inCheck = pos.in_check();
1133     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1134
1135     // Transposition table lookup. At PV nodes, we don't use the TT for
1136     // pruning, but only for move ordering.
1137     tte = TT.probe(pos.key());
1138     ttMove = (tte ? tte->move() : MOVE_NONE);
1139     ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_ZERO;
1140
1141     if (!PvNode && tte && can_return_tt(tte, ttDepth, ttValue, beta))
1142     {
1143         ss->currentMove = ttMove; // Can be MOVE_NONE
1144         return ttValue;
1145     }
1146
1147     // Evaluate the position statically
1148     if (inCheck)
1149     {
1150         bestValue = futilityBase = -VALUE_INFINITE;
1151         ss->eval = evalMargin = VALUE_NONE;
1152         enoughMaterial = false;
1153     }
1154     else
1155     {
1156         if (tte)
1157         {
1158             assert(tte->static_value() != VALUE_NONE);
1159
1160             evalMargin = tte->static_value_margin();
1161             ss->eval = bestValue = tte->static_value();
1162         }
1163         else
1164             ss->eval = bestValue = evaluate(pos, evalMargin);
1165
1166         // Stand pat. Return immediately if static value is at least beta
1167         if (bestValue >= beta)
1168         {
1169             if (!tte)
1170                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1171
1172             return bestValue;
1173         }
1174
1175         if (PvNode && bestValue > alpha)
1176             alpha = bestValue;
1177
1178         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1179         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1180     }
1181
1182     // Initialize a MovePicker object for the current position, and prepare
1183     // to search the moves. Because the depth is <= 0 here, only captures,
1184     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1185     // be generated.
1186     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1187     CheckInfo ci(pos);
1188
1189     // Loop through the moves until no moves remain or a beta cutoff occurs
1190     while (   bestValue < beta
1191            && (move = mp.next_move<false>()) != MOVE_NONE)
1192     {
1193       assert(is_ok(move));
1194
1195       givesCheck = pos.move_gives_check(move, ci);
1196
1197       // Futility pruning
1198       if (   !PvNode
1199           && !inCheck
1200           && !givesCheck
1201           &&  move != ttMove
1202           &&  enoughMaterial
1203           &&  type_of(move) != PROMOTION
1204           && !pos.is_passed_pawn_push(move))
1205       {
1206           futilityValue =  futilityBase
1207                          + PieceValue[Eg][pos.piece_on(to_sq(move))]
1208                          + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1209
1210           if (futilityValue < beta)
1211           {
1212               if (futilityValue > bestValue)
1213                   bestValue = futilityValue;
1214
1215               continue;
1216           }
1217
1218           // Prune moves with negative or equal SEE
1219           if (   futilityBase < beta
1220               && depth < DEPTH_ZERO
1221               && pos.see(move) <= 0)
1222               continue;
1223       }
1224
1225       // Detect non-capture evasions that are candidate to be pruned
1226       evasionPrunable =   !PvNode
1227                        &&  inCheck
1228                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1229                        && !pos.is_capture(move)
1230                        && !pos.can_castle(pos.side_to_move());
1231
1232       // Don't search moves with negative SEE values
1233       if (   !PvNode
1234           && (!inCheck || evasionPrunable)
1235           &&  move != ttMove
1236           &&  type_of(move) != PROMOTION
1237           &&  pos.see_sign(move) < 0)
1238           continue;
1239
1240       // Don't search useless checks
1241       if (   !PvNode
1242           && !inCheck
1243           &&  givesCheck
1244           &&  move != ttMove
1245           && !pos.is_capture_or_promotion(move)
1246           &&  ss->eval + PawnValueMg / 4 < beta
1247           && !check_is_dangerous(pos, move, futilityBase, beta))
1248           continue;
1249
1250       // Check for legality only before to do the move
1251       if (!pos.pl_move_is_legal(move, ci.pinned))
1252           continue;
1253
1254       ss->currentMove = move;
1255
1256       // Make and search the move
1257       pos.do_move(move, st, ci, givesCheck);
1258       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1259       pos.undo_move(move);
1260
1261       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1262
1263       // New best move?
1264       if (value > bestValue)
1265       {
1266           bestValue = value;
1267           bestMove = move;
1268
1269           if (   PvNode
1270               && value > alpha
1271               && value < beta) // We want always alpha < beta
1272               alpha = value;
1273        }
1274     }
1275
1276     // All legal moves have been searched. A special case: If we're in check
1277     // and no legal moves were found, it is checkmate.
1278     if (inCheck && bestValue == -VALUE_INFINITE)
1279         return mated_in(ss->ply); // Plies to mate from the root
1280
1281     // Update transposition table
1282     move = bestValue <= oldAlpha ? MOVE_NONE : bestMove;
1283     bt   = bestValue <= oldAlpha ? BOUND_UPPER
1284          : bestValue >= beta ? BOUND_LOWER : BOUND_EXACT;
1285
1286     TT.store(pos.key(), value_to_tt(bestValue, ss->ply), bt, ttDepth, move, ss->eval, evalMargin);
1287
1288     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1289
1290     return bestValue;
1291   }
1292
1293
1294   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1295   // bestValue is updated only when returning false because in that case move
1296   // will be pruned.
1297
1298   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1299   {
1300     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1301     Square from, to, ksq;
1302     Piece pc;
1303     Color them;
1304
1305     from = from_sq(move);
1306     to = to_sq(move);
1307     them = ~pos.side_to_move();
1308     ksq = pos.king_square(them);
1309     kingAtt = pos.attacks_from<KING>(ksq);
1310     pc = pos.piece_moved(move);
1311
1312     occ = pos.pieces() ^ from ^ ksq;
1313     oldAtt = pos.attacks_from(pc, from, occ);
1314     newAtt = pos.attacks_from(pc,   to, occ);
1315
1316     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1317     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1318
1319     if (!more_than_one(b))
1320         return true;
1321
1322     // Rule 2. Queen contact check is very dangerous
1323     if (type_of(pc) == QUEEN && (kingAtt & to))
1324         return true;
1325
1326     // Rule 3. Creating new double threats with checks
1327     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1328     while (b)
1329     {
1330         // Note that here we generate illegal "double move"!
1331         if (futilityBase + PieceValue[Eg][pos.piece_on(pop_lsb(&b))] >= beta)
1332             return true;
1333     }
1334
1335     return false;
1336   }
1337
1338
1339   // connected_moves() tests whether two moves are 'connected' in the sense
1340   // that the first move somehow made the second move possible (for instance
1341   // if the moving piece is the same in both moves). The first move is assumed
1342   // to be the move that was made to reach the current position, while the
1343   // second move is assumed to be a move from the current position.
1344
1345   bool connected_moves(const Position& pos, Move m1, Move m2) {
1346
1347     Square f1, t1, f2, t2;
1348     Piece p1, p2;
1349     Square ksq;
1350
1351     assert(is_ok(m1));
1352     assert(is_ok(m2));
1353
1354     // Case 1: The moving piece is the same in both moves
1355     f2 = from_sq(m2);
1356     t1 = to_sq(m1);
1357     if (f2 == t1)
1358         return true;
1359
1360     // Case 2: The destination square for m2 was vacated by m1
1361     t2 = to_sq(m2);
1362     f1 = from_sq(m1);
1363     if (t2 == f1)
1364         return true;
1365
1366     // Case 3: Moving through the vacated square
1367     p2 = pos.piece_on(f2);
1368     if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1369       return true;
1370
1371     // Case 4: The destination square for m2 is defended by the moving piece in m1
1372     p1 = pos.piece_on(t1);
1373     if (pos.attacks_from(p1, t1) & t2)
1374         return true;
1375
1376     // Case 5: Discovered check, checking piece is the piece moved in m1
1377     ksq = pos.king_square(pos.side_to_move());
1378     if (    piece_is_slider(p1)
1379         && (between_bb(t1, ksq) & f2)
1380         && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1381         return true;
1382
1383     return false;
1384   }
1385
1386
1387   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1388   // "plies to mate from the current position". Non-mate scores are unchanged.
1389   // The function is called before storing a value to the transposition table.
1390
1391   Value value_to_tt(Value v, int ply) {
1392
1393     if (v >= VALUE_MATE_IN_MAX_PLY)
1394       return v + ply;
1395
1396     if (v <= VALUE_MATED_IN_MAX_PLY)
1397       return v - ply;
1398
1399     return v;
1400   }
1401
1402
1403   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1404   // from the transposition table (where refers to the plies to mate/be mated
1405   // from current position) to "plies to mate/be mated from the root".
1406
1407   Value value_from_tt(Value v, int ply) {
1408
1409     if (v >= VALUE_MATE_IN_MAX_PLY)
1410       return v - ply;
1411
1412     if (v <= VALUE_MATED_IN_MAX_PLY)
1413       return v + ply;
1414
1415     return v;
1416   }
1417
1418
1419   // connected_threat() tests whether it is safe to forward prune a move or if
1420   // is somehow connected to the threat move returned by null search.
1421
1422   bool connected_threat(const Position& pos, Move m, Move threat) {
1423
1424     assert(is_ok(m));
1425     assert(is_ok(threat));
1426     assert(!pos.is_capture_or_promotion(m));
1427     assert(!pos.is_passed_pawn_push(m));
1428
1429     Square mfrom, mto, tfrom, tto;
1430
1431     mfrom = from_sq(m);
1432     mto = to_sq(m);
1433     tfrom = from_sq(threat);
1434     tto = to_sq(threat);
1435
1436     // Case 1: Don't prune moves which move the threatened piece
1437     if (mfrom == tto)
1438         return true;
1439
1440     // Case 2: If the threatened piece has value less than or equal to the
1441     // value of the threatening piece, don't prune moves which defend it.
1442     if (   pos.is_capture(threat)
1443         && (   PieceValue[Mg][pos.piece_on(tfrom)] >= PieceValue[Mg][pos.piece_on(tto)]
1444             || type_of(pos.piece_on(tfrom)) == KING)
1445         && pos.move_attacks_square(m, tto))
1446         return true;
1447
1448     // Case 3: If the moving piece in the threatened move is a slider, don't
1449     // prune safe moves which block its ray.
1450     if (    piece_is_slider(pos.piece_on(tfrom))
1451         && (between_bb(tfrom, tto) & mto)
1452         &&  pos.see_sign(m) >= 0)
1453         return true;
1454
1455     return false;
1456   }
1457
1458
1459   // can_return_tt() returns true if a transposition table score can be used to
1460   // cut-off at a given point in search.
1461
1462   bool can_return_tt(const TTEntry* tte, Depth depth, Value v, Value beta) {
1463
1464     return   (   tte->depth() >= depth
1465               || v >= std::max(VALUE_MATE_IN_MAX_PLY, beta)
1466               || v < std::min(VALUE_MATED_IN_MAX_PLY, beta))
1467
1468           && (   ((tte->type() & BOUND_LOWER) && v >= beta)
1469               || ((tte->type() & BOUND_UPPER) && v < beta));
1470   }
1471
1472
1473   // refine_eval() returns the transposition table score if possible, otherwise
1474   // falls back on static position evaluation.
1475
1476   Value refine_eval(const TTEntry* tte, Value v, Value defaultEval) {
1477
1478       assert(tte);
1479
1480       if (   ((tte->type() & BOUND_LOWER) && v >= defaultEval)
1481           || ((tte->type() & BOUND_UPPER) && v < defaultEval))
1482           return v;
1483
1484       return defaultEval;
1485   }
1486
1487
1488   // When playing with strength handicap choose best move among the MultiPV set
1489   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1490
1491   Move do_skill_level() {
1492
1493     assert(MultiPV > 1);
1494
1495     static RKISS rk;
1496
1497     // PRNG sequence should be not deterministic
1498     for (int i = Time::current_time().msec() % 50; i > 0; i--)
1499         rk.rand<unsigned>();
1500
1501     // RootMoves are already sorted by score in descending order
1502     size_t size = std::min(MultiPV, RootMoves.size());
1503     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1504     int weakness = 120 - 2 * SkillLevel;
1505     int max_s = -VALUE_INFINITE;
1506     Move best = MOVE_NONE;
1507
1508     // Choose best move. For each move score we add two terms both dependent on
1509     // weakness, one deterministic and bigger for weaker moves, and one random,
1510     // then we choose the move with the resulting highest score.
1511     for (size_t i = 0; i < size; i++)
1512     {
1513         int s = RootMoves[i].score;
1514
1515         // Don't allow crazy blunders even at very low skills
1516         if (i > 0 && RootMoves[i-1].score > s + EasyMoveMargin)
1517             break;
1518
1519         // This is our magic formula
1520         s += (  weakness * int(RootMoves[0].score - s)
1521               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1522
1523         if (s > max_s)
1524         {
1525             max_s = s;
1526             best = RootMoves[i].pv[0];
1527         }
1528     }
1529     return best;
1530   }
1531
1532
1533   // uci_pv() formats PV information according to UCI protocol. UCI requires
1534   // to send all the PV lines also if are still to be searched and so refer to
1535   // the previous search score.
1536
1537   string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1538
1539     std::stringstream s;
1540     int t = SearchTime.elapsed();
1541     int selDepth = 0;
1542
1543     for (size_t i = 0; i < Threads.size(); i++)
1544         if (Threads[i].maxPly > selDepth)
1545             selDepth = Threads[i].maxPly;
1546
1547     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1548     {
1549         bool updated = (i <= PVIdx);
1550
1551         if (depth == 1 && !updated)
1552             continue;
1553
1554         int d = (updated ? depth : depth - 1);
1555         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1556
1557         if (s.rdbuf()->in_avail())
1558             s << "\n";
1559
1560         s << "info depth " << d
1561           << " seldepth " << selDepth
1562           << " score " << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1563           << " nodes " << pos.nodes_searched()
1564           << " nps " << (t > 0 ? pos.nodes_searched() * 1000 / t : 0)
1565           << " time " << t
1566           << " multipv " << i + 1
1567           << " pv";
1568
1569         for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1570             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1571     }
1572
1573     return s.str();
1574   }
1575
1576 } // namespace
1577
1578
1579 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1580 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1581 /// allow to always have a ponder move even when we fail high at root, and a
1582 /// long PV to print that is important for position analysis.
1583
1584 void RootMove::extract_pv_from_tt(Position& pos) {
1585
1586   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1587   TTEntry* tte;
1588   int ply = 1;
1589   Move m = pv[0];
1590
1591   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1592
1593   pv.clear();
1594   pv.push_back(m);
1595   pos.do_move(m, *st++);
1596
1597   while (   (tte = TT.probe(pos.key())) != NULL
1598          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1599          && pos.is_pseudo_legal(m)
1600          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1601          && ply < MAX_PLY
1602          && (!pos.is_draw<false>() || ply < 2))
1603   {
1604       pv.push_back(m);
1605       pos.do_move(m, *st++);
1606       ply++;
1607   }
1608   pv.push_back(MOVE_NONE);
1609
1610   do pos.undo_move(pv[--ply]); while (ply);
1611 }
1612
1613
1614 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1615 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1616 /// first, even if the old TT entries have been overwritten.
1617
1618 void RootMove::insert_pv_in_tt(Position& pos) {
1619
1620   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1621   TTEntry* tte;
1622   Key k;
1623   Value v, m = VALUE_NONE;
1624   int ply = 0;
1625
1626   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1627
1628   do {
1629       k = pos.key();
1630       tte = TT.probe(k);
1631
1632       // Don't overwrite existing correct entries
1633       if (!tte || tte->move() != pv[ply])
1634       {
1635           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1636           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1637       }
1638       pos.do_move(pv[ply], *st++);
1639
1640   } while (pv[++ply] != MOVE_NONE);
1641
1642   do pos.undo_move(pv[--ply]); while (ply);
1643 }
1644
1645
1646 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1647
1648 void Thread::idle_loop() {
1649
1650   // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1651   // object for which the thread is the master.
1652   const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1653
1654   assert(!sp_master || (sp_master->master == this && is_searching));
1655
1656   // If this thread is the master of a split point and all slaves have
1657   // finished their work at this split point, return from the idle loop.
1658   while (!sp_master || sp_master->slavesMask)
1659   {
1660       // If we are not searching, wait for a condition to be signaled
1661       // instead of wasting CPU time polling for work.
1662       while (   do_sleep
1663              || do_exit
1664              || (!is_searching && Threads.use_sleeping_threads()))
1665       {
1666           if (do_exit)
1667           {
1668               assert(!sp_master);
1669               return;
1670           }
1671
1672           // Grab the lock to avoid races with Thread::wake_up()
1673           lock_grab(sleepLock);
1674
1675           // If we are master and all slaves have finished don't go to sleep
1676           if (sp_master && !sp_master->slavesMask)
1677           {
1678               lock_release(sleepLock);
1679               break;
1680           }
1681
1682           // Do sleep after retesting sleep conditions under lock protection, in
1683           // particular we need to avoid a deadlock in case a master thread has,
1684           // in the meanwhile, allocated us and sent the wake_up() call before we
1685           // had the chance to grab the lock.
1686           if (do_sleep || !is_searching)
1687               cond_wait(sleepCond, sleepLock);
1688
1689           lock_release(sleepLock);
1690       }
1691
1692       // If this thread has been assigned work, launch a search
1693       if (is_searching)
1694       {
1695           assert(!do_sleep && !do_exit);
1696
1697           lock_grab(Threads.splitLock);
1698
1699           assert(is_searching);
1700           SplitPoint* sp = curSplitPoint;
1701
1702           lock_release(Threads.splitLock);
1703
1704           Stack ss[MAX_PLY_PLUS_2];
1705           Position pos(*sp->pos, this);
1706
1707           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1708           (ss+1)->sp = sp;
1709
1710           lock_grab(sp->lock);
1711
1712           if (sp->nodeType == Root)
1713               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1714           else if (sp->nodeType == PV)
1715               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1716           else if (sp->nodeType == NonPV)
1717               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1718           else
1719               assert(false);
1720
1721           assert(is_searching);
1722
1723           is_searching = false;
1724           sp->slavesMask &= ~(1ULL << idx);
1725           sp->nodes += pos.nodes_searched();
1726
1727           // Wake up master thread so to allow it to return from the idle loop in
1728           // case we are the last slave of the split point.
1729           if (    Threads.use_sleeping_threads()
1730               &&  this != sp->master
1731               && !sp->slavesMask)
1732           {
1733               assert(!sp->master->is_searching);
1734               sp->master->wake_up();
1735           }
1736
1737           // After releasing the lock we cannot access anymore any SplitPoint
1738           // related data in a safe way becuase it could have been released under
1739           // our feet by the sp master. Also accessing other Thread objects is
1740           // unsafe because if we are exiting there is a chance are already freed.
1741           lock_release(sp->lock);
1742       }
1743   }
1744 }
1745
1746
1747 /// check_time() is called by the timer thread when the timer triggers. It is
1748 /// used to print debug info and, more important, to detect when we are out of
1749 /// available time and so stop the search.
1750
1751 void check_time() {
1752
1753   static Time lastInfoTime = Time::current_time();
1754
1755   if (lastInfoTime.elapsed() >= 1000)
1756   {
1757       lastInfoTime.restart();
1758       dbg_print();
1759   }
1760
1761   if (Limits.ponder)
1762       return;
1763
1764   int e = SearchTime.elapsed();
1765   bool stillAtFirstMove =    Signals.firstRootMove
1766                          && !Signals.failedLowAtRoot
1767                          &&  e > TimeMgr.available_time();
1768
1769   bool noMoreTime =   e > TimeMgr.maximum_time() - 2 * TimerResolution
1770                    || stillAtFirstMove;
1771
1772   if (   (Limits.use_time_management() && noMoreTime)
1773       || (Limits.movetime && e >= Limits.movetime))
1774       Signals.stop = true;
1775 }