绘制用于递归函数的堆栈帧

时间:2016-01-10 00:37:07

标签: c assembly stack

给出以下递归函数:

int silly(int n, int *p)
{
    int val, val2;

    if (n > 0) {
        val2 = silly(n << 1, &val);
    } else {
        val = val2 = 0;
    }

    *p = val + val2 + n;

    return val + val2;
}

如果未启用优化程序,则会生成以下汇编代码:

silly:
pushq   %rbp
movq    %rsp, %rbp
subq    $32, %rsp
movl    %edi, -20(%rbp)
movq    %rsi, -32(%rbp)
cmpl    $0, -20(%rbp)
jle     .L2
movl    -20(%rbp), %eax
leal    (%rax,%rax), %edx
leaq    -8(%rbp), %rax
movq    %rax, %rsi
movl    %edx, %edi
call    silly
movl    %eax, -4(%rbp)
jmp     .L3
.L2:
movl    $0, -4(%rbp)
movl    -4(%rbp), %eax
movl    %eax, -8(%rbp)
.L3:
movl    -8(%rbp), %edx
movl    -4(%rbp), %eax
addl    %eax, %edx
movl    -20(%rbp), %eax
addl    %eax, %edx
movq    -32(%rbp), %rax
movl    %edx, (%rax)
movl    -8(%rbp), %edx
movl    -4(%rbp), %eax
addl    %edx, %eax
movq    %rbp, %rsp
popq    %rbp
ret

有人可以协助我绘制此函数中使用的堆栈帧,指示程序值的存储位置和位置 %rsp%rbp寄存器指向递归调用之前 silly()?

1 个答案:

答案 0 :(得分:1)

所以这是最终答案:

    |                                |  
    +--------------------------------+
    |                                |  
    +--------------------------------+
    |             ...                |  
    +--------------------------------+
    |        return address          |  12
    +--------------------------------+
    |        return address          |  8
    +--------------------------------+
    |             %rbp               |  4
    +--------------------------------+
    |             %rbp               |  0
    +--------------------------------+
    |             val2               |  -4
    +--------------------------------+
    |             val                |  -8
    +--------------------------------+
    |                                |  -12
    +--------------------------------+
    |                                |  -16
    +--------------------------------+
    |              n                 |  -20
    +--------------------------------+
    |                                |  -24
    +--------------------------------+
    |              p                 |  -28
    +--------------------------------+
    |              p                 |  -32
    +--------------------------------+