WebAssembly / WebAssembly/binaryen

RemoveUnusedBrs fails to optimize control flow based dead code

Open
#7,652 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
WebAssembly
Stars
8.6k
Forks
885
Avg merge
1d 19h
Merged PRs (30d)
69

Description

Given the following code:

(module
  (import "env" "dead" (func $dead))
  (func $_start (param $0 i32)
    i32.const 0
    i32.const 0
    call $main)
  (func $main (param $0 i32) (param $1 i32)
    block  ;; label = @1
      i32.const 0
      i32.const 0
      i32.store
      i32.const 0
      i32.load
      local.set $1
      i32.const 1
      local.set $0
      local.get $1
      br_if 0 (;@1;)
      i32.const 0
      i32.const 0
      i32.store
      i32.const 1
      local.set $0
      local.get $0
      br_if 0 (;@1;)
      i32.const 0
      local.set $0
    end
    local.get $0
    if  ;; label = @1
      unreachable
    end
    call $dead
    call $dead
    call $dead
    )
  (memory 1)
  (export "_start" (func $_start)))

wasm-opt version: 2b989ae

O2 can eliminate the dead code because it identifies the statements of if unreachable:

 (func $_start (param $0 i32)
  (i32.store
   (i32.const 0)
   (i32.const 0)
  )
  (if
   (i32.eqz
    (i32.load
     (i32.const 0)
    )
   )
   (then
    (i32.store
     (i32.const 0)
     (i32.const 0)
    )
   )
  )
  (unreachable)
 )

O3 cannot:

 (func $_start (param $0 i32)
  (if
   (block $block (result i32)
    (i32.store
     (i32.const 0)
     (i32.const 0)
    )
    (drop
     (br_if $block
      (i32.const 1)
      (i32.load
       (i32.const 0)
      )
     )
    )
    (i32.store
     (i32.const 0)
     (i32.const 0)
    )
    (i32.const 1)
   )
   (then
    (unreachable)
   )
  )
  (call $dead)
  (call $dead)
  (call $dead)
 )

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the RemoveUnusedBrs optimization and reproduce the supplied WebAssembly case using wasm-opt version 2b989ae at O2 and O3. Compare the resulting control flow with the expected O2 output; done means O3 also eliminates the unreachable branch body and following dead calls as shown.

Written by the indexing model from the issue text.

Assessment

Tech stack
wasm
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.