From Code to Chip
At the end of chapter 26, our CPU counted to 10 - in simulation. We also saw that this is not the end of the story: when we tried to load the CPU onto an FPGA, it needed more than three times as many logic cells as the chip has.
In this chapter we close the gap between the Verilog code and a configured chip. We look at what an FPGA consists of, which tools turn our code into a configuration, and what each of these tools reports. Step by step we go from a blinking LED to the 7-segment decoder from chapter 23 and finally to the CPU, which counts on the displays of a real board.
Tip | All examples of this chapter are in the folder |
Note | Status of this chapter Synthesis, place & route, timing analysis and the simulation of the complete board design were run and are shown here with their real output. The test on the Go Board itself is still pending. |
What is an FPGA?
So far we have built circuits from gates whose function was fixed: an AND gate is an AND gate. An FPGA (Field-Programmable Gate Array) is a chip whose function is not fixed at manufacturing. It contains thousands of small, identical building blocks, and a configuration decides what each of them does and how they are wired. Loading a new configuration turns the same chip into a different circuit.
How does this compare to the other ways of building digital hardware? The following picture compares a DSP, an FPGA and an ASIC:
A DSP is a processor: it executes instructions one after the other, like our CPU. An ASIC is a custom chip: it contains exactly the circuit that is needed, but it can never be changed. The FPGA lies in between: it computes in parallel, like an ASIC, but it can be reconfigured as often as we like.
The logic cell
The most important building block of an FPGA is the logic cell. On the Lattice iCE40, which we use in this chapter, it looks like this:
The LUT4 (look-up table with 4 inputs) is a tiny memory with 16 bits. The four inputs form an address, and the bit at this address is the output. If we store the right 16 bits, the LUT behaves like any function of 4 inputs - it simply is a truth table. An AND gate, an XOR gate, a multiplexer: everything with at most 4 inputs fits into one LUT.
The D flip-flop can store the output of the LUT. A multiplexer selects whether the cell outputs the stored value or the value directly from the LUT. So one cell is either a piece of combinational logic, or a register with logic in front of it - exactly the building blocks of RTL from chapter 24.
The carry logic connects neighbouring cells into a fast carry chain for adders and counters.
Besides the logic cells, the iCE40 has block RAM for larger memories, I/O cells that connect the pins, and a programmable routing network that connects everything. The configuration of all these parts together is called the bitstream.
| iCE40 HX1K | |
|---|---|
Logic cells (LUT4 + flip-flop) | 1280 |
Block RAM | 16 × 4 kbit = 64 kbit |
Package on the Go Board | VQ100 (100 pins) |
The Nandland Go Board
We use the Nandland Go Board, a small board with an iCE40 HX1K. For us, the following parts are important:
a 25 MHz oscillator as the clock,
4 LEDs and 4 push buttons,
two 7-segment displays,
a USB connection, through which the board is powered and programmed.
Which pin of the chip is connected to which LED or button is written in a constraint file (.pcf).
Ours contains the pins we use in this chapter, with the names and numbers from Nandland’s official file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Nandland Go Board (iCE40 HX1K, VQ100) - pins used in chapter 27
# Signal names and pins as in Nandland's official Go_Board_Constraints.pcf
# (https://nandland.com/project-1-your-first-go-board-project/).
# -nowarn: no warning if a design does not use a pin.
# 25 MHz clock
set_io -nowarn i_Clk 15
# LEDs (1 = on)
set_io -nowarn o_LED_1 56
set_io -nowarn o_LED_2 57
set_io -nowarn o_LED_3 59
set_io -nowarn o_LED_4 60
# push buttons (1 = pressed)
set_io -nowarn i_Switch_1 53
set_io -nowarn i_Switch_2 51
set_io -nowarn i_Switch_3 54
set_io -nowarn i_Switch_4 52
# 7-segment display 1 (left digit)
set_io -nowarn o_Segment1_A 3
set_io -nowarn o_Segment1_B 4
set_io -nowarn o_Segment1_C 93
set_io -nowarn o_Segment1_D 91
set_io -nowarn o_Segment1_E 90
set_io -nowarn o_Segment1_F 1
set_io -nowarn o_Segment1_G 2
# 7-segment display 2 (right digit)
set_io -nowarn o_Segment2_A 100
set_io -nowarn o_Segment2_B 99
set_io -nowarn o_Segment2_C 97
set_io -nowarn o_Segment2_D 95
set_io -nowarn o_Segment2_E 94
set_io -nowarn o_Segment2_F 8
set_io -nowarn o_Segment2_G 96
One detail matters later: the LEDs light up with a 1, but the segments of the displays light up with a 0 - they are active low.
The open-source toolchain
From the Verilog code to the configured chip, it takes four tools:
Yosys synthesizes the Verilog code: it translates our RTL description into a netlist of iCE40 cells - LUTs, flip-flops, carry logic and block RAM.
nextpnr places every cell of the netlist on a concrete place on the chip, connects them through the routing network (place & route) and then checks the timing. The
.pcffile tells it which signal goes to which pin.icepack packs the result into a bitstream.
iceprog sends the bitstream via USB to the board.
All four are open source. The simplest way to install them is the OSS CAD Suite,
or on Debian and Ubuntu the packages yosys, nextpnr-ice40 and fpga-icestorm.
Since we need the same commands for every example, they are collected in a small makefile, which every example includes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Shared build rules for the Go Board examples (included by every Makefile in this folder).
# Each Makefile sets TOP (top module), SRC (Verilog files) and optionally TB (testbench).
#
# make synthesis, place & route, bitstream -> $(TOP).bin
# make prog load the bitstream onto the Go Board (via USB)
# make stat resource usage after synthesis
# make sim simulate the testbench with Icarus Verilog
# make clean remove generated files
PCF ?= ../go_board.pcf
all: $(TOP).bin
# 1. synthesis: Verilog -> netlist of iCE40 cells (LUTs, flip-flops, block RAM)
$(TOP).json: $(SRC)
yosys -q -l $(TOP)_yosys.log -p "synth_ice40 -top $(TOP) -json $@" $(SRC)
# 2. place & route: every cell gets a place on the chip, then the wires are routed;
# --freq 25: timing analysis against the 25 MHz clock of the Go Board
$(TOP).asc: $(TOP).json $(PCF)
nextpnr-ice40 --hx1k --package vq100 --freq 25 --json $< --pcf $(PCF) --asc $@ \
2>&1 | tee $(TOP)_nextpnr.log | grep -E "^Info:\s+(ICESTORM_LC|ICESTORM_RAM|SB_IO):|Max frequency for clock|ERROR"
# 3. bitstream: the configuration of the chip as a binary file
$(TOP).bin: $(TOP).asc
icepack $< $@
# 4. load it onto the board
prog: $(TOP).bin
iceprog $<
stat: $(SRC)
yosys -q -p "synth_ice40 -top $(TOP); tee -o /dev/stdout stat" $(SRC)
sim: $(TB) $(SRC)
iverilog -o sim $(TB) $(SRC) && vvp sim
clean:
rm -f *.json *.asc *.bin *.log *.vcd *.svg *.dot sim
.PHONY: all prog stat sim clean
An example then only has to say which module is at the top and which files belong to it. For the first example:
1
2
3
4
5
TOP = blinky
SRC = blinky.v
TB = blinky_tb.v
include ../fpga.mk
Step 1: Blinky
The "hello world" of FPGAs is a blinking LED. A counter runs with the 25 MHz clock, and its highest bits drive the LEDs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Blinky - the "hello world" of FPGAs.
// A free-running counter divides the 25 MHz clock of the Go Board.
// The four highest bits drive the four LEDs: they show a binary counter.
// With WIDTH = 24, the highest bit toggles every 2^23 clock cycles,
// so LED 4 is on for 0.34 s and off for 0.34 s.
module blinky #(
parameter WIDTH = 24
) (
input wire i_Clk,
output wire o_LED_1,
output wire o_LED_2,
output wire o_LED_3,
output wire o_LED_4
);
reg [WIDTH-1:0] count = 0; // initial value: the iCE40 starts with 0
always @(posedge i_Clk)
count <= count + 1;
assign {o_LED_4, o_LED_3, o_LED_2, o_LED_1} = count[WIDTH-1 -: 4];
endmodule
Why 24 bits? At 25 MHz, a bit toggles visibly only if it is high enough: bit 23 changes every 223 clock cycles, that is every 0.34 s. LED 4 is on for 0.34 s and off for 0.34 s, the other three LEDs blink faster. Together they show a binary counter from 0 to 15.
Two things are new compared to the previous chapters:
reg [WIDTH-1:0] count = 0;gives the register an initial value. In an ASIC, this would only work in simulation. The iCE40, however, sets all flip-flops to their initial value when the configuration is loaded.count[WIDTH-1 -: 4]selects 4 bits, starting at bit WIDTH-1 and going down. This is the same ascount[23:20], but it adapts automatically to WIDTH.
First in simulation
Before we load anything onto the board, we simulate - as in the previous chapters. With 24 bits we would have to wait millions of clock cycles, so the testbench sets WIDTH to 6:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
`timescale 1ns / 1ps
// Testbench for blinky: with WIDTH = 6 instead of 24, the LEDs change every 4 clock cycles,
// so we can watch them in simulation (with 24 bits we would wait millions of cycles).
module blinky_tb;
reg clk = 0;
wire led1, led2, led3, led4;
integer i, errors = 0;
always #20 clk = ~clk; // 25 MHz: period 40 ns
blinky #(.WIDTH(6)) dut (
.i_Clk(clk), .o_LED_1(led1), .o_LED_2(led2), .o_LED_3(led3), .o_LED_4(led4)
);
initial begin
$dumpfile("blinky.vcd");
$dumpvars(0, blinky_tb);
for (i = 1; i <= 64; i = i + 1) begin
@(posedge clk); #1;
if ({led4, led3, led2, led1} !== i[5:2]) errors = errors + 1;
if (i % 4 == 0) $display("cycle %2d LEDs (4..1) = %b%b%b%b", i, led4, led3, led2, led1);
end
if (errors == 0) $display("PASSED: LEDs show bits 5..2 of the counter");
else $display("FAILED: %0d errors", errors);
$finish;
end
endmodule
make sim prints:
cycle 4 LEDs (4..1) = 0001 cycle 8 LEDs (4..1) = 0010 cycle 12 LEDs (4..1) = 0011 ... cycle 60 LEDs (4..1) = 1111 cycle 64 LEDs (4..1) = 0000 PASSED: LEDs show bits 5..2 of the counter
Then onto the chip
make runs Yosys, nextpnr and icepack one after the other. The makefile only shows the most important lines of the report:
Info: ICESTORM_LC: 28/ 1280 2% Info: ICESTORM_RAM: 0/ 16 0% Info: SB_IO: 5/ 112 4% Info: Max frequency for clock 'i_Clk$SB_IO_IN_$glb_clk': 190.33 MHz (PASS at 25.00 MHz) Info: Max frequency for clock 'i_Clk$SB_IO_IN_$glb_clk': 194.33 MHz (PASS at 25.00 MHz)
The blinker needs 28 of the 1280 logic cells, no block RAM, and 5 I/O cells: one for the clock, four for the LEDs.
It could run with up to 194 MHz, but the board only provides 25 MHz - plenty of reserve. Then make prog loads the bitstream
onto the board, and the LEDs start counting.
Step 2: Synthesis
What exactly does Yosys do? It reads the Verilog code, resolves the hierarchy and all generate loops
(chapter 23), optimizes the logic and finally maps it to the cells of the iCE40.
In the terms of chapter 24: synthesis takes us from the register-transfer level
down to the gate level - which on an FPGA means LUTs and flip-flops.
make stat shows the result for the blinker:
Number of cells: 70
SB_CARRY 22
SB_DFF 24
SB_LUT4 2424 flip-flops for the 24 bits of the counter, 24 LUTs and 22 carry cells for the adder that computes count + 1.
These are 70 cells, but nextpnr only reported 28 logic cells. The reason is the logic cell from above:
the LUT, the flip-flop and the carry logic of one bit fit into one and the same logic cell.
The 7-segment decoder on the chip
As a second example, we put the 7-segment decoder from chapter 23 onto the chip - unchanged. The four buttons form a 4-bit number, and the right display shows it as a hex digit:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// The 7-segment decoder from chapter 23 on real hardware.
// The four buttons form a 4-bit number (button 1 = bit 0), the right display shows it as a hex digit.
// The Go Board's segments are active low (0 = segment on), so the outputs of the decoder are inverted.
module hex_display (
input wire i_Switch_1,
input wire i_Switch_2,
input wire i_Switch_3,
input wire i_Switch_4,
output wire o_Segment2_A,
output wire o_Segment2_B,
output wire o_Segment2_C,
output wire o_Segment2_D,
output wire o_Segment2_E,
output wire o_Segment2_F,
output wire o_Segment2_G
);
wire [3:0] value = {i_Switch_4, i_Switch_3, i_Switch_2, i_Switch_1};
wire [6:0] seg; // {g, f, e, d, c, b, a}, 1 = on
seven_seg dec (.value(value), .seg(seg));
assign {o_Segment2_G, o_Segment2_F, o_Segment2_E, o_Segment2_D,
o_Segment2_C, o_Segment2_B, o_Segment2_A} = ~seg;
endmodule
The only addition is the ~: the decoder from chapter 23 outputs a 1 for a segment that should light up,
but the segments of the Go Board light up with a 0.
The synthesis result is remarkably small:
Number of cells: 7
SB_LUT4 7Seven LUTs - one per segment. Each segment is a function of the same 4 input bits, and every function of 4 inputs fits
into exactly one LUT4. All the logic we derived for the decoder in chapter 23 ends up as 7 small truth tables.
make schematic lets Yosys draw the result:
On the left is the input value, on the right the output seg. Every LUT is connected to all four bits of value
and produces one bit of seg.
What cannot be synthesized
Synthesis only understands the part of Verilog that describes hardware. Everything else is ignored or rejected:
#10delays: a chip cannot wait for a fixed time without a clock.$display,$finish,$dumpvars: there is no console on the chip.Hierarchical names like
dut.rf.regs[1]: in the testbench of chapter 26 we used them to look into the CPU. On the chip, a signal that is not led out through a port cannot be watched.
Two pitfalls are less obvious:
Yosys removes everything that has no effect on an output. A module without outputs is optimized away completely - the CPU from chapter 26 has only
clkandrstas ports, so Yosys would produce an empty circuit.Constants are optimized, too. Our instruction memory is a fixed table, loaded with
$readmemh. Yosys knows every instruction and removes what our program never uses - for example all registers except x1, x2 and x3. The size of the CPU therefore depends on the program it runs.
Step 3: Place and route
The netlist only says which cells there are and how they are connected. nextpnr decides where each of them sits on the chip, and which wires of the routing network connect them. This is similar to designing a circuit board: synthesis creates the parts list and the schematic, place & route creates the layout.
The most important part of its report is the utilization: how many logic cells (ICESTORM_LC), block RAMs (ICESTORM_RAM)
and I/O cells (SB_IO) the design needs. If one of them exceeds 100 %, nextpnr gives up with an error -
we will see this in a moment.
Step 4: Timing analysis
After placing and routing, nextpnr knows the delay of every cell and every wire. It looks for the critical path: the longest path from one register through combinational logic to the next register - the RTL picture from chapter 24 again. Its delay must be shorter than the clock period, otherwise the next register would take over a value that is not yet final (the setup time from chapter 12).
The report shows this as the maximum frequency, checked against the clock we specified with --freq 25:
Info: Max frequency for clock 'i_Clk$SB_IO_IN_$glb_clk': 194.33 MHz (PASS at 25.00 MHz)
The line appears twice: the first value is an estimate after placing, the second one is the result after routing,
when the real wires are known. PASS means that the design works at 25 MHz. With FAIL, nextpnr stops with an error.
Step 5: The CPU on the Go Board
Now we have all the tools to put our CPU onto the board.
First attempt: it does not fit
We take the CPU from chapter 26 unchanged and wrap it into a top module for the board. nextpnr answers:
Info: ICESTORM_LC: 4126/ 1280 322% Info: ICESTORM_RAM: 0/ 16 0% ERROR: Unable to place cell 'cpu.dmem.mem[40]_SB_DFFE_Q_18_DFFLC', no BELs remaining to implement cell type 'ICESTORM_LC'
The design needs 322 % of the logic cells, and not a single block RAM. The name of the cell gives a hint where the problem is:
cpu.dmem.mem[40] is word 40 of the data memory. Yosys has built the data memory from flip-flops - 64 words of 32 bits,
that is 2048 flip-flops. The chip only has 1280 logic cells, so this can never fit.
But why does Yosys not use the block RAM? Because the block RAM of the iCE40 can only be read on a clock edge. Our data memory and our register file are read combinationally: as soon as the address changes, the data appears. This is exactly what we wanted for the single-cycle CPU, and in simulation it costs nothing. But on this chip, there is only one way to build a memory with combinational reading: from flip-flops and large multiplexers.
Making the memories fit
The solution has two parts.
The data memory gets smaller. Our counter program only uses a single address. 8 words are enough, and 8 × 32 = 256 flip-flops fit easily:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Data memory: 8 words (chapter 26: 64 words).
// Reading is combinational (MemRead), writing happens on the rising clock edge (MemWrite).
// With a combinational read, the memory cannot be mapped to block RAM, so it is built from
// flip-flops. 8 words are enough for our counter program, which only uses address 4.
module data_mem (
input wire clk,
input wire [31:0] addr,
input wire mem_read,
input wire mem_write,
input wire [31:0] wd,
output wire [31:0] rd
);
reg [31:0] mem [0:7];
integer i;
initial for (i = 0; i < 8; i = i + 1) mem[i] = 0; // initial values work on the iCE40, too
assign rd = mem_read ? mem[addr[4:2]] : 32'd0;
always @(posedge clk)
if (mem_write)
mem[addr[4:2]] <= wd;
endmodule
The register file moves into block RAM. For this, it must be read on a clock edge. A block RAM has only one read port, but the register file needs two - so there are two copies, which are always written together:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// RISC-V register file in block RAM (chapter 26: built from flip-flops).
//
// The iCE40 block RAM can only be read on a clock edge. So reading is no longer combinational:
// rd1 and rd2 show the registers that were selected by rs1 and rs2 at the last rising edge.
// A block RAM has one read port, so there are two copies (bank1, bank2) that are always
// written together - one copy per read port.
//
// Important: this only works because of the clock enable in the CPU. After every instruction
// (ce = 1), the register file needs one more clock edge to read the operands of the next
// instruction. So ce must never be 1 in two clock cycles in a row.
module regfile (
input wire clk,
input wire [4:0] rs1, // read port 1
input wire [4:0] rs2, // read port 2
output wire [31:0] rd1,
output wire [31:0] rd2,
input wire we, // RegWrite (already combined with ce)
input wire [4:0] rd, // write port
input wire [31:0] wd
);
reg [31:0] bank1 [0:31];
reg [31:0] bank2 [0:31];
reg [31:0] q1, q2;
reg zero1, zero2; // was register x0 selected?
always @(posedge clk) begin // read: synchronous -> block RAM
q1 <= bank1[rs1];
q2 <= bank2[rs2];
zero1 <= (rs1 == 0);
zero2 <= (rs2 == 0);
end
always @(posedge clk) // write
if (we && rd != 0) begin
bank1[rd] <= wd;
bank2[rd] <= wd;
end
assign rd1 = zero1 ? 32'd0 : q1; // x0 always reads as 0
assign rd2 = zero2 ? 32'd0 : q2;
endmodule
Which edge should be used for reading? The first idea is the falling edge: the instruction is fetched after the rising edge, the register file reads its operands half a period later, and the ALU has the second half of the period to compute. The CPU would stay single-cycle. It fits - but the timing analysis says no:
Info: ICESTORM_LC: 779/ 1280 60% Info: ICESTORM_RAM: 4/ 16 25% ERROR: Max frequency for clock 'i_Clk$SB_IO_IN_$glb_clk': 15.37 MHz (FAIL at 25.00 MHz)
Fetching and reading in the first half, computing and writing back in the second half: at 25 MHz each half has only 20 ns, and that is not enough. This is a real example of what timing analysis is for: the design is logically correct, it even fits, but it would not work reliably on the chip.
The solution used in regfile.v reads on the rising edge. This works because of the clock enable, which we introduce
in the next section: the CPU executes only one instruction every few million clock cycles. After every instruction, the register file
uses the next rising edge to read the operands of the following instruction, and after that there is plenty of time.
The only condition: two instructions must never be executed in two clock cycles in a row. Strictly speaking, our CPU
is now no longer a single-cycle CPU - every instruction needs at least two clock cycles. In part 4 we will meet
CPUs that use several clock cycles per instruction on purpose.
Clock, reset and output
The CPU itself needs only small changes in cpu.v: a clock enable input ce, and two debug outputs. All storing parts -
PC, register file and data memory - only change when ce is 1:
1
2
3
always @(posedge clk)
if (rst) pc <= 0;
else if (ce) pc <= pc_next;
The debug output dbg_x1 is a copy of register x1, updated on every write to x1. We need it because the contents of a block RAM
cannot be watched from outside - and hierarchical names, which we used in the testbench of chapter 26, do not exist on a chip.
Everything else happens in the top module for the board:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Top module for the Nandland Go Board: the CPU from chapter 26 on the iCE40 HX1K.
//
// - clock enable: the CPU executes CE_DIV-th clock cycle one instruction.
// With CE_DIV = 6,250,000: 4 instructions per second at 25 MHz.
// - reset: automatically after power-up, and while button 1 is pressed.
// - output: the lowest byte of register x1 as two hex digits on the 7-segment displays,
// the instruction number (PC / 4) on the four LEDs.
module go_board_top #(
parameter CE_DIV = 6_250_000 // must be at least 2, see regfile.v
) (
input wire i_Clk, // 25 MHz
input wire i_Switch_1, // reset
output wire o_LED_1,
output wire o_LED_2,
output wire o_LED_3,
output wire o_LED_4,
output wire o_Segment1_A, o_Segment1_B, o_Segment1_C, o_Segment1_D,
output wire o_Segment1_E, o_Segment1_F, o_Segment1_G,
output wire o_Segment2_A, o_Segment2_B, o_Segment2_C, o_Segment2_D,
output wire o_Segment2_E, o_Segment2_F, o_Segment2_G
);
// ---- reset ------------------------------------------------------------------
// The button is not synchronous to the clock: two flip-flops in a row (synchronizer)
// keep a metastable state away from the rest of the circuit.
reg [1:0] sw_sync = 2'b00;
always @(posedge i_Clk)
sw_sync <= {sw_sync[0], i_Switch_1};
// power-on reset: the first 15 clock cycles after configuration
reg [3:0] por = 4'd0;
always @(posedge i_Clk)
if (por != 4'd15) por <= por + 1;
wire rst = (por != 4'd15) | sw_sync[1];
// ---- clock enable ---------------------------------------------------------------
// Instead of a slower clock, ce is 1 for exactly one cycle every CE_DIV cycles.
// The whole design runs on the 25 MHz clock, which stays on the global clock network.
reg [$clog2(CE_DIV)-1:0] div = 0;
reg ce = 1'b0;
always @(posedge i_Clk)
if (div == CE_DIV - 1) begin div <= 0; ce <= 1'b1; end
else begin div <= div + 1; ce <= 1'b0; end
// ---- CPU --------------------------------------------------------------------------
wire [31:0] pc, x1;
cpu #(.PROGRAM("program.hex")) cpu (
.clk(i_Clk), .rst(rst), .ce(ce), .dbg_pc(pc), .dbg_x1(x1)
);
// ---- output -------------------------------------------------------------------------
assign {o_LED_4, o_LED_3, o_LED_2, o_LED_1} = pc[5:2]; // instruction number 0..6
wire [6:0] seg_hi, seg_lo; // {g,f,e,d,c,b,a}, 1 = on
seven_seg dec_hi (.value(x1[7:4]), .seg(seg_hi));
seven_seg dec_lo (.value(x1[3:0]), .seg(seg_lo));
// the segments of the Go Board are active low
assign {o_Segment1_G, o_Segment1_F, o_Segment1_E, o_Segment1_D,
o_Segment1_C, o_Segment1_B, o_Segment1_A} = ~seg_hi;
assign {o_Segment2_G, o_Segment2_F, o_Segment2_E, o_Segment2_D,
o_Segment2_C, o_Segment2_B, o_Segment2_A} = ~seg_lo;
endmodule
Clock enable instead of a slower clock. We could divide the clock with a counter and use one of its bits as the clock of the CPU. On an FPGA, this is a bad idea: the clock is distributed over a special network that reaches all flip-flops at the same time, and a self-made clock would not run on it. So the whole design runs at 25 MHz, and
ceis 1 for exactly one clock cycle every 6,250,000 cycles: 4 instructions per second.Reset. For the first 15 clock cycles after loading the configuration, the CPU is held in reset (power-on reset). After that, button 1 resets it. The button is not synchronous to the clock, so it first passes through two flip-flops in a row, a synchronizer. It keeps a metastable state - a flip-flop that is caught exactly while its input changes - away from the CPU. That a button bounces does not matter for a reset.
Output. The lowest byte of x1 appears as two hex digits on the displays, with the decoder from chapter 23 - inverted again, because the segments are active low. The LEDs show the number of the next instruction, PC / 4.
Simulating the complete design
Before the design goes onto the chip, we simulate it as a whole - including clock enable, reset and display. The testbench sets CE_DIV to 4, so one instruction is executed every 4 clock cycles:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
`timescale 1ns / 1ps
// Testbench for the complete Go Board design.
// CE_DIV = 4 instead of 6,250,000: one instruction every 4 clock cycles.
// The testbench prints one line per instruction and checks the result at the end:
// x1 = 10, the PC loops at 0x18, and the displays show "0A".
// The LEDs show the instruction number of the NEXT instruction (PC / 4).
module go_board_top_tb;
reg clk = 0, sw1 = 0;
wire l1, l2, l3, l4;
wire s1a, s1b, s1c, s1d, s1e, s1f, s1g;
wire s2a, s2b, s2c, s2d, s2e, s2f, s2g;
integer n = 0;
reg [31:0] pc_now;
always #20 clk = ~clk; // 25 MHz
go_board_top #(.CE_DIV(4)) dut (
.i_Clk(clk), .i_Switch_1(sw1),
.o_LED_1(l1), .o_LED_2(l2), .o_LED_3(l3), .o_LED_4(l4),
.o_Segment1_A(s1a), .o_Segment1_B(s1b), .o_Segment1_C(s1c), .o_Segment1_D(s1d),
.o_Segment1_E(s1e), .o_Segment1_F(s1f), .o_Segment1_G(s1g),
.o_Segment2_A(s2a), .o_Segment2_B(s2b), .o_Segment2_C(s2c), .o_Segment2_D(s2d),
.o_Segment2_E(s2e), .o_Segment2_F(s2f), .o_Segment2_G(s2g)
);
// one line per executed instruction (at every clock edge with ce = 1, after reset)
always @(posedge clk)
if (dut.ce && !dut.rst) begin
n = n + 1;
pc_now = dut.cpu.pc; // PC of the instruction executed now
#1 $display("instruction %2d PC=0x%02h x1=%2d -> LEDs show %b%b%b%b",
n, pc_now[7:0], dut.cpu.dbg_x1, l4, l3, l2, l1);
end
initial begin
$dumpfile("go_board_top.vcd");
$dumpvars(0, go_board_top_tb);
#(40 * 4 * 40); // 40 instructions
$display("display: left gfedcba = %b%b%b%b%b%b%b, right gfedcba = %b%b%b%b%b%b%b (0 = on)",
s1g, s1f, s1e, s1d, s1c, s1b, s1a, s2g, s2f, s2e, s2d, s2c, s2b, s2a);
if (dut.cpu.dbg_x1 == 10 && dut.cpu.pc == 32'h18 &&
{s1g, s1f, s1e, s1d, s1c, s1b, s1a} == ~7'b0111111 && // "0"
{s2g, s2f, s2e, s2d, s2c, s2b, s2a} == ~7'b1110111) // "A"
$display("PASSED: x1 = 10, display shows 0A, CPU loops at 0x18");
else
$display("FAILED: x1 = %0d, PC = 0x%h", dut.cpu.dbg_x1, dut.cpu.pc);
$finish;
end
endmodule
instruction 1 PC=0x00 x1= 0 -> LEDs show 0001 instruction 2 PC=0x04 x1= 0 -> LEDs show 0010 instruction 3 PC=0x08 x1= 0 -> LEDs show 0011 instruction 4 PC=0x0c x1= 1 -> LEDs show 0100 instruction 5 PC=0x10 x1= 1 -> LEDs show 0101 instruction 6 PC=0x14 x1= 1 -> LEDs show 0011 ... instruction 31 PC=0x0c x1=10 -> LEDs show 0100 instruction 32 PC=0x10 x1=10 -> LEDs show 0101 instruction 33 PC=0x14 x1=10 -> LEDs show 0110 instruction 34 PC=0x18 x1=10 -> LEDs show 0110 display: left gfedcba = 1000000, right gfedcba = 0001000 (0 = on) PASSED: x1 = 10, display shows 0A, CPU loops at 0x18
The same 33 instructions as in chapter 26. At the end, the left display shows "0" and the right one "A": 10 in hexadecimal.
The result
make for the complete CPU:
Info: ICESTORM_LC: 839/ 1280 65% Info: ICESTORM_RAM: 4/ 16 25% Info: SB_IO: 20/ 112 17% Info: Max frequency for clock 'i_Clk$SB_IO_IN_$glb_clk': 29.94 MHz (PASS at 25.00 MHz) Info: Max frequency for clock 'i_Clk$SB_IO_IN_$glb_clk': 30.31 MHz (PASS at 25.00 MHz)
Here are all three attempts side by side:
| Variant | Logic cells | Block RAM | Max. frequency | Result |
|---|---|---|---|---|
CPU from chapter 26, unchanged | 4126 (322 %) | 0 | - | does not fit |
register file in block RAM, read on the falling edge | 779 (60 %) | 4 | 15.4 MHz | timing fails |
register file in block RAM, read on the rising edge | 839 (65 %) | 4 | 30.3 MHz | PASS |
The critical path in the report starts at the output of the register file’s block RAM and runs through about 27 LUTs - the ALU from chapter 26, which we built from single cells, the comparison for the branch and the selection of the next PC - until the next PC is stored. Of its 33 ns, only 13.3 ns are spent in the logic, and 19.7 ns on the wires between the cells. On an FPGA, routing often costs more time than the logic itself.
The CPU counts on real hardware
make prog loads the CPU onto the board. Four times per second it executes an instruction: the LEDs show where it is in the program,
and every three instructions x1 increases by one on the displays - 01, 02, … 09, 0A. After about 8 seconds, it has arrived
in the endless loop at 0x18, and the display stays at 0A.
Simulation vs. hardware: a checklist
What works in simulation does not automatically work on the chip. Before the next design goes onto an FPGA:
Is everything that matters led out through a port? Otherwise Yosys removes it.
Does every register have a defined start value? By reset, or by an initial value that the chip supports.
Should a memory become block RAM? Then it must be read on a clock edge. Check:
SB_RAM40_4Kmust appear inmake stat.Are there delays,
$displayor hierarchical names in the design? They belong in the testbench.Are external signals like buttons synchronous to the clock? If not: synchronizer, and debouncing where it matters.
Does the design run on the clock network? Slower operation with a clock enable, not with a self-made clock.
What do the reports say? Utilization below 100 %, and
PASSat the frequency of the board.
Try it yourself
Single-step mode. Change
go_board_top.vso that button 2 executes exactly one instruction per press. You will need a synchronizer, a debouncer - a pressed button bounces for a few milliseconds - and a circuit that turns the press into a singlecepulse.A different display. Show the PC instead of x1 on the displays.
The ALU with the
+operator. Replace the ALU from single cells inalu.vwithassign result = a + b;and so on. How do the number of logic cells and the maximum frequency change? Hint: look forSB_CARRYinmake stat.How big can the data memory get? Increase it step by step from 8 words. At which size does the CPU no longer fit?
Summary
An FPGA consists of logic cells - a 4-input LUT, a flip-flop and carry logic -, block RAM, I/O cells and a programmable routing network. The bitstream configures all of them.
The open-source toolchain for the iCE40: Yosys synthesizes the RTL code into a netlist, nextpnr places, routes and checks the timing, icepack creates the bitstream, iceprog loads it onto the board.
Every step has a report: the cells after synthesis, the utilization after place & route, the maximum frequency after the timing analysis.
The CPU from chapter 26 only fit onto the chip after two changes to its memories: a smaller data memory, and a register file in block RAM that is read on the rising edge thanks to the clock enable.
Verilog that works in simulation is not yet Verilog for a specific chip. Memories must be described the way the chip can build them, and the timing must be met.
With this, part 3 is complete: from the schematic of part 2 to a CPU on a real chip.
In part 4 we will make the CPU faster - with performance measurements, pipelining, and the problems that come with it.
(Created with Claude AI)