1//=== WebAssemblyLowerEmscriptenEHSjLj.cpp - Lower exceptions for Emscripten =//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file lowers exception-related instructions and setjmp/longjmp function
11/// calls to use Emscripten's library functions. The pass uses JavaScript's try
12/// and catch mechanism in case of Emscripten EH/SjLj and Wasm EH intrinsics in
13/// case of Emscripten SjLJ.
14///
15/// * Emscripten exception handling
16/// This pass lowers invokes and landingpads into library functions in JS glue
17/// code. Invokes are lowered into function wrappers called invoke wrappers that
18/// exist in JS side, which wraps the original function call with JS try-catch.
19/// If an exception occurred, cxa_throw() function in JS side sets some
20/// variables (see below) so we can check whether an exception occurred from
21/// wasm code and handle it appropriately.
22///
23/// * Emscripten setjmp-longjmp handling
24/// This pass lowers setjmp to a reasonably-performant approach for emscripten.
25/// The idea is that each block with a setjmp is broken up into two parts: the
26/// part containing setjmp and the part right after the setjmp. The latter part
27/// is either reached from the setjmp, or later from a longjmp. To handle the
28/// longjmp, all calls that might longjmp are also called using invoke wrappers
29/// and thus JS / try-catch. JS longjmp() function also sets some variables so
30/// we can check / whether a longjmp occurred from wasm code. Each block with a
31/// function call that might longjmp is also split up after the longjmp call.
32/// After the longjmp call, we check whether a longjmp occurred, and if it did,
33/// which setjmp it corresponds to, and jump to the right post-setjmp block.
34/// We assume setjmp-longjmp handling always run after EH handling, which means
35/// we don't expect any exception-related instructions when SjLj runs.
36/// FIXME Currently this scheme does not support indirect call of setjmp,
37/// because of the limitation of the scheme itself. fastcomp does not support it
38/// either.
39///
40/// In detail, this pass does following things:
41///
42/// 1) Assumes the existence of global variables: __THREW__, __threwValue
43/// __THREW__ and __threwValue are defined in compiler-rt in Emscripten.
44/// These variables are used for both exceptions and setjmp/longjmps.
45/// __THREW__ indicates whether an exception or a longjmp occurred or not. 0
46/// means nothing occurred, 1 means an exception occurred, and other numbers
47/// mean a longjmp occurred. In the case of longjmp, __THREW__ variable
48/// indicates the corresponding setjmp buffer the longjmp corresponds to.
49/// __threwValue is 0 for exceptions, and the argument to longjmp in case of
50/// longjmp.
51///
52/// * Emscripten exception handling
53///
54/// 2) We assume the existence of setThrew and setTempRet0/getTempRet0 functions
55/// at link time. setThrew exists in Emscripten's compiler-rt:
56///
57/// void setThrew(uintptr_t threw, int value) {
58/// if (__THREW__ == 0) {
59/// __THREW__ = threw;
60/// __threwValue = value;
61/// }
62/// }
63//
64/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
65/// In exception handling, getTempRet0 indicates the type of an exception
66/// caught, and in setjmp/longjmp, it means the second argument to longjmp
67/// function.
68///
69/// 3) Lower
70/// invoke @func(arg1, arg2) to label %invoke.cont unwind label %lpad
71/// into
72/// __THREW__ = 0;
73/// call @__invoke_SIG(func, arg1, arg2)
74/// %__THREW__.val = __THREW__;
75/// __THREW__ = 0;
76/// if (%__THREW__.val == 1)
77/// goto %lpad
78/// else
79/// goto %invoke.cont
80/// SIG is a mangled string generated based on the LLVM IR-level function
81/// signature. After LLVM IR types are lowered to the target wasm types,
82/// the names for these wrappers will change based on wasm types as well,
83/// as in invoke_vi (function takes an int and returns void). The bodies of
84/// these wrappers will be generated in JS glue code, and inside those
85/// wrappers we use JS try-catch to generate actual exception effects. It
86/// also calls the original callee function. An example wrapper in JS code
87/// would look like this:
88/// function invoke_vi(index,a1) {
89/// try {
90/// Module["dynCall_vi"](index,a1); // This calls original callee
91/// } catch(e) {
92/// if (typeof e !== 'number' && e !== 'longjmp') throw e;
93/// _setThrew(1, 0); // setThrew is called here
94/// }
95/// }
96/// If an exception is thrown, __THREW__ will be set to true in a wrapper,
97/// so we can jump to the right BB based on this value.
98///
99/// 4) Lower
100/// %val = landingpad catch c1 catch c2 catch c3 ...
101/// ... use %val ...
102/// into
103/// %fmc = call @__cxa_find_matching_catch_N(c1, c2, c3, ...)
104/// %val = {%fmc, getTempRet0()}
105/// ... use %val ...
106/// Here N is a number calculated based on the number of clauses.
107/// setTempRet0 is called from __cxa_find_matching_catch() in JS glue code.
108///
109/// 5) Lower
110/// resume {%a, %b}
111/// into
112/// call @__resumeException(%a)
113/// where __resumeException() is a function in JS glue code.
114///
115/// 6) Lower
116/// call @llvm.eh.typeid.for(type) (intrinsic)
117/// into
118/// call @llvm_eh_typeid_for(type)
119/// llvm_eh_typeid_for function will be generated in JS glue code.
120///
121/// * Emscripten setjmp / longjmp handling
122///
123/// If there are calls to longjmp()
124///
125/// 1) Lower
126/// longjmp(env, val)
127/// into
128/// emscripten_longjmp(env, val)
129///
130/// If there are calls to setjmp()
131///
132/// 2) In the function entry that calls setjmp, initialize
133/// functionInvocationId as follows:
134///
135/// functionInvocationId = alloca(4)
136///
137/// Note: the alloca size is not important as this pointer is
138/// merely used for pointer comparisions.
139///
140/// 3) Lower
141/// setjmp(env)
142/// into
143/// __wasm_setjmp(env, label, functionInvocationId)
144///
145/// __wasm_setjmp records the necessary info (the label and
146/// functionInvocationId) to the "env".
147/// A BB with setjmp is split into two after setjmp call in order to
148/// make the post-setjmp BB the possible destination of longjmp BB.
149///
150/// 4) Lower every call that might longjmp into
151/// __THREW__ = 0;
152/// call @__invoke_SIG(func, arg1, arg2)
153/// %__THREW__.val = __THREW__;
154/// __THREW__ = 0;
155/// %__threwValue.val = __threwValue;
156/// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
157/// %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
158/// if (%label == 0)
159/// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
160/// setTempRet0(%__threwValue.val);
161/// } else {
162/// %label = -1;
163/// }
164/// longjmp_result = getTempRet0();
165/// switch %label {
166/// label 1: goto post-setjmp BB 1
167/// label 2: goto post-setjmp BB 2
168/// ...
169/// default: goto splitted next BB
170/// }
171///
172/// __wasm_setjmp_test examines the jmp buf to see if it was for a matching
173/// setjmp call. After calling an invoke wrapper, if a longjmp occurred,
174/// __THREW__ will be the address of matching jmp_buf buffer and
175/// __threwValue be the second argument to longjmp.
176/// __wasm_setjmp_test returns a setjmp label, a unique ID to each setjmp
177/// callsite. Label 0 means this longjmp buffer does not correspond to one
178/// of the setjmp callsites in this function, so in this case we just chain
179/// the longjmp to the caller. Label -1 means no longjmp occurred.
180/// Otherwise we jump to the right post-setjmp BB based on the label.
181///
182/// * Wasm setjmp / longjmp handling
183/// This mode still uses some Emscripten library functions but not JavaScript's
184/// try-catch mechanism. It instead uses Wasm exception handling intrinsics,
185/// which will be lowered to exception handling instructions.
186///
187/// If there are calls to longjmp()
188///
189/// 1) Lower
190/// longjmp(env, val)
191/// into
192/// __wasm_longjmp(env, val)
193///
194/// If there are calls to setjmp()
195///
196/// 2) and 3): The same as 2) and 3) in Emscripten SjLj.
197/// (functionInvocationId initialization + setjmp callsite transformation)
198///
199/// 4) Create a catchpad with a wasm.catch() intrinsic, which returns the value
200/// thrown by __wasm_longjmp function. In the runtime library, we have an
201/// equivalent of the following struct:
202///
203/// struct __WasmLongjmpArgs {
204/// void *env;
205/// int val;
206/// };
207///
208/// The thrown value here is a pointer to the struct. We use this struct to
209/// transfer two values by throwing a single value. Wasm throw and catch
210/// instructions are capable of throwing and catching multiple values, but
211/// it also requires multivalue support that is currently not very reliable.
212/// TODO Switch to throwing and catching two values without using the struct
213///
214/// All longjmpable function calls will be converted to an invoke that will
215/// unwind to this catchpad in case a longjmp occurs. Within the catchpad, we
216/// test the thrown values using __wasm_setjmp_test function as we do for
217/// Emscripten SjLj. The main difference is, in Emscripten SjLj, we need to
218/// transform every longjmpable callsite into a sequence of code including
219/// __wasm_setjmp_test() call; in Wasm SjLj we do the testing in only one
220/// place, in this catchpad.
221///
222/// After testing calling __wasm_setjmp_test(), if the longjmp does not
223/// correspond to one of the setjmps within the current function, it rethrows
224/// the longjmp by calling __wasm_longjmp(). If it corresponds to one of
225/// setjmps in the function, we jump to the beginning of the function, which
226/// contains a switch to each post-setjmp BB. Again, in Emscripten SjLj, this
227/// switch is added for every longjmpable callsite; in Wasm SjLj we do this
228/// only once at the top of the function. (after functionInvocationId
229/// initialization)
230///
231/// The below is the pseudocode for what we have described
232///
233/// entry:
234/// Initialize functionInvocationId
235///
236/// setjmp.dispatch:
237/// switch %label {
238/// label 1: goto post-setjmp BB 1
239/// label 2: goto post-setjmp BB 2
240/// ...
241/// default: goto splitted next BB
242/// }
243/// ...
244///
245/// bb:
246/// invoke void @foo() ;; foo is a longjmpable function
247/// to label %next unwind label %catch.dispatch.longjmp
248/// ...
249///
250/// catch.dispatch.longjmp:
251/// %0 = catchswitch within none [label %catch.longjmp] unwind to caller
252///
253/// catch.longjmp:
254/// %longjmp.args = wasm.catch() ;; struct __WasmLongjmpArgs
255/// %env = load 'env' field from __WasmLongjmpArgs
256/// %val = load 'val' field from __WasmLongjmpArgs
257/// %label = __wasm_setjmp_test(%env, functionInvocationId);
258/// if (%label == 0)
259/// __wasm_longjmp(%env, %val)
260/// catchret to %setjmp.dispatch
261///
262///===----------------------------------------------------------------------===//
263
264#include "WebAssembly.h"
265#include "WebAssemblyTargetMachine.h"
266#include "llvm/ADT/MapVector.h"
267#include "llvm/ADT/StringExtras.h"
268#include "llvm/CodeGen/TargetPassConfig.h"
269#include "llvm/CodeGen/WasmEHInfo.h"
270#include "llvm/IR/DebugInfoMetadata.h"
271#include "llvm/IR/Dominators.h"
272#include "llvm/IR/IRBuilder.h"
273#include "llvm/IR/IntrinsicsWebAssembly.h"
274#include "llvm/IR/Module.h"
275#include "llvm/Support/CommandLine.h"
276#include "llvm/Transforms/Utils/BasicBlockUtils.h"
277#include "llvm/Transforms/Utils/Local.h"
278#include "llvm/Transforms/Utils/SSAUpdater.h"
279#include "llvm/Transforms/Utils/SSAUpdaterBulk.h"
280#include <set>
281
282using namespace llvm;
283
284#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
285
286static cl::list<std::string>
287 EHAllowlist("emscripten-cxx-exceptions-allowed",
288 cl::desc("The list of function names in which Emscripten-style "
289 "exception handling is enabled (see emscripten "
290 "EMSCRIPTEN_CATCHING_ALLOWED options)"),
291 cl::CommaSeparated);
292
293namespace {
294class WebAssemblyLowerEmscriptenEHSjLj final : public ModulePass {
295 bool EnableEmEH; // Enable Emscripten exception handling
296 bool EnableEmSjLj; // Enable Emscripten setjmp/longjmp handling
297 bool EnableWasmSjLj; // Enable Wasm setjmp/longjmp handling
298 bool DoSjLj; // Whether we actually perform setjmp/longjmp handling
299
300 GlobalVariable *ThrewGV = nullptr; // __THREW__ (Emscripten)
301 GlobalVariable *ThrewValueGV = nullptr; // __threwValue (Emscripten)
302 Function *GetTempRet0F = nullptr; // getTempRet0() (Emscripten)
303 Function *SetTempRet0F = nullptr; // setTempRet0() (Emscripten)
304 Function *ResumeF = nullptr; // __resumeException() (Emscripten)
305 Function *EHTypeIDF = nullptr; // llvm.eh.typeid.for() (intrinsic)
306 Function *EmLongjmpF = nullptr; // emscripten_longjmp() (Emscripten)
307 Function *WasmSetjmpF = nullptr; // __wasm_setjmp() (Emscripten)
308 Function *WasmSetjmpTestF = nullptr; // __wasm_setjmp_test() (Emscripten)
309 Function *WasmLongjmpF = nullptr; // __wasm_longjmp() (Emscripten)
310 Function *CatchF = nullptr; // wasm.catch() (intrinsic)
311
312 // type of 'struct __WasmLongjmpArgs' defined in emscripten
313 Type *LongjmpArgsTy = nullptr;
314
315 // __cxa_find_matching_catch_N functions.
316 // Indexed by the number of clauses in an original landingpad instruction.
317 DenseMap<int, Function *> FindMatchingCatches;
318 // Map of <function signature string, invoke_ wrappers>
319 StringMap<Function *> InvokeWrappers;
320 // Set of allowed function names for exception handling
321 std::set<std::string, std::less<>> EHAllowlistSet;
322 // Functions that contains calls to setjmp
323 SmallPtrSet<Function *, 8> SetjmpUsers;
324
325 StringRef getPassName() const override {
326 return "WebAssembly Lower Emscripten Exceptions";
327 }
328
329 using InstVector = SmallVectorImpl<Instruction *>;
330 bool runEHOnFunction(Function &F);
331 bool runSjLjOnFunction(Function &F);
332 void handleLongjmpableCallsForEmscriptenSjLj(
333 Function &F, Instruction *FunctionInvocationId,
334 SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
335 void
336 handleLongjmpableCallsForWasmSjLj(Function &F,
337 Instruction *FunctionInvocationId,
338 SmallVectorImpl<PHINode *> &SetjmpRetPHIs);
339 Function *getFindMatchingCatch(Module &M, unsigned NumClauses);
340
341 Value *wrapInvoke(CallBase *CI);
342 void wrapTestSetjmp(BasicBlock *BB, DebugLoc DL, Value *Threw,
343 Value *FunctionInvocationId, Value *&Label,
344 Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
345 PHINode *&CallEmLongjmpBBThrewPHI,
346 PHINode *&CallEmLongjmpBBThrewValuePHI,
347 BasicBlock *&EndBB);
348 Function *getInvokeWrapper(CallBase *CI);
349
350 bool areAllExceptionsAllowed() const { return EHAllowlistSet.empty(); }
351 bool supportsException(const Function *F) const {
352 return EnableEmEH &&
353 (areAllExceptionsAllowed() || EHAllowlistSet.count(x: F->getName()));
354 }
355 void replaceLongjmpWith(Function *LongjmpF, Function *NewF);
356
357 void rebuildSSA(Function &F);
358
359public:
360 static char ID;
361
362 WebAssemblyLowerEmscriptenEHSjLj()
363 : ModulePass(ID), EnableEmEH(WebAssembly::WasmEnableEmEH),
364 EnableEmSjLj(WebAssembly::WasmEnableEmSjLj),
365 EnableWasmSjLj(WebAssembly::WasmEnableSjLj) {
366 assert(!(EnableEmSjLj && EnableWasmSjLj) &&
367 "Two SjLj modes cannot be turned on at the same time");
368 assert(!(EnableEmEH && EnableWasmSjLj) &&
369 "Wasm SjLj should be only used with Wasm EH");
370 EHAllowlistSet.insert(first: EHAllowlist.begin(), last: EHAllowlist.end());
371 }
372 bool runOnModule(Module &M) override;
373
374 void getAnalysisUsage(AnalysisUsage &AU) const override {
375 AU.addRequired<DominatorTreeWrapperPass>();
376 }
377};
378} // End anonymous namespace
379
380char WebAssemblyLowerEmscriptenEHSjLj::ID = 0;
381INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE,
382 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
383 false, false)
384
385ModulePass *llvm::createWebAssemblyLowerEmscriptenEHSjLj() {
386 return new WebAssemblyLowerEmscriptenEHSjLj();
387}
388
389static bool canThrow(const Value *V) {
390 if (const auto *F = dyn_cast<const Function>(Val: V)) {
391 // Intrinsics cannot throw
392 if (F->isIntrinsic())
393 return false;
394 StringRef Name = F->getName();
395 // leave setjmp and longjmp (mostly) alone, we process them properly later
396 if (Name == "setjmp" || Name == "longjmp" || Name == "emscripten_longjmp")
397 return false;
398 return !F->doesNotThrow();
399 }
400 // not a function, so an indirect call - can throw, we can't tell
401 return true;
402}
403
404// Get a thread-local global variable with the given name. If it doesn't exist
405// declare it, which will generate an import and assume that it will exist at
406// link time.
407static GlobalVariable *getGlobalVariable(Module &M, Type *Ty,
408 WebAssemblyTargetMachine &TM,
409 const char *Name) {
410 auto *GV = dyn_cast<GlobalVariable>(Val: M.getOrInsertGlobal(Name, Ty));
411 if (!GV)
412 report_fatal_error(reason: Twine("unable to create global: ") + Name);
413
414 // Variables created by this function are thread local. If the target does not
415 // support TLS, we depend on CoalesceFeaturesAndStripAtomics to downgrade it
416 // to non-thread-local ones, in which case we don't allow this object to be
417 // linked with other objects using shared memory.
418 GV->setThreadLocalMode(GlobalValue::GeneralDynamicTLSModel);
419 return GV;
420}
421
422// Simple function name mangler.
423// This function simply takes LLVM's string representation of parameter types
424// and concatenate them with '_'. There are non-alphanumeric characters but llc
425// is ok with it, and we need to postprocess these names after the lowering
426// phase anyway.
427static std::string getSignature(FunctionType *FTy) {
428 std::string Sig;
429 raw_string_ostream OS(Sig);
430 OS << *FTy->getReturnType();
431 for (Type *ParamTy : FTy->params())
432 OS << "_" << *ParamTy;
433 if (FTy->isVarArg())
434 OS << "_...";
435 Sig = OS.str();
436 erase_if(C&: Sig, P: isSpace);
437 // When s2wasm parses .s file, a comma means the end of an argument. So a
438 // mangled function name can contain any character but a comma.
439 llvm::replace(Range&: Sig, OldValue: ',', NewValue: '.');
440 return Sig;
441}
442
443static Function *getFunction(FunctionType *Ty, const Twine &Name, Module *M) {
444 return Function::Create(Ty, Linkage: GlobalValue::ExternalLinkage, N: Name, M);
445}
446
447static void markAsImported(Function *F) {
448 // Tell the linker that this function is expected to be imported from the
449 // 'env' module. This is necessary for functions that do not have fixed names
450 // (e.g. __import_xyz). These names cannot be provided by any kind of shared
451 // or static library as instead we mark them explictly as imported.
452 if (!F->hasFnAttribute(Kind: "wasm-import-module")) {
453 llvm::AttrBuilder B(F->getParent()->getContext());
454 B.addAttribute(A: "wasm-import-module", V: "env");
455 F->addFnAttrs(Attrs: B);
456 }
457 if (!F->hasFnAttribute(Kind: "wasm-import-name")) {
458 llvm::AttrBuilder B(F->getParent()->getContext());
459 B.addAttribute(A: "wasm-import-name", V: F->getName());
460 F->addFnAttrs(Attrs: B);
461 }
462}
463
464// Returns an integer type for the target architecture's address space.
465// i32 for wasm32 and i64 for wasm64.
466static Type *getAddrIntType(Module *M) {
467 IRBuilder<> IRB(M->getContext());
468 return IRB.getIntNTy(N: M->getDataLayout().getPointerSizeInBits());
469}
470
471// Returns an integer pointer type for the target architecture's address space.
472// i32* for wasm32 and i64* for wasm64. With opaque pointers this is just a ptr
473// in address space zero.
474static Type *getAddrPtrType(Module *M) {
475 return PointerType::getUnqual(C&: M->getContext());
476}
477
478// Returns an integer whose type is the integer type for the target's address
479// space. Returns (i32 C) for wasm32 and (i64 C) for wasm64, when C is the
480// integer.
481static Value *getAddrSizeInt(Module *M, uint64_t C) {
482 IRBuilder<> IRB(M->getContext());
483 return IRB.getIntN(N: M->getDataLayout().getPointerSizeInBits(), C);
484}
485
486// Returns true if the function has "target-features"="+exception-handling"
487// attribute.
488static bool hasEHTargetFeatureAttr(const Function &F) {
489 Attribute FeaturesAttr = F.getFnAttribute(Kind: "target-features");
490 return FeaturesAttr.isValid() &&
491 FeaturesAttr.getValueAsString().contains(Other: "+exception-handling");
492}
493
494// Returns __cxa_find_matching_catch_N function, where N = NumClauses + 2.
495// This is because a landingpad instruction contains two more arguments, a
496// personality function and a cleanup bit, and __cxa_find_matching_catch_N
497// functions are named after the number of arguments in the original landingpad
498// instruction.
499Function *
500WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(Module &M,
501 unsigned NumClauses) {
502 auto [It, Inserted] = FindMatchingCatches.try_emplace(Key: NumClauses);
503 if (!Inserted)
504 return It->second;
505 PointerType *Int8PtrTy = PointerType::getUnqual(C&: M.getContext());
506 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
507 FunctionType *FTy = FunctionType::get(Result: Int8PtrTy, Params: Args, isVarArg: false);
508 Function *F = getFunction(
509 Ty: FTy, Name: "__cxa_find_matching_catch_" + Twine(NumClauses + 2), M: &M);
510 markAsImported(F);
511 It->second = F;
512 return F;
513}
514
515// Generate invoke wrapper seqence with preamble and postamble
516// Preamble:
517// __THREW__ = 0;
518// Postamble:
519// %__THREW__.val = __THREW__; __THREW__ = 0;
520// Returns %__THREW__.val, which indicates whether an exception is thrown (or
521// whether longjmp occurred), for future use.
522Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallBase *CI) {
523 Module *M = CI->getModule();
524 LLVMContext &C = M->getContext();
525
526 IRBuilder<> IRB(C);
527 IRB.SetInsertPoint(CI);
528
529 // Pre-invoke
530 // __THREW__ = 0;
531 IRB.CreateStore(Val: getAddrSizeInt(M, C: 0), Ptr: ThrewGV);
532
533 // Invoke function wrapper in JavaScript
534 SmallVector<Value *, 16> Args;
535 // Put the pointer to the callee as first argument, so it can be called
536 // within the invoke wrapper later
537 Args.push_back(Elt: CI->getCalledOperand());
538 Args.append(in_start: CI->arg_begin(), in_end: CI->arg_end());
539 CallInst *NewCall = IRB.CreateCall(Callee: getInvokeWrapper(CI), Args);
540 NewCall->takeName(V: CI);
541 NewCall->setCallingConv(CallingConv::WASM_EmscriptenInvoke);
542 NewCall->setDebugLoc(CI->getDebugLoc());
543
544 // Because we added the pointer to the callee as first argument, all
545 // argument attribute indices have to be incremented by one.
546 SmallVector<AttributeSet, 8> ArgAttributes;
547 const AttributeList &InvokeAL = CI->getAttributes();
548
549 // No attributes for the callee pointer.
550 ArgAttributes.push_back(Elt: AttributeSet());
551 // Copy the argument attributes from the original
552 for (unsigned I = 0, E = CI->arg_size(); I < E; ++I)
553 ArgAttributes.push_back(Elt: InvokeAL.getParamAttrs(ArgNo: I));
554
555 AttrBuilder FnAttrs(CI->getContext(), InvokeAL.getFnAttrs());
556 if (auto Args = FnAttrs.getAllocSizeArgs()) {
557 // The allocsize attribute (if any) referes to parameters by index and needs
558 // to be adjusted.
559 auto [SizeArg, NEltArg] = *Args;
560 SizeArg += 1;
561 if (NEltArg)
562 NEltArg = *NEltArg + 1;
563 FnAttrs.addAllocSizeAttr(ElemSizeArg: SizeArg, NumElemsArg: NEltArg);
564 }
565 // In case the callee has 'noreturn' attribute, We need to remove it, because
566 // we expect invoke wrappers to return.
567 FnAttrs.removeAttribute(Val: Attribute::NoReturn);
568
569 // Reconstruct the AttributesList based on the vector we constructed.
570 AttributeList NewCallAL = AttributeList::get(
571 C, FnAttrs: AttributeSet::get(C, B: FnAttrs), RetAttrs: InvokeAL.getRetAttrs(), ArgAttrs: ArgAttributes);
572 NewCall->setAttributes(NewCallAL);
573
574 CI->replaceAllUsesWith(V: NewCall);
575
576 // Post-invoke
577 // %__THREW__.val = __THREW__; __THREW__ = 0;
578 Value *Threw =
579 IRB.CreateLoad(Ty: getAddrIntType(M), Ptr: ThrewGV, Name: ThrewGV->getName() + ".val");
580 IRB.CreateStore(Val: getAddrSizeInt(M, C: 0), Ptr: ThrewGV);
581 return Threw;
582}
583
584// Get matching invoke wrapper based on callee signature
585Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallBase *CI) {
586 Module *M = CI->getModule();
587 SmallVector<Type *, 16> ArgTys;
588 FunctionType *CalleeFTy = CI->getFunctionType();
589
590 std::string Sig = getSignature(FTy: CalleeFTy);
591 auto It = InvokeWrappers.find(Key: Sig);
592 if (It != InvokeWrappers.end())
593 return It->second;
594
595 // Put the pointer to the callee as first argument
596 ArgTys.push_back(Elt: PointerType::getUnqual(C&: CI->getContext()));
597 // Add argument types
598 ArgTys.append(in_start: CalleeFTy->param_begin(), in_end: CalleeFTy->param_end());
599
600 FunctionType *FTy = FunctionType::get(Result: CalleeFTy->getReturnType(), Params: ArgTys,
601 isVarArg: CalleeFTy->isVarArg());
602 Function *F = getFunction(Ty: FTy, Name: "__invoke_" + Sig, M);
603 markAsImported(F);
604 InvokeWrappers[Sig] = F;
605 return F;
606}
607
608static bool canLongjmp(const Value *Callee) {
609 if (auto *CalleeF = dyn_cast<Function>(Val: Callee))
610 if (CalleeF->isIntrinsic())
611 return false;
612
613 // Attempting to transform inline assembly will result in something like:
614 // call void @__invoke_void(void ()* asm ...)
615 // which is invalid because inline assembly blocks do not have addresses
616 // and can't be passed by pointer. The result is a crash with illegal IR.
617 if (isa<InlineAsm>(Val: Callee))
618 return false;
619 StringRef CalleeName = Callee->getName();
620
621 // TODO Include more functions or consider checking with mangled prefixes
622
623 // The reason we include malloc/free here is to exclude the malloc/free
624 // calls generated in setjmp prep / cleanup routines.
625 if (CalleeName == "setjmp" || CalleeName == "malloc" || CalleeName == "free")
626 return false;
627
628 // There are functions in Emscripten's JS glue code or compiler-rt
629 if (CalleeName == "__resumeException" || CalleeName == "llvm_eh_typeid_for" ||
630 CalleeName == "__wasm_setjmp" || CalleeName == "__wasm_setjmp_test" ||
631 CalleeName == "getTempRet0" || CalleeName == "setTempRet0")
632 return false;
633
634 // __cxa_find_matching_catch_N functions cannot longjmp
635 if (Callee->getName().starts_with(Prefix: "__cxa_find_matching_catch_"))
636 return false;
637
638 // Exception-catching related functions
639 //
640 // We intentionally treat __cxa_end_catch longjmpable in Wasm SjLj even though
641 // it surely cannot longjmp, in order to maintain the unwind relationship from
642 // all existing catchpads (and calls within them) to catch.dispatch.longjmp.
643 //
644 // In Wasm EH + Wasm SjLj, we
645 // 1. Make all catchswitch and cleanuppad that unwind to caller unwind to
646 // catch.dispatch.longjmp instead
647 // 2. Convert all longjmpable calls to invokes that unwind to
648 // catch.dispatch.longjmp
649 // But catchswitch BBs are removed in isel, so if an EH catchswitch (generated
650 // from an exception)'s catchpad does not contain any calls that are converted
651 // into invokes unwinding to catch.dispatch.longjmp, this unwind relationship
652 // (EH catchswitch BB -> catch.dispatch.longjmp BB) is lost and
653 // catch.dispatch.longjmp BB can be placed before the EH catchswitch BB in
654 // CFGSort.
655 // int ret = setjmp(buf);
656 // try {
657 // foo(); // longjmps
658 // } catch (...) {
659 // }
660 // Then in this code, if 'foo' longjmps, it first unwinds to 'catch (...)'
661 // catchswitch, and is not caught by that catchswitch because it is a longjmp,
662 // then it should next unwind to catch.dispatch.longjmp BB. But if this 'catch
663 // (...)' catchswitch -> catch.dispatch.longjmp unwind relationship is lost,
664 // it will not unwind to catch.dispatch.longjmp, producing an incorrect
665 // result.
666 //
667 // Every catchpad generated by Wasm C++ contains __cxa_end_catch, so we
668 // intentionally treat it as longjmpable to work around this problem. This is
669 // a hacky fix but an easy one.
670 if (CalleeName == "__cxa_end_catch")
671 return WebAssembly::WasmEnableSjLj;
672 if (CalleeName == "__cxa_begin_catch" ||
673 CalleeName == "__cxa_allocate_exception" || CalleeName == "__cxa_throw" ||
674 CalleeName == "__clang_call_terminate")
675 return false;
676
677 // std::terminate, which is generated when another exception occurs while
678 // handling an exception, cannot longjmp.
679 if (CalleeName == "_ZSt9terminatev")
680 return false;
681
682 // Otherwise we don't know
683 return true;
684}
685
686static bool isEmAsmCall(const Value *Callee) {
687 StringRef CalleeName = Callee->getName();
688 // This is an exhaustive list from Emscripten's <emscripten/em_asm.h>.
689 return CalleeName == "emscripten_asm_const_int" ||
690 CalleeName == "emscripten_asm_const_double" ||
691 CalleeName == "emscripten_asm_const_int_sync_on_main_thread" ||
692 CalleeName == "emscripten_asm_const_double_sync_on_main_thread" ||
693 CalleeName == "emscripten_asm_const_async_on_main_thread";
694}
695
696// Generate __wasm_setjmp_test function call seqence with preamble and
697// postamble. The code this generates is equivalent to the following
698// JavaScript code:
699// %__threwValue.val = __threwValue;
700// if (%__THREW__.val != 0 & %__threwValue.val != 0) {
701// %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
702// if (%label == 0)
703// emscripten_longjmp(%__THREW__.val, %__threwValue.val);
704// setTempRet0(%__threwValue.val);
705// } else {
706// %label = -1;
707// }
708// %longjmp_result = getTempRet0();
709//
710// As output parameters. returns %label, %longjmp_result, and the BB the last
711// instruction (%longjmp_result = ...) is in.
712void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
713 BasicBlock *BB, DebugLoc DL, Value *Threw, Value *FunctionInvocationId,
714 Value *&Label, Value *&LongjmpResult, BasicBlock *&CallEmLongjmpBB,
715 PHINode *&CallEmLongjmpBBThrewPHI, PHINode *&CallEmLongjmpBBThrewValuePHI,
716 BasicBlock *&EndBB) {
717 Function *F = BB->getParent();
718 Module *M = F->getParent();
719 LLVMContext &C = M->getContext();
720 IRBuilder<> IRB(C);
721 IRB.SetCurrentDebugLocation(DL);
722
723 // if (%__THREW__.val != 0 & %__threwValue.val != 0)
724 IRB.SetInsertPoint(BB);
725 BasicBlock *ThenBB1 = BasicBlock::Create(Context&: C, Name: "if.then1", Parent: F);
726 BasicBlock *ElseBB1 = BasicBlock::Create(Context&: C, Name: "if.else1", Parent: F);
727 BasicBlock *EndBB1 = BasicBlock::Create(Context&: C, Name: "if.end", Parent: F);
728 Value *ThrewCmp = IRB.CreateICmpNE(LHS: Threw, RHS: getAddrSizeInt(M, C: 0));
729 Value *ThrewValue = IRB.CreateLoad(Ty: IRB.getInt32Ty(), Ptr: ThrewValueGV,
730 Name: ThrewValueGV->getName() + ".val");
731 Value *ThrewValueCmp = IRB.CreateICmpNE(LHS: ThrewValue, RHS: IRB.getInt32(C: 0));
732 Value *Cmp1 = IRB.CreateAnd(LHS: ThrewCmp, RHS: ThrewValueCmp, Name: "cmp1");
733 IRB.CreateCondBr(Cond: Cmp1, True: ThenBB1, False: ElseBB1);
734
735 // Generate call.em.longjmp BB once and share it within the function
736 if (!CallEmLongjmpBB) {
737 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
738 CallEmLongjmpBB = BasicBlock::Create(Context&: C, Name: "call.em.longjmp", Parent: F);
739 IRB.SetInsertPoint(CallEmLongjmpBB);
740 CallEmLongjmpBBThrewPHI = IRB.CreatePHI(Ty: getAddrIntType(M), NumReservedValues: 4, Name: "threw.phi");
741 CallEmLongjmpBBThrewValuePHI =
742 IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 4, Name: "threwvalue.phi");
743 CallEmLongjmpBBThrewPHI->addIncoming(V: Threw, BB: ThenBB1);
744 CallEmLongjmpBBThrewValuePHI->addIncoming(V: ThrewValue, BB: ThenBB1);
745 IRB.CreateCall(Callee: EmLongjmpF,
746 Args: {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
747 IRB.CreateUnreachable();
748 } else {
749 CallEmLongjmpBBThrewPHI->addIncoming(V: Threw, BB: ThenBB1);
750 CallEmLongjmpBBThrewValuePHI->addIncoming(V: ThrewValue, BB: ThenBB1);
751 }
752
753 // %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
754 // if (%label == 0)
755 IRB.SetInsertPoint(ThenBB1);
756 BasicBlock *EndBB2 = BasicBlock::Create(Context&: C, Name: "if.end2", Parent: F);
757 Value *ThrewPtr =
758 IRB.CreateIntToPtr(V: Threw, DestTy: getAddrPtrType(M), Name: Threw->getName() + ".p");
759 Value *ThenLabel = IRB.CreateCall(Callee: WasmSetjmpTestF,
760 Args: {ThrewPtr, FunctionInvocationId}, Name: "label");
761 Value *Cmp2 = IRB.CreateICmpEQ(LHS: ThenLabel, RHS: IRB.getInt32(C: 0));
762 IRB.CreateCondBr(Cond: Cmp2, True: CallEmLongjmpBB, False: EndBB2);
763
764 // setTempRet0(%__threwValue.val);
765 IRB.SetInsertPoint(EndBB2);
766 IRB.CreateCall(Callee: SetTempRet0F, Args: ThrewValue);
767 IRB.CreateBr(Dest: EndBB1);
768
769 IRB.SetInsertPoint(ElseBB1);
770 IRB.CreateBr(Dest: EndBB1);
771
772 // longjmp_result = getTempRet0();
773 IRB.SetInsertPoint(EndBB1);
774 PHINode *LabelPHI = IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 2, Name: "label");
775 LabelPHI->addIncoming(V: ThenLabel, BB: EndBB2);
776
777 LabelPHI->addIncoming(V: IRB.getInt32(C: -1), BB: ElseBB1);
778
779 // Output parameter assignment
780 Label = LabelPHI;
781 EndBB = EndBB1;
782 LongjmpResult = IRB.CreateCall(Callee: GetTempRet0F, Args: {}, Name: "longjmp_result");
783}
784
785void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(Function &F) {
786 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
787 DT.recalculate(Func&: F); // CFG has been changed
788
789 SSAUpdaterBulk SSA;
790 for (BasicBlock &BB : F) {
791 for (Instruction &I : BB) {
792 if (I.getType()->isVoidTy())
793 continue;
794
795 if (isa<AllocaInst>(Val: &I)) {
796 // If the alloca has any lifetime marker that is no longer dominated
797 // by the alloca, remove all lifetime markers. Lifetime markers must
798 // always work directly on the alloca, and this is no longer possible.
799 bool HasNonDominatedLifetimeMarker = any_of(Range: I.users(), P: [&](User *U) {
800 auto *UserI = cast<Instruction>(Val: U);
801 return UserI->isLifetimeStartOrEnd() && !DT.dominates(Def: &I, User: UserI);
802 });
803 if (HasNonDominatedLifetimeMarker) {
804 for (User *U : make_early_inc_range(Range: I.users())) {
805 auto *UserI = cast<Instruction>(Val: U);
806 if (UserI->isLifetimeStartOrEnd())
807 UserI->eraseFromParent();
808 }
809 }
810 }
811
812 unsigned VarID = SSA.AddVariable(Name: I.getName(), Ty: I.getType());
813 // If a value is defined by an invoke instruction, it is only available in
814 // its normal destination and not in its unwind destination.
815 if (auto *II = dyn_cast<InvokeInst>(Val: &I))
816 SSA.AddAvailableValue(Var: VarID, BB: II->getNormalDest(), V: II);
817 else
818 SSA.AddAvailableValue(Var: VarID, BB: &BB, V: &I);
819 for (auto &U : I.uses()) {
820 auto *User = cast<Instruction>(Val: U.getUser());
821 if (auto *UserPN = dyn_cast<PHINode>(Val: User))
822 if (UserPN->getIncomingBlock(U) == &BB)
823 continue;
824 if (DT.dominates(Def: &I, User))
825 continue;
826 SSA.AddUse(Var: VarID, U: &U);
827 }
828 }
829 }
830 SSA.RewriteAllUses(DT: &DT);
831}
832
833// Replace uses of longjmp with a new longjmp function in Emscripten library.
834// In Emscripten SjLj, the new function is
835// void emscripten_longjmp(uintptr_t, i32)
836// In Wasm SjLj, the new function is
837// void __wasm_longjmp(i8*, i32)
838// Because the original libc longjmp function takes (jmp_buf*, i32), we need a
839// ptrtoint/bitcast instruction here to make the type match. jmp_buf* will
840// eventually be lowered to i32/i64 in the wasm backend.
841void WebAssemblyLowerEmscriptenEHSjLj::replaceLongjmpWith(Function *LongjmpF,
842 Function *NewF) {
843 assert(NewF == EmLongjmpF || NewF == WasmLongjmpF);
844 Module *M = LongjmpF->getParent();
845 SmallVector<CallInst *, 8> ToErase;
846 LLVMContext &C = LongjmpF->getParent()->getContext();
847 IRBuilder<> IRB(C);
848
849 // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
850 // cast its first argument (jmp_buf*) appropriately
851 for (User *U : LongjmpF->users()) {
852 auto *CI = dyn_cast<CallInst>(Val: U);
853 if (CI && CI->getCalledFunction() == LongjmpF) {
854 IRB.SetInsertPoint(CI);
855 Value *Env = nullptr;
856 if (NewF == EmLongjmpF)
857 Env =
858 IRB.CreatePtrToInt(V: CI->getArgOperand(i: 0), DestTy: getAddrIntType(M), Name: "env");
859 else // WasmLongjmpF
860 Env = IRB.CreateBitCast(V: CI->getArgOperand(i: 0), DestTy: IRB.getPtrTy(), Name: "env");
861 IRB.CreateCall(Callee: NewF, Args: {Env, CI->getArgOperand(i: 1)});
862 ToErase.push_back(Elt: CI);
863 }
864 }
865 for (auto *I : ToErase)
866 I->eraseFromParent();
867
868 // If we have any remaining uses of longjmp's function pointer, replace it
869 // with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp.
870 if (!LongjmpF->uses().empty()) {
871 Value *NewLongjmp =
872 IRB.CreateBitCast(V: NewF, DestTy: LongjmpF->getType(), Name: "longjmp.cast");
873 LongjmpF->replaceAllUsesWith(V: NewLongjmp);
874 }
875}
876
877static bool containsLongjmpableCalls(const Function *F) {
878 for (const auto &BB : *F)
879 for (const auto &I : BB)
880 if (const auto *CB = dyn_cast<CallBase>(Val: &I))
881 if (canLongjmp(Callee: CB->getCalledOperand()))
882 return true;
883 return false;
884}
885
886// When a function contains a setjmp call but not other calls that can longjmp,
887// we don't do setjmp transformation for that setjmp. But we need to convert the
888// setjmp calls into "i32 0" so they don't cause link time errors. setjmp always
889// returns 0 when called directly.
890static void nullifySetjmp(Function *F) {
891 Module &M = *F->getParent();
892 IRBuilder<> IRB(M.getContext());
893 Function *SetjmpF = M.getFunction(Name: "setjmp");
894 SmallVector<Instruction *, 1> ToErase;
895
896 for (User *U : make_early_inc_range(Range: SetjmpF->users())) {
897 auto *CB = cast<CallBase>(Val: U);
898 BasicBlock *BB = CB->getParent();
899 if (BB->getParent() != F) // in other function
900 continue;
901 CallInst *CI = nullptr;
902 // setjmp cannot throw. So if it is an invoke, lower it to a call
903 if (auto *II = dyn_cast<InvokeInst>(Val: CB))
904 CI = llvm::changeToCall(II);
905 else
906 CI = cast<CallInst>(Val: CB);
907 ToErase.push_back(Elt: CI);
908 CI->replaceAllUsesWith(V: IRB.getInt32(C: 0));
909 }
910 for (auto *I : ToErase)
911 I->eraseFromParent();
912}
913
914bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(Module &M) {
915 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
916
917 LLVMContext &C = M.getContext();
918 IRBuilder<> IRB(C);
919
920 Function *SetjmpF = M.getFunction(Name: "setjmp");
921 Function *LongjmpF = M.getFunction(Name: "longjmp");
922
923 // In some platforms _setjmp and _longjmp are used instead. Change these to
924 // use setjmp/longjmp instead, because we later detect these functions by
925 // their names.
926 Function *SetjmpF2 = M.getFunction(Name: "_setjmp");
927 Function *LongjmpF2 = M.getFunction(Name: "_longjmp");
928 if (SetjmpF2) {
929 if (SetjmpF) {
930 if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
931 report_fatal_error(reason: "setjmp and _setjmp have different function types");
932 } else {
933 SetjmpF = Function::Create(Ty: SetjmpF2->getFunctionType(),
934 Linkage: GlobalValue::ExternalLinkage, N: "setjmp", M);
935 }
936 SetjmpF2->replaceAllUsesWith(V: SetjmpF);
937 }
938 if (LongjmpF2) {
939 if (LongjmpF) {
940 if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
941 report_fatal_error(
942 reason: "longjmp and _longjmp have different function types");
943 } else {
944 LongjmpF = Function::Create(Ty: LongjmpF2->getFunctionType(),
945 Linkage: GlobalValue::ExternalLinkage, N: "setjmp", M);
946 }
947 LongjmpF2->replaceAllUsesWith(V: LongjmpF);
948 }
949
950 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
951 assert(TPC && "Expected a TargetPassConfig");
952 auto &TM = TPC->getTM<WebAssemblyTargetMachine>();
953
954 // Declare (or get) global variables __THREW__, __threwValue, and
955 // getTempRet0/setTempRet0 function which are used in common for both
956 // exception handling and setjmp/longjmp handling
957 ThrewGV = getGlobalVariable(M, Ty: getAddrIntType(M: &M), TM, Name: "__THREW__");
958 ThrewValueGV = getGlobalVariable(M, Ty: IRB.getInt32Ty(), TM, Name: "__threwValue");
959 GetTempRet0F = getFunction(Ty: FunctionType::get(Result: IRB.getInt32Ty(), isVarArg: false),
960 Name: "getTempRet0", M: &M);
961 SetTempRet0F =
962 getFunction(Ty: FunctionType::get(Result: IRB.getVoidTy(), Params: IRB.getInt32Ty(), isVarArg: false),
963 Name: "setTempRet0", M: &M);
964 GetTempRet0F->setDoesNotThrow();
965 SetTempRet0F->setDoesNotThrow();
966
967 bool Changed = false;
968
969 // Function registration for exception handling
970 if (EnableEmEH) {
971 // Register __resumeException function
972 FunctionType *ResumeFTy =
973 FunctionType::get(Result: IRB.getVoidTy(), Params: IRB.getPtrTy(), isVarArg: false);
974 ResumeF = getFunction(Ty: ResumeFTy, Name: "__resumeException", M: &M);
975 ResumeF->addFnAttr(Kind: Attribute::NoReturn);
976
977 // Register llvm_eh_typeid_for function
978 FunctionType *EHTypeIDTy =
979 FunctionType::get(Result: IRB.getInt32Ty(), Params: IRB.getPtrTy(), isVarArg: false);
980 EHTypeIDF = getFunction(Ty: EHTypeIDTy, Name: "llvm_eh_typeid_for", M: &M);
981 }
982
983 // Functions that contains calls to setjmp but don't have other longjmpable
984 // calls within them.
985 SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
986
987 if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
988 // Precompute setjmp users
989 for (User *U : SetjmpF->users()) {
990 if (auto *CB = dyn_cast<CallBase>(Val: U)) {
991 auto *UserF = CB->getFunction();
992 // If a function that calls setjmp does not contain any other calls that
993 // can longjmp, we don't need to do any transformation on that function,
994 // so can ignore it
995 if (containsLongjmpableCalls(F: UserF))
996 SetjmpUsers.insert(Ptr: UserF);
997 else
998 SetjmpUsersToNullify.insert(Ptr: UserF);
999 } else {
1000 std::string S;
1001 raw_string_ostream SS(S);
1002 SS << *U;
1003 report_fatal_error(reason: Twine("Indirect use of setjmp is not supported: ") +
1004 SS.str());
1005 }
1006 }
1007 }
1008
1009 bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
1010 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
1011 DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
1012
1013 // Function registration and data pre-gathering for setjmp/longjmp handling
1014 if (DoSjLj) {
1015 assert(EnableEmSjLj || EnableWasmSjLj);
1016
1017 if (EnableEmSjLj) {
1018 // Register emscripten_longjmp function
1019 FunctionType *FTy = FunctionType::get(
1020 Result: IRB.getVoidTy(), Params: {getAddrIntType(M: &M), IRB.getInt32Ty()}, isVarArg: false);
1021 EmLongjmpF = getFunction(Ty: FTy, Name: "emscripten_longjmp", M: &M);
1022 EmLongjmpF->addFnAttr(Kind: Attribute::NoReturn);
1023 } else { // EnableWasmSjLj
1024 Type *Int8PtrTy = IRB.getPtrTy();
1025 // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
1026 FunctionType *FTy = FunctionType::get(
1027 Result: IRB.getVoidTy(), Params: {Int8PtrTy, IRB.getInt32Ty()}, isVarArg: false);
1028 WasmLongjmpF = getFunction(Ty: FTy, Name: "__wasm_longjmp", M: &M);
1029 WasmLongjmpF->addFnAttr(Kind: Attribute::NoReturn);
1030 }
1031
1032 if (EnableWasmSjLj) {
1033 for (auto *SjLjF : {SetjmpF, LongjmpF}) {
1034 if (SjLjF) {
1035 for (User *U : SjLjF->users()) {
1036 if (auto *CI = dyn_cast<CallInst>(Val: U)) {
1037 auto &F = *CI->getFunction();
1038 if (!hasEHTargetFeatureAttr(F))
1039 report_fatal_error(reason: "Function " + F.getName() +
1040 " is using setjmp/longjmp but does not have "
1041 "+exception-handling target feature");
1042 }
1043 }
1044 }
1045 }
1046 }
1047
1048 if (SetjmpF) {
1049 Type *Int8PtrTy = IRB.getPtrTy();
1050 Type *Int32PtrTy = IRB.getPtrTy();
1051 Type *Int32Ty = IRB.getInt32Ty();
1052
1053 // Register __wasm_setjmp function
1054 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
1055 FunctionType *FTy = FunctionType::get(
1056 Result: IRB.getVoidTy(), Params: {SetjmpFTy->getParamType(i: 0), Int32Ty, Int32PtrTy},
1057 isVarArg: false);
1058 WasmSetjmpF = getFunction(Ty: FTy, Name: "__wasm_setjmp", M: &M);
1059
1060 // Register __wasm_setjmp_test function
1061 FTy = FunctionType::get(Result: Int32Ty, Params: {Int32PtrTy, Int32PtrTy}, isVarArg: false);
1062 WasmSetjmpTestF = getFunction(Ty: FTy, Name: "__wasm_setjmp_test", M: &M);
1063
1064 // wasm.catch() will be lowered down to wasm 'catch' instruction in
1065 // instruction selection.
1066 CatchF = Intrinsic::getOrInsertDeclaration(M: &M, id: Intrinsic::wasm_catch);
1067 // Type for struct __WasmLongjmpArgs
1068 LongjmpArgsTy = StructType::get(elt1: Int8PtrTy, // env
1069 elts: Int32Ty // val
1070 );
1071 }
1072 }
1073
1074 // Exception handling transformation
1075 if (EnableEmEH) {
1076 for (Function &F : M) {
1077 if (F.isDeclaration())
1078 continue;
1079 Changed |= runEHOnFunction(F);
1080 }
1081 }
1082
1083 // Setjmp/longjmp handling transformation
1084 if (DoSjLj) {
1085 Changed = true; // We have setjmp or longjmp somewhere
1086 if (LongjmpF)
1087 replaceLongjmpWith(LongjmpF, NewF: EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
1088 // Only traverse functions that uses setjmp in order not to insert
1089 // unnecessary prep / cleanup code in every function
1090 if (SetjmpF)
1091 for (Function *F : SetjmpUsers)
1092 runSjLjOnFunction(F&: *F);
1093 }
1094
1095 // Replace unnecessary setjmp calls with 0
1096 if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) {
1097 Changed = true;
1098 assert(SetjmpF);
1099 for (Function *F : SetjmpUsersToNullify)
1100 nullifySetjmp(F);
1101 }
1102
1103 // Delete unused global variables and functions
1104 for (auto *V : {ThrewGV, ThrewValueGV})
1105 if (V && V->use_empty())
1106 V->eraseFromParent();
1107 for (auto *V : {GetTempRet0F, SetTempRet0F, ResumeF, EHTypeIDF, EmLongjmpF,
1108 WasmSetjmpF, WasmSetjmpTestF, WasmLongjmpF, CatchF})
1109 if (V && V->use_empty())
1110 V->eraseFromParent();
1111
1112 return Changed;
1113}
1114
1115bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(Function &F) {
1116 Module &M = *F.getParent();
1117 LLVMContext &C = F.getContext();
1118 IRBuilder<> IRB(C);
1119 bool Changed = false;
1120 SmallVector<Instruction *, 64> ToErase;
1121 SmallPtrSet<LandingPadInst *, 32> LandingPads;
1122
1123 // rethrow.longjmp BB that will be shared within the function.
1124 BasicBlock *RethrowLongjmpBB = nullptr;
1125 // PHI node for the loaded value of __THREW__ global variable in
1126 // rethrow.longjmp BB
1127 PHINode *RethrowLongjmpBBThrewPHI = nullptr;
1128
1129 for (BasicBlock &BB : F) {
1130 auto *II = dyn_cast<InvokeInst>(Val: BB.getTerminator());
1131 if (!II)
1132 continue;
1133 Changed = true;
1134 LandingPads.insert(Ptr: II->getLandingPadInst());
1135 IRB.SetInsertPoint(II);
1136
1137 const Value *Callee = II->getCalledOperand();
1138 bool NeedInvoke = supportsException(F: &F) && canThrow(V: Callee);
1139 if (NeedInvoke) {
1140 // Wrap invoke with invoke wrapper and generate preamble/postamble
1141 Value *Threw = wrapInvoke(CI: II);
1142 ToErase.push_back(Elt: II);
1143
1144 // If setjmp/longjmp handling is enabled, the thrown value can be not an
1145 // exception but a longjmp. If the current function contains calls to
1146 // setjmp, it will be appropriately handled in runSjLjOnFunction. But even
1147 // if the function does not contain setjmp calls, we shouldn't silently
1148 // ignore longjmps; we should rethrow them so they can be correctly
1149 // handled in somewhere up the call chain where setjmp is. __THREW__'s
1150 // value is 0 when nothing happened, 1 when an exception is thrown, and
1151 // other values when longjmp is thrown.
1152 //
1153 // if (%__THREW__.val == 0 || %__THREW__.val == 1)
1154 // goto %tail
1155 // else
1156 // goto %longjmp.rethrow
1157 //
1158 // rethrow.longjmp: ;; This is longjmp. Rethrow it
1159 // %__threwValue.val = __threwValue
1160 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
1161 //
1162 // tail: ;; Nothing happened or an exception is thrown
1163 // ... Continue exception handling ...
1164 if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(Ptr: &F) &&
1165 canLongjmp(Callee)) {
1166 // Create longjmp.rethrow BB once and share it within the function
1167 if (!RethrowLongjmpBB) {
1168 RethrowLongjmpBB = BasicBlock::Create(Context&: C, Name: "rethrow.longjmp", Parent: &F);
1169 IRB.SetInsertPoint(RethrowLongjmpBB);
1170 RethrowLongjmpBBThrewPHI =
1171 IRB.CreatePHI(Ty: getAddrIntType(M: &M), NumReservedValues: 4, Name: "threw.phi");
1172 RethrowLongjmpBBThrewPHI->addIncoming(V: Threw, BB: &BB);
1173 Value *ThrewValue = IRB.CreateLoad(Ty: IRB.getInt32Ty(), Ptr: ThrewValueGV,
1174 Name: ThrewValueGV->getName() + ".val");
1175 IRB.CreateCall(Callee: EmLongjmpF, Args: {RethrowLongjmpBBThrewPHI, ThrewValue});
1176 IRB.CreateUnreachable();
1177 } else {
1178 RethrowLongjmpBBThrewPHI->addIncoming(V: Threw, BB: &BB);
1179 }
1180
1181 IRB.SetInsertPoint(II); // Restore the insert point back
1182 BasicBlock *Tail = BasicBlock::Create(Context&: C, Name: "tail", Parent: &F);
1183 Value *CmpEqOne =
1184 IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 1), Name: "cmp.eq.one");
1185 Value *CmpEqZero =
1186 IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 0), Name: "cmp.eq.zero");
1187 Value *Or = IRB.CreateOr(LHS: CmpEqZero, RHS: CmpEqOne, Name: "or");
1188 IRB.CreateCondBr(Cond: Or, True: Tail, False: RethrowLongjmpBB);
1189 IRB.SetInsertPoint(Tail);
1190 BB.replaceSuccessorsPhiUsesWith(Old: &BB, New: Tail);
1191 }
1192
1193 // Insert a branch based on __THREW__ variable
1194 Value *Cmp = IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 1), Name: "cmp");
1195 IRB.CreateCondBr(Cond: Cmp, True: II->getUnwindDest(), False: II->getNormalDest());
1196
1197 } else {
1198 // This can't throw, and we don't need this invoke, just replace it with a
1199 // call+branch
1200 changeToCall(II);
1201 }
1202 }
1203
1204 // Process resume instructions
1205 for (BasicBlock &BB : F) {
1206 // Scan the body of the basic block for resumes
1207 for (Instruction &I : BB) {
1208 auto *RI = dyn_cast<ResumeInst>(Val: &I);
1209 if (!RI)
1210 continue;
1211 Changed = true;
1212
1213 // Split the input into legal values
1214 Value *Input = RI->getValue();
1215 IRB.SetInsertPoint(RI);
1216 Value *Low = IRB.CreateExtractValue(Agg: Input, Idxs: 0, Name: "low");
1217 // Create a call to __resumeException function
1218 IRB.CreateCall(Callee: ResumeF, Args: {Low});
1219 // Add a terminator to the block
1220 IRB.CreateUnreachable();
1221 ToErase.push_back(Elt: RI);
1222 }
1223 }
1224
1225 // Process llvm.eh.typeid.for intrinsics
1226 for (BasicBlock &BB : F) {
1227 for (Instruction &I : BB) {
1228 auto *CI = dyn_cast<CallInst>(Val: &I);
1229 if (!CI)
1230 continue;
1231 const Function *Callee = CI->getCalledFunction();
1232 if (!Callee)
1233 continue;
1234 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
1235 continue;
1236 Changed = true;
1237
1238 IRB.SetInsertPoint(CI);
1239 CallInst *NewCI =
1240 IRB.CreateCall(Callee: EHTypeIDF, Args: CI->getArgOperand(i: 0), Name: "typeid");
1241 CI->replaceAllUsesWith(V: NewCI);
1242 ToErase.push_back(Elt: CI);
1243 }
1244 }
1245
1246 // Look for orphan landingpads, can occur in blocks with no predecessors
1247 for (BasicBlock &BB : F) {
1248 BasicBlock::iterator I = BB.getFirstNonPHIIt();
1249 if (auto *LPI = dyn_cast<LandingPadInst>(Val&: I))
1250 LandingPads.insert(Ptr: LPI);
1251 }
1252 Changed |= !LandingPads.empty();
1253
1254 // Handle all the landingpad for this function together, as multiple invokes
1255 // may share a single lp
1256 for (LandingPadInst *LPI : LandingPads) {
1257 IRB.SetInsertPoint(LPI);
1258 SmallVector<Value *, 16> FMCArgs;
1259 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
1260 Constant *Clause = LPI->getClause(Idx: I);
1261 // TODO Handle filters (= exception specifications).
1262 // https://github.com/llvm/llvm-project/issues/49740
1263 if (LPI->isCatch(Idx: I))
1264 FMCArgs.push_back(Elt: Clause);
1265 }
1266
1267 // Create a call to __cxa_find_matching_catch_N function
1268 Function *FMCF = getFindMatchingCatch(M, NumClauses: FMCArgs.size());
1269 CallInst *FMCI = IRB.CreateCall(Callee: FMCF, Args: FMCArgs, Name: "fmc");
1270 Value *Poison = PoisonValue::get(T: LPI->getType());
1271 Value *Pair0 = IRB.CreateInsertValue(Agg: Poison, Val: FMCI, Idxs: 0, Name: "pair0");
1272 Value *TempRet0 = IRB.CreateCall(Callee: GetTempRet0F, Args: {}, Name: "tempret0");
1273 Value *Pair1 = IRB.CreateInsertValue(Agg: Pair0, Val: TempRet0, Idxs: 1, Name: "pair1");
1274
1275 LPI->replaceAllUsesWith(V: Pair1);
1276 ToErase.push_back(Elt: LPI);
1277 }
1278
1279 // Erase everything we no longer need in this function
1280 for (Instruction *I : ToErase)
1281 I->eraseFromParent();
1282
1283 return Changed;
1284}
1285
1286// This tries to get debug info from the instruction before which a new
1287// instruction will be inserted, and if there's no debug info in that
1288// instruction, tries to get the info instead from the previous instruction (if
1289// any). If none of these has debug info and a DISubprogram is provided, it
1290// creates a dummy debug info with the first line of the function, because IR
1291// verifier requires all inlinable callsites should have debug info when both a
1292// caller and callee have DISubprogram. If none of these conditions are met,
1293// returns empty info.
1294static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
1295 DISubprogram *SP) {
1296 assert(InsertBefore);
1297 if (InsertBefore->getDebugLoc())
1298 return InsertBefore->getDebugLoc();
1299 const Instruction *Prev = InsertBefore->getPrevNode();
1300 if (Prev && Prev->getDebugLoc())
1301 return Prev->getDebugLoc();
1302 if (SP)
1303 return DILocation::get(Context&: SP->getContext(), Line: SP->getLine(), Column: 1, Scope: SP);
1304 return DebugLoc();
1305}
1306
1307bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(Function &F) {
1308 assert(EnableEmSjLj || EnableWasmSjLj);
1309 Module &M = *F.getParent();
1310 LLVMContext &C = F.getContext();
1311 IRBuilder<> IRB(C);
1312 SmallVector<Instruction *, 64> ToErase;
1313
1314 // Setjmp preparation
1315
1316 SmallVector<AllocaInst *> StaticAllocas;
1317 for (Instruction &I : F.getEntryBlock())
1318 if (auto *AI = dyn_cast<AllocaInst>(Val: &I))
1319 if (AI->isStaticAlloca())
1320 StaticAllocas.push_back(Elt: AI);
1321
1322 BasicBlock *Entry = &F.getEntryBlock();
1323 DebugLoc FirstDL = getOrCreateDebugLoc(InsertBefore: &*Entry->begin(), SP: F.getSubprogram());
1324 SplitBlock(Old: Entry, SplitPt: &*Entry->getFirstInsertionPt());
1325
1326 // Move static allocas back into the entry block, so they stay static.
1327 for (AllocaInst *AI : StaticAllocas)
1328 AI->moveBefore(InsertPos: Entry->getTerminator()->getIterator());
1329
1330 IRB.SetInsertPoint(Entry->getTerminator()->getIterator());
1331 // This alloca'ed pointer is used by the runtime to identify function
1332 // invocations. It's just for pointer comparisons. It will never be
1333 // dereferenced.
1334 Instruction *FunctionInvocationId =
1335 IRB.CreateAlloca(Ty: IRB.getInt32Ty(), ArraySize: nullptr, Name: "functionInvocationId");
1336 FunctionInvocationId->setDebugLoc(FirstDL);
1337
1338 // Setjmp transformation
1339 SmallVector<PHINode *, 4> SetjmpRetPHIs;
1340 Function *SetjmpF = M.getFunction(Name: "setjmp");
1341 for (auto *U : make_early_inc_range(Range: SetjmpF->users())) {
1342 auto *CB = cast<CallBase>(Val: U);
1343 BasicBlock *BB = CB->getParent();
1344 if (BB->getParent() != &F) // in other function
1345 continue;
1346 if (CB->getOperandBundle(ID: LLVMContext::OB_funclet)) {
1347 std::string S;
1348 raw_string_ostream SS(S);
1349 SS << "In function " + F.getName() +
1350 ": setjmp within a catch clause is not supported in Wasm EH:\n";
1351 SS << *CB;
1352 report_fatal_error(reason: StringRef(SS.str()));
1353 }
1354
1355 CallInst *CI = nullptr;
1356 // setjmp cannot throw. So if it is an invoke, lower it to a call
1357 if (auto *II = dyn_cast<InvokeInst>(Val: CB))
1358 CI = llvm::changeToCall(II);
1359 else
1360 CI = cast<CallInst>(Val: CB);
1361
1362 // The tail is everything right after the call, and will be reached once
1363 // when setjmp is called, and later when longjmp returns to the setjmp
1364 BasicBlock *Tail = SplitBlock(Old: BB, SplitPt: CI->getNextNode());
1365 // Add a phi to the tail, which will be the output of setjmp, which
1366 // indicates if this is the first call or a longjmp back. The phi directly
1367 // uses the right value based on where we arrive from
1368 IRB.SetInsertPoint(TheBB: Tail, IP: Tail->getFirstNonPHIIt());
1369 PHINode *SetjmpRet = IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 2, Name: "setjmp.ret");
1370
1371 // setjmp initial call returns 0
1372 SetjmpRet->addIncoming(V: IRB.getInt32(C: 0), BB);
1373 // The proper output is now this, not the setjmp call itself
1374 CI->replaceAllUsesWith(V: SetjmpRet);
1375 // longjmp returns to the setjmp will add themselves to this phi
1376 SetjmpRetPHIs.push_back(Elt: SetjmpRet);
1377
1378 // Fix call target
1379 // Our index in the function is our place in the array + 1 to avoid index
1380 // 0, because index 0 means the longjmp is not ours to handle.
1381 IRB.SetInsertPoint(CI);
1382 Value *Args[] = {CI->getArgOperand(i: 0), IRB.getInt32(C: SetjmpRetPHIs.size()),
1383 FunctionInvocationId};
1384 IRB.CreateCall(Callee: WasmSetjmpF, Args);
1385 ToErase.push_back(Elt: CI);
1386 }
1387
1388 // Handle longjmpable calls.
1389 if (EnableEmSjLj)
1390 handleLongjmpableCallsForEmscriptenSjLj(F, FunctionInvocationId,
1391 SetjmpRetPHIs);
1392 else // EnableWasmSjLj
1393 handleLongjmpableCallsForWasmSjLj(F, FunctionInvocationId, SetjmpRetPHIs);
1394
1395 // Erase everything we no longer need in this function
1396 for (Instruction *I : ToErase)
1397 I->eraseFromParent();
1398
1399 // Finally, our modifications to the cfg can break dominance of SSA variables.
1400 // For example, in this code,
1401 // if (x()) { .. setjmp() .. }
1402 // if (y()) { .. longjmp() .. }
1403 // We must split the longjmp block, and it can jump into the block splitted
1404 // from setjmp one. But that means that when we split the setjmp block, it's
1405 // first part no longer dominates its second part - there is a theoretically
1406 // possible control flow path where x() is false, then y() is true and we
1407 // reach the second part of the setjmp block, without ever reaching the first
1408 // part. So, we rebuild SSA form here.
1409 rebuildSSA(F);
1410 return true;
1411}
1412
1413// Update each call that can longjmp so it can return to the corresponding
1414// setjmp. Refer to 4) of "Emscripten setjmp/longjmp handling" section in the
1415// comments at top of the file for details.
1416void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForEmscriptenSjLj(
1417 Function &F, Instruction *FunctionInvocationId,
1418 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1419 Module &M = *F.getParent();
1420 LLVMContext &C = F.getContext();
1421 IRBuilder<> IRB(C);
1422 SmallVector<Instruction *, 64> ToErase;
1423
1424 // call.em.longjmp BB that will be shared within the function.
1425 BasicBlock *CallEmLongjmpBB = nullptr;
1426 // PHI node for the loaded value of __THREW__ global variable in
1427 // call.em.longjmp BB
1428 PHINode *CallEmLongjmpBBThrewPHI = nullptr;
1429 // PHI node for the loaded value of __threwValue global variable in
1430 // call.em.longjmp BB
1431 PHINode *CallEmLongjmpBBThrewValuePHI = nullptr;
1432 // rethrow.exn BB that will be shared within the function.
1433 BasicBlock *RethrowExnBB = nullptr;
1434
1435 // Because we are creating new BBs while processing and don't want to make
1436 // all these newly created BBs candidates again for longjmp processing, we
1437 // first make the vector of candidate BBs.
1438 std::vector<BasicBlock *> BBs;
1439 for (BasicBlock &BB : F)
1440 BBs.push_back(x: &BB);
1441
1442 // BBs.size() will change within the loop, so we query it every time
1443 for (unsigned I = 0; I < BBs.size(); I++) {
1444 BasicBlock *BB = BBs[I];
1445 for (Instruction &I : *BB) {
1446 if (isa<InvokeInst>(Val: &I)) {
1447 std::string S;
1448 raw_string_ostream SS(S);
1449 SS << "In function " << F.getName()
1450 << ": When using Wasm EH with Emscripten SjLj, there is a "
1451 "restriction that `setjmp` function call and exception cannot be "
1452 "used within the same function:\n";
1453 SS << I;
1454 report_fatal_error(reason: StringRef(SS.str()));
1455 }
1456 auto *CI = dyn_cast<CallInst>(Val: &I);
1457 if (!CI)
1458 continue;
1459
1460 const Value *Callee = CI->getCalledOperand();
1461 if (!canLongjmp(Callee))
1462 continue;
1463 if (isEmAsmCall(Callee))
1464 report_fatal_error(reason: "Cannot use EM_ASM* alongside setjmp/longjmp in " +
1465 F.getName() +
1466 ". Please consider using EM_JS, or move the "
1467 "EM_ASM into another function.",
1468 gen_crash_diag: false);
1469
1470 Value *Threw = nullptr;
1471 BasicBlock *Tail;
1472 if (Callee->getName().starts_with(Prefix: "__invoke_")) {
1473 // If invoke wrapper has already been generated for this call in
1474 // previous EH phase, search for the load instruction
1475 // %__THREW__.val = __THREW__;
1476 // in postamble after the invoke wrapper call
1477 LoadInst *ThrewLI = nullptr;
1478 StoreInst *ThrewResetSI = nullptr;
1479 for (auto I = std::next(x: BasicBlock::iterator(CI)), IE = BB->end();
1480 I != IE; ++I) {
1481 if (auto *LI = dyn_cast<LoadInst>(Val&: I))
1482 if (auto *GV = dyn_cast<GlobalVariable>(Val: LI->getPointerOperand()))
1483 if (GV == ThrewGV) {
1484 Threw = ThrewLI = LI;
1485 break;
1486 }
1487 }
1488 // Search for the store instruction after the load above
1489 // __THREW__ = 0;
1490 for (auto I = std::next(x: BasicBlock::iterator(ThrewLI)), IE = BB->end();
1491 I != IE; ++I) {
1492 if (auto *SI = dyn_cast<StoreInst>(Val&: I)) {
1493 if (auto *GV = dyn_cast<GlobalVariable>(Val: SI->getPointerOperand())) {
1494 if (GV == ThrewGV &&
1495 SI->getValueOperand() == getAddrSizeInt(M: &M, C: 0)) {
1496 ThrewResetSI = SI;
1497 break;
1498 }
1499 }
1500 }
1501 }
1502 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1503 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1504 Tail = SplitBlock(Old: BB, SplitPt: ThrewResetSI->getNextNode());
1505
1506 } else {
1507 // Wrap call with invoke wrapper and generate preamble/postamble
1508 Threw = wrapInvoke(CI);
1509 ToErase.push_back(Elt: CI);
1510 Tail = SplitBlock(Old: BB, SplitPt: CI->getNextNode());
1511
1512 // If exception handling is enabled, the thrown value can be not a
1513 // longjmp but an exception, in which case we shouldn't silently ignore
1514 // exceptions; we should rethrow them.
1515 // __THREW__'s value is 0 when nothing happened, 1 when an exception is
1516 // thrown, other values when longjmp is thrown.
1517 //
1518 // if (%__THREW__.val == 1)
1519 // goto %eh.rethrow
1520 // else
1521 // goto %normal
1522 //
1523 // eh.rethrow: ;; Rethrow exception
1524 // %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr
1525 // __resumeException(%exn)
1526 //
1527 // normal:
1528 // <-- Insertion point. Will insert sjlj handling code from here
1529 // goto %tail
1530 //
1531 // tail:
1532 // ...
1533 if (supportsException(F: &F) && canThrow(V: Callee)) {
1534 // We will add a new conditional branch. So remove the branch created
1535 // when we split the BB
1536 ToErase.push_back(Elt: BB->getTerminator());
1537
1538 // Generate rethrow.exn BB once and share it within the function
1539 if (!RethrowExnBB) {
1540 RethrowExnBB = BasicBlock::Create(Context&: C, Name: "rethrow.exn", Parent: &F);
1541 IRB.SetInsertPoint(RethrowExnBB);
1542 CallInst *Exn =
1543 IRB.CreateCall(Callee: getFindMatchingCatch(M, NumClauses: 0), Args: {}, Name: "exn");
1544 IRB.CreateCall(Callee: ResumeF, Args: {Exn});
1545 IRB.CreateUnreachable();
1546 }
1547
1548 IRB.SetInsertPoint(CI);
1549 BasicBlock *NormalBB = BasicBlock::Create(Context&: C, Name: "normal", Parent: &F);
1550 Value *CmpEqOne =
1551 IRB.CreateICmpEQ(LHS: Threw, RHS: getAddrSizeInt(M: &M, C: 1), Name: "cmp.eq.one");
1552 IRB.CreateCondBr(Cond: CmpEqOne, True: RethrowExnBB, False: NormalBB);
1553
1554 IRB.SetInsertPoint(NormalBB);
1555 IRB.CreateBr(Dest: Tail);
1556 BB = NormalBB; // New insertion point to insert __wasm_setjmp_test()
1557 }
1558 }
1559
1560 // We need to replace the terminator in Tail - SplitBlock makes BB go
1561 // straight to Tail, we need to check if a longjmp occurred, and go to the
1562 // right setjmp-tail if so
1563 ToErase.push_back(Elt: BB->getTerminator());
1564
1565 // Generate a function call to __wasm_setjmp_test function and
1566 // preamble/postamble code to figure out (1) whether longjmp
1567 // occurred (2) if longjmp occurred, which setjmp it corresponds to
1568 Value *Label = nullptr;
1569 Value *LongjmpResult = nullptr;
1570 BasicBlock *EndBB = nullptr;
1571 wrapTestSetjmp(BB, DL: CI->getDebugLoc(), Threw, FunctionInvocationId, Label,
1572 LongjmpResult, CallEmLongjmpBB, CallEmLongjmpBBThrewPHI,
1573 CallEmLongjmpBBThrewValuePHI, EndBB);
1574 assert(Label && LongjmpResult && EndBB);
1575
1576 // Create switch instruction
1577 IRB.SetInsertPoint(EndBB);
1578 IRB.SetCurrentDebugLocation(EndBB->back().getDebugLoc());
1579 SwitchInst *SI = IRB.CreateSwitch(V: Label, Dest: Tail, NumCases: SetjmpRetPHIs.size());
1580 // -1 means no longjmp happened, continue normally (will hit the default
1581 // switch case). 0 means a longjmp that is not ours to handle, needs a
1582 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1583 // 0).
1584 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1585 SI->addCase(OnVal: IRB.getInt32(C: I + 1), Dest: SetjmpRetPHIs[I]->getParent());
1586 SetjmpRetPHIs[I]->addIncoming(V: LongjmpResult, BB: EndBB);
1587 }
1588
1589 // We are splitting the block here, and must continue to find other calls
1590 // in the block - which is now split. so continue to traverse in the Tail
1591 BBs.push_back(x: Tail);
1592 }
1593 }
1594
1595 for (Instruction *I : ToErase)
1596 I->eraseFromParent();
1597}
1598
1599static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CPI) {
1600 for (const User *U : CPI->users())
1601 if (const auto *CRI = dyn_cast<CleanupReturnInst>(Val: U))
1602 return CRI->getUnwindDest();
1603 return nullptr;
1604}
1605
1606// Create a catchpad in which we catch a longjmp's env and val arguments, test
1607// if the longjmp corresponds to one of setjmps in the current function, and if
1608// so, jump to the setjmp dispatch BB from which we go to one of post-setjmp
1609// BBs. Refer to 4) of "Wasm setjmp/longjmp handling" section in the comments at
1610// top of the file for details.
1611void WebAssemblyLowerEmscriptenEHSjLj::handleLongjmpableCallsForWasmSjLj(
1612 Function &F, Instruction *FunctionInvocationId,
1613 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1614 Module &M = *F.getParent();
1615 LLVMContext &C = F.getContext();
1616 IRBuilder<> IRB(C);
1617
1618 // A function with catchswitch/catchpad instruction should have a personality
1619 // function attached to it. Search for the wasm personality function, and if
1620 // it exists, use it, and if it doesn't, create a dummy personality function.
1621 // (SjLj is not going to call it anyway.)
1622 if (!F.hasPersonalityFn()) {
1623 StringRef PersName = getEHPersonalityName(Pers: EHPersonality::Wasm_CXX);
1624 FunctionType *PersType =
1625 FunctionType::get(Result: IRB.getInt32Ty(), /* isVarArg */ true);
1626 Value *PersF = M.getOrInsertFunction(Name: PersName, T: PersType).getCallee();
1627 F.setPersonalityFn(
1628 cast<Constant>(Val: IRB.CreateBitCast(V: PersF, DestTy: IRB.getPtrTy())));
1629 }
1630
1631 // Use the entry BB's debugloc as a fallback
1632 BasicBlock *Entry = &F.getEntryBlock();
1633 DebugLoc FirstDL = getOrCreateDebugLoc(InsertBefore: &*Entry->begin(), SP: F.getSubprogram());
1634 IRB.SetCurrentDebugLocation(FirstDL);
1635
1636 // Add setjmp.dispatch BB right after the entry block. Because we have
1637 // initialized functionInvocationId in the entry block and split the
1638 // rest into another BB, here 'OrigEntry' is the function's original entry
1639 // block before the transformation.
1640 //
1641 // entry:
1642 // functionInvocationId initialization
1643 // setjmp.dispatch:
1644 // switch will be inserted here later
1645 // entry.split: (OrigEntry)
1646 // the original function starts here
1647 BasicBlock *OrigEntry = Entry->getNextNode();
1648 BasicBlock *SetjmpDispatchBB =
1649 BasicBlock::Create(Context&: C, Name: "setjmp.dispatch", Parent: &F, InsertBefore: OrigEntry);
1650 cast<UncondBrInst>(Val: Entry->getTerminator())->setSuccessor(SetjmpDispatchBB);
1651
1652 // Create catch.dispatch.longjmp BB and a catchswitch instruction
1653 BasicBlock *CatchDispatchLongjmpBB =
1654 BasicBlock::Create(Context&: C, Name: "catch.dispatch.longjmp", Parent: &F);
1655 IRB.SetInsertPoint(CatchDispatchLongjmpBB);
1656 CatchSwitchInst *CatchSwitchLongjmp =
1657 IRB.CreateCatchSwitch(ParentPad: ConstantTokenNone::get(Context&: C), UnwindBB: nullptr, NumHandlers: 1);
1658
1659 // Create catch.longjmp BB and a catchpad instruction
1660 BasicBlock *CatchLongjmpBB = BasicBlock::Create(Context&: C, Name: "catch.longjmp", Parent: &F);
1661 CatchSwitchLongjmp->addHandler(Dest: CatchLongjmpBB);
1662 IRB.SetInsertPoint(CatchLongjmpBB);
1663 CatchPadInst *CatchPad = IRB.CreateCatchPad(ParentPad: CatchSwitchLongjmp, Args: {});
1664
1665 // Wasm throw and catch instructions can throw and catch multiple values, but
1666 // that requires multivalue support in the toolchain, which is currently not
1667 // very reliable. We instead throw and catch a pointer to a struct value of
1668 // type 'struct __WasmLongjmpArgs', which is defined in Emscripten.
1669 Instruction *LongjmpArgs =
1670 IRB.CreateCall(Callee: CatchF, Args: {IRB.getInt32(C: WebAssembly::C_LONGJMP)}, Name: "thrown");
1671 Value *EnvField =
1672 IRB.CreateConstGEP2_32(Ty: LongjmpArgsTy, Ptr: LongjmpArgs, Idx0: 0, Idx1: 0, Name: "env_gep");
1673 Value *ValField =
1674 IRB.CreateConstGEP2_32(Ty: LongjmpArgsTy, Ptr: LongjmpArgs, Idx0: 0, Idx1: 1, Name: "val_gep");
1675 // void *env = __wasm_longjmp_args.env;
1676 Instruction *Env = IRB.CreateLoad(Ty: IRB.getPtrTy(), Ptr: EnvField, Name: "env");
1677 // int val = __wasm_longjmp_args.val;
1678 Instruction *Val = IRB.CreateLoad(Ty: IRB.getInt32Ty(), Ptr: ValField, Name: "val");
1679
1680 // %label = __wasm_setjmp_test(%env, functionInvocatinoId);
1681 // if (%label == 0)
1682 // __wasm_longjmp(%env, %val)
1683 // catchret to %setjmp.dispatch
1684 BasicBlock *ThenBB = BasicBlock::Create(Context&: C, Name: "if.then", Parent: &F);
1685 BasicBlock *EndBB = BasicBlock::Create(Context&: C, Name: "if.end", Parent: &F);
1686 Value *EnvP = IRB.CreateBitCast(V: Env, DestTy: getAddrPtrType(M: &M), Name: "env.p");
1687 Value *Label = IRB.CreateCall(Callee: WasmSetjmpTestF, Args: {EnvP, FunctionInvocationId},
1688 OpBundles: OperandBundleDef("funclet", CatchPad), Name: "label");
1689 Value *Cmp = IRB.CreateICmpEQ(LHS: Label, RHS: IRB.getInt32(C: 0));
1690 IRB.CreateCondBr(Cond: Cmp, True: ThenBB, False: EndBB);
1691
1692 IRB.SetInsertPoint(ThenBB);
1693 CallInst *WasmLongjmpCI = IRB.CreateCall(
1694 Callee: WasmLongjmpF, Args: {Env, Val}, OpBundles: OperandBundleDef("funclet", CatchPad));
1695 IRB.CreateUnreachable();
1696
1697 IRB.SetInsertPoint(EndBB);
1698 // Jump to setjmp.dispatch block
1699 IRB.CreateCatchRet(CatchPad, BB: SetjmpDispatchBB);
1700
1701 // Go back to setjmp.dispatch BB
1702 // setjmp.dispatch:
1703 // switch %label {
1704 // label 1: goto post-setjmp BB 1
1705 // label 2: goto post-setjmp BB 2
1706 // ...
1707 // default: goto splitted next BB
1708 // }
1709 IRB.SetInsertPoint(SetjmpDispatchBB);
1710 PHINode *LabelPHI = IRB.CreatePHI(Ty: IRB.getInt32Ty(), NumReservedValues: 2, Name: "label.phi");
1711 LabelPHI->addIncoming(V: Label, BB: EndBB);
1712 LabelPHI->addIncoming(V: IRB.getInt32(C: -1), BB: Entry);
1713 SwitchInst *SI = IRB.CreateSwitch(V: LabelPHI, Dest: OrigEntry, NumCases: SetjmpRetPHIs.size());
1714 // -1 means no longjmp happened, continue normally (will hit the default
1715 // switch case). 0 means a longjmp that is not ours to handle, needs a
1716 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1717 // 0).
1718 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1719 SI->addCase(OnVal: IRB.getInt32(C: I + 1), Dest: SetjmpRetPHIs[I]->getParent());
1720 SetjmpRetPHIs[I]->addIncoming(V: Val, BB: SetjmpDispatchBB);
1721 }
1722
1723 // Convert all longjmpable call instructions to invokes that unwind to the
1724 // newly created catch.dispatch.longjmp BB.
1725 SmallVector<CallInst *, 64> LongjmpableCalls;
1726 for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) {
1727 for (auto &I : *BB) {
1728 auto *CI = dyn_cast<CallInst>(Val: &I);
1729 if (!CI)
1730 continue;
1731 const Value *Callee = CI->getCalledOperand();
1732 if (!canLongjmp(Callee))
1733 continue;
1734 if (isEmAsmCall(Callee))
1735 report_fatal_error(reason: "Cannot use EM_ASM* alongside setjmp/longjmp in " +
1736 F.getName() +
1737 ". Please consider using EM_JS, or move the "
1738 "EM_ASM into another function.",
1739 gen_crash_diag: false);
1740 // This is __wasm_longjmp() call we inserted in this function, which
1741 // rethrows the longjmp when the longjmp does not correspond to one of
1742 // setjmps in this function. We should not convert this call to an invoke.
1743 if (CI == WasmLongjmpCI)
1744 continue;
1745 LongjmpableCalls.push_back(Elt: CI);
1746 }
1747 }
1748
1749 SmallMapVector<BasicBlock *, SmallSetVector<BasicBlock *, 4>, 4>
1750 UnwindDestToNewPreds;
1751 for (auto *CI : LongjmpableCalls) {
1752 // Even if the callee function has attribute 'nounwind', which is true for
1753 // all C functions, it can longjmp, which means it can throw a Wasm
1754 // exception now.
1755 CI->removeFnAttr(Kind: Attribute::NoUnwind);
1756 if (Function *CalleeF = CI->getCalledFunction())
1757 CalleeF->removeFnAttr(Kind: Attribute::NoUnwind);
1758
1759 // Change it to an invoke and make it unwind to the catch.dispatch.longjmp
1760 // BB. If the call is enclosed in another catchpad/cleanuppad scope, unwind
1761 // to its parent pad's unwind destination instead to preserve the scope
1762 // structure. It will eventually unwind to the catch.dispatch.longjmp.
1763 BasicBlock *UnwindDest = nullptr;
1764 if (auto Bundle = CI->getOperandBundle(ID: LLVMContext::OB_funclet)) {
1765 Instruction *FromPad = cast<Instruction>(Val: Bundle->Inputs[0]);
1766 while (!UnwindDest) {
1767 if (auto *CPI = dyn_cast<CatchPadInst>(Val: FromPad)) {
1768 UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
1769 break;
1770 }
1771 if (auto *CPI = dyn_cast<CleanupPadInst>(Val: FromPad)) {
1772 // getCleanupRetUnwindDest() can return nullptr when
1773 // 1. This cleanuppad's matching cleanupret uwninds to caller
1774 // 2. There is no matching cleanupret because it ends with
1775 // unreachable.
1776 // In case of 2, we need to traverse the parent pad chain.
1777 UnwindDest = getCleanupRetUnwindDest(CPI);
1778 Value *ParentPad = CPI->getParentPad();
1779 if (isa<ConstantTokenNone>(Val: ParentPad))
1780 break;
1781 FromPad = cast<Instruction>(Val: ParentPad);
1782 }
1783 }
1784 }
1785 if (!UnwindDest)
1786 UnwindDest = CatchDispatchLongjmpBB;
1787 // Because we are changing a longjmpable call to an invoke, its unwind
1788 // destination can be an existing EH pad that already have phis, and the BB
1789 // with the newly created invoke will become a new predecessor of that EH
1790 // pad. In this case we need to add the new predecessor to those phis.
1791 UnwindDestToNewPreds[UnwindDest].insert(X: CI->getParent());
1792 changeToInvokeAndSplitBasicBlock(CI, UnwindEdge: UnwindDest);
1793 }
1794
1795 SmallVector<Instruction *, 16> ToErase;
1796 for (auto &BB : F) {
1797 if (auto *CSI = dyn_cast<CatchSwitchInst>(Val: BB.getFirstNonPHIIt())) {
1798 if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
1799 IRB.SetInsertPoint(CSI);
1800 ToErase.push_back(Elt: CSI);
1801 auto *NewCSI = IRB.CreateCatchSwitch(ParentPad: CSI->getParentPad(),
1802 UnwindBB: CatchDispatchLongjmpBB, NumHandlers: 1);
1803 NewCSI->addHandler(Dest: *CSI->handler_begin());
1804 NewCSI->takeName(V: CSI);
1805 CSI->replaceAllUsesWith(V: NewCSI);
1806 }
1807 }
1808
1809 if (auto *CRI = dyn_cast<CleanupReturnInst>(Val: BB.getTerminator())) {
1810 if (CRI->unwindsToCaller()) {
1811 IRB.SetInsertPoint(CRI);
1812 ToErase.push_back(Elt: CRI);
1813 IRB.CreateCleanupRet(CleanupPad: CRI->getCleanupPad(), UnwindBB: CatchDispatchLongjmpBB);
1814 }
1815 }
1816 }
1817
1818 for (Instruction *I : ToErase)
1819 I->eraseFromParent();
1820
1821 // Add entries for new predecessors to phis in unwind destinations. We use
1822 // 'poison' as a placeholder value. We should make sure the phis have a valid
1823 // set of predecessors before running SSAUpdater, because SSAUpdater
1824 // internally can use existing phis to gather predecessor info rather than
1825 // scanning the actual CFG (See FindPredecessorBlocks in SSAUpdater.cpp for
1826 // details).
1827 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1828 for (PHINode &PN : UnwindDest->phis()) {
1829 for (auto *NewPred : NewPreds) {
1830 assert(PN.getBasicBlockIndex(NewPred) == -1);
1831 PN.addIncoming(V: PoisonValue::get(T: PN.getType()), BB: NewPred);
1832 }
1833 }
1834 }
1835
1836 // For unwind destinations for newly added invokes to longjmpable functions,
1837 // calculate incoming values for the newly added predecessors using
1838 // SSAUpdater. We add existing values in the phis to SSAUpdater as available
1839 // values and let it calculate what the value should be at the end of new
1840 // incoming blocks.
1841 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1842 for (PHINode &PN : UnwindDest->phis()) {
1843 SSAUpdater SSA;
1844 SSA.Initialize(Ty: PN.getType(), Name: PN.getName());
1845 for (unsigned Idx = 0, E = PN.getNumIncomingValues(); Idx != E; ++Idx) {
1846 if (NewPreds.contains(key: PN.getIncomingBlock(i: Idx)))
1847 continue;
1848 Value *V = PN.getIncomingValue(i: Idx);
1849 if (auto *II = dyn_cast<InvokeInst>(Val: V))
1850 SSA.AddAvailableValue(BB: II->getNormalDest(), V: II);
1851 else if (auto *I = dyn_cast<Instruction>(Val: V))
1852 SSA.AddAvailableValue(BB: I->getParent(), V: I);
1853 else
1854 SSA.AddAvailableValue(BB: PN.getIncomingBlock(i: Idx), V);
1855 }
1856 for (auto *NewPred : NewPreds)
1857 PN.setIncomingValueForBlock(BB: NewPred, V: SSA.GetValueAtEndOfBlock(BB: NewPred));
1858 assert(PN.isComplete());
1859 }
1860 }
1861}
1862