[cfe-dev] Memory allocation in current function stack using __builtin_alloca

Tim Northover t.p.northover at gmail.com
Sat Jul 13 06:00:55 PDT 2013


> clang version- clang version 3.4 (trunk 186087)
> On compiling it with clang the output is:
> sp1 points at 0xbf87d30f
> sp2 points at 0xbf87d30e

Interestingly, it doesn't if -O3 is used.

There's potential interactions with C++'s rule that each object has a
unique pointer, though since C++11 doesn't mention alloca at all (it's
POSIX) that's a bit of a shaky connection.

> Would be really helpful if someone could throw some light on how stack
> allocation and alignment takes place in clang?

Well, Clang just produces one of LLVM's "alloca" instructions for the
code. The LLVM language reference at
http://llvm.org/docs/LangRef.html#alloca-instruction says: "allocating
zero bytes is legal, but the result is undefined".

More generally, all local variables get an LLVM "alloca" instruction,
which can specify size and alignment. Various LLVM passes know how to
optimise these (hence the difference between -O0 and -O3), and then
they eventually get assigned to stack slots with the appropriate size
and alignment during CodeGen.

To understand what Clang does to your code, it's very helpful to give
it the "-emit-llvm" option (I usually use "-S -o-" as well to actually
see it). At "-O0" that'll be directly what Clang itself creates; at
"-O3" it'll be the code after the LLVM passes have gone to work.

What's happening here (at -O3) is that some pass ("InstCombine" by the
looks of it) is combining the two "alloca 0" instructions into just
one.

Tim.



More information about the cfe-dev mailing list