More pure optimizations

Brad Roberts braddr at puremagic.com
Wed Jun 3 18:54:45 PDT 2009


On Wed, 3 Jun 2009, bearophile wrote:

> If I compile code like the following with D2, with no inlining:
> 
> import std.c.stdio: printf;
> 
> pure int bar(int x) { return x * 2; }
> 
> int foo() {
>     int x;
>     for (int i; i < 100; i++)
>         x += bar(10);
>     return x;
> }
> 
> void main() {
>     printf("%d\n", foo());
> }
> 
> bar() is pure, so the compiler can compute it only once before the loop.
> 
> But currently DMD compiles foo() as:
> 
> L0:		push	EAX
> 		push	EBX
> 		xor	EBX,EBX
> 		push	ESI
> 		xor	ESI,ESI
> L7:		mov	EAX,0Ah
> 		call	near ptr _D5temp23barFNaiZi
> 		add	ESI,EAX
> 		inc	EBX
> 		cmp	EBX,064h
> 		jb	L7
> 		mov	EAX,ESI
> 		pop	ESI
> 		pop	EBX
> 		pop	ECX
> 		ret
> 
> Once that optimization is in place, the reading access to associative arrays too can be marked as "pure" so the in the following code h["bar"] is seen as a loop invariant, and computed only once before the loop:

Hrm.. Walter, I thought D2's optimizer had already grown the ability to 
take advantage of pure.  Does it not do loop hoisting yet?

On a related note, I started this past weekend playing with automatic 
detection / proof of pureness in the d2 codebase.  It's a long way from 
complete, but could allow the optimizer to find pure by implementation 
rather than pure by definition cases to play with.  The same code can be 
used to validate the pure attribute and warn or error on violations.

Once I get it a semi-useful state, I'll toss a patch into a bug report so 
others can see it.  Right now it's too embrionic to share. :(

Later,
Brad



More information about the Digitalmars-d mailing list