ISA & Assembly

A function that calls no other functions (a leaf function) often does not need to save ra on the stack. Why?

  1. ABecause leaf functions do not use the ret instruction
  2. BBecause the CPU automatically pushes the return address of leaf functions
  3. CBecause it calls no one, ra is never overwritten and the return address stays intact
Show answer and explanation

Answer: C. Because it calls no one, ra is never overwritten and the return address stays intact

Every jal overwrites ra, so a function that calls others must first save its own return address on the stack. A leaf function makes no calls that write ra (jal ra or jalr ra), so ra stays intact and it can ret without saving it. If it also avoids callee-saved registers, it does not even need a stack frame. x86's call instruction always pushes the return address on the stack, which is a difference from RISC-V.

  • A. Leaf functions also return with ret.
  • B. RISC-V jal only writes a register; it does not push to the stack.
  • C. Correct. It never executes a jal that would overwrite ra.