www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - How does the compiler avoid creating a closure here?

reply Andrei Alexandrescu <SeeWebsiteForEmail erdani.org> writes:
Consider http://dpaste.dzfl.pl/fork/ae75176d7d3f.

It's a bit roundabout but in brief it instantiates a template with a 
nested function. The nested function, in turn, uses a parameter in its 
environment. By the canon, that function needs to create a closure with 
dynamically-allocated environment.

To my surprise, however, the generated code uses no closure (disassembly 
at http://goo.gl/ti23W0) yet works correctly.

How come? Can anyone explain to me where x (used by the nested function) 
is stored?


Thanks,

Andrei

P.S. I'd like to thank Iain and Vladimir for making it so easy and 
pleasing to inspect and share code snippets with dpaste and asm.dlang.org.
Jun 02 2015
parent Walter Bright <newshound2 digitalmars.com> writes:
On 6/2/2015 11:05 PM, Andrei Alexandrescu wrote:
 Consider http://dpaste.dzfl.pl/fork/ae75176d7d3f.

 It's a bit roundabout but in brief it instantiates a template with a nested
 function. The nested function, in turn, uses a parameter in its environment. By
 the canon, that function needs to create a closure with dynamically-allocated
 environment.

 To my surprise, however, the generated code uses no closure (disassembly at
 http://goo.gl/ti23W0) yet works correctly.

 How come? Can anyone explain to me where x (used by the nested function) is
stored?
It doesn't avoid creating a closure. The dpaste compiler is not showing the call to __d_allocmemory because it is incorrectly resolving it to another symbol. (A closure can be detected by the presence of a call to __d_allocmemory.)
Jun 02 2015