# Wasm Support

**URL:** <https://forums.swift.org/t/wasm-support/16087>\
**Category:** Compiler\
**Created:** [September 11, 2018, 10:23pm UTC](https://forums.swift.org/t/wasm-support/16087 "2018-09-11T22:23:35Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![George](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/george/32/37757_2.png) [@George](https://forums.swift.org/u/George)\
**Post date:** [September 11, 2018, 10:23pm UTC](https://forums.swift.org/t/wasm-support/16087/1 "2018-09-11T22:23:35Z")

</div>

I'm not sure if this is the correct section for this, but WebAssembly support was brought up in [this thread](https://forums.swift.org/t/server-work-group-new-focus-areas/15969/29). Is there any ongoing work on this front? Is there some place we can track that work? If we wanted to pitch in, is there a good place to start?

---

<div class="post-metadata">

**Author:** ![ahti](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ahti/32/604_2.png) [@ahti](https://forums.swift.org/u/ahti)\
**Post date:** [September 12, 2018, 12:56am UTC](https://forums.swift.org/t/wasm-support/16087/2 "2018-09-12T00:56:56Z")

</div>

There has been some discussion and a little work (but no working compilation to wasm) in this GitHub issue a few months ago: [Unable to compile a simple Swift file (maybe not possible?) · Issue #2427 · emscripten-core/emscripten · GitHub](https://github.com/kripken/emscripten/issues/2427).

---

<div class="post-metadata">

**Author:** ![George](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/george/32/37757_2.png) [@George](https://forums.swift.org/u/George)\
**Post date:** [September 12, 2018, 2:26pm UTC](https://forums.swift.org/t/wasm-support/16087/3 "2018-09-12T14:26:45Z")

</div>

I have seen that issue. Do folks think using emscripten is the right path forward? I may be misremembering but I think the Rust folks started with emscripten and then rolled their own wasm target.

---

<div class="post-metadata">

**Author:** ![ahti](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ahti/32/604_2.png) [@ahti](https://forums.swift.org/u/ahti)\
**Post date:** [September 13, 2018, 8:34am UTC](https://forums.swift.org/t/wasm-support/16087/4 "2018-09-13T08:34:22Z")

</div>

I'm neither a compiler- nor wasm-expert, but at least some of the changes posted in the last few comments on the issue look like they'd be relevant either way. From the little research on wasm vs. emscripten I did just now, it looks to me like the first step would be to allow the LLVM wasm backend to work with Swift, which I think is the backend both Clang and Rust (which indeed switched from the backend coming with emscripten) use.

Even when using that, It looks to me like emscripten can still be used to generate glue code and provide shims for libc, opengl and such things (I think that's what it is at least). Rust is using their own system, [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) for at least a part of what emscripten provides, but I'm not sure whether they are still using emscripten for other functionality.

The wasm project also has at least some of the features emscripten provides on their [roadmap](https://github.com/WebAssembly/design/blob/master/FutureFeatures.md)

---

<div class="post-metadata">

**Author:** ![Max\_Desiatov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_desiatov/32/20654_2.png) [@Max\_Desiatov](https://forums.swift.org/u/Max_Desiatov)\
**Post date:** [September 21, 2018, 2:55pm UTC](https://forums.swift.org/t/wasm-support/16087/5 "2018-09-21T14:55:27Z")

</div>

While the original issue has been created in the emscripten repository, it contains the discussion of using LLVM WebAssembly backend and a few patches for the Swift toolchain for enabling that. I haven't seen any more work done on that in the Swift toolchain for the last half a year, but LLVM 7.0 had some good progress on WebAssembly target since then. I've pulled LLVM 7.0 updates and rebased the patches, which now live in these branches:

[Swift compiler support](https://github.com/maxdesiatov/swift/tree/swift-to-wasm)  
[compiler-rt with LLVM 7.0 updates](https://github.com/maxdesiatov/swift-compiler-rt/tree/wasm)  
[Swift's fork of LLVM with 7.0 updates](https://github.com/maxdesiatov/swift-llvm/tree/wasm)  
[Swift's clang fork with 7.0 updates](https://github.com/maxdesiatov/swift-clang/tree/wasm)

It looks like the main blocker is going to be the dependency on glibc. My understanding is being able to switch from glibc to musl in Swift toolchain would be super helpful, especially as there was some progress in porting musl to WebAssembly: [GitHub - jfbastien/musl: musl libc experiment](https://github.com/jfbastien/musl)

---

<div class="post-metadata">

**Author:** ![ddunbar](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ddunbar/32/1933_2.png) [@ddunbar](https://forums.swift.org/u/ddunbar)\
**Post date:** [January 4, 2019, 4:38pm UTC](https://forums.swift.org/t/wasm-support/16087/6 "2019-01-04T16:38:25Z")

</div>

FWIW, I have been a tiny bit of poking at this, primarily in the context of purely native (non-emscripten) support. Tracking status here: [[SR-9307] RFE: WebAssembly Support · Issue #51778 · apple/swift · GitHub](https://bugs.swift.org/browse/SR-9307)

---

<div class="post-metadata">

**Author:** ![shial4](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/shial4/32/2004_2.png) [@shial4](https://forums.swift.org/u/shial4)\
**Post date:** [September 22, 2019, 11:19pm UTC](https://forums.swift.org/t/wasm-support/16087/7 "2019-09-22T23:19:28Z")

</div>

Is WASM moving forward?

---

<div class="post-metadata">

**Author:** ![dlbuckley](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dlbuckley/32/14986_2.png) [@dlbuckley](https://forums.swift.org/u/dlbuckley)\
**Post date:** [September 23, 2019, 8:44am UTC](https://forums.swift.org/t/wasm-support/16087/8 "2019-09-23T08:44:56Z")

</div>

There has been progress ([https://swiftwasm.org](https://swiftwasm.org)) but I haven't seen anything in a while.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [September 23, 2019, 11:56am UTC](https://forums.swift.org/t/wasm-support/16087/9 "2019-09-23T11:56:16Z")

</div>

FWIW, I just tried and that website now works on my iPhone 6S (iOS 13). IIRC, it didn't work on iOS 12.

If we could get WASM support completed and get regular nightlies built, it would be a very cool way to try out the latest language features. The Playgrounds App on iPad is cool, but not if you want to experiment with cutting-edge stuff.

---

<div class="post-metadata">

**Author:** ![Max\_Desiatov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_desiatov/32/20654_2.png) [@Max\_Desiatov](https://forums.swift.org/u/Max_Desiatov)\
**Post date:** [February 17, 2020, 12:11pm UTC](https://forums.swift.org/t/wasm-support/16087/10 "2020-02-17T12:11:21Z")

</div>

Quick update: me and @kateinoigakukun got some good progress since last year and quite a few tests from the upstream test suite pass. A lot of effort now is put into upstreaming the changes to the main apple/swift repository, tracked here [Upstream all the changes 🙌 · Issue #187 · swiftwasm/swift · GitHub](https://github.com/swiftwasm/swift/issues/187)

Every bit of help and feedback would be very much appreciated, please have a look at our open [issues](https://github.com/swiftwasm/swift/issues) and [PRs](https://github.com/swiftwasm/swift/pulls) and let us know if anything's missing to get you started if you're interested in contributing.

We'd also appreciate any help from fellow compiler developers on a few issues here:

- What do you find works best for improving the build time on CI and locally? I personally try to use incremental builds as much as possible, but this doesn't work well a lot of the time, especially when working on the build system itself. The build time is also the main thing that makes me intensely wish Swift didn't fork LLVM and Clang and we could avoid building forked LLVM/Clang and just use upstream prebuilt versions 😔 Improving the iteration time and cold build time would allow many more people to get involved, especially those who don't have beefy multi-core hardware to get the whole infrastructure compiled from scratch.
- Who should we request a review from when upstreaming our changes? Are there any compiler contributors who'd be willing to provide review feedback for our PRs, as we had a few PRs where we couldn't get any review feedback for quite a long time? Given that making Swift available on more platforms is one of the explicit goals of Swift 6, are there any regular compiler contributors interested in upstreaming WebAssembly support?
- What's the best source of documentation on the compiler build system? I see CMake, shell scripts and Python 2 and 3 all used at the same time in the build system, but what's the best way to approach it, especially when trying to enable a new platform with support for cross-compilation?

Thanks and I'm looking forward to your feedback!

---

<div class="post-metadata">

**Author:** ![ddunbar](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ddunbar/32/1933_2.png) [@ddunbar](https://forums.swift.org/u/ddunbar)\
**Post date:** [February 17, 2020, 2:55pm UTC](https://forums.swift.org/t/wasm-support/16087/11 "2020-02-17T14:55:35Z")

</div>

Have you tried using sccache? That should help considerably when working on the build system.

---

<div class="post-metadata">

**Author:** ![Max\_Desiatov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_desiatov/32/20654_2.png) [@Max\_Desiatov](https://forums.swift.org/u/Max_Desiatov)\
**Post date:** [February 17, 2020, 3:09pm UTC](https://forums.swift.org/t/wasm-support/16087/12 "2020-02-17T15:09:13Z")

</div>

No, I haven't tried it, never heard of it actually. For future reference, I found [a section about it](https://github.com/apple/swift/blob/master/docs/DevelopmentTips.md#use-sccache-to-cache-build-artifacts) just now in the `docs` directory after seeing you mentioning it.

Which leads me to another question, are these compiler docs hosted anywhere in a rendered form other than GitHub? Rust has its own [Rustc book](https://doc.rust-lang.org/rustc/what-is-rustc.html), which is nicely formatted and supports search, shouldn't we have something similar for Swift so that it's much easier to onboard new contributors to the Swift compiler?

---

<div class="post-metadata">

**Author:** ![typesanitizer](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/typesanitizer/32/8661_2.png) [@typesanitizer](https://forums.swift.org/u/typesanitizer)\
**Post date:** [February 18, 2020, 2:47am UTC](https://forums.swift.org/t/wasm-support/16087/13 "2020-02-18T02:47:00Z")

</div>

> No, I haven't tried it, never heard of it actually. For future reference, I found [a section about it](https://github.com/apple/swift/blob/master/docs/DevelopmentTips.md#use-sccache-to-cache-build-artifacts) just now in the `docs` directory after seeing you mentioning it.

Hmm, we should probably add a link to this in the Readme.

> Which leads me to another question, are these compiler docs hosted anywhere in a rendered form other than GitHub?

No 🙁. Earlier, there used to be hosted Doxygen pages for the source code but we don't have that anymore [last time I tried building them a few months back, I ran into sphinx issues and I gave up after a few hours]. I would love to get that set up when I have some spare time. If someone wants to poke around and needs PR review, I can help there.

> Rust has its own [Rustc book](https://doc.rust-lang.org/rustc/what-is-rustc.html), which is nicely formatted and supports search, shouldn't we have something similar for Swift so that it's much easier to onboard new contributors to the Swift compiler?

A big challenge with comprehensive documentation like that is that it needs to be maintained, much like anything else. Unlike the code, we don't have a compiler that reminds us to update "call-sites", so that needs to be done by hand. For example, I started doing this using named notes, right now there is exactly one of these `[Note: ModuleInterfaceLoader-defer-to-SerializedModuleLoader]` 😐. (this is inspired by the [notes in GHC](https://www.aosabook.org/en/ghc.html))

Plus documenting the internals means that it needs to be changed frequently, compared to the surface language which doesn't change so often. This is reflected in several other documents in `docs/` which are out-of-date at the moment. I agree that having something like that would be extremely valuable for newcomers. IMO we need to take small steps first. That would involve updating the existing documentation, removing what is inapplicable and incorporate external sources about compiler internals, such as blog posts and talks from LLVM Dev.

---

<div class="post-metadata">

**Author:** ![kateinoigakukun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kateinoigakukun/32/16706_2.png) [@kateinoigakukun](https://forums.swift.org/u/kateinoigakukun)\
**Post date:** [February 18, 2020, 2:06pm UTC](https://forums.swift.org/t/wasm-support/16087/14 "2020-02-18T14:06:10Z")

</div>

# Design clarification

Now swiftwasm project succeeds to pass quite a few test suite, so we are planning to send some patches to upstream as Max said.

Before sending them, I want to confirm and clarify the direction of supporting WebAssembly.

## Implementation design of stdlib

There are some topics to discuss for the implementation of stdlib for WebAssembly.

### ICU

I know there is some discussion about implementing a subset of stdlib without ICU. But I want to use ICU to support WebAssembly incrementally. I’ve sent some patches to ICU project to build it for WebAssembly.

- [ICU-20978 Reduce unnecessary building for tools when cross-building by kateinoigakukun · Pull Request #990 · unicode-org/icu · GitHub](https://github.com/unicode-org/icu/pull/990)
- [ICU-20977 Minimal support for WebAssembly in double-conversion-utils.h by kateinoigakukun · Pull Request #989 · unicode-org/icu · GitHub](https://github.com/unicode-org/icu/pull/989)

After these patches applied, it'll get to be able to built for WebAssembly and integrated with Swift stdlib. Actually, I prepared a patched prebuilt ICU library and it works well on WebAssembly with Swift.

### wasi-libc

Swift stdlib depends on libc but libc can’t be built for WebAssembly because pure WebAssembly doesn't have a system call interface.

wasi-libc is a bytecode alliance project which enables us to build a libc compatible library depending on WASI. As same as I want to use ICU to achieve incremental support, I want to depend on WASI to use wasi-libc also.

We need to provide some polyfills for some missing features like pthread, but swiftwasm project has already implemented them and it works well.

Basically we are focusing to run Swift executable files correctly on WebAssembly runtime, so we want to depend on ICU and WASI to support WebAssembly progressively. I also consider supporting WASI independent target in the future, but for that kind of target, we have to implement a subset of stdlib.

In addition, we want to package wasi-libc and ICU libraries in Swift toolchain of WASM. If a general SDK like wasi-sdk becomes popular in the future, we may use it. But at present, it’s difficult to install wasi-sdk, and unlike the general sysroot, the path to be installed is not fixed. For this reason, we think it is appropriate to distribute them as part of the Swift toolchain at this time.

## Implementation design of runtime

As zhuowei said in [https://github.com/apple/swift/pull/24684](https://github.com/apple/swift/pull/24684), some of Swift runtime features can’t work on WebAssembly.

### Relative Pointer

Relative Pointer does not work on WASM. See the PR [#24684](https://github.com/apple/swift/pull/24684) description for details.

The swiftwasm project has temporarily applied a hacky patch as a solution to this issue. However, the use cases of Relative Pointer have been almost completely identified, and related features also work well.

When merging to the upstream, we plan to implement some kind of abstract pointer type instead of using the RelativePointer type directly. I think that this design should be discussed with the core team more.

### swifterror, swiftself

swifterror and swiftself don’t work on WASM also. See the PR #24684 description for details.

I have tried to solve this in several ways.

A conversion from non-throws to throws function and a conversion from thin function to thick function is the root cause of this issue.

First, I tried to emit the thunk function at the SIL level. ABI compatibility between function types is checked in the process of converting a typed AST to SIL. For example, conversion from `() -> Int` type to `() -> Optional<Int>` type requires thunk, but conversion from `()-> Void` type to `() throws -> Void` type doesn’t require thunk.

This patch [https://github.com/swiftwasm/swift/pull/6](https://github.com/swiftwasm/swift/pull/6) enables many cases of function calls to work on WASM. However, there was one problem with this solution.

Thunk functions were created at the SIL level, but in some cases, the functions were rewritten as `thin_to_thick_function` instructions by optimization. e.g. CapturePropagation rewrites `partial_apply` to a `thin_to_thick_function` function. As described above, `thin_to_thick_function` instruction outputs function call without thunk and it's an invalid instruction as WASM.

So I implemented IRGen as thin\_to\_thick\_function emits valid LLVM IR for WASM. This change transforms `thin_to_thick_function` into function call using LLVM IR level thunk like `partial_apply`. Here is the patch PR. [[WASM] Implement thin-to-thick semantic for WebAssembly by kateinoigakukun · Pull Request #186 · swiftwasm/swift · GitHub](https://github.com/swiftwasm/swift/pull/186)

These changes make output executable files no longer cause WASM runtime errors in function calls.

## Trivial issues

WebAssembly doesn't support multi-thread yet, so we run the test suite in a single thread. This makes it difficult to run some test suite that expects to be crashed. Should we ignore these kinds of suite temporarily using ifdef? or is there a better way?

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [February 18, 2020, 7:49pm UTC](https://forums.swift.org/t/wasm-support/16087/15 "2020-02-18T19:49:15Z")

</div>

Great work!

> [@kateinoigakukun](#):
>
> ### Relative Pointer
> 
> Relative Pointer does not work on WASM. See the PR [#24684](https://github.com/apple/swift/pull/24684) description for details.
> 
> The swiftwasm project has temporarily applied a hacky patch as a solution to this issue. However, the use cases of Relative Pointer have been almost completely identified, and related features also work well.
> 
> When merging to the upstream, we plan to implement some kind of abstract pointer type instead of using the RelativePointer type directly. I think that this design should be discussed with the core team more.

Is this because of a fundamental limitation of the wasm format, or because of missing support in LLVM? The goals of RelativePointer are to (a) reduce metadata size on 64-bit platforms, because it's always 32-bit, and (b) reduce load time overhead by representing references to symbols in the same binary in a way that can be directly encoded in the on-disk image format. Does wasm have an alternative way to achieve this, maybe by using an index into the current object's symbol table, or an address relative to the start of the object file rather than to the PC?

> [@kateinoigakukun](#):
>
> ### swifterror, swiftself
> 
> swifterror and swiftself don’t work on WASM also. See the PR #24684 description for details.
> 
> I have tried to solve this in several ways.

Would it be possible to make it so that `swiftcc` functions in LLVM are always lowered with an extra argument and return for the `swifterror` argument, regardless of whether they have one or not, so that they still do not need a thunk?

> [@kateinoigakukun](#):
>
> ## Trivial issues
> 
> WebAssembly doesn't support multi-thread yet, so we run the test suite in a single thread. This makes it difficult to run some test suite that expects to be crashed. Should we ignore these kinds of suite temporarily using ifdef? or is there a better way?

It seems reasonable to expect that a future version of wasm may include some amount of multithreading and atomics support, so "polyfilling" in stub support for pthreads, atomics, and such that really run on a single thread seems like a good approach. Is it practical to provide something that looks enough like multiple kernel threads to fool the tests? If not, disabling them should be fine.

---

<div class="post-metadata">

**Author:** ![kateinoigakukun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kateinoigakukun/32/16706_2.png) [@kateinoigakukun](https://forums.swift.org/u/kateinoigakukun)\
**Post date:** [February 19, 2020, 5:36am UTC](https://forums.swift.org/t/wasm-support/16087/16 "2020-02-19T05:36:04Z")

</div>

> [@Joe\_Groff](#):
>
> Is this because of a fundamental limitation of the wasm format, or because of missing support in LLVM?

It's due to the design of WebAssembly and LLVM support.  
If LLVM supports substruction relocation type on WebAssembly like `R_X86_64_PC32` or `X86_64_RELOC_SUBTRACTOR`, this issue can be solved easily.

But LLVM doesn't support this relocation type because of the design of WebAssembly.

First, `R_X86_64_PC32` and `X86_64_RELOC_SUBTRACTOR` are mainly used to generate PIC but WebAssembly doesn't require PIC because it doesn't support dynamic linking. In addition, the memory space also begins at 0, so it's unnecessary to relocate at load time. All absolute addresses can be embedded in wasm binary file directly.

WebAssembly natively achieves the motivation of Relative Pointer without Relative Pointer.

> [@Joe\_Groff](#):
>
> (a) reduce metadata size on 64-bit platforms, because it's always 32-bit

Now we target only wasm32, not including wasm64 because there is no fixed spec for wasm64 and no runtime supporting 64bit.  
IMHO we should discuss about wasm32 and wasm64 separately and it's no use discussing non-existing architecture.

> [@Joe\_Groff](#):
>
> (b) reduce load time overhead by representing references to symbols in the same binary in a way that can be directly encoded in the on-disk image format.

As I said above, WebAssembly doesn't need to relocate at load time, so wasm binary format can contain absolute address directly.  
And relative pointer has time overhead on dereferencing to calculate real absolute address. On the other hand, if absolute pointers are embedded in binary file directly, there is no overhead at both load time and accessing time.

For these reasons, WebAssembly natively achieves the motivation of Relative Pointer and has a superior runtime performance without Relative Pointer.

> [@Joe\_Groff](#):
>
> Would it be possible to make it so that `swiftcc` functions in LLVM are always lowered with an extra argument and return for the `swifterror` argument, regardless of whether they have one or not, so that they still do not need a thunk?

I've tried this way also, but it was quite hard to switch the number of arguments for all functions. Here is the WIP patch for this way [Comparing apple:9466d120ce1b1d79543864938b28bb500f8af4c8...kateinoigakukun:katei/swifterror · apple/swift · GitHub](https://github.com/apple/swift/compare/9466d120ce1b1d79543864938b28bb500f8af4c8...kateinoigakukun:katei/swifterror) .  
I spent quite a few weeks to solve this issue in this way, but I couldn't list up all function emission code because there is no common helper to emit function in IRGen. (maybe I overlooked)

And I know there is runtime overhead when using thunk, but I don't know that which is more expensive, thunk function or extra argument. What do you think about this?

**Update: 2020/02/19 15:21 JST**

I think adding extra arguments to all functions costs more than using thunk because the former way has dispatch overheads for every function call and the latter has overhead only when type conversion needed.

> [@Joe\_Groff](#):
>
> Is it practical to provide something that looks enough like multiple kernel threads to fool the tests?

No, there isn't.

IMO it's impossible even if there are user level multiple threads because WASI doesn't support signal yet. If we can hook abortion, it may work well.

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [February 19, 2020, 5:24pm UTC](https://forums.swift.org/t/wasm-support/16087/17 "2020-02-19T17:24:05Z")

</div>

Thanks for the replies Yuta!

> [@kateinoigakukun](#):
>
> As I said above, WebAssembly doesn't need to relocate at load time, so wasm binary format can contain absolute address directly.  
> And relative pointer has time overhead on dereferencing to calculate real absolute address. On the other hand, if absolute pointers are embedded in binary file directly, there is no overhead at both load time and accessing time.
> 
> For these reasons, WebAssembly natively achieves the motivation of Relative Pointer and has a superior runtime performance without Relative Pointer.

That sounds great, then I agree using an absolute pointer in place of relative is the way to go. However, does WASM support loading and linking multiple wasm files on the client side? How does symbol resolution work in that case? If there's the equivalent of an import table or GOT, it might still be interesting to have something like `RelativeIndirectablePointer`, but with an absolute address, to still be able to avoid up-front load time costs for cold metadata structures.

> [@kateinoigakukun](#):
>
> I've tried this way also, but it was quite hard to switch the number of arguments for all functions. Here is the WIP patch for this way [https://github.com/apple/swift/compare/9466d120ce1b1d79543864938b28bb500f8af4c8...kateinoigakukun:katei/swifterror](https://github.com/apple/swift/compare/9466d120ce1b1d79543864938b28bb500f8af4c8...kateinoigakukun:katei/swifterror) .  
> I spent quite a few weeks to solve this issue in this way, but I couldn't list up all function emission code because there is no common helper to emit function in IRGen. (maybe I overlooked)
> 
> And I know there is runtime overhead when using thunk, but I don't know that which is more expensive, thunk function or extra argument. What do you think about this?
> 
> **Update: 2020/02/19 15:21 JST**
> 
> I think adding extra arguments to all functions costs more than using thunk because the former way has dispatch overheads for every function call and the latter has overhead only when type conversion needed.

I wouldn't expect an extra added argument and return to have that much overhead, and it seems like it'd be a reasonably tractable peephole optimization for WASM code generators to elide the argument materialization if it were passed an undef value. I would be concerned that, even if you patch up the compiler to thunk instead of assuming the ABIs match up, we still assume that nonthrowing functions are ABI-compatible with throwing functions fairly pervasively through the runtime, and that existing Swift code in the wild may also be relying on that assumption.

If it helps, it's also worth noting that the value in the memory pointed to by the `swifterror` argument is generally not significant in the calling convention, only the value at the time the function returns. You could probably avoid materializing an argument altogether and just treat it as undefined on function entry and only materialize an extra return. Another possibility might be, if WASM has a native encoding for alternative returns to represent exception handling, to utilize that to represent error returns and throws instead.

> [@kateinoigakukun](#):
>
> No, there isn't.
> 
> IMO it's impossible even if there are user level multiple threads because WASI doesn't support signal yet. If we can hook abortion, it may work well.

In that case, I would simply disable the tests for now.

---

<div class="post-metadata">

**Author:** ![kateinoigakukun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kateinoigakukun/32/16706_2.png) [@kateinoigakukun](https://forums.swift.org/u/kateinoigakukun)\
**Post date:** [February 20, 2020, 11:12am UTC](https://forums.swift.org/t/wasm-support/16087/18 "2020-02-20T11:12:26Z")

</div>

@Joe_Groff

> [@Joe\_Groff](#):
>
> That sounds great, then I agree using an absolute pointer in place of relative is the way to go. However, does WASM support loading and linking multiple wasm files on the client side? How does symbol resolution work in that case? If there's the equivalent of an import table or GOT, it might still be interesting to have something like `RelativeIndirectablePointer` , but with an absolute address, to still be able to avoid up-front load time costs for cold metadata structures

Thanks! :)

WebAssembly MVP doesn't support loading multiple wasm files now and there is no stable ABI for dynamic linking. And also doesn't provide GOT or something related to PIC.  
However, LLVM generates virtual static GOT on wasm memory space if the frontend compiler emits IR as PIC. Now, swiftc emits IR as PIC even for wasm, so we have to use something like AbsoluteIndirectPointer to reference through static GOT.

~~As you said, there is some potential for performance improvement if swiftc emits IR as non-PIC using direct absolute pointer.~~

* * *

### Update 2020/02/20 21:38 JST

(I misunderstood what you said, sorry)

> If there's the equivalent of an import table or GOT, it might still be interesting to have something like `RelativeIndirectablePointer` , but with an absolute address, to still be able to avoid up-front load time costs for cold metadata structures

Do you mean we should use `RelativeIndirectablePointer` instead of absolute pointer if there is GOT on WASM?

* * *

> [@Joe\_Groff](#):
>
> I wouldn't expect an extra added argument and return to have that much overhead, and it seems like it'd be a reasonably tractable peephole optimization for WASM code generators to elide the argument materialization if it were passed an undef value. I would be concerned that, even if you patch up the compiler to thunk instead of assuming the ABIs match up, we still assume that nonthrowing functions are ABI-compatible with throwing functions fairly pervasively through the runtime, and that existing Swift code in the wild may also be relying on that assumption.

I see, I basically agree with you at this point. I’ll try this way!

BTW what module should be patched, IRGen or IR lowering module in LLVM? As I said above post, it was quite hard to patch IRGen because I had to modify many places. Do you have any rough plans for this way?

---

<div class="post-metadata">

**Author:** ![Joe\_Groff](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/joe_groff/32/1929_2.png) [@Joe\_Groff](https://forums.swift.org/u/Joe_Groff)\
**Post date:** [February 20, 2020, 3:33pm UTC](https://forums.swift.org/t/wasm-support/16087/19 "2020-02-20T15:33:56Z")

</div>

> [@kateinoigakukun](#):
>
> WebAssembly MVP doesn't support loading multiple wasm files now and there is no stable ABI for dynamic linking. And also doesn't provide GOT or something related to PIC.  
> However, LLVM generates virtual static GOT on wasm memory space if the frontend compiler emits IR as PIC. Now, swiftc emits IR as PIC even for wasm, so we have to use something like AbsoluteIndirectPointer to reference through static GOT.
> 
> ~~As you said, there is some potential for performance improvement if swiftc emits IR as non-PIC using direct absolute pointer.~~
> 
> ### Update 2020/02/20 21:38 JST
> 
> (I misunderstood what you said, sorry)
> 
> > If there's the equivalent of an import table or GOT, it might still be interesting to have something like `RelativeIndirectablePointer` , but with an absolute address, to still be able to avoid up-front load time costs for cold metadata structures
> 
> Do you mean we should use `RelativeIndirectablePointer` instead of absolute pointer if there is GOT on WASM?

Well, if all wasm code is eventually linked into one object file for deployment, then there shouldn't ever strictly be a need for a GOT (though Swift or LLVM may end up incidentally generating entries because it assumes a symbol might come from a dynamic library in many cases). You might be able to fend off these unnecessary GOT entries in the short term by marking all symbols as `dsolocal` in the generated LLVM IR, and changing the logic in Swift IRGen's `getAddrOfLLVMVariableOrGOTEquivalent` to always generate direct references when targeting WASM.

If WASM in the future does end up having a dynamic linking story, then we would still probably want to keep the places where we use `RelativeIndirectablePointer` as true-const to minimize startup time, but maybe we can avoid solving that problem until the future. A future WASM with dynamic linking support might end up growing full support for PIC too, you never know.

> [@kateinoigakukun](#):
>
> I see, I basically agree with you at this point. I’ll try this way!
> 
> BTW what module should be patched, IRGen or IR lowering module in LLVM? As I said above post, it was quite hard to patch IRGen because I had to modify many places. Do you have any rough plans for this way?

To me, it seems more natural to change the LLVM calling convention lowering for `swiftcc` functions.

---

<div class="post-metadata">

**Author:** ![kateinoigakukun](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kateinoigakukun/32/16706_2.png) [@kateinoigakukun](https://forums.swift.org/u/kateinoigakukun)\
**Post date:** [February 21, 2020, 1:57am UTC](https://forums.swift.org/t/wasm-support/16087/20 "2020-02-21T01:57:57Z")

</div>

@Joe_Groff

> [@Joe\_Groff](#):
>
> You might be able to fend off these unnecessary GOT entries in the short term by marking all symbols as `dsolocal` in the generated LLVM IR, and changing the logic in Swift IRGen's `getAddrOfLLVMVariableOrGOTEquivalent` to always generate direct references when targeting WASM.

Thanks for your detailed description! I'll try to eliminate GOT related global variables.  
[I simply changed the linkage flag](https://github.com/swiftwasm/swift/pull/211/commits/c4f86601f68736a0554702b292f7b1cccf7cdf42) and it seems produced object files are linked well :)

> [@Joe\_Groff](#):
>
> To me, it seems more natural to change the LLVM calling convention lowering for `swiftcc` functions.

OK, I'll take a look around `SwiftCallingConv.cpp`. Thanks!

BTW do you know who is a right person to review around build-script? I offered @compnerd to review [bootstrapping PR](https://github.com/apple/swift/pull/29465), but it seems he is too busy to take a look.

[Next page](https://forums.swift.org/t/wasm-support/16087.md?page=2)
