Rai*_*Rai 8 c++ macos optimization x86 assembly
我有一个仅包含以下内容的cpp文件:
void f(int* const x)
{
(*x)*= 2;
}
Run Code Online (Sandbox Code Playgroud)
我编译:
g++ -S -masm=intel -O3 -fno-exceptions -fno-asynchronous-unwind-tables f.cpp
Run Code Online (Sandbox Code Playgroud)
这导致f.s
包含:
.section __TEXT,__text,regular,pure_instructions
.macosx_version_min 10, 12
.intel_syntax noprefix
.globl __Z1fPi
.p2align 4, 0x90
__Z1fPi: ## @_Z1fPi
## BB#0:
push rbp
mov rbp, rsp
shl dword ptr [rdi]
pop rbp
ret
.subsections_via_symbols
Run Code Online (Sandbox Code Playgroud)
如果我删除了push
,mov
和pop
指令并组装(在mac上,我正在使用Clang),结果对象文件要小4个字节.链接和执行结果具有相同的行为和相同大小的可执行文件.
这表明这些指令是多余的 - 为什么编译器会把它们放入?这只是一个留给链接器的优化吗?
CLANG/CLANG++既是本机编译器,也是支持多个目标的交叉编译器。在 OS/X 上,默认目标通常是x86_64-apple-darwin
64 位代码和i386-apple-darwin
32 位代码的变体。您看到的代码类似于以下形式:
push rbp
mov rbp, rsp
[snip]
pop rbp
ret
Run Code Online (Sandbox Code Playgroud)
是为了引入栈帧而产生的。默认情况下,CLANG++ 隐式启用 Apple Darwin 目标的堆栈帧。x86_64-linux-gnu
这与和等 Linux 目标不同i386-linux-gnu
。堆栈框架对于某些分析和展开库可以派上用场,并且可以帮助在 OS/X 平台上进行调试,这就是为什么我相信他们选择默认打开它们。
您可以使用CLANG++选项显式省略帧指针-fomit-frame-pointer
。如果您使用构建命令
g++ -S -masm=intel -O3 -fno-exceptions -fno-asynchronous-unwind-tables \
-fomit-frame-pointer f.cpp
Run Code Online (Sandbox Code Playgroud)
输出类似于:
shl dword ptr [rdi]
ret
Run Code Online (Sandbox Code Playgroud)
如果您在CLANG++中使用不同的目标,您会发现行为不同。这是一个 x86-64 Linux 目标,我们没有显式省略帧指针:
clang++ -target x86_64-linux-gnu -S -masm=intel -O3 -fno-exceptions \
-fno-asynchronous-unwind-tables f.cpp
Run Code Online (Sandbox Code Playgroud)
生成:
shl dword ptr [rdi]
ret
Run Code Online (Sandbox Code Playgroud)
这是您原来的 x86-64 Apple Darwin 目标:
clang++ -target x86_64-apple-darwin -S -masm=intel -O3 -fno-exceptions \
-fno-asynchronous-unwind-tables f.cpp
Run Code Online (Sandbox Code Playgroud)
生成:
push rbp
mov rbp, rsp
shl dword ptr [rdi]
pop rbp
ret
Run Code Online (Sandbox Code Playgroud)
然后是省略了帧指针的 x86-64 Apple 目标:
clang++ -target x86_64-apple-darwin -S -masm=intel -O3 -fno-exceptions \
-fno-asynchronous-unwind-tables -fomit-frame-pointer f.cpp
Run Code Online (Sandbox Code Playgroud)
生成:
shl dword ptr [rdi]
ret
Run Code Online (Sandbox Code Playgroud)
您可以在Godbolt上对这些目标进行比较。生成的代码的第一列类似于问题 - Apple target with隐式帧指针。第二个是没有帧指针的 Apple 目标,第三个是 x86-64 Linux 目标。
归档时间: |
|
查看次数: |
168 次 |
最近记录: |