我们正在学习 MIPS 汇编器(我想这个问题可以适用于一般的汇编),老师向我们介绍了帧指针.
如果我有一个函数序言,我曾经直接执行堆栈指针:
addiu $sp, $sp, -8 ; alloc 2 words in the stack
sw $s0, 4($sp) ; save caller function $s0 value in the stack
sw $ra, ($sp) ; save the return address for the callee function
在函数尾声中:
move $v0, $0 ; set 0 as return value
lw $s0, 4($sp) ; pick up caller $s0 value from the stack
lw $ra, ($sp) ; pick up return address to return to the caller
addiu $sp, $sp, 8 ; dealloc the stack words I used
jr $ra ; return back to caller
老师说,当我们用汇编语言编写函数时,使用帧指针对于我们人类来说很有用:
addiu $sp, $sp, -12 ; alloc 3 words in the stack
sw $fp, 8($sp) ; save caller frame pointer in the stack
addiu $fp, $sp, 8 ; set $fp to the uppermost address of the activation frame
sw $ra, -4($fp) ; saving like the first example, but relative
sw $s0, -8($fp) ; to the frame pointer
老师还说,有时堆栈指针会继续分配其他空间,并且在函数内引用激活帧会更困难,因为我们需要注意。
使用帧指针,我们将有一个指向激活帧的静态指针。
是的,但是我会ever需要在函数内使用激活,因为它只包含调用者函数保存的数据?
我认为这只会让事情变得更难实施。有没有一个真正的实际例子表明帧指针对程序员来说是一个很大的优势?