<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/108770>108770</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            clang emits invalid wasm code when compiling C
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            clang
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          TerrorJack
      </td>
    </tr>
</table>

<pre>
    Minimal repro:

```c
extern int a;
void* b();
void c(void *);
void f() {
  void *d = b();
e:
  switch (a)
  case 0: {
 b();
    c(d);
    c((void *)*(int *)(d + -sizeof(int)));
    d = d - sizeof(int);
    goto e;
  }
}
```

The above code, when compiled with `--target=wasm32 -O1` using latest `clang` on `main`, will produce the following **invalid** assembly code:

```asm
f: # @f
        .functype       f () -> ()
 .local          i32
# %bb.0:
        call    b
        local.set 0
        block
        i32.const       0
        i32.load a
        br_if           0                               # 0: down to label0
# %bb.1:
        local.get       0
        local.set 0
.LBB0_2:                                # =>This Inner Loop Header: Depth=1
        loop                                            # label1:
        call    b
        drop
        local.get       0
 local.tee       0
        call    c
        local.get 0
        i32.load        -4
        call    c
        local.get 0
        i32.const       -4
        i32.add
        local.set 0
        i32.const       0
        i32.load        a
 i32.eqz
        br_if           0                               # 0: up to label1
.LBB0_3:
        end_loop
        end_block # label0:
                                        # fallthrough-return
        end_function
```

Note the `i32.const -4` line. This is invalid per wasm spec, the memarg offset/align must all be non-negative u32 literals. And indeed this code will trigger a memory trap at runtime!

I bisected this bug on `master` and the first bad commit is https://github.com/llvm/llvm-project/commit/7eca38ce76d5d1915f4ab7e665964062c0b37697. cc @hazzlim 
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJysVlGT2yYQ_jX4ZccaBLZkP-jhLs5N00nbl7xnEKwkGgQqoHPvfn0HST777FxynZbx2GIXvt2P_bRYhKBbi1iR7T3ZHlZijJ3z1Rf03vlf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