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