Leaf vs nonleaf leaf function does not call other

This preview shows page 14 - 21 out of 25 pages.

Leaf vs. Nonleaf Leaf function Does not call other function(s) No need to save $ra Need to save other registers if required Nonleaf function Does call other function(s) Need to save $ra Need to save other registers if required
Leaf Procedure Example C code: int leaf_example (int g, h, i, j) { int f; f = (g + h) - (i + j); return f; } Arguments g, h, i, j in $a0, …, $a3 Use $s0 for variable f $s0 is a saved register Need to save on stack Result in $v0
Leaf Procedure Example leaf_example: addi $sp, $sp, -4 sw $s0, 0($sp) add $t0, $a0, $a1 add $t1, $a2, $a3 sub $s0, $t0, $t1 add $v0, $s0, $zero lw $s0, 0($sp) addi $sp, $sp, 4 jr $ra Save s register Procedure body Return value set Restore s register Return
Non-Leaf Procedures Procedures that call other procedures For nested call, caller needs to save on the stack: Its return address At beginning of function Any arguments and temporaries needed after the call At beginning of function is saved Before function call if not saved Restore from the stack after the call
Multiple calls on stack Each time a procedure is called, an activation record is created. So if subA calls subB which calls subC, when subC executes all activation records are on the stack $sp is updated on call and return
Non-Leaf Procedure Example C code: int max3(int n1, int n2, int n3) { return max (n1, max (n2, n3); } int max (int v1, int v2) { if (v1 > v2) return v1; return v2; } Arguments in $a0, $a1, $a2 Result in $v0
MIPS Solution – leaf or non-leaf? int max (int v1, int v2) { if (v1 > v2) return v1; return v2; } max: slt $t0, $a0, $a1 bne $t0, $0, val2 ori $v0, $a0, 0 jr $ra Val2: ori $v0, $a1, 0 jr $ra

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture