ControlCplusControlV / Scribe

Minimal Yul Transpilation to the Miden VM
GNU General Public License v3.0
51 stars 4 forks source link

More optimizations #3

Closed marcusbuffett closed 2 years ago

marcusbuffett commented 2 years ago

Building off the previous optimization work, a couple new ones.

For loops -> repeat

When for loops match a particular structure, we can output repeat.{} instructions instead of all the cruft involved in for loops usually (init_block, conditional, after block, conditional again).

One cool thing here is that this builds on top of the const-ing of variables from the previous optimization pass. So in the fibonacci example, this optimization wouldn't happen, if we didn't first const the n variable.

For now this is really fragile, it only works for for loops that declare a var to start from a constant, then check with lt that it is below another constant. It also doesn't detect if the iterator variable is referenced inside the for loop, but that's trivial to add.

Equating references

When we hit a line like a := b, we don't actually have to do anything to the stack. So now the stack will keep track of a set of references that that slot points to, instead of duplicating that slot.

Results

Fibonnaci has slimmed down another 50%, to 13 instructions:

begin
    push.0
    push.1
    push.0
    repeat.10
        dup.2
        dup.2
        add
        dup.2
        dup.1
        dup.2
    end
    dup.1
end
ControlCplusControlV commented 2 years ago

LGTM, really impressive work. Now I have to step up my game and start implementing more opcodes . I will say that make an issue once you merge this to make sure the index variable isn't referenced within the for loop, otherwise this will cause some nasty errors