Branches and jumps are what turn a list of instructions into a program: loops, if-statements, function calls and returns all change the PC to somewhere other than the next instruction. This article specifies the branch comparator, cvr32_branch, for exercise E10, and the changes to your core for E11: the branch and jump targets, the redirect to the PC, and the return address that calls save. After E11 your core runs compiled C, and this article also shows how to run your own C programs on it in the lab.

11 min read | Beginner to Intermediate

What You'll Learn

  • Write a branch comparator for the six RV32I conditions, signed and unsigned
  • Compute the targets of branches, jal and jalr, including the cleared bit 0 of jalr
  • Save the return address of a call and redirect the PC in the same cycle
  • Run a compiled C program on your own core in the lab and read the result

Before You Start

The Verilog for this step is small, but you need to be comfortable with signed comparison in Verilog, which The ALU explained, and with the Verilog Tutorial basics. Branches and Jumps in the first half of this tutorial covers the six branches, PC-relative targets and how calls and returns are compiled; How a Program Runs: Loops, Calls and the Stack shows them at run time. Pass E09 before E11; E10 can be done any time.

The Branch Comparator

A conditional branch compares two registers and jumps if the condition holds. The comparator decides the "if":

module cvr32_branch (
    input  logic [2:0]  funct3,    // which condition
    input  logic [31:0] a,         // rs1
    input  logic [31:0] b,         // rs2
    output logic        take       // 1 when the condition holds
);
funct3Instructiontake when
000beqa == b
001bnea != b
100blta < b, signed
101bgea >= b, signed
110bltua < b, unsigned
111bgeua >= b, unsigned

It is combinational and needs no clock. The signed and unsigned rules are the same as for SLT and SLTU in the ALU: compilers use blt and bge for int comparisons and bltu and bgeu for unsigned ones and for loop bounds that cannot be negative. RV32I has no "branch if greater than": bgt a, b is the assembler writing blt b, a with the operands swapped. Note that bge includes equality; it is the exact opposite of blt.

The core uses a separate comparator rather than the ALU because a branch needs the ALU-style comparison and an address addition at the same time: the comparator decides, and a separate adder computes PC + immediate.

Targets

There are three kinds of target:

  • Branches jump to PC + immediate, the B-type immediate from your immediate generator. The PC is the branch's own address, not PC + 4.
  • jal jumps to PC + immediate, with the J-type immediate. It is used for calls to functions and for unconditional jumps within a function (the assembler's j).
  • jalr jumps to rs1 + immediate, with the I-type immediate, and with bit 0 of the sum cleared to 0. It is used for returns (ret is jalr x0, 0(ra)), for calls through function pointers, and with auipc for calls to faraway functions.

For jalr your decoder already sets the ALU to add rs1 and the immediate, so the ALU result is the target before bit 0 is cleared. Clearing bit 0 is part of the RISC-V specification; it lets software use bit 0 of a code address for its own purposes. For branches and jal you need an adder of PC and immediate next to the ALU.

Redirect and the Return Address

The core now tells the PC module to redirect when the instruction is a taken branch, a jal or a jalr, and gives it the right target. The new parts are green:

The complete single-cycle datapath: the branch comparator compares rs1 and rs2, a PC plus immediate adder computes the target, and redirect and target go back to the PC module; for jalr the target is rs1 plus immediate with bit 0 cleared. PC + 4 goes to the write-back multiplexer as the link value for jal and jalr.

jal and jalr also write a register: rd gets PC + 4, the address of the instruction after the jump, so that the called function can return there. The decoder sets wb_sel = 2 for them, and the write-back multiplexer gets a third input. A plain jump writes its link to x0, which throws it away.

All of this happens in one cycle: the jump writes its link register and redirects the PC at the same clock edge. A jalr whose rd and rs1 are the same register, such as jalr ra, 0(ra), still works, because the target is computed from the old value read at the start of the cycle and the new value is written at its end.

Quick Check

Q: At address 0x0000_0030, jalr x7, 0(x6) executes with x6 = 0x0000_00C5. What is the next PC, and what is written to x7?

Show Answer

rs1 + 0 = 0x0000_00C5; clearing bit 0 gives 0x0000_00C4, the next PC. x7 = PC + 4 = 0x0000_0034. The test program does exactly this, with an odd address it builds on purpose.

A Loop and a Call

The test program branch.S exercises every branch, taken and not taken, then a small loop and two calls:

    addi  x3, x0, 10           # a loop: count down to zero
    addi  x4, x0, 0
8:  addi  x4, x4, 3
    addi  x3, x3, -1
    bne   x3, x0, 8b
    jal   x5, sub1             # call: x5 = return address

The loop body runs 10 times. The bne is taken 9 times, back to the label 8, and falls through on the tenth, when x3 reaches 0; x4 ends as 30. The jal then saves its own address plus 4 in x5 and jumps to sub1, which returns with jalr x0, 0(x5). Each check in the program sets one bit of a register that is stored to EXIT at the end: a correct core ends with 0x1FF, nine checks passed. In all, the program executes 68 instructions, makes 42 register writes, and redirects the PC 20 times.

How It Is Tested

E10 tests the comparator with every condition on all pairs of seven corner values (0, 1, -1, 5, -5 and the largest and smallest signed numbers) and 200 random pairs each, a quarter of them equal, which makes 1,494 checks. These are real messages from the three mistakes it was checked against:

Output
FAIL: blt a=0x00000000 b=0xffffffff: expected take=0, got 1
FAIL: bgeu a=0x00000000 b=0xffffffff: expected take=0, got 1
FAIL: bge a=0x00000000 b=0x00000000: expected take=1, got 0

An unsigned blt thinks 0 is less than 0xFFFF_FFFF; a signed bgeu thinks 0 is at least -1; and a strict bge forgets equality.

E11 tests the core with five programs: alu.S and mem.S again, branch.S, all three compared write by write with the reference, and then two C programs compiled with gcc at -O2. hello must print "Hello from cvr32!" through CONSOLE and return 3 (the number of vowels it printed), and sum, which adds up an array, must return 0x0017_FE00. If your core gets lost in a C program, the test stops it after a generous number of cycles and reports where the PC was:

Output
FAIL: register write 33: expected x5 = 0x00000090, got x5 = 0x0000008c
FAIL: no end after 815 cycles: the core is stuck or running the wrong code (PC 0x00000044)

Both come from a core whose jal saves PC instead of PC + 4: in branch.S the link register is off by 4, and in hello every return goes back to the call itself, which calls again, forever. A core whose branch targets are computed from PC + 4, one whose jalr ignores rs1 and one that takes every branch all fail too.

Where Does This Matter?

In the seven C programs the core exercises run, between about one instruction in seven and more than one in three is a branch or a jump, and in the single-cycle core they cost nothing extra. In a pipeline they do: the branch is decided after the next instruction has already been fetched. That cost is why real processors spend so much hardware on branch prediction, which Why Branches Hurt explains, and it is the control hazard you handle yourself in A Control Hazard: Flushing After a Taken Branch.

Running Your Own C on Your Core

After E11 your core can run the code the lab's compiler produces, so you can use it in your own project, not just in the exercises:

  1. In your project with your modules, open the Software panel and press Attach to Current Design. The lab adds a memory model, cv_ram.sv, and a boot testbench, tb_boot.sv, sets the testbench as the top module, and adds a main.c if there is none.
  2. Open tb_boot.sv. It instantiates a placeholder module named my_riscv_core with exactly your core's ports. Change the name to cvr32_core.
  3. Press Run Simulation. The lab compiles main.c, loads the image into cv_ram and simulates. The Console shows the address of the first fetch next to the address the program was loaded at (both should be 0x00000000), whatever the program prints, and finally the number of cycles and the result, for the template program 0x0000002a, which is 42.

From then on, every simulation compiles your C first. Change the program, run again, and look at your own core executing it in the waveform.

Quick Check

Q: A loop is compiled as a bne at the bottom that jumps back 12 bytes. How many times is the bne taken if the loop body runs 100 times, and how many times does it fall through?

Show Answer

Taken 99 times and not taken once, on the last iteration, when the loop exits. This pattern, almost always taken, is typical of loop branches, and it is what simple branch predictors exploit.

Common Mistakes

Mistake #1: Branch targets from PC + 4

The branch offset is relative to the branch instruction's own address. Adding it to PC + 4 lands one instruction too far, every time.

Mistake #2: Forgetting the link or getting it wrong

jal and jalr write PC + 4, not PC, and not the target. Without the link, functions cannot return; with PC instead of PC + 4, they return to the call and call again.

Mistake #3: Not clearing bit 0 of the jalr target

The simulated memory ignores the low address bits, so an odd target seems to work, until the next PC + 4 or the link value is computed from it. The test calls through an odd address on purpose.

Your Turn in the Lab

Each exercise opens with a visible test, testbench.v, next to your design: for the comparator, a short list of directed checks; for the core, the program branch.S, compared write by write with the reference. Simulate it as you work and add your own checks to it. When you submit, it runs together with the hidden tests, and your edits to it do not change the grading.

  1. E10: write cvr32_branch.
  2. E11: paste your E09 core and blocks plus your comparator, and add the targets, the redirect and the link. When it passes, attach a C program to your project and run it on your own core.
Open exercise E10 in ChipVerify Lab Open exercise E11 in ChipVerify Lab

Summary

  • The branch comparator decides beq, bne, blt, bge, bltu and bgeu from funct3, comparing rs1 and rs2 as signed or unsigned numbers.
  • Branches and jal jump to PC + immediate; jalr jumps to rs1 + immediate with bit 0 cleared, computed by the ALU.
  • A taken branch, jal or jalr sets redirect, and the PC takes the target at the next clock edge; jal and jalr write PC + 4 to rd.
  • E11 checks three assembly programs write by write and two C programs by their results; after it, your core runs compiled C.
  • In your own project, Attach to Current Design adds a boot testbench; rename its core instance to cvr32_core and your C runs on your hardware.
Did you find what you were looking for?

Quiz

No quiz questions available for this article.