SIL pass for optimizing layout of mutable globals?


I'd like to write a SIL pass that aggregates all of the mutable static variables within a type declaration into cache-line aligned global at the IR level. What if any existing passes are a good starting place to crib from? Any tips would be appreciated.


[EDIT] – For example, transform this:

class Foo {
    static var x = 123
    static var y = 456
    static let z = 789

    static func getX() -> Int { return x }

Into something like this before IRGen:

class Foo {
    @_alignment(64) struct _MutableGlobals {
        var x : Int = 123
        var y : Int = 456
    static var _mutableGlobals = _MutableGlobals()
    static let z = 789

    static func getX() -> Int { return _mutableGlobals.x }

In its current form, SIL does not really expose type layouts at all, and it's awkward at best to build new layouts since you would generally have to synthesize types at the AST level in order to do so. Building up SIL's support for representing layouts independent of AST types would be valuable, not only for optimizations like this, but for type layout optimizations that remove dead fields, promote invariant constant fields into globals, and things like that. You might have to build up some of that infrastructure first to get the effect you want.

If you don't want to do that, though, you might be able to make some progress by transforming individual sil_global declarations into aggregate sil_globals of tuple type, and replacing all uses of the original sil_global with a projection on the tuple global. Tuples won't give you much control over alignment or padding within the tuple, though.

1 Like

Hi @Joe_Groff and @John_McCall,

So I'm trying to dial my expectations back given how much work is involved in repacking all of the static mutable variables. I had hoped to slide in some extra mutable data during this optimization pass and make it mandatory, but that seems quite unrealistic for now.

What approach would either of you recommend for modeling and generating ~32 bytes of mutable data per type in the language?

If it helps, I've modeled everything so far as if the metatype/vtable were mutable, but that obviously doesn't work during IRGen and runtime. Specifically, I have a couple new reference storage types that support both instances and metatypes (of classes, if it matters).