Chess in C and Silicon

A chess engine in C, then in silicon

Made by swr06

Write a small chess engine in plain C. Rebuild the same engine as SystemVerilog hardware. Prove the two agree on every move, run it on the PYNQ-Z2's programmable logic, and finish with a game you play from a serial terminal, drawn on a VGA monitor by your own GPU.

Blue steps: C on the CPU Green steps: RTL on the FPGA Amber steps: Vivado and the board Purple steps: the playable game
A chess position is just twelve 64-bit numbers. Pick a piece set to see its number.

0Before you start

This guide builds one thing twice. First you write a chess engine in about 550 lines of C, small enough to read in an evening. Then you build the same engine again as a circuit, and prove, move by move and node by node, that the hardware gives exactly the same answers as the C.

The work is split the way the Zynq is built:

The programmable logic does the thinking: given a position, it searches for the best move. The Cortex-A9 does everything else: it reads your moves from the UART, checks them, keeps the game's history, and draws the board through your GPU library.

The finished system. Your moves arrive over the USB serial port. The CPU sends a whole position and a START command over AXI; the hardware searches on its own and returns the best move, its score, and how many positions it looked at. The CPU then draws the result through your GPU.

Sending the whole board for every search sounds wasteful, but it is the right design. A position is only 26 register writes, and the search that follows visits about a million positions. It also makes the system robust: the CPU always holds the true game, so nothing can drift out of step.

How each step works

Every step follows the same rhythm, in both halves of the guide:

  1. Concept. What problem this step solves, explained with pictures you can play with.
  2. Code. A short snippet. Each snippet's header tells you which file it goes in, and whether it starts the file (Create) or goes on the end of it (Add to). Copy the snippets in order and you will have the complete project.
  3. Check. How to prove the step is right before moving on.

The interactive figures run a JavaScript copy of the C engine inside this page. That copy was tested against the C engine on every test vector, so what the figures show is exactly what your code will do.

What has been tested

CheckHowResult
C perft: 6 standard positions to depth 5gcc and clang, -std=c99 -Wall -Wextra -pedanticAll 30 counts correct
RTL against C: attacks, moves, legality, evaluationVerilator 5.0201,109 positions, 29,666 moves, 2,218 move lists, no mismatches
Full searches and perfts, hardware against CVerilator 5.020577 runs, about 2.4 million nodes: same nodes, score and best move every time
AXI registers, abort, both CPU driversVerilator, with the real C and Python driver codePassed
The game program: UART input, rendering, rules, engine repliesmain_game.c against the Verilated core, plus models of your GPU and the UARTScripted session matches the page; screenshots in Part 4 are its output
Size estimateYosys synth_xilinxAbout 11,400 LUTs (21%), 16 block RAMs (11%)
Vivado synthesis, timing, bitstreamVivadoNot run: Vivado was not available
The physical boardPYNQ-Z2Not run: no board was available

So the chess logic, the register interface and the game program are proven in simulation. The Vivado and board steps (Parts 3 and 4) are written from AMD and PYNQ documentation, and they give the exact output to expect, so if anything differs you will see it at once.

Tools

ToolForNotes
A C compilerPart 1MSYS2 UCRT64 gcc, or Visual Studio 2019 16.8 or later
AMD VivadoParts 2 and 3Includes the xsim simulator. The free edition supports the XC7Z020
AMD VitisSteps 39 and 43 to 48Installed with Vivado if you tick it
PYNQ SD imageStep 38 only (optional)From pynq.io/boards
PuTTY or Tera TermSteps 39 and 48Any serial terminal works

Folders

Create the project folder. The guide uses C:\chess; any path without spaces works.

Command Prompt
mkdir C:\chess
cd /d C:\chess
mkdir c rtl tb sw scripts vectors
Expected output
C:\chess
  c\         chess.h, main.c, gen_vectors.c       the engine and its tools
  rtl\       chess_pkg.sv ... chess_axi_top.v     the hardware
  tb\        tb_functions.sv ... tb_axi.sv        hardware tests
  sw\        chess_pl.h, main_baremetal.c,        code for the Cortex-A9
             game.h, chess_pynq.py,               and for PYNQ
             samgl.h, sprites.h, uart_in.h,       the playable game (Part 4)
             render.h, main_game.c
  scripts\   run_sim.bat, build.tcl
  vectors\   written by gen_vectors

Prefer not to type? gives you every file in this guide as a ZIP, plus the finished killer-move upgrade from Part 5. Still read the steps: the point is to understand every line.

Part 1

The engine, in plain C

The C engine has two jobs. It teaches each algorithm in a form you can run in seconds, and it is the golden model: the reference that the hardware must match exactly. Everything lives in one header, c/chess.h, which any program can include.

1Squares and bitboards

Goal: describe a chess position with nothing but numbers, in a form that both C and hardware handle well.

Concept

Give every square a number from 0 to 63. Start at a1, go along the rank to h1, then up to the next rank:

square = 8 × (rank − 1) + file   (file a = 0 ... h = 7)

So a1 = 0, e1 = 4, e4 = 28, a8 = 56 and h8 = 63. Hover over the board to see how any square gets its number.

Square numbers. Six bits are enough for a square: the top three are the rank and the bottom three are the file. This numbering must be identical in the C and the RTL.

Now the key idea of this whole project. A 64-bit number has exactly one bit per square. So we can store "where are the white pawns?" as one number, called a bitboard, where bit n is 1 if a white pawn stands on square n. At the start, the white pawns are on squares 8 to 15, so their bitboard is 0x000000000000FF00.

Twelve bitboards hold every piece on the board: six piece types for each of two colors. The index is color × 6 + type:

Index01234567891011
PiecesPNBRQKpnbrqk

Three more facts finish a position: whose turn it is, which castling rights are left (four bits: white kingside, white queenside, black kingside, black queenside), and the en-passant square, if a pawn has just moved two squares. We use 64 to mean "no en-passant square".

The move word

A move fits in 15 bits: six for the from-square, six for the to-square, three for a promotion piece.

BitsMeaninge2 to e4a7 to a8, promote to queen
5:0from square1248
11:6to square2856
14:12promotion: 0 none, 1 knight, 2 bishop, 3 rook, 4 queen04
as a number0x070C0x4E30

There is no "capture" flag and no "castling" flag. The position already tells you if something stands on the destination, or if a king moved two squares. Fewer fields means fewer ways for the C and hardware to disagree. And since a1-to-a1 can never be a real move, the move word 0 means "no move".

One small trick: promotion codes 1 to 4 equal the piece-type numbers of knight to queen. So the promoted piece's board index needs no conversion at all.

Code

This first snippet starts chess.h: the types, the position, and macros to build and take apart move words. MAKE_MOVE(12, 28, 0) is e2 to e4.

Create c/chess.hpart 1 of 18
/* chess.h - the whole golden chess engine, in plain C (C99).
 * Include it from any program: #include "chess.h"                     */
#ifndef CHESS_H
#define CHESS_H

#include <stdint.h>
#include <string.h>

typedef uint64_t U64;     /* a bitboard: bit n is square n (a1 = 0, h8 = 63) */
typedef uint16_t Move;    /* bits 5:0 from, 11:6 to, 14:12 promotion        */

enum { WHITE = 0, BLACK = 1 };
enum { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING };   /* piece types 0..5 */
enum { WK = 1, WQ = 2, BK = 4, BQ = 8 };            /* castling rights  */

#define NO_EP     64      /* "there is no en-passant square"       */
#define MAX_PLY   32      /* deepest search, same as the RTL stack */
#define MAX_MOVES 256     /* room for one move list                */

/* One chess position. The board index is color * 6 + type,
 * so bb[0] is the white pawns and bb[11] is the black king. */
typedef struct {
    U64 bb[12];
    int side;      /* WHITE or BLACK: whose turn it is            */
    int castle;    /* castling rights still available (WK|WQ|...) */
    int ep;        /* en-passant target square, or NO_EP          */
} Position;

/* Squares and move words */
#define BIT(sq)                    ((U64)1 << (sq))
#define MAKE_MOVE(from, to, promo) ((Move)((from) | ((to) << 6) | ((promo) << 12)))
#define MOVE_FROM(m)               ((m) & 63)
#define MOVE_TO(m)                 (((m) >> 6) & 63)
#define MOVE_PROMO(m)              (((m) >> 12) & 7)

Notice that Position holds no "occupied squares" bitboard. We calculate that when we need it, so it can never go stale.

Line by line

  • #ifndef CHESS_H ... #define CHESS_H is an include guard: if two files both include chess.h, the second copy is skipped, so nothing is defined twice.
  • typedef uint64_t U64: one bitboard. Bit n is square n, where n = rank × 8 + file, counting from 0. So a1 is 0, h1 is 7, a2 is 8, e4 is 3 × 8 + 4 = 28, and h8 is 63.
  • typedef uint16_t Move: a move packed into 15 bits. e2e4 is from 12, to 28, no promotion: 12 + 28 × 64 = 1804, or 0x070C. Packing a move into one small number makes move lists cheap to store, and in Part 2 a move fits in one 15-bit RAM word.
  • enum { WHITE = 0, BLACK = 1 }: because the colours are 0 and 1, !side is the other colour, and side * 6 is where that colour's boards start.
  • The piece-type enum gives PAWN = 0 up to KING = 5. The promotion field reuses it: 1 to 4 are knight to queen, and 0 means "no promotion".
  • Castling rights are four separate bits, so they combine with | and test with &: "White can still castle short" is castle & WK.
  • NO_EP is 64, one past the last square, so it can never be confused with a real square. MAX_PLY 32 is the deepest the search may go; the hardware stack in Part 2 has exactly 32 rows. MAX_MOVES 256 is comfortably above the most legal moves any chess position has (218).
  • Position: twelve boards, indexed color * 6 + type. The black knights are board 1 × 6 + 1 = 7.
  • BIT(sq) casts to U64 before shifting. 1 << 40 would shift a 32-bit int and is undefined behaviour in C; (U64)1 << 40 is correct.
  • MOVE_FROM, MOVE_TO and MOVE_PROMO undo MAKE_MOVE: shift the field down to bit 0, then mask it with 63 (six bits) or 7 (three bits).

2Bit tricks

Goal: learn the four operations that answer almost every question about bitboards.

Concept

With bitboards, questions about sets of squares become single operations on numbers:

ExpressionMeaningChess example
a & bin bothsquares I attack that hold an enemy piece
a | bin eitherall my bishops and queens
~anot inempty squares, from the occupied ones
a << 8move every bit up one rankwhite pawn pushes

Two more are less obvious and worth working through once, because loops over pieces use them constantly. Take b = 0110 1000 in binary:

Expected output
b           = 0110 1000
b - 1       = 0110 0111     borrowing flips the lowest 1, and every 0 below it
b & (b - 1) = 0110 0000     the lowest 1 is gone

-b = ~b + 1 = 1001 1000     two's complement
b & -b      = 0000 1000     only the lowest 1 is left

So b & (b - 1) removes the lowest piece, and b & -b isolates it. A loop over every piece in a set looks like this:

C
while (pieces) {
    int sq = lsb(pieces);       /* the lowest square in the set */
    /* ... use sq ... */
    pieces &= pieces - 1;       /* remove it; the loop ends when the set is empty */
}
Try them. Click squares on the input board, then pick an operation. "Right, no mask" shows a bug you will meet in the next step: pieces on the h-file wrap around to the a-file.
Code

The masks are named sets of squares: FILE_A is the a-file, NOT_A is everything else. lsb finds the number of the lowest set square, and count_bits counts the set squares. Processors have instructions for both, and GCC and Clang expose them as __builtin_ctzll (count trailing zeros) and __builtin_popcountll; on the Cortex-A9 they become two instructions. The #if keeps a plain loop as a fallback for other compilers, so the file still builds anywhere. This one change makes perft about 30% faster. side_pieces combines one side's six boards, and occupied combines both sides.

Add to c/chess.hpart 2 of 18
#define ALL_SQ   (~(U64)0)
#define FILE_A   0x0101010101010101ULL
#define FILE_B   (FILE_A << 1)
#define FILE_G   (FILE_A << 6)
#define FILE_H   (FILE_A << 7)
#define NOT_A    (~FILE_A)
#define NOT_H    (~FILE_H)
#define NOT_AB   (~(FILE_A | FILE_B))
#define NOT_GH   (~(FILE_G | FILE_H))
#define RANK_1   0x00000000000000FFULL
#define RANK_4   0x00000000FF000000ULL
#define RANK_5   0x000000FF00000000ULL
#define RANK_8   0xFF00000000000000ULL

/* Number of the lowest set square. b must not be 0.
 * GCC and Clang (including Vitis's ARM gcc) turn the builtin into one or two
 * instructions; the loop is a portable fallback for other compilers. */
static inline int lsb(U64 b) {
#if defined(__GNUC__) || defined(__clang__)
    return __builtin_ctzll(b);
#else
    int sq = 0;
    while (!(b & 1)) { b >>= 1; sq++; }
    return sq;
#endif
}

static inline int count_bits(U64 b) {
#if defined(__GNUC__) || defined(__clang__)
    return __builtin_popcountll(b);
#else
    int n = 0;
    while (b) { b &= b - 1; n++; }      /* each pass removes one bit */
    return n;
#endif
}

static inline U64 side_pieces(const Position *p, int color) {
    const U64 *b = p->bb + color * 6;
    return b[0] | b[1] | b[2] | b[3] | b[4] | b[5];
}

static inline U64 occupied(const Position *p) {
    return side_pieces(p, WHITE) | side_pieces(p, BLACK);
}

Every function here is static inline. That lets the whole engine live in one header: each program that includes it gets its own copy, and the compiler does not warn about functions a program does not use.

Line by line

  • FILE_A is 0x0101010101010101: one set bit in each byte, and each byte is one rank, so it is the bottom-left bit of every rank, the a-file. Shifting it left by one gives the b-file, and so on.
  • NOT_A, NOT_H, NOT_AB, NOT_GH exist to stop wrap-around. Moving a set one square east is b << 1, but a piece on h4 (bit 31) then lands on bit 32, which is a5: it has wrapped onto the next rank. Every square east of a piece is never on the a-file, so (b << 1) & NOT_A removes exactly the wrapped bits. Moves two files east use NOT_AB.
  • RANK_4 and RANK_5 are where a double pawn push lands for White and Black. RANK_1 and RANK_8 are the promotion ranks.
  • lsb(b) counts the zero bits below the lowest 1. For b = binary 10100 it returns 2. It is undefined for 0, so every caller checks b first.
  • side_pieces ORs one colour's six boards together; occupied ORs both colours. Both are a handful of instructions, which is why the position does not store them.

One idiom appears in almost every function from here on. It visits every square in a set, lowest first:

C
while (b) {                 /* until no squares are left       */
    int sq = lsb(b);        /* the lowest one                  */
    b &= b - 1;             /* remove it: 10100 & 10011 = 10000 */
    /* ... use sq ... */
}

Subtracting 1 turns the lowest 1 into 0 and every 0 below it into 1, so the AND clears exactly that one bit.

3Knights, kings and pawns

Goal: for any set of knights, kings or pawns, find every square they attack, in a handful of operations.

Concept

An attack is not the same as a legal move. A pawn attacks diagonally even when nothing stands there, and a pinned piece still attacks. Attacks are the basic building block for both "is the king in check?" and "where can this piece go?".

Shifting a bitboard moves every piece at once by the same number of squares. A knight on square s can jump to s + 17, + 15, + 10, + 6, − 6, − 10, − 15 and − 17. So the knight's attacks are just eight shifts ORed together.

Shifts know nothing about the edge of the board, though. A knight on h4 (square 31), shifted by + 10, lands on square 41: b6. That is not a knight move. It wrapped around the edge. The fix is a mask: a knight that moves two files to the right can never land on file a or b, so we throw those squares away.

StepShiftMask after shifting
Up a rank+8none needed: it falls off the top
Down a rank−8none needed
Right+1NOT_A
Left−1NOT_H
Up-right, down-right+9, −7NOT_A
Up-left, down-left+7, −9NOT_H
Knight, two files right+10, −6NOT_AB
Knight, two files left+6, −10NOT_GH
Attack explorer. Each attacked square is labelled with the shift that reaches it. Move the knight to the h-file or a corner and watch the masks drop the shifts that would wrap.

Because the functions take a set, the same code works for one piece or for all of them. Pass all your knights and you get every square any of them attacks. That is what makes the next steps so short.

Code
Add to c/chess.hpart 3 of 18
/* Shift every bit by s squares: up for s > 0, down for s < 0. */
static inline U64 shift(U64 b, int s) {
    return s >= 0 ? b << s : b >> -s;
}

static inline U64 knight_attacks(U64 set) {
    return (shift(set, 17) & NOT_A)  | (shift(set, 15) & NOT_H)
         | (shift(set, 10) & NOT_AB) | (shift(set, 6)  & NOT_GH)
         | (shift(set, -6) & NOT_AB) | (shift(set, -10) & NOT_GH)
         | (shift(set, -15) & NOT_A) | (shift(set, -17) & NOT_H);
}

static inline U64 king_attacks(U64 set) {
    return shift(set, 8) | shift(set, -8)
         | (shift(set, 1) & NOT_A)  | (shift(set, -1) & NOT_H)
         | (shift(set, 9) & NOT_A)  | (shift(set, 7)  & NOT_H)
         | (shift(set, -7) & NOT_A) | (shift(set, -9) & NOT_H);
}

static inline U64 pawn_attacks(int color, U64 set) {
    if (color == WHITE) return (shift(set, 9) & NOT_A)  | (shift(set, 7) & NOT_H);
    else                return (shift(set, -7) & NOT_A) | (shift(set, -9) & NOT_H);
}

White pawns attack up and to the sides (+9 and +7). Black pawns attack down (−7 and −9). The king is the eight single steps.

Line by line

  • shift(b, s) exists because C cannot shift by a negative amount. Positive s moves pieces up the board (towards rank 8), negative s moves them down. Bits pushed past bit 63 or below bit 0 simply disappear, so the top and bottom edges of the board need no masks at all. Only the left and right edges can wrap.
  • A knight jump is one of eight offsets. Up two ranks is +16, so up two and right one is +17, up two and left one is +15. Up one and right two is +8 + 2 = +10, up one and left two is +6. The other four are the same jumps downwards.
  • Each offset that moves right must not land on the files it cannot reach: one file right can never land on the a-file (NOT_A), two files right never on a or b (NOT_AB). Moves to the left use NOT_H and NOT_GH.
  • knight_attacks takes a set, not one square. Pass it all your knights at once and you get every square any of them attacks: one call instead of a loop. The attack map in Step 5 depends on that.
  • The king's eight steps are ±8 (straight up or down: never wraps, no mask), ±1 (sideways) and ±7, ±9 (diagonal).
  • pawn_attacks covers captures only. Pushes are not attacks (a pawn cannot capture straight ahead), so they are generated separately in Step 8.

4Sliding pieces

Goal: rooks, bishops and queens: slide along a line until something is in the way.

Concept

A rook moves along a ray until it hits a piece. The square it hits counts as attacked, because whatever stands there might be capturable (or, if it is your own piece, defended). Squares beyond it are not attacked.

So we walk the ray one square at a time. The set set holds the front of the ray. Each pass steps it one square, adds the new square to the attacks, and then drops any ray that has just hit a piece:

One ray, one iteration at a time. The rook starts on d4. The amber outline is the front of the ray; red squares are attacked. Click squares to move the blockers, and try each direction.

The loop handles any number of sliders at once: if set holds both rooks, both rays advance together. A bishop is four diagonal rays, a rook is four straight rays, and a queen is both.

Notice the blocker's square is attacked, even when it is your own piece. We remove our own pieces later, in move generation. Keeping them in the attack set means the same function can say "my pawn on d6 is defended".

The attack explorer again, now with sliders. Choose "Click adds blockers" and build a position, then compare the rook, bishop and queen.
Code
Add to c/chess.hpart 4 of 18
/* All squares reached by sliding from every piece in "set" in one
 * direction (s = step, mask = squares a wrapped step can never reach). */
static inline U64 slide(U64 set, U64 occ, int s, U64 mask) {
    U64 attacks = 0;
    while (set) {
        set = shift(set, s) & mask;   /* step one square              */
        attacks |= set;               /* this square is attacked      */
        set &= ~occ;                  /* only empty squares go on     */
    }
    return attacks;
}

static inline U64 bishop_attacks(U64 set, U64 occ) {
    return slide(set, occ, 9, NOT_A)  | slide(set, occ, 7, NOT_H)
         | slide(set, occ, -7, NOT_A) | slide(set, occ, -9, NOT_H);
}

static inline U64 rook_attacks(U64 set, U64 occ) {
    return slide(set, occ, 8, ALL_SQ) | slide(set, occ, -8, ALL_SQ)
         | slide(set, occ, 1, NOT_A)  | slide(set, occ, -1, NOT_H);
}

The while loop runs at most seven times per direction, because a ray can cross at most seven squares. Hold on to that fact: in Part 2 it is the reason this loop turns into just three layers of logic.

Line by line, with an example

Take a rook on d4 with a pawn on d6, and slide north (s = +8). set starts as just d4.

  1. Pass 1: shift moves the set to d5. d5 joins attacks. d5 is empty, so it stays in set.
  2. Pass 2: the set moves to d6, and d6 joins attacks: the rook attacks the blocker (that is how captures happen). d6 is occupied, so set &= ~occ removes it, and the set is now empty.
  3. The loop ends. attacks is {d5, d6}: everything up to and including the first piece.
  • The blocker may be one of your own pieces. It is still included: the square is "defended". Step 8 removes your own pieces when it turns attacks into moves.
  • mask plays the same role as in the knight: east-going directions (+9, +1, −7) use NOT_A, west-going ones (+7, −1, −9) use NOT_H, and straight up or down needs no mask (ALL_SQ).
  • Because set may hold several pieces, one call slides all of them at once. bishop_attacks and rook_attacks just combine four directions each, and a queen is simply passed to both.

5The attack map, and check

Goal: one function that answers every "is this square attacked?" question in the engine.

Concept

Since every attack function takes a set, we can compute everything one side attacks with five calls: pawns, knights, king, then bishops and queens together (both slide diagonally), then rooks and queens together. The result is the side's attack map.

"Am I in check?" is then a single AND: is my king's bit inside the opponent's attack map?

Attack maps. Red squares are attacked by the chosen side. The ringed square is the other side's king. The "Check" position is the fastest checkmate in chess: White's king is inside Black's map.
Code
Add to c/chess.hpart 5 of 18
/* Every square attacked by every piece of one color. */
static inline U64 side_attacks(const Position *p, int color) {
    const U64 *b = p->bb + color * 6;
    U64 occ = occupied(p);
    return pawn_attacks(color, b[PAWN])
         | knight_attacks(b[KNIGHT])
         | king_attacks(b[KING])
         | bishop_attacks(b[BISHOP] | b[QUEEN], occ)
         | rook_attacks(b[ROOK] | b[QUEEN], occ);
}

/* Is the side to move in check? */
static inline int in_check(const Position *p) {
    U64 my_king = p->bb[p->side * 6 + KING];
    return (side_attacks(p, !p->side) & my_king) != 0;
}

This map does a lot of work later. It decides whether a move left your king in check, whether castling crosses an attacked square, and in Part 2 the hardware computes it in a single clock cycle.

Line by line

  • b points at the six boards of one colour, so b[KNIGHT] is that colour's knights.
  • occ includes both colours: any piece stops a ray.
  • Queens are added to both the bishop set and the rook set, because a queen moves like both.
  • in_check asks one question of the map: is my king on a square the other side attacks? !p->side is the opponent.

Computing the whole map to answer one question looks wasteful, and a CPU engine would instead look outward from the king. We keep the simple version on purpose: it is short, obviously correct, and it is exactly what the hardware builds, so the C and the RTL can be compared line for line.

6Making a move

Goal: play a move on a position, including captures, en passant, castling and promotion.

Concept

Engines search by trying a move, looking deeper, then taking it back. "Taking it back" is a common source of bugs, so we avoid it entirely with copy-make: copy the position, then change the copy. The parent is never touched, so there is nothing to undo.

C
Position child = *p;            /* copy  (a Position is 112 bytes)   */
make_move(&child, m);           /* make  (p itself is unchanged)     */

The hardware does the same thing: it keeps the parent on a stack and builds the child in a separate register. So copy-make keeps the C and the RTL close.

make_move does six things, in order:

  1. Capture. Clear the destination square on all six enemy boards. No flag is needed: if nothing is there, nothing changes.
  2. En passant. If a pawn lands on the en-passant square, remove the enemy pawn behind it.
  3. Move the piece. Clear from, set to. For a promotion, set to on the new piece's board instead.
  4. Castling rook. If the king moved two squares, move the rook too.
  5. Castling rights. Anything leaving or arriving on e1, a1, h1, e8, a8 or h8 removes the matching rights. This one rule covers a king moving, a rook moving, and a rook being captured.
  6. New en-passant square. A double pawn push sets it to the square it jumped over. Every other move clears it.
make_move, step by step. Pick a move type. The bold steps did something for this move. In the en-passant example, the dashed outline marks the pawn that disappears even though nothing moved onto its square.

The rook squares for castling come from two small formulas:

Expected output
e1 to g1:  rook_from = to + 1 = 7 (h1)     rook_to = (from + to) / 2 = 5 (f1)
e1 to c1:  rook_from = to - 2 = 0 (a1)     rook_to = (from + to) / 2 = 3 (d1)
Code
Add to c/chess.hpart 6 of 18
/* Castling rights lost when a piece leaves or lands on square sq. */
static inline int rights_lost(int sq) {
    switch (sq) {
    case 4:  return WK | WQ;     /* e1: white king */
    case 7:  return WK;          /* h1 rook        */
    case 0:  return WQ;          /* a1 rook        */
    case 60: return BK | BQ;     /* e8: black king */
    case 63: return BK;          /* h8 rook        */
    case 56: return BQ;          /* a8 rook        */
    default: return 0;
    }
}

/* Play move m on *p. Callers copy the position first ("copy-make"). */
static inline void make_move(Position *p, Move m) {
    int us = p->side;
    int from = MOVE_FROM(m), to = MOVE_TO(m), promo = MOVE_PROMO(m);
    U64 from_bit = BIT(from), to_bit = BIT(to);
    U64 *mine   = p->bb + us * 6;
    U64 *theirs = p->bb + (!us) * 6;
    int moved = PAWN, t;

    while (moved < KING && !(mine[moved] & from_bit)) moved++;

    /* 1. Capture: clear the destination on all enemy boards. */
    for (t = PAWN; t <= KING; t++) theirs[t] &= ~to_bit;

    /* 2. En passant: the captured pawn stands behind the destination. */
    if (moved == PAWN && to == p->ep)
        theirs[PAWN] &= ~(us == WHITE ? to_bit >> 8 : to_bit << 8);

    /* 3. Move the piece. Promotion codes 1..4 equal KNIGHT..QUEEN. */
    mine[moved] &= ~from_bit;
    mine[promo ? promo : moved] |= to_bit;

    /* 4. Castling: the king moved two squares, so move the rook too. */
    if (moved == KING && (to == from + 2 || to == from - 2)) {
        int rook_from = to > from ? to + 1 : to - 2;
        int rook_to   = (from + to) / 2;
        mine[ROOK] = (mine[ROOK] & ~BIT(rook_from)) | BIT(rook_to);
    }

    /* 5. Castling rights. */
    p->castle &= ~(rights_lost(from) | rights_lost(to));

    /* 6. En-passant square: only right after a double pawn push. */
    if (moved == PAWN && (to == from + 16 || to == from - 16))
        p->ep = (from + to) / 2;
    else
        p->ep = NO_EP;

    p->side = !us;
}

The first line finds which of our six piece types stands on the from-square. A switch statement, rights_lost, lists the six special squares, so step 5 is a single line.

Line by line, following the numbered comments

  • Which piece moves? The while loop tries our pawns, then knights, and so on, until it finds the board with a piece on from. It stops before KING, because if no other board matched, the piece must be the king.
  • 1. Capture. Rather than find out which enemy piece stands on to, it clears to on all six enemy boards. Five of the six operations change nothing, but there is no branch and no search, and the result is always right.
  • 2. En passant. If a pawn moves to the en-passant square, the pawn it captures is not on to but one rank behind it: 8 squares lower for White (to_bit >> 8), 8 higher for Black.
  • 3. Move the piece. Clear from on the mover's board, then set to. On a promotion, the bit is set on the new piece's board instead: promo is 1 to 4, which are exactly KNIGHT to QUEEN.
  • 4. Castling is the only move that moves two pieces. The king moved two squares, so the rook jumps over it. For e1g1 (4 to 6): the rook comes from to + 1 = 7, h1, and goes to (4 + 6) / 2 = 5, f1. For e1c1 (4 to 2): from to − 2 = 0, a1, to (4 + 2) / 2 = 3, d1. The same formulas work for Black, 56 squares higher.
  • 5. Castling rights. Any move from or to e1, a1 or h1 (or their black twins) loses the matching rights, whether the king or rook moved or a rook was captured. rights_lost returns the bits to clear.
  • 6. En-passant square. Only a double pawn push creates one: the square it passed over, (from + to) / 2. For e2e4 that is (12 + 28) / 2 = 20, e3. Every other move clears it, because the right to capture en passant lasts one move only.
  • Finally the side to move flips. Note that make_move never checks anything: it trusts that the move came from the generator. Checking is the next step's job.

8Generating moves, in a good order

Goal: list every move, with the moves most likely to be good coming first.

Concept

The search in Step 13 becomes dramatically faster when it tries good moves first. Instead of generating moves and then sorting them, we generate them in a good order from the start, in seven stages:

StageMovesWhy this order
0pawn pushes that promotealmost always strong
1 to 5captures of a queen, rook, bishop, knight, then pawn (including en passant)take the most valuable victim first
6everything else, including castling"quiet" moves

Inside each stage we visit our pieces from pawn up to king. So within "capture a queen", a pawn takes the queen before a queen does. Together that is a classic rule called most valuable victim, least valuable attacker. Promotions come out as queen, rook, bishop, then knight.

This exact order is part of the specification: the hardware must write exactly the same list, in exactly the same order. That makes the tests in Part 2 very strong, because one move out of place shows up immediately.

The generated list, in search order. Hover over or tap a move to see it on the board. Notice the captures are grouped by victim, not by which piece makes them.

These are pseudo-legal moves: they obey how pieces move, but are not yet checked for king safety. The search checks each move only when it actually tries it (Step 7). At a node that cuts off after its first move, the other legality tests are never needed.

Code

First, one function that answers "where can this one piece go, in this stage?". Pawn pushes are special (they are not attacks), so they come first. Every other piece starts from its attack set: in the quiet stage keep the empty squares, in a capture stage keep only the squares holding that stage's victim.

Add to c/chess.hpart 8 of 18
/* Generation stages, in the order the search will try them. */
enum { ST_PROMO, ST_CAP_Q, ST_CAP_R, ST_CAP_B, ST_CAP_N, ST_CAP_P, ST_QUIET };

/* Destinations of ONE piece (the single bit in from_bit) in one stage. */
static inline U64 stage_targets(const Position *p, int stage, int type, U64 from_bit) {
    int us = p->side;
    U64 occ = occupied(p);
    U64 att, victims;

    /* Pawn pushes: promotions in ST_PROMO, the rest in ST_QUIET. */
    if (stage == ST_PROMO || (stage == ST_QUIET && type == PAWN)) {
        int up = us == WHITE ? 8 : -8;
        U64 one, two;
        if (type != PAWN) return 0;
        one = shift(from_bit, up) & ~occ;
        if (stage == ST_PROMO) return one & (RANK_1 | RANK_8);
        two = shift(one, up) & ~occ & (us == WHITE ? RANK_4 : RANK_5);
        return (one & ~(RANK_1 | RANK_8)) | two;
    }

    switch (type) {
    case PAWN:   att = pawn_attacks(us, from_bit);                     break;
    case KNIGHT: att = knight_attacks(from_bit);                       break;
    case BISHOP: att = bishop_attacks(from_bit, occ);                  break;
    case ROOK:   att = rook_attacks(from_bit, occ);                    break;
    case QUEEN:  att = bishop_attacks(from_bit, occ)
                     | rook_attacks(from_bit, occ);                    break;
    default:     att = king_attacks(from_bit);                         break;
    }

    if (stage == ST_QUIET) {
        U64 t = att & ~occ;
        if (type == KING) {           /* castling: right + empty squares */
            if (us == WHITE) {
                if ((p->castle & WK) && !(occ & 0x60ULL)) t |= BIT(6);
                if ((p->castle & WQ) && !(occ & 0x0EULL)) t |= BIT(2);
            } else {
                if ((p->castle & BK) && !(occ & (0x60ULL << 56))) t |= BIT(62);
                if ((p->castle & BQ) && !(occ & (0x0EULL << 56))) t |= BIT(58);
            }
        }
        return t;
    }

    /* Capture stages ST_CAP_Q..ST_CAP_P pick the victim QUEEN..PAWN. */
    victims = p->bb[(!us) * 6 + QUEEN - (stage - ST_CAP_Q)];
    if (stage == ST_CAP_P && type == PAWN && p->ep != NO_EP)
        victims |= BIT(p->ep);
    return att & victims;
}

Line by line

  1. The function answers one question: "where can this one piece go, in this stage?" from_bit has exactly one bit set.
  2. Pawn pushes are handled first, because they are the only moves that are not attacks. one is the square ahead if it is empty. In the promotion stage, keep it only if it is on the last rank. In the quiet stage, keep it only if it is not on the last rank (that move was already made as a promotion), plus two: one more step, only from the starting rank, which is why it is masked with rank 4 (White) or 5 (Black).
  3. Any piece type other than a pawn has no moves in the promotion stage, hence return 0.
  4. For everything else, att is the set of squares the piece attacks, from Steps 3 and 4. A queen is a bishop plus a rook.
  5. Quiet stage: attacked squares that are empty. The king adds castling: the right must still exist and the squares between king and rook must be empty (0x60 is f1 and g1; 0x0E is b1, c1 and d1).
  6. Capture stages: QUEEN - (stage - ST_CAP_Q) picks the victim type: the queen stage takes queens, the next rooks, and so on down to pawns. The answer is attacks that land on a victim. In the pawn stage, a pawn may also "capture" the en-passant square, which is empty.

The castling check here only looks at the right and the empty squares between king and rook. Whether those squares are attacked is legal_after's job.

Then the generator itself. It is four nested loops, and in Part 2 each loop becomes one register in the hardware:

Expected output
for each stage                         -> register "stage"
  for each piece type                  -> register "ptype"
    for each piece of that type        -> register "pieces"  (lowest bit first)
      for each destination             -> register "targets" (lowest bit first)
        write the move
Add to c/chess.hpart 9 of 18
/* Write pseudo-legal moves to list; return how many. The order is fixed:
 * promotions, captures (best victim, then cheapest attacker), quiet moves.
 * captures_only stops before the quiet stage (used by quiescence). */
static inline int generate_moves(const Position *p, Move *list, int captures_only) {
    const U64 *mine = p->bb + p->side * 6;
    int last_stage = captures_only ? ST_CAP_P : ST_QUIET;
    int n = 0, stage, type;

    for (stage = ST_PROMO; stage <= last_stage; stage++) {
        for (type = PAWN; type <= KING; type++) {
            U64 pieces = mine[type];
            while (pieces) {
                int from = lsb(pieces);
                U64 targets = stage_targets(p, stage, type, BIT(from));
                pieces &= pieces - 1;               /* next piece next time */
                while (targets) {
                    int to = lsb(targets);
                    targets &= targets - 1;
                    if (type == PAWN && (BIT(to) & (RANK_1 | RANK_8))) {
                        int promo;
                        for (promo = QUEEN; promo >= KNIGHT; promo--)
                            list[n++] = MAKE_MOVE(from, to, promo);
                    } else {
                        list[n++] = MAKE_MOVE(from, to, 0);
                    }
                }
            }
        }
    }
    return n;
}

Line by line

  1. Three nested loops: stage, then piece type from pawn to king, then each piece of that type. That nesting is the move order: all queen captures by pawns, then by knights, ..., then all rook captures, and so on.
  2. lsb(pieces) takes the lowest piece; pieces &= pieces - 1 removes it (Step 2's trick). The same two lines walk through targets.
  3. A pawn reaching rank 1 or 8 produces four moves, queen first, because the queen is almost always the best choice and should be searched first.
  4. captures_only stops after the last capture stage. Quiescence uses it: it only looks at captures.
  5. The moves are pseudo-legal: they may leave the king in check. Checking is done later, one move at a time, by legal_after. Most of the time the search cuts off before it reaches the illegal ones, so that work is never done.

9Proving the rules with perft

Goal: prove that steps 1 to 8 are exactly right before writing any search.

Concept

Perft counts every legal sequence of moves to a fixed depth. From the start position there are 20 legal first moves, 400 two-move sequences, 8,902 three-move sequences, and so on. These counts have been published for many test positions, so they are a perfect check: perft has no evaluation and no pruning, so a wrong count can only mean a rules bug.

Expected output
perft(position, 0) = 1
perft(position, d) = sum over each legal move of perft(child, d - 1)
Perft counts and "divide". Divide splits the count by first move, which is how you find a bug: compare against another engine, and the move whose count differs is where to look.
Code

Perft is the simplest recursive function in the engine, and it shows the shape every search will have: generate, copy, make, test legality, recurse.

Add to c/chess.hpart 10 of 18
/* Count every legal move sequence of exactly "depth" moves. */
static inline uint64_t perft(const Position *p, int depth) {
    Move list[MAX_MOVES];
    uint64_t leaves = 0;
    int n, i;
    if (depth == 0) return 1;
    n = generate_moves(p, list, 0);
    for (i = 0; i < n; i++) {
        Position child = *p;                  /* copy ...  */
        make_move(&child, list[i]);           /* ... make  */
        if (legal_after(&child, list[i]))
            leaves += perft(&child, depth - 1);
    }
    return leaves;
}

Line by line

  1. At depth 0 the current position is one leaf: return 1.
  2. Otherwise generate every pseudo-legal move. For each one, copy the position, make the move on the copy, and keep it only if the mover's king is safe.
  3. Add up the leaves under every legal move. The recursion goes as deep as depth; each level has its own list and child on the C stack.
  4. Copy-make means there is no "unmake": the parent position *p is never changed, so nothing can be restored wrongly. A position is only 100 bytes, so copying it is cheap.

To test real positions we need to read FEN, the standard one-line text format for a chess position. A FEN has four fields we care about: the pieces rank by rank from rank 8 (digits mean empty squares), the side to move, castling rights, and the en-passant square:

Expected output
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
\_____________ pieces ____________________/ |  |    |
                                  side to move  |    en passant
                                         castling
Add to c/chess.hpart 11 of 18
/* Read a FEN string such as
 * "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1".
 * Returns 1 on success, 0 if the text is not a usable position. */
static inline int from_fen(const char *fen, Position *p) {
    static const char symbols[] = "PNBRQKpnbrqk";
    const char *s = fen;
    int file = 0, rank = 7;

    memset(p, 0, sizeof *p);
    p->ep = NO_EP;

    /* 1. Pieces, from a8 to h1. */
    for (; *s && *s != ' '; s++) {
        const char *hit = strchr(symbols, *s);
        if (*s == '/') {
            file = 0;
            rank--;
        } else if (*s >= '1' && *s <= '8') {
            file += *s - '0';
        } else if (hit) {
            if (file > 7 || rank < 0) return 0;
            p->bb[hit - symbols] |= BIT(rank * 8 + file);
            file++;
        } else {
            return 0;
        }
    }

    /* 2. Side to move. */
    while (*s == ' ') s++;
    if (*s != 'w' && *s != 'b') return 0;
    p->side = *s == 'w' ? WHITE : BLACK;
    s++;

Line by line: the board field

  1. memset clears all twelve boards, the side, the rights; then ep is set to NO_EP, because 0 would mean "a1".
  2. A FEN board lists rank 8 first, from the a-file to the h-file, so we start at rank = 7, file = 0.
  3. / moves down one rank and back to the a-file. A digit skips that many empty squares.
  4. A letter is looked up in "PNBRQKpnbrqk". Its position in that string is exactly its board index: P is 0 (white pawns), k is 11 (black king). strchr returns a pointer into the string, and hit - symbols turns it into that index. The square number is rank * 8 + file, as in Step 1.
  5. Any other character, or a piece beyond the board edge, means the text is broken: return 0.

The remaining fields are short. Each one is separated by spaces, so each part starts by skipping them.

Add to c/chess.hpart 12 of 18
    /* 3. Castling rights. */
    while (*s == ' ') s++;
    for (; *s && *s != ' '; s++) {
        if (*s == 'K') p->castle |= WK;
        if (*s == 'Q') p->castle |= WQ;
        if (*s == 'k') p->castle |= BK;
        if (*s == 'q') p->castle |= BQ;
    }
    /* A right only counts if the king and rook are really at home. */
    if (!(p->bb[KING] & BIT(4)))      p->castle &= ~(WK | WQ);
    if (!(p->bb[6 + KING] & BIT(60))) p->castle &= ~(BK | BQ);
    if (!(p->bb[ROOK] & BIT(7)))      p->castle &= ~WK;
    if (!(p->bb[ROOK] & BIT(0)))      p->castle &= ~WQ;
    if (!(p->bb[6 + ROOK] & BIT(63))) p->castle &= ~BK;
    if (!(p->bb[6 + ROOK] & BIT(56))) p->castle &= ~BQ;

    /* 4. En-passant square, such as "e3", or "-". */
    while (*s == ' ') s++;
    if (*s == '\0') return 0;
    if (*s != '-') {
        if (s[0] < 'a' || s[0] > 'h' || s[1] < '1' || s[1] > '8') return 0;
        p->ep = (s[1] - '1') * 8 + (s[0] - 'a');
    }

    /* 5. Exactly one king each, and the side that just moved is not in check. */
    if (count_bits(p->bb[KING]) != 1 || count_bits(p->bb[6 + KING]) != 1) return 0;
    return (side_attacks(p, p->side) & p->bb[(!p->side) * 6 + KING]) == 0;
}

Line by line: the other fields

  1. Castling: each letter sets one right. - sets none. Then the six checks throw away any right whose king or rook is not on its starting square: a hand-written FEN can claim rights the board cannot have, and the move generator trusts the rights.
  2. En passant: - or a square name such as e3. (s[1] - '1') * 8 + (s[0] - 'a') converts it to 20.
  3. The half-move and full-move counters at the end are not needed by the engine, so they are not read.
  4. Sanity: exactly one king each (count_bits), and the side that just moved must not be in check. That second test catches positions where the wrong side is "to move".

from_fen also rejects impossible positions: a missing king, or a position where the side that just moved is still in check. Then one small helper turns a move word into text such as e2e4:

Add to c/chess.hpart 13 of 18
/* Write a move as text: "e2e4", "a7a8q", or "none" for move 0. */
static inline void move_to_text(Move m, char text[6]) {
    if (m == 0) {
        strcpy(text, "none");
        return;
    }
    text[0] = (char)('a' + (MOVE_FROM(m) & 7));
    text[1] = (char)('1' + (MOVE_FROM(m) >> 3));
    text[2] = (char)('a' + (MOVE_TO(m) & 7));
    text[3] = (char)('1' + (MOVE_TO(m) >> 3));
    text[4] = MOVE_PROMO(m) ? " nbrq"[MOVE_PROMO(m)] : '\0';
    text[5] = '\0';
}

Now the test program. It holds six well-known positions with their published counts, from the Chess Programming Wiki. Each one stresses different rules:

PositionWhat it stresses
startnormal play
kiwipetecastling, pins, en passant, tactics
pos3en passant that exposes the king along a rank
pos4promotions, castling after captures
pos5promotion with check, castling rights
pos6a busy, normal middlegame
Create c/main.cpart 1 of 2
/* main.c - command-line tool for the golden engine.
 *   engine test                      check 30 published perft counts
 *   engine perft  "<fen>" <depth>    count moves, split by first move
 *   engine search "<fen>" <depth>    search depth 1, 2, ... depth      */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "chess.h"

#define START_FEN "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"

typedef struct {
    const char *name;
    const char *fen;
    uint64_t expected[5];          /* perft counts for depth 1 to 5 */
} PerftCase;

static const PerftCase PERFT_CASES[] = {
    {"start", START_FEN,
        {20, 400, 8902, 197281, 4865609}},
    {"kiwipete", "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
        {48, 2039, 97862, 4085603, 193690690}},
    {"pos3", "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1",
        {14, 191, 2812, 43238, 674624}},
    {"pos4", "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1",
        {6, 264, 9467, 422333, 15833292}},
    {"pos5", "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8",
        {44, 1486, 62379, 2103487, 89941194}},
    {"pos6", "r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10",
        {46, 2079, 89890, 3894594, 164075551}},
};

static int run_tests(void) {
    int failures = 0, c, d;
    for (c = 0; c < 6; c++) {
        Position p;
        from_fen(PERFT_CASES[c].fen, &p);
        for (d = 1; d <= 5; d++) {
            uint64_t got = perft(&p, d);
            int ok = got == PERFT_CASES[c].expected[d - 1];
            printf("%-9s depth %d  %11llu  %s\n", PERFT_CASES[c].name, d,
                   (unsigned long long)got, ok ? "ok" : "FAIL");
            if (!ok) failures++;
        }
    }
    if (failures) printf("FAILED: %d mismatches\n", failures);
    else          printf("ALL PERFT TESTS PASSED\n");
    return failures != 0;
}

Line by line

  1. Each PerftCase is a name, a FEN, and the published correct counts for depths 1 to 5. These numbers come from the Chess Programming Wiki's perft results and have been confirmed by many independent engines.
  2. run_tests loads each position, runs perft at depths 1 to 5, and prints one line per depth with ok or FAIL.
  3. It returns non-zero if anything failed, so a script or a build tool can stop on a broken engine.

And main, which also gives us a "divide" command for debugging and, later, a search command:

Add to c/main.cpart 2 of 2
int main(int argc, char **argv) {
    Position p;
    int depth;
    clock_t start = clock();

    if (argc < 2 || strcmp(argv[1], "test") == 0) return run_tests();
    if (argc < 4) {
        printf("usage: engine test | perft \"<fen>\" <depth> | search \"<fen>\" <depth>\n");
        return 1;
    }
    if (!from_fen(argv[2], &p)) {
        printf("invalid FEN\n");
        return 1;
    }
    depth = atoi(argv[3]);

    if (strcmp(argv[1], "perft") == 0) {
        /* "Divide": the count under each first move, then the total. */
        Move list[MAX_MOVES];
        uint64_t total = 0;
        int n = generate_moves(&p, list, 0), i;
        for (i = 0; i < n; i++) {
            Position child = p;
            char text[6];
            make_move(&child, list[i]);
            if (!legal_after(&child, list[i])) continue;
            uint64_t count = perft(&child, depth - 1);
            move_to_text(list[i], text);
            printf("%-6s %llu\n", text, (unsigned long long)count);
            total += count;
        }
        printf("total  %llu\n", (unsigned long long)total);
    } else if (strcmp(argv[1], "search") == 0) {
        int d;
        for (d = 1; d <= depth; d++) {
            SearchResult r = search(&p, d, 0);
            char text[6];
            move_to_text(r.best, text);
            printf("depth %2d  best %-6s score %6d  nodes %llu\n",
                   d, text, r.score, (unsigned long long)r.nodes);
        }
    }
    printf("time %.3f s\n", (double)(clock() - start) / CLOCKS_PER_SEC);
    return 0;
}
Check

Build and run with MSYS2 (UCRT64 terminal, or Command Prompt with MSYS2's ucrt64\bin on the PATH):

Command Prompt
cd /d C:\chess\c
gcc -std=c99 -O2 -Wall -Wextra main.c -o engine.exe
engine.exe test

Or with Visual Studio, from the "x64 Native Tools Command Prompt":

Command Prompt
cl /O2 /std:c11 /D_CRT_SECURE_NO_WARNINGS main.c /Fe:engine.exe
engine.exe test

It takes about 30 seconds with gcc at -O2, a little longer with Visual Studio, which uses the portable loop. The last lines must be:

Expected output
pos6      depth 4      3894594  ok
pos6      depth 5    164075551  ok
ALL PERFT TESTS PASSED
If a count is wrong

Fix the shallowest failing depth first. Run divide on that position and depth:

Command Prompt
engine.exe perft "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1" 2

Compare each move's count with another engine (Stockfish's go perft 2 does this). Play the move whose count differs, run divide one level shallower from there, and repeat until a single position shows the bug.

10Evaluating a position

Goal: turn any position into one number: how good it is for the side to move.

Concept

When the search stops looking ahead, it needs a guess at who is better. Scores are in centipawns: a pawn is worth 100. We use the well-known Simplified Evaluation Function by Tomasz Michniewski, which has two parts:

  • Material: pawn 100, knight 320, bishop 330, rook 500, queen 900.
  • Piece-square tables: a bonus or penalty for every piece on every square. Knights like the center, pawns like to advance, the king likes to hide in a corner.

The king gets two tables. While any queen is on the board, it should stay sheltered. Once both queens are gone the danger drops, and it should walk to the center to help in the endgame. That is a single, simple rule, and in hardware it is one wire.

Piece-square tables. Hover over a square to see how the table is read. Switch to "Black piece" to see the same table mirrored.

The tables are written like a printed board, rank 8 on the first row. A white piece on square sq reads entry sq ^ 56. XOR with 56 flips the rank (e2 is square 12, and 12 ^ 56 = 52, which is the row for rank 2). A black piece reads entry sq directly, which mirrors the board, so both sides see the table from their own end.

Two more details. Tempo: the side to move gets 10 extra, for having the move. Sign: the final score is from the point of view of the side to move: positive is good for whoever is about to move. The next steps explain why that makes the search simpler.

Where a score comes from. The start position is perfectly symmetric, so everything cancels except tempo: evaluate returns 10. After 1.e4 e5 2.Nf3, it is Black to move, so the sign flips.

This evaluator is weak by modern standards: it knows nothing about mobility, pawn structure or king safety. It is chosen because it suits hardware perfectly. Each square's contribution depends only on what stands on that square, so all 64 can be computed at the same moment, then added up with a tree of adders.

Code

First the numbers. PIECE_VALUE is the material value of each type in centipawns. PST holds seven 64-entry tables: one per piece type, plus a second king table for the endgame. They are written as you would see the board from White's side, rank 8 on the first line.

Add to c/chess.hpart 14 of 18
static const int PIECE_VALUE[6] = {100, 320, 330, 500, 900, 0};

/* Piece-square tables, printed like a board: the first row is rank 8.
 * A white piece on square sq uses PST[type][sq ^ 56]; a black one uses
 * PST[type][sq], which mirrors the table for Black. */
static const int PST[7][64] = {
  { /* pawn */
     0,  0,  0,  0,  0,  0,  0,  0,
    50, 50, 50, 50, 50, 50, 50, 50,
    10, 10, 20, 30, 30, 20, 10, 10,
     5,  5, 10, 25, 25, 10,  5,  5,
     0,  0,  0, 20, 20,  0,  0,  0,
     5, -5,-10,  0,  0,-10, -5,  5,
     5, 10, 10,-20,-20, 10, 10,  5,
     0,  0,  0,  0,  0,  0,  0,  0 },
  { /* knight */
   -50,-40,-30,-30,-30,-30,-40,-50,
   -40,-20,  0,  0,  0,  0,-20,-40,
   -30,  0, 10, 15, 15, 10,  0,-30,
   -30,  5, 15, 20, 20, 15,  5,-30,
   -30,  0, 15, 20, 20, 15,  0,-30,
   -30,  5, 10, 15, 15, 10,  5,-30,
   -40,-20,  0,  5,  5,  0,-20,-40,
   -50,-40,-30,-30,-30,-30,-40,-50 },
  { /* bishop */
   -20,-10,-10,-10,-10,-10,-10,-20,
   -10,  0,  0,  0,  0,  0,  0,-10,
   -10,  0,  5, 10, 10,  5,  0,-10,
   -10,  5,  5, 10, 10,  5,  5,-10,
   -10,  0, 10, 10, 10, 10,  0,-10,
   -10, 10, 10, 10, 10, 10, 10,-10,
   -10,  5,  0,  0,  0,  0,  5,-10,
   -20,-10,-10,-10,-10,-10,-10,-20 },
  { /* rook */
     0,  0,  0,  0,  0,  0,  0,  0,
     5, 10, 10, 10, 10, 10, 10,  5,
    -5,  0,  0,  0,  0,  0,  0, -5,
    -5,  0,  0,  0,  0,  0,  0, -5,
    -5,  0,  0,  0,  0,  0,  0, -5,
    -5,  0,  0,  0,  0,  0,  0, -5,
    -5,  0,  0,  0,  0,  0,  0, -5,
     0,  0,  0,  5,  5,  0,  0,  0 },
  { /* queen */
   -20,-10,-10, -5, -5,-10,-10,-20,
   -10,  0,  0,  0,  0,  0,  0,-10,
   -10,  0,  5,  5,  5,  5,  0,-10,
    -5,  0,  5,  5,  5,  5,  0, -5,
     0,  0,  5,  5,  5,  5,  0, -5,
   -10,  5,  5,  5,  5,  5,  0,-10,
   -10,  0,  5,  0,  0,  0,  0,-10,
   -20,-10,-10, -5, -5,-10,-10,-20 },
  { /* king, while any queen is on the board: stay sheltered */
   -30,-40,-40,-50,-50,-40,-40,-30,
   -30,-40,-40,-50,-50,-40,-40,-30,
   -30,-40,-40,-50,-50,-40,-40,-30,
   -30,-40,-40,-50,-50,-40,-40,-30,
   -20,-30,-30,-40,-40,-30,-30,-20,
   -10,-20,-20,-20,-20,-20,-20,-10,
    20, 20,  0,  0,  0,  0, 20, 20,
    20, 30, 10,  0,  0, 10, 30, 20 },
  { /* king, once all queens are gone: walk to the center */
   -50,-40,-30,-20,-20,-30,-40,-50,
   -30,-20,-10,  0,  0,-10,-20,-30,
   -30,-10, 20, 30, 30, 20,-10,-30,
   -30,-10, 30, 40, 40, 30,-10,-30,
   -30,-10, 30, 40, 40, 30,-10,-30,
   -30,-10, 20, 30, 30, 20,-10,-30,
   -30,-30,  0,  0,  0,  0,-30,-30,
   -50,-30,-30,-30,-30,-30,-30,-50 },
};

#define TEMPO 10          /* small bonus for having the move */

Then the function that adds them up:

Add to c/chess.hpart 15 of 18
/* Score in centipawns (pawn = 100) from the side to move's point of view. */
static inline int evaluate(const Position *p) {
    int endgame = (p->bb[QUEEN] | p->bb[6 + QUEEN]) == 0;
    int white_minus_black = 0, pc;

    for (pc = 0; pc < 12; pc++) {
        int type  = pc % 6;
        int table = (type == KING && endgame) ? 6 : type;
        U64 b = p->bb[pc];
        while (b) {
            int sq = lsb(b);
            b &= b - 1;
            if (pc < 6) white_minus_black += PIECE_VALUE[type] + PST[table][sq ^ 56];
            else        white_minus_black -= PIECE_VALUE[type] + PST[table][sq];
        }
    }
    white_minus_black += p->side == WHITE ? TEMPO : -TEMPO;
    return p->side == WHITE ? white_minus_black : -white_minus_black;
}

Line by line

  1. Endgame? Here simply "no queens on the board". It only changes which king table is used: in the middlegame the king should hide, in the endgame it should come to the centre.
  2. The loop visits every piece on the board. For each one, it adds its material value and its square bonus to a running "White minus Black" total.
  3. sq ^ 56 for White. The tables are printed rank 8 first, so entry 0 is the top-left corner, a8, and entries 56 to 63 are the bottom row, rank 1. A white piece on a1 (square 0) must read the bottom row, so its index is flipped: 0 ^ 56 = 56. XOR with 56 flips the rank and keeps the file. A black piece uses sq as it is: Black's back rank, squares 56 to 63, also lands on the bottom row. So both sides read "their own home row" from the same table, which mirrors it for free.
  4. The side to move gets a small bonus, TEMPO, for having the move.
  5. The last line turns "White minus Black" into "me minus you": negamax always wants the score from the side to move's point of view.

11The game tree, and minimax

Goal: understand how looking ahead turns many guesses into one good decision.

Concept

Picture every possible future as a tree. The current position is the root. Each legal move is a branch to a child position, each reply branches again, and so on. One move by one side is called a ply, so "depth 3" means three plies: my move, your reply, my move.

We can't search to the end of the game, so we stop at a fixed depth and evaluate the leaves. Then the scores flow back up the tree, under one assumption: both players always choose the move that is best for them.

  • At White's turns (MAX nodes), White picks the child with the highest score.
  • At Black's turns (MIN nodes), Black picks the child with the lowest score, since scores here are from White's side.

This is minimax. Step through it on a small tree: three moves at the root, two replies to each, two moves after that, then twelve leaves.

Minimax, bottom up. Leaf scores are from White's view. Each step fills in one node from its children. The root's value tells White what it can force, whatever Black does, and which first move gets it.

Look at what minimax finds. B, the first root move, contains a leaf worth 20, but White never gets it: Black would steer the game elsewhere. Minimax doesn't trust hope. It plays the line where the opponent defends as well as possible.

The cost is the problem. With about 35 legal moves in a typical position, depth 6 has 356, almost 1.8 billion, leaves. Steps 13 and 14 are about not visiting most of them.

A worked example, by hand

Take the smallest interesting tree: White has two moves, A and B, and Black has two replies to each. The leaves are scored from White's side.

Expected output
            root (White, MAX)
           /                 \
      A (Black, MIN)     B (Black, MIN)
       /      \           /      \
     +30     -10        +5      +8
  1. At A, Black chooses between +30 and −10. Black wants the lowest score, so A is worth −10. The +30 is a line White would love, but Black will never play into it.
  2. At B, Black chooses between +5 and +8, so B is worth +5.
  3. At the root, White chooses between A (−10) and B (+5), so the root is worth +5, and the move to play is B.

Notice that White picks B even though the best single leaf, +30, is under A. That is the "assume the opponent defends perfectly" rule at work.

How fast the tree grows

Real chess trees grow by a factor of about 35 per ply. The right-hand column is the exact number of positions at each depth from the starting position (the perft counts you will check in Step 9):

Depth35depthReal positions from the start
13520
21,225400
342,8758,902
41,500,625197,281
552,521,8754,865,609
61,838,265,625119,060,324

The opening has fewer moves than a typical middlegame, so the real numbers are smaller, but the growth is the same story: every extra ply multiplies the work by twenty to forty.

12Negamax: one rule instead of two

Goal: write minimax as a single function with no "if White ... else Black".

Concept

Chess is zero-sum: what is good for me is exactly that bad for you. If a position is worth +3 to Black, it is worth −3 to White. So if every score is given from the point of view of the side to move (which is how evaluate already works), the MIN rule disappears:

score(position) = maximum over moves of −score(child)

The minus sign switches perspective at every level. The child's score is from the opponent's side, so negating it gives my side. Every node becomes a MAX node. Switch the figure to the negamax view: the tree is the same, only the signs at the MIN levels change, and the root's answer is identical.

The same tree, in negamax. Every number is from the view of the player to move at that node, so every node takes the maximum of its negated children.

The worked example again, in negamax

Same tree as in Step 11. Now every leaf is scored from the side to move at that leaf. After A or B and a black reply it is White's move again, so the leaves keep their values: +30, −10, +5, +8.

  1. At A it is Black's move. Black takes the maximum of the negated children: max(−30, +10) = +10. From Black's side, A is worth +10.
  2. At B: max(−5, −8) = −5.
  3. At the root it is White's move: max(−(+10), −(−5)) = max(−10, +5) = +5, move B.

Same answer, +5 and move B, but there was only one rule, "take the maximum of the negated children", at every node. That is what lets the C, and later the hardware state machine, use one piece of code for both colours.

In code, negamax is about ten lines. This is the core of the engine, before any speed-ups:

C
int negamax(const Position *p, int depth) {
    if (depth == 0) return evaluate(p);       /* a leaf                      */
    int best = -INF;
    for each legal move m {
        Position child = *p;  make_move(&child, m);
        int score = -negamax(&child, depth - 1);  /* the child's view, negated */
        if (score > best) best = score;
    }
    return best;
}

13Alpha-beta: skipping what can't matter

Goal: get exactly the minimax answer while visiting far fewer leaves.

Concept

Imagine you are choosing between three restaurants, and a friend picks your dish at each one, always the worst on the menu. You check restaurant B fully: its worst dish is fine, call it 12. At restaurant C, the first dish you look at is terrible, 8. Do you need to read the rest of C's menu? No. Your friend can already give you an 8 there, which is worse than the 12 you are sure of at B. C is ruled out, whatever else is on its menu.

That is the whole idea of alpha-beta pruning. While searching, carry two numbers down the tree:

  • α (alpha): the score MAX is already sure of, from moves searched earlier. MAX will never accept less.
  • β (beta): the score MIN is already sure of. MIN will never allow more.

Only scores strictly between α and β can change any decision higher in the tree. As soon as a node proves its score is outside that window, the rest of its moves cannot matter, and we stop searching it. That is a cutoff.

Step through it. Watch the window [α, β] above each node, and the three cutoffs: two where MIN refuses to enter (at F and J), and one where MAX refuses (at C).

Alpha-beta, step by step. The same tree as before. The window above each node shows what it received; faded branches are never searched, and pale leaf scores haven't been looked at yet. Try "Best move first" and "Worst move first": the answer never changes, but the work does.

Three things to take away from the figure:

  1. The answer is exactly the minimax answer. Pruning never changes the root's value or the move it picks, only how much work it takes.
  2. A cutoff happens when α ≥ β. At that point this node's score is already too good (or too bad) for the player above to allow.
  3. Order matters enormously. With the best move first, the very first child sets a tight window, and later siblings are cut off almost immediately.

Alpha-beta in negamax form

Our code uses negamax, so how does the window work there? When we go down one level, the opponent's view of the same window is negated and swapped:

Expected output
my window            [ alpha,  beta ]
child's window       [ -beta, -alpha ]

Why? If I already have α, my opponent knows I will refuse any line worth less than α to me, which is more than −α to them. So −α becomes their upper bound, their β. And the rule "stop when α ≥ β" is the same at every node, because every node is a MAX node. That gives the loop body you will see in Step 16:

C
score = -negamax(&child, depth - 1, -beta, -alpha, ply + 1);
if (score > best)  best = score;
if (score > alpha) alpha = score;
if (alpha >= beta) break;            /* cutoff: the rest cannot matter */

The cutoff on the worked example

Go back to the tree from Step 11 and search B first this time (B, then A):

  1. The root starts with the window [−∞, +∞]. It searches B fully: B is worth +5 to White, as before. The root's α becomes +5: White is now sure of at least +5.
  2. The root moves on to A, passing the window down negated and swapped: [−β, −α] = [−∞, −5]. In words, Black at A is told: "White already has +5 elsewhere, so anything worse than −5 for you is irrelevant".
  3. A's first reply leads to the leaf +30, which is −30 from Black's side. A's α becomes −30. Not yet ≥ −5, so carry on.
  4. A's second reply leads to −10, which is +10 from Black's side. A's α becomes +10. Now α (+10) ≥ β (−5): cutoff. A stops. (Here it was the last move anyway; with more replies, every remaining one would be skipped.)
  5. A returns +10, the root sees −10, which does not beat +5, so the answer is still +5 and move B.

Now imagine A had thirty replies and the strong one came first. Black's first reply would already reach α ≥ β, and the other twenty-nine would never be searched. That is where the savings come from, and why the order of moves matters so much.

14Why move order matters so much

Goal: see why Step 8 generates captures first.

Concept

On the small tree the savings looked modest. On real trees they are enormous, but only if good moves come first. With perfect ordering, alpha-beta needs about bd/2 leaves instead of bd: the square root. In the same time, it searches roughly twice as deep.

Leaves evaluated on random trees. Move the sliders. "Best first" orders every node's children perfectly, which no real engine can do, but good ordering gets surprisingly close.

The numbers behind "square root"

Knuth and Moore proved in 1975 that with perfect ordering, alpha-beta visits b⌈d/2⌉ + b⌊d/2⌋ − 1 leaves. For 35 moves and depth 6 that is 42,875 + 42,875 − 1 = 85,749 leaves, against 1.8 billion for plain minimax: twenty thousand times fewer. With the worst ordering, alpha-beta cuts nothing and visits all 1.8 billion.

No engine knows the best move in advance; that is what it is searching for. But cheap rules get close:

  • Captures first, biggest victim first (MVV-LVA, Step 8). Winning material is often best, and even when it is not, a capture quickly raises α.
  • Promotions before everything. A new queen is worth 800 centipawns.
  • Killer moves (Part 5). A quiet move that caused a cutoff in a sibling position probably refutes this one too.

Real numbers from this engine, at depth 6 from the start position: the version you are building visits 1,519,394 nodes. In Part 5 we add one ordering idea, the killer move, and the same search visits 159,788 nodes, nine and a half times fewer, with exactly the same result. That is why the generator works so hard to put captures of valuable pieces first.

15The horizon, and quiescence

Goal: stop the engine from being fooled at the edge of its search.

Concept

A fixed depth creates a blind spot. Suppose the search stops right after my queen takes a pawn. The evaluator counts material and sees me a pawn up. It cannot see that the pawn was defended and my queen is lost on the very next move. Beyond the depth limit, the engine is blind. This is called the horizon effect.

The horizon effect. A depth-1 search that just evaluates after one move falls for the trap. The real engine keeps going and avoids it.

The cure is quiescence search: when the normal depth runs out, don't evaluate straight away. Keep searching, but only captures and promotions, until the position is quiet. Two rules make it work:

  1. Stand pat. The side to move doesn't have to capture. So evaluate first: that score is a floor. If it is already at least β, stop at once. Otherwise raise α to it and try the captures.
  2. Not in check. In check, you can't "stand pat", because you must answer the check. So in check, search every legal reply. If there are none, it is checkmate.

Quiescence ends naturally: captures remove pieces, so capture sequences are short. And since moves come out "most valuable victim first", the strongest captures are tried first and cutoffs come quickly.

The trap from the figure, step by step

White's queen on h2 can take the pawn on e5, but the pawn on d6 defends it.

  1. Without quiescence, at depth 1: White plays Qxe5 and the search stops. evaluate counts material: White has won a pawn, so the score goes up by about 100 centipawns, and Qxe5 looks like the best move.
  2. With quiescence: after Qxe5 the depth is 0, but instead of evaluating at once the engine calls quiesce. It is Black's move. Stand pat first: the evaluation as it stands, with White a pawn richer, is Black's floor.
  3. Then Black tries the captures. dxe5 takes the queen. Now it is White's move, again in quiescence. White's stand-pat score has dropped by about 900 (the queen), and White has no capture back, so that is the value of the line.
  4. For Black, dxe5 is far better than standing pat, so Black takes the queen. Passed back up, Qxe5 is now worth about 800 centipawns less to White than not capturing at all (a queen lost, a pawn won). The engine plays something else.

One extra ply of captures-only search turned a blunder into a refused move, at a tiny cost: a capture sequence rarely runs more than a few moves deep.

16The search, in code

Goal: put negamax, alpha-beta, quiescence, and mate scores together in one function.

Concept

Two details remain.

Mate and stalemate. If a node has no legal move at all, it is checkmate if the side to move is in check, and stalemate (a draw, score 0) if not. Checkmate at ply p scores −MATE + p. A quicker mate is worth slightly more, so the engine plays the fastest win and the slowest defence.

A depth limit for the stack. The hardware stack holds 32 plies. Quiescence can, in theory, go very deep, so at ply 31 we stop and return the evaluation. The C does the same, so both always visit exactly the same nodes.

Every variable in negamax that must survive the recursive call (alpha, beta, best, the loop index, any_legal, check) becomes a field in the hardware's stack frame in Part 2. Keep an eye on them.

Code

The result type, plus counters that live outside the recursion. The node limit lets the CPU stop a search that is taking too long; the hardware has the same feature.

Add to c/chess.hpart 16 of 18
#define INF  32000        /* bigger than any real score     */
#define MATE 30000        /* score for giving checkmate     */

typedef struct {
    Move     best;        /* 0 means no legal move (mate or stalemate) */
    int      score;
    uint64_t nodes;
    int      aborted;     /* 1 if the node limit stopped the search    */
} SearchResult;

/* The search keeps its bookkeeping here, outside the recursion. */
static SearchResult search_result;
static uint64_t     search_node_limit;     /* 0 = no limit */

Line by line

  1. INF is larger than any score the evaluation can produce, so -INF is a safe "worse than anything" starting value. MATE is below INF and above any material score.
  2. SearchResult is everything the caller gets back. best is the move at the root; 0 means there is no legal move.
  3. The two static variables are shared by every level of the recursion: the node counter and the limit. Keeping them outside negamax keeps its argument list short; the hardware keeps them in single registers for the same reason.

And the heart of the engine. Read it top to bottom alongside Steps 12 to 15. Every line has a reason you've already seen.

Add to c/chess.hpart 17 of 18
/* Fail-soft negamax alpha-beta with quiescence. rtl/search_core.sv
 * performs exactly this recursion, one state per clock. */
static inline int negamax(const Position *p, int depth, int alpha, int beta, int ply) {
    Move list[MAX_MOVES];
    int check, quiesce, stand_pat, best, n, i, any_legal = 0;

    search_result.nodes++;
    if (search_node_limit && search_result.nodes >= search_node_limit) {
        search_result.aborted = 1;
        return 0;
    }

    check = in_check(p);
    if (ply == MAX_PLY - 1) return evaluate(p);     /* the stack is full */

    quiesce   = depth == 0;
    stand_pat = quiesce && !check;
    best = -INF;
    if (stand_pat) {                 /* may refuse every capture */
        best = evaluate(p);
        if (best >= beta) return best;
        if (best > alpha) alpha = best;
    }

    n = generate_moves(p, list, stand_pat);
    for (i = 0; i < n; i++) {
        Position child = *p;
        int score;
        make_move(&child, list[i]);
        if (!legal_after(&child, list[i])) continue;
        any_legal = 1;

        score = -negamax(&child, quiesce ? 0 : depth - 1, -beta, -alpha, ply + 1);
        if (search_result.aborted) return 0;

        if (score > best) {
            best = score;
            if (ply == 0) search_result.best = list[i];
        }
        if (score > alpha) alpha = score;
        if (alpha >= beta) break;     /* cutoff: the rest cannot matter */
    }

    if (!any_legal && !stand_pat)     /* no legal move at all */
        return check ? -MATE + ply : 0;
    return best;
}

Line by line

  1. Count the node, check the limit. If the limit is reached, set aborted and return 0. Every caller checks aborted right after its recursive call, so the whole search unwinds immediately and the half-finished answer is never used.
  2. In check? Computed once; it decides whether this node may stand pat and whether "no legal moves" means mate or stalemate.
  3. The deepest ply simply returns the evaluation: the hardware has 32 stack rows, so the C stops at the same depth.
  4. Quiescence (depth == 0): if not in check, the side to move may "stand pat", meaning decline every capture and accept the static evaluation. That value is a lower bound on this node's score, so it may cause an immediate cutoff, or raise alpha.
  5. Generate all moves, or captures only when standing pat. In check, all moves are generated even at depth 0, because every escape must be considered.
  6. The loop: copy, make, skip illegal moves. any_legal records that at least one move was legal.
  7. The recursive call searches the child with the window negated and swapped: (-beta, -alpha). The minus sign in front turns the child's score, which is from the opponent's point of view, into ours. In quiescence the depth stays at 0.
  8. Update: a new best (remembering the move at the root), a raised alpha, and the cutoff: once alpha >= beta, the opponent already has a better option elsewhere and will never allow this position, so the remaining moves cannot matter.
  9. No legal move at a node that was not standing pat: checkmate if in check (-MATE + ply: losing later is less bad), otherwise stalemate, a draw.

Two details worth noticing. The score is "fail-soft": a node can return a value outside its window, not just α or β, which gives slightly better information to the level above. And the root's best move is recorded whenever a root move beats best.

Finally, the entry point, and the end of chess.h:

Add to c/chess.hpart 18 of 18
static inline SearchResult search(const Position *root, int depth, uint64_t node_limit) {
    memset(&search_result, 0, sizeof search_result);
    search_node_limit = node_limit;
    search_result.score = negamax(root, depth, -INF, INF, 0);
    return search_result;
}

#endif
A real search tree. This is every node this code visits for each position. Each line shows the move that led to the node, the window it received, and the score it returned (from the mover's view at that node). Look for stand-pat cutoffs, and for the mate in one: the checkmated side, at ply 1, returns −MATE + 1 = −29999.
Check
Command Prompt
gcc -std=c99 -O2 -Wall -Wextra main.c -o engine.exe
engine.exe search "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" 6
Expected output
depth  1  best b1c3   score     40  nodes 21
depth  2  best b1c3   score     10  nodes 238
depth  3  best b1c3   score     40  nodes 2639
depth  4  best b1c3   score     10  nodes 25933
depth  5  best d2d4   score     30  nodes 199412
depth  6  best d2d4   score     10  nodes 1519394
time 2.974 s

Every number except the time must match exactly: the engine has no randomness. Two more checks:

Command Prompt
engine.exe search "6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1" 2
engine.exe search "7k/5Q2/6K1/8/8/8/8/8 b - - 0 1" 2

The first finds d1d8, mate in one, with score 29999 (MATE − 1). The second is stalemate: Black has no move, so it prints none with score 0.

Why do the scores swing between 10 and 40 from one depth to the next? At odd depths White makes the last move, and at even depths Black does. Whoever moves last tends to look a little better. It is normal, and it is one reason engines use iterative deepening (Step 39) rather than trusting a single depth.

17Play against it

Before turning it into hardware, play the engine you have just written. This board runs the JavaScript twin of chess.h, with the killer-move upgrade from Part 5 so it answers quickly. JavaScript in a browser is about 80 times slower than the FPGA will be, so depth 4 can take a few seconds.

The golden model, playing. Click a piece, then a square. Pawns promote to a queen. It plays solidly at short range, and has no opening knowledge at all.

What to watch for while you play

  • It never hangs a piece to a one-move threat. Quiescence sees every capture sequence to the end, so leaving a piece where it can simply be taken does not happen.
  • It grabs material greedily. The evaluation is mostly material, so if a pawn can be won safely within its depth, it takes it, even at the cost of development.
  • It has no plan. It knows piece-square tables, not strategy. In a quiet position it shuffles pieces towards "good" squares. Beat it by setting up a tactic deeper than its search: a quiet move that only pays off four or five plies later.
  • Depth matters more than anything. Change the depth and play the same opening: at depth 2 it misses simple forks, at depth 4 it rarely does. The FPGA reaches depth 6 to 7 in two seconds, which is a noticeably stronger player.
  • The readout shows the node count. Watch it jump by a factor of 5 to 10 with each extra ply: the tree from Step 11, cut down by alpha-beta.

18Writing the test vectors

Goal: save the engine's answers to files that the hardware tests will check, line by line.

Concept

The hardware will be tested the way a teacher marks homework: against an answer key. gen_vectors makes the key. It starts from 16 hand-picked positions that cover every special rule, then plays random legal games from each and keeps every fourth position. For each position it writes:

FileEach line holdsChecked by
vec_positions.txtposition, both attack maps, evaluation, in-check flagtb_functions, tb_eval
vec_apply.txtposition, one move, the child position, legal or nottb_functions
vec_moves.txtposition, mode, the exact ordered move listtb_move_gen
vec_search.txtposition, depth, node limit, nodes, score, best movetb_search, tb_axi

A tiny fixed random-number generator (xorshift) makes the "random" games identical on every computer, so your vector files will be byte-for-byte the same as mine.

Code

First the seed positions and two helpers. The seeds are the six perft positions plus ten small positions, each chosen to exercise one tricky rule: every castling case, en passant (including the rare case where it exposes the king), promotion, mate and stalemate.

Create c/gen_vectors.cpart 1 of 3
/* gen_vectors.c - writes the answers the RTL testbenches must reproduce.
 *   gen_vectors <folder>        quick set (minutes in Vivado's simulator)
 *   gen_vectors <folder> full   thorough set (hours in Vivado's simulator) */
#include <stdio.h>
#include <string.h>
#include "chess.h"

static const char *SEEDS[] = {
    "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
    "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
    "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1",
    "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1",
    "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8",
    "r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10",
    "r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1",          /* all four castlings      */
    "4k3/8/8/2Pp4/8/8/8/4K3 w - d6 0 2",             /* ordinary en passant     */
    "8/8/8/KPp4r/8/8/8/7k w - c6 0 2",               /* en passant exposes king */
    "4k3/P7/8/8/8/8/p7/4K3 w - - 0 1",               /* promotions              */
    "6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1",         /* mate in one             */
    "7k/5Q2/6K1/8/8/8/8/8 b - - 0 1",                /* stalemate               */
    "r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4", /* mated */
    "4k3/8/8/8/8/8/4r3/R3K2R w KQ - 0 1",            /* in check: no castling   */
    "4k3/8/8/8/8/5r2/8/R3K2R w KQ - 0 1",            /* f1 attacked: no O-O     */
    "1r2k3/8/8/8/8/8/8/R3K2R w KQ - 0 1",            /* only b1 attacked: O-O-O ok */
};
#define NUM_SEEDS (int)(sizeof SEEDS / sizeof SEEDS[0])

static FILE *f_pos, *f_apply, *f_moves, *f_search;
static int full;

static void put_position(FILE *f, const Position *p) {
    int i;
    for (i = 0; i < 12; i++) fprintf(f, "%016llx ", (unsigned long long)p->bb[i]);
    fprintf(f, "%d %d %d", p->side, p->castle, p->ep);
}

/* A tiny random generator, so everyone gets the same vectors. */
static uint32_t rng_state = 2463534242u;
static uint32_t random_number(void) {
    rng_state ^= rng_state << 13;
    rng_state ^= rng_state >> 17;
    rng_state ^= rng_state << 5;
    return rng_state;
}

Line by line

  1. put_position writes a position as one line of text: twelve 16-digit hex numbers, then side, castling rights and en-passant square. SystemVerilog's $fscanf reads exactly this format back.
  2. random_number is xorshift: three shifts and XORs. Same starting value, same sequence, on every computer.

Then the two writers, one per kind of answer:

Add to c/gen_vectors.cpart 2 of 3
/* One position: attack maps, evaluation, check, both move lists, and
 * every pseudo-legal move with its child position and legality. */
static void write_position_vectors(const Position *p) {
    Move list[MAX_MOVES];
    int mode, n, k;

    put_position(f_pos, p);
    fprintf(f_pos, " %016llx %016llx %d %d\n",
            (unsigned long long)side_attacks(p, WHITE),
            (unsigned long long)side_attacks(p, BLACK),
            evaluate(p), in_check(p));

    for (mode = 0; mode < 2; mode++) {
        n = generate_moves(p, list, mode);
        put_position(f_moves, p);
        fprintf(f_moves, " %d %d", mode, n);
        for (k = 0; k < n; k++) fprintf(f_moves, " %04x", list[k]);
        fputc('\n', f_moves);
    }

    n = generate_moves(p, list, 0);
    for (k = 0; k < n; k++) {
        Position child = *p;
        make_move(&child, list[k]);
        put_position(f_apply, p);
        fprintf(f_apply, " %04x ", list[k]);
        put_position(f_apply, &child);
        fprintf(f_apply, " %d\n", legal_after(&child, list[k]));
    }
}

/* One whole search (mode 0) or perft (mode 1). */
static void write_search_vector(const Position *p, int mode, int depth, uint64_t limit) {
    uint64_t nodes;
    int score = 0, best = 0, aborted = 0;
    if (mode == 1) {
        nodes = perft(p, depth);
    } else {
        SearchResult r = search(p, depth, limit);
        nodes = r.nodes;
        aborted = r.aborted;
        if (!aborted) {
            score = r.score;
            best = r.best;
        }
    }
    if (!full && nodes > 1500) return;              /* keep the quick set quick */
    put_position(f_search, p);
    fprintf(f_search, " %d %d %llu %llu %d %04x %d\n", mode, depth,
            (unsigned long long)limit, (unsigned long long)nodes, score, best, aborted);
}

Line by line

  1. write_position_vectors writes everything that can be checked about one position: both sides' attack maps, the evaluation and the check flag (vec_positions.txt); both move lists, all moves and captures only (vec_moves.txt); and, for every pseudo-legal move, the child position and whether it is legal (vec_apply.txt).
  2. write_search_vector runs one perft or one search and writes the position, the settings and the answer: nodes, score, best move, and whether the node limit stopped it (vec_search.txt). In the quick set, searches above 1,500 nodes are skipped to keep simulation short.

And main, which builds the list of positions and calls the writers:

Add to c/gen_vectors.cpart 3 of 3
static FILE *open_output(const char *folder, const char *name) {
    char path[512];
    FILE *f;
    sprintf(path, "%s/%s", folder, name);
    f = fopen(path, "w");
    if (!f) printf("cannot create %s\n", path);
    return f;
}

static Position corpus[4096];

int main(int argc, char **argv) {
    const char *folder = argc > 1 ? argv[1] : ".";
    int count = 0, s, game, ply, i, d;
    full = argc > 2 && strcmp(argv[2], "full") == 0;

    f_pos    = open_output(folder, "vec_positions.txt");
    f_apply  = open_output(folder, "vec_apply.txt");
    f_moves  = open_output(folder, "vec_moves.txt");
    f_search = open_output(folder, "vec_search.txt");
    if (!f_pos || !f_apply || !f_moves || !f_search) return 1;

    /* The corpus: every seed, plus positions from random legal games. */
    for (s = 0; s < NUM_SEEDS; s++) {
        Position start;
        if (!from_fen(SEEDS[s], &start)) { printf("bad FEN %s\n", SEEDS[s]); return 1; }
        corpus[count++] = start;
        for (game = 0; game < (full ? 8 : 2); game++) {
            Position p = start;
            for (ply = 0; ply < 40; ply++) {
                Move list[MAX_MOVES], legal[MAX_MOVES];
                int n = generate_moves(&p, list, 0), k = 0;
                for (i = 0; i < n; i++) {
                    Position child = p;
                    make_move(&child, list[i]);
                    if (legal_after(&child, list[i])) legal[k++] = list[i];
                }
                if (k == 0) break;                      /* game over */
                make_move(&p, legal[random_number() % k]);
                if (ply % 4 == 3) corpus[count++] = p;
            }
        }
    }

    for (i = 0; i < count; i++) write_position_vectors(&corpus[i]);

    for (s = 0; s < NUM_SEEDS; s++) {
        Position p;
        from_fen(SEEDS[s], &p);
        for (d = 0; d <= (full ? 3 : 2); d++) write_search_vector(&p, 1, d, 0);
        for (d = 0; d <= (full ? 4 : 2); d++) write_search_vector(&p, 0, d, 0);
        write_search_vector(&p, 0, 3, 100);        /* the node limit must stop it */
    }
    for (i = 0; i < count; i += 8) {
        write_search_vector(&corpus[i], 1, 2, 0);
        write_search_vector(&corpus[i], 0, 2, 0);
        if (full) write_search_vector(&corpus[i], 0, 3, 0);
    }

    printf("wrote %d positions\n", count);
    fclose(f_pos); fclose(f_apply); fclose(f_moves); fclose(f_search);
    return 0;
}

Line by line

  1. Open the four output files in the folder given on the command line.
  2. Build the corpus: each seed, plus positions from random legal games starting at that seed (2 games per seed in the quick set, 8 in the full set), keeping every fourth position. Random games reach positions no one would think of writing by hand.
  3. Write the position vectors for the whole corpus.
  4. Write search vectors: perft and searches at several depths for each seed, one search with a node limit of 100 (it must abort), and shallow searches on every eighth corpus position.
Check
Command Prompt
cd /d C:\chess\c
gcc -std=c99 -O2 -Wall -Wextra gen_vectors.c -o gen_vectors.exe
gen_vectors.exe ..\vectors
Expected output
wrote 295 positions

With Visual Studio, use cl /O2 /std:c11 /D_CRT_SECURE_NO_WARNINGS gen_vectors.c /Fe:gen_vectors.exe. The vectors folder now holds about 3.4 MB of text. This is the quick set, sized so Vivado's simulator gets through it in minutes. gen_vectors.exe ..\vectors full writes the thorough set: 1,109 positions and 577 searches, about 2.4 million nodes. I ran that one under Verilator; in Vivado's simulator it would take many hours.

Part 1 checklist
  • engine.exe test prints ALL PERFT TESTS PASSED.
  • The depth 1 to 6 search table matches exactly.
  • Mate in one and stalemate behave as described.
  • vectors\ holds the four files.
Part 2

The same engine, as hardware

Now you build the engine again, as circuits, in SystemVerilog. Nothing here needs a board yet: every block is simulated and checked against the C engine's answer files before the next block is built. The first four steps are about thinking in hardware; the code starts in Step 23.

19Thinking in hardware

Goal: understand the one big difference between a C program and a circuit.

Concept

A C program is a list of instructions, run one after another by a single processor. A circuit is not a list. Every part of it is working all the time, in parallel. A clock ticks (50 million times a second, in our design), and on each tick, every register in the chip captures the value on its input at the same instant.

So a C statement like score = evaluate(p); becomes three separate facts in hardware:

  1. The evaluator circuit is always computing, from whatever position is on its input wires.
  2. A state machine puts the right position on those wires, then waits.
  3. The state machine reads the answer only when a valid signal says the answer belongs to that position.

Most of the strange, intermittent bugs in FPGA designs are not logic bugs. They are a correct answer read on the wrong clock cycle. This design avoids them with two simple rules, which Step 22 explains.

Here is how each C idea from Part 1 maps onto hardware. The next three steps look at the three most interesting rows.

In CIn hardware
a pure function such as knight_attackswires and gates: the answer appears in the same clock cycle
a loop with a known maximum, such as slideunrolled into a fixed number of logic layers (Step 20)
nested loops over stages, pieces and movesa state machine with one register per loop, one step per clock (Step 29)
a local variable that survives a recursive calla field of a stack frame, stored in block RAM (Step 21)
a function call and returnwrite the frame to the stack RAM, then read it back (Step 21)
an array, such as a move lista block RAM: reading takes one clock cycle (Step 22)
Position child = *p;a second 780-bit register, child, next to pos

Reading SystemVerilog: the constructs this guide uses

If you know C, you can read every line of the RTL with this table. There are only a dozen constructs, and the code uses them the same way every time.

You will seeIt meansClosest C
logic [63:0] b;a 64-bit signal. Bit 63 is the left oneuint64_t b;
typedef struct packed {...}a struct that is also one long bit vector, so it can be copied or stored in RAM wholestruct
localparama named constant, fixed when the chip is built#define, enum
function automatic ...a pure function; synthesis copies it into logic wherever it is calledstatic inline
always_comb begin ... endlogic that recomputes whenever an input changes: wires and gates, no memoryan expression
always_ff @(posedge clk)registers: everything assigned inside changes only at the clock edgethe variables of a loop, updated once per iteration
x <= y;non-blocking: "at the next edge, x becomes y". All of them happen at once, using the old valueswriting into a "next" copy
x = y;blocking: used only in always_comb and functions, reads like Cx = y;
{a, b}concatenation: the bits of a followed by the bits of b(a << width_b) | b
4'(x), 8'd5a cast to 4 bits; the number 5 written as 8 bits(uint8_t)5
case (state) ... endcasepick the branch for the current stateswitch
typedef enum logic [3:0] {...}named states, stored in 4 bitsenum

The rule that surprises C programmers is the non-blocking assignment. In a <= b; b <= a; the two registers swap, because both right-hand sides are read before either register changes. Every always_ff block in this design is written so that it reads like "the next state of every register, given the current ones". Try it:

Wires change now, registers change at the edge. sum is always_comb: it follows the inputs at once. acc and prev are always_ff: they change only when you press "Clock edge", and both use the values from just before the edge.

SystemVerilog lets you write functions that look almost like C. When a function only uses constants and its inputs, synthesis turns it into plain logic. Most of the package in Steps 24 to 27 is written that way, so it reads almost line for line like chess.h.

20Loops become logic: sliding in three layers

Goal: compute a sliding piece's attacks with a fixed, short chain of logic.

Concept

A loop in hardware is unrolled: the tool copies its body once per iteration, chaining the copies. The C slide loop can run seven times, so unrolled it becomes seven layers of logic in a row. Seven layers is slow: the signal has to ripple through all of them before the next clock edge.

The Kogge-Stone method gets the same answer in three layers. It keeps two sets:

  • g: squares the ray has reached so far. It starts as just the slider.
  • p: squares the ray may pass through. It starts as the empty squares.

Each layer lets every ray jump twice as far as the last: 1 square, then 2, then 4. The trick is that p doubles too: after layer 1, p means "this square and the one below it are both empty", after layer 2 "four in a row are empty". So a ray can only jump a distance if every square it jumps over is empty.

Expected output
g = slider              p = empty squares
layer 1:  g |= p & (g shifted 1);   p &= (p shifted 1)     reach: 2 squares
layer 2:  g |= p & (g shifted 2);   p &= (p shifted 2)     reach: 4 squares
layer 3:  g |= p & (g shifted 4)                           reach: 8 squares
attacks = g shifted once more                               includes the blocker

A worked example on one file

Take a rook on d1 sliding north, with pieces on d4 and d7. Write the d-file as eight bits, rank 1 on the left: the slider is 10000000, and the empty squares are every square except d1, d4 and d7: 01101101. "Shifted" below means one rank up the file, which is a shift by 8 squares in the real board.

Expected output
start      g = 10000000   p = 01101101                 (p: empty squares)
layer 1    g |= p & (g up 1)  -> g = 11000000            reached d2
           p &= (p up 1)      -> p = 00100100            "two empties in a row" ends here
layer 2    g |= p & (g up 2)  -> g = 11100000            reached d3
           p &= (p up 2)      -> p = 00000000            no run of four empties
layer 3    g |= p & (g up 4)  -> g = 11100000            nothing more
attacks    g up 1, without the slider -> 01110000         d2, d3 and the blocker d4

The ray stops at d4, the first piece, exactly as the C loop would, and it took three layers whether the board was empty or crowded.

Kogge-Stone on one file. Click the first column to place blockers, the second to move the slider. The final column always equals what the C loop computes, in three steps however far the ray goes.

Shifts by a constant cost nothing in hardware: they are just wires, connecting bit n to bit n + 8. So each direction is about three layers of AND and OR, whatever the board looks like. The hardware test in Step 27 checks that the two methods agree on all 1,109 test positions.

Why not lookup tables?

CPU engines use large precomputed tables for sliders ("magic bitboards"). In an FPGA, a big table needs block RAM, which takes a clock cycle to read and has only two ports. Logic gives the answer in the same cycle, and you can build as many copies as you like. FPGAs reward this style.

21Recursion becomes a state machine and a stack

Goal: run a recursive function in a circuit, which has no call stack of its own.

Concept

When C calls negamax recursively, the compiler quietly does a lot of work. It saves every local variable of the current call, starts a fresh copy of the function for the child, and when the child returns, restores the saved variables and carries on where it left off. That saved bundle is a stack frame.

Hardware has no compiler doing this for you, so we do it by hand:

  • The current node lives in registers: pos (the position) and f (the frame: alpha, beta, best, the loop index, and so on).
  • Every ancestor of the current node lives in a block RAM, the stack RAM, one row per ply.
  • A call writes {pos, f} into row ply, loads the child into the registers, and adds 1 to ply.
  • A return reads row ply − 1 back into the registers, subtracts 1 from ply, and carries on with the parent's next move.
The same walk, two ways. On the left, the frames C keeps on its call stack. On the right, the frames the hardware keeps: the current one in registers, the ancestors in the stack RAM. They hold the same information at every step. (To keep the focus on the stack, this tree is searched without pruning.)

This is why so little memory is needed. A depth-first search never stores the tree, only one path from the root to the current node, like a trail of breadcrumbs instead of a map. A million-node search fits in 32 rows.

MemoryShapeBitsHolds
Stack RAM32 rows × 851 bits27,232one ancestor position plus its frame, per ply
Move RAM8,192 rows × 15 bits122,880a 256-move list for each of the 32 plies

The XC7Z020 has 140 block RAMs of 36 Kib each. The stack uses 12 of them even though it holds few bits, because one block RAM is at most 72 bits wide and each row is 851 bits wide. The move RAM uses 4. That is 16 in all, about 11% of the chip.

The move lists need their own RAM because each ply's list must survive while the children use the plies above it. When a child returns, the parent reads its next move from its own list, still sitting at addresses ply × 256 onward.

22Clocks, RAM latency, and valid signals

Goal: two rules that keep every block in step with the others.

Concept

Rule 1: a block RAM read takes one clock. You present the address on one clock edge, and the data appears after it. So the state machine sets the address in one state and uses the data in the next. Here is that rule in action as the search core tries a move:

Trying one move. In S_NEXT the RAM address is {ply, index}. The move appears on rdata one clock later, and S_READ stores it in move_r. Each following state does one piece of work and stores its result in a register, so no single clock has too much logic to do.

Rule 2: blocks say when they are done. The move generator pulses done, and the evaluator raises valid. The state machine waits for them, so it never depends on knowing a block's exact delay. You could add a pipeline stage to the evaluator later, and the search core would still work.

The evaluator handshake. A one-clock start pulse goes into a shift register that travels alongside the data, so valid comes out exactly when score belongs to position P.

In a waveform, a high line is 1 and a low line is 0. A boxed region is a multi-bit value such as a move or a score, and a crossed region means "don't care yet". You will see these in Vivado's simulator too.

23Set up the simulator

Goal: one command that compiles and runs any testbench in Vivado's simulator.

Vivado's simulator has three command-line tools: xvlog compiles Verilog and SystemVerilog, xelab links the design, and xsim runs it. This batch file runs all three for whichever testbench you name, in a sim folder with a copy of the vector files.

Create scripts/run_sim.bat
@echo off
rem run_sim.bat - compiles the RTL and one testbench, then runs it in Vivado's simulator.
rem Usage (from the project folder, in a window where settings64.bat has been run):
rem     scripts\run_sim.bat tb_functions
if "%~1"=="" (
  echo Usage: scripts\run_sim.bat tb_functions ^| tb_eval ^| tb_move_gen ^| tb_search ^| tb_axi
  exit /b 1
)
if not exist sim mkdir sim
copy /y vectors\vec_*.txt sim >nul
cd sim
call xvlog -sv ..\rtl\chess_pkg.sv ..\rtl\sdp_ram.sv ..\rtl\eval_pipe.sv ..\rtl\move_gen.sv ..\rtl\search_core.sv ..\rtl\chess_axi.sv ..\tb\%~1.sv || goto :failed
call xvlog ..\rtl\chess_axi_top.v || goto :failed
call xelab %~1 -s %~1_sim || goto :failed
call xsim %~1_sim -R || goto :failed
cd ..
exit /b 0
:failed
cd ..
echo COMPILE OR SIMULATION ERROR: read the messages above.
exit /b 1

Before using it, open a Command Prompt and load Vivado's tools (use your own version number):

Command Prompt
call C:\Xilinx\Vivado\2023.2\settings64.bat
cd /d C:\chess

You need to do this once per new window. xvlog --version confirms it worked. Every testbench in this guide ends by printing TB_... PASS or TB_... FAIL, plus one line per mismatch. A testbench that prints neither has crashed or is stuck.

The batch file compiles every RTL file each time, so create empty placeholders for the files you haven't written yet:

Command Prompt
cd /d C:\chess
for %f in (sdp_ram.sv eval_pipe.sv move_gen.sv search_core.sv chess_axi.sv chess_axi_top.v) do type nul > rtl\%f

24The package: types and helpers

Goal: the hardware version of the first two snippets of chess.h.

Concept

A SystemVerilog package holds types, constants and functions that every module can share, just as chess.h does for the C programs. The position becomes a packed struct. "Packed" means the whole struct is also one long vector of bits, here 780 of them:

Expected output
bb[11] ... bb[0]   12 x 64 = 768 bits
side                      1 bit
castle                    4 bits
ep                        7 bits     (0 to 63, or 64 for none)
                        -----
                        780 bits

That matters later: because it is one vector, the whole position can be written into a RAM, or copied into another register, in a single clock.

Code
Create rtl/chess_pkg.svpart 1 of 11
// chess_pkg.sv - shared types and pure chess functions.
// Everything here is plain combinational logic. Function names match c/chess.h.
`timescale 1ns / 1ps
package chess_pkg;

  typedef logic [63:0] bb_t;       // bitboard: bit n is square n (a1 = 0, h8 = 63)
  typedef logic [14:0] move_t;     // [5:0] from, [11:6] to, [14:12] promotion

  localparam logic WHITE = 1'b0;
  localparam logic BLACK = 1'b1;

  // Piece types. A board index is color * 6 + type.
  localparam int PAWN = 0, KNIGHT = 1, BISHOP = 2, ROOK = 3, QUEEN = 4, KING = 5;

  // Castling-right bits
  localparam logic [3:0] WK = 4'b0001, WQ = 4'b0010, BK = 4'b0100, BQ = 4'b1000;

  localparam logic [6:0] NO_EP = 7'd64;
  localparam int MAX_PLY = 32;

  typedef struct packed {
    logic [11:0][63:0] bb;      // bb[0] white pawns ... bb[11] black king
    logic              side;
    logic [3:0]        castle;
    logic [6:0]        ep;      // 0..63, or 64 for "none"
  } position_t;                 // 780 bits

  localparam bb_t ALL    = 64'hFFFFFFFFFFFFFFFF;
  localparam bb_t FILE_A = 64'h0101010101010101;
  localparam bb_t FILE_B = 64'h0202020202020202;
  localparam bb_t FILE_G = 64'h4040404040404040;
  localparam bb_t FILE_H = 64'h8080808080808080;
  localparam bb_t NOT_A  = ~FILE_A;
  localparam bb_t NOT_H  = ~FILE_H;
  localparam bb_t NOT_AB = ~(FILE_A | FILE_B);
  localparam bb_t NOT_GH = ~(FILE_G | FILE_H);
  localparam bb_t RANK_1 = 64'h00000000000000FF;
  localparam bb_t RANK_4 = 64'h00000000FF000000;
  localparam bb_t RANK_5 = 64'h000000FF00000000;
  localparam bb_t RANK_8 = 64'hFF00000000000000;
  localparam bb_t LAST_RANKS = RANK_1 | RANK_8;

  // Generation stages: same order as the C enum
  localparam logic [2:0] ST_PROMO = 3'd0, ST_CAP_Q = 3'd1, ST_CAP_R = 3'd2,
                         ST_CAP_B = 3'd3, ST_CAP_N = 3'd4, ST_CAP_P = 3'd5,
                         ST_QUIET = 3'd6;

Line by line, next to the C

  • package chess_pkg; ... endpackage is the hardware chess.h. Every module that says import chess_pkg::*; can use these names.
  • typedef logic [63:0] bb_t is U64, and move_t, 15 bits wide, is Move. In hardware a type is exactly as wide as you say: there is no 16th bit to waste.
  • localparam is a constant fixed when the chip is built, like an enum or #define. Colours are one bit, castling rights four bits, matching the C values exactly, so a position can be copied between C and hardware bit for bit.
  • logic [11:0][63:0] bb is a packed two-dimensional array: twelve 64-bit boards, stored side by side as one 768-bit vector. bb[7] is still the black knights.
  • In a packed struct, the first field holds the highest bits. That order only matters when the whole struct is treated as one vector, for instance when it is written into the stack RAM, and the same type is used on both sides, so it always matches.
  • The file and rank masks are the same numbers as in C, written in hex with the 64'h prefix: 64 bits wide, hexadecimal.
  • The stage numbers must match the C enum, because both sides must produce the moves in the same order for the tests to compare them.

Two helpers are new compared with C. lowest_bit is the b & -b trick from Step 2. square_of turns a one-hot bitboard (exactly one bit set) into its square number. It only works because exactly one bit is set: bit k of the answer is simply the OR of the 32 input bits whose square number has bit k set. That is a small OR tree. A general "find the first set bit" circuit, like C's lsb loop, would be much bigger.

Add to rtl/chess_pkg.svpart 2 of 11
  // ---------------- small helpers ----------------
  function automatic bb_t side_pieces(input position_t p, input logic c);
    bb_t x = 64'b0;
    for (int t = 0; t < 6; t++) x |= p.bb[(c ? 6 : 0) + t];
    return x;
  endfunction

  function automatic bb_t occupied(input position_t p);
    bb_t x = 64'b0;
    for (int i = 0; i < 12; i++) x |= p.bb[i];
    return x;
  endfunction

  // Isolate the lowest set bit: 0b0110_1000 -> 0b0000_1000
  function automatic bb_t lowest_bit(input bb_t x);
    return x & (~x + 64'd1);
  endfunction

  // Turn a one-hot bitboard into its square number. Each result bit is one OR gate tree.
  function automatic logic [5:0] square_of(input bb_t one_hot);
    logic [5:0] sq = 6'd0;
    for (int i = 0; i < 64; i++)
      if (one_hot[i]) sq |= 6'(i);
    return sq;
  endfunction

25Attacks in hardware

Goal: the same attack functions as C, with the slide loop replaced by three layers.

Code

sh is the C shift. slide is the Kogge-Stone version from Step 20, line for line. Note how the mask goes into p at the start, so that a wrapped step can't continue a ray either.

Add to rtl/chess_pkg.svpart 3 of 11
  // ---------------- attack generation ----------------
  // Shift left for s > 0, right for s < 0. With a constant s this is only wiring.
  function automatic bb_t sh(input bb_t b, input int s);
    return (s >= 0) ? (b << s) : (b >> (-s));
  endfunction

  // Kogge-Stone fill: the same answer as the C loop, but three AND/OR layers
  // instead of seven, because each layer doubles the reach of every ray.
  function automatic bb_t slide(input bb_t gen, input bb_t occ, input int s, input bb_t m);
    bb_t g = gen;
    bb_t p = ~occ & m;                 // squares a ray may continue through
    g |= p & sh(g, s);    p &= sh(p, s);
    g |= p & sh(g, 2*s);  p &= sh(p, 2*s);
    g |= p & sh(g, 4*s);
    return sh(g, s) & m;               // one last step reaches the first blocker
  endfunction

Line by line

  1. sh shifts left for a positive step and right for a negative one. Because every call passes a constant s, synthesis resolves the ?: at build time and the shift becomes plain wiring: bit n connects to bit n + s. It costs no logic at all.
  2. g ("generate") is the set of squares the ray has reached, starting with the sliders themselves. p ("propagate") is the set of squares a ray may pass through: empty, and not across the board edge (m).
  3. Layer 1: every ray steps one square into an empty square; p becomes "this square and the next are both empty". Layer 2 jumps two, layer 3 jumps four. After three layers a ray has covered up to seven squares, the longest possible.
  4. The last line takes one more step without requiring the square to be empty: that is the first blocker, which a slider attacks (a capture, or protecting its own piece).

The rest is a direct copy of the C, with C's shift(set, 17) becoming sh(s, 17). Since every shift amount is a constant, all of this is wiring and gates; no clock is involved.

Add to rtl/chess_pkg.svpart 4 of 11
  function automatic bb_t bishop_attacks(input bb_t set, input bb_t occ);
    return slide(set, occ, 9, NOT_A) | slide(set, occ, 7, NOT_H)
         | slide(set, occ, -7, NOT_A) | slide(set, occ, -9, NOT_H);
  endfunction

  function automatic bb_t rook_attacks(input bb_t set, input bb_t occ);
    return slide(set, occ, 8, ALL) | slide(set, occ, -8, ALL)
         | slide(set, occ, 1, NOT_A) | slide(set, occ, -1, NOT_H);
  endfunction

  function automatic bb_t knight_attacks(input bb_t s);
    return (sh(s, 17) & NOT_A)  | (sh(s, 15) & NOT_H)
         | (sh(s, 10) & NOT_AB) | (sh(s, 6) & NOT_GH)
         | (sh(s, -6) & NOT_AB) | (sh(s, -10) & NOT_GH)
         | (sh(s, -15) & NOT_A) | (sh(s, -17) & NOT_H);
  endfunction

  function automatic bb_t king_attacks(input bb_t s);
    return sh(s, 8) | sh(s, -8)
         | (sh(s, 1) & NOT_A)  | (sh(s, -1) & NOT_H)
         | (sh(s, 9) & NOT_A)  | (sh(s, 7) & NOT_H)
         | (sh(s, -7) & NOT_A) | (sh(s, -9) & NOT_H);
  endfunction

  function automatic bb_t pawn_attacks(input logic color, input bb_t s);
    return (color == WHITE) ? ((sh(s, 9) & NOT_A) | (sh(s, 7) & NOT_H))
                            : ((sh(s, -7) & NOT_A) | (sh(s, -9) & NOT_H));
  endfunction

  // Every square attacked by every piece of side c.
  function automatic bb_t side_attacks(input position_t p, input logic c);
    int  base = c ? 6 : 0;
    bb_t occ  = occupied(p);
    return pawn_attacks(c, p.bb[base + PAWN])
         | knight_attacks(p.bb[base + KNIGHT])
         | king_attacks(p.bb[base + KING])
         | bishop_attacks(p.bb[base + BISHOP] | p.bb[base + QUEEN], occ)
         | rook_attacks(p.bb[base + ROOK] | p.bb[base + QUEEN], occ);
  endfunction

26Making a move, in two clocks

Goal: the C make_move, split in half so neither half is too slow.

Concept

In C, make_move is one function. As one block of hardware it would be a long chain: find the moving piece, work out the rook squares and the en-passant victim, then update twelve 64-bit boards. A long chain forces a slow clock, so we split it at a natural seam:

  • Clock 1, decode_move: work out what changes. Which type moved, which type lands, the one-hot from and to squares, the rook squares if castling, the en-passant victim, the new rights and en-passant square.
  • Clock 2, apply_decoded: apply those changes to the twelve boards. Each board only needs a few ANDs and ORs per bit.

The struct decoded_move_t is the register between the two halves. This is pipelining: splitting a long job into short stages with registers between them, so the clock can run faster.

Code

First the struct that travels between the two clocks. Each field is one fact about the move, already in the form the second half needs: one-hot squares as bitboards, so applying them is just AND and OR.

Add to rtl/chess_pkg.svpart 5 of 11
  // ---------------- making a move ----------------
  // Making a move takes two clocks: decode_move() works out WHAT changes, and
  // apply_decoded() changes the twelve boards. Splitting it shortens the logic path.
  typedef struct packed {
    bb_t        from_bit;
    bb_t        to_bit;
    bb_t        ep_victim;      // pawn captured en passant (0 if none)
    bb_t        rook_clear;     // rook square emptied by castling (0 if none)
    bb_t        rook_set;       // rook square filled by castling (0 if none)
    logic [5:0] moved;          // one-hot: type that leaves "from"
    logic [5:0] placed;         // one-hot: type that lands on "to"
    logic [3:0] castle;         // castling rights after the move
    logic [6:0] ep;             // en-passant square after the move
  } decoded_move_t;

Now the first clock. It reads like the C, but every line computes in parallel: there is no "first" and "then" inside a function, only wires.

Add to rtl/chess_pkg.svpart 6 of 11
  function automatic decoded_move_t decode_move(input position_t p, input move_t m);
    decoded_move_t d;
    logic       us = p.side;
    logic [5:0] from = m[5:0];
    logic [5:0] to   = m[11:6];
    logic [2:0] promo = m[14:12];
    logic       is_castle;
    logic [3:0] lost;

    d.from_bit = 64'b1 << from;
    d.to_bit   = 64'b1 << to;
    for (int t = 0; t < 6; t++)
      d.moved[t] = p.bb[(us ? 6 : 0) + t][from];

    d.ep_victim = 64'b0;
    if (d.moved[PAWN] && {1'b0, to} == p.ep)
      d.ep_victim = (us == WHITE) ? (d.to_bit >> 8) : (d.to_bit << 8);

    is_castle = d.moved[KING] && (to == from + 6'd2 || from == to + 6'd2);
    d.rook_clear = 64'b0;
    d.rook_set   = 64'b0;
    if (is_castle) begin
      d.rook_clear = (to > from) ? (d.to_bit << 1) : (d.to_bit >> 2);
      d.rook_set   = (to > from) ? (d.to_bit >> 1) : (d.to_bit << 1);
    end

    d.placed = d.moved;
    if (promo != 3'd0) begin
      d.placed = 6'b0;
      d.placed[promo] = 1'b1;           // promotion codes 1..4 = KNIGHT..QUEEN
    end

    lost = 4'b0;
    if (from == 6'd4  || to == 6'd4)  lost |= WK | WQ;
    if (from == 6'd7  || to == 6'd7)  lost |= WK;
    if (from == 6'd0  || to == 6'd0)  lost |= WQ;
    if (from == 6'd60 || to == 6'd60) lost |= BK | BQ;
    if (from == 6'd63 || to == 6'd63) lost |= BK;
    if (from == 6'd56 || to == 6'd56) lost |= BQ;
    d.castle = p.castle & ~lost;

    d.ep = NO_EP;
    if (d.moved[PAWN] && (to == from + 6'd16 || from == to + 6'd16))
      d.ep = {1'b0, from[5:3] + (to > from ? 3'd1 : 3'd7), from[2:0]};
    return d;
  endfunction

Line by line

  1. from, to and promo are just slices of the 15-bit move word: bits 5..0, 11..6, 14..12.
  2. from_bit and to_bit shift a single 1 into place: a 6-to-64 decoder.
  3. d.moved[t] asks each of my six boards whether it has a piece on from. Exactly one answers 1, so moved is one-hot. C searched with a while loop; hardware asks all six at once.
  4. En passant: a pawn landing on the en-passant square captures the pawn one rank behind it, so ep_victim is to_bit shifted back by 8.
  5. Castling: a king moving two files. For a king-side castle (to > from) the rook comes from the square right of to and lands left of it; queen-side, from two left and lands one right.
  6. Promotion: placed starts as a copy of moved; a promotion replaces it with the promoted type, using the fact that promotion codes 1..4 equal KNIGHT..QUEEN.
  7. Rights: moving from or capturing on a king or rook home square removes the matching rights, exactly as rights_lost in C.
  8. New en-passant square: after a double pawn push, the square passed over. from[5:3] is the rank; adding 1 (or 7, which is −1 in three bits) gives the rank in between.

The second clock applies those facts to the twelve boards:

Add to rtl/chess_pkg.svpart 7 of 11
  function automatic position_t apply_decoded(input position_t p, input decoded_move_t d);
    position_t q = p;
    for (int i = 0; i < 12; i++) begin
      int t = i % 6;
      if ((i >= 6) == p.side) begin     // one of my boards
        if (d.moved[t])  q.bb[i] = q.bb[i] & ~d.from_bit;
        if (d.placed[t]) q.bb[i] = q.bb[i] | d.to_bit;
        if (t == ROOK)   q.bb[i] = (q.bb[i] & ~d.rook_clear) | d.rook_set;
      end else begin                    // one of the enemy boards
        q.bb[i] = q.bb[i] & ~d.to_bit;
        if (t == PAWN) q.bb[i] = q.bb[i] & ~d.ep_victim;
      end
    end
    q.castle = d.castle;
    q.ep     = d.ep;
    q.side   = ~p.side;
    return q;
  endfunction

Line by line

  1. (i >= 6) == p.side picks my six boards: indices 0..5 are white, 6..11 black.
  2. On my board of the moved type, clear from; on my board of the placed type, set to. For an ordinary move these are the same board; for a promotion they differ.
  3. My rook board also gets the castling rook moved. When not castling, rook_clear and rook_set are 0, so the line changes nothing.
  4. Every enemy board loses to: that is the capture, with no need to know what was captured. The enemy pawn board also loses the en-passant victim.
  5. Finally the new rights, en-passant square, and the side flips.

And the legality test. safe_squares returns the squares that must not be attacked: the king, or the three castling squares. It uses a case on four constants instead of C's shift by min(from, to), because a king moving two squares can only be one of the four castling moves.

Add to rtl/chess_pkg.svpart 8 of 11
  // Squares that must not be attacked after move m (see legal_after in C).
  function automatic bb_t safe_squares(input position_t child, input move_t m);
    logic [5:0] from = m[5:0];
    logic [5:0] to   = m[11:6];
    bb_t king = child.bb[(child.side ? 0 : 6) + KING];   // the mover's king
    if (king[to] && (to == from + 6'd2 || from == to + 6'd2))
      case (to)
        6'd6:    return 64'h0000000000000070;
        6'd2:    return 64'h000000000000001C;
        6'd62:   return 64'h7000000000000000;
        default: return 64'h1C00000000000000;
      endcase
    return king;
  endfunction

27Targets, tables, and the first test

Goal: finish the package, then prove every function in it against the C.

Code

stage_targets matches the C function exactly, with one difference: occ comes in as an argument, so the move generator can keep it in a register instead of recomputing it every clock.

Add to rtl/chess_pkg.svpart 9 of 11
  // ---------------- move-generation targets ----------------
  function automatic bb_t stage_targets(input position_t p, input bb_t occ,
                                        input logic [2:0] stage,
                                        input logic [2:0] ptype, input bb_t from_bit);
    logic us = p.side;
    int   theirs_base = us ? 0 : 6;
    bb_t  att, one, two, targets, victims;

    one = ((us == WHITE) ? (from_bit << 8) : (from_bit >> 8)) & ~occ;
    two = ((us == WHITE) ? (one << 8) : (one >> 8)) & ~occ
        & ((us == WHITE) ? RANK_4 : RANK_5);

    case (ptype)
      3'd0:    att = pawn_attacks(us, from_bit);
      3'd1:    att = knight_attacks(from_bit);
      3'd2:    att = bishop_attacks(from_bit, occ);
      3'd3:    att = rook_attacks(from_bit, occ);
      3'd4:    att = bishop_attacks(from_bit, occ) | rook_attacks(from_bit, occ);
      default: att = king_attacks(from_bit);
    endcase

    case (stage)
      ST_CAP_Q: victims = p.bb[theirs_base + QUEEN];
      ST_CAP_R: victims = p.bb[theirs_base + ROOK];
      ST_CAP_B: victims = p.bb[theirs_base + BISHOP];
      ST_CAP_N: victims = p.bb[theirs_base + KNIGHT];
      default: begin
        victims = p.bb[theirs_base + PAWN];
        if (ptype == 3'd0 && !p.ep[6]) victims[p.ep[5:0]] = 1'b1;
      end
    endcase

    if (stage == ST_PROMO) begin
      targets = (ptype == 3'd0) ? (one & LAST_RANKS) : 64'b0;
    end else if (stage == ST_QUIET) begin
      targets = (ptype == 3'd0) ? ((one & ~LAST_RANKS) | two) : (att & ~occ);
      if (ptype == 3'd5) begin
        if (us == WHITE) begin
          if (p.castle[0] && (occ & 64'h60) == 64'b0) targets[6] = 1'b1;
          if (p.castle[1] && (occ & 64'h0E) == 64'b0) targets[2] = 1'b1;
        end else begin
          if (p.castle[2] && (occ & 64'h6000000000000000) == 64'b0) targets[62] = 1'b1;
          if (p.castle[3] && (occ & 64'h0E00000000000000) == 64'b0) targets[58] = 1'b1;
        end
      end
    end else begin
      targets = att & victims;
    end
    return targets;
  endfunction

The evaluation tables are the same numbers as in C. SystemVerilog writes an array constant as '{...}.

Add to rtl/chess_pkg.svpart 10 of 11
  // ---------------- evaluation tables ----------------
  localparam int PIECE_VALUE [0:5] = '{100, 320, 330, 500, 900, 0};

  // Same tables as C: first row of each table = rank 8.
  localparam int PST [0:6][0:63] = '{
    '{ // pawn
       0,  0,  0,  0,  0,  0,  0,  0,
      50, 50, 50, 50, 50, 50, 50, 50,
      10, 10, 20, 30, 30, 20, 10, 10,
       5,  5, 10, 25, 25, 10,  5,  5,
       0,  0,  0, 20, 20,  0,  0,  0,
       5, -5,-10,  0,  0,-10, -5,  5,
       5, 10, 10,-20,-20, 10, 10,  5,
       0,  0,  0,  0,  0,  0,  0,  0 },
    '{ // knight
     -50,-40,-30,-30,-30,-30,-40,-50,
     -40,-20,  0,  0,  0,  0,-20,-40,
     -30,  0, 10, 15, 15, 10,  0,-30,
     -30,  5, 15, 20, 20, 15,  5,-30,
     -30,  0, 15, 20, 20, 15,  0,-30,
     -30,  5, 10, 15, 15, 10,  5,-30,
     -40,-20,  0,  5,  5,  0,-20,-40,
     -50,-40,-30,-30,-30,-30,-40,-50 },
    '{ // bishop
     -20,-10,-10,-10,-10,-10,-10,-20,
     -10,  0,  0,  0,  0,  0,  0,-10,
     -10,  0,  5, 10, 10,  5,  0,-10,
     -10,  5,  5, 10, 10,  5,  5,-10,
     -10,  0, 10, 10, 10, 10,  0,-10,
     -10, 10, 10, 10, 10, 10, 10,-10,
     -10,  5,  0,  0,  0,  0,  5,-10,
     -20,-10,-10,-10,-10,-10,-10,-20 },
    '{ // rook
       0,  0,  0,  0,  0,  0,  0,  0,
       5, 10, 10, 10, 10, 10, 10,  5,
      -5,  0,  0,  0,  0,  0,  0, -5,
      -5,  0,  0,  0,  0,  0,  0, -5,
      -5,  0,  0,  0,  0,  0,  0, -5,
      -5,  0,  0,  0,  0,  0,  0, -5,
      -5,  0,  0,  0,  0,  0,  0, -5,
       0,  0,  0,  5,  5,  0,  0,  0 },
    '{ // queen
     -20,-10,-10, -5, -5,-10,-10,-20,
     -10,  0,  0,  0,  0,  0,  0,-10,
     -10,  0,  5,  5,  5,  5,  0,-10,
      -5,  0,  5,  5,  5,  5,  0, -5,
       0,  0,  5,  5,  5,  5,  0, -5,
     -10,  5,  5,  5,  5,  5,  0,-10,
     -10,  0,  5,  0,  0,  0,  0,-10,
     -20,-10,-10, -5, -5,-10,-10,-20 },
    '{ // king, while any queen is on the board
     -30,-40,-40,-50,-50,-40,-40,-30,
     -30,-40,-40,-50,-50,-40,-40,-30,
     -30,-40,-40,-50,-50,-40,-40,-30,
     -30,-40,-40,-50,-50,-40,-40,-30,
     -20,-30,-30,-40,-40,-30,-30,-20,
     -10,-20,-20,-20,-20,-20,-20,-10,
      20, 20,  0,  0,  0,  0, 20, 20,
      20, 30, 10,  0,  0, 10, 30, 20 },
    '{ // king, once all queens are gone
     -50,-40,-30,-20,-20,-30,-40,-50,
     -30,-20,-10,  0,  0,-10,-20,-30,
     -30,-10, 20, 30, 30, 20,-10,-30,
     -30,-10, 30, 40, 40, 30,-10,-30,
     -30,-10, 30, 40, 40, 30,-10,-30,
     -30,-10, 20, 30, 30, 20,-10,-30,
     -30,-30,  0,  0,  0,  0,-30,-30,
     -50,-30,-30,-30,-30,-30,-30,-50 }
  };

piece_on_square returns the signed value of one piece standing on one square, already negated for Black. The evaluator calls it with constant arguments, so synthesis replaces each call with a single constant: there is no table lookup left in the hardware at all.

Add to rtl/chess_pkg.svpart 11 of 11
  localparam int TEMPO = 10;

  // Signed White-minus-Black value of piece pc standing on square sq.
  // With constant pc and sq this is a constant; synthesis builds only an OR.
  function automatic logic signed [11:0] piece_on_square(input int pc, input int sq,
                                                         input int table_index);
    int type_index = pc % 6;
    int v;
    if (pc < 6) v =   PIECE_VALUE[type_index] + PST[table_index][sq ^ 56];
    else        v = -(PIECE_VALUE[type_index] + PST[table_index][sq]);
    return 12'(v);
  endfunction
endpackage
Check

This testbench calls the package functions directly; it doesn't even need a clock. It reads each test position, compares both attack maps, then plays every move and compares the child position and the legality verdict with the C's answers. Note the !== operator: it treats an unknown x bit as a mismatch, which != would not.

Create tb/tb_functions.sv
// tb_functions.sv - checks side_attacks(), apply_move() and safe_squares().
`timescale 1ns / 1ps
module tb_functions;
  import chess_pkg::*;

  task automatic read_pos(input int fd, output position_t p);
    logic [63:0] b;
    int side, castle, ep, r;
    for (int i = 0; i < 12; i++) begin
      r = $fscanf(fd, "%h", b);
      p.bb[i] = b;
    end
    r = $fscanf(fd, "%d %d %d", side, castle, ep);
    p.side = side[0];
    p.castle = castle[3:0];
    p.ep = ep[6:0];
  endtask

  initial begin
    int fd, errors, checked, r, legal;
    position_t p, child, expected;
    logic [63:0] att_w, att_b;
    logic [15:0] mv;
    int score, check_flag;
    errors = 0;
    checked = 0;

    fd = $fopen("vec_positions.txt", "r");
    if (fd == 0) $fatal(1, "cannot open vec_positions.txt");
    while (!$feof(fd)) begin
      read_pos(fd, p);
      r = $fscanf(fd, "%h %h %d %d\n", att_w, att_b, score, check_flag);
      if (r != 4) break;
      checked++;
      if (side_attacks(p, WHITE) !== att_w || side_attacks(p, BLACK) !== att_b) begin
        errors++;
        $display("ATTACK MISMATCH at position %0d", checked);
      end
    end
    $fclose(fd);
    $display("attacks checked on %0d positions, errors = %0d", checked, errors);

    checked = 0;
    fd = $fopen("vec_apply.txt", "r");
    if (fd == 0) $fatal(1, "cannot open vec_apply.txt");
    while (!$feof(fd)) begin
      read_pos(fd, p);
      r = $fscanf(fd, "%h", mv);
      if (r != 1) break;
      read_pos(fd, expected);
      r = $fscanf(fd, "%d\n", legal);
      checked++;
      child = apply_decoded(p, decode_move(p, mv[14:0]));
      if (child !== expected) begin
        errors++;
        $display("APPLY MISMATCH: move %h, line %0d", mv, checked);
      end
      if (((side_attacks(child, child.side) & safe_squares(child, mv[14:0])) == 64'b0)
          !== (legal == 1)) begin
        errors++;
        $display("LEGALITY MISMATCH: move %h, line %0d", mv, checked);
      end
    end
    $fclose(fd);
    $display("apply and legality checked on %0d moves, errors = %0d", checked, errors);

    if (errors == 0) $display("TB_FUNCTIONS PASS");
    else             $display("TB_FUNCTIONS FAIL");
    $finish;
  end
endmodule
Command Prompt
scripts\run_sim.bat tb_functions
Expected output
attacks checked on 295 positions, errors = 0
apply and legality checked on 7490 moves, errors = 0
TB_FUNCTIONS PASS
If you seeLook at
cannot open vec_positions.txtStep 18 not run, or the files are not in vectors\
ATTACK MISMATCHa shift amount or mask in one direction: compare with the table in Step 3
APPLY MISMATCHen passant and the castling rook first, the unusual paths
LEGALITY MISMATCHsafe_squares, or the attacker's color

28Block RAM, and the evaluator

Goal: a RAM that Vivado maps onto block RAM, and the C evaluate as a four-stage pipeline.

Concept: block RAM

Vivado recognises a RAM from the way you describe it. This shape (write on the clock edge, and read on the clock edge too) is the one it maps onto the chip's block RAMs. A RAM read without a clock can't use block RAM, and would be built out of thousands of flip-flops instead. The ram_style attribute makes the request explicit.

Create rtl/sdp_ram.sv
// sdp_ram.sv - simple dual-port block RAM with one clock of read latency.
`timescale 1ns / 1ps
module sdp_ram #(
    parameter int WIDTH = 8,
    parameter int DEPTH = 16
) (
    input  logic                     clk,
    input  logic                     we,
    input  logic [$clog2(DEPTH)-1:0] waddr,
    input  logic [WIDTH-1:0]         wdata,
    input  logic [$clog2(DEPTH)-1:0] raddr,
    output logic [WIDTH-1:0]         rdata
);
  (* ram_style = "block" *) logic [WIDTH-1:0] mem [0:DEPTH-1];

  always_ff @(posedge clk) begin
    if (we) mem[waddr] <= wdata;
    rdata <= mem[raddr];
  end
endmodule

Line by line

  1. WIDTH and DEPTH are parameters, so the same file makes both RAMs: 15 bits × 8,192 for the moves, 851 bits × 32 for the stack. $clog2(DEPTH) computes the number of address bits.
  2. (* ram_style = "block" *) asks Vivado to use block RAM rather than flip-flops or LUTs.
  3. The write and the read happen in the same always_ff: the RAM has a separate write port and read port ("simple dual port"), so the move generator can write while the search reads.
  4. rdata <= mem[raddr] is registered, so data appears one clock after the address. That is exactly how Xilinx block RAM behaves, which is why the tools can map it directly.
Concept: the evaluator

The C evaluate loops over pieces and adds up values. The hardware computes all 64 squares at once, then adds them with a tree of adders:

  1. Stage 1: for each of the 64 squares, the signed value of whatever stands there (0 if empty). Only one board can have a piece on a given square, so the twelve candidate constants can simply be ORed together: no priority logic.
  2. Stage 2: add the 8 squares of each rank.
  3. Stage 3: add the 8 rank sums.
  4. Stage 4: add or subtract the tempo bonus, and flip the sign if Black is to move.

Each stage ends in a register, so each clock cycle only has to cover one stage's worth of logic. A new position could enter every clock, with four in flight at once:

A pipeline. Press "Clock edge" a few times. P1's score comes out four clocks after it went in, but a new position could enter on every clock. The search only sends one position at a time; the point of the stages is the short logic paths.

Why add in a tree? Eight numbers added one after another form a chain seven adders long. Added in pairs, then pairs of pairs, the chain is only three adders deep: ((a+b)+(c+d))+((e+f)+(g+h)). Synthesis tools don't rebalance a chain for you, so sum8 writes the tree out explicitly.

The worst-case total fits easily in 16 signed bits: even nine queens a side stay around ±11,000.

Code

The module's ports, and the one wire that depends on the game phase: endgame is high when neither side has a queen.

Create rtl/eval_pipe.svpart 1 of 3
// eval_pipe.sv - four-stage parallel evaluator: 64 lookups, 8 rank sums, one total,
// then tempo and sign. A new position can enter every clock.
`timescale 1ns / 1ps
module eval_pipe
  import chess_pkg::*;
(
    input  logic               clk,
    input  logic               rst,
    input  logic               start,
    input  position_t          pos,
    output logic               valid,
    output logic signed [15:0] score
);
  logic endgame;
  assign endgame = (pos.bb[QUEEN] | pos.bb[6 + QUEEN]) == 64'b0;

Stage 1. square_score runs once per square inside a loop with constant bounds, so synthesis builds 64 copies side by side.

Add to rtl/eval_pipe.svpart 2 of 3
  // The value of whatever stands on one square. Only one bitboard can have this
  // bit set, so OR-ing the constants needs no priority logic at all.
  function automatic logic [11:0] square_score(input position_t p, input int sq,
                                               input logic is_endgame);
    logic [11:0] v = 12'd0;
    for (int pc = 0; pc < 12; pc++) begin
      if (p.bb[pc][sq]) begin
        if (pc % 6 == KING && is_endgame) v |= 12'(piece_on_square(pc, sq, 6));
        else                              v |= 12'(piece_on_square(pc, sq, pc % 6));
      end
    end
    return v;
  endfunction

  // Stage 1: one lookup per square.
  logic [63:0][11:0] square_value;
  logic              side_1;
  always_ff @(posedge clk) begin
    side_1 <= pos.side;
    for (int sq = 0; sq < 64; sq++)
      square_value[sq] <= square_score(pos, sq, endgame);
  end

Line by line

  1. square_score looks at one square and returns the value of whatever stands on it: material plus the piece-square bonus, already signed so Black's pieces count negative. Twelve bitboards are tested, but at most one has the bit set, so the twelve constants can simply be ORed together. An empty square gives 0.
  2. In the endgame (no queens), the king uses its endgame table, index 6 in piece_on_square.
  3. The for loop over 64 squares is unrolled: 64 copies of the lookup work side by side, and their results are stored in 64 registers at the clock edge. side_1 carries the side to move along so it arrives at stage 4 together with the sum.

Stages 2 to 4, and the valid signal. A copy of side travels down the pipeline with the data (side_1, side_2, side_3) so the sign flip in stage 4 uses the side of the position actually in stage 4.

Add to rtl/eval_pipe.svpart 3 of 3
  // A balanced adder tree: three adders deep instead of a chain of seven.
  function automatic logic [15:0] sum8(input logic [7:0][15:0] x);
    return ((x[0] + x[1]) + (x[2] + x[3])) + ((x[4] + x[5]) + (x[6] + x[7]));
  endfunction

  // Sign-extend the eight values of one rank from 12 to 16 bits.
  function automatic logic [7:0][15:0] rank_values(input logic [63:0][11:0] v, input int r);
    logic [7:0][15:0] out;
    for (int f = 0; f < 8; f++)
      out[f] = {{4{v[r*8 + f][11]}}, v[r*8 + f]};
    return out;
  endfunction

  // Stage 2: one sum per rank.
  logic [7:0][15:0] rank_sum;
  logic             side_2;
  always_ff @(posedge clk) begin
    side_2 <= side_1;
    for (int r = 0; r < 8; r++)
      rank_sum[r] <= sum8(rank_values(square_value, r));
  end

  // Stage 3: the sum of the ranks.
  logic [15:0] total;
  logic        side_3;
  always_ff @(posedge clk) begin
    side_3 <= side_2;
    total <= sum8(rank_sum);
  end

  // Stage 4: tempo bonus, then the point of view of the side to move.
  logic [2:0] valid_shift;
  always_ff @(posedge clk) begin
    score <= (side_3 == WHITE) ? $signed(total + 16'(TEMPO))
                               : -$signed(total - 16'(TEMPO));
    valid_shift <= {valid_shift[1:0], start};
    valid <= valid_shift[2];
    if (rst) begin
      valid_shift <= 3'b000;
      valid <= 1'b0;
    end
  end
endmodule

Line by line

  1. sum8 adds eight numbers as a tree: four additions in parallel, then two, then one. Three adders deep instead of seven in a row, so it fits easily in a clock.
  2. rank_values widens the eight 12-bit values of one rank to 16 bits, copying the sign bit ({4{v[11]}}), so negative values stay negative.
  3. Stage 2 sums each rank: eight sums at once. Stage 3 sums the eight rank sums.
  4. Stage 4 adds the tempo bonus for the side to move and negates the result when Black is to move, exactly like the last line of evaluate in C.
  5. valid_shift is a three-bit shift register: the start pulse enters at one end and comes out of valid on the same clock as the score for that position. The search never needs to know how many stages there are.
Check

This testbench drives the inputs on the falling clock edge. That is a good habit: every input is then stable long before the rising edge where the design samples it, so the testbench and the design can never race.

Create tb/tb_eval.sv
// tb_eval.sv - evaluator scores must equal the C evaluate() exactly.
`timescale 1ns / 1ps
module tb_eval;
  import chess_pkg::*;

  logic clk = 1'b0;
  logic rst = 1'b1;
  logic start = 1'b0;
  position_t pos, next_pos;
  logic valid;
  logic signed [15:0] score;
  always #5 clk = ~clk;

  eval_pipe dut (.clk, .rst, .start, .pos, .valid, .score);

  initial begin
    int fd, errors, checked, r, side, castle, ep, expected, check_flag, latency;
    logic [63:0] b, att_w, att_b;
    errors = 0;
    checked = 0;
    repeat (3) @(negedge clk);
    rst = 1'b0;
    fd = $fopen("vec_positions.txt", "r");
    if (fd == 0) $fatal(1, "cannot open vec_positions.txt");
    while (!$feof(fd)) begin
      for (int i = 0; i < 12; i++) begin
        r = $fscanf(fd, "%h", b);
        next_pos.bb[i] = b;
      end
      r = $fscanf(fd, "%d %d %d %h %h %d %d\n",
                  side, castle, ep, att_w, att_b, expected, check_flag);
      if (r != 7) break;
      next_pos.side = side[0];
      next_pos.castle = castle[3:0];
      next_pos.ep = ep[6:0];
      // Inputs change on the falling edge, so they are stable at the rising edge.
      @(negedge clk);
      pos = next_pos;
      start = 1'b1;
      @(negedge clk);
      start = 1'b0;
      latency = 1;
      while (valid !== 1'b1) begin
        @(negedge clk);
        latency++;
        if (latency > 20) $fatal(1, "evaluator never answered");
      end
      if (checked == 0) $display("evaluator latency = %0d clocks", latency);
      checked++;
      if (int'(score) != expected) begin 
        errors++;
        $display("EVAL MISMATCH: position %0d got %0d expected %0d", checked, score, expected);
      end
    end
    $display("evaluation checked on %0d positions, errors = %0d", checked, errors);
    if (errors == 0) $display("TB_EVAL PASS");
    else             $display("TB_EVAL FAIL");
    $finish;
  end
endmodule
Command Prompt
scripts\run_sim.bat tb_eval
Expected output
evaluator latency = 4 clocks
evaluation checked on 295 positions, errors = 0
TB_EVAL PASS
If the scores areLook at
wrong only with Black to movethe sign or tempo in stage 4
wrong only when the queens are gonethe endgame wire, or the seventh table
off by twice a table valuesq ^ 56 used for the wrong color

29The move generator

Goal: write exactly the list the C writes, in exactly the same order, into the move RAM, one move per clock.

Concept: loops become registers

The C generator is four nested loops (Step 8). The hardware keeps each loop's position in a register, and each clock does one step of the innermost loop that still has work:

C loopRegister
for (stage ...)stage
for (type ...)ptype
while (pieces)pieces: the pieces of this type not yet visited
while (targets)targets: this piece's destinations not yet written
for (promo ...)promo, counting 4 down to 1

The state machine has seven states:

StateWhat it does in one clock
G_IDLEwait for start, clear count
G_OCCstore the occupied squares in a register
G_STAGEstore movers: my pieces that can do anything in this stage
G_DECIDEno movers? skip the whole stage (or finish). Otherwise load the pawns
G_PIECEtake the lowest remaining piece, or move on to the next type, or the next stage
G_TARGETScompute that piece's destinations for this stage
G_EMITwrite one move into the RAM, or go back for the next piece
Concept: the backward trick

Most capture stages find nothing: usually no piece can capture the queen. Visiting all 16 pieces just to learn that costs dozens of clocks per stage. So G_STAGE asks the question backwards:

If a knight stood on the victim's square, which squares would it attack? My knights on those squares are exactly the knights that can capture the victim.

Knight attacks are symmetric, and so are bishop, rook, queen and king attacks. Pawns need the opposite color's direction. So one clock of attack logic, run backwards from all the victims at once, gives the set of pieces worth visiting. If it is empty, the whole stage costs two clocks. This is the "super-piece" idea from the Brutus FPGA chess machine (Donninger, Kure and Lorenz, 2004), done with bitboards.

Shining attacks backwards. Blue squares are reached by some backward attack from a victim; the amber pieces sit where a matching piece type can strike back. Only those are visited. In the queen stage, only two of White's 14 pieces, the knight on c3 and the bishop on c4, can take the queen. The pawn stage finds no movers at all, so it costs just two clocks.

On the test set this trick took the generator from 85 to 55 clocks per list. It cannot change the order, because it only skips pieces that have no moves in that stage anyway.

Code

The ports and registers. The write port goes straight to the move RAM. The list for ply p starts at address p × 256, which is just {ply, count}: putting the bits side by side, so no adder is needed.

Create rtl/move_gen.svpart 1 of 5
// move_gen.sv - writes pseudo-legal moves into the move RAM, in exactly the order
// of generate_moves() in the C engine.
`timescale 1ns / 1ps
module move_gen
  import chess_pkg::*;
(
    input  logic        clk,
    input  logic        rst,
    input  logic        start,          // one-clock pulse; pos must stay stable
    input  position_t   pos,
    input  logic        captures_only,
    input  logic [4:0]  ply,            // selects this node's list in the RAM
    output logic        done,           // one-clock pulse; count is then valid
    output logic [7:0]  count,
    output logic        overflow,       // more than 255 moves (should never happen)
    output logic        we,
    output logic [12:0] waddr,
    output move_t       wdata
);
  typedef enum logic [2:0] {
    G_IDLE, G_OCC, G_STAGE, G_DECIDE, G_PIECE, G_TARGETS, G_EMIT
  } gen_state_t;

  gen_state_t state;
  logic [2:0] stage;
  logic [2:0] ptype;
  bb_t        occ;          // all occupied squares (pos is stable during a list)
  bb_t        movers;       // my pieces worth visiting in this stage
  bb_t        pieces;       // pieces of this type not yet visited in this stage
  bb_t        piece_r;      // the current piece, as a one-hot bitboard
  bb_t        targets;      // destinations of the current piece not yet written
  logic [5:0] from;
  logic [2:0] promo;

  logic [3:0] mine_base;
  logic [3:0] theirs_base;
  assign mine_base   = pos.side ? 4'd6 : 4'd0;
  assign theirs_base = pos.side ? 4'd0 : 4'd6;

The backward trick, as combinational logic. pawn_attacks(~pos.side, victims) uses the enemy pawn direction, because we are looking backwards from the victim.

Add to rtl/move_gen.svpart 2 of 5
  // ---- which of my pieces can do anything in this stage? ----------------------
  // A capture stage asks the question backwards: pretend the victims are pieces of
  // every type and see which of my pieces they "attack". Those pieces, and only
  // those, can capture a victim. (Brutus calls this idea a "super-piece".)
  bb_t victims, stage_movers, ep_bit, relative_rank7;
  always_comb begin
    ep_bit = 64'b0;
    if (!pos.ep[6]) ep_bit[pos.ep[5:0]] = 1'b1;
    relative_rank7 = pos.side ? 64'h000000000000FF00 : 64'h00FF000000000000;

    case (stage)
      ST_CAP_Q: victims = pos.bb[theirs_base + QUEEN];
      ST_CAP_R: victims = pos.bb[theirs_base + ROOK];
      ST_CAP_B: victims = pos.bb[theirs_base + BISHOP];
      ST_CAP_N: victims = pos.bb[theirs_base + KNIGHT];
      default:  victims = pos.bb[theirs_base + PAWN] | ep_bit;
    endcase

    if (stage == ST_QUIET)
      stage_movers = ALL;
    else if (stage == ST_PROMO)
      stage_movers = pos.bb[mine_base + PAWN] & relative_rank7;
    else
      stage_movers =
          (pawn_attacks(~pos.side, victims) & pos.bb[mine_base + PAWN])
        | (knight_attacks(victims)          & pos.bb[mine_base + KNIGHT])
        | (king_attacks(victims)            & pos.bb[mine_base + KING])
        | (bishop_attacks(victims, occ)
           & (pos.bb[mine_base + BISHOP] | pos.bb[mine_base + QUEEN]))
        | (rook_attacks(victims, occ)
           & (pos.bb[mine_base + ROOK] | pos.bb[mine_base + QUEEN]));
  end

Line by line

  1. ep_bit is the en-passant square as a bitboard, or 0 (bit 6 of ep is set only for the value 64, "none"). relative_rank7 is the rank a pawn promotes from: rank 7 for White, rank 2 for Black.
  2. The case picks the victims of this capture stage. The pawn stage includes the en-passant square, as in C.
  3. Quiet stage: every piece may have moves, so stage_movers is everything. Promotion stage: only my pawns on the seventh rank.
  4. Capture stages: each line pretends the victims are pieces of one type and attacks backwards. A knight-shaped attack from the victims that lands on one of my knights finds a knight that can capture. Bishops and queens share the diagonal test, rooks and queens the straight one. Pawns use the opponent's direction (~pos.side), because a pawn attacking forward is attacked from behind.
  5. This is all combinational: it is one clock of logic, stored into movers in G_STAGE.

The write port. Everything on it comes straight from registers, so the RAM's inputs are clean and early in the clock cycle.

Add to rtl/move_gen.svpart 3 of 5
  logic [2:0] last_stage;
  assign last_stage = captures_only ? ST_CAP_P : ST_QUIET;

  bb_t piece_bit, target_bit;
  assign piece_bit  = lowest_bit(pieces);
  assign target_bit = lowest_bit(targets);

  logic [5:0] to;
  logic       is_promo;
  assign to       = square_of(target_bit);
  assign is_promo = (ptype == 3'd0) && ((target_bit & LAST_RANKS) != 64'b0);

  // The write port is pure wiring from registers.
  assign we    = (state == G_EMIT) && (targets != 64'b0);
  assign waddr = {ply, count};
  assign wdata = {is_promo ? promo : 3'd0, to, from};

Line by line

  1. last_stage is the pawn-capture stage in quiescence, and the quiet stage otherwise.
  2. piece_bit and target_bit isolate the lowest set bit of pieces and targets; to converts the target to a square number.
  3. is_promo: a pawn landing on rank 1 or 8.
  4. The three assigns are the RAM's write port. waddr = {ply, count} places move number count of this ply's list; wdata builds the move word, with the promotion code only for promotions. All three come straight from registers, so the RAM sees clean, early signals.

And the state machine. Promotions stay on the same destination while promo counts down from queen to knight; only then is the destination removed from targets.

Add to rtl/move_gen.svpart 4 of 5
  always_ff @(posedge clk) begin
    done <= 1'b0;
    if (rst) begin
      state <= G_IDLE;
      count <= 8'd0;
      overflow <= 1'b0;
    end else begin
      case (state)
        G_IDLE: if (start) begin
          count <= 8'd0;
          overflow <= 1'b0;
          state <= G_OCC;
        end

        G_OCC: begin
          occ <= occupied(pos);
          stage <= ST_PROMO;
          state <= G_STAGE;
        end

        G_STAGE: begin                       // movers latches at this edge
          movers <= stage_movers;
          state <= G_DECIDE;
        end

        G_DECIDE: begin
          if (movers != 64'b0) begin
            ptype <= 3'd0;
            pieces <= pos.bb[mine_base + PAWN] & movers;
            state <= G_PIECE;
          end else if (stage == last_stage) begin
            done <= 1'b1;
            state <= G_IDLE;
          end else begin
            stage <= stage + 3'd1;
            state <= G_STAGE;
          end
        end

Line by line: starting a list

  1. done <= 1'b0 at the top makes done a one-clock pulse: any state that sets it overrides this default for one clock only.
  2. G_IDLE: on start, reset the move counter and the overflow flag.
  3. G_OCC: store all occupied squares once, and begin at the first stage, promotions.
  4. G_STAGE: store movers, the combinational "who can do anything in this stage" from the backward trick. Storing it breaks a long path: the attack logic gets this whole clock.
  5. G_DECIDE: if nobody can move, skip the stage, or finish if it was the last one. Otherwise start the piece loop at pawns, keeping only the pawns that are movers.

Then the piece loop and the emitting of moves:

Add to rtl/move_gen.svpart 5 of 5
        G_PIECE: begin
          if (pieces != 64'b0) begin
            piece_r <= piece_bit;
            from <= square_of(piece_bit);
            pieces <= pieces & ~piece_bit;
            state <= G_TARGETS;
          end else if (ptype != 3'd5) begin
            ptype <= ptype + 3'd1;
            pieces <= pos.bb[mine_base + 4'(ptype) + 4'd1] & movers;
          end else if (stage == last_stage) begin
            done <= 1'b1;
            state <= G_IDLE;
          end else begin
            stage <= stage + 3'd1;
            state <= G_STAGE;
          end
        end

        G_TARGETS: begin
          targets <= stage_targets(pos, occ, stage, ptype, piece_r);
          promo <= 3'd4;                     // queen first
          state <= G_EMIT;
        end

        G_EMIT: begin
          if (targets == 64'b0) begin        // this piece has nothing (more) to do
            state <= G_PIECE;
          end else begin
            if (count == 8'hFF) overflow <= 1'b1;
            count <= count + 8'd1;
            if (is_promo && promo != 3'd1) begin
              promo <= promo - 3'd1;         // same destination, next piece
            end else begin
              promo <= 3'd4;
              targets <= targets & ~target_bit;
            end
          end
        end

        default: state <= G_IDLE;
      endcase
    end
  end
endmodule

Line by line: pieces and moves

  1. G_PIECE is the C while (pieces) and for (type ...) together. If pieces of this type remain, take the lowest (piece_bit), remember it, and remove it from pieces. Otherwise load the next type's movers. After the king, go to the next stage, or finish.
  2. G_TARGETS computes this piece's destinations for this stage: the same function as C's stage_targets. promo starts at 4, the queen.
  3. G_EMIT writes one move per clock. The write itself happens through we, which is high in this state whenever targets is not empty. The state only does the bookkeeping: count the move, then either count promo down (a promotion is written four times, queen to knight, on the same square) or remove the destination from targets.
  4. When targets is empty, back to G_PIECE for the next piece.

Follow it once

Here is what happens, clock by clock, for the position in the trace below: white pawn on e4 and king on e1, against a black queen on d5.

  1. G_IDLE → G_OCC. start arrives; count is cleared, so the first move goes to address {ply, 0}.
  2. G_OCC. The occupied squares are stored once in occ. Every later state reads the register rather than recomputing the OR of twelve boards.
  3. G_STAGE, G_DECIDE (promotions). No pawn is on the seventh rank, so movers is empty and the whole stage is skipped in two clocks.
  4. G_STAGE, G_DECIDE (captures of the queen). The backward pawn attack from d5 hits e4, so movers holds the e4 pawn. pieces is loaded with the pawns among the movers.
  5. G_PIECE. piece_bit picks e4; from becomes 28, and e4 is removed from pieces.
  6. G_TARGETS. stage_targets computes e4's destinations for this stage: just d5.
  7. G_EMIT. we is high because targets is not empty, so the RAM stores e4d5 at this edge, and d5 leaves targets. On the next clock targets is empty, so it goes back to G_PIECE, finds no more pawns, steps through the other piece types and moves to the next stage.
  8. The rook, bishop, knight and pawn capture stages are skipped in two clocks each. The quiet stage visits the pawn (e5) and the king (d1, f1, d2, e2, f2, lowest square first) the same way, and done pulses with count = 7.

Notice that no state does more than one "thing": a choice, a store, or one RAM write. That is why the generator runs at 50 MHz with room to spare, even though stage_targets is a large block of logic: it has a whole clock to itself in G_TARGETS.

A real trace. This replays the simulated hardware, clock by clock, generating moves for white pawn e4 and king e1 against black queen d5 and king e8. The capture e4xd5 is written first, even though the king's moves come from a lower square: the queen-capture stage comes before the quiet stage.
Check

The testbench copies every move the generator writes, then compares the whole list, in order, with the C's list. It also measures clocks per list.

Create tb/tb_move_gen.sv
// tb_move_gen.sv - the RTL must write the same moves in the same order as C.
`timescale 1ns / 1ps
module tb_move_gen;
  import chess_pkg::*;

  logic clk = 1'b0;
  logic rst = 1'b1;
  logic start = 1'b0;
  logic captures_only = 1'b0;
  position_t pos, next_pos;
  logic done, overflow, we;
  logic [7:0] count;
  logic [12:0] waddr;
  move_t wdata;
  always #5 clk = ~clk;

  move_gen dut (.clk, .rst, .start, .pos, .captures_only, .ply(5'd3),
                .done, .count, .overflow, .we, .waddr, .wdata);

  // Copies of every move the DUT writes.
  move_t  written [0:255];
  longint total_cycles = 0, total_lists = 0;
  always @(posedge clk) begin
    if (we) begin
      if (waddr[12:8] !== 5'd3) $fatal(1, "wrong ply in write address");
      written[waddr[7:0]] = wdata;
    end
  end

  initial begin
    int fd, errors, r, side, castle, ep, mode, n, wait_cycles;
    logic [63:0] b;
    logic [15:0] expected [0:255];
    errors = 0;
    repeat (3) @(negedge clk);
    rst = 1'b0;
    fd = $fopen("vec_moves.txt", "r");
    if (fd == 0) $fatal(1, "cannot open vec_moves.txt");
    while (!$feof(fd)) begin
      for (int i = 0; i < 12; i++) begin
        r = $fscanf(fd, "%h", b);
        next_pos.bb[i] = b;
      end
      r = $fscanf(fd, "%d %d %d %d %d", side, castle, ep, mode, n);
      if (r != 5) break;
      for (int i = 0; i < n; i++) r = $fscanf(fd, "%h", expected[i]);
      next_pos.side = side[0];
      next_pos.castle = castle[3:0];
      next_pos.ep = ep[6:0];
      @(negedge clk);
      pos = next_pos;
      captures_only = (mode == 1);
      start = 1'b1;
      @(negedge clk);
      start = 1'b0;
      wait_cycles = 0;
      while (done !== 1'b1) begin
        @(negedge clk);
        wait_cycles++;
        if (wait_cycles > 5000) $fatal(1, "move_gen hung");
      end
      total_cycles += wait_cycles;
      total_lists++;
      if (int'(count) != n || overflow) begin
        errors++;
        $display("COUNT MISMATCH: list %0d got %0d expected %0d", total_lists, count, n);
      end else begin
        for (int i = 0; i < n; i++)
          if ({1'b0, written[i]} !== expected[i]) begin
            errors++;
            $display("MOVE MISMATCH: list %0d index %0d got %h expected %h",
                     total_lists, i, written[i], expected[i]);
          end
      end
    end
    $display("checked %0d lists, average %0d clocks per list, errors = %0d",
             total_lists, total_cycles / total_lists, errors);
    if (errors == 0) $display("TB_MOVE_GEN PASS");
    else             $display("TB_MOVE_GEN FAIL");
    $finish;
  end
endmodule
Command Prompt
scripts\run_sim.bat tb_move_gen
Expected output
checked 590 lists, average 53 clocks per list, errors = 0
TB_MOVE_GEN PASS
If you seeLook at
COUNT MISMATCH by a few movesa special rule in stage_targets: castling squares, double pushes, en passant
right count, MOVE MISMATCHan order problem: promotion order or stage order
move_gen hunga state that never leaves: open the waveform on state
missing moves when few pieces are leftmovers for one type: check the pawn color

30The search core: frame, stack and services

Goal: set up everything the alpha-beta state machine needs: its registers, the two RAMs, the generator, the evaluator, and one attack tester.

Concept

Step 21 showed the plan: the current node in registers, the ancestors in the stack RAM. The frame holds every variable from the C negamax that must survive a recursive call:

In CFrame fieldBits
alpha, beta, bestalpha, beta, best16 each
depthdepth5
loop index iindex8
ncount8
any_legalany_legal1
checkin_check1

The position (780 bits) plus this frame (71 bits) is one stack row: 851 bits, pushed or popped through one RAM port in one clock. The root's best move is not in the frame, since only the root needs it; one register, root_move, remembers which root move is being searched.

One more saving: the design has one attack tester, a full side_attacks circuit, which is large. Its input is always the child register, and it answers two different questions:

  • in S_TEST: did the move just made leave the mover's king (or castling path) attacked?
  • in S_ENTER: is the side to move in check? At that moment child holds the same position as pos, because entering a child copies it into pos and child already held it.
Code

The ports. The search is started with a pulse on start, and reports with a pulse on done. perft_mode turns the same machine into a perft counter, which tests almost every part of the core.

Create rtl/search_core.svpart 1 of 8
// search_core.sv - the alpha-beta recursion written as a state machine.
// "pos" and "f" hold the current node; the stack RAM holds all its ancestors.
`timescale 1ns / 1ps
module search_core
  import chess_pkg::*;
(
    input  logic               clk,
    input  logic               rst,
    input  logic               start,       // one-clock pulse while busy = 0
    input  logic               abort,       // takes effect at the next node
    input  position_t          root,
    input  logic [4:0]         depth,
    input  logic               perft_mode,  // count leaves instead of searching
    input  logic [31:0]        node_limit,  // 0 = no limit
    output logic               busy,
    output logic               done,        // one-clock pulse at the end
    output logic               aborted,
    output logic               fault,
    output move_t              best_move,   // 0 = no legal move
    output logic signed [15:0] best_score,
    output logic [47:0]        nodes,       // perft mode: leaves
    output logic [47:0]        cycles
);
  localparam logic signed [15:0] SCORE_INF  = 16'sd32000;
  localparam logic signed [15:0] SCORE_MATE = 16'sd30000;

The frame, the stack row, the sixteen states, and the registers. ret carries a score from a finished node back up to its parent: the hardware version of a function's return value.

Add to rtl/search_core.svpart 2 of 8
  // Everything the C function keeps in local variables across its recursive
  // call. The position itself is the local variable "p".
  typedef struct packed {
    logic signed [15:0] alpha;
    logic signed [15:0] beta;
    logic signed [15:0] best;
    logic [4:0]         depth;
    logic [7:0]         index;       // next move to try
    logic [7:0]         count;       // moves in this node's list
    logic               any_legal;
    logic               in_check;
  } frame_t;

  typedef struct packed {
    position_t pos;
    frame_t    f;
  } node_t;

  typedef enum logic [3:0] {
    S_IDLE, S_ENTER, S_CLASSIFY, S_EVAL_WAIT, S_GEN_START, S_GEN_WAIT,
    S_NEXT, S_READ, S_DECODE, S_APPLY, S_TEST, S_LEGAL, S_END_NODE, S_RETURN, S_POP, S_SCORE
  } state_t;

  state_t    state;
  logic [4:0] ply;
  position_t pos, child;
  frame_t    f;
  move_t     move_r, root_move;
  decoded_move_t decoded;
  logic signed [15:0] ret;           // score returned by the node that just finished
  logic      abort_pending, limit_on;
  logic      attacked;       // result of the attack test, one clock later

Line by line

  1. frame_t holds every local variable of the C negamax that must survive the recursive call: the window (alpha, beta), best, the remaining depth, the loop index, the list length, and two flags. Scores are 16-bit signed: ±32,000 fits.
  2. node_t is a frame plus its position: one row of the stack RAM, 780 + 71 = 851 bits.
  3. The state names follow the table above. Sixteen states fit in 4 bits.
  4. pos and f are the current node. child is the position after the move being tried. ret carries a finished node's score up to its parent, like a C return value.

The services: the move generator and its RAM, the stack RAM, and the evaluator. Look at the stack RAM's ports: it writes {pos, f} at row ply on a legal move, and always reads row ply − 1, the parent.

Add to rtl/search_core.svpart 3 of 8
  // ---- services ------------------------------------------------------------
  logic  gen_start, gen_done, gen_overflow, gen_we;
  logic  [7:0]  gen_count;
  logic  [12:0] gen_waddr;
  move_t gen_wdata;
  logic  stand_pat;
  assign stand_pat = (f.depth == 5'd0) && !f.in_check && !perft_mode;

  move_gen u_move_gen (
    .clk, .rst, .start(gen_start), .pos, .captures_only(stand_pat), .ply,
    .done(gen_done), .count(gen_count), .overflow(gen_overflow),
    .we(gen_we), .waddr(gen_waddr), .wdata(gen_wdata)
  );

  move_t move_rdata;
  sdp_ram #(.WIDTH($bits(move_t)), .DEPTH(8192)) u_move_ram (
    .clk, .we(gen_we), .waddr(gen_waddr), .wdata(gen_wdata),
    .raddr({ply, f.index}), .rdata(move_rdata)
  );

  logic  stack_we;
  logic  [4:0] stack_raddr;
  node_t stack_rdata;
  sdp_ram #(.WIDTH($bits(node_t)), .DEPTH(MAX_PLY)) u_stack_ram (
    .clk, .we(stack_we), .waddr(ply), .wdata({pos, f}),
    .raddr(stack_raddr), .rdata(stack_rdata)
  );
  assign stack_we    = (state == S_LEGAL) && !attacked;
  assign stack_raddr = ply - 5'd1;

  logic eval_start, eval_valid;
  logic signed [15:0] eval_score;
  eval_pipe u_eval (
    .clk, .rst, .start(eval_start), .pos, .valid(eval_valid), .score(eval_score)
  );

Line by line

  1. stand_pat is the condition for "captures only": depth 0, not in check, and not in perft mode (perft must count every move).
  2. The move generator writes into the move RAM; the search reads it at {ply, f.index}, so each ply has its own 256-entry region.
  3. The stack RAM is written at row ply when a legal move is entered (stack_we is high in S_LEGAL for a legal move), and read at row ply - 1, the parent, which is what a return needs.
  4. The evaluator reads pos directly; the search only pulses eval_start and waits for eval_valid.

The one attack tester, and the arithmetic for updating a node after a child returns. These are wires, computed continuously; the state machine just uses them in the right state.

Add to rtl/search_core.svpart 4 of 8
  // ---- the one attack test: uses "child", which also equals pos in S_ENTER -----
  logic attacker_side;
  bb_t  test_squares;
  always_comb begin
    if (state == S_TEST) begin           // did the mover leave its king attacked?
      attacker_side = child.side;
      test_squares  = safe_squares(child, move_r);
    end else begin                       // S_ENTER: is the side to move in check?
      attacker_side = ~child.side;
      test_squares  = child.bb[(child.side ? 6 : 0) + KING];
    end
  end
  always_ff @(posedge clk)
    attacked <= (side_attacks(child, attacker_side) & test_squares) != 64'b0;

  // ---- score arithmetic for S_SCORE ------------------------------------------
  logic signed [15:0] child_score, new_best, new_alpha;
  assign child_score = -ret;
  assign new_best    = (child_score > f.best)  ? child_score : f.best;
  assign new_alpha   = (child_score > f.alpha) ? child_score : f.alpha;

Line by line

  1. There is only one copy of the large attack logic (side_attacks), and it always looks at child. Two states share it by choosing what to test.
  2. In S_TEST the question is "after this move, is the mover's king attacked?": the attacker is the side now to move in child, and the squares are from safe_squares.
  3. In S_ENTER, child equals the new node's position (it was just copied into pos), so the same logic answers "is the side to move in check?".
  4. The answer is registered into attacked, so the long attack path has a whole clock. That is why S_TEST exists: one clock to compute, then S_LEGAL reads the result.
  5. child_score, new_best and new_alpha are the comparisons S_SCORE needs, computed as wires so S_SCORE can update everything in one clock.

31The search core: the state machine

Goal: the C negamax, one state per clock, matching the C exactly in nodes, score and best move.

Concept

Each state does one small piece of the C function:

StateThe C it matchesWhat it does
S_IDLEthe call from search()wait for start; load the root
S_ENTERnodes++count the node; the check test latches
S_CLASSIFYcheck, quiesce, the node limitstop on abort or limit; choose evaluate or generate
S_EVAL_WAITstand patwait for valid; return on a cutoff, otherwise raise alpha
S_GEN_START, S_GEN_WAITgenerate_movesstart the generator and wait for done
S_NEXTthe for testend of list? Otherwise the RAM is reading this move
S_READlist[i]store the move
S_DECODE, S_APPLYmake_movebuild child, in two clocks
S_TESTlegal_afterthe attack test latches
S_LEGALcontinue, or the recursive callillegal: next move. Legal: push, and enter the child
S_END_NODEthe mate and stalemate testreturn mate, stalemate, or best
S_RETURNreturnat ply 0, finish; otherwise the stack RAM is reading the parent
S_POPthe call returningrestore pos, f, ply
S_SCOREscore = -..., the updates, breakupdate best and alpha; cut off or go to the next move

Abort and the node limit are both checked in one place, S_CLASSIFY. The core can simply stop there, without unwinding the stack, because a stopped search's position and frames are thrown away. The CPU ignores the aborted result and keeps the answer from its last finished search.

Code

Entering a node: count it, classify it, evaluate if it is a leaf, and generate its moves.

Add to rtl/search_core.svpart 5 of 8
  // ---- the state machine -----------------------------------------------------
  always_ff @(posedge clk) begin
    done       <= 1'b0;
    gen_start  <= 1'b0;
    eval_start <= 1'b0;
    if (busy) cycles <= cycles + 48'd1;
    if (abort && busy) abort_pending <= 1'b1;

    if (rst) begin
      state <= S_IDLE;
      busy <= 1'b0;
      aborted <= 1'b0;
      fault <= 1'b0;
      abort_pending <= 1'b0;
      nodes <= 48'd0;
      cycles <= 48'd0;
      best_move <= '0;
      best_score <= '0;
    end else begin
      case (state)
        S_IDLE: if (start) begin
          pos <= root;
          child <= root;
          f <= '{alpha: -SCORE_INF, beta: SCORE_INF, best: -SCORE_INF,
                 depth: depth, index: 8'd0, count: 8'd0,
                 any_legal: 1'b0, in_check: 1'b0};
          ply <= 5'd0;
          nodes <= 48'd0;
          cycles <= 48'd0;
          best_move <= '0;
          best_score <= '0;
          aborted <= 1'b0;
          fault <= 1'b0;
          abort_pending <= 1'b0;
          limit_on <= (node_limit != 32'd0);
          busy <= 1'b1;
          state <= S_ENTER;
        end

Line by line: the defaults and S_IDLE

  1. The first lines run on every clock. done, gen_start and eval_start default to 0, so whenever a state sets one of them it becomes a one-clock pulse.
  2. cycles counts every clock while busy. An ABORT that arrives at any time is remembered in abort_pending and acted on at the next node.
  3. S_IDLE: on start, copy the root into both pos and child (the attack tester looks at child), set up the root frame with the full window (-INF, +INF), clear the counters, and remember whether a node limit is in force.

Every node then starts the same way:

Add to rtl/search_core.svpart 6 of 8
        // A node begins here. "attacked" latches the check test at this edge.
        S_ENTER: begin
          if (!perft_mode || f.depth == 5'd0) nodes <= nodes + 48'd1;
          state <= S_CLASSIFY;
        end

        S_CLASSIFY: begin
          f.in_check <= attacked;
          if (abort_pending || (limit_on && nodes == 48'(node_limit))) begin
            aborted <= 1'b1;           // stop at once: the CPU ignores this result
            busy <= 1'b0;
            done <= 1'b1;
            state <= S_IDLE;
          end else if (perft_mode) begin
            ret <= 16'sd0;
            state <= (f.depth == 5'd0) ? S_RETURN : S_GEN_START;
          end else if (ply == 5'(MAX_PLY - 1) || (f.depth == 5'd0 && !attacked)) begin
            eval_start <= 1'b1;
            state <= S_EVAL_WAIT;
          end else begin
            state <= S_GEN_START;
          end
        end

        S_EVAL_WAIT: if (eval_valid) begin
          if (ply == 5'(MAX_PLY - 1) || eval_score >= f.beta) begin
            ret <= eval_score;
            state <= S_RETURN;
          end else begin
            f.best <= eval_score;
            if (eval_score > f.alpha) f.alpha <= eval_score;
            state <= S_GEN_START;
          end
        end

        S_GEN_START: begin
          gen_start <= 1'b1;
          state <= S_GEN_WAIT;
        end

        S_GEN_WAIT: if (gen_done) begin
          if (gen_overflow) fault <= 1'b1;
          f.count <= gen_count;
          f.index <= 8'd0;
          state <= S_NEXT;
        end

Line by line: entering a node

  1. S_ENTER counts the node (in perft mode, only leaves are counted). During this clock the attack tester is already checking whether the side to move is in check, because child holds this node's position.
  2. S_CLASSIFY stores that answer in f.in_check and makes the big decision. Abort or node limit: stop at once and report ABORTED. Perft: count the leaf or generate. Search: at depth 0 and not in check, or at the deepest ply, this is a stand-pat node, so start the evaluator; otherwise generate moves.
  3. S_EVAL_WAIT waits for eval_valid. At the deepest ply, return the static score whatever it is. If it is already at least beta, return it too: the opponent will avoid this position anyway. Otherwise it becomes best, may raise alpha, and the node goes on to try its captures.
  4. S_GEN_START / S_GEN_WAIT: pulse the generator and wait for done. Then this node's list sits in the move RAM at {ply, 0} onward; store its length in f.count and start at index 0.

Trying moves: read, decode, apply, test, and either skip an illegal move or push and enter the child. Notice the new frame's window in S_LEGAL: alpha: -f.beta, beta: -f.alpha, exactly the C call's -beta, -alpha.

Add to rtl/search_core.svpart 7 of 8
        // The RAM address {ply, f.index} is sampled at this clock edge.
        S_NEXT: begin
          if (f.index == f.count) state <= S_END_NODE;
          else                    state <= S_READ;
        end

        S_READ: begin
          move_r <= move_rdata;
          if (ply == 5'd0) root_move <= move_rdata;
          state <= S_DECODE;
        end

        S_DECODE: begin
          decoded <= decode_move(pos, move_r);
          state <= S_APPLY;
        end

        S_APPLY: begin
          child <= apply_decoded(pos, decoded);
          state <= S_TEST;
        end

        S_TEST: state <= S_LEGAL;      // "attacked" latches at this edge

        S_LEGAL: begin
          if (attacked) begin          // illegal move: try the next one
            f.index <= f.index + 8'd1;
            state <= S_NEXT;
          end else begin               // legal: stack_we pushes {pos, f} at this edge
            pos <= child;
            f <= '{alpha: -f.beta, beta: -f.alpha, best: -SCORE_INF,
                   depth: (f.depth == 5'd0) ? 5'd0 : f.depth - 5'd1,
                   index: 8'd0, count: 8'd0, any_legal: 1'b0, in_check: 1'b0};
            ply <= ply + 5'd1;
            state <= S_ENTER;
          end
        end

Line by line: trying one move

  1. S_NEXT is the for test. If every move has been tried, finish the node. Otherwise the RAM is reading address {ply, f.index} during this clock.
  2. S_READ stores the move. At the root it is also saved in root_move, because if this move turns out best, that is what the CPU will receive.
  3. S_DECODE and S_APPLY are the two clocks of make_move from Step 26, producing child.
  4. S_TEST waits one clock while the attack tester checks child: is the mover's king (or a castling square) attacked?
  5. S_LEGAL: if attacked, the move is illegal, so skip it. If legal, this is the recursive call: stack_we writes {pos, f} into row ply of the stack RAM at this very edge, while pos becomes child, the frame is set up for the child with the window negated and swapped, and ply goes up by one.

Returning: finish the node, pop the parent, and update it with the child's score. child_score = -ret is the negamax minus sign.

Add to rtl/search_core.svpart 8 of 8
        S_END_NODE: begin
          if (!f.any_legal && !stand_pat)
            ret <= f.in_check ? (-SCORE_MATE + 16'(ply)) : 16'sd0;
          else
            ret <= f.best;
          state <= S_RETURN;
        end

        S_RETURN: begin
          if (ply == 5'd0) begin
            best_score <= ret;
            busy <= 1'b0;
            done <= 1'b1;
            state <= S_IDLE;
          end else begin
            state <= S_POP;            // the stack address is sampled at this edge
          end
        end

        S_POP: begin
          pos <= stack_rdata.pos;
          f <= stack_rdata.f;
          ply <= ply - 5'd1;
          state <= S_SCORE;
        end

        S_SCORE: begin
          f.any_legal <= 1'b1;         // we only came back because a move was legal
          f.best <= new_best;
          f.alpha <= new_alpha;
          if (child_score > f.best && ply == 5'd0) best_move <= root_move;
          if (!perft_mode && new_alpha >= f.beta) begin
            ret <= new_best;           // beta cutoff
            state <= S_RETURN;
          end else begin
            f.index <= f.index + 8'd1;
            state <= S_NEXT;
          end
        end

        default: state <= S_IDLE;
      endcase
    end
  end
endmodule

Line by line: returning

  1. S_END_NODE: no legal move at all means checkmate (score -MATE + ply, so a quicker mate scores higher for the winner) or stalemate (0). Otherwise return best.
  2. S_RETURN: at the root, publish the score and finish. Anywhere else, the stack RAM is reading row ply - 1, the parent.
  3. S_POP restores the parent's position and frame and decreases ply. This is the moment the C call returns.
  4. S_SCORE is the code after the recursive call: negate the child's score (child_score = -ret), update best and alpha, record the root move if it is a new best, and either cut off (alpha >= beta: return at once) or move on to the next index.

Where the clocks go

An interior node costs, roughly: 2 clocks to enter and classify, about 55 for the generator to write its list (Step 29), then for each move 6 clocks to read, decode, apply, test and push, and 3 to pop and score when the child returns. A leaf in quiescence is cheaper: enter, classify, a few clocks for the evaluation pipeline, then return at once if it stands pat. Averaged over a real search, that is the 45 to 50 clocks per node the testbench reports, about a million nodes a second at 50 MHz.

Two design choices keep that number low. First, the stack RAM is read only on a return, and written only on a call, so neither ever waits for the other. Second, an illegal move costs only its own 6 clocks: the attack test on child rejects it before anything is pushed, exactly like legal_after in the C.

The whole search, clock by clock. A replay of the simulated core searching the e4-pawn position to depth 2: 23 nodes in 842 clocks. "Next node" jumps to the next S_ENTER, and the highlighted line in the search tree is the node the hardware is working on. It is the same tree the C produces, node for node.
Check

This is the big one. For every test, the hardware must visit the same number of nodes as the C, and reach the same score and the same best move.

Create tb/tb_search.sv
// tb_search.sv - complete searches and perfts: nodes, score and best move must
// all match the C engine exactly.
`timescale 1ns / 1ps
module tb_search;
  import chess_pkg::*;

  logic clk = 1'b0;
  logic rst = 1'b1;
  logic start = 1'b0;
  logic abort = 1'b0;
  position_t root, next_root;
  logic [4:0] depth;
  logic perft_mode;
  logic [31:0] node_limit;
  logic busy, done, aborted, fault;
  move_t best_move;
  logic signed [15:0] best_score;
  logic [47:0] nodes, cycles;
  always #5 clk = ~clk;

  search_core dut (.clk, .rst, .start, .abort, .root, .depth, .perft_mode, .node_limit,
                   .busy, .done, .aborted, .fault, .best_move, .best_score, .nodes, .cycles);

  initial begin
    int fd, errors, checked, r, side, castle, ep, mode, d, score_x, abort_x;
    longint limit_x, nodes_x;
    longint total_nodes, total_cycles;
    logic [63:0] b;
    logic [15:0] best_x;
    errors = 0;
    checked = 0;
    total_nodes = 0;
    total_cycles = 0;
    repeat (3) @(negedge clk);
    rst = 1'b0;
    fd = $fopen("vec_search.txt", "r");
    if (fd == 0) $fatal(1, "cannot open vec_search.txt");
    while (!$feof(fd)) begin
      for (int i = 0; i < 12; i++) begin
        r = $fscanf(fd, "%h", b);
        next_root.bb[i] = b;
      end
      r = $fscanf(fd, "%d %d %d %d %d %d %d %d %h %d\n",
                  side, castle, ep, mode, d, limit_x, nodes_x, score_x, best_x, abort_x);
      if (r != 10) break;
      next_root.side = side[0];
      next_root.castle = castle[3:0];
      next_root.ep = ep[6:0];
      @(negedge clk);
      root = next_root;
      depth = d[4:0];
      perft_mode = (mode == 1);
      node_limit = limit_x[31:0];
      start = 1'b1;
      @(negedge clk);
      start = 1'b0;
      while (done !== 1'b1) @(negedge clk);
      checked++;
      if (mode == 0 && abort_x == 0) begin
        total_nodes += nodes;
        total_cycles += cycles;
      end
      if (longint'(nodes) != nodes_x || int'(aborted) != abort_x || fault) begin
        errors++;
        $display("NODE MISMATCH: test %0d mode %0d depth %0d got %0d expected %0d aborted %b",
                 checked, mode, d, nodes, nodes_x, aborted);
      end
      if (mode == 0 && abort_x == 0
          && (int'(best_score) != score_x || {1'b0, best_move} !== best_x)) begin
        errors++;
        $display("RESULT MISMATCH: test %0d depth %0d got %0d %h expected %0d %h",
                 checked, d, best_score, best_move, score_x, best_x);
      end
    end
    $display("checked %0d searches, errors = %0d", checked, errors);
    $display("alpha-beta average: %0d.%0d clocks per node",
             total_cycles / total_nodes, (10 * total_cycles / total_nodes) % 10);
    if (errors == 0) $display("TB_SEARCH PASS");
    else             $display("TB_SEARCH FAIL");
    $finish;
  end
endmodule
Command Prompt
scripts\run_sim.bat tb_search
Expected output
checked 167 searches, errors = 0
alpha-beta average: 44.1 clocks per node
TB_SEARCH PASS

An off-by-one anywhere in the search changes a node count almost at once, so this one line means a lot. If it fails, find the first failing test and work down this list:

  1. Perft mismatches first. They mean the rules or the stack are wrong; search results mean nothing until they are fixed.
  2. Perft passes, but alpha-beta node counts differ. Suspect the window (negate and swap) or a comparison done as unsigned. In the waveform, show alpha, beta and ret as signed decimal.
  3. Nodes match, the score differs. Suspect S_END_NODE, or stand pat in S_EVAL_WAIT.
  4. The score matches, the move differs. Suspect root_move or the ply == 0 test.

To see waveforms, add -debug typical to the xelab line in run_sim.bat, then run xsim tb_search_sim -gui from the sim folder.

32The AXI4-Lite register block

Goal: let the Cortex-A9 load a position, start a search and read the result, then test the whole design over the bus.

Concept

The Cortex-A9 talks to the programmable logic over AXI4-Lite, a simple bus for reading and writing 32-bit registers. To the C program, each register is just a memory address. A write uses three channels: the address, the data, and a response. A read uses two: the address and the data. Each channel has a valid signal (the sender has something) and a ready signal (the receiver can take it). A transfer happens on a clock edge where both are high.

Writing START to the CONTROL register. The address and data may arrive on different clocks. This slave waits until both are valid, accepts them together, then raises bvalid to say "done".

Register map

All registers are 32 bits wide; always use full 32-bit accesses.

OffsetNameAccessMeaning
0x00IDreadalways 0xC4E55A01: the first thing to check
0x04CONTROLwritebit 0 START, bit 1 ABORT
0x08STATUSreadbit 0 BUSY, bit 1 DONE, bit 2 ABORTED, bit 3 FAULT
0x0CDEPTHread/writesearch depth, 0 to 31
0x10MODEread/write0 search, 1 perft
0x14NODE_LIMITread/write0 means no limit
0x18METAread/writebit 0 side to move, bits 4:1 castling rights, bits 11:5 en-passant square
0x1CBEST_MOVEreadmove word; 0 means no legal move
0x20SCOREreadsigned, from the side to move's view
0x24, 0x28NODESreadlow and high words; leaves in perft mode
0x2C, 0x30CYCLESreadclocks used by the last search
0x40 to 0x9CBOARDSwrite24 words: board 0 low, board 0 high, board 1 low, ...

Why a shadow copy? The CPU writes the 26 position registers one at a time. If the search used them directly, it could see a half-written board. Instead they fill a shadow copy, and START copies all 780 bits into the core in one clock. Writes are ignored while the core is busy, so a running search can never be disturbed.

Code

The module has five groups of ports, one per AXI channel, plus the clock and reset. The names follow Xilinx's convention (s_axi_ for a slave, then the channel and signal), which is what lets Vivado recognise the whole group as one bus later.

Create rtl/chess_axi.svpart 1 of 6
// chess_axi.sv - AXI4-Lite register block around search_core.
// The CPU writes a shadow copy of the position; START copies it into the core
// in one clock, so the search can never see a half-written board.
`timescale 1ns / 1ps
module chess_axi
  import chess_pkg::*;
(
    input  logic        aclk,
    input  logic        aresetn,
    // write address
    input  logic [11:0] s_axi_awaddr,
    input  logic        s_axi_awvalid,
    output logic        s_axi_awready,
    // write data
    input  logic [31:0] s_axi_wdata,
    input  logic [3:0]  s_axi_wstrb,
    input  logic        s_axi_wvalid,
    output logic        s_axi_wready,
    // write response
    output logic [1:0]  s_axi_bresp,
    output logic        s_axi_bvalid,
    input  logic        s_axi_bready,
    // read address
    input  logic [11:0] s_axi_araddr,
    input  logic        s_axi_arvalid,
    output logic        s_axi_arready,
    // read data
    output logic [31:0] s_axi_rdata,
    output logic [1:0]  s_axi_rresp,
    output logic        s_axi_rvalid,
    input  logic        s_axi_rready
);
  localparam logic [31:0] CHESS_ID = 32'hC4E5_5A01;

  // Word offsets. Byte address = word offset * 4.
  localparam logic [9:0] R_ID = 10'd0, R_CONTROL = 10'd1, R_STATUS = 10'd2,
                         R_DEPTH = 10'd3, R_MODE = 10'd4, R_NODE_LIMIT = 10'd5,
                         R_META = 10'd6, R_BEST_MOVE = 10'd7, R_SCORE = 10'd8,
                         R_NODES_LO = 10'd9, R_NODES_HI = 10'd10,
                         R_CYCLES_LO = 10'd11, R_CYCLES_HI = 10'd12,
                         R_BOARD_FIRST = 10'd16;   // 24 words: board 0 low, board 0 high, ...

Line by line

  1. Write address channel (awaddr, awvalid, awready): the CPU puts the byte address it wants to write on awaddr and raises awvalid. Twelve address bits are enough because the block occupies a 4 KB window; the interconnect strips off the upper bits (0x43C0_0000) before they reach us.
  2. Write data channel (wdata, wstrb, wvalid, wready): the 32-bit value. wstrb says which of the four bytes are valid; we ask the CPU to always write whole words, so we ignore it.
  3. Write response channel (bresp, bvalid, bready): after taking a write we answer "OKAY" (bresp = 00). The CPU's store instruction is not complete until it sees this.
  4. Read address (ar...) and read data (r...) channels: the same idea for loads. The answer comes back on rdata with rvalid.
  5. Word offsets. Registers are 4 bytes apart, so byte address 0x08 is word 2. The code compares word numbers (awaddr[11:2]) because they are smaller and match the table above directly: R_STATUS = 2 is byte offset 0x08. The board words start at word 16, byte 0x40.

Next, the storage behind the registers. The CPU never writes into the search core directly; it writes into these flip-flops, and the core reads them only at the moment it starts.

Add to rtl/chess_axi.svpart 2 of 6
  // ---- shadow registers ------------------------------------------------------
  logic [23:0][31:0] board_regs;
  logic [31:0] meta_reg, limit_reg;
  logic [4:0]  depth_reg;
  logic        mode_reg;

  // ---- core ------------------------------------------------------------------
  logic        core_start, core_abort, core_busy, core_done, core_aborted, core_fault;
  logic        done_sticky;
  position_t   root_pos;
  move_t       core_best;
  logic signed [15:0] core_score;
  logic [47:0] core_nodes, core_cycles;

  always_comb begin
    for (int i = 0; i < 12; i++)
      root_pos.bb[i] = {board_regs[2*i + 1], board_regs[2*i]};
    root_pos.side   = meta_reg[0];
    root_pos.castle = meta_reg[4:1];
    root_pos.ep     = meta_reg[11:5];
  end

  search_core u_core (
    .clk(aclk), .rst(!aresetn), .start(core_start), .abort(core_abort),
    .root(root_pos), .depth(depth_reg), .perft_mode(mode_reg), .node_limit(limit_reg),
    .busy(core_busy), .done(core_done), .aborted(core_aborted), .fault(core_fault),
    .best_move(core_best), .best_score(core_score),
    .nodes(core_nodes), .cycles(core_cycles)
  );

Line by line

  1. board_regs is 24 registers of 32 bits: two per bitboard, because a bitboard is 64 bits and an AXI4-Lite word is 32. Word 2i holds the low half of board i, word 2i+1 the high half.
  2. meta_reg packs the three small fields: side to move in bit 0, castling rights in bits 4 to 1, en-passant square in bits 11 to 5. depth_reg, mode_reg and limit_reg are the search settings.
  3. The always_comb block is pure wiring. It glues each pair of words back into a 64-bit board, {high, low}, and slices the META fields out, building a complete position_t called root_pos. No logic, no clock: just a different view of the same flip-flops.
  4. The core's root input is connected to root_pos. In S_IDLE, on the clock where start is high, the core copies root into its own pos register (Step 31). That copy is the "snapshot": all 780 bits at once.

The write channel, in two parts. First the handshake, which decides when a write happens:

Add to rtl/chess_axi.svpart 3 of 6
  // ---- write channel: accept AW and W together, answer with B ------------------
  logic       write_fire;
  logic [9:0] waddr_word;
  assign s_axi_awready = s_axi_awvalid && s_axi_wvalid && !s_axi_bvalid;
  assign s_axi_wready  = s_axi_awready;
  assign s_axi_bresp   = 2'b00;
  assign write_fire    = s_axi_awready;           // both channels valid this clock
  assign waddr_word    = s_axi_awaddr[11:2];

  assign core_start = write_fire && waddr_word == R_CONTROL && s_axi_wdata[0] && !core_busy;
  assign core_abort = write_fire && waddr_word == R_CONTROL && s_axi_wdata[1];

Line by line

  1. awready is high only when the address and the data are both being offered, and we are not still waiting to deliver the previous response. AXI allows the two to arrive on different clocks; by waiting for both we never need to store one while waiting for the other. This is the simplest correct AXI4-Lite slave.
  2. wready equals awready, so both channels complete on the same clock edge. That edge is called write_fire: "a write is happening now".
  3. core_start is a one-clock pulse: a write to CONTROL with bit 0 set, while the core is idle. core_abort is the same for bit 1, and works only while the core is busy (the core ignores it otherwise).

Then the registers, which decide what a write does:

Add to rtl/chess_axi.svpart 4 of 6
  always_ff @(posedge aclk) begin
    if (!aresetn) begin
      s_axi_bvalid <= 1'b0;
      done_sticky  <= 1'b0;
      depth_reg    <= 5'd1;
      mode_reg     <= 1'b0;
      limit_reg    <= 32'd0;
      meta_reg     <= 32'd0;
      board_regs   <= '0;
    end else begin
      if (s_axi_bvalid && s_axi_bready) s_axi_bvalid <= 1'b0;
      if (core_start) done_sticky <= 1'b0;
      if (core_done)  done_sticky <= 1'b1;
      if (write_fire) begin
        s_axi_bvalid <= 1'b1;
        // Registers may only change while the core is idle.
        if (!core_busy) begin
          case (waddr_word)
            R_DEPTH:      depth_reg <= s_axi_wdata[4:0];
            R_MODE:       mode_reg  <= s_axi_wdata[0];
            R_NODE_LIMIT: limit_reg <= s_axi_wdata;
            R_META:       meta_reg  <= s_axi_wdata;
            default:
              if (waddr_word >= R_BOARD_FIRST && waddr_word < R_BOARD_FIRST + 10'd24)
                board_regs[5'(waddr_word - R_BOARD_FIRST)] <= s_axi_wdata;
          endcase
        end
      end
    end
  end

Line by line

  1. On reset, everything is cleared and the depth is set to 1, a safe default.
  2. bvalid goes high one clock after a write fires, and drops once the CPU has taken the response (bvalid && bready). While it is high, awready stays low, so a second write waits its turn.
  3. done_sticky remembers that a search finished. The core's done is a one-clock pulse, far too short for a CPU to catch by polling, so this bit holds it until the next START clears it. STATUS bit 1 reads this register.
  4. The case stores the data in the register the address selects. The default branch handles the 24 board words with one range check: word 16 goes to board_regs[0], word 39 to board_regs[23].
  5. Everything is inside if (!core_busy): while a search runs, writes are acknowledged (the CPU must not hang) but have no effect. So nothing the CPU does can change a position under a running search.

The read channel, also in two parts. First, what each address reads as:

Add to rtl/chess_axi.svpart 5 of 6
  // ---- read channel ------------------------------------------------------------
  logic [9:0]  raddr_word;
  logic [31:0] read_value;
  assign raddr_word    = s_axi_araddr[11:2];
  assign s_axi_arready = s_axi_arvalid && !s_axi_rvalid;
  assign s_axi_rresp   = 2'b00;

  always_comb begin
    case (raddr_word)
      R_ID:         read_value = CHESS_ID;
      R_STATUS:     read_value = {28'd0, core_fault, core_aborted, done_sticky, core_busy};
      R_DEPTH:      read_value = {27'd0, depth_reg};
      R_MODE:       read_value = {31'd0, mode_reg};
      R_NODE_LIMIT: read_value = limit_reg;
      R_META:       read_value = meta_reg;
      R_BEST_MOVE:  read_value = {17'd0, core_best};
      R_SCORE:      read_value = 32'(core_score);
      R_NODES_LO:   read_value = core_nodes[31:0];
      R_NODES_HI:   read_value = {16'd0, core_nodes[47:32]};
      R_CYCLES_LO:  read_value = core_cycles[31:0];
      R_CYCLES_HI:  read_value = {16'd0, core_cycles[47:32]};
      default:      read_value = 32'd0;
    endcase
  end

Line by line

  1. arready accepts a read address whenever we are not still holding a previous answer.
  2. The always_comb case is a multiplexer: for each word address, which value would be returned. STATUS packs four bits: BUSY, DONE (the sticky copy), ABORTED, FAULT.
  3. 32'(core_score) sign-extends the 16-bit score, so a negative score reads as a negative 32-bit number and C can simply cast it to int32_t.
  4. Node and clock counters are 48 bits wide, so they need two words each. The board registers are write-only: reading them returns 0, which saves 24 inputs on this multiplexer.

Then the reply, registered so the data leaves on a clean clock edge:

Add to rtl/chess_axi.svpart 6 of 6
  always_ff @(posedge aclk) begin
    if (!aresetn) begin
      s_axi_rvalid <= 1'b0;
      s_axi_rdata  <= 32'd0;
    end else begin
      if (s_axi_rvalid && s_axi_rready) s_axi_rvalid <= 1'b0;
      if (s_axi_arready) begin
        s_axi_rvalid <= 1'b1;
        s_axi_rdata  <= read_value;
      end
    end
  end
endmodule

Line by line

  1. When a read address is accepted, the looked-up value is stored in rdata and rvalid rises on the next clock.
  2. rvalid stays high until the CPU takes the data (rready). A read therefore costs two clocks inside this block; most of the time a CPU read spends is in the interconnect and the processor, not here.

One more file. Vivado's block design can't use a SystemVerilog module as the top of a "module reference" (UG994 lists this limit). So this plain Verilog file wraps it.

Create rtl/chess_axi_top.v
// chess_axi_top.v - Vivado's "Add Module" needs a plain Verilog top level, because
// a block-design module reference cannot have a SystemVerilog top. This file only
// renames ports and adds the interface hints.
`timescale 1ns / 1ps
module chess_axi_top (
    (* X_INTERFACE_INFO = "xilinx.com:signal:clock:1.0 aclk CLK" *)
    (* X_INTERFACE_PARAMETER = "ASSOCIATED_BUSIF s_axi, ASSOCIATED_RESET aresetn" *)
    input  wire        aclk,
    (* X_INTERFACE_INFO = "xilinx.com:signal:reset:1.0 aresetn RST" *)
    (* X_INTERFACE_PARAMETER = "POLARITY ACTIVE_LOW" *)
    input  wire        aresetn,
    input  wire [11:0] s_axi_awaddr,
    input  wire [2:0]  s_axi_awprot,
    input  wire        s_axi_awvalid,
    output wire        s_axi_awready,
    input  wire [31:0] s_axi_wdata,
    input  wire [3:0]  s_axi_wstrb,
    input  wire        s_axi_wvalid,
    output wire        s_axi_wready,
    output wire [1:0]  s_axi_bresp,
    output wire        s_axi_bvalid,
    input  wire        s_axi_bready,
    input  wire [11:0] s_axi_araddr,
    input  wire [2:0]  s_axi_arprot,
    input  wire        s_axi_arvalid,
    output wire        s_axi_arready,
    output wire [31:0] s_axi_rdata,
    output wire [1:0]  s_axi_rresp,
    output wire        s_axi_rvalid,
    input  wire        s_axi_rready
);
  chess_axi u_chess_axi (
    .aclk(aclk), .aresetn(aresetn),
    .s_axi_awaddr(s_axi_awaddr), .s_axi_awvalid(s_axi_awvalid), .s_axi_awready(s_axi_awready),
    .s_axi_wdata(s_axi_wdata), .s_axi_wstrb(s_axi_wstrb),
    .s_axi_wvalid(s_axi_wvalid), .s_axi_wready(s_axi_wready),
    .s_axi_bresp(s_axi_bresp), .s_axi_bvalid(s_axi_bvalid), .s_axi_bready(s_axi_bready),
    .s_axi_araddr(s_axi_araddr), .s_axi_arvalid(s_axi_arvalid), .s_axi_arready(s_axi_arready),
    .s_axi_rdata(s_axi_rdata), .s_axi_rresp(s_axi_rresp),
    .s_axi_rvalid(s_axi_rvalid), .s_axi_rready(s_axi_rready)
  );
endmodule

Line by line

  1. X_INTERFACE_INFO ... clock on aclk tells Vivado "this pin is a clock". ASSOCIATED_BUSIF s_axi says the s_axi bus is synchronous to it, so Connection Automation will connect the same clock that drives the bus master. ASSOCIATED_RESET aresetn pairs the reset with it.
  2. POLARITY ACTIVE_LOW on aresetn: the core is in reset while this pin is 0, which is what the Processor System Reset block produces.
  3. The bus pins need no attributes: because every name starts with s_axi_ and ends in a standard AXI signal name, Vivado infers an AXI4-Lite slave interface called s_axi by itself.
  4. awprot and arprot (protection type) exist only so the interface is complete; the core does not use them.
Check

This testbench plays the part of the Cortex-A9: every action goes over AXI, with the address and data deliberately offered on different clocks. It runs 40 searches from the vector file, then starts a long perft and aborts it.

Create tb/tb_axi.sv
// tb_axi.sv - plays the part of the Cortex-A9: every access goes over AXI4-Lite.
`timescale 1ns / 1ps
module tb_axi;
  parameter int MAX_TESTS = 40;
  logic aclk = 1'b0;
  logic aresetn = 1'b0;
  logic [11:0] awaddr, araddr;
  logic awvalid = 1'b0, wvalid = 1'b0, bready = 1'b0, arvalid = 1'b0, rready = 1'b0;
  logic awready, wready, bvalid, arready, rvalid;
  logic [31:0] wdata, rdata;
  logic [1:0] bresp, rresp;
  always #5 aclk = ~aclk;

  chess_axi_top dut (
    .aclk, .aresetn,
    .s_axi_awaddr(awaddr), .s_axi_awprot(3'b000), .s_axi_awvalid(awvalid), .s_axi_awready(awready),
    .s_axi_wdata(wdata), .s_axi_wstrb(4'hF), .s_axi_wvalid(wvalid), .s_axi_wready(wready),
    .s_axi_bresp(bresp), .s_axi_bvalid(bvalid), .s_axi_bready(bready),
    .s_axi_araddr(araddr), .s_axi_arprot(3'b000), .s_axi_arvalid(arvalid), .s_axi_arready(arready),
    .s_axi_rdata(rdata), .s_axi_rresp(rresp), .s_axi_rvalid(rvalid), .s_axi_rready(rready)
  );

  // Address and data are offered on separate clocks on purpose, to prove the
  // slave waits for both.
  task automatic axi_write(input logic [11:0] addr, input logic [31:0] data);
    @(negedge aclk);
    awaddr = addr;
    awvalid = 1'b1;
    @(negedge aclk);
    wdata = data;
    wvalid = 1'b1;
    bready = 1'b1;
    while (awready !== 1'b1) @(negedge aclk);
    @(negedge aclk);               // the handshake happened at the rising edge
    awvalid = 1'b0;
    wvalid = 1'b0;
    while (bvalid !== 1'b1) @(negedge aclk);
    @(negedge aclk);
    bready = 1'b0;
  endtask

  task automatic axi_read(input logic [11:0] addr, output logic [31:0] data);
    @(negedge aclk);
    araddr = addr;
    arvalid = 1'b1;
    rready = 1'b1;
    while (arready !== 1'b1) @(negedge aclk);
    @(negedge aclk);
    arvalid = 1'b0;
    while (rvalid !== 1'b1) @(negedge aclk);
    data = rdata;
    @(negedge aclk);
    rready = 1'b0;
  endtask

  initial begin
    int fd, errors, checked, r, side, castle, ep, mode, d, score_x, abort_x;
    longint limit_x, nodes_x;
    logic [63:0] b;
    logic [15:0] best_x;
    logic [31:0] v, nodes_lo, nodes_hi, best, score;
    errors = 0;
    checked = 0;
    repeat (5) @(negedge aclk);
    aresetn = 1'b1;

    axi_read(12'h000, v);
    if (v !== 32'hC4E55A01) begin
      errors++;
      $display("BAD ID %h", v);
    end

    fd = $fopen("vec_search.txt", "r");
    if (fd == 0) $fatal(1, "cannot open vec_search.txt");
    while (!$feof(fd) && checked < MAX_TESTS) begin
      for (int i = 0; i < 12; i++) begin
        r = $fscanf(fd, "%h", b);
        axi_write(12'h040 + 12'(8*i),     b[31:0]);
        axi_write(12'h040 + 12'(8*i) + 4, b[63:32]);
      end
      r = $fscanf(fd, "%d %d %d %d %d %d %d %d %h %d\n",
                  side, castle, ep, mode, d, limit_x, nodes_x, score_x, best_x, abort_x);
      if (r != 10) break;
      axi_write(12'h018, side | (castle << 1) | (ep << 5));
      axi_write(12'h00C, d);
      axi_write(12'h010, mode);
      axi_write(12'h014, limit_x[31:0]);
      axi_write(12'h004, 32'd1);                  // START
      do axi_read(12'h008, v); while (v[1] !== 1'b1);   // wait for DONE
      axi_read(12'h01C, best);
      axi_read(12'h020, score);
      axi_read(12'h024, nodes_lo);
      axi_read(12'h028, nodes_hi);
      checked++;
      if (longint'({nodes_hi, nodes_lo}) != nodes_x || int'(v[2]) != abort_x) begin
        errors++;
        $display("NODES: test %0d got %0d expected %0d", checked, nodes_lo, nodes_x);
      end
      if (mode == 0 && abort_x == 0
          && (int'($signed(score)) != score_x || best[15:0] !== best_x)) begin
        errors++;
        $display("RESULT: test %0d got %0d %h expected %0d %h",
                 checked, $signed(score), best, score_x, best_x);
      end
    end

    // A running search must obey ABORT.
    axi_write(12'h00C, 32'd8);
    axi_write(12'h010, 32'd1);
    axi_write(12'h014, 32'd0);
    axi_write(12'h004, 32'd1);
    axi_read(12'h008, v);
    if (v[0] !== 1'b1) begin errors++; $display("core did not go busy"); end
    axi_write(12'h004, 32'd2);
    do axi_read(12'h008, v); while (v[1] !== 1'b1);
    if (v[2] !== 1'b1) begin errors++; $display("abort flag not set"); end

    $display("checked %0d searches over AXI, errors = %0d", checked, errors);
    if (errors == 0) $display("TB_AXI PASS");
    else             $display("TB_AXI FAIL");
    $finish;
  end
endmodule
Command Prompt
scripts\run_sim.bat tb_axi
Expected output
checked 40 searches over AXI, errors = 0
TB_AXI PASS

Results so far

These are the numbers from my run of the full vector set under Verilator:

TestbenchCoverageResult
tb_functions1,109 positions, 29,666 moves0 errors
tb_eval1,109 positions0 errors
tb_move_gen2,218 lists0 errors, 55 clocks per list
tb_search577 searches and perfts, 2.4 million nodes0 errors, 49.9 clocks per node
tb_axi40 searches, plus abort0 errors

Clocks per node depends on the position: 33 to 36 for depth 5 and 6 from the start, about 50 across the tactical test set. At 50 MHz that is 1 to 1.5 million nodes per second, from a few percent of the chip, against about 12,000 for the JavaScript in this page.

Part 2 checklist
  • All five testbenches print PASS under xsim.
  • You can explain why child can feed the attack test in S_ENTER.
  • You can point to where each negamax variable lives in the frame.
Part 3

On the PYNQ-Z2

From source files to a move on real silicon. Do the steps in order. Vivado's menus move a little between releases, so if a label differs, look for the closest match. This part could not be run while writing the guide, so each step says exactly what to expect: if something differs, trust what Vivado tells you, and check the troubleshooting tables at the end.

33Install the board files

Vivado needs the PYNQ-Z2 board files to know the board's DDR memory settings and how the Zynq processor is wired.

  1. Check whether they are already installed. Start Vivado, click Create Project, and press Next until the Default Part page. Open the Boards tab and search for pynq. If pynq-z2 appears, cancel and go to Step 34.
  2. Download the board files from TUL's PYNQ-Z2 page.
  3. Extract them to a folder without spaces, such as C:\Xilinx\boards\pynq-z2\A.0. It should contain a board.xml file.
  4. Tell Vivado where they are. Create or edit %APPDATA%\Xilinx\Vivado\init.tcl and add this line, using forward slashes even on Windows (the method described by element14):
    Tcl console
    set_param board.repoPaths [list "C:/Xilinx/boards/pynq-z2/A.0"]
    
  5. Restart Vivado and repeat check 1. You should now see pynq-z2.

34Create the Vivado project

  1. Start Vivado. Click Create Project, then Next.
  2. Project name: chess_pynq. Location: C:/chess/vivado. Keep Create project subdirectory ticked. Next.
  3. Project type: RTL Project, and tick Do not specify sources at this time. Next.
  4. Default Part: open the Boards tab, select pynq-z2, then Next and Finish.
  5. In the Flow Navigator on the left, under PROJECT MANAGER, click Add Sources. Choose Add or create design sources, Next.
  6. Click Add Files, go to C:\chess\rtl, select all seven files, and click OK.
  7. Untick Copy sources into project, so your edits in C:\chess\rtl are the ones that get built. Finish.
  8. In the Sources window, under Design Sources, you should see chess_axi_top with chess_axi, search_core and the rest beneath it.

Don't add the testbenches: you have already run them from the command line. If Vivado reports that chess_pkg is not declared, open the Compile Order tab in the Sources window and make sure chess_pkg.sv is first, with file type SystemVerilog.

35Draw the block design

The block design connects your core to the Zynq's processor system:

The finished block design. The processor's general-purpose AXI master drives your core through an interconnect. The processor also supplies the 50 MHz fabric clock and, through a reset block, the reset.
  1. In the Flow Navigator, under IP INTEGRATOR, click Create Block Design. Name it system, OK.
  2. Click + (Add IP) in the empty diagram, search for zynq, and double-click ZYNQ7 Processing System.
  3. Click Run Block Automation in the green banner. Leave Apply Board Preset ticked, and click OK. The DDR and FIXED_IO ports appear. This configures the board's DDR memory; without it, bare-metal programs won't run.
  4. Double-click the Zynq block:
    1. Open Clock Configuration, expand PL Fabric Clocks, tick FCLK_CLK0, and set Requested Frequency to 50.
    2. Open PS-PL Configuration, then AXI Non Secure Enablement, then GP Master AXI Interface, and make sure M AXI GP0 interface is ticked.
    3. Click OK.
  5. Right-click an empty part of the diagram and choose Add Module. Select chess_axi_top and click OK. A block named chess_axi_top_0 appears, with one s_axi bus port, aclk and aresetn.
  6. Click Run Connection Automation, tick All Automation, OK. Vivado adds an AXI Interconnect (or SmartConnect) and a Processor System Reset, and wires the clocks.
  7. Open the Address Editor tab. Find chess_axi_top_0: it should have a 4K range at an address such as 0x43C0_0000. Write this address down. Your software needs it.
  8. Press F6 (Validate Design). You want "Validation successful". Warnings about unused interrupts are fine; critical warnings are not.
  9. Save with Ctrl+S. In the Sources window, right-click system.bd, choose Create HDL Wrapper, then Let Vivado manage wrapper and auto-update, OK.
  10. system_wrapper should now be the top module, shown in bold. If not, right-click it and choose Set as Top.

What you just built, block by block

BlockIts job in the AXI path
ZYNQ7 Processing SystemThe Cortex-A9. Its M_AXI_GP0 port is an AXI master: every load or store the CPU makes to an address from 0x4000_0000 to 0x7FFF_FFFF leaves the processor through this port. FCLK_CLK0 is a clock it generates for the fabric.
AXI Interconnect / SmartConnectRoutes each transaction by address to the right slave, and converts the processor's full AXI3 protocol into the simpler AXI4-Lite your core speaks. With one slave it is almost a wire; with your GPU added (Step 42) it really routes.
Processor System ResetTakes the processor's reset and produces a clean, clock-synchronous peripheral_aresetn for the fabric. Your core's aresetn comes from here.
chess_axi_top_0Your core: an AXI4-Lite slave, answering at the address you assign it.

Check the AXI connection before going on

  1. Click the chess_axi_top_0 block. Its left side should show one bus port, s_axi, with a + next to it. Expand it: you should see the AWADDR, WDATA, BRESP, ARADDR and RDATA groups. That means Vivado inferred the AXI4-Lite interface from the port names. If instead you see 19 loose pins, the names don't match the convention: check chess_axi_top.v is the file you added.
  2. Hover over the aclk pin: the tooltip should list ASSOCIATED_BUSIF s_axi. If the clock and the bus were inferred separately, Validate (F6) warns that s_axi has no associated clock.
  3. Follow the wires: M_AXI_GP0 → interconnect S00_AXI; interconnect M00_AXI → chess_axi_top_0/s_axi; FCLK_CLK0 → M_AXI_GP0_ACLK, the interconnect clocks, and aclk; reset block peripheral_aresetn → aresetn.
  4. In the Address Editor, the row reads roughly: /chess_axi_top_0/s_axi, interface s_axi, base name reg0, Offset Address 0x43C0_0000, Range 4K. The core decodes 12 address bits, so 4K is exactly its size. If the row says "unassigned", right-click it and choose Assign.

If Validate complains

Message (roughly)Fix
"slave segment is not assigned into address space"Address Editor: right-click the row, Assign, then Validate again.
"interface s_axi has no associated clock" or a clock frequency mismatchMake sure aclk and the interconnect's M00_ACLK come from the same FCLK_CLK0. If the frequency differs, right-click the aclk pin, Properties, and check FREQ_HZ matches 50000000, or simply delete and redo Connection Automation.
"Module chess_axi_top not found" when adding the moduleThe rtl files must be in the project's design sources and chess_pkg.sv must be among them. Refresh the hierarchy (Sources window, right-click, Refresh Hierarchy).
Port width mismatch on awaddrNormal: the interconnect's 32-bit address is truncated to the core's 12 bits. Vivado does this for you; it is only an info message.

36Synthesize and read the reports

  1. Click Run Synthesis, then OK. It takes a few minutes.
  2. When it finishes, choose Open Synthesized Design.
  3. Open Reports, then Report Utilization, and click OK.

Compare with my estimate. These numbers came from Yosys, for the chess block alone; Vivado's will differ somewhat, and add the interconnect.

ResourceEstimateShare of the XC7Z020
LUTs11,42321%
Flip-flops4,2484%
RAMB36 block RAMs1611%
CARRY4141

Then check five things in the reports and the synthesis messages:

CheckGoodIf not
Block RAMabout 16 RAMB36 (or the same in RAMB18s)0 block RAM and thousands of extra flip-flops: the RAM was not inferred. Read the messages about mem in sdp_ram
Latchesnoneany "inferred latch" is a bug
Multi-driven netsnonea signal assigned in two places
LUT countthe same order as the estimateseveral times larger: the hierarchy view shows which block grew
Width warningsfew, and you can explain themlook hard at any on alpha, beta, score or ret

Warnings that s_axi_wstrb, s_axi_awprot and s_axi_arprot are unused are expected.

Reading the utilisation report

  • Slice LUTs is the main measure of logic. A 6-input LUT is a tiny lookup table that can compute any function of six inputs; the XC7Z020 has 53,200 of them. The chess core should use about a fifth, leaving plenty for your GPU.
  • Slice Registers are flip-flops: one per stored bit. The pos and child registers alone are over 1,500 of them.
  • Block RAM Tile counts 36 Kib RAMs. 16 is expected: 12 for the stack (because it is 851 bits wide) and 4 for the move lists.
  • Click Hierarchy in the report window to see the same numbers per module. Expect move_gen and search_core (with its attack tester) to be the two largest, and chess_axi to be small: it is mostly the 26 shadow registers.

37Implement, close timing, and write the bitstream

Run at 50 MHz first

  1. Click Run Implementation, then OK.
  2. When it's done, open Reports, then Timing, then Report Timing Summary.
  3. Read two numbers. WNS (worst negative slack) is the spare time on the slowest path; it must be zero or more. WHS (worst hold slack) must also be zero or more.

At 50 MHz each clock is 20 ns. My estimate puts the longest paths at about 12 logic levels; at very roughly 0.7 to 0.9 ns a level, 50 MHz should pass comfortably. That is an estimate, so read the real WNS.

Never ignore a negative WNS

A design that fails timing may seem to work, then return wrong moves at random. Fix it before you trust anything the board says.

How fast could it go?

Expected output
fastest period  ~ current period - WNS
fastest clock   ~ 1000 / fastest period    (MHz)

example: at 50 MHz, WNS = +8.2 ns  ->  20 - 8.2 = 11.8 ns  ->  about 85 MHz

To try a faster clock, double-click the Zynq block, open Clock Configuration, then PL Fabric Clocks, and set FCLK_CLK0 to the next target, say 75. Read the Actual Frequency column, since the processor can only make certain frequencies. Then run implementation again. The software reads the same clock counts at any speed: a faster clock just finishes sooner.

If timing fails

Don't hide it with false-path constraints. Find the real path: in Report Timing Summary, open Intra-Clock Paths, then the clock, then Setup, and double-click the worst path. Its Destination tells you where to look:

Destination containsPathFix
u_move_gen/targetssliding attacks for one piecesplit G_TARGETS into two clocks
u_move_gen/moversthe backward attacksgive G_STAGE a second clock
attackedthe full attack mapregister side_attacks(child, ...) first, then AND it a clock later
childapply_decodedduplicate the decoded registers to cut fanout
u_evalthe addersalready pipelined: check the clock setting first

Each fix adds a clock to one state. That changes clocks per node, but never nodes, scores or moves, so tb_search must still pass afterwards. Vivado's effort settings can also help: Settings, Synthesis, strategy Flow_PerfOptimized_high, and Settings, Implementation, strategy Performance_Explore.

Write the bitstream

  1. Click Generate Bitstream.
  2. Find the two output files (<proj> is C:\chess\vivado\chess_pynq):
    FileWhere
    Bitstream<proj>\chess_pynq.runs\impl_1\system_wrapper.bit
    Hardware handoff<proj>\chess_pynq.gen\sources_1\bd\system\hw_handoff\system.hwh (older Vivado: under chess_pynq.srcs)
  3. For Vitis, export the hardware: File, Export, Export Hardware, choose Include bitstream, and save as C:\chess\output\chess.xsa.

The same thing, by script

Once you have clicked through it once, this script does Steps 34 to 37 in one command, and copies the results and reports to output\:

Create scripts/build.tcl
# build.tcl - creates the whole Vivado project and bitstream without clicking.
# Usage, from the project folder:   vivado -mode batch -source scripts/build.tcl
set clock_mhz 50

set root [file normalize [file join [file dirname [info script]] ..]]
create_project chess_pynq [file join $root vivado] -part xc7z020clg400-1 -force

set boards [get_board_parts -quiet *pynq-z2*]
if {[llength $boards] == 0} {
    error "PYNQ-Z2 board files are not installed: see the board-file step in the guide"
}
set_property board_part [lindex $boards end] [current_project]

add_files -norecurse [glob [file join $root rtl *.sv]]
add_files -norecurse [file join $root rtl chess_axi_top.v]
update_compile_order -fileset sources_1

create_bd_design system
create_bd_cell -type ip -vlnv xilinx.com:ip:processing_system7:5.5 processing_system7_0
apply_bd_automation -rule xilinx.com:bd_rule:processing_system7 \
    -config {make_external "FIXED_IO, DDR" apply_board_preset "1" Master "Disable" Slave "Disable"} \
    [get_bd_cells processing_system7_0]
set_property CONFIG.PCW_FPGA0_PERIPHERAL_FREQMHZ $clock_mhz [get_bd_cells processing_system7_0]

create_bd_cell -type module -reference chess_axi_top chess_axi_top_0
apply_bd_automation -rule xilinx.com:bd_rule:axi4 \
    -config {Clk_master {Auto} Clk_slave {Auto} Clk_xbar {Auto} \
             Master {/processing_system7_0/M_AXI_GP0} Slave {/chess_axi_top_0/s_axi} \
             ddr_seg {Auto} intc_ip {New AXI Interconnect} master_apm {0}} \
    [get_bd_intf_pins chess_axi_top_0/s_axi]
assign_bd_address
validate_bd_design
save_bd_design

add_files -norecurse [make_wrapper -files [get_files system.bd] -top]
set_property top system_wrapper [current_fileset]
update_compile_order -fileset sources_1

launch_runs synth_1 -jobs 4
wait_on_run synth_1
launch_runs impl_1 -to_step write_bitstream -jobs 4
wait_on_run impl_1
if {[get_property PROGRESS [get_runs impl_1]] != "100%"} { error "implementation failed" }

open_run impl_1
set out [file join $root output]
file mkdir $out
report_timing_summary -file [file join $out timing.txt]
report_utilization    -file [file join $out utilization.txt]
write_hw_platform -fixed -include_bit -force -file [file join $out chess.xsa]
file copy -force [glob [file join $root vivado chess_pynq.runs impl_1 *.bit]] [file join $out chess.bit]
file copy -force [file join $root vivado chess_pynq.gen sources_1 bd system hw_handoff system.hwh] \
                 [file join $out chess.hwh]
puts "Bitstream, hardware handoff and reports are in $out"
puts "Worst setup slack: [get_property SLACK [get_timing_paths -delay_type max]] ns"
Command Prompt
cd /d C:\chess
vivado -mode batch -source scripts/build.tcl

Read the last line it prints, and output\timing.txt. Change clock_mhz at the top to try a faster clock.

38First run, with PYNQ and Python

This is the quickest way to see your core work, because it needs no Vitis at all.

Prepare the board

  1. Write the PYNQ-Z2 image to a micro-SD card (images at pynq.io/boards).
  2. Following the PYNQ-Z2 setup guide, set the Boot jumper to SD and the Power jumper to USB.
  3. Connect USB to the PROG-UART port and Ethernet to your PC or network, and switch on.
  4. On a direct cable, the board is at 192.168.2.99; give your PC a fixed address on the same subnet, such as 192.168.2.1. On a network with DHCP it takes an assigned address.

Copy the files

In File Explorer's address bar, type \\192.168.2.99\xilinx (login xilinx, password xilinx), and create a folder named chess. Copy these into it, renaming the first two so they share a base name. The PYNQ documentation requires the .hwh to match the .bit:

FromTo
system_wrapper.bitchess\chess.bit
system.hwhchess\chess.hwh
C:\chess\sw\chess_pynq.pychess\chess_pynq.py

Here is that driver. It reads a FEN, writes the 26 registers, starts a search and reads the result. It is the Python twin of the C driver in the next step.

Create sw/chess_pynq.py
# chess_pynq.py - run the chess core from Jupyter on the PYNQ-Z2.
from pynq import Overlay, MMIO

REG_ID, REG_CONTROL, REG_STATUS, REG_DEPTH = 0x00, 0x04, 0x08, 0x0C
REG_MODE, REG_NODE_LIMIT, REG_META, REG_BEST_MOVE = 0x10, 0x14, 0x18, 0x1C
REG_SCORE, REG_NODES_LO, REG_NODES_HI = 0x20, 0x24, 0x28
REG_CYCLES_LO, REG_CYCLES_HI, REG_BOARDS = 0x2C, 0x30, 0x40
STAT_DONE, STAT_ABORTED, STAT_FAULT = 2, 4, 8
EXPECTED_ID = 0xC4E55A01
PIECES = "PNBRQKpnbrqk"


def parse_fen(fen):
    """Returns (boards, side, castle, ep) in the format the hardware expects."""
    fields = fen.split()
    boards = [0] * 12
    rank, file = 7, 0
    for ch in fields[0]:
        if ch == "/":
            rank, file = rank - 1, 0
        elif ch.isdigit():
            file += int(ch)
        else:
            boards[PIECES.index(ch)] |= 1 << (rank * 8 + file)
            file += 1
    side = 0 if fields[1] == "w" else 1
    castle = sum(bit for ch, bit in zip("KQkq", (1, 2, 4, 8)) if ch in fields[2])
    # A right only counts when the king and rook are really at home.
    if not boards[5] >> 4 & 1:
        castle &= ~3
    if not boards[11] >> 60 & 1:
        castle &= ~12
    if not boards[3] >> 7 & 1:
        castle &= ~1
    if not boards[3] >> 0 & 1:
        castle &= ~2
    if not boards[9] >> 63 & 1:
        castle &= ~4
    if not boards[9] >> 56 & 1:
        castle &= ~8
    ep = 64
    if fields[3] != "-":
        ep = (int(fields[3][1]) - 1) * 8 + "abcdefgh".index(fields[3][0])
    return boards, side, castle, ep


def move_text(word):
    """15-bit hardware move -> text such as e2e4 or a7a8q. 0 means no move."""
    if word == 0:
        return "none"
    frm, to, promo = word & 63, (word >> 6) & 63, (word >> 12) & 7
    text = "abcdefgh"[frm & 7] + str((frm >> 3) + 1)
    text += "abcdefgh"[to & 7] + str((to >> 3) + 1)
    return text + " nbrq"[promo].strip()


class ChessCore:
    def __init__(self, mmio):
        self.mmio = mmio
        found = mmio.read(REG_ID)
        if found != EXPECTED_ID:
            raise RuntimeError(f"ID register reads {found:08x}: wrong bitstream or address")

    def load_fen(self, fen):
        boards, side, castle, ep = parse_fen(fen)
        for i, board in enumerate(boards):
            self.mmio.write(REG_BOARDS + 8 * i, board & 0xFFFFFFFF)
            self.mmio.write(REG_BOARDS + 8 * i + 4, board >> 32)
        self.mmio.write(REG_META, side | (castle << 1) | (ep << 5))

    def run(self, depth, perft=False, node_limit=0):
        self.mmio.write(REG_DEPTH, depth)
        self.mmio.write(REG_MODE, 1 if perft else 0)
        self.mmio.write(REG_NODE_LIMIT, node_limit)
        self.mmio.write(REG_CONTROL, 1)
        while not self.mmio.read(REG_STATUS) & STAT_DONE:
            pass
        status = self.mmio.read(REG_STATUS)
        score = self.mmio.read(REG_SCORE)
        return {
            "best": move_text(self.mmio.read(REG_BEST_MOVE)),
            "score": score - (1 << 32) if score >= (1 << 31) else score,
            "nodes": self.mmio.read(REG_NODES_LO) | (self.mmio.read(REG_NODES_HI) << 32),
            "cycles": self.mmio.read(REG_CYCLES_LO) | (self.mmio.read(REG_CYCLES_HI) << 32),
            "aborted": bool(status & STAT_ABORTED),
            "fault": bool(status & STAT_FAULT),
        }


def open_core(bitfile="chess.bit", base_address=0x43C00000):
    Overlay(bitfile)                    # loads chess.bit and sets the PL clock from chess.hwh
    return ChessCore(MMIO(base_address, 0x1000))

Run it

Open Jupyter in a browser. Current PYNQ images serve it on port 9090: http://192.168.2.99:9090, password xilinx. Open the chess folder and start a new Python 3 notebook there. First cell, with the address you wrote down in Step 35:

Jupyter cell
from chess_pynq import open_core, move_text
core = open_core("chess.bit", base_address=0x43C00000)
print("Core found")

You should see Core found. ID register reads ... means the address or the bitstream is wrong. Next, perft: the most important test on the board.

Jupyter cell
START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
KIWI = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1"

core.load_fen(START)
r = core.run(4, perft=True)
print(r["nodes"], r["cycles"], "expected 197281 3186591")

core.load_fen(KIWI)
r = core.run(3, perft=True)
print(r["nodes"], r["cycles"], "expected 97862 1432430")

Both the counts and the clock counts must match exactly: the core is fully deterministic, and its clock count doesn't depend on the clock speed. Now a search:

Jupyter cell
core.load_fen(START)
for depth in range(1, 7):
    r = core.run(depth)
    print(depth, r["best"], r["score"], r["nodes"], r["cycles"])

Expected, from running this exact driver code against the simulated hardware:

Expected output
1 b1c3 40 21 489
2 b1c3 10 238 7115
3 b1c3 40 2639 76208
4 b1c3 10 25933 844430
5 d2d4 30 199412 6684151
6 d2d4 10 1519394 55995067

At 50 MHz, 55,995,067 clocks is 1.12 seconds for 1.5 million nodes. The C engine on a desktop took about 3 seconds for the same search. Finally, three special positions:

Jupyter cell
tests = [
    ("mate in one", "6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1", 2),  # d1d8, 29999
    ("stalemate",   "7k/5Q2/6K1/8/8/8/8/8 b - - 0 1", 3),         # none, 0
    ("promotion",   "4k3/P7/8/8/8/8/8/4K3 w - - 0 1", 1),         # a7a8q, 890
]
for name, fen, depth in tests:
    core.load_fen(fen)
    r = core.run(depth)
    print(name, r["best"], r["score"])

If all of that matches, your chess engine is running in the programmable logic.

39Bare-metal C, with Vitis

Goal: drive the core from C on the Cortex-A9: the route to your final game.

Concept: the board over AXI4-Lite, end to end

This is the whole conversation between the Cortex-A9 and the chess core. There is no special protocol and no interrupt: the CPU sends a position by writing registers, presses START, watches STATUS, and reads the answer. Every step is one 32-bit load or store to an address between 0x43C0_0000 and 0x43C0_009C.

  1. Check the core is there. Read ID (offset 0x00). It must be 0xC4E55A01. Anything else means the bitstream isn't loaded or the address is wrong, and no other step will work.
  2. Send the twelve bitboards. Each 64-bit board is split into two 32-bit words, low half first: board 0 low at 0x40, board 0 high at 0x44, board 1 low at 0x48, and so on up to board 11 high at 0x9C. That is 24 writes. Write all of them every time, even the zeros, because the shadow registers still hold the previous position.
  3. Send META (0x18): side to move in bit 0, castling rights in bits 4 to 1, en-passant square in bits 11 to 5 (64 for none).
  4. Set the search: DEPTH (0x0C), MODE (0x10, 0 for a search) and NODE_LIMIT (0x14, 0 for none). These keep their values between searches, but writing them each time keeps the code obviously correct.
  5. Write 1 to CONTROL (0x04). In that clock, the core copies the shadow registers into itself and STATUS shows BUSY.
  6. Poll STATUS (0x08) until bit 1, DONE, is set. Your main loop can do other work between polls; a search takes from microseconds to seconds, depending on the depth.
  7. Read the result: BEST_MOVE (0x1C), SCORE (0x20), and if you want them, NODES and CYCLES. If STATUS bit 2, ABORTED, is set, the result is incomplete and must be ignored.

Twenty-eight writes and a handful of reads take a few microseconds on the Zynq's GP0 port, nothing next to the search. Step through it here, for real positions. The values in the table are exactly what pl_write_position sends:

One search, transaction by transaction. For a board word, the small board shows the 32 squares that word carries, with the pieces in it highlighted. Watch the shadow registers fill, then START hand them to the core in one clock. The move and score come from this page's copy of the engine, searching to depth 3.
MistakeWhat you seeWhy
Writing the high word first, or swapping low and highpieces on the wrong half of the board; nonsense movesword 2i is bits 31..0, word 2i+1 bits 63..32
Skipping boards that are zeropieces from the previous position appearthe shadow registers keep old values until overwritten
Writing the position while BUSYthe search ignores it and plays a move for the old positionwrites are ignored while a search runs; wait for DONE or ABORT first
Reading BEST_MOVE before DONEthe move from the previous searchresults only change when a search finishes
Using 8- or 16-bit storesgarbled registersthe block ignores wstrb; always use Xil_Out32

Where does the address come from? Vivado's Address Editor (Step 35). Vitis also writes the addresses of the blocks it knows about into xparameters.h; open it and search for 43C0 to see if your core got a name there. The driver uses CHESS_BASE, which defaults to 0x43C00000 and can be overridden with a compiler symbol.

Try it by hand first: the XSCT console

Before writing any C, you can send a position and read the move yourself, one register at a time. This is the best possible test of the AXI-Lite path: if these commands work, the block design, the address and the bitstream are all right, and any later problem is in software. Vitis includes a Tcl console for the debugger, called XSCT (Vitis Classic: Xilinx, XSCT Console) or XSDB (Unified IDE: Vitis, XSDB Console, or run xsdb from a Vivado/Vitis command prompt). Two commands do all the work: mwr address value writes a 32-bit word, and mrd address reads one.

Option A, quickest. Run any application once from Vitis (even an empty "Hello World"), with Program FPGA and Run ps7_init enabled. The logic is now programmed and the processor initialised. In the console:

Tcl console
connect
targets -set -nocase -filter {name =~ "*A9*#0"}
mrd 0x43C00000
Expected output
43C00000:   C4E55A01

Option B, no application at all. An .xsa file is a ZIP archive. Copy C:\chess\output\chess.xsa to chess.zip and extract it to C:\chess\output\hw: inside are the bitstream and ps7_init.tcl, the script that sets up the processor's clocks and DDR. Then this program does everything a C driver does: it loads the bitstream, initialises the processor, writes the starting position into the 24 board registers and META, starts a depth-4 search, waits for DONE and decodes the answer. Save it as C:\chess\scripts\by_hand.tcl, then type source C:/chess/scripts/by_hand.tcl in the console (use forward slashes, and your own bitstream file name).

Tcl console
# by_hand.tcl - send a position over AXI4-Lite and read the best move,
# with no C program. Every line is one 32-bit read or write.
connect
targets -set -nocase -filter {name =~ "APU*"}
rst -system                                  ;# reset the whole Zynq
after 2000
targets -set -nocase -filter {name =~ "xc7z020"}
fpga -file C:/chess/output/hw/system_wrapper.bit   ;# program the logic
targets -set -nocase -filter {name =~ "APU*"}
source C:/chess/output/hw/ps7_init.tcl
ps7_init                                     ;# clocks, DDR, MIO (UART)
ps7_post_config                              ;# enable the PS-to-PL level shifters
targets -set -nocase -filter {name =~ "*A9*#0"}

set BASE 0x43C00000
proc wr {off val} { global BASE; mwr [expr {$BASE + $off}] $val }
proc rd {off} { global BASE; return [lindex [mrd -value [expr {$BASE + $off}]] 0] }

# 1. Is the core there?
puts [format "ID        = 0x%08X (want 0xC4E55A01)" [rd 0x00]]

# 2. The start position: 12 boards x (low word, high word), from 0x40 to 0x9C.
#    White: pawns FF00, knights 42, bishops 24, rooks 81, queen 08, king 10.
#    Black: the same pieces, in the high words (ranks 5 to 8).
set words {0x0000FF00 0  0x42 0  0x24 0  0x81 0  0x08 0  0x10 0
           0 0x00FF0000  0 0x42000000  0 0x24000000  0 0x81000000  0 0x08000000  0 0x10000000}
for {set i 0} {$i < 24} {incr i} { wr [expr {0x40 + 4 * $i}] [lindex $words $i] }

# 3. META = side (0, White) | castling 1111 << 1 | en passant 64 << 5 = 0x81E
wr 0x18 0x81E
# 4. Depth 4, search mode, no node limit, then START.
wr 0x0C 4
wr 0x10 0
wr 0x14 0
wr 0x04 1

# 5. Wait for STATUS bit 1 (DONE).
while {([rd 0x08] & 2) == 0} { after 10 }

# 6. Read and decode the answer.
set m [rd 0x1C]
set f "abcdefgh"
set from [expr {$m & 63}]
set to   [expr {($m >> 6) & 63}]
set score [rd 0x20]
if {$score > 0x7FFFFFFF} { set score [expr {$score - 0x100000000}] }
puts [format "BEST_MOVE = 0x%X = %s%d%s%d" $m [string index $f [expr {$from & 7}]] [expr {($from >> 3) + 1}] \
                                           [string index $f [expr {$to & 7}]]   [expr {($to >> 3) + 1}]]
puts "SCORE     = $score"
puts "NODES     = [rd 0x24]"
puts "CYCLES    = [rd 0x2C]"

Expected output. These numbers come from making exactly these register accesses to the simulated core; the hardware must give the same move, score, node count and clock count:

Expected output
ID        = 0xC4E55A01 (want 0xC4E55A01)
BEST_MOVE = 0x481 = b1c3
SCORE     = 10
NODES     = 25933
CYCLES    = 844430

Read the move word yourself to check you understand it: 0x481 is binary 000 010010 000001. The low six bits are 1, square b1; the next six are 18, square c3; the top three are 0, no promotion. 844,430 clocks at 50 MHz is 17 ms for 25,933 positions.

What you seeMeaningFix
mrd prints an error such as "Memory read error" or "AXI slave error"nothing answers at that address, or the logic is not programmedcheck the Address Editor; run fpga and ps7_post_config again
ID reads 00000000 or a fixed patterna different block is at that addresscheck the Address Editor
The console hangs on the first mrdthe PL clock or the level shifters are offyou skipped ps7_init or ps7_post_config; FCLK_CLK0 must be enabled in the Zynq block
ID is right, STATUS never shows DONESTART was not seenread STATUS: if BUSY is 0 and DONE 0, re-write CONTROL with 1
A different movea board word is wrong or in the wrong orderread back META (rd 0x18) and compare every word with the list above
Code

The driver is a small header. First the register map and two functions that every other function uses: Xil_Out32 and Xil_In32, from the Xilinx board support package, write and read one 32-bit register.

Create sw/chess_pl.hpart 1 of 3
/* chess_pl.h - Cortex-A9 driver for the chess core (bare-metal, Vitis).
 * Everything here is reads and writes of 32-bit registers. */
#ifndef CHESS_PL_H
#define CHESS_PL_H

#include "xil_io.h"       /* Xil_In32, Xil_Out32          */
#include "xtime_l.h"      /* XTime_GetTime, COUNTS_PER_SECOND */
#include "chess.h"

/* The address from Vivado's Address Editor (also in xparameters.h). */
#ifndef CHESS_BASE
#define CHESS_BASE 0x43C00000U
#endif

#define REG_ID          0x00
#define REG_CONTROL     0x04
#define REG_STATUS      0x08
#define REG_DEPTH       0x0C
#define REG_MODE        0x10
#define REG_NODE_LIMIT  0x14
#define REG_META        0x18
#define REG_BEST_MOVE   0x1C
#define REG_SCORE       0x20
#define REG_NODES_LO    0x24
#define REG_CYCLES_LO   0x2C
#define REG_BOARDS      0x40

#define CTRL_START    1u
#define CTRL_ABORT    2u
#define STAT_BUSY     1u
#define STAT_DONE     2u
#define STAT_ABORTED  4u
#define STAT_FAULT    8u
#define CHESS_ID      0xC4E55A01u

static inline void pl_write(uint32_t offset, uint32_t value) {
    Xil_Out32(CHESS_BASE + offset, value);
}
static inline uint32_t pl_read(uint32_t offset) {
    return Xil_In32(CHESS_BASE + offset);
}
static inline uint64_t pl_read64(uint32_t lo_offset) {
    uint32_t lo = pl_read(lo_offset);
    return ((uint64_t)pl_read(lo_offset + 4) << 32) | lo;
}

/* 1 when the bitstream is loaded and the core answers at CHESS_BASE. */
static inline int pl_present(void) {
    return pl_read(REG_ID) == CHESS_ID;
}

Line by line

  1. xil_io.h comes with the Vitis board support package. Xil_Out32(addr, v) is a 32-bit store and Xil_In32(addr) a 32-bit load, through a volatile pointer, so the compiler can never remove, merge or reorder them. The standalone BSP maps the PL address range as device memory, so the processor sends them to the bus in program order too.
  2. CHESS_BASE is wrapped in #ifndef, so you can change it with a compiler symbol (-DCHESS_BASE=...) without editing the file.
  3. The REG_ offsets are byte offsets, exactly the ones in the register map of Step 32. The CTRL_ and STAT_ values are bit masks for CONTROL and STATUS.
  4. pl_read64 reads a 48-bit counter as two words, low first. The counters only change while the core is busy, and we read them after DONE, so the two halves always belong together.
  5. pl_present is the first thing any program should call: if the ID register is wrong, nothing else will work.

Writing a position is 24 board words plus one META word; then pl_start sets the depth and mode and writes START. pl_run waits for DONE and collects the results.

Add to sw/chess_pl.hpart 2 of 3
/* Send a position: 24 board words, then META. Board i is split in two:
 *   0x40 + 8*i  <- bits 31..0  (squares a1..h4)
 *   0x44 + 8*i  <- bits 63..32 (squares a5..h8)
 * All 24 are written every time, even zeros, so nothing is left over from
 * the previous position. The core ignores these writes while it is busy. */
static inline void pl_write_position(const Position *p) {
    int i;
    for (i = 0; i < 12; i++) {
        pl_write(REG_BOARDS + 8 * i,     (uint32_t)p->bb[i]);           /* low  */
        pl_write(REG_BOARDS + 8 * i + 4, (uint32_t)(p->bb[i] >> 32));   /* high */
    }
    pl_write(REG_META, (uint32_t)p->side                 /* bit 0          */
                     | ((uint32_t)p->castle << 1)        /* bits 4..1      */
                     | ((uint32_t)p->ep << 5));          /* bits 11..5     */
}

/* Start one search (perft_mode = 0) or perft (perft_mode = 1). Writing
 * START copies the whole shadow position into the core in one clock. */
static inline void pl_start(int depth, int perft_mode, uint32_t node_limit) {
    pl_write(REG_DEPTH, (uint32_t)depth);
    pl_write(REG_MODE, perft_mode ? 1u : 0u);
    pl_write(REG_NODE_LIMIT, node_limit);
    pl_write(REG_CONTROL, CTRL_START);
}

static inline int  pl_done(void)  { return (pl_read(REG_STATUS) & STAT_DONE) != 0; }
static inline void pl_abort(void) { pl_write(REG_CONTROL, CTRL_ABORT); }

typedef struct {
    Move     best;
    int      score;
    uint64_t nodes;
    uint64_t cycles;
    int      depth;      /* deepest iteration that finished */
} PlResult;

/* Run one search or perft and wait for it: send, start, poll, read.
 * This blocks; a game should use the Thinker below instead. */
static inline PlResult pl_run(const Position *p, int depth, int perft_mode) {
    PlResult r;
    pl_write_position(p);
    pl_start(depth, perft_mode, 0);
    while (!pl_done()) { }
    r.best   = (Move)pl_read(REG_BEST_MOVE);
    r.score  = (int32_t)pl_read(REG_SCORE);
    r.nodes  = pl_read64(REG_NODES_LO);
    r.cycles = pl_read64(REG_CYCLES_LO);
    r.depth  = depth;
    return r;
}

Line by line

  1. pl_write_position is the "transmit the board" function. The loop sends board i as two writes at 0x40 + 8i (low word, (uint32_t)bb keeps bits 31..0) and 0x44 + 8i (high word, bb >> 32).
  2. The META word is assembled with shifts and ORs to match the bit layout the RTL slices apart: side | castle << 1 | ep << 5.
  3. pl_start writes the three settings, then CONTROL = START. The order matters: START must be the last write, because the core takes its snapshot on that clock.
  4. pl_run (the rest of this snippet) is the blocking version: start, spin on pl_done(), then collect everything into a PlResult. It is ideal for tests; a game uses the non-blocking thinker below instead.

A game needs a time limit, and it must keep drawing the screen while the engine thinks. Thinker does iterative deepening: search depth 1, then 2, then 3, keeping the last finished answer, until the time budget runs out. Then it sends ABORT. The aborted search is thrown away, so the answer is always from a complete search. It never blocks: your main loop calls think_poll as often as it likes.

Add to sw/chess_pl.hpart 3 of 3
/* Iterative deepening under a time budget, without blocking: call
 * think_begin once, then think_poll from your main loop until it returns 1.
 * The answer always comes from the last iteration that finished. */
typedef struct {
    XTime    t0;
    uint64_t budget_ticks;
    int      max_depth, depth, abort_sent;
    PlResult result;
} Thinker;

static inline void think_begin(Thinker *t, const Position *p, int max_depth,
                               uint32_t budget_ms) {
    XTime_GetTime(&t->t0);
    t->budget_ticks = (uint64_t)COUNTS_PER_SECOND * budget_ms / 1000;
    t->max_depth = max_depth;
    t->depth = 1;
    t->abort_sent = 0;
    memset(&t->result, 0, sizeof t->result);
    pl_write_position(p);
    pl_start(t->depth, 0, 0);
}

static inline int think_poll(Thinker *t, PlResult *out) {
    if (!pl_done()) {                         /* still searching */
        XTime now;
        XTime_GetTime(&now);
        if (!t->abort_sent && (uint64_t)(now - t->t0) > t->budget_ticks) {
            pl_abort();                       /* out of time */
            t->abort_sent = 1;
        }
        return 0;
    }
    if (!(pl_read(REG_STATUS) & STAT_ABORTED)) {   /* this depth finished */
        int forced;
        t->result.best    = (Move)pl_read(REG_BEST_MOVE);
        t->result.score   = (int32_t)pl_read(REG_SCORE);
        t->result.nodes  += pl_read64(REG_NODES_LO);
        t->result.cycles += pl_read64(REG_CYCLES_LO);
        t->result.depth   = t->depth;
        forced = t->result.best == 0 || t->result.score >= MATE - MAX_PLY;
        if (t->depth < t->max_depth && !forced && !t->abort_sent) {
            pl_start(++t->depth, 0, 0);       /* go one ply deeper */
            return 0;
        }
    }
    *out = t->result;
    return 1;
}

#endif

Line by line

  1. think_begin notes the start time with the A9's global timer (XTime_GetTime, which counts at COUNTS_PER_SECOND), converts the budget from milliseconds to timer ticks, sends the position, and starts depth 1.
  2. think_poll first asks "is the core done?". If not, it checks the clock, and once the budget is used it sends ABORT exactly once (abort_sent), then returns 0: "not yet".
  3. When the core is done and was not aborted, this depth finished. Its move and score become the current answer, and the node and clock counts are added up.
  4. If there is depth left, time left, and the score is not already a forced mate, it starts the next depth with pl_start alone: the position is still in the shadow registers, so it does not need to be sent again.
  5. Otherwise, or if the last search was aborted, it returns 1 and the result of the deepest search that finished. An aborted search is never used: its move could be a half-examined mistake.

The bring-up program checks the ID, runs both perfts, searches depths 1 to 6, then thinks for one second, printing everything on the serial port:

Create sw/main_baremetal.c
/* main_baremetal.c - bring-up test on the Cortex-A9. Prints on the UART. */
#include <stdio.h>
#include "chess_pl.h"

static int check_perft(const char *name, const char *fen, int depth, uint64_t expected) {
    Position p;
    PlResult r;
    from_fen(fen, &p);
    r = pl_run(&p, depth, 1);
    printf("perft %-8s depth %d: %llu (expected %llu) %s, %llu clocks\r\n",
           name, depth, (unsigned long long)r.nodes, (unsigned long long)expected,
           r.nodes == expected ? "OK" : "FAIL", (unsigned long long)r.cycles);
    return r.nodes == expected;
}

int main(void) {
    const char *start_fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
    const char *kiwipete  = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1";
    static Thinker thinker;
    Position p;
    PlResult r;
    char text[6];
    int ok, d;

    printf("\r\nchess core bring-up\r\n");
    if (!pl_present()) {
        printf("FAIL: ID register reads %08lx\r\n", (unsigned long)pl_read(REG_ID));
        return 1;
    }
    printf("ID register OK\r\n");

    ok = check_perft("start", start_fen, 4, 197281);
    ok = check_perft("kiwipete", kiwipete, 3, 97862) && ok;
    if (!ok) {
        printf("PERFT FAILED: do not trust searches\r\n");
        return 1;
    }

    from_fen(start_fen, &p);
    for (d = 1; d <= 6; d++) {
        r = pl_run(&p, d, 0);
        move_to_text(r.best, text);
        printf("depth %d best %s score %d nodes %llu clocks %llu (%llu clocks/node)\r\n",
               d, text, r.score, (unsigned long long)r.nodes,
               (unsigned long long)r.cycles, (unsigned long long)(r.cycles / r.nodes));
    }

    think_begin(&thinker, &p, 20, 1000);
    while (!think_poll(&thinker, &r)) {
        /* your VGA and controller code keeps running here */
    }
    move_to_text(r.best, text);
    printf("1 second think: best %s score %d depth %d nodes %llu\r\n",
           text, r.score, r.depth, (unsigned long long)r.nodes);
    printf("DONE\r\n");
    return 0;
}

Prepare the board

  1. Set the Boot jumper to JTAG. Connect USB to PROG-UART and switch on.
  2. In Windows Device Manager, under Ports, find the board's COM port. Open it in PuTTY or Tera Term at 115200 baud, 8 data bits, no parity, 1 stop bit.

Create the application

Vitis Classic (2023.1 and earlier):

  1. Start Vitis with a workspace such as C:\chess\vitis.
  2. File, New, Application Project, Next.
  3. Create a new platform from hardware (XSA): browse to C:\chess\output\chess.xsa, Next.
  4. Name the application chess_test, processor ps7_cortexa9_0, Next. Keep the standalone domain, Next.
  5. Choose Empty Application (C), Finish.

Vitis Unified IDE (2023.2 and later):

  1. File, New Component, Platform. Name it chess_platform, choose your .xsa, operating system standalone, processor ps7_cortexa9_0. Build it from the Flow panel.
  2. File, New Component, Application. Name it chess_test and select the platform and its domain.

Add the code and run

  1. Copy c\chess.h, sw\chess_pl.h, sw\game.h and sw\main_baremetal.c into the application's src folder.
  2. If your Address Editor showed a different address, add -DCHESS_BASE=0x... to the compiler's other flags (Classic: right-click the application, C/C++ Build Settings, ARM v7 gcc compiler, Miscellaneous).
  3. Build the application.
  4. Run it. Classic: right-click the application, Run As, Launch Hardware. Unified: Run in the Flow panel. Make sure Program FPGA and Run ps7_init are enabled; they normally are for an XSA with a bitstream.

Expected on the serial terminal, from running this exact program against the simulated hardware:

Expected output
chess core bring-up
ID register OK
perft start    depth 4: 197281 (expected 197281) OK, 3186591 clocks
perft kiwipete depth 3: 97862 (expected 97862) OK, 1432430 clocks
depth 1 best b1c3 score 40 nodes 21 clocks 489 (23 clocks/node)
depth 2 best b1c3 score 10 nodes 238 clocks 7115 (29 clocks/node)
depth 3 best b1c3 score 40 nodes 2639 clocks 76208 (28 clocks/node)
depth 4 best b1c3 score 10 nodes 25933 clocks 844430 (32 clocks/node)
depth 5 best d2d4 score 30 nodes 199412 clocks 6684151 (33 clocks/node)
depth 6 best d2d4 score 10 nodes 1519394 clocks 55995067 (36 clocks/node)
1 second think: best d2d4 score 30 depth 5 nodes 228243
DONE

Everything except the last search line must match exactly. The one-second think depends on your clock speed; this output is for 50 MHz.

40Look inside the chip with an ILA

You should rarely need this, because simulation found the logic bugs. If the board disagrees with simulation, an Integrated Logic Analyzer (ILA) records real signals inside the running chip.

  1. Mark the signals you want in search_core.sv, for example:
    SystemVerilog
    (* mark_debug = "true" *) state_t state;
    (* mark_debug = "true" *) logic [4:0] ply;
    (* mark_debug = "true" *) move_t move_r;
    (* mark_debug = "true" *) logic signed [15:0] ret;
    
  2. Run synthesis and open the synthesized design. Choose Tools, Set Up Debug, Next. The marked nets are listed; pick the FCLK clock domain if asked, a sample depth such as 4096, and Finish.
  3. Save (Ctrl+S), then Generate Bitstream.
  4. With the board in JTAG mode, open Open Hardware Manager, Open Target, Auto Connect, then Program Device with the .bit and the .ltx probes file beside it.
  5. Start your program from Vitis with Program FPGA turned off, so it doesn't reload a bitstream. In the ILA window, set a trigger such as state == S_POP and click Run.

What to look for

  • Trigger on state leaving S_IDLE to catch the start of a search. The next few hundred samples should walk through S_ENTER, S_CLASSIFY, the generator wait and S_NEXT, just as in the trace figure of Step 31.
  • If state never leaves S_IDLE, START never arrived: look at the AXI side instead (s_axi_awvalid, s_axi_wvalid, s_axi_bvalid).
  • If ply climbs to 31 and stays there, the search is not returning: compare with the same position in simulation.
  • If the core finishes but the move differs from simulation, capture move_r at the root (ply == 0) and compare the sequence of moves tried with the C engine's move list for the same position.

Probing all 780 bits of a position is rarely useful. Start with the small signals.

Part 4

The playable game: UART in, VGA out

Part 3 proved the core on its own. Now it joins your GPU in one design, and the Cortex-A9 becomes the referee: it reads your moves from a serial terminal, checks them, draws the board with your samGL library, and hands the thinking to the hardware. Each step below ends with something you can check, and every program in this part was run, unchanged, against the simulated chess core plus models of your GPU and the UART.

41The plan: who does what

Goal: know exactly which part of the chip owns which job before writing any code.

Concept

Three workers share the board, and each does only what it is best at:

  • The chess core (PL) only searches. It gets a position, finds the best move, and says how good it thinks the position is. It knows nothing about the game's history, the screen, or you.
  • Your GPU (PL) only draws: a pixel, or a filled rectangle, into a 320 × 240 frame that it sends to the VGA monitor.
  • The Cortex-A9 (PS) runs the game. It reads keys from the UART, turns e2e4 into a move, checks the move is legal, keeps the history for repetitions and undo, decides what to draw, and starts and stops the chess core's searches.
One bus, two address windows. The processor reaches both your GPU and the chess core through the same AXI master port, M_AXI_GP0. Which one it talks to depends only on the address. The serial port is part of the processor system itself, so it needs no logic in the PL.

Here is the finished game, running in this page. It uses a JavaScript copy of the renderer you are about to write, drawing your own sprites into a 320 × 240 frame with your palette, and the same commands as the C program. Type e2e4 and press Enter.

The finished game. Left: the VGA screen. Right: the serial terminal on your PC. The evaluation bar on the left of the screen shows who the engine thinks is winning; the lamp is green on your turn and red while the engine thinks, and the bar under it fills as the thinking time runs out. The browser's engine is about 80 times slower than the FPGA, so here it searches less deeply.

One turn, step by step

  1. You type e2e4 and Enter in the terminal. Each key travels as one byte over the USB cable into the PS UART's receive FIFO.
  2. The main loop polls the UART. The line is complete, so it parses it into a move and checks it against the legal moves.
  3. The move is played on the Game. The renderer redraws only the four squares that changed.
  4. Now it is the engine's turn. The A9 writes the position into the core and presses START. The lamp turns red.
  5. While the core searches, the loop keeps running: it fills the thinking bar and would still read keys. Each time a depth finishes, the thinker starts the next one, until the time is up.
  6. The A9 reads the best move, plays it, redraws, updates the evaluation bar, and prints the move. Your turn again.

The files

FileFromJob
chess.hPart 1the rules: move generation, legality, FEN
chess_pl.hStep 39talks to the chess core over AXI, and the Thinker
game.hStep 47a game: history, legality of your moves, game over
samgl.h, sprites.hyour codeyour GPU library and your piece sprites
uart_in.hStep 44reads typed lines without ever waiting
render.hSteps 45 and 46draws the board, the bars and the lamp
main_game.cStep 47the game loop and the commands

42Put your GPU and the chess core in one design

Goal: one bitstream with both blocks, at known addresses, and the serial port enabled.

Concept

The Zynq gives its GP0 master port a 1 GB address window, from 0x4000_0000 to 0x7FFF_FFFF. An AXI interconnect splits that window between the blocks attached to it. Your library expects the GPU at 0x4000_0000 (or wherever XPAR_GPU_BASEADDR says), and the chess driver expects 0x43C0_0000. Each block gets a 4 KB or 64 KB slice; they must not overlap, and the Address Editor guarantees that.

BlockBase addressUsed by
Your GPU0x4000_0000GPU_BASEADDR in samgl.h
Chess core0x43C0_0000CHESS_BASE in chess_pl.h
PS UART00xE000_0000fixed inside the processor; uart_in.h and printf

On the PYNQ-Z2, UART0 is wired through MIO pins 14 and 15 to the same USB chip as the JTAG programmer, so one micro-USB cable programs the board and carries your moves. The board preset turns UART0 on at 115200 baud.

Do it
  1. Open the Vivado project that holds your GPU. (Or open chess_pynq from Step 34 and add your GPU's IP to it; the steps are the same.)
  2. Add the seven chess files: in the Flow Navigator, Add Sources, Add or create design sources, Add Files, select everything in C:\chess\rtl, untick Copy sources into project, Finish.
  3. Open the block design. Right-click an empty area, Add Module, choose chess_axi_top.
  4. Click Run Connection Automation, tick All Automation, OK. Vivado connects s_axi to the existing interconnect (adding a master port to it), and the clock and reset to the same ones your GPU's AXI port uses.
  5. Check the clock on chess_axi_top_0/aclk. If it is FCLK_CLK0 at 50 MHz, you are done. If your design runs the AXI bus faster, either check timing passes for the core at that speed (Step 37), or give the core its own 50 MHz clock with a second interconnect, as Step 35 describes.
  6. Double-click the Zynq block and open Peripheral I/O Pins (in some versions, MIO Configuration, I/O Peripherals). Check that UART 0 is ticked on MIO 14 .. 15. OK.
  7. Open the Address Editor. You should see two rows under processing_system7_0 / Data: your GPU at 0x4000_0000 and chess_axi_top_0 at 0x43C0_0000. If Vivado picked other addresses, either change them here, or remember them for Step 43.
  8. F6 to validate, Ctrl+S, then Generate Bitstream. Check timing as in Step 37.
  9. File, Export, Export Hardware, choose Include bitstream, and save it as C:\chess\output\chess_game.xsa.
Check

The implemented design's utilisation report should show your GPU's resources plus about 11,400 LUTs and 16 block RAMs for the chess core. If the bitstream builds and timing is met, the hardware side is finished: everything from here is C.

43Create the game application in Vitis

Goal: an empty bare-metal C application, built for the new hardware, with every file in place.

  1. Start Vitis with the workspace C:\chess\vitis.
  2. Create a platform from chess_game.xsa: in the Unified IDE, File, New Component, Platform, name it game_platform, operating system standalone, processor ps7_cortexa9_0, and build it. (Vitis Classic: File, New, Platform Project.)
  3. In the platform's standalone settings, check that stdin and stdout are ps7_uart_0. They are by default.
  4. Create an application component named chess_game on that platform, starting from Empty Application (C).
  5. Copy these files into the application's src folder:
    Command Prompt
    copy C:\chess\c\chess.h        C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\chess_pl.h    C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\game.h        C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\samgl.h       C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\sprites.h     C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\uart_in.h     C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\render.h      C:\chess\vitis\chess_game\src\
    copy C:\chess\sw\main_game.c   C:\chess\vitis\chess_game\src\
  6. Build with optimisation. Unified IDE: open the application's Settings (UserConfig.cmake) and set the optimisation level to -O2, or choose the Release configuration. Classic: right-click the application, C/C++ Build Settings, ARM v7 gcc compiler, Optimization, -O2. A debug build at -O0 works too, just with slower drawing.
  7. If the Address Editor showed other addresses, add them as compiler symbols, for example CHESS_BASE=0x43C10000. The GPU address comes from xparameters.h automatically if your GPU IP exports XPAR_GPU_BASEADDR.

sprites.h is your PieceBitmap array moved into its own file, exactly as it was. It is in the ZIP, but it is only data, so it is not printed in this guide.

44Read keys from the UART without ever waiting

Goal: collect typed lines while the screen and the engine keep running.

Concept

The obvious way to read a line is scanf or getchar. Both block: the processor sits inside them until you press Enter. While it waits, nothing else in the loop runs: the thinking bar would freeze, and, worse, the A9 could not collect the engine's answer.

So we poll instead. The UART has a 64-byte receive FIFO that fills by itself as bytes arrive, whatever the processor is doing. Each time round the main loop, we look at its status register. If the FIFO is empty we return at once; if not, we take every byte waiting, add it to a line buffer, and report a finished line when we see Enter. A human types perhaps ten keys a second, and the loop runs millions of times a second, so nothing is ever lost.

Only two of the UART's registers are needed. Both names come from xuartps_hw.h, part of Vitis's standalone library:

RegisterOffsetWhat we use
Channel status, XUARTPS_SR_OFFSET0x2Cbit 1, RXEMPTY: 1 while the receive FIFO is empty. XUartPs_IsReceiveData tests it.
FIFO, XUARTPS_FIFO_OFFSET0x30reading takes the oldest received byte
From keys to a move. Each key you type is one byte; the hex code shows what really crosses the cable. Nothing happens until Enter, then the line is parsed into the 15-bit move word from Step 2 and checked against the legal moves. Try e2e5 (not legal) and hello (not a move).
Code
Create sw/uart_in.h
/* uart_in.h - read typed lines from the PS UART without ever waiting.
 * On the PYNQ-Z2, UART0 is wired to the USB serial port (PROG/UART). */
#ifndef UART_IN_H
#define UART_IN_H

#include "xuartps_hw.h"      /* register names and the IsReceiveData macro */
#include "xparameters.h"

#ifndef UART_BASE
#  ifdef STDIN_BASEADDRESS
#    define UART_BASE STDIN_BASEADDRESS   /* the UART printf already uses */
#  else
#    define UART_BASE 0xE0000000u         /* PS UART0 */
#  endif
#endif

#define LINE_MAX 96          /* long enough for "fen" plus a full FEN */

typedef struct {
    char text[LINE_MAX];     /* the finished line, 0-terminated */
    int  len;                /* characters typed so far         */
} LineReader;

/* Take every byte waiting in the receive FIFO. Returns 1 when Enter
 * finishes a line (now in r->text), 0 if the line is not finished yet.
 * Typed characters are echoed, and Backspace works. */
static int uart_poll_line(LineReader *r) {
    while (XUartPs_IsReceiveData(UART_BASE)) {
        char c = (char)XUartPs_ReadReg(UART_BASE, XUARTPS_FIFO_OFFSET);

        if (c == '\r' || c == '\n') {             /* Enter */
            if (r->len == 0) continue;            /* ignore empty lines and \r\n */
            r->text[r->len] = '\0';
            r->len = 0;
            XUartPs_SendByte(UART_BASE, '\r');
            XUartPs_SendByte(UART_BASE, '\n');
            return 1;
        }
        if (c == '\b' || c == 127) {              /* Backspace or Delete */
            if (r->len > 0) {
                r->len--;
                XUartPs_SendByte(UART_BASE, '\b');  /* erase it on screen */
                XUartPs_SendByte(UART_BASE, ' ');
                XUartPs_SendByte(UART_BASE, '\b');
            }
            continue;
        }
        if (c >= ' ' && c <= '~' && r->len < LINE_MAX - 1) {
            r->text[r->len++] = c;
            XUartPs_SendByte(UART_BASE, (u8)c);     /* echo */
        }
    }
    return 0;
}

#endif

Three details. Echo: the terminal does not show what you type unless the board sends it back, so every accepted character is written back with XUartPs_SendByte. Line endings: terminals send Enter as \r, \n or both; the empty-line check swallows the second half of a \r\n pair. Backspace: the "back, space, back" sequence erases the character on screen too.

STDIN_BASEADDRESS is the UART that the BSP connected to printf, so the game's input and output always use the same port.

Line by line: typing e2e4 and Enter

  1. The loop calls uart_poll_line perhaps a million times before you press the first key. Each time, XUartPs_IsReceiveData reads the status register, sees RXEMPTY = 1, and the function returns 0 at once.
  2. You press e. The byte 0x65 arrives over USB and lands in the receive FIFO. On the next call the while condition is true, XUartPs_ReadReg takes the byte, it is printable, so it goes into text[0], len becomes 1, and the byte is echoed. The FIFO is now empty, the while ends, and the function returns 0: the line is not finished.
  3. 2, e, 4 follow the same path. text holds "e2e4", len is 4.
  4. You press Enter. PuTTY sends \r (0x0D). The function writes the terminating \0, resets len to 0 for the next line, moves the cursor to a new line on your screen, and returns 1. The caller now reads line.text.
  5. If your terminal sends \r\n, the \n arrives with len = 0 and is skipped by continue, so one Enter is always one line.
  6. Characters beyond LINE_MAX − 1 are dropped, so a long paste can never overflow the buffer.

45Your library, the layout, and sprites as runs

Goal: draw one piece as fast as your GPU allows, using only your library.

Concept

Your library has two ways to draw. samGL_DrawPixel writes three registers (X, Y, colour) per pixel. samGL_HardwareDrawRect writes six registers (X, Y, width, height, colour, START), and then the GPU fills the whole rectangle by itself. A rectangle costs twice as much as a pixel to start, but any rectangle wider than two pixels is a bargain.

A sprite row is mostly long stretches of one colour: transparent, then outline, then body. So the renderer cuts each row into runs of one colour and draws every visible run as a one-pixel-high rectangle. Transparent runs are simply skipped, so the square's colour shows through.

Your sprites are 16 × 16, drawn at 24 × 24. Your SpriteScaleMap table says which source pixel each screen pixel copies: every second source pixel is used twice, so 16 become 24. This is nearest-neighbour scaling, the same thing a game console does, and it keeps the pixel-art edges sharp.

Scaling and runs. Left: your sprite as stored. Right: as drawn, 1.5 times larger; outlined boxes are the runs. Switch to Per pixel to compare: runs need 20 to 45% fewer register writes, depending on the piece.
Code

First, your library, unchanged except that each function is now static inline, so the header can be included safely:

Create sw/samgl.h
/* samgl.h - your GPU library, moved into a header so every file can use it.
 * The only change: each function is "static inline", so including the header in
 * more than one place cannot cause duplicate definitions. */
#ifndef SAMGL_H
#define SAMGL_H
// INTERNAL -----------------
#include <stdio.h>
#include "xil_io.h"
#include "xparameters.h"
#include "sleep.h"

// Base ADD
#ifdef XPAR_GPU_BASEADDR
#define GPU_BASEADDR XPAR_GPU_BASEADDR
#else
#define GPU_BASEADDR 0x40000000
#endif

// AXI
#define REG_GPU_STATUS   0x00
#define REG_PIXEL_X      0x30
#define REG_PIXEL_Y      0x34
#define REG_PIXEL_COLOR  0x38
#define REG_RECT_W       0x3C
#define REG_RECT_H       0x40
#define REG_START        0x44
#define REG_VERSION      0x48
#define GPU_WRITE(offset, data) Xil_Out32(GPU_BASEADDR + (offset), (u32)(data))
#define GPU_READ(offset)        Xil_In32(GPU_BASEADDR + (offset))



#define RGB444(r, g, b) (((r & 0xF) << 8) | ((g & 0xF) << 4) | (b & 0xF))
#define PAL_INDEX(r, g, b) ((((r) / 2) * 32) + (((g) / 2) * 4) + ((b) / 4))
#define SCREEN_W 320
#define SCREEN_H 240


// GPU Library //
static inline void samGL_DrawPixel(u32 x, u32 y, u16 color) {
    if (x >= SCREEN_W || y >= SCREEN_H) return;
    GPU_WRITE(REG_PIXEL_X, x);
    GPU_WRITE(REG_PIXEL_Y, y);
    GPU_WRITE(REG_PIXEL_COLOR, color);
}

static inline void samGL_DrawRect(u32 start_x, u32 start_y, u32 width, u32 height, u16 color) {
    for (u32 y = start_y; y < start_y + height; y++) {
        for (u32 x = start_x; x < start_x + width; x++) {
            samGL_DrawPixel(x, y, color);
        }
    }
}

static inline void samGL_ClearScreen_CPU(u16 color) {
    for (u32 y = 0; y < SCREEN_H; y++) {
        for (u32 x = 0; x < SCREEN_W; x++) {
            samGL_DrawPixel(x, y, color);
        }
    }
}

static inline void samGL_Flush(void) {
    while (GPU_READ(REG_GPU_STATUS) & 0x01) {
        // wait
    }
}

static inline void samGL_HardwareDrawRect(u32 x, u32 y, u32 w, u32 h, u16 color) {
    samGL_Flush();
    GPU_WRITE(REG_PIXEL_X, x);
    GPU_WRITE(REG_PIXEL_Y, y);
    GPU_WRITE(REG_RECT_W, w);
    GPU_WRITE(REG_RECT_H, h);
    GPU_WRITE(REG_PIXEL_COLOR, color);
    GPU_WRITE(REG_START, 1);
}

static inline void samGL_HardwareClearScreen(u16 color) {
    samGL_Flush();
    samGL_HardwareDrawRect(0, 0, SCREEN_W, SCREEN_H, color);
}

static inline void samGL_Init(){
    u32 hw_version = GPU_READ(REG_VERSION);
    printf("\n==========================================\n");
    printf("FPGA GPU Hardware Version: 0x%08X\n", hw_version);
    printf("=-=-BY SWR06-=-=\n");
    printf("==========================================\n\n");
}

#endif

The layout keeps your board exactly where it was (28-pixel squares, centred) and uses the two 48-pixel margins: an evaluation bar on the left, and a lamp and thinking bar on the right. Colours are your palette indexes, made with your PAL_INDEX macro. Its 3-3-2 format has only four levels of blue, so the highlight colours were picked from the strong reds, yellows and greens it can show.

Create sw/render.hpart 1 of 4
/* render.h - draws the game with your samGL library.
 * Two ideas keep it fast: only squares that changed are redrawn, and
 * sprites are drawn as horizontal runs by the rectangle engine. */
#ifndef RENDER_H
#define RENDER_H

#include <string.h>
#include "samgl.h"
#include "sprites.h"
#include "chess.h"

/* Layout on the 320 x 240 screen. The board is centred, as in your code. */
#define SQ_PX     28                              /* one square            */
#define PIECE_PX  24                              /* a 16 px sprite at 1.5x */
#define BOARD_PX  (8 * SQ_PX)                     /* 224                   */
#define BOARD_X   ((SCREEN_W - BOARD_PX) / 2)     /* 48                    */
#define BOARD_Y   ((SCREEN_H - BOARD_PX) / 2)     /* 8                     */
#define FRAME_PX  3
#define EVAL_X    18                              /* evaluation bar, left  */
#define EVAL_W    12
#define SIDE_X    (BOARD_X + BOARD_PX + FRAME_PX + 14)   /* right column  */
#define LAMP_PX   12                              /* whose-turn lamp       */
#define THINK_Y   (BOARD_Y + LAMP_PX + 8)         /* thinking bar          */
#define THINK_W   LAMP_PX
#define THINK_H   (BOARD_Y + BOARD_PX - THINK_Y)

/* Colours, as indexes into your 3-3-2 palette. */
enum {
    COL_BACKGROUND = PAL_INDEX(2, 4, 0),    /* your theme ...          */
    COL_FRAME      = PAL_INDEX(4, 2, 0),
    COL_LIGHT      = PAL_INDEX(14, 12, 8),
    COL_DARK       = PAL_INDEX(10, 6, 4),
    COL_LAST_LIGHT = PAL_INDEX(14, 14, 4),  /* ... plus highlights     */
    COL_LAST_DARK  = PAL_INDEX(12, 10, 0),
    COL_CHECK      = PAL_INDEX(14, 2, 0),
    COL_WHITE      = PAL_INDEX(14, 14, 12),
    COL_BLACK      = PAL_INDEX(0, 0, 0),
    COL_YOUR_TURN  = PAL_INDEX(4, 12, 4),   /* lamp colours            */
    COL_THINKING   = PAL_INDEX(12, 2, 0),
    COL_GAME_OVER  = PAL_INDEX(14, 14, 4),
    COL_THINK_BAR  = PAL_INDEX(6, 10, 14)
};

/* What the screen shows, so we can redraw only what changes.
 * cell[sq] = sprite number + 1 (0 = empty), plus a highlight in bits 4-5. */
enum { MARK_NONE = 0, MARK_LAST = 1, MARK_CHECK = 2 };
#define CELL(sprite1, mark) ((uint8_t)((sprite1) | ((mark) << 4)))
#define CELL_UNKNOWN 0xFF

typedef struct {
    uint8_t cell[64];
    int     flipped;        /* 1 = Black at the bottom              */
    int     think_rows;     /* rows of the thinking bar filled so far */
} Screen;

The Screen struct is the renderer's memory of what the monitor shows right now. One byte per square is enough: which sprite (0 to 12) and which highlight (none, last move, check). Step 46 uses it to skip squares that are already right.

Add to sw/render.hpart 2 of 4
/* Your 1.5x scaling table: destination pixel -> sprite pixel. */
static const u8 SpriteScaleMap[PIECE_PX] = {
    0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7,
    8, 9, 9, 10, 11, 11, 12, 13, 13, 14, 15, 15
};

/* Sprite order is K Q B N R P (black, then white). Engine order is
 * PAWN KNIGHT BISHOP ROOK QUEEN KING, so translate with a table. */
static const u8 SPRITE_OF_TYPE[6] = { 5, 3, 2, 4, 1, 0 };

/* Sprite number + 1 of the piece on sq, or 0 for an empty square. */
static int sprite_on(const Position *p, int sq) {
    int i;
    for (i = 0; i < 12; i++)
        if (p->bb[i] & BIT(sq))
            return (i / 6 == WHITE ? 6 : 0) + SPRITE_OF_TYPE[i % 6] + 1;
    return 0;
}

/* Draw one sprite with its top-left corner at (x0, y0). Each row is cut
 * into runs of one colour; every visible run is one hardware rectangle,
 * instead of one AXI write sequence per pixel. */
static void draw_sprite(int sprite, u32 x0, u32 y0) {
    const u16 *pixels = PieceBitmap + sprite * PIECE_SPRITE_PIXELS;
    u32 dy, dx, start;

    for (dy = 0; dy < PIECE_PX; dy++) {
        const u16 *row = pixels + SpriteScaleMap[dy] * PIECE_SPRITE_W;
        for (dx = 0; dx < PIECE_PX; ) {
            u16 colour = row[SpriteScaleMap[dx]];
            start = dx;
            while (dx < PIECE_PX && row[SpriteScaleMap[dx]] == colour) dx++;
            if (colour != SPRITE_TRANSPARENT)
                samGL_HardwareDrawRect(x0 + start, y0 + dy, dx - start, 1, colour);
        }
    }
}

The engine numbers pieces PAWN = 0 to KING = 5; your sprites go king, queen, bishop, knight, rook, pawn. SPRITE_OF_TYPE translates, so neither side has to change. In draw_sprite, the inner while extends a run as long as the next pixel has the same colour; when it stops, dx − start is the run's width.

Why not keep DrawPixel?

It works, and it is what your prototype does. Drawing the 32 pieces of the starting position pixel by pixel takes 25,944 register writes; as runs, 17,856. That saving is real but modest. The next step matters far more: most frames redraw only four squares.

46Redraw only what changed

Goal: update the screen after a move in about a tenth of the work of a full redraw, with no flicker.

Concept

Your prototype clears the screen and redraws everything after each move. On the GPU that is about 18,000 register writes, and for a moment the screen shows an empty board: that is the flicker you may have seen.

Instead, the renderer remembers what each square shows (the Screen struct), works out what each square should show, and redraws only the squares where the two differ. After a normal move that is four squares: the two squares of the new move, which become highlighted, and the two squares of the previous move, which lose their highlight. Castling adds the rook's two squares. A check adds the king's square.

Dirty squares. Step through a short game. Outlined squares are the only ones redrawn. The counts are the renderer's real register writes.
Code
Add to sw/render.hpart 3 of 4
/* Screen position of a square. a1 is bottom-left unless flipped. */
static void square_xy(const Screen *s, int sq, u32 *x, u32 *y) {
    int file = sq & 7, rank = sq >> 3;
    int col = s->flipped ? 7 - file : file;
    int row = s->flipped ? rank : 7 - rank;
    *x = BOARD_X + col * SQ_PX;
    *y = BOARD_Y + row * SQ_PX;
}

static void draw_cell(const Screen *s, int sq, uint8_t cell) {
    int light = ((sq >> 3) + (sq & 7)) & 1;     /* a1 (0 + 0) is dark */
    int mark = cell >> 4, sprite1 = cell & 15;
    u16 colour = light ? COL_LIGHT : COL_DARK;
    u32 x, y;

    if (mark == MARK_LAST)  colour = light ? COL_LAST_LIGHT : COL_LAST_DARK;
    if (mark == MARK_CHECK) colour = COL_CHECK;
    square_xy(s, sq, &x, &y);
    samGL_HardwareDrawRect(x, y, SQ_PX, SQ_PX, colour);
    if (sprite1)
        draw_sprite(sprite1 - 1, x + (SQ_PX - PIECE_PX) / 2, y + (SQ_PX - PIECE_PX) / 2);
}

/* Bring the board up to date with position p. "last" is the move just
 * played (0 for none); its squares are highlighted, and so is a king in
 * check. Returns how many squares had to be redrawn. */
static int render_board(Screen *s, const Position *p, Move last) {
    uint8_t want[64];
    int sq, redrawn = 0;

    for (sq = 0; sq < 64; sq++) want[sq] = CELL(sprite_on(p, sq), MARK_NONE);
    if (last) {
        want[MOVE_FROM(last)] |= MARK_LAST << 4;
        want[MOVE_TO(last)]   |= MARK_LAST << 4;
    }
    if (in_check(p)) {
        sq = lsb(p->bb[p->side * 6 + KING]);
        want[sq] = (uint8_t)((want[sq] & 15) | (MARK_CHECK << 4));
    }
    for (sq = 0; sq < 64; sq++) {
        if (want[sq] != s->cell[sq]) {
            draw_cell(s, sq, want[sq]);
            s->cell[sq] = want[sq];
            redrawn++;
        }
    }
    samGL_Flush();
    return redrawn;
}

render_board is the whole idea in twenty lines. It builds want, compares it with s->cell, and draws the differences. Because it compares the final picture, not the move, it never needs special cases: castling, en passant and promotion all just work. And any time the screen might be wrong, after "new" or "flip", setting every cell to CELL_UNKNOWN forces a full redraw.

Add to sw/render.hpart 4 of 4
/* The lamp above the thinking bar: green = your move, red = thinking. */
static void render_lamp(u16 colour) {
    samGL_HardwareDrawRect(SIDE_X - 1, BOARD_Y - 1, LAMP_PX + 2, LAMP_PX + 2, COL_FRAME);
    samGL_HardwareDrawRect(SIDE_X, BOARD_Y, LAMP_PX, LAMP_PX, colour);
    samGL_Flush();
}

/* Evaluation bar: White's share grows upward from the bottom (from the
 * top when flipped). white_cp is the score from White's view, in
 * centipawns; +/-800 or more fills almost the whole bar. */
static void render_eval(const Screen *s, int white_cp) {
    int lim = 800, white_px;
    if (white_cp > lim) white_cp = lim;
    if (white_cp < -lim) white_cp = -lim;
    white_px = BOARD_PX / 2 + white_cp * (BOARD_PX / 2 - 8) / lim;
    if (s->flipped) {
        samGL_HardwareDrawRect(EVAL_X, BOARD_Y, EVAL_W, white_px, COL_WHITE);
        samGL_HardwareDrawRect(EVAL_X, BOARD_Y + white_px, EVAL_W, BOARD_PX - white_px, COL_BLACK);
    } else {
        samGL_HardwareDrawRect(EVAL_X, BOARD_Y, EVAL_W, BOARD_PX - white_px, COL_BLACK);
        samGL_HardwareDrawRect(EVAL_X, BOARD_Y + BOARD_PX - white_px, EVAL_W, white_px, COL_WHITE);
    }
    samGL_Flush();
}

/* Thinking bar: empty it, then fill it from the bottom as time passes.
 * Only the newly filled rows are drawn, so calling it often is cheap. */
static void render_think_clear(Screen *s) {
    samGL_HardwareDrawRect(SIDE_X, THINK_Y, THINK_W, THINK_H, COL_FRAME);
    s->think_rows = 0;
}

static void render_think(Screen *s, u32 elapsed_ms, u32 budget_ms) {
    int rows = (int)((uint64_t)THINK_H * elapsed_ms / budget_ms);
    if (rows > THINK_H) rows = THINK_H;
    if (rows > s->think_rows) {
        samGL_HardwareDrawRect(SIDE_X, THINK_Y + THINK_H - rows, THINK_W,
                               rows - s->think_rows, COL_THINK_BAR);
        s->think_rows = rows;
    }
}

/* Draw everything from scratch: after reset, "new" or "flip". */
static void render_all(Screen *s, const Position *p, Move last, int white_cp) {
    samGL_HardwareClearScreen(COL_BACKGROUND);
    samGL_HardwareDrawRect(BOARD_X - FRAME_PX, BOARD_Y - FRAME_PX,
                           BOARD_PX + 2 * FRAME_PX, BOARD_PX + 2 * FRAME_PX, COL_FRAME);
    samGL_HardwareDrawRect(EVAL_X - 1, BOARD_Y - 1, EVAL_W + 2, BOARD_PX + 2, COL_FRAME);
    memset(s->cell, CELL_UNKNOWN, sizeof s->cell);   /* forces a full redraw */
    render_board(s, p, last);
    render_eval(s, white_cp);
    render_think_clear(s);
}

#endif

The evaluation bar converts the engine's score to White's point of view, clamps it to ±800 centipawns (eight pawns: a decisive advantage), and splits the bar's 224 pixels. The thinking bar draws only the rows it has not drawn yet, so the main loop can call render_think every time round without flooding the bus.

Check

This frame comes from running main_game.c against models of your GPU and the UART and the real chess core in simulation, right after you play e2e4 and the engine answers b8c6. Only the last move is highlighted, the evaluation bar leans slightly to White (the engine scored −25 for itself), the lamp is green and the thinking bar has been emptied for your turn:

The game screen after 1. e4 Nc6: b8 and c6 highlighted, evaluation bar slightly in White's favour, green lamp
Simulated VGA output, at twice the real size.

47The game loop

Goal: tie the UART, the rules, the renderer and the chess core together, in one loop that never blocks.

Concept

The core only finds moves. It has no memory of the game, so it cannot see a repeated position or the fifty-move rule, and it does not check your moves. The Cortex-A9 does that, with the same chess.h:

Create sw/game.h
/* game.h - the rules the hardware does not know: is the human's move legal,
 * and is the game over? Your game loop owns one Game (make it static: it
 * holds the position history). */
#ifndef GAME_H
#define GAME_H

#include "chess.h"

#define MAX_HISTORY 128

typedef enum {
    GAME_PLAYING, GAME_CHECKMATE, GAME_STALEMATE, GAME_REPETITION, GAME_FIFTY_MOVES
} GameState;

typedef struct {
    Position current;
    Position history[MAX_HISTORY];   /* positions since the last pawn move or capture */
    int      history_count;
    int      quiet_plies;            /* fifty-move counter, in plies */
} Game;

static inline void game_init(Game *g, const Position *start) {
    g->current = *start;
    g->history[0] = *start;
    g->history_count = 1;
    g->quiet_plies = 0;
}

/* 1 if move m is legal in the current position. */
static inline int game_is_legal(const Game *g, Move m) {
    Move list[MAX_MOVES];
    int n = generate_moves(&g->current, list, 0), i;
    for (i = 0; i < n; i++) {
        if (list[i] == m) {
            Position child = g->current;
            make_move(&child, m);
            return legal_after(&child, m);
        }
    }
    return 0;
}

/* Play a move that is already known to be legal. */
static inline void game_play(Game *g, Move m) {
    int pawn_move = (g->current.bb[g->current.side * 6 + PAWN] & BIT(MOVE_FROM(m))) != 0;
    int capture   = (occupied(&g->current) & BIT(MOVE_TO(m))) != 0;
    make_move(&g->current, m);
    if (pawn_move || capture) {          /* no earlier position can repeat */
        g->history_count = 0;
        g->quiet_plies = 0;
    } else {
        g->quiet_plies++;
    }
    if (g->history_count < MAX_HISTORY) g->history[g->history_count++] = g->current;
}

static inline int same_position(const Position *a, const Position *b) {
    return memcmp(a->bb, b->bb, sizeof a->bb) == 0 && a->side == b->side
        && a->castle == b->castle && a->ep == b->ep;
}

static inline GameState game_state(const Game *g) {
    Move list[MAX_MOVES];
    int n = generate_moves(&g->current, list, 0), i, any_legal = 0, repeats = 0;
    for (i = 0; i < n && !any_legal; i++) {
        Position child = g->current;
        make_move(&child, list[i]);
        any_legal = legal_after(&child, list[i]);
    }
    if (!any_legal) return in_check(&g->current) ? GAME_CHECKMATE : GAME_STALEMATE;
    if (g->quiet_plies >= 100) return GAME_FIFTY_MOVES;
    for (i = 0; i < g->history_count; i++)
        if (same_position(&g->history[i], &g->current)) repeats++;
    return repeats >= 3 ? GAME_REPETITION : GAME_PLAYING;
}

#endif

Line by line

  1. Game holds the current position plus every position since the last pawn move or capture. Only those can ever repeat, because pawn moves and captures cannot be undone. quiet_plies counts towards the fifty-move rule (100 plies).
  2. game_is_legal checks a move from the human: it must appear in the generated list, and the mover's king must be safe afterwards. The same two tests the engine uses, so the human and the engine play by exactly the same rules.
  3. game_play makes the move. A pawn move or capture resets the history and the counter; then the new position is appended.
  4. game_state decides whether the game is over. No legal move: checkmate if in check, else stalemate. Then the fifty-move rule. Then repetition: the current position appearing three times in the history.
  5. same_position compares boards, side, rights and en-passant square: two positions are "the same" for repetition only if all of these match.

The game itself is a small state machine with three modes. Every change to the game goes through one function, next_turn, which redraws and then decides the next mode, so the screen can never fall out of step with the game.

The three modes. The main loop always polls the UART; in ENGINE_THINKING it also polls the core and fills the thinking bar.
Code

All state is static. Game holds up to 128 positions of history, about 14 KB, and the bare-metal stack is small. THINK_MS is the engine's time per move: 2 seconds gives depth 6 or 7 in the middle game.

Create sw/main_game.cpart 1 of 5
/* main_game.c - play chess on the PYNQ-Z2.
 * You type moves on a serial terminal. The Cortex-A9 checks them, draws the
 * board with samGL, and asks the chess core in the PL for its reply. */
#include <stdio.h>
#include <string.h>
#include "chess_pl.h"
#include "game.h"
#include "render.h"
#include "uart_in.h"

#ifndef THINK_MS
#define THINK_MS 2000            /* the engine's time per move        */
#endif
#define MAX_DEPTH      20        /* iterative deepening stops here     */
#define MAX_GAME_PLIES 512

static const char *START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

typedef enum { WAIT_HUMAN, ENGINE_THINKING, GAME_OVER } Mode;

/* Everything lives in static variables: Game alone is about 14 KB. */
static Game       game;                  /* position + repetition history */
static Thinker    thinker;               /* the engine's search, in the PL */
static Screen     screen;                /* what the VGA screen shows      */
static LineReader line;                  /* the line being typed           */
static Position   start_pos;             /* for "undo", which replays      */
static Move       played[MAX_GAME_PLIES];
static int        played_count;
static Mode       mode;
static int        engine_side = BLACK;
static Move       last_move;
static int        eval_white;            /* engine's last score, White's view */

Parsing works in two steps: first the shape of the text, then the rules. Building the move from the text and asking game_is_legal means the parser needs no chess knowledge of its own: castling (e1g1) and en passant are just moves in the legal list. A pawn reaching the last rank without a letter becomes a queen, because that is nearly always what you want.

Add to sw/main_game.cpart 2 of 5
/* Turn "e2e4" or "e7e8q" into a legal Move, or 0. Castling is the king's
 * two-square move (e1g1). A promotion without a letter becomes a queen. */
static Move parse_move(const Game *g, const char *s) {
    int from, to, promo = 0;
    if (strlen(s) < 4 || strlen(s) > 5) return 0;
    if (s[0] < 'a' || s[0] > 'h' || s[1] < '1' || s[1] > '8') return 0;
    if (s[2] < 'a' || s[2] > 'h' || s[3] < '1' || s[3] > '8') return 0;
    from = (s[0] - 'a') + 8 * (s[1] - '1');
    to   = (s[2] - 'a') + 8 * (s[3] - '1');
    if (s[4]) {
        static const char LETTERS[] = "nbrq";            /* KNIGHT=1 ... QUEEN=4 */
        const char *p = strchr(LETTERS, s[4]);
        if (!p) return 0;
        promo = KNIGHT + (int)(p - LETTERS);
    } else if ((g->current.bb[g->current.side * 6 + PAWN] & BIT(from))
               && (to >> 3 == 0 || to >> 3 == 7)) {
        promo = QUEEN;
    }
    return game_is_legal(g, MAKE_MOVE(from, to, promo)) ? MAKE_MOVE(from, to, promo) : 0;
}

/* The board as text on the terminal: White in capitals, rank 8 on top. */
static void print_board(const Position *p) {
    static const char LETTER[] = "PNBRQKpnbrqk";
    int rank, file, i;
    for (rank = 7; rank >= 0; rank--) {
        printf("  %d ", rank + 1);
        for (file = 0; file < 8; file++) {
            char c = '.';
            for (i = 0; i < 12; i++)
                if (p->bb[i] & BIT(rank * 8 + file)) c = LETTER[i];
            printf(" %c", c);
        }
        printf("\r\n");
    }
    printf("     a b c d e f g h\r\n");
}

static void print_help(void) {
    printf("Type a move like e2e4 (castle: e1g1, promote: e7e8q), or:\r\n"
           "  new    start again        undo   take back your last move\r\n"
           "  go     engine plays now   stop   engine moves at once\r\n"
           "  flip   turn the board     board  print the board here\r\n"
           "  fen <FEN>  set up a position\r\n");
}

undo does not try to reverse moves. It replays the game from the start, minus the last moves, which is simple and keeps the repetition history exactly right. Replaying a few hundred moves takes well under a millisecond.

Add to sw/main_game.cpart 3 of 5
static void play(Move m) {
    game_play(&game, m);
    played[played_count++] = m;
    last_move = m;
}

static void start_thinking(void) {
    mode = ENGINE_THINKING;
    render_lamp(COL_THINKING);
    render_think_clear(&screen);
    think_begin(&thinker, &game.current, MAX_DEPTH, THINK_MS);
}

/* Called after every change to the game: redraw, then decide who moves. */
static void next_turn(void) {
    static const char *const RESULT[] = { "", "checkmate", "stalemate, a draw",
        "threefold repetition, a draw", "fifty-move rule, a draw" };
    GameState st = game_state(&game);

    render_board(&screen, &game.current, last_move);
    if (st != GAME_PLAYING) {
        mode = GAME_OVER;
        render_lamp(COL_GAME_OVER);
        printf("Game over: %s", RESULT[st]);
        if (st == GAME_CHECKMATE) printf(", %s wins", game.current.side == WHITE ? "Black" : "White");
        printf(". Type new to play again.\r\n");
    } else if (game.current.side == engine_side) {
        start_thinking();
    } else {
        mode = WAIT_HUMAN;
        render_lamp(COL_YOUR_TURN);
        render_think_clear(&screen);
        printf("%s to move> ", game.current.side == WHITE ? "White" : "Black");
        fflush(stdout);                    /* show the prompt before Enter */
    }
}

static void new_game(const Position *p) {
    start_pos = *p;
    game_init(&game, p);
    played_count = 0;
    last_move = 0;
    eval_white = 0;
    render_all(&screen, &game.current, last_move, eval_white);
    next_turn();
}

/* Take back moves by replaying the game from the start, so the repetition
 * history stays exactly right. Undo stops on the human's turn. */
static void undo(void) {
    int n = played_count, i;
    if (n == 0) { printf("Nothing to undo.\r\n"); return; }
    do {
        n--;
        game_init(&game, &start_pos);
        for (i = 0; i < n; i++) game_play(&game, played[i]);
    } while (n > 0 && game.current.side == engine_side);
    played_count = n;
    last_move = n ? played[n - 1] : 0;
    next_turn();
}

static void engine_moved(const PlResult *r) {
    char text[6];
    int mate = r->score >= MATE - MAX_PLY || r->score <= -MATE + MAX_PLY;
    uint64_t ms = (uint64_t)(r->cycles / 50000);           /* 50 MHz core */

    move_to_text(r->best, text);
    eval_white = game.current.side == WHITE ? r->score : -r->score;
    printf("Engine plays %s  (depth %d, %s %d, %llu nodes, %llu knodes/s)\r\n",
           text, r->depth, mate ? "mate score" : "score", r->score,
           (unsigned long long)r->nodes,
           (unsigned long long)(ms ? r->nodes / ms : 0));
    play(r->best);
    render_eval(&screen, eval_white);
    next_turn();
}

Line by line

  1. play is the only place a move is made: it updates the rules (game_play), the move list used by undo, and last_move for the highlight.
  2. start_thinking turns the lamp red, empties the thinking bar, and hands the position to the PL with think_begin. It returns immediately; the search runs in hardware.
  3. next_turn is the heart of the program. It redraws (only the changed squares), then picks the next mode: game over (yellow lamp and a message), the engine's turn (start thinking), or yours (green lamp and the prompt). Every action ends by calling it, so the screen and the mode can never disagree.
  4. new_game stores the starting position (needed by undo), resets the history, draws everything from scratch, and calls next_turn.
  5. undo replays the game from the start without the last move, and repeats while it is still the engine's turn, so you always land on your own move.
  6. engine_moved prints the move with its depth, score and speed, turns the score into White's point of view for the evaluation bar, plays the move, and calls next_turn.

engine_moved reports the speed in thousands of nodes per second, computed from the core's own clock counter: on a 50 MHz core, cycles / 50000 is milliseconds. The score is printed from the engine's side; the evaluation bar converts it to White's.

Add to sw/main_game.cpart 4 of 5
static void handle_line(const char *s) {
    Position p;
    Move m;

    if (mode == ENGINE_THINKING) {                 /* only "stop" while thinking */
        if (strcmp(s, "stop") == 0) pl_abort();
        else printf("The engine is thinking; type stop to make it move now.\r\n");
        return;
    }
    if (strcmp(s, "help") == 0)        { print_help(); next_turn(); }
    else if (strcmp(s, "new") == 0)    { from_fen(START_FEN, &p); engine_side = BLACK; new_game(&p); }
    else if (strcmp(s, "undo") == 0)   undo();
    else if (strcmp(s, "board") == 0)  { print_board(&game.current); next_turn(); }
    else if (strcmp(s, "flip") == 0) {
        screen.flipped = !screen.flipped;
        render_all(&screen, &game.current, last_move, eval_white);
        next_turn();
    }
    else if (strcmp(s, "go") == 0 && mode == WAIT_HUMAN) {
        engine_side = game.current.side;           /* swap sides with the engine */
        start_thinking();
    }
    else if (strncmp(s, "fen ", 4) == 0) {
        if (from_fen(s + 4, &p)) new_game(&p);
        else { printf("Could not read that FEN.\r\n"); next_turn(); }
    }
    else if (mode == GAME_OVER) printf("Game over. Type new or undo.\r\n");
    else if ((m = parse_move(&game, s)) != 0) { play(m); next_turn(); }
    else { printf("Not a legal move: %s (type help)\r\n", s); next_turn(); }
}

Line by line

  1. While the engine thinks, only stop does something: it writes ABORT to the core. Everything else gets a short message, so a stray key can never corrupt the game.
  2. Each command is a plain strcmp. After any command that changes nothing on the board, next_turn reprints the prompt.
  3. flip toggles the view and redraws everything, because every square moves on screen.
  4. go swaps sides with the engine: it now plays the side to move, and starts thinking at once.
  5. Anything else is tried as a move. parse_move returns 0 for text that is not a legal move here, and the message tells you so.

While the engine thinks, only stop is accepted. It sends ABORT; the thinker then returns the move from the last depth that finished, so even a stopped search plays a sensible move.

Add to sw/main_game.cpart 5 of 5
int main(void) {
    Position p;

    samGL_Init();
    if (!pl_present()) {
        printf("Chess core not found: ID register reads %08lx\r\n", (unsigned long)pl_read(REG_ID));
        return 1;
    }
    printf("\r\nFPGA chess. You are White.\r\n");
    print_help();
    from_fen(START_FEN, &p);
    new_game(&p);

    for (;;) {
        if (uart_poll_line(&line)) handle_line(line.text);

        if (mode == ENGINE_THINKING) {
            PlResult r;
            if (think_poll(&thinker, &r)) {
                engine_moved(&r);
            } else {
                XTime now;
                XTime_GetTime(&now);
                render_think(&screen, (u32)((now - thinker.t0) * 1000 / COUNTS_PER_SECOND), THINK_MS);
            }
        }
        /* anything else your game animates goes here: the loop never blocks */
    }
}

Line by line

  1. samGL_Init prints your GPU's version. pl_present checks the chess core answers with the right ID; if not, there is no point going on, so the program says why and stops.
  2. The help text, then new_game with the standard start: the screen is drawn and the first prompt appears.
  3. The endless loop polls the UART for a finished line, and, while the engine thinks, polls the core. If the core is not finished yet, it updates the thinking bar from the elapsed time: (now - t0) * 1000 / COUNTS_PER_SECOND converts timer ticks to milliseconds.

The loop body is two polls. Neither ever waits, so the loop also has room for anything else your game animates, such as a clock.

48Build, run, and play

Goal: a game of chess on the monitor, with your moves typed on the PC.

  1. Set the PYNQ-Z2's boot jumper to JTAG. Connect the monitor to the VGA output, the micro-USB cable to PROG/UART, and switch on.
  2. Find the COM port: Windows Device Manager, Ports (COM & LPT). The board shows up as a USB serial port.
  3. Open PuTTY. Connection type: Serial, your COM port, speed 115200. Under Connection, Serial: 8 data bits, 1 stop bit, no parity, flow control None. Under Terminal, set Local echo and Local line editing to Force off: the board echoes for you. Open.
  4. In Vitis, build chess_game, then Run (Classic: Run As, Launch Hardware) with Program FPGA and Run ps7_init enabled.
  5. Click into PuTTY and type your moves.
Check

This is the exact terminal output of main_game.c running against the simulated core, with the default 2-second thinking time. Your engine moves should be identical; only the knodes/s figure depends on your bus timing.

Expected output
==========================================
FPGA GPU Hardware Version: 0x00010002
=-=-BY SWR06-=-=
==========================================


FPGA chess. You are White.
Type a move like e2e4 (castle: e1g1, promote: e7e8q), or:
  new    start again        undo   take back your last move
  go     engine plays now   stop   engine moves at once
  flip   turn the board     board  print the board here
  fen <FEN>  set up a position
White to move> e2e4
Engine plays b8c6  (depth 6, score -25, 2453736 nodes, 1332 knodes/s)
White to move> d2d4
Engine plays d7d5  (depth 6, score -20, 2013082 nodes, 1315 knodes/s)
White to move> e2e5
Not a legal move: e2e5 (type help)
White to move> g1f3
Engine plays d5e4  (depth 7, score 120, 1907220 nodes, 1157 knodes/s)
White to move> undo
White to move> b1c3
Engine plays d5e4  (depth 6, score 45, 452707 nodes, 1024 knodes/s)
White to move> board
  8  r . b q k b n r
  7  p p p . p p p p
  6  . . n . . . . .
  5  . . . . . . . .
  4  . . . P p . . .
  3  . . N . . . . .
  2  P P P . . P P P
  1  R . B Q K B N R
     a b c d e f g h
White to move> fen 6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1
White to move> d1d8
Game over: checkmate, White wins. Type new to play again.

And the screen at the end of that session, after d1d8 mates. The lamp is yellow (game over) and the mated king's square is red:

The game screen after the back-rank mate: black king on g8 on a red square, white rook on d8 highlighted
Simulated VGA output, at twice the real size.

If it doesn't work

What you seeLikely causeFix
Nothing in the terminal at allwrong COM port, or the program didn't startcheck Device Manager; in Vitis, check the Run console for errors
Garbled charactersbaud rate115200 in PuTTY; check the BSP's UART baud rate
Every letter appears twicePuTTY echoes as well as the boardLocal echo: Force off
Nothing you type appearsLocal line editing is on, or flow control is setboth off, as in step 3
Chess core not found: ID register reads ...address mismatch, or old bitstreamcompare the Address Editor with CHESS_BASE; re-export the XSA with the bitstream
Text works, screen stays blackGPU address, or VGA clockcheck GPU_BASEADDR; run your prototype to confirm the GPU still works
Engine moves are slow to appearexpected: it thinks for THINK_MSlower THINK_MS, or type stop
Pieces drawn in the wrong colourssprite orderSPRITE_OF_TYPE assumes your order K, Q, B, N, R, P
Part 5

Making it stronger

Add upgrades one at a time, only after Part 3 works. The rule never changes: change the C first, regenerate the vectors, then make the RTL match.

49Killer moves: a tested upgrade

Goal: better move ordering, so alpha-beta cuts off sooner, with exactly the same answers.

Concept

Remember Step 14: alpha-beta is only as fast as its move ordering. Our generator already puts captures first, but quiet moves come out in board order. The killer heuristic improves that with one observation: a quiet move that refuted one position often refutes its siblings too. If ...Qh4 punished one White move, it probably punishes a similar one.

So for each ply, remember the last quiet move that caused a cutoff (the "killer"), and at the next node on that ply, try it first among the quiet moves. It is an ordering change only, so the search's score and best move can't change, only the amount of work. Measured at depth 6:

PositionNodes beforeNodes with killersScore and move
Start1,519,394159,788unchanged
Kiwipete2,312,7152,197,846unchanged
pos61,864,1961,408,694unchanged

The gain ranges from 5% to almost 90%, and it is largest in quiet positions, where the captures-first rule has nothing to work with. On the board, the depth-6 search from the start drops from 56 million clocks to 7.1 million, and the one-second think reaches depth 7 instead of 5.

How the hardware does it. The generator already writes quiet moves one by one. When it is about to write the killer, it writes the first quiet move in the killer's place instead, then spends one extra clock writing the killer into the first quiet slot. The two trade places, and the C does exactly the same swap, so the lists still match move for move.

This upgrade was fully tested: the C killer engine passes perft, and the hardware matched it on all 577 full-set searches. The finished files are in the ZIP, under upgrades/killer/.

Code

Apply these changes in order. Each "find" text appears exactly once in its file.

Change 1 in c/chess.h. Add the killer table, and a test for quiet moves. Captures and promotions always come first in the list, so the quiet moves are one block at the end.

Find
static SearchResult search_result;
static uint64_t     search_node_limit;     /* 0 = no limit */
Replace with
static SearchResult search_result;
static uint64_t     search_node_limit;     /* 0 = no limit */
static Move         killer[MAX_PLY];       /* per ply: last quiet move that cut off */

/* A quiet move: no promotion, nothing captured (en passant is a capture). */
static inline int is_quiet(const Position *p, Move m) {
    int pawn = (p->bb[p->side * 6 + PAWN] & BIT(MOVE_FROM(m))) != 0;
    if (MOVE_PROMO(m)) return 0;
    if (occupied(p) & BIT(MOVE_TO(m))) return 0;
    if (pawn && (MOVE_FROM(m) & 7) != (MOVE_TO(m) & 7)) return 0;
    return 1;
}

Change 2 in c/chess.h. After generating, move this ply's killer to the front of the quiet moves. The hardware does exactly this swap while it writes the list.

Find
    n = generate_moves(p, list, stand_pat);
    for (i = 0; i < n; i++) {
Replace with
    n = generate_moves(p, list, stand_pat);

    /* Find the first quiet move, then swap the killer into that place. */
    int first_quiet = n;
    for (i = 0; i < n; i++)
        if (is_quiet(p, list[i])) { first_quiet = i; break; }
    if (killer[ply])
        for (i = first_quiet; i < n; i++)
            if (list[i] == killer[ply]) {
                Move tmp = list[first_quiet];
                list[first_quiet] = list[i];
                list[i] = tmp;
                break;
            }

    for (i = 0; i < n; i++) {

Change 3 in c/chess.h. Remember a quiet move that causes a cutoff.

Find
        if (alpha >= beta) break;     /* cutoff: the rest cannot matter */
Replace with
        if (alpha >= beta) {          /* cutoff: the rest cannot matter */
            if (i >= first_quiet) killer[ply] = list[i];
            break;
        }

Change 4 in c/chess.h. Every search starts with no killers, just like the hardware.

Find
    search_node_limit = node_limit;
Replace with
    search_node_limit = node_limit;
    memset(killer, 0, sizeof killer);

Change 5 in rtl/move_gen.sv. New ports on the generator.

Find
    input  logic [4:0]  ply,            // selects this node's list in the RAM
    output logic        done,           // one-clock pulse; count is then valid
    output logic [7:0]  count,
Replace with
    input  logic [4:0]  ply,            // selects this node's list in the RAM
    input  move_t       killer,         // 0 = none
    output logic        done,           // one-clock pulse; count is then valid
    output logic [7:0]  count,
    output logic [7:0]  first_quiet,    // index of the first quiet move

Change 6 in rtl/move_gen.sv. One new state: the second write of the swap.

Find
    G_IDLE, G_OCC, G_STAGE, G_DECIDE, G_PIECE, G_TARGETS, G_EMIT
Replace with
    G_IDLE, G_OCC, G_STAGE, G_DECIDE, G_PIECE, G_TARGETS, G_EMIT, G_SWAP

Change 7 in rtl/move_gen.sv. The write port now chooses between the normal write and the two swap writes.

Find
  // The write port is pure wiring from registers.
  assign we    = (state == G_EMIT) && (targets != 64'b0);
  assign waddr = {ply, count};
  assign wdata = {is_promo ? promo : 3'd0, to, from};
Replace with
  // The write port. When the killer is found, the first quiet move is written at
  // the killer's index, then G_SWAP writes the killer at the first quiet index.
  move_t new_move, first_quiet_move;
  logic  swap_now;
  assign new_move = {is_promo ? promo : 3'd0, to, from};
  assign swap_now = (stage == ST_QUIET) && (new_move == killer)
                 && (killer != '0) && (count != first_quiet);
  assign we    = ((state == G_EMIT) && (targets != 64'b0)) || (state == G_SWAP);
  assign waddr = (state == G_SWAP) ? {ply, first_quiet} : {ply, count};
  assign wdata = (state == G_SWAP) ? killer : (swap_now ? first_quiet_move : new_move);

Change 8 in rtl/move_gen.sv. Clear `first_quiet` at the start of a list.

Find
        G_OCC: begin
          occ <= occupied(pos);
Replace with
        G_OCC: begin
          occ <= occupied(pos);
          first_quiet <= 8'd0;

Change 9 in rtl/move_gen.sv. Each stage records the current count, so when the quiet stage begins, `first_quiet` holds the right index.

Find
        G_STAGE: begin                       // movers latches at this edge
          movers <= stage_movers;
Replace with
        G_STAGE: begin                       // movers latches at this edge
          movers <= stage_movers;
          first_quiet <= count;              // ends up holding the quiet start

Change 10 in rtl/move_gen.sv. A list can end in two places. This is the first: in a captures-only list with an empty last stage, `first_quiet` must equal the list length, as it does in C.

Find
          end else if (stage == last_stage) begin
            done <= 1'b1;
            state <= G_IDLE;
          end else begin
            stage <= stage + 3'd1;
            state <= G_STAGE;
          end
        end

        G_PIECE: begin
Replace with
          end else if (stage == last_stage) begin
            first_quiet <= count;
            done <= 1'b1;
            state <= G_IDLE;
          end else begin
            stage <= stage + 3'd1;
            state <= G_STAGE;
          end
        end

        G_PIECE: begin

Change 11 in rtl/move_gen.sv. This is the second place. A full list must keep its value, so only a captures-only list updates it here.

Find
          end else if (stage == last_stage) begin
            done <= 1'b1;
            state <= G_IDLE;
          end else begin
            stage <= stage + 3'd1;
            state <= G_STAGE;
          end
        end

        G_TARGETS: begin
Replace with
          end else if (stage == last_stage) begin
            if (captures_only) first_quiet <= count;
            done <= 1'b1;
            state <= G_IDLE;
          end else begin
            stage <= stage + 3'd1;
            state <= G_STAGE;
          end
        end

        G_TARGETS: begin

Change 12 in rtl/move_gen.sv. Remember the first quiet move, and start the swap.

Find
            if (count == 8'hFF) overflow <= 1'b1;
            count <= count + 8'd1;
            if (is_promo && promo != 3'd1) begin
Replace with
            if (count == 8'hFF) overflow <= 1'b1;
            count <= count + 8'd1;
            if (count == first_quiet) first_quiet_move <= new_move;
            if (swap_now) state <= G_SWAP;
            if (is_promo && promo != 3'd1) begin

Change 13 in rtl/move_gen.sv. Add the new state.

Find
        default: state <= G_IDLE;
      endcase
Replace with
        G_SWAP: state <= G_EMIT;             // the killer is written during this clock

        default: state <= G_IDLE;
      endcase

Change 14 in rtl/search_core.sv. Add a state.

Find
    S_NEXT, S_READ, S_DECODE, S_APPLY, S_TEST, S_LEGAL, S_END_NODE, S_RETURN, S_POP, S_SCORE
Replace with
    S_NEXT, S_READ, S_DECODE, S_APPLY, S_TEST, S_LEGAL, S_END_NODE, S_RETURN, S_POP, S_SCORE,
    S_KILLER

Change 15 in rtl/search_core.sv. That makes 17 states, which no longer fit in four bits.

Find
  typedef enum logic [3:0] {
Replace with
  typedef enum logic [4:0] {

Change 16 in rtl/search_core.sv. The frame must remember where the quiet moves begin.

Find
    logic [7:0]         count;       // moves in this node's list
Replace with
    logic [7:0]         count;       // moves in this node's list
    logic [7:0]         first_quiet; // index of this node's first quiet move

Change 17 in rtl/search_core.sv. Killer storage: a small RAM, plus valid bits that clear in one clock.

Find
  logic  [7:0]  gen_count;
Replace with
  logic  [7:0]  gen_count, gen_first_quiet;
  move_t        killer [0:MAX_PLY-1];
  logic [MAX_PLY-1:0] killer_valid;
  move_t        killer_r;

Change 18 in rtl/search_core.sv. Connect the generator.

Find
    .clk, .rst, .start(gen_start), .pos, .captures_only(stand_pat), .ply,
    .done(gen_done), .count(gen_count), .overflow(gen_overflow),
Replace with
    .clk, .rst, .start(gen_start), .pos, .captures_only(stand_pat), .ply,
    .killer(killer_r), .first_quiet(gen_first_quiet),
    .done(gen_done), .count(gen_count), .overflow(gen_overflow),

Change 19 in rtl/search_core.sv. Initialize at the start of a search.

Find
                 depth: depth, index: 8'd0, count: 8'd0,
                 any_legal: 1'b0, in_check: 1'b0};
Replace with
                 depth: depth, index: 8'd0, count: 8'd0, first_quiet: 8'd0,
                 any_legal: 1'b0, in_check: 1'b0};
          killer_valid <= '0;

Change 20 in rtl/search_core.sv. Hand this ply's killer to the generator.

Find
        S_GEN_START: begin
          gen_start <= 1'b1;
Replace with
        S_GEN_START: begin
          killer_r <= killer_valid[ply] ? killer[ply] : '0;
          gen_start <= 1'b1;

Change 21 in rtl/search_core.sv. Store the quiet start in the frame.

Find
          f.count <= gen_count;
Replace with
          f.count <= gen_count;
          f.first_quiet <= gen_first_quiet;

Change 22 in rtl/search_core.sv. Initialize the child frame.

Find
                   index: 8'd0, count: 8'd0, any_legal: 1'b0, in_check: 1'b0};
Replace with
                   index: 8'd0, count: 8'd0, first_quiet: 8'd0,
                   any_legal: 1'b0, in_check: 1'b0};

Change 23 in rtl/search_core.sv. On a quiet cutoff, go and read the move that caused it.

Find
            ret <= new_best;           // beta cutoff
            state <= S_RETURN;
          end else begin
Replace with
            ret <= new_best;           // beta cutoff
            // The move RAM is already addressed with {ply, f.index}; its output
            // is the move that caused this cutoff, one clock from now.
            state <= (f.index >= f.first_quiet) ? S_KILLER : S_RETURN;
          end else begin

Change 24 in rtl/search_core.sv. Store it.

Find
        default: state <= S_IDLE;
      endcase
    end
  end
endmodule
Replace with
        S_KILLER: begin
          killer[ply] <= move_rdata;
          killer_valid[ply] <= 1'b1;
          state <= S_RETURN;
        end

        default: state <= S_IDLE;
      endcase
    end
  end
endmodule

Change 25 in tb/tb_move_gen.sv. The generator testbench needs the two new ports. With no killer the list order is unchanged.

Find
  move_gen dut (.clk, .rst, .start, .pos, .captures_only, .ply(5'd3),
Replace with
  move_gen dut (.clk, .rst, .start, .pos, .captures_only, .ply(5'd3),
                .killer('0), .first_quiet(),
Check
Command Prompt
cd /d C:\chess\c
gcc -std=c99 -O2 -Wall -Wextra main.c -o engine.exe
engine.exe test
gcc -std=c99 -O2 -Wall -Wextra gen_vectors.c -o gen_vectors.exe
gen_vectors.exe ..\vectors
cd ..
scripts\run_sim.bat tb_move_gen
scripts\run_sim.bat tb_search
scripts\run_sim.bat tb_axi

All must pass. The estimated size stays about the same (11,478 LUTs, 16 block RAMs). Perft counts and their clock counts don't change, because perft never records a killer.

50What to add next

These are not built or tested here. They are the directions I would take, roughly in order of value for effort. Note which kind each is, because it decides how you test it:

KindExamplesHow to test
Ordering onlykillers, history, hash movescore at each depth must not change; nodes should fall
Window onlyaspiration windows, PVSscore must not change; re-searches may add work
Selectivenull move, late-move reductionsscore can change: judge by test suites and by playing games
UpgradeWhat it doesHardware notes
Previous best move firstat the root, search last iteration's best move firstone register; makes iterative deepening really pay off
Second killercatches more quiet refutationsa second killer table and swap
Zobrist hashinga 64-bit fingerprint for each positiona ROM of 781 random constants, updated with XOR on each move
Repetition in searchstops walking into drawsneeds the hash; compare against the path and the game history from the CPU
Transposition tablereuses results for positions reached by different move orders8,192 entries is about 24 block RAMs; store key, score, depth, bound and move
Null move pruningif passing still beats β, cut offflip side, clear en passant, reduce depth; never in check, nor with only pawns left
Better evaluationmobility, passed pawns, king safetyside_attacks already exists; add a stage to eval_pipe

For speed, measure before changing anything. The cycles and nodes counters are always there; add counters for generator-busy and evaluator-wait clocks, and fix whichever is largest.

Troubleshooting

C and simulation

SymptomCheck
A perft count is wrongdivide at the shallowest failing depth (Step 9)
xvlog is not recognisedrun settings64.bat in this window
xvlog can't find a file in rtl\create the placeholders from Step 23
cannot open vec_...txtrun gen_vectors.exe ..\vectors
A simulation never endsa testbench is waiting on done: add -debug typical and look at state
A simulation is very slownormal for xsim: use the quick vectors and let it run

Vivado

SymptomCheck
Add Module doesn't list chess_axi_topall seven files in Design Sources; it must be the .v file; try Tools, Refresh Hierarchy
Error about a SystemVerilog module referenceyou referenced chess_axi, not chess_axi_top
The block shows dozens of separate s_axi_ pinsthe bus wasn't recognised: right-click the block, Refresh Module, and check the port names
The core shows as unassigned in the Address Editorright-click, Assign; check again after any Refresh Module
chess_pkg is not declaredcompile order: chess_pkg.sv first, type SystemVerilog
0 block RAMsread the sdp_ram messages in the synthesis log
Negative WNSStep 37. Never ship with it
Critical warning about DDR or FIXED_IORun Block Automation with Apply Board Preset

On the board

SymptomCheck
The CPU freezes reading the IDthe logic isn't programmed or its clock is stopped: a read with nobody answering hangs the bus. Check Program FPGA, or that Overlay ran first
ID reads zero or garbagewrong address: compare with the Address Editor
Overlay error about .hwhthe .bit and .hwh names differ, or the file is missing
Perft wrong on the board, right in simulationtiming first: read WNS. Then clock and reset
Clock counts differ, nodes matchyou changed the RTL (expected after a timing fix) or added an upgrade
FAULT bit seta move list overflowed: an impossible position. Check the FEN
Best move is 0mate or stalemate: check with game_state
Results look randomthe order of the board writes: low word, then high word, for each board
64-bit numbers print wronglythe C library in your BSP may lack %llu: print the high and low 32-bit halves instead
Nothing on the serial portCOM port and 115200 baud, and the board in JTAG boot mode

To read a register without any of your code, use the XSCT console in Vitis, once the processor is initialised and the logic is programmed. It should print C4E55A01:

Tcl console
connect
targets -set -filter {name =~ "*A9*#0"}
mrd 0x43C00000

Final checklist

Rules
  • engine.exe test passes all 30 counts
  • tb_functions and tb_move_gen pass
  • board perft matches, clock counts included
Search
  • tb_search passes
  • the board's depth 1 to 6 table matches
  • mate, stalemate and promotion tests pass
  • an aborted search never changes the move
Implementation
  • WNS and WHS both zero or more
  • no latches or multi-driven nets
  • about 16 block RAMs inferred
  • your VGA design still meets timing
Game
  • human moves checked by game_is_legal
  • the screen keeps drawing while the engine thinks
  • checkmate, stalemate, repetition and the fifty-move rule end the game

References

  1. C. Donninger, A. Kure and U. Lorenz, Parallel Brutus: The First Distributed, FPGA Accelerated Chess Program, IPDPS 2004. The inspiration for the hardware architecture; this design is new, not the Brutus source.
  2. D. E. Knuth and R. W. Moore, An Analysis of Alpha-Beta Pruning, Artificial Intelligence, 1975.
  3. C. E. Shannon, Programming a Computer for Playing Chess, 1950.
  4. FIDE Laws of Chess: movement, castling, en passant, promotion and draws.
  5. Chess Programming Wiki: Perft Results and Simplified Evaluation Function.
  6. AMD, Zynq-7000 SoC Technical Reference Manual (UG585).
  7. AMD, Vivado Synthesis (UG901): HDL coding styles and RAM inference.
  8. AMD, Limitations of the Module Reference Feature (UG994).
  9. AMD, Zynq-7000 Embedded Design Tutorial (UG1165).
  10. PYNQ: Overlay design, PYNQ-Z2 setup, Jupyter notebooks, and the forum tutorial Creating a hardware design for PYNQ.
  11. TUL, PYNQ-Z2 product page.

Every code snippet on this page was extracted from this HTML file into an empty folder, rebuilt and re-tested before delivery: C with gcc and clang, the RTL with Verilator against the C engine's vectors, and the drivers against the simulated hardware. Vivado, Vitis and the physical board were not available, so Part 3 is untested.