我试图理解这个简单的C程序:
int square(int num) {
return num * num;
}
当它在汇编代码中时:
square(int):
push rbp ;push rbp register onto stack
mov rbp, rsp ;move contents of rbp register into rsp register
mov DWORD PTR [rbp-4], edi ;not sure what happens here
mov eax, DWORD PTR [rbp-4] ;not sure what happens here
imul eax, DWORD PTR [rbp-4] ;multiply eax and DWORD PTR [rbp-4] (?)
pop rbp ;pop original register out of stack
ret ;return
-
第3和第4行发生了什么?
-
为什么必须使用两个寄存器(edi和eax)而不是rsp?
-
DWORD PTR [rbp-4]实际发生了什么?
1 回答
x86_64 System V ABI通过寄存器传递函数参数 - 第一个整数参数在
rdi/edi
寄存器中传递 . 因此,该行将参数num
复制到本地(从存储在rbp
中的帧指针值偏移-4个字节) .这会将本地的值复制到
eax
寄存器中 .这将
eax
中的值乘以local,并将结果存储到eax
(它也恰好是存储函数返回值的寄存器) .正如其他人在评论中指出的那样,使用优化进行编译可能会消除本地,并直接从
edi
写入eax
.