]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
AVX512, AVX2 and SSSE3 speedups
[stockfish] / src / movepick.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2020 The Stockfish developers (see AUTHORS file)
4
5   Stockfish 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   Stockfish 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 #include <cassert>
20
21 #include "movepick.h"
22
23 namespace {
24
25   enum Stages {
26     MAIN_TT, CAPTURE_INIT, GOOD_CAPTURE, REFUTATION, QUIET_INIT, QUIET, BAD_CAPTURE,
27     EVASION_TT, EVASION_INIT, EVASION,
28     PROBCUT_TT, PROBCUT_INIT, PROBCUT,
29     QSEARCH_TT, QCAPTURE_INIT, QCAPTURE, QCHECK_INIT, QCHECK
30   };
31
32   // partial_insertion_sort() sorts moves in descending order up to and including
33   // a given limit. The order of moves smaller than the limit is left unspecified.
34   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
35
36     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
37         if (p->value >= limit)
38         {
39             ExtMove tmp = *p, *q;
40             *p = *++sortedEnd;
41             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
42                 *q = *(q - 1);
43             *q = tmp;
44         }
45   }
46
47 } // namespace
48
49
50 /// Constructors of the MovePicker class. As arguments we pass information
51 /// to help it to return the (presumably) good moves first, to decide which
52 /// moves to return (in the quiescence search, for instance, we only want to
53 /// search captures, promotions, and some checks) and how important good move
54 /// ordering is at the current node.
55
56 /// MovePicker constructor for the main search
57 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh, const ButterflyHistory* sh, const LowPlyHistory* lp,
58                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Move cm, const Move* killers, int pl)
59            : pos(p), mainHistory(mh), staticHistory(sh), lowPlyHistory(lp), captureHistory(cph), continuationHistory(ch),
60              ttMove(ttm), refutations{{killers[0], 0}, {killers[1], 0}, {cm, 0}}, depth(d), ply(pl) {
61
62   assert(d > 0);
63
64   stage = (pos.checkers() ? EVASION_TT : MAIN_TT) +
65           !(ttm && pos.pseudo_legal(ttm));
66 }
67
68 /// MovePicker constructor for quiescence search
69 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh, const ButterflyHistory* sh,
70                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Square rs)
71            : pos(p), mainHistory(mh), staticHistory(sh), captureHistory(cph), continuationHistory(ch), ttMove(ttm), recaptureSquare(rs), depth(d) {
72
73   assert(d <= 0);
74
75   stage = (pos.checkers() ? EVASION_TT : QSEARCH_TT) +
76           !(   ttm
77             && (pos.checkers() || depth > DEPTH_QS_RECAPTURES || to_sq(ttm) == recaptureSquare)
78             && pos.pseudo_legal(ttm));
79 }
80
81 /// MovePicker constructor for ProbCut: we generate captures with SEE greater
82 /// than or equal to the given threshold.
83 MovePicker::MovePicker(const Position& p, Move ttm, Value th, const CapturePieceToHistory* cph)
84            : pos(p), captureHistory(cph), ttMove(ttm), threshold(th) {
85
86   assert(!pos.checkers());
87
88   stage = PROBCUT_TT + !(ttm && pos.capture(ttm)
89                              && pos.pseudo_legal(ttm)
90                              && pos.see_ge(ttm, threshold));
91 }
92
93 /// MovePicker::score() assigns a numerical value to each move in a list, used
94 /// for sorting. Captures are ordered by Most Valuable Victim (MVV), preferring
95 /// captures with a good history. Quiets moves are ordered using the histories.
96 template<GenType Type>
97 void MovePicker::score() {
98
99   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
100
101   for (auto& m : *this)
102       if (Type == CAPTURES)
103           m.value =  int(PieceValue[MG][pos.piece_on(to_sq(m))]) * 6
104                    + (*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))];
105
106       else if (Type == QUIETS)
107           m.value =      (*mainHistory)[pos.side_to_move()][from_to(m)]
108                    +     (*staticHistory)[pos.side_to_move()][from_to(m)]
109                    + 2 * (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
110                    + 2 * (*continuationHistory[1])[pos.moved_piece(m)][to_sq(m)]
111                    + 2 * (*continuationHistory[3])[pos.moved_piece(m)][to_sq(m)]
112                    +     (*continuationHistory[5])[pos.moved_piece(m)][to_sq(m)]
113                    + (ply < MAX_LPH ? std::min(4, depth / 3) * (*lowPlyHistory)[ply][from_to(m)] : 0);
114
115       else // Type == EVASIONS
116       {
117           if (pos.capture(m))
118               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
119                        - Value(type_of(pos.moved_piece(m)));
120           else
121               m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
122                        + (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
123                        - (1 << 28);
124       }
125 }
126
127 /// MovePicker::select() returns the next move satisfying a predicate function.
128 /// It never returns the TT move.
129 template<MovePicker::PickType T, typename Pred>
130 Move MovePicker::select(Pred filter) {
131
132   while (cur < endMoves)
133   {
134       if (T == Best)
135           std::swap(*cur, *std::max_element(cur, endMoves));
136
137       if (*cur != ttMove && filter())
138           return *cur++;
139
140       cur++;
141   }
142   return MOVE_NONE;
143 }
144
145 /// MovePicker::next_move() is the most important method of the MovePicker class. It
146 /// returns a new pseudo legal move every time it is called until there are no more
147 /// moves left, picking the move with the highest score from a list of generated moves.
148 Move MovePicker::next_move(bool skipQuiets) {
149
150 top:
151   switch (stage) {
152
153   case MAIN_TT:
154   case EVASION_TT:
155   case QSEARCH_TT:
156   case PROBCUT_TT:
157       ++stage;
158       return ttMove;
159
160   case CAPTURE_INIT:
161   case PROBCUT_INIT:
162   case QCAPTURE_INIT:
163       cur = endBadCaptures = moves;
164       endMoves = generate<CAPTURES>(pos, cur);
165
166       score<CAPTURES>();
167       ++stage;
168       goto top;
169
170   case GOOD_CAPTURE:
171       if (select<Best>([&](){
172                        return pos.see_ge(*cur, Value(-69 * cur->value / 1024)) ?
173                               // Move losing capture to endBadCaptures to be tried later
174                               true : (*endBadCaptures++ = *cur, false); }))
175           return *(cur - 1);
176
177       // Prepare the pointers to loop over the refutations array
178       cur = std::begin(refutations);
179       endMoves = std::end(refutations);
180
181       // If the countermove is the same as a killer, skip it
182       if (   refutations[0].move == refutations[2].move
183           || refutations[1].move == refutations[2].move)
184           --endMoves;
185
186       ++stage;
187       [[fallthrough]];
188
189   case REFUTATION:
190       if (select<Next>([&](){ return    *cur != MOVE_NONE
191                                     && !pos.capture(*cur)
192                                     &&  pos.pseudo_legal(*cur); }))
193           return *(cur - 1);
194       ++stage;
195       [[fallthrough]];
196
197   case QUIET_INIT:
198       if (!skipQuiets)
199       {
200           cur = endBadCaptures;
201           endMoves = generate<QUIETS>(pos, cur);
202
203           score<QUIETS>();
204           partial_insertion_sort(cur, endMoves, -3000 * depth);
205       }
206
207       ++stage;
208       [[fallthrough]];
209
210   case QUIET:
211       if (   !skipQuiets
212           && select<Next>([&](){return   *cur != refutations[0].move
213                                       && *cur != refutations[1].move
214                                       && *cur != refutations[2].move;}))
215           return *(cur - 1);
216
217       // Prepare the pointers to loop over the bad captures
218       cur = moves;
219       endMoves = endBadCaptures;
220
221       ++stage;
222       [[fallthrough]];
223
224   case BAD_CAPTURE:
225       return select<Next>([](){ return true; });
226
227   case EVASION_INIT:
228       cur = moves;
229       endMoves = generate<EVASIONS>(pos, cur);
230
231       score<EVASIONS>();
232       ++stage;
233       [[fallthrough]];
234
235   case EVASION:
236       return select<Best>([](){ return true; });
237
238   case PROBCUT:
239       return select<Best>([&](){ return pos.see_ge(*cur, threshold); });
240
241   case QCAPTURE:
242       if (select<Best>([&](){ return   depth > DEPTH_QS_RECAPTURES
243                                     || to_sq(*cur) == recaptureSquare; }))
244           return *(cur - 1);
245
246       // If we did not find any move and we do not try checks, we have finished
247       if (depth != DEPTH_QS_CHECKS)
248           return MOVE_NONE;
249
250       ++stage;
251       [[fallthrough]];
252
253   case QCHECK_INIT:
254       cur = moves;
255       endMoves = generate<QUIET_CHECKS>(pos, cur);
256
257       ++stage;
258       [[fallthrough]];
259
260   case QCHECK:
261       return select<Next>([](){ return true; });
262   }
263
264   assert(false);
265   return MOVE_NONE; // Silence warning
266 }