LLVM 24.0.0git
WebAssemblyLowerEmscriptenEHSjLj.cpp
Go to the documentation of this file.
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"
266#include "llvm/ADT/MapVector.h"
270#include "llvm/IR/Analysis.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"
283#include <set>
284
285using namespace llvm;
286
287#define DEBUG_TYPE "wasm-lower-em-ehsjlj"
288
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)"),
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(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(EHAllowlist.begin(), 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
404 return new WebAssemblyLowerEmscriptenEHSjLjLegacy(EnableEmEH);
405}
406
407static bool canThrow(const Value *V) {
408 if (const auto *F = dyn_cast<const Function>(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.
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, [&]() {
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(Sig, 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(Sig, ',', '.');
454 return Sig;
455}
456
457static Function *getFunction(FunctionType *Ty, const Twine &Name, Module *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("wasm-import-module")) {
467 llvm::AttrBuilder B(F->getParent()->getContext());
468 B.addAttribute("wasm-import-module", "env");
469 F->addFnAttrs(B);
470 }
471 if (!F->hasFnAttribute("wasm-import-name")) {
472 llvm::AttrBuilder B(F->getParent()->getContext());
473 B.addAttribute("wasm-import-name", F->getName());
474 F->addFnAttrs(B);
475 }
476}
477
478// Returns an integer type for the target architecture's address space.
479// i32 for wasm32 and i64 for wasm64.
481 IRBuilder<> IRB(*M);
482 return IRB.getIntNTy(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.
489 return PointerType::getUnqual(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.
496 IRBuilder<> IRB(*M);
497 return IRB.getIntN(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("target-features");
504 return FeaturesAttr.isValid() &&
505 FeaturesAttr.getValueAsString().contains("+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(NumClauses);
516 if (!Inserted)
517 return It->second;
518 PointerType *Int8PtrTy = PointerType::getUnqual(M.getContext());
519 SmallVector<Type *, 16> Args(NumClauses, Int8PtrTy);
520 FunctionType *FTy = FunctionType::get(Int8PtrTy, Args, false);
522 FTy, "__cxa_find_matching_catch_" + Twine(NumClauses + 2), &M);
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(getAddrSizeInt(M, 0), 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(CI->getCalledOperand());
550 Args.append(CI->arg_begin(), CI->arg_end());
551 CallInst *NewCall = IRB.CreateCall(getInvokeWrapper(CI), Args);
552 NewCall->takeName(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(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(InvokeAL.getParamAttrs(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(SizeArg, 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(Attribute::NoReturn);
580
581 // Reconstruct the AttributesList based on the vector we constructed.
582 AttributeList NewCallAL = AttributeList::get(
583 C, AttributeSet::get(C, FnAttrs), InvokeAL.getRetAttrs(), ArgAttributes);
584 NewCall->setAttributes(NewCallAL);
585
586 CI->replaceAllUsesWith(NewCall);
587
588 // Post-invoke
589 // %__THREW__.val = __THREW__; __THREW__ = 0;
590 Value *Threw =
591 IRB.CreateLoad(getAddrIntType(M), ThrewGV, ThrewGV->getName() + ".val");
592 IRB.CreateStore(getAddrSizeInt(M, 0), 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();
600 FunctionType *CalleeFTy = CI->getFunctionType();
601
602 std::string Sig = getSignature(CalleeFTy);
603 auto It = InvokeWrappers.find(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(PointerType::getUnqual(CI->getContext()));
609 // Add argument types
610 ArgTys.append(CalleeFTy->param_begin(), CalleeFTy->param_end());
611
612 FunctionType *FTy = FunctionType::get(CalleeFTy->getReturnType(), ArgTys,
613 CalleeFTy->isVarArg());
614 Function *F = getFunction(FTy, "__invoke_" + Sig, M);
616 InvokeWrappers[Sig] = F;
617 return F;
618}
619
620static bool canLongjmp(const Value *Callee) {
621 if (auto *CalleeF = dyn_cast<Function>(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>(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("__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")
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(C, "if.then1", F);
737 BasicBlock *ElseBB1 = BasicBlock::Create(C, "if.else1", F);
738 BasicBlock *EndBB1 = BasicBlock::Create(C, "if.end", F);
739 Value *ThrewCmp = IRB.CreateICmpNE(Threw, getAddrSizeInt(M, 0));
740 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
741 ThrewValueGV->getName() + ".val");
742 Value *ThrewValueCmp = IRB.CreateICmpNE(ThrewValue, IRB.getInt32(0));
743 Value *Cmp1 = IRB.CreateAnd(ThrewCmp, ThrewValueCmp, "cmp1");
744 IRB.CreateCondBr(Cmp1, ThenBB1, 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(C, "call.em.longjmp", F);
750 IRB.SetInsertPoint(CallEmLongjmpBB);
751 CallEmLongjmpBBThrewPHI = IRB.CreatePHI(getAddrIntType(M), 4, "threw.phi");
752 CallEmLongjmpBBThrewValuePHI =
753 IRB.CreatePHI(IRB.getInt32Ty(), 4, "threwvalue.phi");
754 CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
755 CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
756 IRB.CreateCall(EmLongjmpF,
757 {CallEmLongjmpBBThrewPHI, CallEmLongjmpBBThrewValuePHI});
758 IRB.CreateUnreachable();
759 } else {
760 CallEmLongjmpBBThrewPHI->addIncoming(Threw, ThenBB1);
761 CallEmLongjmpBBThrewValuePHI->addIncoming(ThrewValue, ThenBB1);
762 }
763
764 // %label = __wasm_setjmp_test(%__THREW__.val, functionInvocationId);
765 // if (%label == 0)
766 IRB.SetInsertPoint(ThenBB1);
767 BasicBlock *EndBB2 = BasicBlock::Create(C, "if.end2", F);
768 Value *ThrewPtr =
769 IRB.CreateIntToPtr(Threw, getAddrPtrType(M), Threw->getName() + ".p");
770 Value *ThenLabel = IRB.CreateCall(WasmSetjmpTestF,
771 {ThrewPtr, FunctionInvocationId}, "label");
772 Value *Cmp2 = IRB.CreateICmpEQ(ThenLabel, IRB.getInt32(0));
773 IRB.CreateCondBr(Cmp2, CallEmLongjmpBB, EndBB2);
774
775 // setTempRet0(%__threwValue.val);
776 IRB.SetInsertPoint(EndBB2);
777 IRB.CreateCall(SetTempRet0F, ThrewValue);
778 IRB.CreateBr(EndBB1);
779
780 IRB.SetInsertPoint(ElseBB1);
781 IRB.CreateBr(EndBB1);
782
783 // longjmp_result = getTempRet0();
784 IRB.SetInsertPoint(EndBB1);
785 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label");
786 LabelPHI->addIncoming(ThenLabel, EndBB2);
787
788 LabelPHI->addIncoming(IRB.getInt32(-1), ElseBB1);
789
790 // Output parameter assignment
791 Label = LabelPHI;
792 EndBB = EndBB1;
793 LongjmpResult = IRB.CreateCall(GetTempRet0F, {}, "longjmp_result");
794}
795
796void WebAssemblyLowerEmscriptenEHSjLjImpl::rebuildSSA(Function &F) {
797 DominatorTree &DT = GetDominatorTree(F);
798 DT.recalculate(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>(&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(I.users(), [&](User *U) {
811 auto *UserI = cast<Instruction>(U);
812 return UserI->isLifetimeStartOrEnd() && !DT.dominates(&I, UserI);
813 });
814 if (HasNonDominatedLifetimeMarker) {
815 for (User *U : make_early_inc_range(I.users())) {
816 auto *UserI = cast<Instruction>(U);
817 if (UserI->isLifetimeStartOrEnd())
818 UserI->eraseFromParent();
819 }
820 }
821 }
822
823 unsigned VarID = SSA.AddVariable(I.getName(), 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>(&I))
827 SSA.AddAvailableValue(VarID, II->getNormalDest(), II);
828 else
829 SSA.AddAvailableValue(VarID, &BB, &I);
830 for (auto &U : I.uses()) {
831 auto *User = cast<Instruction>(U.getUser());
832 if (auto *UserPN = dyn_cast<PHINode>(User))
833 if (UserPN->getIncomingBlock(U) == &BB)
834 continue;
835 if (DT.dominates(&I, User))
836 continue;
837 SSA.AddUse(VarID, &U);
838 }
839 }
840 }
841 SSA.RewriteAllUses(&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();
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>(U);
863 if (CI && CI->getCalledFunction() == LongjmpF) {
864 IRB.SetInsertPoint(CI);
865 Value *Env = nullptr;
866 if (NewF == EmLongjmpF)
867 Env =
868 IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
869 else // WasmLongjmpF
870 Env = IRB.CreateBitCast(CI->getArgOperand(0), IRB.getPtrTy(), "env");
871 IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)});
872 ToErase.push_back(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(NewF, LongjmpF->getType(), "longjmp.cast");
883 LongjmpF->replaceAllUsesWith(NewLongjmp);
884 }
885}
886
888 for (const auto &BB : *F)
889 for (const auto &I : BB)
890 if (const auto *CB = dyn_cast<CallBase>(&I))
891 if (canLongjmp(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("setjmp");
905
906 for (User *U : make_early_inc_range(SetjmpF->users())) {
907 auto *CB = cast<CallBase>(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>(CB))
915 else
916 CI = cast<CallInst>(CB);
917 ToErase.push_back(CI);
918 CI->replaceAllUsesWith(IRB.getInt32(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("setjmp");
935 Function *LongjmpF = M.getFunction("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("_setjmp");
941 Function *LongjmpF2 = M.getFunction("_longjmp");
942 if (SetjmpF2) {
943 if (SetjmpF) {
944 if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
945 report_fatal_error("setjmp and _setjmp have different function types");
946 } else {
947 SetjmpF = Function::Create(SetjmpF2->getFunctionType(),
948 GlobalValue::ExternalLinkage, "setjmp", M);
949 }
950 SetjmpF2->replaceAllUsesWith(SetjmpF);
951 }
952 if (LongjmpF2) {
953 if (LongjmpF) {
954 if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
956 "longjmp and _longjmp have different function types");
957 } else {
958 LongjmpF = Function::Create(LongjmpF2->getFunctionType(),
959 GlobalValue::ExternalLinkage, "setjmp", M);
960 }
961 LongjmpF2->replaceAllUsesWith(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, getAddrIntType(&M), "__THREW__");
968 ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), "__threwValue");
969 GetTempRet0F = getFunction(FunctionType::get(IRB.getInt32Ty(), false),
970 "getTempRet0", &M);
971 SetTempRet0F =
972 getFunction(FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
973 "setTempRet0", &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(IRB.getVoidTy(), IRB.getPtrTy(), false);
984 ResumeF = getFunction(ResumeFTy, "__resumeException", &M);
985 ResumeF->addFnAttr(Attribute::NoReturn);
986
987 // Register llvm_eh_typeid_for function
988 FunctionType *EHTypeIDTy =
989 FunctionType::get(IRB.getInt32Ty(), IRB.getPtrTy(), false);
990 EHTypeIDF = getFunction(EHTypeIDTy, "llvm_eh_typeid_for", &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>(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(UserF))
1006 SetjmpUsers.insert(UserF);
1007 else
1008 SetjmpUsersToNullify.insert(UserF);
1009 } else {
1010 std::string S;
1011 raw_string_ostream SS(S);
1012 SS << *U;
1013 report_fatal_error(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 IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
1031 EmLongjmpF = getFunction(FTy, "emscripten_longjmp", &M);
1032 EmLongjmpF->addFnAttr(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 IRB.getVoidTy(), {Int8PtrTy, IRB.getInt32Ty()}, false);
1038 WasmLongjmpF = getFunction(FTy, "__wasm_longjmp", &M);
1039 WasmLongjmpF->addFnAttr(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>(U)) {
1047 auto &F = *CI->getFunction();
1049 report_fatal_error("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 IRB.getVoidTy(), {SetjmpFTy->getParamType(0), Int32Ty, Int32PtrTy},
1067 false);
1068 WasmSetjmpF = getFunction(FTy, "__wasm_setjmp", &M);
1069
1070 // Register __wasm_setjmp_test function
1071 FTy = FunctionType::get(Int32Ty, {Int32PtrTy, Int32PtrTy}, false);
1072 WasmSetjmpTestF = getFunction(FTy, "__wasm_setjmp_test", &M);
1073
1074 // wasm.catch() will be lowered down to wasm 'catch' instruction in
1075 // instruction selection.
1076 CatchF = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_catch);
1077 // Type for struct __WasmLongjmpArgs
1078 LongjmpArgsTy = StructType::get(Int8PtrTy, // env
1079 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, 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);
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)
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;
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>(BB.getTerminator());
1141 if (!II)
1142 continue;
1143 Changed = true;
1144 LandingPads.insert(II->getLandingPadInst());
1145 IRB.SetInsertPoint(II);
1146
1147 const Value *Callee = II->getCalledOperand();
1148 bool NeedInvoke = supportsException(&F) && canThrow(Callee);
1149 if (NeedInvoke) {
1150 // Wrap invoke with invoke wrapper and generate preamble/postamble
1151 Value *Threw = wrapInvoke(II);
1152 ToErase.push_back(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(&F) &&
1175 canLongjmp(Callee)) {
1176 // Create longjmp.rethrow BB once and share it within the function
1177 if (!RethrowLongjmpBB) {
1178 RethrowLongjmpBB = BasicBlock::Create(C, "rethrow.longjmp", &F);
1179 IRB.SetInsertPoint(RethrowLongjmpBB);
1180 RethrowLongjmpBBThrewPHI =
1181 IRB.CreatePHI(getAddrIntType(&M), 4, "threw.phi");
1182 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1183 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
1184 ThrewValueGV->getName() + ".val");
1185 IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue});
1186 IRB.CreateUnreachable();
1187 } else {
1188 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1189 }
1190
1191 IRB.SetInsertPoint(II); // Restore the insert point back
1192 BasicBlock *Tail = BasicBlock::Create(C, "tail", &F);
1193 Value *CmpEqOne =
1194 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1195 Value *CmpEqZero =
1196 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero");
1197 Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or");
1198 IRB.CreateCondBr(Or, Tail, RethrowLongjmpBB);
1199 IRB.SetInsertPoint(Tail);
1200 BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
1201 }
1202
1203 // Insert a branch based on __THREW__ variable
1204 Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
1205 IRB.CreateCondBr(Cmp, II->getUnwindDest(), 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
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>(&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(Input, 0, "low");
1227 // Create a call to __resumeException function
1228 IRB.CreateCall(ResumeF, {Low});
1229 // Add a terminator to the block
1230 IRB.CreateUnreachable();
1231 ToErase.push_back(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>(&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(EHTypeIDF, CI->getArgOperand(0), "typeid");
1251 CI->replaceAllUsesWith(NewCI);
1252 ToErase.push_back(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>(I))
1260 LandingPads.insert(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(I);
1271 // TODO Handle filters (= exception specifications).
1272 // https://github.com/llvm/llvm-project/issues/49740
1273 if (LPI->isCatch(I))
1274 FMCArgs.push_back(Clause);
1275 }
1276
1277 // Create a call to __cxa_find_matching_catch_N function
1278 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
1279 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
1280 Value *Poison = PoisonValue::get(LPI->getType());
1281 Value *Pair0 = IRB.CreateInsertValue(Poison, FMCI, 0, "pair0");
1282 Value *TempRet0 = IRB.CreateCall(GetTempRet0F, {}, "tempret0");
1283 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
1284
1285 LPI->replaceAllUsesWith(Pair1);
1286 ToErase.push_back(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(SP->getContext(), SP->getLine(), 1, SP);
1314 return DebugLoc();
1315}
1316
1317bool WebAssemblyLowerEmscriptenEHSjLjImpl::runSjLjOnFunction(Function &F) {
1318 assert(EnableEmSjLj || EnableWasmSjLj);
1319 Module &M = *F.getParent();
1320 IRBuilder IRB(M);
1322
1323 // Setjmp preparation
1324
1325 SmallVector<AllocaInst *> StaticAllocas;
1326 for (Instruction &I : F.getEntryBlock())
1327 if (auto *AI = dyn_cast<AllocaInst>(&I))
1328 if (AI->isStaticAlloca())
1329 StaticAllocas.push_back(AI);
1330
1331 BasicBlock *Entry = &F.getEntryBlock();
1332 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1333 SplitBlock(Entry, &*Entry->getFirstInsertionPt());
1334
1335 // Move static allocas back into the entry block, so they stay static.
1336 for (AllocaInst *AI : StaticAllocas)
1337 AI->moveBefore(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(IRB.getInt32Ty(), nullptr, "functionInvocationId");
1345 FunctionInvocationId->setDebugLoc(FirstDL);
1346
1347 // Setjmp transformation
1348 SmallVector<PHINode *, 4> SetjmpRetPHIs;
1349 Function *SetjmpF = M.getFunction("setjmp");
1350 for (auto *U : make_early_inc_range(SetjmpF->users())) {
1351 auto *CB = cast<CallBase>(U);
1352 BasicBlock *BB = CB->getParent();
1353 if (BB->getParent() != &F) // in other function
1354 continue;
1355 if (CB->getOperandBundle(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(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>(CB))
1367 CI = llvm::changeToCall(II);
1368 else
1369 CI = cast<CallInst>(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(BB, 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(IRB.getInt32Ty(), 2, "setjmp.ret");
1379
1380 // setjmp initial call returns 0
1381 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
1382 // The proper output is now this, not the setjmp call itself
1383 CI->replaceAllUsesWith(SetjmpRet);
1384 // longjmp returns to the setjmp will add themselves to this phi
1385 SetjmpRetPHIs.push_back(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(0), IRB.getInt32(SetjmpRetPHIs.size()),
1392 FunctionInvocationId};
1393 IRB.CreateCall(WasmSetjmpF, Args);
1394 ToErase.push_back(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);
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(&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>(&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(StringRef(SS.str()));
1465 }
1466 auto *CI = dyn_cast<CallInst>(&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("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 false);
1479
1480 Value *Threw = nullptr;
1482 if (Callee->getName().starts_with("__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(BasicBlock::iterator(CI)), IE = BB->end();
1490 I != IE; ++I) {
1491 if (auto *LI = dyn_cast<LoadInst>(I))
1492 if (auto *GV = dyn_cast<GlobalVariable>(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(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1501 I != IE; ++I) {
1502 if (auto *SI = dyn_cast<StoreInst>(I)) {
1503 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
1504 if (GV == ThrewGV &&
1505 SI->getValueOperand() == getAddrSizeInt(&M, 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(BB, ThrewResetSI->getNextNode());
1515
1516 } else {
1517 // Wrap call with invoke wrapper and generate preamble/postamble
1518 Threw = wrapInvoke(CI);
1519 ToErase.push_back(CI);
1520 Tail = SplitBlock(BB, 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) && canThrow(Callee)) {
1544 // We will add a new conditional branch. So remove the branch created
1545 // when we split the BB
1546 ToErase.push_back(BB->getTerminator());
1547
1548 // Generate rethrow.exn BB once and share it within the function
1549 if (!RethrowExnBB) {
1550 RethrowExnBB = BasicBlock::Create(C, "rethrow.exn", &F);
1551 IRB.SetInsertPoint(RethrowExnBB);
1552 CallInst *Exn =
1553 IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn");
1554 IRB.CreateCall(ResumeF, {Exn});
1555 IRB.CreateUnreachable();
1556 }
1557
1558 IRB.SetInsertPoint(CI);
1559 BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F);
1560 Value *CmpEqOne =
1561 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1562 IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB);
1563
1564 IRB.SetInsertPoint(NormalBB);
1565 IRB.CreateBr(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(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, 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(Label, Tail, 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(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1596 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, 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(Tail);
1602 }
1603 }
1604
1605 for (Instruction *I : ToErase)
1606 I->eraseFromParent();
1607}
1608
1610 for (const User *U : CPI->users())
1611 if (const auto *CRI = dyn_cast<CleanupReturnInst>(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(EHPersonality::Wasm_CXX);
1634 FunctionType *PersType =
1635 FunctionType::get(IRB.getInt32Ty(), /* isVarArg */ true);
1636 Value *PersF = M.getOrInsertFunction(PersName, PersType).getCallee();
1637 F.setPersonalityFn(
1638 cast<Constant>(IRB.CreateBitCast(PersF, IRB.getPtrTy())));
1639 }
1640
1641 // Use the entry BB's debugloc as a fallback
1642 BasicBlock *Entry = &F.getEntryBlock();
1643 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), 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(C, "setjmp.dispatch", &F, OrigEntry);
1660 cast<UncondBrInst>(Entry->getTerminator())->setSuccessor(SetjmpDispatchBB);
1661
1662 // Create catch.dispatch.longjmp BB and a catchswitch instruction
1663 BasicBlock *CatchDispatchLongjmpBB =
1664 BasicBlock::Create(C, "catch.dispatch.longjmp", &F);
1665 IRB.SetInsertPoint(CatchDispatchLongjmpBB);
1666 CatchSwitchInst *CatchSwitchLongjmp =
1667 IRB.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1);
1668
1669 // Create catch.longjmp BB and a catchpad instruction
1670 BasicBlock *CatchLongjmpBB = BasicBlock::Create(C, "catch.longjmp", &F);
1671 CatchSwitchLongjmp->addHandler(CatchLongjmpBB);
1672 IRB.SetInsertPoint(CatchLongjmpBB);
1673 CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitchLongjmp, {});
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(CatchF, {IRB.getInt32(WebAssembly::C_LONGJMP)}, "thrown");
1681 Value *EnvField =
1682 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0, "env_gep");
1683 Value *ValField =
1684 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1, "val_gep");
1685 // void *env = __wasm_longjmp_args.env;
1686 Instruction *Env = IRB.CreateLoad(IRB.getPtrTy(), EnvField, "env");
1687 // int val = __wasm_longjmp_args.val;
1688 Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField, "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(C, "if.then", &F);
1695 BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F);
1696 Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p");
1697 Value *Label = IRB.CreateCall(WasmSetjmpTestF, {EnvP, FunctionInvocationId},
1698 OperandBundleDef("funclet", CatchPad), "label");
1699 Value *Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0));
1700 IRB.CreateCondBr(Cmp, ThenBB, EndBB);
1701
1702 IRB.SetInsertPoint(ThenBB);
1703 CallInst *WasmLongjmpCI = IRB.CreateCall(
1704 WasmLongjmpF, {Env, Val}, OperandBundleDef("funclet", CatchPad));
1705 IRB.CreateUnreachable();
1706
1707 IRB.SetInsertPoint(EndBB);
1708 // Jump to setjmp.dispatch block
1709 IRB.CreateCatchRet(CatchPad, 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(IRB.getInt32Ty(), 2, "label.phi");
1721 LabelPHI->addIncoming(Label, EndBB);
1722 LabelPHI->addIncoming(IRB.getInt32(-1), Entry);
1723 SwitchInst *SI = IRB.CreateSwitch(LabelPHI, OrigEntry, 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(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1730 SetjmpRetPHIs[I]->addIncoming(Val, 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>(&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("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 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(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(Attribute::NoUnwind);
1766 if (Function *CalleeF = CI->getCalledFunction())
1767 CalleeF->removeFnAttr(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(LLVMContext::OB_funclet)) {
1775 Instruction *FromPad = cast<Instruction>(Bundle->Inputs[0]);
1776 while (!UnwindDest) {
1777 if (auto *CPI = dyn_cast<CatchPadInst>(FromPad)) {
1778 UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
1779 break;
1780 }
1781 if (auto *CPI = dyn_cast<CleanupPadInst>(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>(ParentPad))
1790 break;
1791 FromPad = cast<Instruction>(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(CI->getParent());
1802 changeToInvokeAndSplitBasicBlock(CI, UnwindDest);
1803 }
1804
1805 SmallVector<Instruction *, 16> ToErase;
1806 for (auto &BB : F) {
1807 if (auto *CSI = dyn_cast<CatchSwitchInst>(BB.getFirstNonPHIIt())) {
1808 if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
1809 IRB.SetInsertPoint(CSI);
1810 ToErase.push_back(CSI);
1811 auto *NewCSI = IRB.CreateCatchSwitch(CSI->getParentPad(),
1812 CatchDispatchLongjmpBB, 1);
1813 NewCSI->addHandler(*CSI->handler_begin());
1814 NewCSI->takeName(CSI);
1815 CSI->replaceAllUsesWith(NewCSI);
1816 }
1817 }
1818
1819 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB.getTerminator())) {
1820 if (CRI->unwindsToCaller()) {
1821 IRB.SetInsertPoint(CRI);
1822 ToErase.push_back(CRI);
1823 IRB.CreateCleanupRet(CRI->getCleanupPad(), 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(PoisonValue::get(PN.getType()), 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(PN.getType(), PN.getName());
1855 for (unsigned Idx = 0, E = PN.getNumIncomingValues(); Idx != E; ++Idx) {
1856 if (NewPreds.contains(PN.getIncomingBlock(Idx)))
1857 continue;
1858 Value *V = PN.getIncomingValue(Idx);
1859 if (auto *II = dyn_cast<InvokeInst>(V))
1860 SSA.AddAvailableValue(II->getNormalDest(), II);
1861 else if (auto *I = dyn_cast<Instruction>(V))
1862 SSA.AddAvailableValue(I->getParent(), I);
1863 else
1864 SSA.AddAvailableValue(PN.getIncomingBlock(Idx), V);
1865 }
1866 for (auto *NewPred : NewPreds)
1867 PN.setIncomingValueForBlock(NewPred, SSA.GetValueAtEndOfBlock(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
1884 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
1885 EnableEmEH, [&](Function &F) -> DominatorTree & {
1886 return MAM.getResult<FunctionAnalysisManagerModuleProxy>(M)
1887 .getManager()
1888 .getResult<DominatorTreeAnalysis>(F);
1889 });
1890 return Impl.runOnModule(M) ? PreservedAnalyses::none()
1892}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
Memory SSA
Definition MemorySSA.cpp:73
uint64_t IntrinsicInst * II
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
cl::opt< bool > WasmEnableSjLj
cl::opt< bool > WasmEnableEmSjLj
static void nullifySetjmp(Function *F)
static void markAsImported(Function *F)
static bool canLongjmp(const Value *Callee)
static cl::list< std::string > EHAllowlist("emscripten-cxx-exceptions-allowed", cl::desc("The list of function names in which Emscripten-style " "exception handling is enabled (see emscripten " "EMSCRIPTEN_CATCHING_ALLOWED options)"), cl::CommaSeparated)
static bool hasEHTargetFeatureAttr(const Function &F)
static Type * getAddrPtrType(Module *M)
static std::string getSignature(FunctionType *FTy)
static Type * getAddrIntType(Module *M)
static bool canThrow(const Value *V)
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore, DISubprogram *SP)
static bool containsLongjmpableCalls(const Function *F)
static GlobalVariable * getGlobalVariable(Module &M, Type *Ty, const char *Name)
static Value * getAddrSizeInt(Module *M, uint64_t C)
static bool isEmAsmCall(const Value *Callee)
This file declares the WebAssembly-specific subclass of TargetMachine.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
static BasicBlock * getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad)
AnalysisUsage & addRequired()
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction & back() const
Definition BasicBlock.h:471
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
FunctionType * getFunctionType() const
void removeFnAttr(Attribute::AttrKind Kind)
Removes the attribute from the function.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
LLVM_ABI void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction... Note: This action invalidates handler_end().
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
Subprogram description. Uses SubclassData1.
A debug info location.
Definition DebugLoc.h:126
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:644
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
const Function & getFunction() const
Definition Function.h:167
void setDoesNotThrow()
Definition Function.h:580
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:544
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:474
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
Definition IRBuilder.h:484
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:446
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
Changed
Pass manager infrastructure for declaring and invalidating analyses.
cl::opt< bool > WasmEnableSjLj
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Entry
Definition COFF.h:862
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI StringRef getEHPersonalityName(EHPersonality Pers)
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
Definition Local.cpp:2636
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition Local.cpp:2612
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
ModulePass * createWebAssemblyLowerEmscriptenEHSjLjLegacyPass(bool EnableEmEH)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:34
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
@ Or
Bitwise or logical OR of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool isSpace(char C)
Checks whether character C is whitespace in the "C" locale.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39