www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Inlining of function(){...}()

reply "Mathias Laurenz Baumann" <anonym001 supradigital.org> writes:
Greetings,

The following code seems to create a new function call:

module test;
void main(char[][] args)
{
	return function(int i) { return i+2; }(1);
}


compiled with dmd test.d -inline
At least objdump of the .o file contains:

RELOCATION RECORDS FOR [.text._Dmain]:
OFFSET   TYPE              VALUE
00000009 R_386_PC32        _D4test4mainFAAaZv14__funcliteral1FiZi

which looks like a additional function to me. Though I must mention that=
 I  =

don't really know how correct my interpretation of these information is.=



Using nested functions, it seems to get inlined:

module test;
void main(char[][] args)
{
	int tmp(int i)
	{
		return i+2;
	}
	return tmp(1);
}



I was wondering if this is correctly interpreted by me and if yes, why i=
t  =

isn't inlined? I would expect that inlining function() {} () would even =
be  =

more easy than a nested function because it is used only at one place.



    --Marenz
-- =

Erstellt mit Operas revolution=C3=A4rem E-Mail-Modul: http://www.opera.c=
om/mail/
Apr 26 2010
parent reply Clemens <eriatarka84 gmail.com> writes:
Mathias Laurenz Baumann Wrote:

 Greetings,
 
 The following code seems to create a new function call:
 
 module test;
 void main(char[][] args)
 {
 	return function(int i) { return i+2; }(1);
 }
 

I guess the compiler could peephole-optimize that. Though: how common would that idiom be? Why create a function literal just to call it on the spot? Why not use a nested function in the first place?
Apr 26 2010
parent reply BCS <none anon.com> writes:
Hello Clemens,

 Mathias Laurenz Baumann Wrote:
 
 Greetings,
 
 The following code seems to create a new function call:
 
 module test;
 void main(char[][] args)
 {
 return function(int i) { return i+2; }(1);
 }

would that idiom be? Why create a function literal just to call it on the spot? Why not use a nested function in the first place?

int Wrap(int function() fn, int i) { pre(); auto r = fn(i); post(); return r; } void main() { Wrap(function(int i) { return i+2; },0); } after Wrap is inlined, you get the same case as above -- ... <IXOYE><
Apr 26 2010
parent Clemens <eriatarka84 gmail.com> writes:
BCS Wrote:

 Hello Clemens,
 
 Mathias Laurenz Baumann Wrote:
 
 Greetings,
 
 The following code seems to create a new function call:
 
 module test;
 void main(char[][] args)
 {
 return function(int i) { return i+2; }(1);
 }

would that idiom be? Why create a function literal just to call it on the spot? Why not use a nested function in the first place?

int Wrap(int function() fn, int i) { pre(); auto r = fn(i); post(); return r; } void main() { Wrap(function(int i) { return i+2; },0); } after Wrap is inlined, you get the same case as above

Ah yes, good point. In that light it seems like a very useful optimization.
Apr 26 2010