For the Embedded Computer Architecture (ECA) project we built a five-stage pipelined RISC-V processor in Verilog, together with Shaunak Sarang Moharir and Ajay Rathakrishnan Thulasimani. The processor runs a 2D matrix convolution: a kernel applied to a signed integer matrix, producing an output matrix.

We then made it faster in two steps: first by rewriting the assembly program, then by adding a custom multiply-accumulate (MAC) instruction to the hardware.

VersionCyclesSpeedup
Baseline12,5131.00×
Software optimized2,1015.96×
Software + MAC instruction1,7387.20×

Why Verilog

The testbench, the RAM and ROM models and the test generator that came with the project are all written in Verilog, so a Verilog core plugs straight into them. For the same reason we kept the port list of CustomCore and the testbench parameter names unchanged. Verilog also fits the work well: pipeline registers, forwarding muxes and control signals are described at register-transfer level, which maps directly onto the block diagrams below. We used Icarus Verilog for simulation and Yosys to check that the design is synthesizable.


Baseline architecture

The processor has the classic five stages:

  • IF (instruction fetch): fetches the instruction at the program counter
  • ID (instruction decode): decodes the instruction and reads the register operands
  • EX (execute): arithmetic and branch decisions
  • MEM (memory access): loads and stores
  • WB (write-back): selects the result that is written to the register file

The design is based on the pipelined RISC-V processor from Harris & Harris, Digital Design and Computer Architecture: RISC-V Edition:

The pipelined RISC-V processor with hazard unit from Harris & Harris, which our design is based on.

Our version differs from it in four ways, all following from the project interface and our implementation choices:

  1. The control unit and the extend unit are merged into one decoder module.
  2. The program counter counts instruction words instead of bytes.
  3. Branch conditions are evaluated by a separate compare unit instead of the ALU zero flag.
  4. Forwarding and hazard detection are split over two modules.

Our baseline datapath.

Decoder and immediate generation

The decoder generates all control signals for an instruction plus a sign-extended 32-bit immediate. By default the immediate comes from bits [31:20] (I-type, used by addi, slli, lw and jalr). For sw, branches, jal and lui it is taken from the S-, B-, J- and U-type formats instead. Since the decoder picks the format from the opcode itself, no separate immediate-source signal is needed. alu_src_imm selects a register or immediate as the second ALU input, and the uses_rs1 / uses_rs2 flags tell the hazard unit which source registers are actually read.

Word-indexed PC

The instruction ROM is indexed by instruction words, so the PC holds a word index and advances by one instead of four. Byte quantities only show up where the instruction set requires them:

  • A branch or jal target is the current PC plus the byte offset divided by four, imm[IW+1:2].
  • The return address of jal and jalr is converted back to a byte address, {pc+1, 2'b00}.
  • The jalr target, which the ALU computes as rs1 + immediate, is divided by four again.

The behaviour is therefore identical to a byte-addressed PC.

Branching and supported instructions

The compare unit evaluates branch conditions on the forwarded register values, selected by funct3, and supports all six RISC-V conditional branches: beq, bne, blt, bge, bltu and bgeu. A redirect happens when a branch condition holds or for jal/jalr: the PC loads the target, IF/ID is cleared and a bubble goes into ID/EX, so a taken control transfer costs two cycles.

RequiredImplementation
lw, swaddress rs1 + imm computed in the ALU
add, mul, addi, slliALU addition, multiplication (low 32 bits), addition with immediate, left shift
eq, nebeq, bne in the branch compare unit
lt, gtblt; bgt = blt with swapped operands
unconditional branchj = jal x0, target pc + imm/4
retjalr x0, 0(ra), target from the ALU
labelsresolved by the assembler into PC-relative offsets
extrabge, bltu, bgeu, sub, lui

Hazard handling

  • Forwarding: the forwarding unit compares the source registers of the instruction in EX with the destination registers in EX/MEM and MEM/WB, and selects the EX/MEM result (01) or the write-back value (10). If both match, the newer EX/MEM value wins, and x0 is never forwarded. The forwarded rs2 value also serves as store data.
  • Register-file write-through: an operand can receive a value that is being written back in the same cycle.
  • Load-use stall: when a load in EX writes a register that the instruction in ID reads, the hazard unit holds the PC and IF/ID and clears the control bits of ID/EX for one cycle. Because the check is qualified by uses_rs1 and uses_rs2, the immediate field of an I-type instruction can’t cause a false stall.
  • Control hazards: control transfers are resolved in EX and the two younger instructions are flushed.

Memory interface and program end

The data address is the EX/MEM result divided by four. The RAM registers its read data, so the loaded word arrives on data_memory_read in WB and is selected there, which means the MEM/WB register doesn’t need to store read data. When a jalr with target 0 reaches EX, the finish_q register is set: it signals completion to the testbench, freezes the PC and blocks further memory writes.

Baseline limitations

The pipeline overlaps instructions fine, but the original convolution program does a lot of work besides the actual arithmetic: matrix addresses are recalculated over and over, kernel coefficients are loaded multiple times, separate loop counters add extra instructions, and multiply and add are separate instructions. All of that adds up to 12,513 cycles.


Optimization 1: Software

The first optimization only touches the assembly program, not the hardware.

  • Kernel reuse: the four kernel coefficients are loaded into registers once and kept there for the whole convolution.
  • Pointer-based addressing: each input element is 4 bytes and each row has 13 elements, so the row stride is 52 bytes. The four samples of each window are at byte offsets 0, 4, 52 and 56 from the current input pointer, and the output pointer advances by 4 bytes after each store.
  • Simpler loop control: instead of separate row and column counters, the loop compares the output pointer with the end of the row and the end of the output matrix.

This brings the static instruction count from 42 to 28, and the cycle count from 12,513 to 2,101 (a 5.96× speedup). The savings come from three places:

  1. The loop body shrinks from about 91 instructions per output to 15: 4 loads, 4 multiplies, 3 adds, 1 store, 2 pointer updates and 1 branch.
  2. The 4 loads are issued before their first use, so all 484 load-use stalls of the baseline disappear.
  3. One pointer comparison replaces the 3-instruction counter update and compare for every output.

We considered keeping counter-based loops and recomputed addresses, but every extra instruction in the loop is repeated 121 times, so they were dropped.


Optimization 2: Custom MAC instruction

After the software rewrite, each output element still needs four multiplications and three additions. So we added a multiply-accumulate instruction:

It uses the custom-0 opcode 0001011 with funct3 = 000 and funct7 = 0000000.

The datapath with the MAC changes highlighted in orange.

Datapath and control changes

MAC reads three source values (rs1, rs2 and rd), which takes some extra hardware:

  • The register file gets a third read port, and the accumulator value is carried through ID/EX into EX.
  • The ALU multiplies the first two operands and adds the accumulator.
  • The forwarding unit gets an extra path to forward the newest accumulator value from EX/MEM or WB, needed when consecutive MACs accumulate into the same register.
  • The hazard unit stalls when a load is directly followed by a MAC that accumulates into the loaded register.
  • x0 stays protected from writes.

Trade-offs

MAC removes three instructions from every output, but costs a third read port with its selection logic, another forwarding path and mux, and a longer critical path through the ALU (multiply followed by add).

Alternatives we considered

  • Auto-incrementing loads/stores: would fold the pointer updates into the memory instructions and save about 240 cycles, but needs a second register-file write port.
  • Static backward-taken branch prediction: would resolve loop branches in ID and cut the taken-branch penalty from two cycles to one, but the 12 loop exits would be mispredicted. The estimated net saving was only about 85 cycles while touching the control path and flush logic.
  • Sliding window: keeping the previous column in registers would halve the loads per output, but needs more registers and a more complex loop.
  • Asynchronous RAM read: rejected, since ram.v stays unchanged and the pipeline already absorbs the one-cycle read latency in WB.

MAC won because it removes three instructions per output without adding a stall and without touching the control path. With it, the cycle count drops to 1,738.


Verification and results

Every version runs on the project testbench, which feeds random input and kernel matrices from the project generator and compares the output region of the RAM with a reference convolution. All three versions pass 10/10 random tests, plus 10/10 tests with inputs spanning the full signed 32-bit range to check the wraparound behaviour of the multiplier and the MAC accumulation.

On top of that, directed assembly tests check each instruction group separately: every conditional branch taken and not taken with positive and negative operands, jal and ret with the flush, the ALU instructions including sub, lui and signed multiplication, and eight load-use and forwarding cases. Seven more cases cover MAC: a single MAC, three back-to-back MACs (forwarding rd from EX/MEM), a MAC one instruction after another (forwarding from WB), rd used as rs1, a negative operand, a load directly before a MAC into the loaded register (the added stall), and x0 as destination. The synthesizability script finishes with exit code 0 and no warnings for both the baseline and the MAC core.

Cycle counts are measured from reset release until the finish signal rises, by a separate monitor module that only observes testbench signals (so testbench.v stays untouched). They’re the same for every test, since the timing doesn’t depend on the data.

MetricBaselineSoftwareSoftware + MAC
Static instructions422825
Executed instructions≈11,0601,8581,495
Load-use stalls48400
Flush cycles≈966240240
Cycles (measured)12,5132,1011,738
CPI1.131.131.16
Speedup vs baseline1.00×5.96×7.20×

Each cycle count equals the executed instructions, plus stall and flush cycles, plus about three cycles of pipeline fill, so the totals can be checked by hand (the two ≈ baseline entries are calculated rather than counted). The software rewrite removes 83% of the executed instructions and all stalls. MAC removes 363 more instructions for 17% fewer cycles. Its CPI is slightly higher (1.16 vs 1.13) because the same 240 flush cycles are spread over fewer instructions. Those flushes, from 120 taken loop branches, are now the largest remaining cost at 14% of the final cycle count.


Conclusion

The core supports the full required instruction set, including all conditional branches, jumps and returns, and handles data and control hazards with forwarding, a load-use stall and a two-cycle flush. Rewriting the program took the convolution from 12,513 to 2,101 cycles, and the custom MAC instruction brought it down to 1,738: 7.20× faster than the baseline overall. Most of the gain came from software, while the instruction-set extension added another 17% at the cost of a third register-file read port, an extra forwarding path and a longer ALU path.

Reference

S. L. Harris and D. M. Harris, Digital Design and Computer Architecture: RISC-V Edition. Cambridge, MA, USA: Morgan Kaufmann, 2022.