简体   繁体   English

为什么不使用时分配堆栈内存?

[英]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. pushpop可以省略。 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.对于某些编译器,可以使用命令行参数配置堆栈帧的对齐方式。

  • MSVC : The documentation says that the stack is always 16-byte aligned. MSVC文档说堆栈总是 16 字节对齐。 No command line argument can change this.没有命令行参数可以改变这一点。 The godbolt example shows that 40 bytes are subtracted from rsp at the beginning of the function, which means that something else also affects this.该godbolt例子表明,40个字节从减去rsp在函数的开始,这意味着别的东西也影响到这一点。
  • clang : The -mstack-alignment option specifies the stack alignment. clang-mstack-alignment选项指定堆栈对齐。 It seems, that the default is 16, although not documented.似乎默认值是 16,尽管没有记录。 If you set it to 8, the stack allocation ( push and pop ) disappears from the generated assembly code.如果将其设置为 8,堆栈分配( pushpop )将从生成的汇编代码中消失。
  • gcc : The-mpreferred-stack-boundary option specifies the stack alignment. gcc-mpreferred-stack-boundary选项指定堆栈对齐。 If the given value is N, it means 2^N bytes of alignment.如果给定的值为 N,则表示 2^N 字节对齐。 The default value is 4, which means 16 bytes.默认值为 4,即 16 个字节。 If you set it to 3 (ie 8 bytes), the stack allocation ( sub and add for rsp ) disappears from the generated assembly code.如果将其设置为 3(即 8 个字节),则堆栈分配( rsp subadd )将从生成的汇编代码中消失。

Check out on godbolt .Godbolt查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM