From ec264a81b95279061455c2e636f8c4e577b89762 Mon Sep 17 00:00:00 2001 From: Max Desiatov Date: Sat, 9 May 2020 16:18:46 +0100 Subject: [PATCH] Implement SWIFT_ONCE_F for WebAssembly/WASI --- include/swift/Basic/Lazy.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/include/swift/Basic/Lazy.h b/include/swift/Basic/Lazy.h index 6c899abeeffd6..521227f4db231 100644 --- a/include/swift/Basic/Lazy.h +++ b/include/swift/Basic/Lazy.h @@ -24,6 +24,24 @@ #include "swift/Basic/Malloc.h" #include "swift/Basic/type_traits.h" +#if defined(__wasi__) +// Temporary single-threaded stub. Should be replaced with a thread-safe version +// as soon as the WASI SDK allows it. See https://bugs.swift.org/browse/SR-12766. +inline void wasi_call_once(int *flag, void *context, void (*func)(void *)) { + switch (*flag) { + case 0: + *flag = 1; + func(context); + return; + case 1: + return; + default: + assert(false && "wasi_call_once got invalid flag"); + abort(); + } +} +#endif + namespace swift { #ifdef __APPLE__ @@ -38,6 +56,10 @@ namespace swift { using OnceToken_t = unsigned long; # define SWIFT_ONCE_F(TOKEN, FUNC, CONTEXT) \ _swift_once_f(&TOKEN, CONTEXT, FUNC) +#elif defined(__wasi__) + using OnceToken_t = int; +# define SWIFT_ONCE_F(TOKEN, FUNC, CONTEXT) \ + ::wasi_call_once(&TOKEN, CONTEXT, FUNC) #else using OnceToken_t = std::once_flag; # define SWIFT_ONCE_F(TOKEN, FUNC, CONTEXT) \