finite-wasm icon indicating copy to clipboard operation
finite-wasm copied to clipboard

Optimization: merge instrumentation fees into the preceding if branch bodies

Open nagisa opened this issue 1 year ago • 0 comments

Consider a code like this:

(call $gas (i64.const 10))
;; instructions
if (i32.const 1)
    (call $gas (i64.const 10))
    ;; pure instructions
else
    (call $gas (i64.const 2))
    ;; pure instructions
end
(call $gas (i64.const 10))
;; pure instructions

This could actually merge the fees across the branchy construct, first from the successor block into the bodies of the if branches:

(call $gas (i64.const 10))
;; pure instructions
if (i32.const 1)
    (call $gas (i64.const 20))
    ;; pure instructions
else
    (call $gas (i64.const 12))
    ;; pure instructions
end
;; pure instructions

And then from the if condition bodies into the predecessor block:

(call $gas (i64.const 22))
;; pure instructions
if (i32.const 1)
    (call $gas (i64.const 8))
    ;; pure instructions
else
    ;; pure instructions
end
;; pure instructions

Intuitively at least some of these optimizations seem like they shouldn't be too onerous to implement, but the analysis outputs and the optimization algorithm needs to stop being as linear -- i.e. learn how to merge costs not just for the immediately adjacent instructions, but also into the two bodies of if.


Note, though, that this might not actually be a worthwhile problem to pursue. In particular super-optimizing the (call $gas (i64.const X)) sequence might just produce results good enough that occasionally charging gas more often wouldn't be a huge deal.

nagisa avatar Dec 09 '22 14:12 nagisa