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