Exercise 8
Objective
Section titled “Objective”Consolidate RISC-V assembly learning and understand how the stack is used to preserve registers across procedure calls. The same C expression as Exercise 7 is used, but now leaf_example saves and restores registers t0, t1, and s0 on the stack:
int f = (g + h) - (i + j);Instructions
Section titled “Instructions”- Open the RISC-V simulator.
- Transcribe the code below into the editor:
# Exercise 08# int f = (g + h) - (i + j);
.text j main
leaf_example: addi sp, sp, -12 # adjust stack for 3 registers sw t1, 8(sp) # save t1 sw t0, 4(sp) # save t0 sw s0, 0(sp) # save s0
add t0, a1, a2 # t0 = g + h add t1, a3, a4 # t1 = i + j sub s0, t0, t1 # f = t0 - t1 add a0, s0, zero # return value in a0
lw s0, 0(sp) # restore s0 lw t0, 4(sp) # restore t0 lw t1, 8(sp) # restore t1 addi sp, sp, 12 # free stack space jr ra # return from function
main: addi t1, zero, 1 addi t0, zero, 2 addi s0, zero, 3
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 leaf_example nop # result in a0Step-by-step Execution
Section titled “Step-by-step Execution”Run the program step by step using the Run One Step button. For each instruction, fill in the table below whenever a register or memory position 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.