我试图理解这个简单的C程序:
int square(int num) {
return num * num;
}
Run Code Online (Sandbox Code Playgroud)
当它在汇编代码中时:
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
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)mov DWORD PTR [rbp-4], edi ;not sure what happens here
x86_64 System V ABI通过寄存器传递函数参数 - 第一个整数参数在rdi/edi
寄存器中传递.因此,该行将参数复制num
到本地(从存储在其中的帧指针值偏移-4个字节rbp
).
Run Code Online (Sandbox Code Playgroud)mov eax, DWORD PTR [rbp-4] ;not sure what happens here
这会将本地的值复制到eax
寄存器中.
Run Code Online (Sandbox Code Playgroud)imul eax, DWORD PTR [rbp-4] ;multiply eax and DWORD PTR [rbp-4] (?)
并且它将值乘以eax
local,并将结果存储到eax
(也恰好是存储函数返回值的寄存器).
正如其他人在评论中指出,与优化的编译可能会消除局部,并直接从编写edi
到eax
.