[lld] [WebAssembly] Generate a call to __wasm_apply_global_tls_relocs in __wasm_init_memory (PR #149832)

Sam Clegg via llvm-commits llvm-commits at lists.llvm.org
Wed Oct 8 11:31:22 PDT 2025


sbc100 wrote:

> > If this is the case, then `__wasm_init_memory` shouldn't initialize the TLS section. As it stands, `__wasm_init_memory` initalizes TLS, so a call to `__wasm_init_tls` would lead to initializing TLS twice.
> 
> What exactly is happening twice if you call `__wasm_init_tls` on the main thread today? Do you mean the `memory.init` call? Or some kind of relocation application?
> 
> > As I mentioned earlier, neither wasix-libc nor (afaik, but I'm pretty certain) wasi-libc call `__wasm_init_tls` on the main thread.
> 
> Does this mean that any program that contains TLS relocations (non-empty `__wasm_apply_tls_relocs` function) would not work? Since the main thread TLS data segement would not have these relocations applied?

For example this program:

```
#include <stdio.h>

int sym1 = 42;
int sym2 = 43;

_Thread_local int* tls_data[] = { &sym1, &sym2 };

int main() {
  printf("in mian: %p %p\n", tls_data[0], tls_data[1]);
}
```

When (compiled as `-pie` program) will need two relocations in the TLS segment.

```
$ emcc -sMAIN_MODULE=2 --profiling-funcs test.c -pthread 
```

This generates the following `__wasm_apply_tls_relocs` function:

```
000b81 func[35] <__wasm_apply_tls_relocs>:
 000b82: 41 00                      | i32.const 0
 000b84: 23 07                      | global.get 7 <__tls_base>
 000b86: 6a                         | i32.add
 000b87: 23 01                      | global.get 1 <__memory_base>
 000b89: 41 e8 25                   | i32.const 4840
 000b8c: 6a                         | i32.add
 000b8d: 36 02 00                   | i32.store 2 0
 000b90: 41 04                      | i32.const 4
 000b92: 23 07                      | global.get 7 <__tls_base>
 000b94: 6a                         | i32.add
 000b95: 23 01                      | global.get 1 <__memory_base>
 000b97: 41 ec 25                   | i32.const 4844
 000b9a: 6a                         | i32.add
 000b9b: 36 02 00                   | i32.store 2 0
 000b9e: 41 10                      | i32.const 16
 000ba0: 23 07                      | global.get 7 <__tls_base>
 000ba2: 6a                         | i32.add
 000ba3: 23 01                      | global.get 1 <__memory_base>
 000ba5: 41 c4 27                   | i32.const 5060
 000ba8: 6a                         | i32.add
 000ba9: 36 02 00                   | i32.store 2 0
 000bac: 0b                         | end
```

https://github.com/llvm/llvm-project/pull/149832


More information about the llvm-commits mailing list