Skip to content

Exercise 7

Consolidate RISC-V assembly learning and understand how procedure-support instructions are executed. The following C expression is implemented as a procedure call using jal and jr ra:

int f = (g + h) - (i + j);
  1. Open the RISC-V simulator.
  2. Transcribe the code below into the editor:
# Exercise 07
# C expression: int f = (g + h) - (i + j);
.text
j main
leaf_example:
add a5, a1, a2 # a5 = g + h
add a6, a3, a4 # a6 = i + j
sub a0, a5, a6 # f = (g + h) - (i + j), result in a0
jr ra # return to caller
main:
addi a1, zero, 4 # g = 4
addi a2, zero, 7 # h = 7
addi a3, zero, 2 # i = 2
addi a4, zero, 1 # j = 1
jal leaf_example # call the function
nop # a0 now holds the return value (f)

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.
  • For pseudo-instructions, the simulator shows the real instruction in the Basic column and the original form in the Source column. Copy the Basic value into the Instruction column and the Source value into the Pseudo-instruction column. Leave the pseudo column blank for non-pseudo instructions.
  • 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 Pseudo-instruction x10x11x12x13x14x15x16x1
(a0 (f))(a1 (g))(a2 (h))(a3 (i))(a4 (j))(a5)(a6)(ra)
0x000000000x000000000x000000000x000000000x000000000x000000000x000000000x00000000
0x00400000 jal x0 20 j main

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