5.120 · exercise

Predict: functions

Trace recursive calls, saved registers, and frame records, and say what a function returns or where it stores a value.

0 of 5 correct

Predict the result

// main runs: mov w0, 4 then bl sum
sum:                        // sum(n) = n + sum(n - 1), sum(0) = 0
    stp x29, x30, [sp, -32]!
    mov x29, sp
    str x19, [sp, 16]       // save the caller's x19
    mov w19, w0             // keep n for after the call
    cbz w0, back            // sum(0) returns the 0 already in w0
    sub w0, w0, 1
    bl sum
    add w0, w0, w19
back:
    ldr x19, [sp, 16]
    ldp x29, x30, [sp], 32
    ret

Predict the result

// sp holds 0x8000 when main runs bl keep
keep:
    stp x29, x30, [sp, -32]!
    mov x29, sp
    stp x19, x20, [sp, 16]

Predict the result

// in main
    mov w19, 50
    mov w0, 6
    bl triple
    add w0, w0, w19

triple:
    mov w19, 3              // scratch, never saved
    mul w0, w0, w19
    ret

Predict the result

// sp holds 0x8000 when main runs bl f
f:
    stp x29, x30, [sp, -32]!
    mov x29, sp
    bl g
    ...
g:
    stp x29, x30, [sp, -16]!
    mov x29, sp

Predict the result

// main runs: mov w0, 3 then bl total
total:                      // meant to return n + (n - 1) + ... + 1
    stp x29, x30, [sp, -16]!
    mov x29, sp
    mov w9, w0              // keep n for after the call
    cbz w0, back
    sub w0, w0, 1
    bl total
    add w0, w0, w9
back:
    ldp x29, x30, [sp], 16
    ret