Pipelining

Pipelining

Recap of chapter 32: The multi-cycle CPU splits an instruction into steps, but in every cycle most parts are idle (during EX the instruction memory does nothing, during MEM the ALU does nothing …​). Idea: let every part work on a different instruction at the same time - like an assembly line, or like the classic laundry example: washer, dryer, folding - the next load goes into the washer as soon as the first one moves to the dryer. Goal of this chapter: the five-stage pipeline in Verilog, and the first look at what goes wrong.

Tip

All examples of this chapter are in the folder 33_pipelining of our repository hdl-training: 00-cpu. If you cloned it earlier, git pull fetches the latest version.

The pipelined CPU

The assembly line idea

Note

We discuss different terms for performance here: latency, throughput

  • latency: how long ONE instruction takes from fetch to write back

  • throughput: how many instructions finish per unit of time

  • pipelining does NOT make a single instruction faster - it makes MORE instructions finish

Pipeline diagram: instructions as rows, clock cycles as columns

Counting: k stages, n instructions, no stalls:

\[ \text{cycles} = k + (n - 1) \]

The first instruction needs k cycles to "fill" the pipeline, after that one instruction finishes per cycle.

Counter program: 5 + (33 - 1) = 37 cycles (the preview number from chapter 31).

  • For large n, the CPI approaches 1 - with the short 200 ps clock of the multi-cycle CPU.

The five stages

  • The five stages are the same steps as in the multi-cycle CPU (chapter 32) - but now each one is a separate piece of hardware: IF (instruction fetch: instruction memory, PC + 4) | ID (instruction decode: decoder, register file, immediate) | EX (execute: ALU, branch target) | MEM (memory access: data memory, branch decision) | WB (write back: write register)

  • Every instruction runs through all five stages, even if it does nothing in one of them (add in MEM, sw in WB). Reason: two instructions must never want the same stage in the same cycle. ⇒ latency per instruction is now 5 × 200 ps = 1000 ps, even for add (single-cycle: 800 ps for every instruction).

  • The clock is set by the slowest stage (200 ps) - stages should be balanced. ID and WB only need 100 ps (same loss as in chapter 32).

  • Why no hardware can be shared any more (contrast to chapter 32):

    • the ALU is busy with EX of one instruction while IF of another needs PC + 4 ⇒ separate adder

    • instruction and data memory are needed in the same cycle (IF and MEM) ⇒ two memories

    • sharing would create a STRUCTURAL HAZARD (term, explained properly in chapter 34)

Note

RISC vs. CISC - why pipelining fits RISC so well

In chapter 15 we divided instruction sets into RISC (reduced instruction set computer, e.g. RISC-V, ARM, MIPS) and CISC (complex instruction set computer, e.g. x86). Now we can see why the difference matters so much:

  • Same length for every instruction (32 bits for RISC-V): IF always fetches exactly one word, and ID knows where the register numbers are before it knows what the instruction does. x86 instructions are 1 to 15 bytes long - the processor has to decode an instruction before it even knows where the next one starts.

  • Load/store architecture: only lw and sw access memory, so every instruction needs memory at most once, in its MEM stage. A CISC instruction like add [address], eax reads memory, adds and writes memory again - it does not fit into one pass through five stages.

  • Simple, regular instructions: every instruction passes through the same stages in the same order. Complex CISC instructions were executed by a microprogram over many cycles (the box in chapter 32).

That is why RISC was developed together with pipelining in the early 1980s (Berkeley RISC by David Patterson, Stanford MIPS by John Hennessy - the authors of our textbook). CISC did not disappear: modern x86 processors translate their complex instructions into simple, RISC-like micro-operations and pipeline those.

Pipeline registers

The pipelined data path with the four pipeline registers

Between two stages sits a pipeline register (IF/ID, ID/EX, EX/MEM, MEM/WB); at every rising edge, every instruction moves one stage further. Compare with chapter 32 (table): the multi-cycle registers (IR, A, B, ALUOut, MDR) hold values of ONE instruction, the pipeline registers hold values of up to FOUR different instructions at the same time.

Multi-cycle (ch. 32)

Pipeline (ch. 33)

What is in the registers?

values of one instruction

values of up to four instructions

Hardware

shared (one ALU)

one piece per stage

Control

FSM, per cycle

signals travel with the instruction

  • What an instruction carries along (from cpu.v):

    • IF/ID: PC, instruction

    • ID/EX: PC, rd1, rd2, imm, rd, funct3/funct7, control signals for EX, MEM, WB

    • EX/MEM: branch target, Zero/taken, ALU result, rd2 (store data), rd, control signals for MEM, WB

    • MEM/WB: memory data, ALU result, rd, control signals for WB

  • The orange line: why rd must travel to WB and come back - IF/ID already holds a different instruction when the result is written. (A classic bug in a first pipeline design.)

Control in the pipeline

Surprise: the control unit becomes simple again - the combinational control from chapter 17 (control.v), unchanged, in the ID stage. No FSM any more. The control signals are generated once in ID and travel through the pipeline registers; each stage uses its group and passes the rest on (EX: ALUSrc, ALUOp; MEM: MemRead, MemWrite, Branch; WB: RegWrite, MemtoReg).

Empty stage after reset ("bubble"): all control signals 0 ⇒ nothing happens.

Two details

  • Register file: an instruction writes in WB while a later one reads in ID - in the SAME cycle. Textbooks: write in the first half of the cycle, read in the second half. Here: write-through in regfile.v (if the register is being written right now, pass the new value through) - no negative clock edge (see chapter 27, why the negative edge hurts on the FPGA).

  • Branch decision in MEM: the PC gets the branch target only at the end of the MEM stage of the branch. By then, the three following instructions are already in IF, ID and EX - and they are executed.

The pipelined CPU in Verilog

  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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Pipelined RISC-V CPU (chapter 33): the single-cycle data path from chapter 26,
// cut into 5 stages by 4 pipeline registers.
//
//    IF  --IF/ID-->  ID  --ID/EX-->  EX  --EX/MEM-->  MEM  --MEM/WB-->  WB
//   fetch          decode,         ALU,             data memory,      write back
//                  read registers  branch target    branch decision
//
// Every stage works on a different instruction in the same clock cycle. At every rising
// edge, each instruction moves one stage further, together with everything it still needs
// later: its control signals, its operands, its destination register.
//
// This pipeline has NO hazard handling: it does not notice when an instruction needs a
// result that is not written yet (data hazard, chapter 34), and it does not stop the
// instructions behind a taken branch (control hazard, chapter 35). The program has to take
// care of that itself (program_nops.hex).
//
// The registers *_pc and *_inst are carried along only so the testbench can show which
// instruction is in which stage. The CPU itself does not need them after ID (except the
// PC for the branch target in EX).
module cpu #(
    parameter PROGRAM = "program_nops.hex"
) (
    input  wire clk,
    input  wire rst
);
    // =========================================================================
    // IF: instruction fetch
    // =========================================================================
    reg  [31:0] pc;
    wire [31:0] inst;
    wire [31:0] pc_plus4 = pc + 4;

    instr_mem #(.PROGRAM(PROGRAM)) imem (.addr(pc), .inst(inst));

    // the branch decision comes back from the MEM stage (see below)
    wire        pc_src;
    wire [31:0] branch_target_mem;
    wire [31:0] pc_next = pc_src ? branch_target_mem : pc_plus4;

    always @(posedge clk)
        if (rst) pc <= 0;
        else     pc <= pc_next;

    // ---- pipeline register IF/ID ---------------------------------------------
    reg [31:0] if_id_pc, if_id_inst;

    always @(posedge clk)
        if (rst) begin
            if_id_pc   <= 0;
            if_id_inst <= 0;               // 0 = empty stage ("bubble"), every control signal is 0
        end else begin
            if_id_pc   <= pc;
            if_id_inst <= inst;
        end

    // =========================================================================
    // ID: decode and read registers
    // =========================================================================
    wire [6:0] opcode = if_id_inst[6:0];
    wire [4:0] rs1    = if_id_inst[19:15];
    wire [4:0] rs2    = if_id_inst[24:20];

    wire       reg_write, alu_src, mem_to_reg, mem_read, mem_write, branch;
    wire [1:0] alu_op;

    control ctl (
        .opcode(opcode), .reg_write(reg_write), .alu_src(alu_src),
        .mem_to_reg(mem_to_reg), .mem_read(mem_read), .mem_write(mem_write),
        .branch(branch), .alu_op(alu_op)
    );

    wire [31:0] rd1, rd2, imm;

    // the write port is driven by the WB stage: a DIFFERENT, older instruction
    wire        wb_reg_write;
    wire [4:0]  wb_rd;
    wire [31:0] wb_data;

    regfile rf (
        .clk(clk), .rs1(rs1), .rs2(rs2), .rd1(rd1), .rd2(rd2),
        .we(wb_reg_write), .rd(wb_rd), .wd(wb_data)
    );
    imm_gen ig (.inst(if_id_inst), .imm(imm));

    // ---- pipeline register ID/EX ---------------------------------------------
    // control signals for the later stages
    reg        id_ex_reg_write, id_ex_mem_to_reg;                 // for WB
    reg        id_ex_mem_read, id_ex_mem_write, id_ex_branch;     // for MEM
    reg        id_ex_alu_src;  reg [1:0] id_ex_alu_op;            // for EX
    // data
    reg [31:0] id_ex_pc, id_ex_rd1, id_ex_rd2, id_ex_imm, id_ex_inst;
    reg [4:0]  id_ex_rd;
    reg [2:0]  id_ex_funct3;
    reg        id_ex_funct7_5;

    always @(posedge clk)
        if (rst) begin
            {id_ex_reg_write, id_ex_mem_to_reg, id_ex_mem_read, id_ex_mem_write,
             id_ex_branch, id_ex_alu_src, id_ex_alu_op} <= 0;
            id_ex_inst <= 0;  id_ex_pc <= 0;
        end else begin
            id_ex_reg_write  <= reg_write;
            id_ex_mem_to_reg <= mem_to_reg;
            id_ex_mem_read   <= mem_read;
            id_ex_mem_write  <= mem_write;
            id_ex_branch     <= branch;
            id_ex_alu_src    <= alu_src;
            id_ex_alu_op     <= alu_op;
            id_ex_pc         <= if_id_pc;
            id_ex_rd1        <= rd1;
            id_ex_rd2        <= rd2;
            id_ex_imm        <= imm;
            id_ex_rd         <= if_id_inst[11:7];
            id_ex_funct3     <= if_id_inst[14:12];
            id_ex_funct7_5   <= if_id_inst[30];
            id_ex_inst       <= if_id_inst;
        end

    // =========================================================================
    // EX: execute (ALU) and compute the branch target
    // =========================================================================
    wire [3:0]  alu_ctrl;
    wire [31:0] alu_b = id_ex_alu_src ? id_ex_imm : id_ex_rd2;
    wire [31:0] alu_result;
    wire        zero, overflow;

    alu_control actl (.alu_op(id_ex_alu_op), .funct7_5(id_ex_funct7_5),
                      .funct3(id_ex_funct3), .alu_ctrl(alu_ctrl));

    alu #(.N(32)) alu (
        .a(id_ex_rd1), .b(alu_b), .ctrl(alu_ctrl),
        .result(alu_result), .zero(zero), .overflow(overflow)
    );

    wire [31:0] branch_target = id_ex_pc + id_ex_imm;
    wire        branch_taken  = zero ^ id_ex_funct3[0];          // funct3[0] = 1 for bne

    // ---- pipeline register EX/MEM --------------------------------------------
    reg        ex_mem_reg_write, ex_mem_mem_to_reg;
    reg        ex_mem_mem_read, ex_mem_mem_write, ex_mem_branch;
    reg [31:0] ex_mem_branch_target, ex_mem_alu_result, ex_mem_rd2, ex_mem_pc, ex_mem_inst;
    reg        ex_mem_taken;
    reg [4:0]  ex_mem_rd;

    always @(posedge clk)
        if (rst) begin
            {ex_mem_reg_write, ex_mem_mem_to_reg, ex_mem_mem_read,
             ex_mem_mem_write, ex_mem_branch} <= 0;
            ex_mem_inst <= 0; ex_mem_pc <= 0;
        end else begin
            ex_mem_reg_write     <= id_ex_reg_write;
            ex_mem_mem_to_reg    <= id_ex_mem_to_reg;
            ex_mem_mem_read      <= id_ex_mem_read;
            ex_mem_mem_write     <= id_ex_mem_write;
            ex_mem_branch        <= id_ex_branch;
            ex_mem_branch_target <= branch_target;
            ex_mem_taken         <= branch_taken;
            ex_mem_alu_result    <= alu_result;
            ex_mem_rd2           <= id_ex_rd2;      // the value sw stores
            ex_mem_rd            <= id_ex_rd;
            ex_mem_pc            <= id_ex_pc;
            ex_mem_inst          <= id_ex_inst;
        end

    // =========================================================================
    // MEM: data memory access and branch decision
    // =========================================================================
    wire [31:0] mem_data;

    data_mem dmem (
        .clk(clk), .addr(ex_mem_alu_result), .mem_read(ex_mem_mem_read),
        .mem_write(ex_mem_mem_write), .wd(ex_mem_rd2), .rd(mem_data)
    );

    // back to the PC: by now, 3 more instructions have been fetched behind the branch
    assign pc_src            = ex_mem_branch & ex_mem_taken;
    assign branch_target_mem = ex_mem_branch_target;

    // ---- pipeline register MEM/WB --------------------------------------------
    reg        mem_wb_reg_write, mem_wb_mem_to_reg;
    reg [31:0] mem_wb_mem_data, mem_wb_alu_result, mem_wb_pc, mem_wb_inst;
    reg [4:0]  mem_wb_rd;

    always @(posedge clk)
        if (rst) begin
            {mem_wb_reg_write, mem_wb_mem_to_reg} <= 0;
            mem_wb_inst <= 0; mem_wb_pc <= 0;
        end else begin
            mem_wb_reg_write  <= ex_mem_reg_write;
            mem_wb_mem_to_reg <= ex_mem_mem_to_reg;
            mem_wb_mem_data   <= mem_data;
            mem_wb_alu_result <= ex_mem_alu_result;
            mem_wb_rd         <= ex_mem_rd;
            mem_wb_pc         <= ex_mem_pc;
            mem_wb_inst       <= ex_mem_inst;
        end

    // =========================================================================
    // WB: write back (into the register file in the ID stage, see above)
    // =========================================================================
    assign wb_reg_write = mem_wb_reg_write;
    assign wb_rd        = mem_wb_rd;
    assign wb_data      = mem_wb_mem_to_reg ? mem_wb_mem_data : mem_wb_alu_result;
endmodule
  • What changed compared to the single-cycle CPU of chapter 26: only cuts and registers, the components (ALU, register file, memories, control, imm_gen) are the same modules.

  • regfile.v (write-through), instr_mem.v (filled with nop so instructions fetched beyond a branch are harmless).

  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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
`timescale 1ns / 1ps

// Testbench for the pipelined CPU (chapter 33): runs the counter program with nops
// (program_nops.hex). One line per clock cycle shows which instruction is in which stage,
// like the pipeline diagram in the chapter. At the end, the result and the performance
// are checked and compared with chapters 31 and 32.
module cpu_tb;
    reg clk = 0, rst = 1;
    always #5 clk = ~clk;                       // simulation only: 10 ns per cycle

    cpu #(.PROGRAM("program_nops.hex")) dut (.clk(clk), .rst(rst));

    // copies of single array elements, so they appear in the waveform (see chapter 26)
    wire [31:0] x1   = dut.rf.regs[1];
    wire [31:0] x3   = dut.rf.regs[3];
    wire [31:0] mem4 = dut.dmem.mem[1];         // byte address 4 = word 1

    localparam TRACE_CYCLES = 30;               // how many cycles are printed
    localparam [31:0] BNE_ADDR = 32'h20;        // the program is done after the 10th bne

    // short name of an instruction for the diagram
    function [8*5-1:0] mnemonic(input [31:0] i);
        case (i[6:0])
            7'b0110011: case (i[14:12])
                            3'b000:  mnemonic = i[30] ? "sub" : "add";
                            3'b111:  mnemonic = "and";
                            3'b110:  mnemonic = "or";
                            default: mnemonic = "?";
                        endcase
            7'b0010011: mnemonic = (i == 32'h00000013) ? "nop" : "addi";
            7'b0000011: mnemonic = "lw";
            7'b0100011: mnemonic = "sw";
            7'b1100011: mnemonic = i[12] ? "bne" : "beq";
            default:    mnemonic = "-";          // empty stage after reset
        endcase
    endfunction

    // the instruction in the WB stage is the one that completes in this cycle
    wire [31:0] wb_inst  = dut.mem_wb_inst;
    wire        wb_nop   = (wb_inst == 32'h00000013) || (wb_inst == 0);
    wire        wb_bne   = (wb_inst[6:0] == 7'b1100011) && (dut.mem_wb_pc == BNE_ADDR);

    integer cycles = 0, useful = 0, nops = 0, bnes = 0, writes = 0, errors = 0;
    reg finished = 0;

    always @(posedge clk)
        if (!rst && !finished) begin
            cycles = cycles + 1;
            if (cycles <= TRACE_CYCLES)
                $display("cycle %3d   IF %-4s %02h   ID %-4s %02h   EX %-4s %02h   MEM %-4s %02h   WB %-4s %02h",
                         cycles,
                         mnemonic(dut.inst),        dut.pc[7:0],
                         mnemonic(dut.if_id_inst),  dut.if_id_pc[7:0],
                         mnemonic(dut.id_ex_inst),  dut.id_ex_pc[7:0],
                         mnemonic(dut.ex_mem_inst), dut.ex_mem_pc[7:0],
                         mnemonic(wb_inst),         dut.mem_wb_pc[7:0]);
            if (cycles == TRACE_CYCLES + 1) $display("...");

            // every store must write the next number
            if (dut.ex_mem_mem_write) begin
                writes = writes + 1;
                if (dut.ex_mem_rd2 !== writes) begin
                    errors = errors + 1;
                    $display("ERROR: store %0d writes %0d", writes, dut.ex_mem_rd2);
                end
            end

            // count the instructions that complete in WB
            if (wb_nop) begin
                if (wb_inst != 0) nops = nops + 1;
            end else
                useful = useful + 1;
            if (wb_bne) begin
                bnes = bnes + 1;
                if (bnes == 10) finished = 1;   // the last bne has left the pipeline
            end
        end

    initial begin
        $dumpfile("cpu.vcd");
        $dumpvars(0, cpu_tb);
        #12 rst = 0;
        wait (finished);
        @(negedge clk);

        $display("");
        $display("%0d useful instructions + %0d nops in %0d cycles", useful, nops, cycles);
        $display("  CPI (useful instructions only) = %.2f", 1.0 * cycles / useful);
        $display("  CPU time with 200 ps per cycle: %0d x 200 ps = %.1f ns", cycles, cycles * 0.2);
        $display("  for comparison: single-cycle 26.4 ns, multi-cycle 24.4 ns,");
        $display("                  ideal pipeline without nops 37 x 200 ps = 7.4 ns");
        if (x1 == 10 && x3 == 10 && mem4 == 10 && writes == 10 && errors == 0
            && useful == 33 && cycles == 85)
            $display("PASSED: counted to 10, 33 useful instructions in 85 cycles");
        else
            $display("FAILED: x1 = %0d, memory[4] = %0d, %0d writes, %0d instructions, %0d cycles",
                     x1, mem4, writes, useful, cycles);
        $finish;
    end
endmodule
  • Testbench cpu_tb.v: prints which instruction is in which stage - the pipeline diagram from above, produced by the simulation. Output (first cycles):

cycle   1   IF addi 00   ID -    00   EX -    00   MEM -    00   WB -    00
cycle   2   IF addi 04   ID addi 00   EX -    00   MEM -    00   WB -    00
cycle   3   IF addi 08   ID addi 04   EX addi 00   MEM -    00   WB -    00
cycle   4   IF nop  0c   ID addi 08   EX addi 04   MEM addi 00   WB -    00
cycle   5   IF add  10   ID nop  0c   EX addi 08   MEM addi 04   WB addi 00
...
  • Point out: the diagonal - one instruction moves down-right; one column = one moment in time, five instructions.

It does not work yet: hazards

 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
`timescale 1ns / 1ps

// What goes wrong without the nops (chapter 33, outlook to chapters 34 and 35):
// the SAME pipelined CPU runs the ORIGINAL counter program from chapter 26 (program.hex),
// which works perfectly on the single-cycle and the multi-cycle CPU.
//
// Two things go wrong:
//   - data hazard:    "add x1, x1, x2" reads x2 before "addi x2, x0, 1" has written it,
//                     "sw" and "bne" read x1 before "add" has written it
//   - control hazard: the 3 instructions behind "bne" are executed even when the branch
//                     is taken, among them "beq x0, x0, done" at 0x18
//
// The testbench prints every store and every branch decision for 40 cycles and then
// compares the result with what the program SHOULD do. The FAILED at the end is expected.
module hazard_tb;
    reg clk = 0, rst = 1;
    always #5 clk = ~clk;

    cpu #(.PROGRAM("program.hex")) dut (.clk(clk), .rst(rst));

    wire [31:0] x1   = dut.rf.regs[1];
    wire [31:0] mem4 = dut.dmem.mem[1];

    integer cycles = 0, writes = 0;

    always @(posedge clk)
        if (!rst) begin
            cycles = cycles + 1;
            if (dut.ex_mem_mem_write) begin
                writes = writes + 1;
                $display("cycle %2d  sw  at 0x%02h stores %0d  (should be %0d)",
                         cycles, dut.ex_mem_pc[7:0], dut.ex_mem_rd2, writes);
            end
            if (dut.ex_mem_branch)
                $display("cycle %2d  %s at 0x%02h %s  -> next fetch from 0x%02h",
                         cycles, dut.ex_mem_inst[12] ? "bne" : "beq", dut.ex_mem_pc[7:0],
                         dut.pc_src ? "taken    " : "not taken", dut.pc_next[7:0]);
        end

    initial begin
        #12 rst = 0;
        #400;                                   // 40 cycles: more than enough for 33 instructions

        $display("");
        $display("after 40 cycles: x1 = %0d, memory[4] = %0d, %0d stores", x1, mem4, writes);
        if (x1 == 10 && mem4 == 10 && writes == 10)
            $display("PASSED (unexpected!)");
        else
            $display("FAILED as expected: should be x1 = 10, memory[4] = 10, 10 stores.");
        $display("The pipeline needs hazard handling: chapter 34 (data) and chapter 35 (control).");
        $finish;
    end
endmodule
  • hazard_tb.v runs the same counter program as cpu_tb.v, but without nops. It fails: the store instruction writes 0 instead of 1, and the program gets stuck in an endless loop at 0x18 after one store.

Important

Two causes (terms only, the solutions follow in chapters 34 and 35):

  • DATA HAZARD: add x1, x1, x2 reads x2 before addi x2 has written it (written in WB, read in ID - one cycle too early; sw and bne read x1 even two cycles too early)

  • CONTROL HAZARD: the 3 instructions behind bne are executed even when the branch is taken (here: beq x0,x0,0 at 0x18 - the program jumps into its own end)

  • (STRUCTURAL HAZARD: avoided by design - two memories, separate adders)

The workaround for now: the program keeps enough distance itself ⇒ program_nops.hex

  • at least 2 instructions between writing and reading a register

  • 3 instructions behind every branch

  • gaps filled with nop (= addi x0, x0, 0)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// The counter program from chapter 26, prepared for the pipeline WITHOUT hazard handling (chapter 33).
// The pipeline itself does not notice dependencies, so the program has to keep enough distance:
//   - a value written by one instruction can be read at the earliest 3 instructions later
//     (the producer writes it in WB while the consumer reads it in ID, see regfile.v)
//   - a branch is decided in the MEM stage: the 3 instructions after it are already in
//     the pipeline and are always executed
// Every gap is filled with "nop" = addi x0, x0, 0, which changes nothing.
00000093  // 0x00:        addi x1, x0, 0      x1 = 0  (counter)
00100113  // 0x04:        addi x2, x0, 1      x2 = 1  (step)
00a00193  // 0x08:        addi x3, x0, 10     x3 = 10 (end value)
00000013  // 0x0C:        nop                 add needs x2: only 2 instructions after 0x04
002080b3  // 0x10: loop:  add  x1, x1, x2     x1 = x1 + x2
00000013  // 0x14:        nop                 sw needs the new x1 ...
00000013  // 0x18:        nop                 ... so 2 nops in between
00102223  // 0x1C:        sw   x1, 4(x0)      memory[4] = x1
fe3098e3  // 0x20:        bne  x1, x3, loop   offset -16
00000013  // 0x24:        nop                 these 3 instructions are already in the pipeline
00000013  // 0x28:        nop                 when bne is decided, so they must not
00000013  // 0x2C:        nop                 do anything
00000063  // 0x30: done:  beq  x0, x0, done   endless loop, offset 0

Early MIPS processors left part of this to the compiler: the instruction after a branch was always executed (branch delay slot), and the compiler had to put something useful - or a nop - there.

Performance: was it worth it?

Measured by cpu_tb.v: 33 useful instructions + 48 nops in 85 cycles
CPI (useful instructions) = 2.58, CPU time 85 × 200 ps = 17.0 ns

Comparison (performance equation, chapter 31):

CPU

cycles

T

CPU time

speedup

single-cycle

33

800 ps

26.4 ns

1.0

multi-cycle

122

200 ps

24.4 ns

1.08

pipeline with nops

85

200 ps

17.0 ns

1.55

ideal pipeline

37

200 ps

7.4 ns

3.6

More than half of all executed instructions are nops ⇒ the gap between 17.0 ns and 7.4 ns is the motivation for the upcoming chapters 34 and 35. Still ignored: register overhead per stage (clock-to-Q + setup, chapter 31) - it hurts more with more stages.

Pipelines in real processors

  • The classic five-stage pipeline goes back to the MIPS R2000 (1985). Our CPU uses the same five stages, but for RISC-V - the textbook by Patterson & Hennessy did the same (why RISC suits pipelining: see the box in the section on the five stages).

  • Longer pipelines ⇒ shorter stages ⇒ higher clock - but more hazards and more register overhead. Example: Intel went from 10 stages (Pentium III) to 20 (Pentium 4, 2000) and 31 (Pentium 4 "Prescott", 2004), then back to much shorter pipelines in the following Core processors - the clock gain no longer paid for the losses.

  • Small microcontrollers use short pipelines (e.g. ARM Cortex-M0: 3 stages, see microcontroller vs. microprocessor).

Try it yourself

  • Draw the pipeline diagram for the first 10 cycles of program_nops.hex by hand, then compare with cpu_tb.v.

  • Move sw behind bne into one of the three slots ("delayed branch", early MIPS). It is executed anyway - one nop less per loop. How many cycles now? (the testbench’s end condition has to be adapted: the last sw now comes after the last bne)

  • What if the branch were decided in EX instead of MEM? How many nops are needed behind bne, and how many cycles result?

  • Remove the write-through from regfile.v: which program fails, and how many nops would be needed instead?

  • With 20 ps register overhead per stage: T = 220 ps - recompute the table.

Summary

  • Pipelining overlaps instructions: every stage works on a different instruction.

  • Latency of one instruction does not improve (it gets worse), throughput does: ideally one instruction per cycle.

  • Pipeline registers separate the stages and carry data AND control signals along; rd must travel to WB.

  • The control unit is combinational again (chapter 17), placed in ID.

  • Without help, the pipeline computes wrong results (data and control hazards). With nops it works, but only 1.55× faster instead of 3.6×.

  • Outlook: chapter 34 removes most data-hazard nops (forwarding, stalls), chapter 35 the branch nops (flush, branch prediction).

(Outlined with Claude AI, written by Sven Wehrend)