wasm-opt: global varaible is not optimized
The code example:
#include <stdint.h>
#include <stdio.h>
int32_t a;
static int32_t g;
int16_t b() { a = 0; g = 0; }
void foo(int32_t a, char str[]){
if (!a)
printf(str, a);
}
void main() {
printf("hello\n");
int c = b();
foo(a, "a: 0x%x\n");
}
Version of wasm-opt:
wasm-opt version 109 (version_109-8-gbab21052c)
wasm-opt option:
wasm-opt --post-emscripten -O3 --low-memory-unused --zero-filled-memory --strip-producers -g --mvp-features --converge --inlining-optimizing --local-cse --code-folding --licm --rse --precompute-propagate --optimize-added-constants-propagate
Problem Description:
I try to compile the above code with emcc -O0 -g and then optimize the generated wasm code with wasm-opt, and I expect the global variable g will be optimized as it is not used anywhere. However, wasm-opt seems to fail to remove the assignment to g. Not sure if this is a feature of wasm optimizer or an under-optimization problem.
The global g will be turned into an address in memory. Binaryen can't be sure it isn't read with a non-constant load (a load with a pointer that is an unknown value).
LLVM can do this because it tracks globals separately, and due to undefined behavior can assume nothing else can read them.
If LLVM lowered the global into a wasm global, we could optimize this, but LLVM doesn't do that (it wouldn't work if the global had its address taken, for example).