]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Prefetch earlier in qsearch()
[stockfish] / src / movepick.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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include "movepick.h"
24 #include "thread.h"
25
26 namespace {
27
28   enum Stages {
29     MAIN_SEARCH, CAPTURES_INIT, GOOD_CAPTURES, KILLERS, COUNTERMOVE, QUIET_INIT, QUIET, BAD_CAPTURES,
30     EVASION, EVASIONS_INIT, ALL_EVASIONS,
31     PROBCUT, PROBCUT_INIT, PROBCUT_CAPTURES,
32     QSEARCH_WITH_CHECKS, QCAPTURES_1_INIT, QCAPTURES_1, QCHECKS,
33     QSEARCH_NO_CHECKS, QCAPTURES_2_INIT, QCAPTURES_2,
34     QSEARCH_RECAPTURES, QRECAPTURES
35   };
36
37   // partial_insertion_sort() sorts moves in descending order up to and including
38   // a given limit. The order of moves smaller than the limit is left unspecified.
39   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
40
41     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
42         if (p->value >= limit)
43         {
44             ExtMove tmp = *p, *q;
45             *p = *++sortedEnd;
46             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
47                 *q = *(q - 1);
48             *q = tmp;
49         }
50   }
51
52   // pick_best() finds the best move in the range (begin, end) and moves it to
53   // the front. It's faster than sorting all the moves in advance when there
54   // are few moves, e.g., the possible captures.
55   Move pick_best(ExtMove* begin, ExtMove* end) {
56
57     std::swap(*begin, *std::max_element(begin, end));
58     return *begin;
59   }
60
61 } // namespace
62
63
64 /// Constructors of the MovePicker class. As arguments we pass information
65 /// to help it to return the (presumably) good moves first, to decide which
66 /// moves to return (in the quiescence search, for instance, we only want to
67 /// search captures, promotions, and some checks) and how important good move
68 /// ordering is at the current node.
69
70 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Search::Stack* s)
71            : pos(p), ss(s), depth(d) {
72
73   assert(d > DEPTH_ZERO);
74
75   Square prevSq = to_sq((ss-1)->currentMove);
76   countermove = pos.this_thread()->counterMoves[pos.piece_on(prevSq)][prevSq];
77   killers[0] = ss->killers[0];
78   killers[1] = ss->killers[1];
79
80   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
81   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
82   stage += (ttMove == MOVE_NONE);
83 }
84
85 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Square s)
86            : pos(p) {
87
88   assert(d <= DEPTH_ZERO);
89
90   if (pos.checkers())
91       stage = EVASION;
92
93   else if (d > DEPTH_QS_NO_CHECKS)
94       stage = QSEARCH_WITH_CHECKS;
95
96   else if (d > DEPTH_QS_RECAPTURES)
97       stage = QSEARCH_NO_CHECKS;
98
99   else
100   {
101       stage = QSEARCH_RECAPTURES;
102       recaptureSquare = s;
103       return;
104   }
105
106   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
107   stage += (ttMove == MOVE_NONE);
108 }
109
110 MovePicker::MovePicker(const Position& p, Move ttm, Value th)
111            : pos(p), threshold(th) {
112
113   assert(!pos.checkers());
114
115   stage = PROBCUT;
116
117   // In ProbCut we generate captures with SEE higher than or equal to the given threshold
118   ttMove =   ttm
119           && pos.pseudo_legal(ttm)
120           && pos.capture(ttm)
121           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
122
123   stage += (ttMove == MOVE_NONE);
124 }
125
126
127 /// score() assigns a numerical value to each move in a move list. The moves with
128 /// highest values will be picked first.
129 template<>
130 void MovePicker::score<CAPTURES>() {
131   // Winning and equal captures in the main search are ordered by MVV, preferring
132   // captures near our home rank. Surprisingly, this appears to perform slightly
133   // better than SEE-based move ordering: exchanging big pieces before capturing
134   // a hanging piece probably helps to reduce the subtree size.
135   // In the main search we want to push captures with negative SEE values to the
136   // badCaptures[] array, but instead of doing it now we delay until the move
137   // has been picked up, saving some SEE calls in case we get a cutoff.
138   for (auto& m : *this)
139       m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
140                - Value(200 * relative_rank(pos.side_to_move(), to_sq(m)));
141 }
142
143 template<>
144 void MovePicker::score<QUIETS>() {
145
146   const ButterflyHistory& history = pos.this_thread()->history;
147
148   const PieceToHistory& cmh = *(ss-1)->history;
149   const PieceToHistory& fmh = *(ss-2)->history;
150   const PieceToHistory& fm2 = *(ss-4)->history;
151
152   Color c = pos.side_to_move();
153
154   for (auto& m : *this)
155       m.value =  cmh[pos.moved_piece(m)][to_sq(m)]
156                + fmh[pos.moved_piece(m)][to_sq(m)]
157                + fm2[pos.moved_piece(m)][to_sq(m)]
158                + history[c][from_to(m)];
159 }
160
161 template<>
162 void MovePicker::score<EVASIONS>() {
163   // Try captures ordered by MVV/LVA, then non-captures ordered by stats heuristics
164   const ButterflyHistory& history = pos.this_thread()->history;
165   Color c = pos.side_to_move();
166
167   for (auto& m : *this)
168       if (pos.capture(m))
169           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
170                    - Value(type_of(pos.moved_piece(m))) + (1 << 28);
171       else
172           m.value = history[c][from_to(m)];
173 }
174
175
176 /// next_move() is the most important method of the MovePicker class. It returns
177 /// a new pseudo legal move every time it is called, until there are no more moves
178 /// left. It picks the move with the biggest value from a list of generated moves
179 /// taking care not to return the ttMove if it has already been searched.
180
181 Move MovePicker::next_move(bool skipQuiets) {
182
183   Move move;
184
185   switch (stage) {
186
187   case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
188   case QSEARCH_NO_CHECKS: case PROBCUT:
189       ++stage;
190       return ttMove;
191
192   case CAPTURES_INIT:
193       endBadCaptures = cur = moves;
194       endMoves = generate<CAPTURES>(pos, cur);
195       score<CAPTURES>();
196       ++stage;
197       /* fallthrough */
198
199   case GOOD_CAPTURES:
200       while (cur < endMoves)
201       {
202           move = pick_best(cur++, endMoves);
203           if (move != ttMove)
204           {
205               if (pos.see_ge(move))
206                   return move;
207
208               // Losing capture, move it to the beginning of the array
209               *endBadCaptures++ = move;
210           }
211       }
212
213       ++stage;
214       move = killers[0];  // First killer move
215       if (    move != MOVE_NONE
216           &&  move != ttMove
217           &&  pos.pseudo_legal(move)
218           && !pos.capture(move))
219           return move;
220       /* fallthrough */
221
222   case KILLERS:
223       ++stage;
224       move = killers[1]; // Second killer move
225       if (    move != MOVE_NONE
226           &&  move != ttMove
227           &&  pos.pseudo_legal(move)
228           && !pos.capture(move))
229           return move;
230       /* fallthrough */
231
232   case COUNTERMOVE:
233       ++stage;
234       move = countermove;
235       if (    move != MOVE_NONE
236           &&  move != ttMove
237           &&  move != killers[0]
238           &&  move != killers[1]
239           &&  pos.pseudo_legal(move)
240           && !pos.capture(move))
241           return move;
242       /* fallthrough */
243
244   case QUIET_INIT:
245       cur = endBadCaptures;
246       endMoves = generate<QUIETS>(pos, cur);
247       score<QUIETS>();
248       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
249       ++stage;
250       /* fallthrough */
251
252   case QUIET:
253       while (    cur < endMoves
254              && (!skipQuiets || cur->value >= VALUE_ZERO))
255       {
256           move = *cur++;
257
258           if (   move != ttMove
259               && move != killers[0]
260               && move != killers[1]
261               && move != countermove)
262               return move;
263       }
264       ++stage;
265       cur = moves; // Point to beginning of bad captures
266       /* fallthrough */
267
268   case BAD_CAPTURES:
269       if (cur < endBadCaptures)
270           return *cur++;
271       break;
272
273   case EVASIONS_INIT:
274       cur = moves;
275       endMoves = generate<EVASIONS>(pos, cur);
276       score<EVASIONS>();
277       ++stage;
278       /* fallthrough */
279
280   case ALL_EVASIONS:
281       while (cur < endMoves)
282       {
283           move = pick_best(cur++, endMoves);
284           if (move != ttMove)
285               return move;
286       }
287       break;
288
289   case PROBCUT_INIT:
290       cur = moves;
291       endMoves = generate<CAPTURES>(pos, cur);
292       score<CAPTURES>();
293       ++stage;
294       /* fallthrough */
295
296   case PROBCUT_CAPTURES:
297       while (cur < endMoves)
298       {
299           move = pick_best(cur++, endMoves);
300           if (   move != ttMove
301               && pos.see_ge(move, threshold))
302               return move;
303       }
304       break;
305
306   case QCAPTURES_1_INIT: case QCAPTURES_2_INIT:
307       cur = moves;
308       endMoves = generate<CAPTURES>(pos, cur);
309       score<CAPTURES>();
310       ++stage;
311       /* fallthrough */
312
313   case QCAPTURES_1: case QCAPTURES_2:
314       while (cur < endMoves)
315       {
316           move = pick_best(cur++, endMoves);
317           if (move != ttMove)
318               return move;
319       }
320       if (stage == QCAPTURES_2)
321           break;
322       cur = moves;
323       endMoves = generate<QUIET_CHECKS>(pos, cur);
324       ++stage;
325       /* fallthrough */
326
327   case QCHECKS:
328       while (cur < endMoves)
329       {
330           move = cur++->move;
331           if (move != ttMove)
332               return move;
333       }
334       break;
335
336   case QSEARCH_RECAPTURES:
337       cur = moves;
338       endMoves = generate<CAPTURES>(pos, cur);
339       score<CAPTURES>();
340       ++stage;
341       /* fallthrough */
342
343   case QRECAPTURES:
344       while (cur < endMoves)
345       {
346           move = pick_best(cur++, endMoves);
347           if (to_sq(move) == recaptureSquare)
348               return move;
349       }
350       break;
351
352   default:
353       assert(false);
354   }
355
356   return MOVE_NONE;
357 }