Skip to content

Exercise 3

Consolidate the use of the conditional branch instruction in RISC-V. The following C expression is translated into assembly using beq:

if (i != j)
f = g + h;
f = f - i;
  1. Open the RISC-V simulator.
  2. Transcribe the code below into the editor:
# Exercise 03
# C expression:
# if (i != j)
# f = g + h;
# f = f - i;
.text
main:
addi s0, zero, 15 # f = 15
addi s1, zero, 10 # g = 10
addi s2, zero, 20 # h = 20
addi s3, zero, 1 # i = 1
addi s4, zero, 2 # j = 2
beq s3, s4, L1 # if (i == j) goto L1
add s0, s1, s2 # f = g + h
L1:
sub s0, s0, s3 # f = f - i

Step-by-step Execution - Scenario 1 (i ≠ j)

Section titled “Step-by-step Execution - Scenario 1 (i ≠ j)”

With the initial values i = 1 and j = 2, the branch is not taken and all instructions execute.

Run the program step by step using the Run One Step button. For each instruction, fill in the table below whenever a register is modified.

Fill in the table below

  • Fill in the PC with the instruction address and copy the Instruction column exactly as it appears in the simulator. Only fill in fields that are modified.
  • If you need more rows, click Add row. Verification only runs when all rows are filled, if nothing appears after clicking Check, it means there are still empty rows.
Before After executing the instruction
PC Instruction x8x9x18x19x20
(s0)(s1)(s2)(s3)(s4)
0x000000000x000000000x000000000x000000000x00000000
0x00400000 addi s0 zero 15 0x0000000F

Tip: in the print dialog, select A2 paper size for best results.

Step-by-step Execution - Scenario 2 (i = j)

Section titled “Step-by-step Execution - Scenario 2 (i = j)”

Now change the addi instruction that sets s4 to assign j = 1 (same as i):

addi s4, zero, 1 # j = 1

Click Reset to reload the program, then run it step by step again. With i = j = 1, the branch is taken and the add instruction is skipped.

Fill in the table below

  • Fill in the PC with the instruction address and copy the Instruction column exactly as it appears in the simulator. Only fill in fields that are modified.
  • If you need more rows, click Add row. Verification only runs when all rows are filled, if nothing appears after clicking Check, it means there are still empty rows.
Before After executing the instruction
PC Instruction x8x9x18x19x20
(s0)(s1)(s2)(s3)(s4)
0x000000000x000000000x000000000x000000000x00000000
0x00400000 addi s0 zero 15 0x0000000F

Tip: in the print dialog, select A2 paper size for best results.

Compare both tables and analyze the difference in the instruction flow (observe the PC sequence) and the final value of s0.