在 C++ 中,编译器是否可以优化代码,使本地对象实例完全存在于寄存器中,而不是分配在堆栈中?
例如,使用这段代码:
#include <inttypes.h>
class int24_t {
int32_t val;
public:
int24_t(int32_t v = 0) { val = v & 0xffffff; }
int24_t add(int24_t v) { return int24_t(val + v.val); }
};
int24_t add_two_int24(int24_t a, int24_t b)
{
return a.add(b);
}
没有虚函数,也没有任何其他额外数据,使得“val
”实际上是该对象存储在内存中的唯一数据,因此编译器是否有可能生成如下汇编:
push ebp
mov ebp, esp
mov eax, [ebp+8]
add eax, [ebp+12]
and eax, 0x00ffffff
pop ebp
ret
而不是在栈中为对象分配空间?
编辑:
这是可能的。例如,我的计算机 (x64_64) 中的 gcc -march=native -O2 -c
生成此代码:
Disassembly of section .text:
0000000000000000 <add_two_int24(int24_t, int24_t)>:
0: 8d 04 37 lea (%rdi,%rsi,1),%eax
3: 25 ff ff ff 00 and $0xffffff,%eax
8: c3 retq
最佳答案
是的,如果对象大小小于或等于处理器寄存器的大小,则对象可以存在于处理器的寄存器中。
编译器是否选择这样做是另一回事。生成汇编语言列表。此外,根据需要调整优化级别。
关于c++ - 本地对象可以完全存在于 C++ 中的硬件寄存器中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108252/