emscripten-core / emscripten-core/emscripten
__thread var not respecting initialization when compiled with -O3
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
Please include the following in your bug report:
**Version of emscripten/emsdk:**
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.0.0 (3fd52e107187b8a169bb04a02b9f982c8a075205)
**Failing command line in full:**
Compilation succeeds, but __thread var is not initialized
**Full link command and output with `-v` appended:**
I'm compiling several .o files before the final executable. Depending on how one of those .o files is compiled, the executable will or won't crash.
.o compilation that fails:
```
emcc -fPIC -O3 -fno-unsafe-math-optimizations -flto [... other -W and -I options ...] -c code_with_thread_volatile_var.c -o code_with_thread_volatile_var.o
```
.o compilation that succeeds:
```
emcc -fPIC -O0 -fno-unsafe-math-optimizations -flto [... other -W and -I options ...] -c code_with_thread_volatile_var.c -o code_with_thread_volatile_var.o
```
exe compilation (no change between success vs fail cases):
```
emcc -s EXPORTED_FUNCTIONS="['_free','_malloc' ]" -s EXPORTED_RUNTIME_METHODS="['setValue']" -s RESERVED_FUNCTION_POINTERS=4 -s ALLOW_MEMORY_GROWTH=1 -fPIC -O3 -DNDEBUG=1 -fno-unsafe-math-optimizations -mavx2 -flto -W... -I... -o /path/to/out.em.js [... various .o files including the one in question ...] -s FORCE_FILESYSTEM=1 -lidbfs.js
```
The following code change fixes this issue. Debugging the issue, it appears that without the below change, `v2` is not initialized to zero:
```
#if defined(__EMSCRIPTEN__) // added this to fix the issue
int64_t v2 = 0;
#else
__thread volatile int64_t v2 = 0; /* the issue seems to exist with or without the `volatile` keyword */
#endif
```
Admittedly there is some inconsistency in the fact that the code presumes a threaded environment where the exe compilation command does not include pthread or related options, but shouldn't the code still initialize properly nonetheless?
Contributor guide
Assessment
This issue has not been assessed yet.