Compiler does some flow analysis with -O..?

Denis Koroskin 2korden at gmail.com
Thu Apr 9 07:28:10 PDT 2009


On Thu, 09 Apr 2009 18:19:02 +0400, Jarrett Billingsley <jarrett.billingsley at gmail.com> wrote:

> Try this.
>
> void main()
> {
>     int x = void;
>     int y = 3;
>
>     if(y < 10)
>         x += 5;
>     else
>         x = 2;
> }
>
> Notice that x is uninitialized, so "x += 5;" shouldn't work.
>
> If you compile this, even with -w, DMD happily accepts it.  But if you
> throw -O, it gives the error:
>
> dtest.d(187): Error: variable x used before set
>
> This seems to be a relatively recent development, and doesn't seem to
> be documented.  It's also very surprising that it only happens when -O
> is thrown.
>
> I like it a lot.  Could this functionality be formalized and extended
> (i.e. to include accesses to variables declared like "int x;", like it
> says in the spec)?

I believe this is just an optimization and not a general-purpose flow analysis:

Step 0:
int x = void;
int y = 3;

if (y < 10)
    x += 5;
else
    x = 2;

Step 1:
int x = void;
int y = 3;
if (true)
    x += 5;
else
    x = 2;

Step2:
int x = void;
int y = 3;
x += 5;  // Error: variable x used before set



More information about the Digitalmars-d mailing list