cardillan / mindcode

A high level language for Mindustry Logic (mlog) and Mindustry Schematics.
http://mindcode.herokuapp.com/
MIT License
87 stars 13 forks source link

Function return values misplaced by loop hoisting #129

Closed cardillan closed 8 months ago

cardillan commented 8 months ago

The loop hoisting optimization mistakenly processes assignments from function return variables. This code

#set function-inlining = off

while true
    a = foo()
    b = foo()
    print(a, b)
end

def foo()
    rand(10)
end

produces

set a __fn0retval
set __fn0retaddr 3
jump 8 always 0 0
set __fn0retaddr 5
jump 8 always 0 0
print a
print __fn0retval
jump 1 always 0 0
op rand __fn0retval 10 0
set @counter __fn0retaddr

The set a __fn0retval instruction was hoisted in front of the loop - the optimizer doesn't recognize the __fn0retval value is actually produced by the function being called.