Escape analysis

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 28 05:58:18 PDT 2008


"Walter Bright" wrote
> The reason the scope/noscope needs to be part of the function signature is 
> because:
>
> 1. that makes it self-documenting

But the documentation is not enough.  You cannot express the intricacies of 
what variables are scope escapes so that the compiler can make intelligent 
enough decisions.  What this will result in is slightly less unnecessary 
closures, but not enough to make a difference.  Or else you won't be able to 
declare things the way you want, so you will be forced to declare something 
that *could* result in an escape, but usually doesn't.

> 2. function bodies may be external, i.e. not present
> 3. virtual functions

Yes, so you are now implying a scope escape contract on all derived classes. 
But not a very expressive one.

> 4. notifies the user if a library function parameter scope-ness changes 
> (you'll get a compile time error)

Oh really?  I imagined that if the scope-ness changed it just results in a 
new heap allocation when I call the function.

i.e.  Joe library developer has this function foo:

int foo(scope int *x) {return *x;}

And he now decides he wants to change it somehow:

int *lastFooCalledWith;
int foo(int *x) {lastFooCalledWith = x; return *x;}

I used foo like this:

int i;
auto j = foo(&i);

So does this now fail to compile?  Or does it silently kill the performance 
of my code?

If the latter, we are left with the same problem we have now.

If the former, how does one call a function with a noscope parameter?

The more I think about this, the more I'd rather have D1 behavior and some 
sort of way to indicate my function should allocate a heap frame (except on 
easily provable scope escapes).

The most common case I think which will cause unnecessary allocations, is a 
very common case.  A class setter:

class X
{
   private int *v_;
   int *v(int *newV) {return v_ = newV;}
   int *v() { return v_;}
}

Clearly, newV escapes into the class instance, but how do we know what the 
scope of the class instance is to know if newV truly escapes its own scope?

-Steve 





More information about the Digitalmars-d mailing list