Bug 3822 – Invalid optimization of alloca called with constant size
Status
RESOLVED
Resolution
FIXED
Severity
critical
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-02-18T11:17:00Z
Last change time
2015-06-09T05:11:34Z
Keywords
pull, wrong-code
Assigned to
yebblies
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2010-02-18T11:17:11Z
import std.stdio: printf;
import std.c.stdlib: alloca;
void main() {
const int n = 8;
for (int i; i < 2; i++)
printf("%p\n", alloca(n));
}
It prints two times the same address, I don't know why, I think this can be wrong.
Comment #1 by shro8822 — 2010-02-18T12:03:35Z
I've never used alloca so I'm not sure, so this is a guess:
alloca does stack allocation and the body of the for statement forms a scope on the stack (this in this case contains no named variables). I'm guessing that when that scope is exited, the allocation automatically gets deallocated.
Comment #2 by bearophile_hugs — 2010-02-18T12:32:38Z
(In reply to comment #1)
> I've never used alloca so I'm not sure, so this is a guess:
>
> alloca does stack allocation and the body of the for statement forms a scope on
> the stack (this in this case contains no named variables). I'm guessing that
> when that scope is exited, the allocation automatically gets deallocated.
You can be right, thank you. Then it's very good for Phobos docs to say that alloca is relative to a scope and not to a function.
The description of alloca() that I have seen says:
The alloca() function allocates space in the stack frame of the caller, and returns a pointer to the allocated block. This temporary space is automatically freed when the function from which alloca() is called returns.
While if you are right D alloca frees space when the scope of alloca ends and not when the function ends.
Comment #3 by bearophile_hugs — 2010-06-07T04:04:04Z
Maybe the alloca() used by dmd frees memory as soon as the current scope is left, instead of deferring all deallocation until function exit. See:
http://compilers.iecc.com/comparch/article/91-12-079
D documentation has to explain how exactly its alloca() works.
Comment #4 by nfxjfg — 2010-06-07T04:17:53Z
C code that compiles in D without modification should work exactly as it does in C.
This means this is a rather bad code gen bug.
The issue here is that n is a compile-time constant, so the call to alloca is optimized away completely, and always reserving the extra space. This optimization is not valid if the call to alloca might be repeated.