binaryen icon indicating copy to clipboard operation
binaryen copied to clipboard

wasm-opt: Optimize out store of load with traps-never-happen

Open Anonymity20202 opened this issue 3 years ago • 4 comments

Such WebAssembly code snippet will not be optimized by wasm-opt

    (local $var i32)
    ...
    local.tee $var
    local.get $var
    i32.load
    i32.store

However, this equals

*var = *var

which is safe to remove.

Anonymity20202 avatar Oct 06 '22 11:10 Anonymity20202

which is safe to remove.

That's not safe in WebAssembly due to load / store has side effects (it may trap OOB). And we already discussed about this

MaxGraey avatar Oct 06 '22 11:10 MaxGraey

It may trap OOB only when the value of $var is undeterministic or the pointed memory is undefined, when this is not the case, I do not see why it is not safe to remove. For example,

    (local $var i32)
    ...
    i32.const 100
    local.tee $var
    i32.const 0
    i32.store
    local.tee $var
    local.get $var
    i32.load
    i32.store

Anonymity20202 avatar Oct 06 '22 11:10 Anonymity20202

Or similarly,

    i32.const 1776
    i32.const 0
    i32.store
    i32.const 1776
    i32.const 1
    i32.store

Anonymity20202 avatar Oct 06 '22 11:10 Anonymity20202

I suppose we could optimize this when trapsNeverHappens is set. Then we can assume that doesn't trap, and the write is redundant.

(edit: ah, I see that was already mentioned in the old thread, sorry for the noise.)

kripken avatar Oct 06 '22 17:10 kripken