[英]Why is stack memory allocated when it is not used?
Consider the following example:考虑以下示例:
struct vector {
int size() const;
bool empty() const;
};
bool vector::empty() const
{
return size() == 0;
}
The generated assembly code for vector::empty
(by clang, with optimizations):为
vector::empty
生成的汇编代码(通过 clang,经过优化):
push rax
call vector::size() const
test eax, eax
sete al
pop rcx
ret
Why does it allocate stack space?为什么要分配堆栈空间? It is not used at all.
它根本没有被使用。 The
push
and pop
could be omitted. push
和pop
可以省略。 Optimized builds of MSVC and gcc also use stack space for this function (see on godbolt ), so there must be a reason. MSVC 和 gcc 的优化构建也为此功能使用堆栈空间(请参阅有关Godbolt 的内容),因此必须有一个原因。
It allocates stack space, so the stack is 16-byte aligned.它分配堆栈空间,因此堆栈是 16 字节对齐的。 It is needed, because the return address takes 8 bytes, so an additional 8-byte space is needed to keep the stack 16-byte aligned.
它是必需的,因为返回地址需要 8 个字节,因此需要额外的 8 个字节空间来保持堆栈 16 字节对齐。
The alignment of stack frames can be configured with command line arguments for some compilers.对于某些编译器,可以使用命令行参数配置堆栈帧的对齐方式。
rsp
at the beginning of the function, which means that something else also affects this.rsp
在函数的开始,这意味着别的东西也影响到这一点。-mstack-alignment
option specifies the stack alignment. -mstack-alignment
选项指定堆栈对齐。 It seems, that the default is 16, although not documented.push
and pop
) disappears from the generated assembly code.push
和pop
)将从生成的汇编代码中消失。-mpreferred-stack-boundary
option specifies the stack alignment. -mpreferred-stack-boundary
选项指定堆栈对齐。 If the given value is N, it means 2^N bytes of alignment.sub
and add
for rsp
) disappears from the generated assembly code.rsp
sub
和add
)将从生成的汇编代码中消失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.