Performance: The Critical Path and the Cycle Time

The single-cycle core runs one instruction in each clock cycle. So its speed is the length of that cycle. This page finds what sets the length, in the lab and in the real core.

You Will Be Able To

  • Add up the delays on the path of each kind of instruction.
  • Name the critical path of a single-cycle datapath, and derive the shortest clock period from it.
  • Read a logic-depth report of a real core, and say where its longest path starts and ends.
Lesson
S2.6
Time
30 min
Runs on
Icarus service
Check
6 questions

So far, logic was instant: a value changed, and its result was there. Real gates take time. A load must pass the instruction memory, the decoder, the ALU, the data memory and the load unit. Only then may the next clock edge come, and every other instruction waits as long.

Before You Start

You need the full datapath of S2.21, and which blocks each kind of instruction uses.

You need to know that a gate takes a little time to change its output.

Five questions this page answers
Question
1What is the critical path of a circuit?
2Which kind of instruction has the longest path in the datapath of the lab?
3How does the critical path set the clock period?
4What happens when the clock is faster than the critical path allows?
5When does a faster block make the core faster?

The Idea: The Slowest Instruction Sets the Clock

Every block of logic has a propagation delay. That is the time from a change at its inputs to the right value at its outputs. This page calls it the delay, and counts it in levels of logic. A level is one simple gate that a signal passes on its way.

After a clock edge, the new PC starts a wave of changes. It runs through the instruction memory, the decoder, the ALU and on. A chain of blocks from one clocked element to the next is a timing path. This page calls it a path. Its delay is the sum of the delays on it.

At the next clock edge, the register file and the PC take whatever value is on their inputs. If the wave has not arrived, they take an old value. Nothing reports that. The program just goes wrong.

So the clock period must be longer than the longest path. The shortest period that works is the cycle time. That longest path has a name: the critical path.

Here is the cost of a single-cycle core. It has one clock period for every instruction. An add needs a short path, and a load a long one. The period must fit the load. So the add waits too.

New Words

New words on this page
WordMeaning
Propagation delayThe time from a change at the inputs of a block to the right value at its outputs. Called the delay for short.
Level of logicOne simple gate on the way of a signal. Used here as the unit of delay.
Logic depthThe largest number of levels between the inputs and the outputs of a block.
Timing pathA chain of logic from the output of one clocked element to the input of the next. This page calls it a path.
Critical pathThe path with the largest delay in the whole circuit.
Cycle timeThe shortest clock period that a core can run with. A clock period is the time from one rising clock edge to the next.
Clock frequencyThe number of clock periods in one second. A longer period means a lower frequency.
YosysThe synthesis tool of this site. It turns a description of logic into gates, and can report the logic depth.

One Picture: Four Paths Through One Cycle

The Paths of One Clock CycleStep through the picture. Each step follows one kind of instruction from a clock edge to the next, and adds up the delays on the way.
  • Clock / reset
  • Memory
  • Control / FSM
  • Processor
The Paths of One Clock CycleStep through the picture. Each step follows one kind of instruction from a clock edge to the next, and adds up the delays on the way. component Clock edge: thePC changes time 0 of every cycle component Instructionmemory 20 levels component Decoder, besidethe register read 11 levels and 10levels: the slowercounts component ALU 65 levels component Branch compareand target adder 19 levels and 57levels, side by side component Data memory 20 levels component Load unit 7 levels component Next clock edge the register file andthe PC take theirvalues the addressthe wordoperands and controlthe result, for rdthe addressthe wordthe loaded value, forrdoperands and theimmediatethe next PC
  1. component Clock edge: the PC changestime 0 of every cycle
    • the address → Instruction memory
  2. component Instruction memory20 levels
    • the word → Decoder, beside the register read
  3. component Decoder, beside the register read11 levels and 10 levels: the slower counts
    • operands and control → ALU
    • operands and the immediate → Branch compare and target adder
  4. component ALU65 levels
    • the result, for rd → Next clock edge
    • the address → Data memory
  5. component Next clock edgethe register file and the PC take their values
  6. component Data memory20 levels
    • the word → Load unit
  7. component Load unit7 levels
    • the loaded value, for rd → Next clock edge
  8. component Branch compare and target adder19 levels and 57 levels, side by side
    • the next PC → Next clock edge
  1. An arithmetic instruction: 96 levels

    The word arrives after 20 levels. The decoder needs 11 more, the register read 10: count 11. The ALU adds 65. In all: 20 plus 11 plus 65.

  2. A load: 123 levels

    A load goes the same way to the ALU: 96 levels. Then come the data memory, 20, and the load unit, 7. No other instruction has so far to go.

  3. A store: 96 levels

    The address and the value must be at the memory when the edge comes. The address takes 96 levels. The write itself happens at the edge.

  4. A branch: 88 levels

    Two things run side by side. The compare is done after 20 plus 10 plus 19, which is 49. The target needs 20 plus 11 plus 57, which is 88. The slower one counts.

Read the diagram as text
  • Clock edge: the PC changes: time 0 of every cycle
  • Instruction memory: 20 levels
  • Decoder, beside the register read: 11 levels and 10 levels: the slower counts
  • ALU: 65 levels
  • Branch compare and target adder: 19 levels and 57 levels, side by side
  • Data memory: 20 levels
  • Load unit: 7 levels
  • Next clock edge: the register file and the PC take their values
  • Clock edge: the PC changes → Instruction memory: the address
  • Instruction memory → Decoder, beside the register read: the word
  • Decoder, beside the register read → ALU: operands and control
  • ALU → Next clock edge: the result, for rd
  • ALU → Data memory: the address
  • Data memory → Load unit: the word
  • Load unit → Next clock edge: the loaded value, for rd
  • Decoder, beside the register read → Branch compare and target adder: operands and the immediate
  • Branch compare and target adder → Next clock edge: the next PC

The delays are those of the lab. The multiplexers are counted as nothing.

The delay of each block in the lab
BlockLevelsWhere the number comes from
Instruction memory20a choice of this page
Decoder11measured on the decoder of ap_rv32
Register file, read10measured on its register file
ALU65measured on its ALU
Branch compare19measured on its branch compare
A 32-bit adder57measured: for the target, and for the PC plus 4
Data memory20a choice of this page
Load unit7measured on its load unit

Measured means: the synthesis tool Yosys built the block from its real source and counted its levels.

The Smallest Example, Worked by Hand

Add up the path of lw x5, 0(x10). Blocks in a row add. Blocks side by side do not: the slower one counts.

The path of a load
BlockIts levelsLevels since the clock edge
Instruction memory2020
Decoder, beside the register read11, beside 1031
ALU6596
Data memory20116
Load unit7123

The loaded value is ready 123 levels after the clock edge.

An add leaves this path after the ALU. Its result is ready after 96 levels.

The longest path of each kind of instruction
KindPathLevels
Arithmetic20 + 11 + 6596
Load20 + 11 + 65 + 20 + 7123
Store20 + 11 + 6596
Branch, jal20 + 11 + 5788

The critical path is that of the load. The clock period must be longer than 123 levels.

The Rules

  1. Rule 1: A path starts at the output of a clocked element and ends at the input of one.

    Here the clocked elements are the PC, the register file and the memories.

  2. Rule 2: Delays in a row add. Of delays side by side, the largest counts.

    The decoder and the register read work side by side.

  3. Rule 3: The critical path is the longest path of the whole circuit.

    It does not matter how seldom a program uses it.

  4. Rule 4: The clock period must be longer than the critical path.

    In the lab, one level longer is enough.

  5. Rule 5: In a single-cycle core, every instruction takes one full period.

    A short instruction finishes early and waits.

  6. Rule 6: A faster block shortens the period only if it lies on the critical path.

    And then only until another path becomes the longest.

Sources for These Rules

The idea that the slowest instruction sets the clock of a single-cycle core is as textbooks commonly describe it. The plan of this track points to Patterson and Hennessy, sections 4.5 and 4.14. It also points to Harris and Harris, sections 7.2 and 7.4. Those places are not checked. The depths on this page are measured: the pinned Yosys of this site, with its command ltp, on the RTL of ap_rv32. A depth counts levels of simple gates. It is not a time. This run did not ask the tool for speed. A tool that is asked builds shallower adders: that remark is common practice, not measured here. The delays of the two memories in the lab, 20 levels each, are a choice of this page.

Now Run It

The lab at the end of this page is the datapath of S2.21 with a delay behind each block. It runs the three test programs of S2.5 at seven clock periods, and says which still give the right result.

Printed by the lab on Icarus. One time unit is one level.
period 140 | arithmetic pass | memory pass | loop pass
period 124 | arithmetic pass | memory pass | loop pass
period 123 | arithmetic pass | memory FAIL | loop pass
period 110 | arithmetic pass | memory FAIL | loop pass
period 97 | arithmetic pass | memory FAIL | loop pass
period 96 | arithmetic FAIL | memory FAIL | loop FAIL
period 80 | arithmetic FAIL | memory FAIL | loop FAIL

Rule 4 at work: at a period of 124, everything passes. At 123, the memory program fails. Its lw needs 123 levels, and the period must be longer.

Rule 3 at work: the memory program has one load among seven instructions. That one load sets the limit.

Now read the columns of the other two programs. They hold no load. They still pass at 97, and fail at 96: the path of an add.

So a core that ran only those two programs could have a period of 97. With loads, it needs 124. Rule 5: every add in every program then takes 124 as well.

Nothing in the lab reports a clock that is too fast. A register simply takes a value that is not ready. The only sign is a wrong result.

The Report of a Real Tool

The lab is a model with round numbers. Here is a measurement. The synthesis tool Yosys built each block of ap_rv32 from simple gates, and then the whole single-cycle core. For each it reports the cells and the logic depth.

Measured with the pinned Yosys of this site: synth, then ltp. Levels of simple gates, not time.
ap_rv32_regfile | 4520 cells | depth 10
ap_rv32_decode | 130 cells | depth 11
ap_rv32_imm_gen | 79 cells | depth 5
ap_rv32_alu | 1243 cells | depth 65
ap_rv32_branch | 178 cells | depth 19
ap_rv32_load_unit | 129 cells | depth 7
adder32 | 172 cells | depth 57
ap_rv32_sc | 9910 cells | depth 122

The rows above the adder are blocks of the core, and the lab takes its delays from five of them. The seventh row is a plain 32-bit adder. The last row is the whole core: 9,910 cells, and a longest path of 122 levels.

The tool also lists that longest path. These are the named wires on it, with the level at which each is reached:

From the same run. The path starts at an input pin and ends at a flip-flop.
level 0 | imem_rdata[1]
level 4 | alu_a_select[1]
level 11 | imm[1]
level 12 | alu_operand_b[1]
level 61 | dmem_addr[0]
level 69 | trace_trap
level 70 | retire
level 122 | u_csr.minstret_next[63]
flip-flop | u_csr.minstret_q[63]

Read it from the top. The path starts at the instruction word. It runs through the decoder and the operand select into the ALU. At level 61, the ALU result leaves as the address of the data memory.

Then comes a part that no picture of this module shows. The core checks whether this instruction must trap, for example for a misaligned address. That decides the wire named retire: the instruction completes.

And retire feeds a counter of 64 bits, which counts the completed instructions. Adding 1 to a 64-bit number takes the last 52 levels. So the longest path of the real core ends in a counter, not in the register file.

Two things are missing from this report. The memories are outside the core, so their delay is not counted. And a level is not a time. The timing track of this site turns levels into nanoseconds.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
One clock period for every instructionA period that changes with the instructionOne simple clock. Every instruction is as slow as the slowest.
The whole instruction in one cycleSeveral short cycles for each instructionNo state between the steps, and no control for it. A long critical path: the next lesson compares.
The decoder beside the register readDecode first, then readThe slower of the two counts, not their sum. The fields rs1 and rs2 must be at fixed places.
A target adder beside the ALUThe ALU works out the targetA branch needs 88 levels and not more than a load. A second adder.
Count levels firstGo straight to timesLevels need no cell library and no layout. They ignore wires and the sizes of gates.

The Trap: The Faster Block That Changed Nothing

A team wants a faster core. One engineer rebuilds the branch path. The compare drops from 19 levels to 5, and both adders from 57 to 20. The work is good. Here is the same run again, with the new blocks.

The same lab with a branch compare of 5 levels and adders of 20.
period 140 | arithmetic pass | memory pass | loop pass
period 124 | arithmetic pass | memory pass | loop pass
period 123 | arithmetic pass | memory FAIL | loop pass
period 110 | arithmetic pass | memory FAIL | loop pass
period 97 | arithmetic pass | memory FAIL | loop pass
period 96 | arithmetic FAIL | memory FAIL | loop FAIL
period 80 | arithmetic FAIL | memory FAIL | loop FAIL

Not one line has changed. The shortest period is still 124, because the path of a load is still 123. The branch path was never the critical path. Rule 6.

A second engineer halves the ALU instead: 33 levels in place of 65.

The same lab with an ALU of 33 levels and the old branch path.
period 124 | arithmetic pass | memory pass | loop pass
period 96 | arithmetic pass | memory pass | loop pass
period 92 | arithmetic pass | memory pass | loop pass
period 91 | arithmetic pass | memory FAIL | loop pass
period 85 | arithmetic pass | memory FAIL | loop FAIL
period 84 | arithmetic pass | memory FAIL | loop FAIL

Now the memory program passes down to 92. The ALU lies on the critical path, so the whole gain of 32 levels arrives.

Look at the loop program in this second run. It fails at 85, although its arithmetic now needs only 64 levels. Its branch needs 88. With the ALU out of the way, the target adder is the next limit.

So the order of work matters. Find the critical path first. Shorten it. Then find the new one.

At Scale

The lab4 kinds of path, 8 delays
A real coremillions of paths, checked by a tool

This section looks ahead. A real core has millions of paths, and a tool checks every one.

  1. Times, not levels

    A tool adds the real delays of gates and wires, and checks every path against the clock. The timing track of this site covers it.

  2. Paths that no picture shows

    Counters, trap checks and debug logic often hold the longest path. The report of the real core above is an example.

  3. Cutting the path

    Put a register in the middle of a long path, and each half needs only half the period. That is a pipeline: S2.7.

  4. A memory takes a whole cycle

    A real SRAM answers at the next clock edge. Then a load cannot fit into one cycle at all: S2.16 and S3.

Try It

Run the lab. Find the shortest period at which each program passes.

Set T_DMEM to 40. Work out the new critical path by hand first. Then change the list of periods and check.

Set T_ALU to 20. Which path is the critical one now? Work it out, then check with the lab.

RUNIcarus Verilog · simulator service
Edit the code, then run it
Expected: period 140 | arithmetic pass | memory pass | loop pass period 124 | arithmetic pass | memory pass | loop pass period 123 | arithmetic pass | memory FAIL | loop pass period 110 | arithmetic pass | memory FAIL | loop pass period 97 | arithmetic pass | memory FAIL | loop pass period 96 | arithmetic FAIL | memory FAIL | loop FAIL period 80 | arithmetic FAIL | memory FAIL | loop FAIL
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_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
Read included file: ap_rv32_branch.sv
// ap_rv32_branch: the branch compare.
// Decides whether the condition of a branch instruction is true.
// Used by both builds. Taught in S2.4 and S2.10. Blueprint: section 2.3.
module ap_rv32_branch (
  input  logic [2:0]  funct3,    // funct3 of the branch instruction: which condition
  input  logic [31:0] rs1_data,  // first value compared
  input  logic [31:0] rs2_data,  // second value compared
  output logic        condition  // the condition is true: the branch is taken
);
  import ap_rv32_pkg::*;

  always_comb begin
    condition = 1'b0;
    unique case (funct3)
      FUNCT3_BEQ:  condition = (rs1_data == rs2_data);
      FUNCT3_BNE:  condition = (rs1_data != rs2_data);
      FUNCT3_BLT:  condition = ($signed(rs1_data) < $signed(rs2_data));
      FUNCT3_BGE:  condition = ($signed(rs1_data) >= $signed(rs2_data));
      FUNCT3_BLTU: condition = (rs1_data < rs2_data);
      FUNCT3_BGEU: condition = (rs1_data >= rs2_data);
      default:     condition = 1'b0;
    endcase
  end

endmodule
Read included file: ap_rv32_load_unit.sv
// ap_rv32_load_unit: the load unit.
// Picks the addressed byte or half out of the word that the memory returned, and extends it to
// 32 bits with the sign bit (lb, lh) or with zeros (lbu, lhu).
// Used by both builds. Taught in S2.4. Blueprint: section 2.3; misalignment rule in section 7.1.
module ap_rv32_load_unit (
  input  logic [31:0] mem_rdata,     // word from the memory, every byte on its own lane
  input  logic [1:0]  addr_low,      // bits 1:0 of the load address: the lane of the first byte
  input  logic [1:0]  mem_size,      // SIZE_BYTE, SIZE_HALF or SIZE_WORD
  input  logic        load_unsigned, // 1: extend with zeros; 0: extend with the sign bit
  output logic [31:0] load_data,     // value for rd
  output logic        misaligned     // the address is not a multiple of the access size
);
  import ap_rv32_pkg::*;

  logic [7:0]  byte_data; // the addressed byte
  logic [15:0] half_data; // the addressed half
  logic        sign;      // bit that fills the upper part of load_data

  assign byte_data = mem_rdata[{addr_low, 3'b000} +: 8];
  assign half_data = addr_low[1] ? mem_rdata[31:16] : mem_rdata[15:0];

  always_comb begin
    load_data  = mem_rdata;
    sign       = 1'b0;
    misaligned = 1'b0;
    unique case (mem_size)
      SIZE_BYTE: begin
        sign      = byte_data[7] & ~load_unsigned;
        load_data = {{24{sign}}, byte_data};
      end
      SIZE_HALF: begin
        sign       = half_data[15] & ~load_unsigned;
        load_data  = {{16{sign}}, half_data};
        misaligned = addr_low[0];
      end
      default: begin
        misaligned = (addr_low != '0);
      end
    endcase
  end

endmodule

Check Yourself

Predict the outputIn this lab the data memory has 40 levels in place of 20. The three programs run at a period of 150, and then at 143. What does the last line say?
// The data memory is slower here: 40 levels. What does the last line say?
// One time unit is one level of gates. Each block has the delay that the table below gives it.
// The bench runs three programs at several clock periods, and says which still give the right result.
// The files ap_rv32_pkg.sv, ap_rv32_regfile.sv, ap_rv32_alu.sv, ap_rv32_branch.sv, ap_rv32_load_unit.sv are the files of the real core.

// A delay: the output follows the input after T time units.
module lab_delay #(parameter int W = 32, parameter int T = 0) (input logic [W-1:0] d, output logic [W-1:0] q);
  always @(d) q <= #(T) d;
endmodule

// The delay of each block, in levels of gates.
package lab_delays;
  localparam int T_IMEM    = 20 ;   // instruction memory: a choice of this page
  localparam int T_DECODE  = 11 ;   // decoder: measured. The immediate is ready at the same level in the real core
  localparam int T_REGFILE = 10 ;   // register file: measured
  localparam int T_ALU     = 65 ;   // ALU: measured
  localparam int T_BRANCH  = 19 ;   // branch compare: measured
  localparam int T_ADDER   = 57 ;   // a 32-bit adder (the target adder, and the adder for the PC plus 4): measured
  localparam int T_DMEM    = 40 ;   // data memory: a choice of this page
  localparam int T_LOAD    = 7  ;   // load unit: measured
endpackage

// The datapath of S2.21 with a delay behind each block. The multiplexers count as no delay.
module lab_datapath (
  input  logic        clk, rst_n,
  output logic [31:0] imem_addr,      // the PC
  input  logic [31:0] imem_rdata,     // the instruction, after the delay of the instruction memory
  input  logic [31:0] imm,            // given, after the delay of the decoder
  input  logic        alu_b_select, reg_write, mem_read, mem_write, branch, jump,
  input  logic [3:0]  alu_operation,
  input  logic [1:0]  result_select,
  output logic        dmem_req, dmem_write,
  output logic [31:0] dmem_addr, dmem_wdata,
  input  logic [31:0] dmem_rdata      // the word from the memory, after the delay of the data memory
);
  import ap_rv32_pkg::*;
  import lab_delays::*;

  logic [31:0] pc_q, instr, rs1_now, rs2_now, rs1_data, rs2_data, alu_operand_b, alu_now, alu_result;
  logic [31:0] load_now, load_data, result, pc_plus_4, target, pc_next;
  logic        condition_now, condition, misaligned, redirect;

  assign imem_addr = pc_q;
  assign instr     = imem_rdata;

  ap_rv32_regfile u_regfile (
    .clk(clk), .rst_n(rst_n),
    .rs1_addr(instr[19:15]), .rs1_data(rs1_now),
    .rs2_addr(instr[24:20]), .rs2_data(rs2_now),
    .write_enable(reg_write), .rd_addr(instr[11:7]), .rd_data(result)
  );
  lab_delay #(32, T_REGFILE) d_rs1 (.d(rs1_now), .q(rs1_data));
  lab_delay #(32, T_REGFILE) d_rs2 (.d(rs2_now), .q(rs2_data));

  assign alu_operand_b = (alu_b_select == ALU_B_IMM) ? imm : rs2_data;
  ap_rv32_alu u_alu (.alu_operation(alu_operation), .operand_a(rs1_data), .operand_b(alu_operand_b), .result(alu_now));
  lab_delay #(32, T_ALU) d_alu (.d(alu_now), .q(alu_result));

  ap_rv32_branch u_branch (.funct3(instr[14:12]), .rs1_data(rs1_data), .rs2_data(rs2_data), .condition(condition_now));
  lab_delay #(1, T_BRANCH) d_condition (.d(condition_now), .q(condition));

  lab_delay #(32, T_ADDER) d_target (.d(pc_q + imm), .q(target));
  lab_delay #(32, T_ADDER) d_plus_4 (.d(pc_q + 32'd4), .q(pc_plus_4));
  assign redirect = jump || (branch && condition);

  assign dmem_req   = mem_read || mem_write;
  assign dmem_write = mem_write;
  assign dmem_addr  = alu_result;
  assign dmem_wdata = rs2_data;

  ap_rv32_load_unit u_load_unit (
    .mem_rdata(dmem_rdata), .addr_low(alu_result[1:0]), .mem_size(instr[13:12]),
    .load_unsigned(instr[14]), .load_data(load_now), .misaligned(misaligned)
  );
  lab_delay #(32, T_LOAD) d_load (.d(load_now), .q(load_data));

  always_comb begin
    result = alu_result;
    if (result_select == RESULT_MEM) result = load_data;
    if (result_select == RESULT_PC_PLUS_4) result = pc_plus_4;
  end
  assign pc_next = redirect ? target : pc_plus_4;

  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) pc_q <= '0;
    else pc_q <= pc_next;
  end
endmodule

module tb;
  import ap_rv32_pkg::*;
  import lab_delays::*;
  logic        clk = 0, rst_n = 1;
  logic [31:0] imem_addr, imem_rdata, imm, dmem_addr, dmem_wdata, dmem_rdata;
  logic        alu_b_select, reg_write, mem_read, mem_write, branch, jump, dmem_req, dmem_write;
  logic [3:0]  alu_operation;
  logic [1:0]  result_select;

  lab_datapath dp (.*);

  // ---- What the decoder says for each class of instruction (S2.5).
  //                                reg_write, alu_b_select, result_select, mem_read, mem_write, branch, jump
  localparam logic [7:0] OP_IMM = {1'b1, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b0, 1'b0, 1'b0};
  localparam logic [7:0] OP     = {1'b1, ALU_B_RS2, RESULT_ALU      , 1'b0, 1'b0, 1'b0, 1'b0};
  localparam logic [7:0] STOP   = {1'b0, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b0, 1'b0, 1'b0};
  localparam logic [7:0] LOAD   = {1'b1, ALU_B_IMM, RESULT_MEM      , 1'b1, 1'b0, 1'b0, 1'b0};
  localparam logic [7:0] STORE  = {1'b0, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b1, 1'b0, 1'b0};
  localparam logic [7:0] BRANCH = {1'b0, ALU_B_IMM, RESULT_ALU      , 1'b0, 1'b0, 1'b1, 1'b0};
  localparam logic [7:0] JAL    = {1'b1, ALU_B_IMM, RESULT_PC_PLUS_4, 1'b0, 1'b0, 1'b0, 1'b1};

  logic [31:0] rom [0:63];          // instruction memory
  logic [7: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
  logic [31:0] ram [0:255];         // data memory, from address 8000_0000
  int rows, cycles;
  task automatic row(input logic [31:0] word, input logic [7:0] control, input logic [3:0] alu, input logic [31:0] immediate_value);
    rom[rows] = word;  given[rows] = control;  operation[rows] = alu;  immediate[rows] = immediate_value;  rows++;
  endtask
  task automatic clear();
    rows = 0;
    for (int n = 0; n < 64; n++) begin rom[n] = 32'h0010_0073;  given[n] = STOP;  operation[n] = ALU_ADD;  immediate[n] = 0; end
    for (int n = 0; n < 256; n++) ram[n] = 0;
  endtask

  task automatic program_1();   // arithmetic
    clear();
    row(32'h0070_0293, OP_IMM, ALU_ADD, 32'd7     );   // 00: addi x5, x0, 7
    row(32'h0050_0313, OP_IMM, ALU_ADD, 32'd5     );   // 04: addi x6, x0, 5
    row(32'h0062_83b3, OP,     ALU_ADD, 32'd0     );   // 08: add x7, x5, x6
    row(32'h4063_8433, OP,     ALU_SUB, 32'd0     );   // 0c: sub x8, x7, x6
  endtask
  task automatic program_2();   // memory
    clear();
    row(32'h0010_0513, OP_IMM, ALU_ADD, 32'd1     );   // 00: addi x10, x0, 1
    row(32'h01f5_1513, OP_IMM, ALU_SLL, 32'd31    );   // 04: slli x10, x10, 31
    row(32'h0280_0413, OP_IMM, ALU_ADD, 32'd40    );   // 08: addi x8, x0, 40
    row(32'h0005_2283, LOAD,   ALU_ADD, 32'd0     );   // 0c: lw x5, 0(x10)
    row(32'h0012_8293, OP_IMM, ALU_ADD, 32'd1     );   // 10: addi x5, x5, 1
    row(32'h0055_2423, STORE,  ALU_ADD, 32'd8     );   // 14: sw x5, 8(x10)
    row(32'h0054_04b3, OP,     ALU_ADD, 32'd0     );   // 18: add x9, x8, x5
    ram[0] = 32'h0000_0011;   // the word at 80000000
  endtask
  task automatic program_3();   // loop
    clear();
    row(32'h0030_0293, OP_IMM, ALU_ADD, 32'd3     );   // 00: addi x5, x0, 3
    row(32'h0000_0313, OP_IMM, ALU_ADD, 32'd0     );   // 04: addi x6, x0, 0
    row(32'h0053_0333, OP,     ALU_ADD, 32'd0     );   // 08: add x6, x6, x5
    row(32'hfff2_8293, OP_IMM, ALU_ADD, -32'sd1   );   // 0c: addi x5, x5, -1
    row(32'hfe02_9ce3, BRANCH, ALU_ADD, -32'sd8   );   // 10: bne x5, x0, 0x8
    row(32'h0080_00ef, JAL,    ALU_ADD, 32'd8     );   // 14: jal x1, 0x1c
    row(32'h0643_0313, OP_IMM, ALU_ADD, 32'd100   );   // 18: addi x6, x6, 100
  endtask

  // ---- The two memories and the decoder, each with its delay.
  logic [31:0] fetched;   // the address that the instruction memory has finished reading
  logic [43:0] decoded;
  lab_delay #(32, T_IMEM)   d_imem   (.d(imem_addr), .q(fetched));
  assign imem_rdata = rom[fetched[7:2]];
  lab_delay #(44, T_DECODE) d_decode (.d({given[fetched[7:2]], operation[fetched[7:2]], immediate[fetched[7:2]]}), .q(decoded));
  assign {reg_write, alu_b_select, result_select, mem_read, mem_write, branch, jump} = decoded[43:36];
  assign alu_operation = decoded[35:32];
  assign imm           = decoded[31:0];
  lab_delay #(32, T_DMEM)   d_dmem   (.d(ram[dmem_addr[9:2]]), .q(dmem_rdata));
  always @(posedge clk) if (dmem_req && dmem_write) ram[dmem_addr[9:2]] <= dmem_wdata;

  function automatic logic [31:0] register(input int n);
    return (n == 0) ? 32'd0 : dp.u_regfile.registers_q[n];
  endfunction

  // ---- Run one program with a clock of the given period. The run stops when the PC reaches the ebreak.
  task automatic run(input int period);
    #1 rst_n = 0;
    #1 rst_n = 1;
    #500;   // long enough for every wire to settle after the reset
    cycles = 0;
    while (rom[imem_addr[7:2]] != 32'h0010_0073 && cycles < 60) begin
      clk = 1;  #1;  clk = 0;  #(period - 1);   // one rising edge, then one period of time for the logic
      cycles++;
    end
  endtask
  function automatic string verdict(input bit ok);
    return ok ? "pass" : "FAIL";
  endfunction

  bit ok [1:3];
  task automatic at_period(input int period);
    program_1();  run(period);  ok[1] = (register(8) === 32'h0000_0007);
    program_2();  run(period);  ok[2] = (register(9) === 32'h0000_003a && ram[2] === 32'h0000_0012);
    program_3();  run(period);  ok[3] = (register(6) === 32'h0000_0006);
    $display("period %0d | arithmetic %s | memory %s | loop %s", period, verdict(ok[1]), verdict(ok[2]), verdict(ok[3]));
  endtask

  initial begin
    at_period(150);
    at_period(143);
    $finish;
  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_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
Read included file: ap_rv32_branch.sv
// ap_rv32_branch: the branch compare.
// Decides whether the condition of a branch instruction is true.
// Used by both builds. Taught in S2.4 and S2.10. Blueprint: section 2.3.
module ap_rv32_branch (
  input  logic [2:0]  funct3,    // funct3 of the branch instruction: which condition
  input  logic [31:0] rs1_data,  // first value compared
  input  logic [31:0] rs2_data,  // second value compared
  output logic        condition  // the condition is true: the branch is taken
);
  import ap_rv32_pkg::*;

  always_comb begin
    condition = 1'b0;
    unique case (funct3)
      FUNCT3_BEQ:  condition = (rs1_data == rs2_data);
      FUNCT3_BNE:  condition = (rs1_data != rs2_data);
      FUNCT3_BLT:  condition = ($signed(rs1_data) < $signed(rs2_data));
      FUNCT3_BGE:  condition = ($signed(rs1_data) >= $signed(rs2_data));
      FUNCT3_BLTU: condition = (rs1_data < rs2_data);
      FUNCT3_BGEU: condition = (rs1_data >= rs2_data);
      default:     condition = 1'b0;
    endcase
  end

endmodule
Read included file: ap_rv32_load_unit.sv
// ap_rv32_load_unit: the load unit.
// Picks the addressed byte or half out of the word that the memory returned, and extends it to
// 32 bits with the sign bit (lb, lh) or with zeros (lbu, lhu).
// Used by both builds. Taught in S2.4. Blueprint: section 2.3; misalignment rule in section 7.1.
module ap_rv32_load_unit (
  input  logic [31:0] mem_rdata,     // word from the memory, every byte on its own lane
  input  logic [1:0]  addr_low,      // bits 1:0 of the load address: the lane of the first byte
  input  logic [1:0]  mem_size,      // SIZE_BYTE, SIZE_HALF or SIZE_WORD
  input  logic        load_unsigned, // 1: extend with zeros; 0: extend with the sign bit
  output logic [31:0] load_data,     // value for rd
  output logic        misaligned     // the address is not a multiple of the access size
);
  import ap_rv32_pkg::*;

  logic [7:0]  byte_data; // the addressed byte
  logic [15:0] half_data; // the addressed half
  logic        sign;      // bit that fills the upper part of load_data

  assign byte_data = mem_rdata[{addr_low, 3'b000} +: 8];
  assign half_data = addr_low[1] ? mem_rdata[31:16] : mem_rdata[15:0];

  always_comb begin
    load_data  = mem_rdata;
    sign       = 1'b0;
    misaligned = 1'b0;
    unique case (mem_size)
      SIZE_BYTE: begin
        sign      = byte_data[7] & ~load_unsigned;
        load_data = {{24{sign}}, byte_data};
      end
      SIZE_HALF: begin
        sign       = half_data[15] & ~load_unsigned;
        load_data  = {{16{sign}}, half_data};
        misaligned = addr_low[0];
      end
      default: begin
        misaligned = (addr_low != '0);
      end
    endcase
  end

endmodule
ConceptWhat is the critical path of a circuit?
ConceptWhich kind of instruction has the longest path in the datapath of the lab?
ConceptHow does the critical path set the clock period?
ConceptWhat happens in the lab when the clock is too fast for a path?
ConceptThe critical path is that of a load. Which change shortens the clock period?

Common Mistakes

Wrong Add the delays of blocks that work side by side.

They work at the same time. The path is as long as the slower one.

Fix Add blocks in a row. Take the largest of blocks side by side.

Wrong Set the clock by the most common instruction.

One load in a thousand instructions still needs its full path.

Fix Set the clock by the longest path, however seldom it is used.

Wrong Speed up a block without asking where the critical path is.

A faster block off the critical path changes nothing.

Fix Find the critical path first, and work there.

Remember

  • The delay of a path is the sum of the blocks in a row. Of blocks side by side, the slower one counts.
  • The critical path is the longest path. The clock period must be longer than it.
  • In a single-cycle core every instruction takes the full period, so the slowest instruction slows all of them.
  • A faster block helps only on the critical path. In the real core, that path ends in a counter that no datapath picture shows.

Practice

Report a problem with this page