Hardware · SystemVerilog

When a CPU guesses wrong.

A two-stage Hack processor that predicts jumps in fetch, checks them in execute, and corrects the path after a miss.

Illustrated switch representing branch prediction
Branch prediction in a two-stage processor

Why the pipeline matters

For a computing systems capstone, I extended an existing Hack CPU implementation with a two-stage pipeline, global-history branch prediction, and fused instructions. The underlying files for earlier projects come from jopdorp/nand2tetris-verilog; the README identifies my changes.

The prediction mechanism

A global history register stores recent branch outcomes. A pattern history table contains two-bit saturating counters, from 00 (strongly not taken) to 11 (strongly taken). An eight-entry branch target buffer caches destinations. Fetch can redirect only when the instruction is a branch, the pattern table predicts taken, and a matching target is available.

Execute resolves the actual branch. If the next address differs from the prediction, the processor redirects fetch and inserts a NOP bubble in execute, discarding the instruction on the wrong path.

A recorded correction

The homepage simulation includes a trace around 190 ns in which the predicted next address is 5 but the correct next address is 7. The subsequent clock edge squashes the wrong-path instruction. Those are simulation timestamps, not hardware frequency measurements.

Source and tests