Bug 4357 – Stack allocation for small scope dynamic arrays
Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-06-21T04:52:00Z
Last change time
2010-06-21T11:23:19Z
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2010-06-21T04:52:09Z
Dynamic arrays are used very often in D, much more often than malloc-allocated arrays in C programs.
A scope dynamic array lives only inside the function it's allocated. So with this program:
int[] foo(int n) {
scope arr = new int[n];
return arr;
}
void main() {}
DMD v2.047 generates this error:
test.d(3): Error: escaping reference to scope local arr
So the compiler can add an inlined runtime test: if the amount of memory necessary to allocate 'arr' is "small" (like few hundred bytes) (or better if it is small compared to the free space currently available on the stack), then the memory for 'arr' can be allocated on the stack instead of the heap, with an alloca. This can improve performance a little if foo() is called many times.
Compared to C programs (or D programs written in C-like style), this optimization can make the D idiom of using dynamic arrays often less costly, and avoids most of the need of the Variable Length Arrays of C99.
This enhancement request is marked as relative to the DMD component (instead of being just a runtime thing) because the test and the optional stack allocation need to be inlined.
A D compiler can perform the same optimization on dynamic array allocation even if the 'scope' attribute is missing if it is able to perform some escape analysis and it is able to verify that 'arr' never escapes foo().
Comment #1 by nfxjfg — 2010-06-21T05:03:49Z
Andrei said this use of scope is gone.
Sorry pal, WONTFIX *bamm*
Comment #2 by bearophile_hugs — 2010-06-21T11:23:19Z
Sorry, I didn't know that. I have thought that the removal of the scope attribute was only for class instances.
Even if the scope attribute can't be used on dynamic arrays, the last point I have expressed applies still: if the compiler is able to perform escape
analysis (LLVM has some of such capability) and it can statically verify a dynamic array never escapes, then if a runtime test shows such dynamic arrays is small it can be allocated on the stack.