]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Small optimization in generate_evasions()
[stockfish] / src / movegen.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author) Copyright (C) 2008 Marco Costalba
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
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25
26 #include "movegen.h"
27
28 // Simple macro to wrap a very common while loop, no facny, no flexibility,
29 // hardcoded list name 'mlist' and from square 'from'.
30 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
31
32 ////
33 //// Local definitions
34 ////
35
36 namespace {
37
38   enum CastlingSide {
39     KING_SIDE,
40     QUEEN_SIDE
41   };
42
43   // Function
44   bool castling_is_check(const Position&, CastlingSide);
45
46   // Template
47   template<CastlingSide Side>
48   MoveStack* generate_castle_moves(const Position&, MoveStack*);
49
50   // Template generate_pawn_captures() with specializations
51   template<Color, Color, Bitboard, SquareDelta, SquareDelta, SquareDelta>
52   MoveStack* do_generate_pawn_captures(const Position& pos, MoveStack* mlist);
53
54   template<Color>
55   inline MoveStack* generate_pawn_captures(const Position& p, MoveStack* m) {
56       return do_generate_pawn_captures<WHITE, BLACK, Rank8BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m);
57   }
58   template<>
59   inline MoveStack* generate_pawn_captures<BLACK>(const Position& p, MoveStack* m) {
60       return do_generate_pawn_captures<BLACK, WHITE, Rank1BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m);
61   }
62
63   // Template generate_pawn_noncaptures() with specializations
64   template<Color, Color, Bitboard, Bitboard, SquareDelta, SquareDelta, SquareDelta>
65   MoveStack* do_generate_pawn_noncaptures(const Position& pos, MoveStack* mlist);
66
67   template<Color>
68   inline MoveStack* generate_pawn_noncaptures(const Position& p, MoveStack* m) {
69       return do_generate_pawn_noncaptures<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m);
70   }
71   template<>
72   inline MoveStack* generate_pawn_noncaptures<BLACK>(const Position& p, MoveStack* m) {
73       return do_generate_pawn_noncaptures<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m);
74   }
75
76   // Template generate_pawn_blocking_evasions() with specializations
77   template<Color Us, Rank, Bitboard, SquareDelta>
78   MoveStack* do_generate_pawn_blocking_evasions(const Position& pos, Bitboard not_pinned,
79                                                 Bitboard blockSquares, MoveStack* mlist);
80   template<Color>
81   inline MoveStack* generate_pawn_blocking_evasions(const Position& p, Bitboard np, Bitboard bs, MoveStack* m) {
82       return do_generate_pawn_blocking_evasions<WHITE, RANK_8, Rank3BB, DELTA_N>(p, np, bs, m);
83   }
84   template<>
85   inline MoveStack* generate_pawn_blocking_evasions<BLACK>(const Position& p, Bitboard np, Bitboard bs, MoveStack* m) {
86       return do_generate_pawn_blocking_evasions<BLACK, RANK_1, Rank6BB, DELTA_S>(p, np, bs, m);
87   }
88
89   // Template generate_pawn_checks() with specializations
90   template<Color, Color, Bitboard, Bitboard, SquareDelta>
91   MoveStack* do_generate_pawn_checks(const Position&, Bitboard, Square, MoveStack*);
92
93   template<Color>
94   inline MoveStack* generate_pawn_checks(const Position& p, Bitboard dc, Square ksq, MoveStack* m) {
95       return do_generate_pawn_checks<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_N>(p, dc, ksq, m);
96   }
97   template<>
98   inline MoveStack* generate_pawn_checks<BLACK>(const Position& p, Bitboard dc, Square ksq, MoveStack* m) {
99       return do_generate_pawn_checks<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_S>(p, dc, ksq, m);
100   }
101
102   // non-pawn templates
103   template<PieceType>
104   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color us, Bitboard);
105   template<>
106   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target);
107
108   template<PieceType>
109   MoveStack* generate_piece_checks(const Position&, Bitboard, Bitboard, Square, MoveStack*);
110   MoveStack* generate_piece_checks_king(const Position&, Square, Bitboard, Square, MoveStack*);
111
112   template<PieceType>
113   MoveStack* generate_piece_blocking_evasions(const Position&, Bitboard, Bitboard, MoveStack*);
114 }
115
116
117 ////
118 //// Functions
119 ////
120
121
122 /// generate_captures generates() all pseudo-legal captures and queen
123 /// promotions.  The return value is the number of moves generated.
124
125 int generate_captures(const Position& pos, MoveStack* mlist) {
126
127   assert(pos.is_ok());
128   assert(!pos.is_check());
129
130   Color us = pos.side_to_move();
131   Bitboard target = pos.pieces_of_color(opposite_color(us));
132   MoveStack* mlist_start = mlist;
133
134   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
135   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
136   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
137   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
138
139   if (us == WHITE)
140       mlist = generate_pawn_captures<WHITE>(pos, mlist);
141   else
142       mlist = generate_pawn_captures<BLACK>(pos, mlist);
143
144   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
145   return int(mlist - mlist_start);
146 }
147
148
149 /// generate_noncaptures() generates all pseudo-legal non-captures and
150 /// underpromotions.  The return value is the number of moves generated.
151
152 int generate_noncaptures(const Position& pos, MoveStack* mlist) {
153
154   assert(pos.is_ok());
155   assert(!pos.is_check());
156
157   Color us = pos.side_to_move();
158   Bitboard target = pos.empty_squares();
159   MoveStack* mlist_start = mlist;
160
161   if (us == WHITE)
162       mlist = generate_pawn_noncaptures<WHITE>(pos, mlist);
163   else
164       mlist = generate_pawn_noncaptures<BLACK>(pos, mlist);
165
166   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
167   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
168   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
169   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
170   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
171   mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
172   mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
173   return int(mlist - mlist_start);
174 }
175
176
177 /// generate_checks() generates all pseudo-legal non-capturing, non-promoting
178 /// checks. It returns the number of generated moves.
179
180 int generate_checks(const Position& pos, MoveStack* mlist, Bitboard dc) {
181
182   assert(pos.is_ok());
183   assert(!pos.is_check());
184
185   Color us = pos.side_to_move();
186   Square ksq = pos.king_square(opposite_color(us));
187   MoveStack* mlist_start = mlist;
188
189   assert(pos.piece_on(ksq) == king_of_color(opposite_color(us)));
190
191   dc = pos.discovered_check_candidates(us);
192
193   // Pawn moves
194   if (us == WHITE)
195      mlist = generate_pawn_checks<WHITE>(pos, dc, ksq, mlist);
196   else
197      mlist = generate_pawn_checks<BLACK>(pos, dc, ksq, mlist);
198
199   // Pieces moves
200   Bitboard b = pos.knights(us);
201   if (b)
202       mlist = generate_piece_checks<KNIGHT>(pos, b, dc, ksq, mlist);
203
204   b = pos.bishops(us);
205   if (b)
206       mlist = generate_piece_checks<BISHOP>(pos, b, dc, ksq, mlist);
207
208   b = pos.rooks(us);
209   if (b)
210       mlist = generate_piece_checks<ROOK>(pos, b, dc, ksq, mlist);
211
212   b = pos.queens(us);
213   if (b)
214       mlist = generate_piece_checks<QUEEN>(pos, b, dc, ksq, mlist);
215
216   // Hopefully we always have a king ;-)
217   mlist = generate_piece_checks_king(pos, pos.king_square(us), dc, ksq, mlist);
218
219   // Castling moves that give check. Very rare but nice to have!
220   if (   pos.can_castle_queenside(us)
221       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_D)
222       && castling_is_check(pos, QUEEN_SIDE))
223       mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
224
225   if (   pos.can_castle_kingside(us)
226       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_F)
227       && castling_is_check(pos, KING_SIDE))
228       mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
229
230   return int(mlist - mlist_start);
231 }
232
233
234 /// generate_evasions() generates all check evasions when the side to move is
235 /// in check.  Unlike the other move generation functions, this one generates
236 /// only legal moves.  It returns the number of generated moves. This
237 /// function is very ugly, and needs cleaning up some time later.  FIXME
238
239 int generate_evasions(const Position& pos, MoveStack* mlist) {
240
241   assert(pos.is_ok());
242   assert(pos.is_check());
243
244   Square from, to;
245   Color us = pos.side_to_move();
246   Color them = opposite_color(us);
247   Square ksq = pos.king_square(us);
248   MoveStack* mlist_start = mlist;
249
250   assert(pos.piece_on(ksq) == king_of_color(us));
251
252   // The bitboard of occupied pieces without our king
253   Bitboard b2 = pos.occupied_squares();
254   clear_bit(&b2, ksq);
255
256   // Find squares attacked by slider checkers, we will
257   // remove them from king evasions set so to avoid a couple
258   // of cycles in the slow king evasions legality check loop.
259   Bitboard checkers = pos.checkers();
260   Bitboard checkersAttacks = EmptyBoardBB;
261   Bitboard b = checkers & (pos.queens() | pos.bishops());
262   while (b)
263   {
264       from = pop_1st_bit(&b);
265       checkersAttacks |= bishop_attacks_bb(from, b2);
266   }
267
268   b = checkers & (pos.queens() | pos.rooks());
269   while (b)
270   {
271       from = pop_1st_bit(&b);
272       checkersAttacks |= rook_attacks_bb(from, b2);
273   }
274
275   // Generate evasions for king
276   Bitboard b1 = pos.piece_attacks<KING>(ksq) & ~pos.pieces_of_color(us) & ~checkersAttacks;
277   while (b1)
278   {
279       to = pop_1st_bit(&b1);
280
281       // Make sure 'to' is not attacked by the other side. This is a bit ugly,
282       // because we can't use Position::square_is_attacked. Instead we use
283       // the low-level bishop_attacks_bb and rook_attacks_bb with the bitboard
284       // b2 (the occupied squares with the king removed) in order to test whether
285       // the king will remain in check on the destination square.
286       if (!(   (pos.piece_attacks<KNIGHT>(to) & pos.knights(them))
287             || (pos.pawn_attacks(us, to)      & pos.pawns(them))
288             || (bishop_attacks_bb(to, b2)     & pos.bishops_and_queens(them))
289             || (rook_attacks_bb(to, b2)       & pos.rooks_and_queens(them))
290             || (pos.piece_attacks<KING>(to)   & pos.kings(them))))
291           (*mlist++).move = make_move(ksq, to);
292   }
293
294   // Generate evasions for other pieces only if not double check. We use a
295   // simple bit twiddling hack here rather than calling count_1s in order to
296   // save some time (we know that pos.checkers() has at most two nonzero bits).
297   if (!(checkers & (checkers - 1))) // Only one bit set?
298   {
299       Square checksq = first_1(checkers);
300
301       assert(pos.color_of_piece_on(checksq) == them);
302
303       // Find pinned pieces
304       Bitboard not_pinned = ~pos.pinned_pieces(us);
305
306       // Generate captures of the checking piece
307
308       // Pawn captures
309       b1 = pos.pawn_attacks(them, checksq) & pos.pawns(us) & not_pinned;
310       while (b1)
311       {
312           from = pop_1st_bit(&b1);
313           if (relative_rank(us, checksq) == RANK_8)
314           {
315               (*mlist++).move = make_promotion_move(from, checksq, QUEEN);
316               (*mlist++).move = make_promotion_move(from, checksq, ROOK);
317               (*mlist++).move = make_promotion_move(from, checksq, BISHOP);
318               (*mlist++).move = make_promotion_move(from, checksq, KNIGHT);
319           } else
320               (*mlist++).move = make_move(from, checksq);
321       }
322
323       // Pieces captures
324       b1 = (  (pos.piece_attacks<KNIGHT>(checksq) & pos.knights(us))
325             | (pos.piece_attacks<BISHOP>(checksq) & pos.bishops_and_queens(us))
326             | (pos.piece_attacks<ROOK>(checksq)   & pos.rooks_and_queens(us)) ) & not_pinned;
327
328       while (b1)
329       {
330           from = pop_1st_bit(&b1);
331           (*mlist++).move = make_move(from, checksq);
332       }
333
334       // Blocking check evasions are possible only if the checking piece is
335       // a slider
336       if (checkers & pos.sliders())
337       {
338           Bitboard blockSquares = squares_between(checksq, ksq);
339
340           assert((pos.occupied_squares() & blockSquares) == EmptyBoardBB);
341
342           // Pawn moves. Because a blocking evasion can never be a capture, we
343           // only generate pawn pushes.
344           if (us == WHITE)
345               mlist = generate_pawn_blocking_evasions<WHITE>(pos, not_pinned, blockSquares, mlist);
346           else
347               mlist = generate_pawn_blocking_evasions<BLACK>(pos, not_pinned, blockSquares, mlist);
348
349           // Pieces moves
350           b1 = pos.knights(us) & not_pinned;
351           if (b1)
352               mlist = generate_piece_blocking_evasions<KNIGHT>(pos, b1, blockSquares, mlist);
353
354           b1 = pos.bishops(us) & not_pinned;
355           if (b1)
356               mlist = generate_piece_blocking_evasions<BISHOP>(pos, b1, blockSquares, mlist);
357
358           b1 = pos.rooks(us) & not_pinned;
359           if (b1)
360               mlist = generate_piece_blocking_evasions<ROOK>(pos, b1, blockSquares, mlist);
361
362           b1 = pos.queens(us) & not_pinned;
363           if (b1)
364               mlist = generate_piece_blocking_evasions<QUEEN>(pos, b1, blockSquares, mlist);
365     }
366
367     // Finally, the ugly special case of en passant captures. An en passant
368     // capture can only be a check evasion if the check is not a discovered
369     // check. If pos.ep_square() is set, the last move made must have been
370     // a double pawn push. If, furthermore, the checking piece is a pawn,
371     // an en passant check evasion may be possible.
372     if (pos.ep_square() != SQ_NONE && (checkers & pos.pawns(them)))
373     {
374         to = pos.ep_square();
375         b1 = pos.pawn_attacks(them, to) & pos.pawns(us);
376
377         assert(b1 != EmptyBoardBB);
378
379         b1 &= not_pinned;
380         while (b1)
381         {
382             from = pop_1st_bit(&b1);
383
384             // Before generating the move, we have to make sure it is legal.
385             // This is somewhat tricky, because the two disappearing pawns may
386             // cause new "discovered checks".  We test this by removing the
387             // two relevant bits from the occupied squares bitboard, and using
388             // the low-level bitboard functions for bishop and rook attacks.
389             b2 = pos.occupied_squares();
390             clear_bit(&b2, from);
391             clear_bit(&b2, checksq);
392             if (!(  (bishop_attacks_bb(ksq, b2) & pos.bishops_and_queens(them))
393                   ||(rook_attacks_bb(ksq, b2)   & pos.rooks_and_queens(them))))
394
395                  (*mlist++).move = make_ep_move(from, to);
396         }
397     }
398   }
399   return int(mlist - mlist_start);
400 }
401
402
403 /// generate_legal_moves() computes a complete list of legal moves in the
404 /// current position. This function is not very fast, and should be used
405 /// only in situations where performance is unimportant. It wouldn't be
406 /// very hard to write an efficient legal move generator, but for the moment
407 /// we don't need it.
408
409 int generate_legal_moves(const Position& pos, MoveStack* mlist) {
410
411   assert(pos.is_ok());
412
413   if (pos.is_check())
414       return generate_evasions(pos, mlist);
415
416   // Generate pseudo-legal moves
417   int n = generate_captures(pos, mlist);
418   n += generate_noncaptures(pos, mlist + n);
419
420   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
421
422   // Remove illegal moves from the list
423   for (int i = 0; i < n; i++)
424       if (!pos.pl_move_is_legal(mlist[i].move, pinned))
425           mlist[i--].move = mlist[--n].move;
426
427   return n;
428 }
429
430
431 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
432 /// move and a pinned pieces bitboard as input, and tests whether
433 /// the move is legal.  If the move is legal, the move itself is
434 /// returned. If not, the function returns false.  This function must
435 /// only be used when the side to move is not in check.
436
437 bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
438
439   assert(pos.is_ok());
440   assert(!pos.is_check());
441   assert(move_is_ok(m));
442   assert(pinned == pos.pinned_pieces(pos.side_to_move()));
443
444   Color us = pos.side_to_move();
445   Color them = opposite_color(us);
446   Square from = move_from(m);
447   Piece pc = pos.piece_on(from);
448
449   // If the from square is not occupied by a piece belonging to the side to
450   // move, the move is obviously not legal.
451   if (color_of_piece(pc) != us)
452       return false;
453
454   Square to = move_to(m);
455
456   // En passant moves
457   if (move_is_ep(m))
458   {
459       // The piece must be a pawn and destination square must be the
460       // en passant square.
461       if (   type_of_piece(pc) != PAWN
462           || to != pos.ep_square())
463           return false;
464
465       assert(pos.square_is_empty(to));
466       assert(pos.piece_on(to - pawn_push(us)) == pawn_of_color(them));
467
468       // The move is pseudo-legal, check if it is also legal
469       return pos.pl_move_is_legal(m, pinned);
470   }
471
472   // Castling moves
473   if (move_is_short_castle(m))
474   {
475       // The piece must be a king and side to move must still have
476       // the right to castle kingside.
477       if (   type_of_piece(pc) != KING
478           ||!pos.can_castle_kingside(us))
479           return false;
480
481       assert(from == pos.king_square(us));
482       assert(to == pos.initial_kr_square(us));
483       assert(pos.piece_on(to) == rook_of_color(us));
484
485       Square g1 = relative_square(us, SQ_G1);
486       Square f1 = relative_square(us, SQ_F1);
487       Square s;
488       bool illegal = false;
489
490       // Check if any of the squares between king and rook
491       // is occupied or under attack.
492       for (s = Min(from, g1); s <= Max(from, g1); s++)
493           if (  (s != from && s != to && !pos.square_is_empty(s))
494               || pos.square_is_attacked(s, them))
495               illegal = true;
496
497       // Check if any of the squares between king and rook
498       // is occupied.
499       for (s = Min(to, f1); s <= Max(to, f1); s++)
500           if (s != from && s != to && !pos.square_is_empty(s))
501               illegal = true;
502
503       return !illegal;
504   }
505
506   if (move_is_long_castle(m))
507   {
508       // The piece must be a king and side to move must still have
509       // the right to castle kingside.
510       if (   type_of_piece(pc) != KING
511           ||!pos.can_castle_queenside(us))
512           return false;
513
514       assert(from == pos.king_square(us));
515       assert(to == pos.initial_qr_square(us));
516       assert(pos.piece_on(to) == rook_of_color(us));
517
518       Square c1 = relative_square(us, SQ_C1);
519       Square d1 = relative_square(us, SQ_D1);
520       Square s;
521       bool illegal = false;
522
523       for (s = Min(from, c1); s <= Max(from, c1); s++)
524           if(  (s != from && s != to && !pos.square_is_empty(s))
525              || pos.square_is_attacked(s, them))
526               illegal = true;
527
528       for (s = Min(to, d1); s <= Max(to, d1); s++)
529           if(s != from && s != to && !pos.square_is_empty(s))
530               illegal = true;
531
532       if (   square_file(to) == FILE_B
533           && (   pos.piece_on(to + DELTA_W) == rook_of_color(them)
534               || pos.piece_on(to + DELTA_W) == queen_of_color(them)))
535           illegal = true;
536
537       return !illegal;
538   }
539
540   // Normal moves
541
542   // The destination square cannot be occupied by a friendly piece
543   if (pos.color_of_piece_on(to) == us)
544       return false;
545
546   // Proceed according to the type of the moving piece.
547   if (type_of_piece(pc) == PAWN)
548   {
549       // If the destination square is on the 8/1th rank, the move must
550       // be a promotion.
551       if (   (  (square_rank(to) == RANK_8 && us == WHITE)
552               ||(square_rank(to) == RANK_1 && us != WHITE))
553            && !move_promotion(m))
554           return false;
555
556       // Proceed according to the square delta between the source and
557       // destionation squares.
558       switch (to - from)
559       {
560       case DELTA_NW:
561       case DELTA_NE:
562       case DELTA_SW:
563       case DELTA_SE:
564       // Capture. The destination square must be occupied by an enemy
565       // piece (en passant captures was handled earlier).
566           if (pos.color_of_piece_on(to) != them)
567               return false;
568           break;
569
570       case DELTA_N:
571       case DELTA_S:
572       // Pawn push. The destination square must be empty.
573           if (!pos.square_is_empty(to))
574               return false;
575           break;
576
577       case DELTA_NN:
578       // Double white pawn push. The destination square must be on the fourth
579       // rank, and both the destination square and the square between the
580       // source and destination squares must be empty.
581       if (   square_rank(to) != RANK_4
582           || !pos.square_is_empty(to)
583           || !pos.square_is_empty(from + DELTA_N))
584           return false;
585           break;
586
587       case DELTA_SS:
588       // Double black pawn push. The destination square must be on the fifth
589       // rank, and both the destination square and the square between the
590       // source and destination squares must be empty.
591           if (   square_rank(to) != RANK_5
592               || !pos.square_is_empty(to)
593               || !pos.square_is_empty(from + DELTA_S))
594               return false;
595           break;
596
597       default:
598           return false;
599       }
600       // The move is pseudo-legal, check if it is also legal
601       return pos.pl_move_is_legal(m, pinned);
602   }
603
604   // Luckly we can handle all the other pieces in one go
605   return (   pos.piece_attacks_square(from, to)
606           && pos.pl_move_is_legal(m, pinned)
607           && !move_promotion(m));
608 }
609
610
611 namespace {
612
613   template<PieceType Piece>
614   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
615
616     Square from;
617     Bitboard b;
618
619     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
620     {
621         from = pos.piece_list(us, Piece, i);
622         b = pos.piece_attacks<Piece>(from) & target;
623         SERIALIZE_MOVES(b);
624     }
625     return mlist;
626   }
627
628   template<>
629   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
630
631     Bitboard b;
632     Square from = pos.king_square(us);
633
634     b = pos.piece_attacks<KING>(from) & target;
635     SERIALIZE_MOVES(b);
636     return mlist;
637   }
638
639   template<PieceType Piece>
640   MoveStack* generate_piece_blocking_evasions(const Position& pos, Bitboard b,
641                                               Bitboard blockSquares, MoveStack* mlist) {
642     while (b)
643     {
644         Square from = pop_1st_bit(&b);
645         Bitboard bb = pos.piece_attacks<Piece>(from) & blockSquares;
646         SERIALIZE_MOVES(bb);
647     }
648     return mlist;
649   }
650
651
652   template<Color Us, Color Them, Bitboard TRank8BB, SquareDelta TDELTA_NE,
653            SquareDelta TDELTA_NW, SquareDelta TDELTA_N
654           >
655   MoveStack* do_generate_pawn_captures(const Position& pos, MoveStack* mlist) {
656
657     Square to;
658     Bitboard pawns = pos.pawns(Us);
659     Bitboard enemyPieces = pos.pieces_of_color(Them);
660
661     // Captures in the a1-h8 (a8-h1 for black) direction
662     Bitboard b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces;
663
664     // Capturing promotions
665     Bitboard b2 = b1 & TRank8BB;
666     while (b2)
667     {
668         to = pop_1st_bit(&b2);
669         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, QUEEN);
670     }
671
672     // Capturing non-promotions
673     b2 = b1 & ~TRank8BB;
674     while (b2)
675     {
676         to = pop_1st_bit(&b2);
677         (*mlist++).move = make_move(to - TDELTA_NE, to);
678     }
679
680     // Captures in the h1-a8 (h8-a1 for black) direction
681     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces;
682
683     // Capturing promotions
684     b2 = b1 & TRank8BB;
685     while (b2)
686     {
687         to = pop_1st_bit(&b2);
688         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, QUEEN);
689     }
690
691     // Capturing non-promotions
692     b2 = b1 & ~TRank8BB;
693     while (b2)
694     {
695         to = pop_1st_bit(&b2);
696         (*mlist++).move = make_move(to - TDELTA_NW, to);
697     }
698
699     // Non-capturing promotions
700     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & pos.empty_squares() & TRank8BB;
701     while (b1)
702     {
703         to = pop_1st_bit(&b1);
704         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
705     }
706
707     // En passant captures
708     if (pos.ep_square() != SQ_NONE)
709     {
710         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
711         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
712
713         b1 = pawns & pos.pawn_attacks(Them, pos.ep_square());
714         assert(b1 != EmptyBoardBB);
715
716         while (b1)
717         {
718             to = pop_1st_bit(&b1);
719             (*mlist++).move = make_ep_move(to, pos.ep_square());
720         }
721     }
722     return mlist;
723   }
724
725   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB,
726            SquareDelta TDELTA_NE, SquareDelta TDELTA_NW, SquareDelta TDELTA_N
727           >
728   MoveStack* do_generate_pawn_noncaptures(const Position& pos, MoveStack* mlist) {
729
730     Bitboard pawns = pos.pawns(Us);
731     Bitboard enemyPieces = pos.pieces_of_color(Them);
732     Bitboard emptySquares = pos.empty_squares();
733     Bitboard b1, b2;
734     Square to;
735
736     // Underpromotion captures in the a1-h8 (a8-h1 for black) direction
737     b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces & TRank8BB;
738     while (b1)
739     {
740         to = pop_1st_bit(&b1);
741         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, ROOK);
742         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, BISHOP);
743         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, KNIGHT);
744     }
745
746     // Underpromotion captures in the h1-a8 (h8-a1 for black) direction
747     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces & TRank8BB;
748     while (b1)
749     {
750         to = pop_1st_bit(&b1);
751         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, ROOK);
752         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, BISHOP);
753         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, KNIGHT);
754     }
755
756     // Single pawn pushes
757     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & emptySquares;
758     b2 = b1 & TRank8BB;
759     while (b2)
760     {
761         to = pop_1st_bit(&b2);
762         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
763         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
764         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
765     }
766     b2 = b1 & ~TRank8BB;
767     while (b2)
768     {
769         to = pop_1st_bit(&b2);
770         (*mlist++).move = make_move(to - TDELTA_N, to);
771     }
772
773     // Double pawn pushes
774     b2 = (Us == WHITE ? (b1 & TRank3BB) << 8 : (b1 & TRank3BB) >> 8) & emptySquares;
775     while (b2)
776     {
777         to = pop_1st_bit(&b2);
778         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
779     }
780     return mlist;
781   }
782
783
784   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB, SquareDelta TDELTA_N>
785   MoveStack* do_generate_pawn_checks(const Position& pos, Bitboard dc, Square ksq, MoveStack* mlist)
786   {
787     // Pawn moves which give discovered check. This is possible only if the
788     // pawn is not on the same file as the enemy king, because we don't
789     // generate captures.
790     Bitboard empty = pos.empty_squares();
791
792     // Find all friendly pawns not on the enemy king's file
793     Bitboard b1 = pos.pawns(Us) & ~file_bb(ksq), b2, b3;
794
795     // Discovered checks, single pawn pushes, no promotions
796     b2 = b3 = (Us == WHITE ? (b1 & dc) << 8 : (b1 & dc) >> 8) & empty & ~TRank8BB;
797     while (b3)
798     {
799         Square to = pop_1st_bit(&b3);
800         (*mlist++).move = make_move(to - TDELTA_N, to);
801     }
802
803     // Discovered checks, double pawn pushes
804     b3 = (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8) & empty;
805     while (b3)
806     {
807         Square to = pop_1st_bit(&b3);
808         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
809     }
810
811     // Direct checks. These are possible only for pawns on neighboring files
812     // of the enemy king
813     b1 &= (~dc & neighboring_files_bb(ksq));
814
815     // Direct checks, single pawn pushes
816     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & empty;
817     b3 = b2 & pos.pawn_attacks(Them, ksq);
818     while (b3)
819     {
820         Square to = pop_1st_bit(&b3);
821         (*mlist++).move = make_move(to - TDELTA_N, to);
822     }
823
824     // Direct checks, double pawn pushes
825     b3 =  (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8)
826         & empty
827         & pos.pawn_attacks(Them, ksq);
828
829     while (b3)
830     {
831         Square to = pop_1st_bit(&b3);
832         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
833     }
834     return mlist;
835   }
836
837   template<PieceType Piece>
838   MoveStack* generate_piece_checks(const Position& pos, Bitboard target, Bitboard dc,
839                                    Square ksq, MoveStack* mlist) {
840     // Discovered checks
841     Bitboard b = target & dc;
842     while (b)
843     {
844         Square from = pop_1st_bit(&b);
845         Bitboard bb = pos.piece_attacks<Piece>(from) & pos.empty_squares();
846         SERIALIZE_MOVES(bb);
847     }
848     // Direct checks
849     b = target & ~dc;
850     Bitboard checkSqs = pos.piece_attacks<Piece>(ksq) & pos.empty_squares();
851     while (b)
852     {
853         Square from = pop_1st_bit(&b);
854         Bitboard bb = pos.piece_attacks<Piece>(from) & checkSqs;
855         SERIALIZE_MOVES(bb);
856     }
857     return mlist;
858   }
859
860   MoveStack* generate_piece_checks_king(const Position& pos, Square from, Bitboard dc,
861                                         Square ksq, MoveStack* mlist) {
862     if (bit_is_set(dc, from))
863     {
864         Bitboard b =   pos.piece_attacks<KING>(from)
865                      & pos.empty_squares()
866                      & ~QueenPseudoAttacks[ksq];
867         SERIALIZE_MOVES(b);
868     }
869     return mlist;
870   }
871
872
873   template<Color Us, Rank TRANK_8, Bitboard TRank3BB, SquareDelta TDELTA_N>
874   MoveStack* do_generate_pawn_blocking_evasions(const Position& pos, Bitboard not_pinned,
875                                                 Bitboard blockSquares, MoveStack* mlist) {
876     Square to;
877
878     // Find non-pinned pawns
879     Bitboard b1 = pos.pawns(Us) & not_pinned;
880
881     // Single pawn pushes. We don't have to AND with empty squares here,
882     // because the blocking squares will always be empty.
883     Bitboard b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & blockSquares;
884     while (b2)
885     {
886         to = pop_1st_bit(&b2);
887
888         assert(pos.piece_on(to) == EMPTY);
889
890         if (square_rank(to) == TRANK_8)
891         {
892             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
893             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
894             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
895             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
896         } else
897             (*mlist++).move = make_move(to - TDELTA_N, to);
898     }
899
900     // Double pawn pushes
901     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & pos.empty_squares() & TRank3BB;
902     b2 = (Us == WHITE ? b2 << 8 : b2 >> 8) & blockSquares;;
903     while (b2)
904     {
905         to = pop_1st_bit(&b2);
906
907         assert(pos.piece_on(to) == EMPTY);
908         assert(Us != WHITE || square_rank(to) == RANK_4);
909         assert(Us != BLACK || square_rank(to) == RANK_5);
910
911         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
912     }
913     return mlist;
914   }
915
916   template<CastlingSide Side>
917   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
918
919     Color us = pos.side_to_move();
920
921     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
922         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
923     {
924         Color them = opposite_color(us);
925         Square ksq = pos.king_square(us);
926
927         assert(pos.piece_on(ksq) == king_of_color(us));
928
929         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
930         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
931         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
932         Square s;
933         bool illegal = false;
934
935         assert(pos.piece_on(rsq) == rook_of_color(us));
936
937         // It is a bit complicated to correctly handle Chess960
938         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
939             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
940                 || pos.square_is_attacked(s, them))
941                 illegal = true;
942
943         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
944             if (s != ksq && s != rsq && pos.square_is_occupied(s))
945                 illegal = true;
946
947         if (   Side == QUEEN_SIDE
948             && square_file(rsq) == FILE_B
949             && (   pos.piece_on(relative_square(us, SQ_A1)) == rook_of_color(them)
950                 || pos.piece_on(relative_square(us, SQ_A1)) == queen_of_color(them)))
951             illegal = true;
952
953         if (!illegal)
954             (*mlist++).move = make_castle_move(ksq, rsq);
955     }
956     return mlist;
957   }
958
959   bool castling_is_check(const Position& pos, CastlingSide side) {
960
961     // After castling opponent king is attacked by the castled rook?
962     File rookFile = (side == QUEEN_SIDE ? FILE_D : FILE_F);
963     Color us = pos.side_to_move();
964     Square ksq = pos.king_square(us);
965     Bitboard occ = pos.occupied_squares();
966
967     clear_bit(&occ, ksq); // Remove our king from the board
968     Square rsq = make_square(rookFile, square_rank(ksq));
969     return bit_is_set(rook_attacks_bb(rsq, occ), pos.king_square(opposite_color(us)));
970   }
971 }