Data Hazards and Forwarding

The pipeline of S2.7 gave 0 where the instruction set says 12. An instruction read a register that was still on its way. This page hands the value over on the way, at no cost of cycles.

You Will Be Able To

  • Say when two instructions have a data hazard, from the distance between them.
  • Say from which stage a forwarded operand comes, for a writer one and two instructions ahead.
  • Read forwarding in a pipeline grid, for ALU operands and for the data of a store.
Lesson
S2.8
Time
30 min
Runs on
Icarus service
Check
6 questions

Look again at the hazard of S2.7. When the add needed x5, the 7 was not lost and not late. It sat in a pipeline register, two stages ahead, in plain sight. The only place that did not have it yet was the register file.

Before You Start

You need the five stages and the pipeline grid from S2.7. You need its last section too: the register that is still on its way.

You need the pipeline registers from S2.24: what EX/MEM and MEM/WB carry.

Five questions this page answers
Question
1What is a data hazard, and how close must two instructions be to have one?
2Where is the value that the reader needs while the reader is in EX?
3What does the forwarding unit compare?
4Which values of an instruction can be forwarded?
5What does forwarding cost?

The Idea: The Value Exists, Take It from Where It Is

Call an instruction that writes a register the writer. Call a later instruction that reads that register the reader. In a pipeline the reader may read before the writer has written.

That is a data hazard. Its full name is a read-after-write hazard. In program order the read comes after the write. In the pipeline it happens first.

The cure starts from one fact. The ALU makes the result of an add in EX. From then on the result exists. It travels through EX/MEM and MEM/WB for two cycles before it is written.

The reader needs the value in EX, where its own ALU is. So the pipeline gets two extra paths. One runs from EX/MEM back to the ALU inputs. One runs from MEM/WB.

Handing a value over on such a path is called forwarding. A small block, the forwarding unit, decides in every cycle which path each ALU input takes.

New Words

New words on this page
WordMeaning
Data hazardA hazard about a value: an instruction would use an old value of a register.
Read-after-write hazardThe data hazard of this pipeline. The reader reads before the writer, which is ahead of it, has written.
ForwardingHanding a result from a pipeline register straight to the stage that needs it.
Forwarding unitThe block that decides, for each operand of the instruction in EX, where its value comes from.
Forwarding multiplexerA multiplexer in front of an ALU input. It chooses among ID/EX, EX/MEM and MEM/WB.
forward_aThe select of the forwarding multiplexer for rs1. forward_b is the one for rs2.
FORWARD_NONEThe select value for the value read in ID. FORWARD_MEM and FORWARD_WB name the two other sources.

One Picture: Two Paths Back to the ALU

Two Ways Back to the ALUStep through the picture. It shows sub x8, x7, x6 of the lab in EX, in cycle 6. Both of its registers are still on their way.
  • Memory
  • Processor
  • Control / FSM
Two Ways Back to the ALUStep through the picture. It shows sub x8, x7, x6 of the lab in EX, in cycle 6. Both of its registers are still on their way. component ID/EX the two values read inID: both are old component Forwardingmultiplexers one for each operand:three inputs each component ALU works on the twochosen values component EX/MEM the result of theinstruction in MEM component MEM/WB the value that theinstruction in WBwrites component Forwarding unit compares registernumbers, givesforward_a andforward_b values read in IDrs1_value_e,rs2_value_eresultone cycle laterforward from MEMforward from WBforward_a,forward_b
  1. component ID/EXthe two values read in ID: both are old
    • values read in ID → Forwarding multiplexers
  2. component EX/MEMthe result of the instruction in MEM
    • one cycle later → MEM/WB
    • forward from MEM → Forwarding multiplexers
  3. component Forwarding multiplexersone for each operand: three inputs each
    • rs1_value_e, rs2_value_e → ALU
  4. component MEM/WBthe value that the instruction in WB writes
    • forward from WB → Forwarding multiplexers
  5. component Forwarding unitcompares register numbers, gives forward_a and forward_b
    • forward_a, forward_b → Forwarding multiplexers
  6. component ALUworks on the two chosen values
    • result → EX/MEM
  1. What ID read

    The sub read x7 and x6 in cycle 5. Neither was written yet. ID/EX holds two old values, both 0.

  2. Where x7 is

    The add that makes x7 is one instruction ahead. In cycle 6 it is in MEM. Its result, c in hex, is in EX/MEM.

  3. Where x6 is

    The addi that makes x6 is two instructions ahead. In cycle 6 it is in WB, and writes 5 at the end of the cycle. The 5 is in MEM/WB.

  4. The forwarding unit decides

    It sees that MEM writes x7 and WB writes x6. It sets forward_a to MEM and forward_b to WB.

  5. The ALU gets new values

    The multiplexers pass c and 5. The ALU subtracts and gives 7. The two old values in ID/EX are never used.

Read the diagram as text
  • ID/EX: the two values read in ID: both are old
  • Forwarding multiplexers: one for each operand: three inputs each
  • ALU: works on the two chosen values
  • EX/MEM: the result of the instruction in MEM
  • MEM/WB: the value that the instruction in WB writes
  • Forwarding unit: compares register numbers, gives forward_a and forward_b
  • ID/EX → Forwarding multiplexers: values read in ID
  • Forwarding multiplexers → ALU: rs1_value_e, rs2_value_e
  • ALU → EX/MEM: result
  • EX/MEM → MEM/WB: one cycle later
  • EX/MEM → Forwarding multiplexers: forward from MEM
  • MEM/WB → Forwarding multiplexers: forward from WB
  • Forwarding unit → Forwarding multiplexers: forward_a, forward_b

No value goes back in time. Both results existed before cycle 6 began. They only had not reached the register file.

Where the value is, by the distance between writer and reader
The reader comesWhen the reader is in EX, the writer isThe value comes from
right after the writerin MEMEX/MEM: forward from MEM
two instructions afterin WBMEM/WB: forward from WB
three instructions afterdone. It was in WB when the reader was in IDthe register file, with a small addition that S2.25 shows
four or more afterdone before the reader reached IDthe register file: no hazard

On a five-stage pipeline, only the three instructions right behind a writer can have a data hazard with it.

The Smallest Example, Worked by Hand

Take the program of the trap in S2.7: addi x5, x0, 7, then addi x6, x0, 5, then add x7, x5, x6. The add is the third instruction, so it is in EX in cycle 5.

Cycle 5, seen from the add in EX
OperandIts writerWhere the writer is in cycle 5SelectValue
rs1 is x5the first instruction, two aheadWBforward_a = FORWARD_WB7
rs2 is x6the second instruction, one aheadMEMforward_b = FORWARD_MEM5

The values that the add read in ID, in cycle 4, were both 0. They are not used.

The ALU adds 7 and 5 and gives 12. That is what the instruction set says. And the add was in EX in cycle 5, exactly as in S2.7: it did not wait.

The Rules

  1. Rule 1: A data hazard needs a writer and a reader of one register, close together.

    The reader is at most three instructions behind the writer.

  2. Rule 2: The forwarding unit looks at the instruction in EX.

    It compares the two register numbers that EX reads with the rd of the instructions in MEM and in WB.

  3. Rule 3: If the instruction in MEM writes that register, the operand comes from EX/MEM.

    That writer is one instruction ahead.

  4. Rule 4: If the instruction in WB writes it, the operand comes from MEM/WB.

    That writer is two instructions ahead.

  5. Rule 5: Each operand has a select of its own.

    One instruction can take rs1 from MEM and rs2 from WB in the same cycle.

  6. Rule 6: Forwarding costs no cycle.

    It costs two multiplexers in front of the ALU, and they make the path through EX longer.

The real core has a third select value for the plain case. These are the three names, from a file of its source.

From ap_rv32_p5_pkg.sv, as built.
// ---- forward_a and forward_b: where the value of a register operand comes from
localparam logic [1:0] FORWARD_NONE = 2'd0; // the value read from the register file in ID
localparam logic [1:0] FORWARD_MEM  = 2'd1; // the result of the instruction now in MEM
localparam logic [1:0] FORWARD_WB   = 2'd2; // the value that the instruction now in WB writes

Two fine points are left for S2.25. What if MEM and WB both write the register? And what about x0?

Sources for These Rules

Data hazards and forwarding are described here as textbooks commonly describe them. The plan of this track points to Patterson and Hennessy, section 4.7, and to Harris and Harris, section 7.5. Those places are not checked. The forwarding rules of the real core are in docs/soc/ap_rv32-blueprint.md, section 8.2. Every grid on this page is recorded from the lab and from the real core.

Now Run It

The lab at the end of this page runs five instructions. The last three each use a result of the one before. A note in the last column tells where EX takes an operand from: a is rs1, b is rs2.

Printed by the lab on Icarus. The real core ap_rv32_p5 gave the same grid and the same forwarding, cycle by cycle.
cy | IF  ID  EX  MEM  WB | what happens
 1 | 00  --  --  --   -- |
 2 | 04  00  --  --   -- |
 3 | 08  04  00  --   -- |
 4 | 0c  08  04  00   -- |
 5 | 10  0c  08  04   00 | x5=7 a<WB b<MEM
 6 | 14  10  0c  08   04 | x6=5 a<MEM b<WB
 7 | --  14  10  0c   08 | x7=c a<MEM
 8 | --  --  14  10   0c | x8=7
 9 | --  --  --  14   10 | x9=e
x7=12 x8=7 x9=14 cycles=9

Rules 3 and 4 at work: read row 5. The add at 08 is in EX. It takes a from WB, where the instruction at 00 writes x5. It takes b from MEM, where 04 holds the new x6.

Rule 5 at work: row 6 has the two selects the other way round. The sub at 0c takes x7 from MEM and x6 from WB.

Rule 6 at work: five instructions end in row 9. That is 5 plus 4, the count of a pipeline with no hazard at all.

The same run as a pipeline diagram
Instruction123456789
00: addi x5, x0, 7IFIDEXMEMWB
04: addi x6, x0, 5IFIDEXMEMWB
08: add x7, x5, x6IFIDEX: a from WB, b from MEMMEMWB
0c: sub x8, x7, x6IFIDEX: a from MEM, b from WBMEMWB
10: add x9, x8, x5IFIDEX: a from MEMMEMWB
14: ebreakIFIDEXMEM

Drawn from the recorded rows. A forwarded operand is written into the EX cell of its reader.

Now the same program with the forwarding switched off. The lab has a switch named FORWARD for that, and here it is 0. This is the pipeline of S2.7 again, with one small difference that S2.25 explains.

The same lab with FORWARD = 0. The real core with its forwarding selects forced to none gave the same rows.
cy | IF  ID  EX  MEM  WB | what happens
 1 | 00  --  --  --   -- |
 2 | 04  00  --  --   -- |
 3 | 08  04  00  --   -- |
 4 | 0c  08  04  00   -- |
 5 | 10  0c  08  04   00 | x5=7
 6 | 14  10  0c  08   04 | x6=5
 7 | --  14  10  0c   08 | x7=0
 8 | --  --  14  10   0c | x8=0
 9 | --  --  --  14   10 | x9=7
x7=0 (wrong: the instruction set says 12) x8=0 (wrong: the instruction set says 7) x9=7 (wrong: the instruction set says 14) cycles=9

The grid has the same shape and the same nine rows. Only the values differ. So forwarding changed no timing at all: it changed which value the ALU sees.

In the lab, the bench plays the forwarding unit. It keeps a note for each register: in which stage the newest writer is. The real unit compares register numbers. Problem S2.8.1 asks you to build it.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Forward the valueMake the reader wait until the writer is doneNo lost cycle. Waiting would cost up to two cycles for every close pair.
Forward to the start of EXForward to ID, before ID/EXA value made in EX can be used in the very next cycle. The multiplexers add to the longest stage.
Two sources: MEM and WBOne source: MEM onlyA writer two ahead is covered too. Each multiplexer needs one more input.
Decide by register numbersTag every value with its ownerFour small comparisons. The numbers rd must travel to MEM and WB, which they do anyway.
The unit sees only EX, MEM and WBDecide in ID and carry the selectThe choice is made when the values are there. The comparison sits in the longest stage.

The Trap: An Operand That Never Reaches the ALU

It is easy to think of forwarding as a matter of the two ALU inputs. One value of one instruction goes round the ALU: the data of a store.

A store adds rs1 and its offset in the ALU. That is its address. Its rs2 is the value to store. It goes past the ALU, straight into EX/MEM.

Now put the writer of that rs2 right before the store. The program below does it: addi x5, x0, 7 and then sw x5, 0(x10).

The lab with a program of six instructions. The real core gave the same rows.
cy | IF  ID  EX  MEM  WB | what happens
 1 | 00  --  --  --   -- |
 2 | 04  00  --  --   -- |
 3 | 08  04  00  --   -- |
 4 | 0c  08  04  00   -- | a<MEM
 5 | 10  0c  08  04   00 | x10=1
 6 | 14  10  0c  08   04 | x10=80000000 a<WB b<MEM
 7 | 18  14  10  0c   08 | x5=7
 8 | --  18  14  10   0c |
 9 | --  --  18  14   10 | x6=7
10 | --  --  --  18   14 |
x6=7 mem[80000000]=7 cycles=10

Read row 6. The store, at 0c, is in EX. It takes a from WB: that is x10, its address. It takes b from MEM: that is x5, its data.

So the store data needs a forwarding multiplexer just like an ALU operand. A core that forwards only into the ALU stores an old value here. The address is right, and the memory holds a wrong word.

The last line shows that this lab got it right. The load reads back 7.

At Scale

This labarithmetic and stores: 2 selects
ap_rv32_p537 instructions read a register: each was seen forwarded from MEM and from WB

This section looks ahead. The lab forwards for three kinds of instruction. The real core must forward for every instruction that reads a register.

  1. Two matches, and x0

    When MEM and WB both write the register, one of them must win. And a value on its way to x0 must never be used. S2.25 covers both.

  2. A value that is not there yet

    A load has its value only after MEM. An instruction right behind it cannot get it by forwarding. S2.9 makes it wait one cycle.

  3. Branches

    A branch compares two registers in EX. It takes them through the same multiplexers. S2.10 shows what a taken branch costs.

  4. Wider cores

    A core that starts several instructions in a cycle has many more pairs to compare. That is common practice, and no source in the library was checked for it.

Try It

Run the lab. For each note in the last column, name the instruction that made the value.

Set FORWARD to 0 and run again. Which rows change, and which column never changes?

Put addi x0, x0, 0 between the second and the third instruction, with its row. Where does the add take x5 from now?

RUNIcarus Verilog · simulator service
Edit the code, then run it
Expected: cy | IF ID EX MEM WB | what happens 1 | 00 -- -- -- -- | 2 | 04 00 -- -- -- | 3 | 08 04 00 -- -- | 4 | 0c 08 04 00 -- | 5 | 10 0c 08 04 00 | x5=7 a<WB b<MEM 6 | 14 10 0c 08 04 | x6=5 a<MEM b<WB 7 | -- 14 10 0c 08 | x7=c a<MEM 8 | -- -- 14 10 0c | x8=7 9 | -- -- -- 14 10 | x9=e x7=12 x8=7 x9=14 cycles=9
Read included file: ap_rv32_pkg.sv
// ap_rv32_pkg: the named constants of the ap_rv32 core.
// Opcodes, function fields, control-signal values, trap causes and CSR addresses.
// Used by both builds (ap_rv32_sc and ap_rv32). Taught in S2.2 and S2.5.
// Blueprint: docs/soc/ap_rv32-blueprint.md sections 4 (instructions), 5 (CSRs) and 7 (traps).
package ap_rv32_pkg;

  // ---- Opcodes: instruction bits 6:0
  localparam logic [6:0] OPCODE_LUI      = 7'b0110111;
  localparam logic [6:0] OPCODE_AUIPC    = 7'b0010111;
  localparam logic [6:0] OPCODE_JAL      = 7'b1101111;
  localparam logic [6:0] OPCODE_JALR     = 7'b1100111;
  localparam logic [6:0] OPCODE_BRANCH   = 7'b1100011;
  localparam logic [6:0] OPCODE_LOAD     = 7'b0000011;
  localparam logic [6:0] OPCODE_STORE    = 7'b0100011;
  localparam logic [6:0] OPCODE_OP_IMM   = 7'b0010011;
  localparam logic [6:0] OPCODE_OP       = 7'b0110011;
  localparam logic [6:0] OPCODE_MISC_MEM = 7'b0001111;
  localparam logic [6:0] OPCODE_SYSTEM   = 7'b1110011;

  // ---- funct3 (instruction bits 14:12) of the branches
  localparam logic [2:0] FUNCT3_BEQ  = 3'b000;
  localparam logic [2:0] FUNCT3_BNE  = 3'b001;
  localparam logic [2:0] FUNCT3_BLT  = 3'b100;
  localparam logic [2:0] FUNCT3_BGE  = 3'b101;
  localparam logic [2:0] FUNCT3_BLTU = 3'b110;
  localparam logic [2:0] FUNCT3_BGEU = 3'b111;

  // ---- funct3 of the arithmetic instructions (OP and OP_IMM) that the decoder must tell apart.
  // All eight values are the low three bits of alu_operation, below.
  localparam logic [2:0] FUNCT3_ADD_SUB = 3'b000;
  localparam logic [2:0] FUNCT3_SLL     = 3'b001;
  localparam logic [2:0] FUNCT3_SRL_SRA = 3'b101;

  // ---- funct3 of JALR and FENCE. Loads and stores: bits 1:0 are mem_size, bit 2 is unsigned.
  // SYSTEM: 000 is ecall, ebreak, mret, wfi; else bits 1:0 are csr_operation, bit 2 is immediate.
  localparam logic [2:0] FUNCT3_JALR  = 3'b000;
  localparam logic [2:0] FUNCT3_FENCE = 3'b000;

  // ---- funct7 (instruction bits 31:25)
  localparam logic [6:0] FUNCT7_BASE = 7'b0000000;
  localparam logic [6:0] FUNCT7_ALT  = 7'b0100000; // sub, sra, srai

  // ---- Instructions matched on all 32 bits
  localparam logic [31:0] INSTR_ECALL  = 32'h0000_0073;
  localparam logic [31:0] INSTR_EBREAK = 32'h0010_0073;
  localparam logic [31:0] INSTR_MRET   = 32'h3020_0073;
  localparam logic [31:0] INSTR_WFI    = 32'h1050_0073;

  // ---- imm_select: which immediate format the instruction carries
  localparam logic [2:0] IMM_I = 3'd0;
  localparam logic [2:0] IMM_S = 3'd1;
  localparam logic [2:0] IMM_B = 3'd2;
  localparam logic [2:0] IMM_U = 3'd3;
  localparam logic [2:0] IMM_J = 3'd4;

  // ---- alu_operation: bit 3 is instruction bit 30, bits 2:0 are funct3
  localparam logic [3:0] ALU_ADD  = 4'b0000;
  localparam logic [3:0] ALU_SUB  = 4'b1000;
  localparam logic [3:0] ALU_SLL  = 4'b0001;
  localparam logic [3:0] ALU_SLT  = 4'b0010;
  localparam logic [3:0] ALU_SLTU = 4'b0011;
  localparam logic [3:0] ALU_XOR  = 4'b0100;
  localparam logic [3:0] ALU_SRL  = 4'b0101;
  localparam logic [3:0] ALU_SRA  = 4'b1101;
  localparam logic [3:0] ALU_OR   = 4'b0110;
  localparam logic [3:0] ALU_AND  = 4'b0111;

  // ---- alu_a_select and alu_b_select: the two ALU operands
  localparam logic [1:0] ALU_A_RS1  = 2'd0;
  localparam logic [1:0] ALU_A_PC   = 2'd1;
  localparam logic [1:0] ALU_A_ZERO = 2'd2;
  localparam logic       ALU_B_RS2  = 1'b0;
  localparam logic       ALU_B_IMM  = 1'b1;

  // ---- result_select: the value written to rd
  localparam logic [1:0] RESULT_ALU       = 2'd0;
  localparam logic [1:0] RESULT_MEM       = 2'd1;
  localparam logic [1:0] RESULT_PC_PLUS_4 = 2'd2;
  localparam logic [1:0] RESULT_CSR       = 2'd3;

  // ---- mem_size: bytes moved by a load or store (as AHB hsize)
  localparam logic [1:0] SIZE_BYTE = 2'd0;
  localparam logic [1:0] SIZE_HALF = 2'd1;
  localparam logic [1:0] SIZE_WORD = 2'd2;

  // ---- csr_operation: what a CSR instruction does with its operand
  localparam logic [1:0] CSR_OPERATION_NONE  = 2'd0; // not a CSR instruction
  localparam logic [1:0] CSR_OPERATION_WRITE = 2'd1;
  localparam logic [1:0] CSR_OPERATION_SET   = 2'd2;
  localparam logic [1:0] CSR_OPERATION_CLEAR = 2'd3;

  // ---- Trap causes: the value written to mcause (bit 31 marks an interrupt)
  localparam logic [31:0] CAUSE_INSTR_ADDR_MISALIGNED = 32'd0;
  localparam logic [31:0] CAUSE_INSTR_ACCESS_FAULT    = 32'd1;
  localparam logic [31:0] CAUSE_ILLEGAL_INSTRUCTION   = 32'd2;
  localparam logic [31:0] CAUSE_BREAKPOINT            = 32'd3;
  localparam logic [31:0] CAUSE_LOAD_ADDR_MISALIGNED  = 32'd4;
  localparam logic [31:0] CAUSE_LOAD_ACCESS_FAULT     = 32'd5;
  localparam logic [31:0] CAUSE_STORE_ADDR_MISALIGNED = 32'd6;
  localparam logic [31:0] CAUSE_STORE_ACCESS_FAULT    = 32'd7;
  localparam logic [31:0] CAUSE_ECALL_FROM_M          = 32'd11;
  localparam logic [31:0] CAUSE_IRQ_SOFTWARE          = 32'h8000_0003;
  localparam logic [31:0] CAUSE_IRQ_TIMER             = 32'h8000_0007;
  localparam logic [31:0] CAUSE_IRQ_EXTERNAL          = 32'h8000_000b;

  // ---- Bit positions in mstatus, and in mie and mip
  localparam int MSTATUS_MIE_BIT  = 3;
  localparam int MSTATUS_MPIE_BIT = 7;
  localparam int IRQ_SOFTWARE_BIT = 3;
  localparam int IRQ_TIMER_BIT    = 7;
  localparam int IRQ_EXTERNAL_BIT = 11;

  // ---- CSR addresses (blueprint 5.1)
  localparam logic [11:0] CSR_MSTATUS    = 12'h300;
  localparam logic [11:0] CSR_MISA       = 12'h301;
  localparam logic [11:0] CSR_MIE        = 12'h304;
  localparam logic [11:0] CSR_MTVEC      = 12'h305;
  localparam logic [11:0] CSR_MSTATUSH   = 12'h310;
  localparam logic [11:0] CSR_MSCRATCH   = 12'h340;
  localparam logic [11:0] CSR_MEPC       = 12'h341;
  localparam logic [11:0] CSR_MCAUSE     = 12'h342;
  localparam logic [11:0] CSR_MTVAL      = 12'h343;
  localparam logic [11:0] CSR_MIP        = 12'h344;
  localparam logic [11:0] CSR_MCYCLE     = 12'hb00;
  localparam logic [11:0] CSR_MINSTRET   = 12'hb02;
  localparam logic [11:0] CSR_MCYCLEH    = 12'hb80;
  localparam logic [11:0] CSR_MINSTRETH  = 12'hb82;
  localparam logic [11:0] CSR_MVENDORID  = 12'hf11;
  localparam logic [11:0] CSR_MARCHID    = 12'hf12;
  localparam logic [11:0] CSR_MIMPID     = 12'hf13;
  localparam logic [11:0] CSR_MHARTID    = 12'hf14;
  localparam logic [11:0] CSR_MCONFIGPTR = 12'hf15;
  // Performance monitors 3 to 31 exist and read 0: first and last address of each range
  localparam logic [11:0] CSR_MHPMEVENT3      = 12'h323;
  localparam logic [11:0] CSR_MHPMEVENT31     = 12'h33f;
  localparam logic [11:0] CSR_MHPMCOUNTER3    = 12'hb03;
  localparam logic [11:0] CSR_MHPMCOUNTER31   = 12'hb1f;
  localparam logic [11:0] CSR_MHPMCOUNTER3H   = 12'hb83;
  localparam logic [11:0] CSR_MHPMCOUNTER31H  = 12'hb9f;
  // Address bits 11:10 of a read-only CSR
  localparam logic [1:0]  CSR_READ_ONLY = 2'b11;

  // ---- CSR values and write masks (a 1 marks a bit that software can change)
  localparam logic [31:0] MSTATUS_RESET      = 32'h0000_1800; // MPP = 11: machine mode only
  localparam logic [31:0] MSTATUS_WRITE_MASK = 32'h0000_0088; // MIE and MPIE
  localparam logic [31:0] MISA_VALUE         = 32'h4000_0100; // 32 bits, extension I
  localparam logic [31:0] MIMPID_VALUE       = 32'h0001_0000; // ap_rv32 version 1.0
  localparam logic [31:0] MIE_WRITE_MASK     = 32'h0000_0888; // MSIE, MTIE and MEIE
  localparam logic [31:0] MTVEC_WRITE_MASK   = 32'hffff_fffd; // BASE and MODE bit 0
  localparam logic [31:0] MEPC_WRITE_MASK    = 32'hffff_fffc; // instructions are 4-byte aligned
  localparam logic [31:0] ALL_BITS           = 32'hffff_ffff;

  // ---- Data bits that a byte and a half cover, from bit 0
  localparam logic [31:0] BYTE_BITS = 32'h0000_00ff;
  localparam logic [31:0] HALF_BITS = 32'h0000_ffff;

  // ---- Other
  localparam logic [1:0] PRIV_MACHINE   = 2'b11; // the only privilege level in v1.0
  localparam int         REGISTER_COUNT = 32;

endpackage
Read included file: ap_rv32_p5_pkg.sv
// ap_rv32_p5_pkg: the named constants that only the five-stage build needs.
// The forwarding selects of the forward unit, and the AHB-Lite codes of the two bus ports.
// Used by the five-stage build (ap_rv32). Taught in S2.8 and S2.16.
// Blueprint: docs/soc/ap_rv32-blueprint.md sections 8.2 (forwarding) and 3.2 (bus ports).
package ap_rv32_p5_pkg;

  // ---- forward_a and forward_b: where the value of a register operand comes from
  localparam logic [1:0] FORWARD_NONE = 2'd0; // the value read from the register file in ID
  localparam logic [1:0] FORWARD_MEM  = 2'd1; // the result of the instruction now in MEM
  localparam logic [1:0] FORWARD_WB   = 2'd2; // the value that the instruction now in WB writes

  // ---- htrans: the two transfer types the core uses (every transfer is a single transfer)
  localparam logic [1:0] HTRANS_IDLE   = 2'b00;
  localparam logic [1:0] HTRANS_NONSEQ = 2'b10;

  // ---- hburst and hprot: constant on each port
  localparam logic [2:0] HBURST_SINGLE     = 3'b000;
  localparam logic [3:0] HPROT_INSTRUCTION = 4'b0010; // opcode fetch, privileged
  localparam logic [3:0] HPROT_DATA        = 4'b0011; // data access, privileged

endpackage
Read included file: ap_rv32_regfile.sv
// ap_rv32_regfile: the register file.
// 31 registers, x1 to x31, and x0 which always reads 0. Two read ports, one write port.
// A read is combinational; a write happens at the clock edge. All registers reset to 0.
// Used by both builds. Taught in S2.4. Blueprint: sections 2.3 and 6.
module ap_rv32_regfile (
  input  logic        clk,          // clock
  input  logic        rst_n,        // reset, active low
  input  logic [4:0]  rs1_addr,     // first register to read
  output logic [31:0] rs1_data,     // its value
  input  logic [4:0]  rs2_addr,     // second register to read
  output logic [31:0] rs2_data,     // its value
  input  logic        write_enable, // write rd at this clock edge
  input  logic [4:0]  rd_addr,      // register to write; a write to x0 is discarded
  input  logic [31:0] rd_data       // value to write
);
  import ap_rv32_pkg::*;

  logic [31:0] registers_q [1:REGISTER_COUNT-1]; // x1 to x31; x0 has no storage

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      for (int i = 1; i < REGISTER_COUNT; i++) registers_q[i] <= '0;
    end else if (write_enable && rd_addr != '0) begin
      registers_q[rd_addr] <= rd_data;
    end
  end

  assign rs1_data = (rs1_addr == '0) ? '0 : registers_q[rs1_addr];
  assign rs2_data = (rs2_addr == '0) ? '0 : registers_q[rs2_addr];

endmodule
Read included file: ap_rv32_alu.sv
// ap_rv32_alu: the arithmetic and logic unit.
// Add, subtract, shifts, compares and bitwise logic on two 32-bit operands.
// Used by both builds. Taught in S2.4. Blueprint: section 2.3.
module ap_rv32_alu (
  input  logic [3:0]  alu_operation, // operation: one of the ALU_* constants
  input  logic [31:0] operand_a,     // first operand
  input  logic [31:0] operand_b,     // second operand; shifts use only its bits 4:0
  output logic [31:0] result         // result of the operation
);
  import ap_rv32_pkg::*;

  logic [4:0] shift_amount; // number of bit positions to shift by

  assign shift_amount = operand_b[4:0];

  always_comb begin
    result = '0;
    unique case (alu_operation)
      ALU_ADD:  result = operand_a + operand_b;
      ALU_SUB:  result = operand_a - operand_b;
      ALU_SLL:  result = operand_a << shift_amount;
      ALU_SLT:  result = {31'b0, $signed(operand_a) < $signed(operand_b)};
      ALU_SLTU: result = {31'b0, operand_a < operand_b};
      ALU_XOR:  result = operand_a ^ operand_b;
      ALU_SRL:  result = operand_a >> shift_amount;
      ALU_SRA:  result = $signed(operand_a) >>> shift_amount;
      ALU_OR:   result = operand_a | operand_b;
      ALU_AND:  result = operand_a & operand_b;
      default:  result = '0;
    endcase
  end

endmodule

Check Yourself

Predict the outputFour instructions in a row each use the result of the one before. They are x5 = 3, x6 = x5 + x5, x7 = x6 + x5 and x8 = x7 - x6. What does the last line say?
// Four instructions in a row use each other. What does the last line say?
// The bench plays the decoder, the forwarding unit and the hazard unit. The problems of these pages ask for the real ones.
// The files ap_rv32_pkg.sv, ap_rv32_p5_pkg.sv, ap_rv32_regfile.sv, ap_rv32_alu.sv are the files of the real core.
module lab_pipeline (
  input  logic        clk,              // clock
  input  logic        rst_n,            // reset, active low
  output logic [31:0] pc_f,             // IF: the address of the instruction in IF
  input  logic [31:0] instr_f,          // IF: its word, in the same cycle
  output logic [31:0] pc_d,             // ID: the address of the instruction in ID
  input  logic [31:0] imm_d,            // given, for the instruction in ID: the immediate
  input  logic        alu_b_select_d,   // given: second ALU operand, rs2 or the immediate
  input  logic [3:0]  alu_operation_d,  // given: what the ALU does
  input  logic        mem_read_d,       // given: this is a load
  input  logic        mem_write_d,      // given: this is a store
  input  logic        reg_write_d,      // given: this instruction writes rd
  input  logic        bypass_a_d,       // given: rs1 is being written in this cycle: read the new value
  input  logic        bypass_b_d,       // given: the same for rs2
  input  logic [1:0]  forward_a_d,      // given: where EX must take rs1 from, one of FORWARD_*
  input  logic [1:0]  forward_b_d,      // given: the same for rs2
  input  logic        wait_d,           // given: the instruction in ID must wait one cycle
  output logic        dmem_req,         // data memory: a load or store is in MEM
  output logic        dmem_write,       // 1: store; 0: load
  output logic [31:0] dmem_addr,        // its address
  output logic [31:0] dmem_wdata,       // the word to store
  input  logic [31:0] dmem_rdata        // the word that the memory returns, in the same cycle
);
  import ap_rv32_pkg::*;
  import ap_rv32_p5_pkg::*;

  // ---- The four pipeline registers. Each lists what it carries.
  typedef struct packed {
    logic        valid;          // 0: a bubble
    logic [31:0] pc;
    logic [31:0] instr;
  } if_id_t;
  typedef struct packed {
    logic        valid;
    logic [31:0] pc;
    logic [4:0]  rd;
    logic [31:0] rs1_data;       // the two register values, as read in ID
    logic [31:0] rs2_data;
    logic [31:0] imm;
    logic [1:0]  forward_a;      // lab only: the bench decided these in ID
    logic [1:0]  forward_b;
    logic        alu_b_select;   // control signals that EX uses
    logic [3:0]  alu_operation;
    logic        mem_read;       // control signals that MEM uses
    logic        mem_write;
    logic        reg_write;      // control signal that WB uses
  } id_ex_t;
  typedef struct packed {
    logic        valid;
    logic [31:0] pc;
    logic [4:0]  rd;
    logic [31:0] result;         // the ALU result; the address of a load or store
    logic [31:0] store_data;
    logic        mem_read;
    logic        mem_write;
    logic        reg_write;
  } ex_mem_t;
  typedef struct packed {
    logic        valid;
    logic [31:0] pc;
    logic [4:0]  rd;
    logic [31:0] result;
    logic [31:0] load_data;      // the word that the data memory returned
    logic        mem_read;
    logic        reg_write;
  } mem_wb_t;

  if_id_t  d_q;  // IF/ID:  what ID works on
  id_ex_t  e_q;  // ID/EX:  what EX works on
  ex_mem_t m_q;  // EX/MEM: what MEM works on
  mem_wb_t w_q;  // MEM/WB: what WB works on

  logic [31:0] pc_q;            // the PC
  logic [31:0] rs1_stored_d;    // value of rs1 in the register file
  logic [31:0] rs2_stored_d;    // value of rs2 in the register file
  logic [31:0] rs1_data_d;      // value of rs1 that ID hands to EX
  logic [31:0] rs2_data_d;      // value of rs2 that ID hands to EX
  logic [31:0] rs1_value_e;     // value of rs1 after forwarding
  logic [31:0] rs2_value_e;     // value of rs2 after forwarding
  logic [31:0] alu_operand_b_e; // second ALU operand
  logic [31:0] alu_result_e;    // ALU result
  logic [31:0] rd_data_w;       // value written to rd

  // ---- IF: the PC addresses the instruction memory. A waiting ID keeps the PC and IF/ID.
  assign pc_f = pc_q;

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      pc_q <= '0;
      d_q  <= '0;
    end else if (!wait_d) begin
      pc_q      <= pc_q + 32'd4;
      d_q.valid <= 1'b1;
      d_q.pc    <= pc_q;
      d_q.instr <= instr_f;
    end
  end

  // ---- ID: read two registers. The decoder is the bench: it looks at pc_d.
  assign pc_d = d_q.pc;

  ap_rv32_regfile u_regfile (
    .clk(clk), .rst_n(rst_n),
    .rs1_addr(d_q.instr[19:15]), .rs1_data(rs1_stored_d),
    .rs2_addr(d_q.instr[24:20]), .rs2_data(rs2_stored_d),
    .write_enable(w_q.valid && w_q.reg_write), .rd_addr(w_q.rd), .rd_data(rd_data_w)
  );

  assign rs1_data_d = bypass_a_d ? rd_data_w : rs1_stored_d;
  assign rs2_data_d = bypass_b_d ? rd_data_w : rs2_stored_d;

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      e_q <= '0;
    end else begin
      e_q.valid         <= d_q.valid && !wait_d;   // a waiting ID sends a bubble
      e_q.pc            <= d_q.pc;
      e_q.rd            <= d_q.instr[11:7];
      e_q.rs1_data      <= rs1_data_d;
      e_q.rs2_data      <= rs2_data_d;
      e_q.imm           <= imm_d;
      e_q.forward_a     <= forward_a_d;
      e_q.forward_b     <= forward_b_d;
      e_q.alu_b_select  <= alu_b_select_d;
      e_q.alu_operation <= alu_operation_d;
      e_q.mem_read      <= mem_read_d;
      e_q.mem_write     <= mem_write_d;
      e_q.reg_write     <= reg_write_d;
    end
  end

  // ---- EX: the forwarding multiplexers, then the ALU.
  assign rs1_value_e = (e_q.forward_a == FORWARD_MEM) ? m_q.result
                     : (e_q.forward_a == FORWARD_WB)  ? rd_data_w : e_q.rs1_data;
  assign rs2_value_e = (e_q.forward_b == FORWARD_MEM) ? m_q.result
                     : (e_q.forward_b == FORWARD_WB)  ? rd_data_w : e_q.rs2_data;

  assign alu_operand_b_e = (e_q.alu_b_select == ALU_B_IMM) ? e_q.imm : rs2_value_e;

  ap_rv32_alu u_alu (
    .alu_operation(e_q.alu_operation), .operand_a(rs1_value_e), .operand_b(alu_operand_b_e),
    .result(alu_result_e)
  );

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      m_q <= '0;
    end else begin
      m_q.valid      <= e_q.valid;
      m_q.pc         <= e_q.pc;
      m_q.rd         <= e_q.rd;
      m_q.result     <= alu_result_e;
      m_q.store_data <= rs2_value_e;
      m_q.mem_read   <= e_q.mem_read;
      m_q.mem_write  <= e_q.mem_write;
      m_q.reg_write  <= e_q.reg_write;
    end
  end

  // ---- MEM: the data memory.
  assign dmem_req   = m_q.valid && (m_q.mem_read || m_q.mem_write);
  assign dmem_write = m_q.mem_write;
  assign dmem_addr  = m_q.result;
  assign dmem_wdata = m_q.store_data;

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      w_q <= '0;
    end else begin
      w_q.valid     <= m_q.valid;
      w_q.pc        <= m_q.pc;
      w_q.rd        <= m_q.rd;
      w_q.result    <= m_q.result;
      w_q.load_data <= dmem_rdata;
      w_q.mem_read  <= m_q.mem_read;
      w_q.reg_write <= m_q.reg_write;
    end
  end

  // ---- WB: choose the value for rd. The write port of the register file is in ID, above.
  assign rd_data_w = w_q.mem_read ? w_q.load_data : w_q.result;
endmodule

module tb;
  import ap_rv32_pkg::*;
  import ap_rv32_p5_pkg::*;
  localparam bit FORWARD = 1;   // 1: operands are forwarded from MEM and WB. 0: never
  logic        clk = 0, rst_n = 1;
  logic [31:0] pc_f, instr_f, pc_d, imm_d, dmem_addr, dmem_wdata, dmem_rdata;
  logic        alu_b_select_d, mem_read_d, mem_write_d, reg_write_d, bypass_a_d, bypass_b_d, wait_d, dmem_req, dmem_write;
  logic [3:0]  alu_operation_d;
  logic [1:0]  forward_a_d, forward_b_d;

  lab_pipeline dp (.*);

  // ---- What the decoder says for each class of instruction (S2.5), and which registers the class reads.
  //                                reg_write, alu_b_select, mem_read, mem_write, reads rs1, reads rs2
  localparam logic [5:0] OP_IMM = {1'b1, ALU_B_IMM, 1'b0, 1'b0, 1'b1, 1'b0};
  localparam logic [5:0] OP     = {1'b1, ALU_B_RS2, 1'b0, 1'b0, 1'b1, 1'b1};
  localparam logic [5:0] STOP   = {1'b0, ALU_B_IMM, 1'b0, 1'b0, 1'b0, 1'b0};

  // ---- The memories of the bench.
  logic [31:0] rom [0:63];          // instruction memory, from address 0
  logic [5:0]  given [0:63];        // the control class of each row
  logic [3:0]  operation [0:63];    // the ALU operation of each row
  logic [31:0] immediate [0:63];    // the immediate of each row
  string       text [0:63];         // the assembly of each row
  logic [31:0] ram [0:255];         // data memory, 1 KiB from address 8000_0000
  int rows = 0, cycles = 0;
  task automatic row(input logic [31:0] word, input logic [5:0] control, input logic [3:0] alu, input logic [31:0] immediate_value, input string assembly);
    rom[rows] = word;  given[rows] = control;  operation[rows] = alu;  immediate[rows] = immediate_value;  text[rows] = assembly;  rows++;
  endtask

  // ---- The program.
  initial begin
    for (int n = 0; n < 64; n++) begin rom[n] = 0;  given[n] = STOP;  operation[n] = ALU_ADD;  immediate[n] = 0; end
    for (int n = 0; n < 256; n++) ram[n] = 0;
    //  word          class   ALU      immediate    assembly
    row(32'h0030_0293, OP_IMM, ALU_ADD, 32'd3,      "addi x5, x0, 3");   // 00
    row(32'h0052_8333, OP,     ALU_ADD, 32'd0,      "add x6, x5, x5");   // 04
    row(32'h0053_03b3, OP,     ALU_ADD, 32'd0,      "add x7, x6, x5");   // 08
    row(32'h4063_8433, OP,     ALU_SUB, 32'd0,      "sub x8, x7, x6");   // 0c
    row(32'h0010_0073, STOP,   ALU_ADD, 32'd0,      "ebreak");   // 10
    #1 rst_n = 0;   // a real falling edge: the reset is asynchronous
    #2 rst_n = 1;
  end
  always #5 clk = ~clk;

  // ---- The bench as the two memories and as the decoder.
  logic rs1_read_d, rs2_read_d;
  assign instr_f         = rom[pc_f[7:2]];
  assign imm_d           = dp.d_q.valid ? immediate[pc_d[7:2]] : 32'd0;   // a bubble has no immediate
  assign alu_operation_d = operation[pc_d[7:2]];
  assign {reg_write_d, alu_b_select_d, mem_read_d, mem_write_d, rs1_read_d, rs2_read_d} = given[pc_d[7:2]];
  assign dmem_rdata      = ram[dmem_addr[9:2]];
  always @(posedge clk) if (rst_n && dmem_req && dmem_write) ram[dmem_addr[9:2]] <= dmem_wdata;

  // ---- The bench as the forwarding unit and the hazard unit.
  // One note for each register: where is the newest instruction that writes it?
  //   0: not in the pipeline. The register file has the value.     1: in EX.     2: in MEM.     3: in WB.
  logic [31:0][1:0] where_q, where_next;
  logic [31:0]      load_q, load_next;    // that instruction is a load
  logic [4:0]       rs1_d, rs2_d, rd_d;
  logic [1:0]       newest_a, newest_b;
  assign rs1_d = dp.d_q.instr[19:15];
  assign rs2_d = dp.d_q.instr[24:20];
  assign rd_d  = dp.d_q.instr[11:7];
  assign newest_a = (rs1_read_d && rs1_d != 0) ? where_q[rs1_d] : 2'd0;
  assign newest_b = (rs2_read_d && rs2_d != 0) ? where_q[rs2_d] : 2'd0;

  // A writer in WB now: the register file is being written. A writer in MEM now is in WB in the next
  // cycle, when this instruction is in EX. A writer in EX now is in MEM then.
  assign bypass_a_d  = 1'b1 && (newest_a == 2'd3);
  assign bypass_b_d  = 1'b1 && (newest_b == 2'd3);
  assign forward_a_d = !FORWARD ? FORWARD_NONE : (newest_a == 2'd1) ? FORWARD_MEM : (newest_a == 2'd2) ? FORWARD_WB : FORWARD_NONE;
  assign forward_b_d = !FORWARD ? FORWARD_NONE : (newest_b == 2'd1) ? FORWARD_MEM : (newest_b == 2'd2) ? FORWARD_WB : FORWARD_NONE;
  // A load in EX has no data yet. An instruction that needs it must wait.
  assign wait_d = 1'b1 && dp.d_q.valid && ((newest_a == 2'd1 && load_q[rs1_d]) || (newest_b == 2'd1 && load_q[rs2_d]));

  always @* begin
    where_next = where_q;
    load_next  = load_q;
    for (int r = 0; r < 32; r++) if (where_q[r] != 2'd0) where_next[r] = where_q[r] + 2'd1;   // 3 becomes 0
    if (dp.d_q.valid && !wait_d && reg_write_d && rd_d != 0) begin   // it moves to EX at this edge
      where_next[rd_d] = 2'd1;
      load_next[rd_d]  = mem_read_d;
    end
  end
  always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin where_q <= '0;  load_q <= '0; end
    else begin where_q <= where_next;  load_q <= load_next; end
  end

  // ---- What is printed. The grid shows the instructions of the program, by address.
  // The pipeline fetches on behind the ebreak. Those words are never executed and are not shown.
  localparam logic [31:0] STOP_PC = 32'd16;
  function automatic string at(input logic valid, input logic [31:0] pc);
    if (valid && pc <= STOP_PC) return $sformatf("%02h", pc[7:0]);
    return "--";
  endfunction
  function automatic logic [31:0] register(input int n);   // the value of register n, read from inside the register file
    return (n == 0) ? 32'd0 : dp.u_regfile.registers_q[n];
  endfunction
  string note;
  initial $display("cy | IF  ID  EX  MEM  WB | what happens");
  always @(posedge clk) if (rst_n) begin
    cycles++;
    note = "";
    if (dp.u_regfile.write_enable && dp.u_regfile.rd_addr != 0) note = {note, $sformatf(" x%0d=%0h", dp.u_regfile.rd_addr, dp.u_regfile.rd_data)};
    if (dp.e_q.valid && dp.e_q.forward_a == FORWARD_MEM) note = {note, " a<MEM"};
    if (dp.e_q.valid && dp.e_q.forward_a == FORWARD_WB)  note = {note, " a<WB"};
    if (dp.e_q.valid && dp.e_q.forward_b == FORWARD_MEM) note = {note, " b<MEM"};
    if (dp.e_q.valid && dp.e_q.forward_b == FORWARD_WB)  note = {note, " b<WB"};
    if (wait_d) note = {note, " stall"};
    $display("%2d | %s  %s  %s  %s   %s |%s", cycles, at(1'b1, pc_f), at(dp.d_q.valid, dp.d_q.pc), at(dp.e_q.valid, dp.e_q.pc),
      at(dp.m_q.valid, dp.m_q.pc), at(dp.w_q.valid, dp.w_q.pc), note);
    if ((dp.m_q.valid && dp.m_q.pc == STOP_PC) || cycles >= 60) begin   // the ebreak has reached MEM
      @(negedge clk);   // let the last write of this edge happen
      $display("x8=%0d cycles=%0d", register(8), cycles);
      $finish;
    end
  end
endmodule
Read included file: ap_rv32_pkg.sv
// ap_rv32_pkg: the named constants of the ap_rv32 core.
// Opcodes, function fields, control-signal values, trap causes and CSR addresses.
// Used by both builds (ap_rv32_sc and ap_rv32). Taught in S2.2 and S2.5.
// Blueprint: docs/soc/ap_rv32-blueprint.md sections 4 (instructions), 5 (CSRs) and 7 (traps).
package ap_rv32_pkg;

  // ---- Opcodes: instruction bits 6:0
  localparam logic [6:0] OPCODE_LUI      = 7'b0110111;
  localparam logic [6:0] OPCODE_AUIPC    = 7'b0010111;
  localparam logic [6:0] OPCODE_JAL      = 7'b1101111;
  localparam logic [6:0] OPCODE_JALR     = 7'b1100111;
  localparam logic [6:0] OPCODE_BRANCH   = 7'b1100011;
  localparam logic [6:0] OPCODE_LOAD     = 7'b0000011;
  localparam logic [6:0] OPCODE_STORE    = 7'b0100011;
  localparam logic [6:0] OPCODE_OP_IMM   = 7'b0010011;
  localparam logic [6:0] OPCODE_OP       = 7'b0110011;
  localparam logic [6:0] OPCODE_MISC_MEM = 7'b0001111;
  localparam logic [6:0] OPCODE_SYSTEM   = 7'b1110011;

  // ---- funct3 (instruction bits 14:12) of the branches
  localparam logic [2:0] FUNCT3_BEQ  = 3'b000;
  localparam logic [2:0] FUNCT3_BNE  = 3'b001;
  localparam logic [2:0] FUNCT3_BLT  = 3'b100;
  localparam logic [2:0] FUNCT3_BGE  = 3'b101;
  localparam logic [2:0] FUNCT3_BLTU = 3'b110;
  localparam logic [2:0] FUNCT3_BGEU = 3'b111;

  // ---- funct3 of the arithmetic instructions (OP and OP_IMM) that the decoder must tell apart.
  // All eight values are the low three bits of alu_operation, below.
  localparam logic [2:0] FUNCT3_ADD_SUB = 3'b000;
  localparam logic [2:0] FUNCT3_SLL     = 3'b001;
  localparam logic [2:0] FUNCT3_SRL_SRA = 3'b101;

  // ---- funct3 of JALR and FENCE. Loads and stores: bits 1:0 are mem_size, bit 2 is unsigned.
  // SYSTEM: 000 is ecall, ebreak, mret, wfi; else bits 1:0 are csr_operation, bit 2 is immediate.
  localparam logic [2:0] FUNCT3_JALR  = 3'b000;
  localparam logic [2:0] FUNCT3_FENCE = 3'b000;

  // ---- funct7 (instruction bits 31:25)
  localparam logic [6:0] FUNCT7_BASE = 7'b0000000;
  localparam logic [6:0] FUNCT7_ALT  = 7'b0100000; // sub, sra, srai

  // ---- Instructions matched on all 32 bits
  localparam logic [31:0] INSTR_ECALL  = 32'h0000_0073;
  localparam logic [31:0] INSTR_EBREAK = 32'h0010_0073;
  localparam logic [31:0] INSTR_MRET   = 32'h3020_0073;
  localparam logic [31:0] INSTR_WFI    = 32'h1050_0073;

  // ---- imm_select: which immediate format the instruction carries
  localparam logic [2:0] IMM_I = 3'd0;
  localparam logic [2:0] IMM_S = 3'd1;
  localparam logic [2:0] IMM_B = 3'd2;
  localparam logic [2:0] IMM_U = 3'd3;
  localparam logic [2:0] IMM_J = 3'd4;

  // ---- alu_operation: bit 3 is instruction bit 30, bits 2:0 are funct3
  localparam logic [3:0] ALU_ADD  = 4'b0000;
  localparam logic [3:0] ALU_SUB  = 4'b1000;
  localparam logic [3:0] ALU_SLL  = 4'b0001;
  localparam logic [3:0] ALU_SLT  = 4'b0010;
  localparam logic [3:0] ALU_SLTU = 4'b0011;
  localparam logic [3:0] ALU_XOR  = 4'b0100;
  localparam logic [3:0] ALU_SRL  = 4'b0101;
  localparam logic [3:0] ALU_SRA  = 4'b1101;
  localparam logic [3:0] ALU_OR   = 4'b0110;
  localparam logic [3:0] ALU_AND  = 4'b0111;

  // ---- alu_a_select and alu_b_select: the two ALU operands
  localparam logic [1:0] ALU_A_RS1  = 2'd0;
  localparam logic [1:0] ALU_A_PC   = 2'd1;
  localparam logic [1:0] ALU_A_ZERO = 2'd2;
  localparam logic       ALU_B_RS2  = 1'b0;
  localparam logic       ALU_B_IMM  = 1'b1;

  // ---- result_select: the value written to rd
  localparam logic [1:0] RESULT_ALU       = 2'd0;
  localparam logic [1:0] RESULT_MEM       = 2'd1;
  localparam logic [1:0] RESULT_PC_PLUS_4 = 2'd2;
  localparam logic [1:0] RESULT_CSR       = 2'd3;

  // ---- mem_size: bytes moved by a load or store (as AHB hsize)
  localparam logic [1:0] SIZE_BYTE = 2'd0;
  localparam logic [1:0] SIZE_HALF = 2'd1;
  localparam logic [1:0] SIZE_WORD = 2'd2;

  // ---- csr_operation: what a CSR instruction does with its operand
  localparam logic [1:0] CSR_OPERATION_NONE  = 2'd0; // not a CSR instruction
  localparam logic [1:0] CSR_OPERATION_WRITE = 2'd1;
  localparam logic [1:0] CSR_OPERATION_SET   = 2'd2;
  localparam logic [1:0] CSR_OPERATION_CLEAR = 2'd3;

  // ---- Trap causes: the value written to mcause (bit 31 marks an interrupt)
  localparam logic [31:0] CAUSE_INSTR_ADDR_MISALIGNED = 32'd0;
  localparam logic [31:0] CAUSE_INSTR_ACCESS_FAULT    = 32'd1;
  localparam logic [31:0] CAUSE_ILLEGAL_INSTRUCTION   = 32'd2;
  localparam logic [31:0] CAUSE_BREAKPOINT            = 32'd3;
  localparam logic [31:0] CAUSE_LOAD_ADDR_MISALIGNED  = 32'd4;
  localparam logic [31:0] CAUSE_LOAD_ACCESS_FAULT     = 32'd5;
  localparam logic [31:0] CAUSE_STORE_ADDR_MISALIGNED = 32'd6;
  localparam logic [31:0] CAUSE_STORE_ACCESS_FAULT    = 32'd7;
  localparam logic [31:0] CAUSE_ECALL_FROM_M          = 32'd11;
  localparam logic [31:0] CAUSE_IRQ_SOFTWARE          = 32'h8000_0003;
  localparam logic [31:0] CAUSE_IRQ_TIMER             = 32'h8000_0007;
  localparam logic [31:0] CAUSE_IRQ_EXTERNAL          = 32'h8000_000b;

  // ---- Bit positions in mstatus, and in mie and mip
  localparam int MSTATUS_MIE_BIT  = 3;
  localparam int MSTATUS_MPIE_BIT = 7;
  localparam int IRQ_SOFTWARE_BIT = 3;
  localparam int IRQ_TIMER_BIT    = 7;
  localparam int IRQ_EXTERNAL_BIT = 11;

  // ---- CSR addresses (blueprint 5.1)
  localparam logic [11:0] CSR_MSTATUS    = 12'h300;
  localparam logic [11:0] CSR_MISA       = 12'h301;
  localparam logic [11:0] CSR_MIE        = 12'h304;
  localparam logic [11:0] CSR_MTVEC      = 12'h305;
  localparam logic [11:0] CSR_MSTATUSH   = 12'h310;
  localparam logic [11:0] CSR_MSCRATCH   = 12'h340;
  localparam logic [11:0] CSR_MEPC       = 12'h341;
  localparam logic [11:0] CSR_MCAUSE     = 12'h342;
  localparam logic [11:0] CSR_MTVAL      = 12'h343;
  localparam logic [11:0] CSR_MIP        = 12'h344;
  localparam logic [11:0] CSR_MCYCLE     = 12'hb00;
  localparam logic [11:0] CSR_MINSTRET   = 12'hb02;
  localparam logic [11:0] CSR_MCYCLEH    = 12'hb80;
  localparam logic [11:0] CSR_MINSTRETH  = 12'hb82;
  localparam logic [11:0] CSR_MVENDORID  = 12'hf11;
  localparam logic [11:0] CSR_MARCHID    = 12'hf12;
  localparam logic [11:0] CSR_MIMPID     = 12'hf13;
  localparam logic [11:0] CSR_MHARTID    = 12'hf14;
  localparam logic [11:0] CSR_MCONFIGPTR = 12'hf15;
  // Performance monitors 3 to 31 exist and read 0: first and last address of each range
  localparam logic [11:0] CSR_MHPMEVENT3      = 12'h323;
  localparam logic [11:0] CSR_MHPMEVENT31     = 12'h33f;
  localparam logic [11:0] CSR_MHPMCOUNTER3    = 12'hb03;
  localparam logic [11:0] CSR_MHPMCOUNTER31   = 12'hb1f;
  localparam logic [11:0] CSR_MHPMCOUNTER3H   = 12'hb83;
  localparam logic [11:0] CSR_MHPMCOUNTER31H  = 12'hb9f;
  // Address bits 11:10 of a read-only CSR
  localparam logic [1:0]  CSR_READ_ONLY = 2'b11;

  // ---- CSR values and write masks (a 1 marks a bit that software can change)
  localparam logic [31:0] MSTATUS_RESET      = 32'h0000_1800; // MPP = 11: machine mode only
  localparam logic [31:0] MSTATUS_WRITE_MASK = 32'h0000_0088; // MIE and MPIE
  localparam logic [31:0] MISA_VALUE         = 32'h4000_0100; // 32 bits, extension I
  localparam logic [31:0] MIMPID_VALUE       = 32'h0001_0000; // ap_rv32 version 1.0
  localparam logic [31:0] MIE_WRITE_MASK     = 32'h0000_0888; // MSIE, MTIE and MEIE
  localparam logic [31:0] MTVEC_WRITE_MASK   = 32'hffff_fffd; // BASE and MODE bit 0
  localparam logic [31:0] MEPC_WRITE_MASK    = 32'hffff_fffc; // instructions are 4-byte aligned
  localparam logic [31:0] ALL_BITS           = 32'hffff_ffff;

  // ---- Data bits that a byte and a half cover, from bit 0
  localparam logic [31:0] BYTE_BITS = 32'h0000_00ff;
  localparam logic [31:0] HALF_BITS = 32'h0000_ffff;

  // ---- Other
  localparam logic [1:0] PRIV_MACHINE   = 2'b11; // the only privilege level in v1.0
  localparam int         REGISTER_COUNT = 32;

endpackage
Read included file: ap_rv32_p5_pkg.sv
// ap_rv32_p5_pkg: the named constants that only the five-stage build needs.
// The forwarding selects of the forward unit, and the AHB-Lite codes of the two bus ports.
// Used by the five-stage build (ap_rv32). Taught in S2.8 and S2.16.
// Blueprint: docs/soc/ap_rv32-blueprint.md sections 8.2 (forwarding) and 3.2 (bus ports).
package ap_rv32_p5_pkg;

  // ---- forward_a and forward_b: where the value of a register operand comes from
  localparam logic [1:0] FORWARD_NONE = 2'd0; // the value read from the register file in ID
  localparam logic [1:0] FORWARD_MEM  = 2'd1; // the result of the instruction now in MEM
  localparam logic [1:0] FORWARD_WB   = 2'd2; // the value that the instruction now in WB writes

  // ---- htrans: the two transfer types the core uses (every transfer is a single transfer)
  localparam logic [1:0] HTRANS_IDLE   = 2'b00;
  localparam logic [1:0] HTRANS_NONSEQ = 2'b10;

  // ---- hburst and hprot: constant on each port
  localparam logic [2:0] HBURST_SINGLE     = 3'b000;
  localparam logic [3:0] HPROT_INSTRUCTION = 4'b0010; // opcode fetch, privileged
  localparam logic [3:0] HPROT_DATA        = 4'b0011; // data access, privileged

endpackage
Read included file: ap_rv32_regfile.sv
// ap_rv32_regfile: the register file.
// 31 registers, x1 to x31, and x0 which always reads 0. Two read ports, one write port.
// A read is combinational; a write happens at the clock edge. All registers reset to 0.
// Used by both builds. Taught in S2.4. Blueprint: sections 2.3 and 6.
module ap_rv32_regfile (
  input  logic        clk,          // clock
  input  logic        rst_n,        // reset, active low
  input  logic [4:0]  rs1_addr,     // first register to read
  output logic [31:0] rs1_data,     // its value
  input  logic [4:0]  rs2_addr,     // second register to read
  output logic [31:0] rs2_data,     // its value
  input  logic        write_enable, // write rd at this clock edge
  input  logic [4:0]  rd_addr,      // register to write; a write to x0 is discarded
  input  logic [31:0] rd_data       // value to write
);
  import ap_rv32_pkg::*;

  logic [31:0] registers_q [1:REGISTER_COUNT-1]; // x1 to x31; x0 has no storage

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
      for (int i = 1; i < REGISTER_COUNT; i++) registers_q[i] <= '0;
    end else if (write_enable && rd_addr != '0) begin
      registers_q[rd_addr] <= rd_data;
    end
  end

  assign rs1_data = (rs1_addr == '0) ? '0 : registers_q[rs1_addr];
  assign rs2_data = (rs2_addr == '0) ? '0 : registers_q[rs2_addr];

endmodule
Read included file: ap_rv32_alu.sv
// ap_rv32_alu: the arithmetic and logic unit.
// Add, subtract, shifts, compares and bitwise logic on two 32-bit operands.
// Used by both builds. Taught in S2.4. Blueprint: section 2.3.
module ap_rv32_alu (
  input  logic [3:0]  alu_operation, // operation: one of the ALU_* constants
  input  logic [31:0] operand_a,     // first operand
  input  logic [31:0] operand_b,     // second operand; shifts use only its bits 4:0
  output logic [31:0] result         // result of the operation
);
  import ap_rv32_pkg::*;

  logic [4:0] shift_amount; // number of bit positions to shift by

  assign shift_amount = operand_b[4:0];

  always_comb begin
    result = '0;
    unique case (alu_operation)
      ALU_ADD:  result = operand_a + operand_b;
      ALU_SUB:  result = operand_a - operand_b;
      ALU_SLL:  result = operand_a << shift_amount;
      ALU_SLT:  result = {31'b0, $signed(operand_a) < $signed(operand_b)};
      ALU_SLTU: result = {31'b0, operand_a < operand_b};
      ALU_XOR:  result = operand_a ^ operand_b;
      ALU_SRL:  result = operand_a >> shift_amount;
      ALU_SRA:  result = $signed(operand_a) >>> shift_amount;
      ALU_OR:   result = operand_a | operand_b;
      ALU_AND:  result = operand_a & operand_b;
      default:  result = '0;
    endcase
  end

endmodule
ConceptHow far behind a writer can a reader be and still have a data hazard, on this pipeline?
ConceptThe reader is two instructions behind the writer. Where does EX take the value from?
ConceptWhat does the forwarding unit compare?
ConceptWhich value of a store may need forwarding, besides its address register?
ConceptWhat does forwarding cost?

Common Mistakes

Wrong Think that forwarding sends a value back in time.

The result was made a cycle or two earlier. It moves sideways, from a pipeline register to the ALU inputs.

Fix Check that the writer has passed EX before the reader needs the value.

Wrong Forward only into the two ALU inputs.

The data of a store goes round the ALU. It can be just as old.

Fix Give the store data the same forwarding as an ALU operand.

Wrong Forward whenever two register numbers are equal.

An instruction such as a store has bits in the rd place and writes no register.

Fix Forward only from an instruction whose reg_write is 1.

Remember

  • A data hazard: a reader would use an old value, because a writer close ahead has not written yet.
  • A writer one ahead is in MEM when the reader is in EX. A writer two ahead is in WB.
  • The forwarding unit compares register numbers and sets one select for each operand.
  • Forwarding costs no cycle. The store data needs it as much as the ALU operands do.

Practice

Report a problem with this page