[MLton] ref flattening and backpatching

Stephen Weeks MLton@mlton.org
Wed, 22 Sep 2004 14:24:23 -0700


> One not so uncommon use of ref's in SML is to backpatch circular
> data-structures.  My understanding of the ref flattening analysis is
> that it will not capture this case, because the constructed ref is
> both put into a tuple and assigned to directly.

You are correct.

> I suspect it's fairly trivial to extend the refFlatten analysis to
> also determine when the ref can be flattened as an immutable field

Yes, this makes sense, and the immutability information could help
other optimizations.

> (and, less interesting, the converse, when the ref is only written
> and never read, in which case the field is essentially useless).

True, although the useless pass already gets this.  Of course, it is
sometimes useful to duplicate optimizations because of phase ordering
issues.

> Although, I'm not sure whether this buys much -- as far as I know,
> the only additional cost we pay for a flattened ref is the card mark
> when it is mutated, which would be zero in the case I'm describing.

I don't understand.  Whether a card mark occurs on a := only depends
on whether the value being assigned is represented as a pointer or
not.  Flattening the ref cell has no impact on that.  The impact of
flattening is the space savings from not allocating the ref cell as a
separate object.

> A simple option would be to be a little more liberal with a ref in
> the block in which it is created -- i.e., as in the case above, if
> the ref were flattened, we could still "get at it" in the
> data-structure.

This seems an easy (and correct!) extension.  I will put it in this
week.