More pure optimizations

bearophile bearophileHUGS at lycos.com
Wed Jun 3 17:40:59 PDT 2009


This bost is born from the following comment:

http://www.reddit.com/r/programming/comments/8piiy/upcoming_luajit_2xs_performance_comparable_to_c/c0a12gb

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:

import std.c.stdio: printf;

int foo(int[string] h) {
    int x;
    for (int i; i < 100; i++)
        x += h["bar"];
    return x;
}

void main() {
    printf("%d\n", foo(["bar": 42]));
}

It seems the LuaJIT2 is already able to do such things.

I'd like to have pure optimizations in LDC D1 too :-)

I guess it's not easy for the compiler to have some heuristics that allows it to infer that a function like:
int bar(int x) { return x * 2; }
is pure even if it's not marked as pure.

-------------

Talking about compiler optimizations, here I have shown an usage example of the new escape analysis the last Java is able to do, with good results:

http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&article_id=16762

Bye,
bearophile



More information about the Digitalmars-d mailing list