Why does GCC allocate more space than necessary on the stack, beyond what's needed for alignment?

后端 未结 2 1324
忘掉有多难
忘掉有多难 2020-12-03 18:58

I\'m reading a textbook which shows assembly code based on C code:

C code:

void echo()
{
   char buf[8];
   otherFunction(buf);
}


        
相关标签:
2条回答
  • 2020-12-03 19:19

    Allocating an extra 16 bytes of stack space is a GCC missed optimization that pops up occasionally. I don't know why it happens, but it's reproducible with GCC10.1 -O3. Clang doesn't do it, it just reserves 8 bytes (with a dummy push). Example on Godbolt, where -fno-stack-protector -fno-pie is the default, unlike GCC in many GNU/Linux distros.

    Even int buf; / foo(&buf) results in over-allocation.

    My wild guess is that there's something GCC doesn't optimize away until after it's already decided it needs more than 8 bytes of space (and thus needs 24). Hopefully this good MCVE will let GCC devs find an fix that bug, if it's easily fixable.

    Feel free to report this as a GCC missed-optimization bug (https://gcc.gnu.org/bugzilla/); I looked recently but didn't find an existing one.


    You're correct that allocating 8 bytes would be enough for char buf[8] and re-align RSP by 16 before the call, as required by the x86-64 System V ABI (Why does System V / AMD64 ABI mandate a 16 byte stack alignment?).

    GCC is not trying to maintain 32-byte stack alignment or anything. The default for -mpreferred-stack-boundary is the minimum allowed by the ABI, 4 (2^4 = 16).

    0 讨论(0)
  • 2020-12-03 19:28

    AFAIK the stack must be 16 byte aligned for function calls but I have no clue as to why 24 bytes were allocated and not only 16.

    There are some questions about this on SO already. Why does GCC 6 assume data is 16-byte aligned?

    and on GCCs bugzilla https://gcc.gnu.org/bugzilla/show_bug.cgi?id=40838

    0 讨论(0)
提交回复
热议问题