当我编译下面的代码时gcc 6 -O3 -std=c++14,我得到了很好的空白main:
Dump of assembler code for function main():
0x00000000004003e0 <+0>: xor %eax,%eax
0x00000000004003e2 <+2>: retq
Run Code Online (Sandbox Code Playgroud)
但在主要的"中断"优化中取消注释最后一行:
Dump of assembler code for function main():
0x00000000004005f0 <+0>: sub $0x78,%rsp
0x00000000004005f4 <+4>: lea 0x40(%rsp),%rdi
0x00000000004005f9 <+9>: movq $0x400838,0x10(%rsp)
0x0000000000400602 <+18>: movb $0x0,0x18(%rsp)
0x0000000000400607 <+23>: mov %fs:0x28,%rax
0x0000000000400610 <+32>: mov %rax,0x68(%rsp)
0x0000000000400615 <+37>: xor %eax,%eax
0x0000000000400617 <+39>: movl $0x0,(%rsp)
0x000000000040061e <+46>: movq $0x400838,0x30(%rsp)
0x0000000000400627 <+55>: movb $0x0,0x38(%rsp)
0x000000000040062c <+60>: movl $0x0,0x20(%rsp)
0x0000000000400634 <+68>: movq $0x400838,0x50(%rsp)
0x000000000040063d <+77>: …Run Code Online (Sandbox Code Playgroud) 我很惊讶看到Jonathan Wakely在libstdc ++中引入了以下优化:https://gcc.gnu.org/ml/libstdc++/2018-05/txtc2I3IxLCfn.txt并尝试对其进行调查.
给出了几个用于任何非平凡类的concat函数的实现,令人惊讶的是只有第一个是最优的(一个副本c-tor和一个运算符+ =调用).其他人会发出额外的复制/移动电话 - 你可以在godbolt.org验证它.
这是为什么?我假设所有这些实现都会生成与-O2相同的代码.
语言规范是否要求这样的行为(如果是这样的话?)或者这是QoI问题吗?
这是GCC和Clang在所有版本和语言版本上的一致行为.
void extern_copy();
void extern_move();
void extern_plus_assign();
struct myclass
{
myclass(const myclass&)
{
extern_copy();
}
myclass(myclass&&)
{
extern_move();
}
myclass& operator+=(const myclass&)
{
extern_plus_assign();
return *this;
}
};
myclass concat(const myclass& lhs, const myclass& rhs)
{
myclass copy(lhs);
copy += rhs;
return copy;
}
myclass concat2(const myclass& lhs, const myclass& rhs)
{
myclass copy(lhs);
return copy += rhs;
}
myclass concat3(const myclass& lhs, const myclass& rhs)
{ …Run Code Online (Sandbox Code Playgroud)