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