emscripten-core / emscripten-core/emscripten
Emscripten/LLVM and Binaryen TrapsNeverHappens
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
In TrapsNeverHappen mode in Binaryen we optimize assuming the program never actually hits a trap. So if we see this:
```js
if (foo) {
sideEffect();
trap;
}
```
Then we can optimize that if away - we assume that path is never taken. This is fairly useful in the wasm GC world as it allows various optimizations to work better, but it can help linear memory too, e.g. it allows removing
```wat
(drop
(i32.load ..)
)
```
Normally we can't remove that.
Testing TNH mode on emscripten today, a problem happens due to noreturn functions. For example in `test_pthread_create` the `ThreadMain` function ends with `pthread_exit`. It looks like LLVM emits an unreachable after such a noreturn function. The problem is that TNH assumes we never reach that, which means that all the body of `ThreadMain` will be optimized out (like `sideEffect()` in the example above).
Perhaps 2 ways to fix this would be:
1. Make LLVM stop emitting an unreachable after each noreturn call. I'm not sure why it does, but I'd guess it's that noreturn functions can be used in ways that require them to not actually return in order to validate?
2. Make Binaryen somehow understand that `pthread_exit` is noreturn. If it knew that then it would realize the unreachable is not actually reached. I'm not sure how to do that, though - LLVM would need to annotate the function somehow, perhaps? Ideally a new instruction would make sense here, but that seems heavyweight.
Contributor guide
Assessment
This issue has not been assessed yet.