2. Instructions: Language of the Computer > 2-4. Supporting procedures in computer HW

Supporting procedures in computer HW

Updated at 2022.09.26

Procedures

Functions in a program

Procedures do calling / returning with other procedures

  • A procedure (caller) calls another procedure (callee)
  • The callee returns values to caller

Calling / returning process

  1. The caller passes input arguments and the return address to the callee
  2. The caller transfers control to the callee
  3. The callee performs its operations with the given input arguments
  4. The callee passes the return values to the caller
  5. The callee transfers control to the caller (Return to the given return address)
  6. The caller restores the saved things

The way to pass values

Use registers for passing arguments, return address, and return values


But, what if different procedures share the same registers?
Use stacks to store all the information for operating each procedure
Stacks are kept in memory

  • The register $sp points the top-of-stack in memory
  • By convention, stack grows towards lower addresses

Register saving

The values of some registers must be preserved on call
It must be possible to recover the values on those registers after calling / returning is completed


If a callee uses preserved registers, the callee must

  • Save the values of the registers on its stack after calling
  • Restore the saved values before returning

If a caller needs to keep the values in non-preserved registers, the caller must

  • Save the values on its stack before calling
  • Restore the saved values after returning

Instructions for procedure calls

jal PROCEDURE_LABEL

  • Jump And Link
  • The return address of a caller (the address of following instruction) put in $ra
  • Jump to the target address (PROCEDURE_LABEL)

jr $ra

  • Jump Register
  • Jump to the address stored in $ra (other registers can also be used as an operand)

Push

addi $sp, $sp, -4
sw $t0, 0($sp)
  • Push the data stored in $t0 into the top-of-stack

Pop

lw $t0, 0($sp)
addi $sp, $sp, 4
  • Pop the data stored in top-of-stack and store it to $t0