Escape analysis (full scope analysis proposal)
Robert Jacques
sandford at jhu.edu
Thu Oct 30 06:04:10 PDT 2008
On Thu, 30 Oct 2008 08:14:31 -0400, Michel Fortin
<michel.fortin at michelf.com> wrote:
>>> And if you try the reverse:
>>> void test1()
>>> {
>>> scope o = new MyObject;
>>> test2(o);
>>> }
>>> void test2(scope MyObject o)
>>> {
>>> int i;
>>> foo(o, &i);
>>> }
>>> Then the compiler could determine automatically that i needs to
>>> escape test2's scope and allocate the variable on the heap to make
>>> its lifetime as long as the object's scope (as it does currently with
>>> nested functions) [see my reserves to this in post scriptum]. This
>>> could be avoided by explictly binding i to the current scope, in
>>> which case the compiler could issue a scope error:
>> The way I read this is o is of type scope MyObject, i is of type scope
>> int and therefore foo(o,&i) is valid and an escape happens.
>
> That's my point. The compiler can detect an escape may happen just by
> looking at the funciton prototype for foo. The prototype tells us that
> foo needs i to be at the same or a lower scope than o, something we
> don't have here.
>
> The compiler can then decide to allocate i dynamically on the heap to
> make sure it exists for at least the scope of o; or it could be decided
> to just make that illegal. I prefer automatic heap allocation, as it
> means we can get rid of the decision to statically or dynamically
> allocate variables: the compiler can decide based on the funciton
> prototypes whichever is best. For cases you really mean a variable to be
> on the stack, you can use scope, as in:
>
> scope int i;
>
> and the compiler would just issue an error if you attept to give a
> reference to i to a function that wants to use it in a lower scope.
> Otherwise, the compiler would be free to decide whichever scope to use
> between local or heap-allocated.
>
Just to clarify:
void test2(scope MyObject o) // the scope of o is a parent of test2
{
int i; // the scope of i is test2
foo(o, &i); // foo(o,&i) requires &i to have o's scope or a parent of
o's scope, so i must be heap (the root parent) allocated.
}
A problem I see is that once shared/local are introduced, you have
multiple heaps where i should be allocated, depending on the runtime type
of o. How would this be handled in this scheme?
More information about the Digitalmars-d
mailing list