我想检查boost::variant在我的代码中应用的程序集输出,以便查看哪些中间调用被优化掉了.
当我编译以下示例(使用GCC 5.3 g++ -O3 -std=c++14 -S)时,似乎编译器优化了所有内容并直接返回100:
(...)
main:
.LFB9320:
.cfi_startproc
movl $100, %eax
ret
.cfi_endproc
(...)
Run Code Online (Sandbox Code Playgroud)
#include <boost/variant.hpp>
struct Foo
{
int get() { return 100; }
};
struct Bar
{
int get() { return 999; }
};
using Variant = boost::variant<Foo, Bar>;
int run(Variant v)
{
return boost::apply_visitor([](auto& x){return x.get();}, v);
}
int main()
{
Foo f;
return run(f);
}
Run Code Online (Sandbox Code Playgroud)
但是,完整的程序集输出包含的内容远远超过上面的摘录,对我而言,它看起来永远不会被调用.有没有办法告诉GCC/clang删除所有"噪音"并输出程序运行时实际调用的内容?
完整装配输出:
.file "main1.cpp"
.section .rodata.str1.8,"aMS",@progbits,1
.align 8
.LC0:
.string "/opt/boost/include/boost/variant/detail/forced_return.hpp"
.section .rodata.str1.1,"aMS",@progbits,1
.LC1: …Run Code Online (Sandbox Code Playgroud) 我正在研究两个代码的输出,使用-fomit-frame-pointer和without(gcc at"-O3"默认启用该选项).
pushq %rbp
movq %rsp, %rbp
...
popq %rbp
Run Code Online (Sandbox Code Playgroud)
如果我全局禁用该选项,即使是在极端情况下编译操作系统,是否有一个问题?
我知道中断使用该信息,那么该选项仅适用于用户空间吗?
据我所知,当一个进程分配局部变量时,它会通过将它们作为堆栈推送到内存中来实现,但仍然可以通过使用堆栈指针的偏移来引用它们作为随机内存来引用它们(从这个线程是什么)使用堆栈为局部变量背后的想法?).
但是,它如何知道哪些变量有什么偏移?我是否以正确的方式思考这个问题?
好吧,我知道main()自动局部变量存储在堆栈中,也是任何函数自动局部变量,但是当我在gcc版本4.6.3上尝试了以下代码时:
#include <stdio.h>
int main(int argc, char *argv[]) {
int var1;
int var2;
int var3;
int var4;
printf("%p\n%p\n%p\n%p\n",&var1,&var2,&var3,&var4);
}
Run Code Online (Sandbox Code Playgroud)
结果是:
0xbfca41e0
0xbfca41e4
0xbfca41e8
0xbfca41ec
Run Code Online (Sandbox Code Playgroud)
根据堆栈顶部的var4和堆栈底部的var1以及堆栈指针现在指向var1地址下面的地址....但是为什么var4位于堆栈顶部而var1位于底部. ..在var1之后声明,所以我认为逻辑上var1应该在堆栈的顶部,var1之后声明的任何变量应该在内存中低于它...所以在我的例子中这样:
>>var1 at 0xbfca41ec
>>var2 at 0xbfca41e8
>>var3 at 0xbfca41e4
>>var4 at 0xbfca41e0
>>and stack pointer pointing here
..
Run Code Online (Sandbox Code Playgroud)
编辑1:
在阅读@AusCBloke的评论后,我尝试了以下代码:
#include <stdio.h>
void fun(){
int var1;
int var2;
printf("inside the function\n");
printf("%p\n%p\n",&var1,&var2);
}
int main(int argc, char *argv[]) {
int var1;
int var2;
int var3;
int var4;
printf("inside the main\n");
printf("%p\n%p\n%p\n%p\n",&var1,&var2,&var3,&var4);
fun();
return …Run Code Online (Sandbox Code Playgroud)