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->getContext());
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->getContext());
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 LLVMContext &C = LongjmpF->getParent()->getContext();
858 IRBuilder<> IRB(C);
859
860 // For calls to longjmp, replace it with emscripten_longjmp/__wasm_longjmp and
861 // cast its first argument (jmp_buf*) appropriately
862 for (User *U : LongjmpF->users()) {
863 auto *CI = dyn_cast<CallInst>(U);
864 if (CI && CI->getCalledFunction() == LongjmpF) {
865 IRB.SetInsertPoint(CI);
866 Value *Env = nullptr;
867 if (NewF == EmLongjmpF)
868 Env =
869 IRB.CreatePtrToInt(CI->getArgOperand(0), getAddrIntType(M), "env");
870 else // WasmLongjmpF
871 Env = IRB.CreateBitCast(CI->getArgOperand(0), IRB.getPtrTy(), "env");
872 IRB.CreateCall(NewF, {Env, CI->getArgOperand(1)});
873 ToErase.push_back(CI);
874 }
875 }
876 for (auto *I : ToErase)
877 I->eraseFromParent();
878
879 // If we have any remaining uses of longjmp's function pointer, replace it
880 // with (void(*)(jmp_buf*, int))emscripten_longjmp / __wasm_longjmp.
881 if (!LongjmpF->uses().empty()) {
882 Value *NewLongjmp =
883 IRB.CreateBitCast(NewF, LongjmpF->getType(), "longjmp.cast");
884 LongjmpF->replaceAllUsesWith(NewLongjmp);
885 }
886}
887
889 for (const auto &BB : *F)
890 for (const auto &I : BB)
891 if (const auto *CB = dyn_cast<CallBase>(&I))
892 if (canLongjmp(CB->getCalledOperand()))
893 return true;
894 return false;
895}
896
897// When a function contains a setjmp call but not other calls that can longjmp,
898// we don't do setjmp transformation for that setjmp. But we need to convert the
899// setjmp calls into "i32 0" so they don't cause link time errors. setjmp always
900// returns 0 when called directly.
901static void nullifySetjmp(Function *F) {
902 Module &M = *F->getParent();
903 IRBuilder<> IRB(M.getContext());
904 Function *SetjmpF = M.getFunction("setjmp");
906
907 for (User *U : make_early_inc_range(SetjmpF->users())) {
908 auto *CB = cast<CallBase>(U);
909 BasicBlock *BB = CB->getParent();
910 if (BB->getParent() != F) // in other function
911 continue;
912 CallInst *CI = nullptr;
913 // setjmp cannot throw. So if it is an invoke, lower it to a call
914 if (auto *II = dyn_cast<InvokeInst>(CB))
916 else
917 CI = cast<CallInst>(CB);
918 ToErase.push_back(CI);
919 CI->replaceAllUsesWith(IRB.getInt32(0));
920 }
921 for (auto *I : ToErase)
922 I->eraseFromParent();
923}
924
925bool WebAssemblyLowerEmscriptenEHSjLjImpl::runOnModule(Module &M) {
926 LLVM_DEBUG(dbgs() << "********** Lower Emscripten EH & SjLj **********\n");
927
928 // The Emscripten EH model may come from the "exception-model" module flag
929 // (e.g. when this pass is run standalone via opt) in addition to being
930 // threaded in from the TargetMachine.
931 EnableEmEH |= M.getExceptionModel() == ExceptionHandling::Emscripten;
932
933 LLVMContext &C = M.getContext();
934 IRBuilder<> IRB(C);
935
936 Function *SetjmpF = M.getFunction("setjmp");
937 Function *LongjmpF = M.getFunction("longjmp");
938
939 // In some platforms _setjmp and _longjmp are used instead. Change these to
940 // use setjmp/longjmp instead, because we later detect these functions by
941 // their names.
942 Function *SetjmpF2 = M.getFunction("_setjmp");
943 Function *LongjmpF2 = M.getFunction("_longjmp");
944 if (SetjmpF2) {
945 if (SetjmpF) {
946 if (SetjmpF->getFunctionType() != SetjmpF2->getFunctionType())
947 report_fatal_error("setjmp and _setjmp have different function types");
948 } else {
949 SetjmpF = Function::Create(SetjmpF2->getFunctionType(),
950 GlobalValue::ExternalLinkage, "setjmp", M);
951 }
952 SetjmpF2->replaceAllUsesWith(SetjmpF);
953 }
954 if (LongjmpF2) {
955 if (LongjmpF) {
956 if (LongjmpF->getFunctionType() != LongjmpF2->getFunctionType())
958 "longjmp and _longjmp have different function types");
959 } else {
960 LongjmpF = Function::Create(LongjmpF2->getFunctionType(),
961 GlobalValue::ExternalLinkage, "setjmp", M);
962 }
963 LongjmpF2->replaceAllUsesWith(LongjmpF);
964 }
965
966 // Declare (or get) global variables __THREW__, __threwValue, and
967 // getTempRet0/setTempRet0 function which are used in common for both
968 // exception handling and setjmp/longjmp handling
969 ThrewGV = getGlobalVariable(M, getAddrIntType(&M), "__THREW__");
970 ThrewValueGV = getGlobalVariable(M, IRB.getInt32Ty(), "__threwValue");
971 GetTempRet0F = getFunction(FunctionType::get(IRB.getInt32Ty(), false),
972 "getTempRet0", &M);
973 SetTempRet0F =
974 getFunction(FunctionType::get(IRB.getVoidTy(), IRB.getInt32Ty(), false),
975 "setTempRet0", &M);
976 GetTempRet0F->setDoesNotThrow();
977 SetTempRet0F->setDoesNotThrow();
978
979 bool Changed = false;
980
981 // Function registration for exception handling
982 if (EnableEmEH) {
983 // Register __resumeException function
984 FunctionType *ResumeFTy =
985 FunctionType::get(IRB.getVoidTy(), IRB.getPtrTy(), false);
986 ResumeF = getFunction(ResumeFTy, "__resumeException", &M);
987 ResumeF->addFnAttr(Attribute::NoReturn);
988
989 // Register llvm_eh_typeid_for function
990 FunctionType *EHTypeIDTy =
991 FunctionType::get(IRB.getInt32Ty(), IRB.getPtrTy(), false);
992 EHTypeIDF = getFunction(EHTypeIDTy, "llvm_eh_typeid_for", &M);
993 }
994
995 // Functions that contains calls to setjmp but don't have other longjmpable
996 // calls within them.
997 SmallPtrSet<Function *, 4> SetjmpUsersToNullify;
998
999 if ((EnableEmSjLj || EnableWasmSjLj) && SetjmpF) {
1000 // Precompute setjmp users
1001 for (User *U : SetjmpF->users()) {
1002 if (auto *CB = dyn_cast<CallBase>(U)) {
1003 auto *UserF = CB->getFunction();
1004 // If a function that calls setjmp does not contain any other calls that
1005 // can longjmp, we don't need to do any transformation on that function,
1006 // so can ignore it
1007 if (containsLongjmpableCalls(UserF))
1008 SetjmpUsers.insert(UserF);
1009 else
1010 SetjmpUsersToNullify.insert(UserF);
1011 } else {
1012 std::string S;
1013 raw_string_ostream SS(S);
1014 SS << *U;
1015 report_fatal_error(Twine("Indirect use of setjmp is not supported: ") +
1016 SS.str());
1017 }
1018 }
1019 }
1020
1021 bool SetjmpUsed = SetjmpF && !SetjmpUsers.empty();
1022 bool LongjmpUsed = LongjmpF && !LongjmpF->use_empty();
1023 DoSjLj = (EnableEmSjLj | EnableWasmSjLj) && (SetjmpUsed || LongjmpUsed);
1024
1025 // Function registration and data pre-gathering for setjmp/longjmp handling
1026 if (DoSjLj) {
1027 assert(EnableEmSjLj || EnableWasmSjLj);
1028
1029 if (EnableEmSjLj) {
1030 // Register emscripten_longjmp function
1031 FunctionType *FTy = FunctionType::get(
1032 IRB.getVoidTy(), {getAddrIntType(&M), IRB.getInt32Ty()}, false);
1033 EmLongjmpF = getFunction(FTy, "emscripten_longjmp", &M);
1034 EmLongjmpF->addFnAttr(Attribute::NoReturn);
1035 } else { // EnableWasmSjLj
1036 Type *Int8PtrTy = IRB.getPtrTy();
1037 // Register __wasm_longjmp function, which calls __builtin_wasm_longjmp.
1038 FunctionType *FTy = FunctionType::get(
1039 IRB.getVoidTy(), {Int8PtrTy, IRB.getInt32Ty()}, false);
1040 WasmLongjmpF = getFunction(FTy, "__wasm_longjmp", &M);
1041 WasmLongjmpF->addFnAttr(Attribute::NoReturn);
1042 }
1043
1044 if (EnableWasmSjLj) {
1045 for (auto *SjLjF : {SetjmpF, LongjmpF}) {
1046 if (SjLjF) {
1047 for (User *U : SjLjF->users()) {
1048 if (auto *CI = dyn_cast<CallInst>(U)) {
1049 auto &F = *CI->getFunction();
1051 report_fatal_error("Function " + F.getName() +
1052 " is using setjmp/longjmp but does not have "
1053 "+exception-handling target feature");
1054 }
1055 }
1056 }
1057 }
1058 }
1059
1060 if (SetjmpF) {
1061 Type *Int8PtrTy = IRB.getPtrTy();
1062 Type *Int32PtrTy = IRB.getPtrTy();
1063 Type *Int32Ty = IRB.getInt32Ty();
1064
1065 // Register __wasm_setjmp function
1066 FunctionType *SetjmpFTy = SetjmpF->getFunctionType();
1067 FunctionType *FTy = FunctionType::get(
1068 IRB.getVoidTy(), {SetjmpFTy->getParamType(0), Int32Ty, Int32PtrTy},
1069 false);
1070 WasmSetjmpF = getFunction(FTy, "__wasm_setjmp", &M);
1071
1072 // Register __wasm_setjmp_test function
1073 FTy = FunctionType::get(Int32Ty, {Int32PtrTy, Int32PtrTy}, false);
1074 WasmSetjmpTestF = getFunction(FTy, "__wasm_setjmp_test", &M);
1075
1076 // wasm.catch() will be lowered down to wasm 'catch' instruction in
1077 // instruction selection.
1078 CatchF = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_catch);
1079 // Type for struct __WasmLongjmpArgs
1080 LongjmpArgsTy = StructType::get(Int8PtrTy, // env
1081 Int32Ty // val
1082 );
1083 }
1084 }
1085
1086 // Exception handling transformation
1087 if (EnableEmEH) {
1088 for (Function &F : M) {
1089 if (F.isDeclaration())
1090 continue;
1091 Changed |= runEHOnFunction(F);
1092 }
1093 }
1094
1095 // Setjmp/longjmp handling transformation
1096 if (DoSjLj) {
1097 Changed = true; // We have setjmp or longjmp somewhere
1098 if (LongjmpF)
1099 replaceLongjmpWith(LongjmpF, EnableEmSjLj ? EmLongjmpF : WasmLongjmpF);
1100 // Only traverse functions that uses setjmp in order not to insert
1101 // unnecessary prep / cleanup code in every function
1102 if (SetjmpF)
1103 for (Function *F : SetjmpUsers)
1104 runSjLjOnFunction(*F);
1105 }
1106
1107 // Replace unnecessary setjmp calls with 0
1108 if ((EnableEmSjLj || EnableWasmSjLj) && !SetjmpUsersToNullify.empty()) {
1109 Changed = true;
1110 assert(SetjmpF);
1111 for (Function *F : SetjmpUsersToNullify)
1113 }
1114
1115 // Delete unused global variables and functions
1116 for (auto *V : {ThrewGV, ThrewValueGV})
1117 if (V && V->use_empty())
1118 V->eraseFromParent();
1119 for (auto *V : {GetTempRet0F, SetTempRet0F, ResumeF, EHTypeIDF, EmLongjmpF,
1120 WasmSetjmpF, WasmSetjmpTestF, WasmLongjmpF, CatchF})
1121 if (V && V->use_empty())
1122 V->eraseFromParent();
1123
1124 return Changed;
1125}
1126
1127bool WebAssemblyLowerEmscriptenEHSjLjImpl::runEHOnFunction(Function &F) {
1128 Module &M = *F.getParent();
1129 LLVMContext &C = F.getContext();
1130 IRBuilder<> IRB(C);
1131 bool Changed = false;
1133 SmallPtrSet<LandingPadInst *, 32> LandingPads;
1134
1135 // rethrow.longjmp BB that will be shared within the function.
1136 BasicBlock *RethrowLongjmpBB = nullptr;
1137 // PHI node for the loaded value of __THREW__ global variable in
1138 // rethrow.longjmp BB
1139 PHINode *RethrowLongjmpBBThrewPHI = nullptr;
1140
1141 for (BasicBlock &BB : F) {
1142 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
1143 if (!II)
1144 continue;
1145 Changed = true;
1146 LandingPads.insert(II->getLandingPadInst());
1147 IRB.SetInsertPoint(II);
1148
1149 const Value *Callee = II->getCalledOperand();
1150 bool NeedInvoke = supportsException(&F) && canThrow(Callee);
1151 if (NeedInvoke) {
1152 // Wrap invoke with invoke wrapper and generate preamble/postamble
1153 Value *Threw = wrapInvoke(II);
1154 ToErase.push_back(II);
1155
1156 // If setjmp/longjmp handling is enabled, the thrown value can be not an
1157 // exception but a longjmp. If the current function contains calls to
1158 // setjmp, it will be appropriately handled in runSjLjOnFunction. But even
1159 // if the function does not contain setjmp calls, we shouldn't silently
1160 // ignore longjmps; we should rethrow them so they can be correctly
1161 // handled in somewhere up the call chain where setjmp is. __THREW__'s
1162 // value is 0 when nothing happened, 1 when an exception is thrown, and
1163 // other values when longjmp is thrown.
1164 //
1165 // if (%__THREW__.val == 0 || %__THREW__.val == 1)
1166 // goto %tail
1167 // else
1168 // goto %longjmp.rethrow
1169 //
1170 // rethrow.longjmp: ;; This is longjmp. Rethrow it
1171 // %__threwValue.val = __threwValue
1172 // emscripten_longjmp(%__THREW__.val, %__threwValue.val);
1173 //
1174 // tail: ;; Nothing happened or an exception is thrown
1175 // ... Continue exception handling ...
1176 if (DoSjLj && EnableEmSjLj && !SetjmpUsers.count(&F) &&
1177 canLongjmp(Callee)) {
1178 // Create longjmp.rethrow BB once and share it within the function
1179 if (!RethrowLongjmpBB) {
1180 RethrowLongjmpBB = BasicBlock::Create(C, "rethrow.longjmp", &F);
1181 IRB.SetInsertPoint(RethrowLongjmpBB);
1182 RethrowLongjmpBBThrewPHI =
1183 IRB.CreatePHI(getAddrIntType(&M), 4, "threw.phi");
1184 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1185 Value *ThrewValue = IRB.CreateLoad(IRB.getInt32Ty(), ThrewValueGV,
1186 ThrewValueGV->getName() + ".val");
1187 IRB.CreateCall(EmLongjmpF, {RethrowLongjmpBBThrewPHI, ThrewValue});
1188 IRB.CreateUnreachable();
1189 } else {
1190 RethrowLongjmpBBThrewPHI->addIncoming(Threw, &BB);
1191 }
1192
1193 IRB.SetInsertPoint(II); // Restore the insert point back
1194 BasicBlock *Tail = BasicBlock::Create(C, "tail", &F);
1195 Value *CmpEqOne =
1196 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1197 Value *CmpEqZero =
1198 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 0), "cmp.eq.zero");
1199 Value *Or = IRB.CreateOr(CmpEqZero, CmpEqOne, "or");
1200 IRB.CreateCondBr(Or, Tail, RethrowLongjmpBB);
1201 IRB.SetInsertPoint(Tail);
1202 BB.replaceSuccessorsPhiUsesWith(&BB, Tail);
1203 }
1204
1205 // Insert a branch based on __THREW__ variable
1206 Value *Cmp = IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp");
1207 IRB.CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
1208
1209 } else {
1210 // This can't throw, and we don't need this invoke, just replace it with a
1211 // call+branch
1213 }
1214 }
1215
1216 // Process resume instructions
1217 for (BasicBlock &BB : F) {
1218 // Scan the body of the basic block for resumes
1219 for (Instruction &I : BB) {
1220 auto *RI = dyn_cast<ResumeInst>(&I);
1221 if (!RI)
1222 continue;
1223 Changed = true;
1224
1225 // Split the input into legal values
1226 Value *Input = RI->getValue();
1227 IRB.SetInsertPoint(RI);
1228 Value *Low = IRB.CreateExtractValue(Input, 0, "low");
1229 // Create a call to __resumeException function
1230 IRB.CreateCall(ResumeF, {Low});
1231 // Add a terminator to the block
1232 IRB.CreateUnreachable();
1233 ToErase.push_back(RI);
1234 }
1235 }
1236
1237 // Process llvm.eh.typeid.for intrinsics
1238 for (BasicBlock &BB : F) {
1239 for (Instruction &I : BB) {
1240 auto *CI = dyn_cast<CallInst>(&I);
1241 if (!CI)
1242 continue;
1243 const Function *Callee = CI->getCalledFunction();
1244 if (!Callee)
1245 continue;
1246 if (Callee->getIntrinsicID() != Intrinsic::eh_typeid_for)
1247 continue;
1248 Changed = true;
1249
1250 IRB.SetInsertPoint(CI);
1251 CallInst *NewCI =
1252 IRB.CreateCall(EHTypeIDF, CI->getArgOperand(0), "typeid");
1253 CI->replaceAllUsesWith(NewCI);
1254 ToErase.push_back(CI);
1255 }
1256 }
1257
1258 // Look for orphan landingpads, can occur in blocks with no predecessors
1259 for (BasicBlock &BB : F) {
1260 BasicBlock::iterator I = BB.getFirstNonPHIIt();
1261 if (auto *LPI = dyn_cast<LandingPadInst>(I))
1262 LandingPads.insert(LPI);
1263 }
1264 Changed |= !LandingPads.empty();
1265
1266 // Handle all the landingpad for this function together, as multiple invokes
1267 // may share a single lp
1268 for (LandingPadInst *LPI : LandingPads) {
1269 IRB.SetInsertPoint(LPI);
1270 SmallVector<Value *, 16> FMCArgs;
1271 for (unsigned I = 0, E = LPI->getNumClauses(); I < E; ++I) {
1272 Constant *Clause = LPI->getClause(I);
1273 // TODO Handle filters (= exception specifications).
1274 // https://github.com/llvm/llvm-project/issues/49740
1275 if (LPI->isCatch(I))
1276 FMCArgs.push_back(Clause);
1277 }
1278
1279 // Create a call to __cxa_find_matching_catch_N function
1280 Function *FMCF = getFindMatchingCatch(M, FMCArgs.size());
1281 CallInst *FMCI = IRB.CreateCall(FMCF, FMCArgs, "fmc");
1282 Value *Poison = PoisonValue::get(LPI->getType());
1283 Value *Pair0 = IRB.CreateInsertValue(Poison, FMCI, 0, "pair0");
1284 Value *TempRet0 = IRB.CreateCall(GetTempRet0F, {}, "tempret0");
1285 Value *Pair1 = IRB.CreateInsertValue(Pair0, TempRet0, 1, "pair1");
1286
1287 LPI->replaceAllUsesWith(Pair1);
1288 ToErase.push_back(LPI);
1289 }
1290
1291 // Erase everything we no longer need in this function
1292 for (Instruction *I : ToErase)
1293 I->eraseFromParent();
1294
1295 return Changed;
1296}
1297
1298// This tries to get debug info from the instruction before which a new
1299// instruction will be inserted, and if there's no debug info in that
1300// instruction, tries to get the info instead from the previous instruction (if
1301// any). If none of these has debug info and a DISubprogram is provided, it
1302// creates a dummy debug info with the first line of the function, because IR
1303// verifier requires all inlinable callsites should have debug info when both a
1304// caller and callee have DISubprogram. If none of these conditions are met,
1305// returns empty info.
1306static DebugLoc getOrCreateDebugLoc(const Instruction *InsertBefore,
1307 DISubprogram *SP) {
1308 assert(InsertBefore);
1309 if (InsertBefore->getDebugLoc())
1310 return InsertBefore->getDebugLoc();
1311 const Instruction *Prev = InsertBefore->getPrevNode();
1312 if (Prev && Prev->getDebugLoc())
1313 return Prev->getDebugLoc();
1314 if (SP)
1315 return DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
1316 return DebugLoc();
1317}
1318
1319bool WebAssemblyLowerEmscriptenEHSjLjImpl::runSjLjOnFunction(Function &F) {
1320 assert(EnableEmSjLj || EnableWasmSjLj);
1321 Module &M = *F.getParent();
1322 LLVMContext &C = F.getContext();
1323 IRBuilder<> IRB(C);
1325
1326 // Setjmp preparation
1327
1328 SmallVector<AllocaInst *> StaticAllocas;
1329 for (Instruction &I : F.getEntryBlock())
1330 if (auto *AI = dyn_cast<AllocaInst>(&I))
1331 if (AI->isStaticAlloca())
1332 StaticAllocas.push_back(AI);
1333
1334 BasicBlock *Entry = &F.getEntryBlock();
1335 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1336 SplitBlock(Entry, &*Entry->getFirstInsertionPt());
1337
1338 // Move static allocas back into the entry block, so they stay static.
1339 for (AllocaInst *AI : StaticAllocas)
1340 AI->moveBefore(Entry->getTerminator()->getIterator());
1341
1342 IRB.SetInsertPoint(Entry->getTerminator()->getIterator());
1343 // This alloca'ed pointer is used by the runtime to identify function
1344 // invocations. It's just for pointer comparisons. It will never be
1345 // dereferenced.
1346 Instruction *FunctionInvocationId =
1347 IRB.CreateAlloca(IRB.getInt32Ty(), nullptr, "functionInvocationId");
1348 FunctionInvocationId->setDebugLoc(FirstDL);
1349
1350 // Setjmp transformation
1351 SmallVector<PHINode *, 4> SetjmpRetPHIs;
1352 Function *SetjmpF = M.getFunction("setjmp");
1353 for (auto *U : make_early_inc_range(SetjmpF->users())) {
1354 auto *CB = cast<CallBase>(U);
1355 BasicBlock *BB = CB->getParent();
1356 if (BB->getParent() != &F) // in other function
1357 continue;
1358 if (CB->getOperandBundle(LLVMContext::OB_funclet)) {
1359 std::string S;
1360 raw_string_ostream SS(S);
1361 SS << "In function " + F.getName() +
1362 ": setjmp within a catch clause is not supported in Wasm EH:\n";
1363 SS << *CB;
1364 report_fatal_error(StringRef(SS.str()));
1365 }
1366
1367 CallInst *CI = nullptr;
1368 // setjmp cannot throw. So if it is an invoke, lower it to a call
1369 if (auto *II = dyn_cast<InvokeInst>(CB))
1370 CI = llvm::changeToCall(II);
1371 else
1372 CI = cast<CallInst>(CB);
1373
1374 // The tail is everything right after the call, and will be reached once
1375 // when setjmp is called, and later when longjmp returns to the setjmp
1376 BasicBlock *Tail = SplitBlock(BB, CI->getNextNode());
1377 // Add a phi to the tail, which will be the output of setjmp, which
1378 // indicates if this is the first call or a longjmp back. The phi directly
1379 // uses the right value based on where we arrive from
1380 IRB.SetInsertPoint(Tail, Tail->getFirstNonPHIIt());
1381 PHINode *SetjmpRet = IRB.CreatePHI(IRB.getInt32Ty(), 2, "setjmp.ret");
1382
1383 // setjmp initial call returns 0
1384 SetjmpRet->addIncoming(IRB.getInt32(0), BB);
1385 // The proper output is now this, not the setjmp call itself
1386 CI->replaceAllUsesWith(SetjmpRet);
1387 // longjmp returns to the setjmp will add themselves to this phi
1388 SetjmpRetPHIs.push_back(SetjmpRet);
1389
1390 // Fix call target
1391 // Our index in the function is our place in the array + 1 to avoid index
1392 // 0, because index 0 means the longjmp is not ours to handle.
1393 IRB.SetInsertPoint(CI);
1394 Value *Args[] = {CI->getArgOperand(0), IRB.getInt32(SetjmpRetPHIs.size()),
1395 FunctionInvocationId};
1396 IRB.CreateCall(WasmSetjmpF, Args);
1397 ToErase.push_back(CI);
1398 }
1399
1400 // Handle longjmpable calls.
1401 if (EnableEmSjLj)
1402 handleLongjmpableCallsForEmscriptenSjLj(F, FunctionInvocationId,
1403 SetjmpRetPHIs);
1404 else // EnableWasmSjLj
1405 handleLongjmpableCallsForWasmSjLj(F, FunctionInvocationId, SetjmpRetPHIs);
1406
1407 // Erase everything we no longer need in this function
1408 for (Instruction *I : ToErase)
1409 I->eraseFromParent();
1410
1411 // Finally, our modifications to the cfg can break dominance of SSA variables.
1412 // For example, in this code,
1413 // if (x()) { .. setjmp() .. }
1414 // if (y()) { .. longjmp() .. }
1415 // We must split the longjmp block, and it can jump into the block split from
1416 // setjmp one. But that means that when we split the setjmp block, it's first
1417 // part no longer dominates its second part - there is a theoretically
1418 // possible control flow path where x() is false, then y() is true and we
1419 // reach the second part of the setjmp block, without ever reaching the first
1420 // part. So, we rebuild SSA form here.
1421 rebuildSSA(F);
1422 return true;
1423}
1424
1425// Update each call that can longjmp so it can return to the corresponding
1426// setjmp. Refer to 4) of "Emscripten setjmp/longjmp handling" section in the
1427// comments at top of the file for details.
1428void WebAssemblyLowerEmscriptenEHSjLjImpl::
1429 handleLongjmpableCallsForEmscriptenSjLj(
1430 Function &F, Instruction *FunctionInvocationId,
1431 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1432 Module &M = *F.getParent();
1433 LLVMContext &C = F.getContext();
1434 IRBuilder<> IRB(C);
1436
1437 // call.em.longjmp BB that will be shared within the function.
1438 BasicBlock *CallEmLongjmpBB = nullptr;
1439 // PHI node for the loaded value of __THREW__ global variable in
1440 // call.em.longjmp BB
1441 PHINode *CallEmLongjmpBBThrewPHI = nullptr;
1442 // PHI node for the loaded value of __threwValue global variable in
1443 // call.em.longjmp BB
1444 PHINode *CallEmLongjmpBBThrewValuePHI = nullptr;
1445 // rethrow.exn BB that will be shared within the function.
1446 BasicBlock *RethrowExnBB = nullptr;
1447
1448 // Because we are creating new BBs while processing and don't want to make
1449 // all these newly created BBs candidates again for longjmp processing, we
1450 // first make the vector of candidate BBs.
1451 std::vector<BasicBlock *> BBs;
1452 for (BasicBlock &BB : F)
1453 BBs.push_back(&BB);
1454
1455 // BBs.size() will change within the loop, so we query it every time
1456 for (unsigned I = 0; I < BBs.size(); I++) {
1457 BasicBlock *BB = BBs[I];
1458 for (Instruction &I : *BB) {
1459 if (isa<InvokeInst>(&I)) {
1460 std::string S;
1461 raw_string_ostream SS(S);
1462 SS << "In function " << F.getName()
1463 << ": When using Wasm EH with Emscripten SjLj, there is a "
1464 "restriction that `setjmp` function call and exception cannot be "
1465 "used within the same function:\n";
1466 SS << I;
1467 report_fatal_error(StringRef(SS.str()));
1468 }
1469 auto *CI = dyn_cast<CallInst>(&I);
1470 if (!CI)
1471 continue;
1472
1473 const Value *Callee = CI->getCalledOperand();
1474 if (!canLongjmp(Callee))
1475 continue;
1476 if (isEmAsmCall(Callee))
1477 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1478 F.getName() +
1479 ". Please consider using EM_JS, or move the "
1480 "EM_ASM into another function.",
1481 false);
1482
1483 Value *Threw = nullptr;
1485 if (Callee->getName().starts_with("__invoke_")) {
1486 // If invoke wrapper has already been generated for this call in
1487 // previous EH phase, search for the load instruction
1488 // %__THREW__.val = __THREW__;
1489 // in postamble after the invoke wrapper call
1490 LoadInst *ThrewLI = nullptr;
1491 StoreInst *ThrewResetSI = nullptr;
1492 for (auto I = std::next(BasicBlock::iterator(CI)), IE = BB->end();
1493 I != IE; ++I) {
1494 if (auto *LI = dyn_cast<LoadInst>(I))
1495 if (auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
1496 if (GV == ThrewGV) {
1497 Threw = ThrewLI = LI;
1498 break;
1499 }
1500 }
1501 // Search for the store instruction after the load above
1502 // __THREW__ = 0;
1503 for (auto I = std::next(BasicBlock::iterator(ThrewLI)), IE = BB->end();
1504 I != IE; ++I) {
1505 if (auto *SI = dyn_cast<StoreInst>(I)) {
1506 if (auto *GV = dyn_cast<GlobalVariable>(SI->getPointerOperand())) {
1507 if (GV == ThrewGV &&
1508 SI->getValueOperand() == getAddrSizeInt(&M, 0)) {
1509 ThrewResetSI = SI;
1510 break;
1511 }
1512 }
1513 }
1514 }
1515 assert(Threw && ThrewLI && "Cannot find __THREW__ load after invoke");
1516 assert(ThrewResetSI && "Cannot find __THREW__ store after invoke");
1517 Tail = SplitBlock(BB, ThrewResetSI->getNextNode());
1518
1519 } else {
1520 // Wrap call with invoke wrapper and generate preamble/postamble
1521 Threw = wrapInvoke(CI);
1522 ToErase.push_back(CI);
1523 Tail = SplitBlock(BB, CI->getNextNode());
1524
1525 // If exception handling is enabled, the thrown value can be not a
1526 // longjmp but an exception, in which case we shouldn't silently ignore
1527 // exceptions; we should rethrow them.
1528 // __THREW__'s value is 0 when nothing happened, 1 when an exception is
1529 // thrown, other values when longjmp is thrown.
1530 //
1531 // if (%__THREW__.val == 1)
1532 // goto %eh.rethrow
1533 // else
1534 // goto %normal
1535 //
1536 // eh.rethrow: ;; Rethrow exception
1537 // %exn = call @__cxa_find_matching_catch_2() ;; Retrieve thrown ptr
1538 // __resumeException(%exn)
1539 //
1540 // normal:
1541 // <-- Insertion point. Will insert sjlj handling code from here
1542 // goto %tail
1543 //
1544 // tail:
1545 // ...
1546 if (supportsException(&F) && canThrow(Callee)) {
1547 // We will add a new conditional branch. So remove the branch created
1548 // when we split the BB
1549 ToErase.push_back(BB->getTerminator());
1550
1551 // Generate rethrow.exn BB once and share it within the function
1552 if (!RethrowExnBB) {
1553 RethrowExnBB = BasicBlock::Create(C, "rethrow.exn", &F);
1554 IRB.SetInsertPoint(RethrowExnBB);
1555 CallInst *Exn =
1556 IRB.CreateCall(getFindMatchingCatch(M, 0), {}, "exn");
1557 IRB.CreateCall(ResumeF, {Exn});
1558 IRB.CreateUnreachable();
1559 }
1560
1561 IRB.SetInsertPoint(CI);
1562 BasicBlock *NormalBB = BasicBlock::Create(C, "normal", &F);
1563 Value *CmpEqOne =
1564 IRB.CreateICmpEQ(Threw, getAddrSizeInt(&M, 1), "cmp.eq.one");
1565 IRB.CreateCondBr(CmpEqOne, RethrowExnBB, NormalBB);
1566
1567 IRB.SetInsertPoint(NormalBB);
1568 IRB.CreateBr(Tail);
1569 BB = NormalBB; // New insertion point to insert __wasm_setjmp_test()
1570 }
1571 }
1572
1573 // We need to replace the terminator in Tail - SplitBlock makes BB go
1574 // straight to Tail, we need to check if a longjmp occurred, and go to the
1575 // right setjmp-tail if so
1576 ToErase.push_back(BB->getTerminator());
1577
1578 // Generate a function call to __wasm_setjmp_test function and
1579 // preamble/postamble code to figure out (1) whether longjmp
1580 // occurred (2) if longjmp occurred, which setjmp it corresponds to
1581 Value *Label = nullptr;
1582 Value *LongjmpResult = nullptr;
1583 BasicBlock *EndBB = nullptr;
1584 wrapTestSetjmp(BB, CI->getDebugLoc(), Threw, FunctionInvocationId, Label,
1585 LongjmpResult, CallEmLongjmpBB, CallEmLongjmpBBThrewPHI,
1586 CallEmLongjmpBBThrewValuePHI, EndBB);
1587 assert(Label && LongjmpResult && EndBB);
1588
1589 // Create switch instruction
1590 IRB.SetInsertPoint(EndBB);
1591 IRB.SetCurrentDebugLocation(EndBB->back().getDebugLoc());
1592 SwitchInst *SI = IRB.CreateSwitch(Label, Tail, SetjmpRetPHIs.size());
1593 // -1 means no longjmp happened, continue normally (will hit the default
1594 // switch case). 0 means a longjmp that is not ours to handle, needs a
1595 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1596 // 0).
1597 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1598 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1599 SetjmpRetPHIs[I]->addIncoming(LongjmpResult, EndBB);
1600 }
1601
1602 // We are splitting the block here, and must continue to find other calls
1603 // in the block - which is now split. so continue to traverse in the Tail
1604 BBs.push_back(Tail);
1605 }
1606 }
1607
1608 for (Instruction *I : ToErase)
1609 I->eraseFromParent();
1610}
1611
1613 for (const User *U : CPI->users())
1614 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
1615 return CRI->getUnwindDest();
1616 return nullptr;
1617}
1618
1619// Create a catchpad in which we catch a longjmp's env and val arguments, test
1620// if the longjmp corresponds to one of setjmps in the current function, and if
1621// so, jump to the setjmp dispatch BB from which we go to one of post-setjmp
1622// BBs. Refer to 4) of "Wasm setjmp/longjmp handling" section in the comments at
1623// top of the file for details.
1624void WebAssemblyLowerEmscriptenEHSjLjImpl::handleLongjmpableCallsForWasmSjLj(
1625 Function &F, Instruction *FunctionInvocationId,
1626 SmallVectorImpl<PHINode *> &SetjmpRetPHIs) {
1627 Module &M = *F.getParent();
1628 LLVMContext &C = F.getContext();
1629 IRBuilder<> IRB(C);
1630
1631 // A function with catchswitch/catchpad instruction should have a personality
1632 // function attached to it. Search for the wasm personality function, and if
1633 // it exists, use it, and if it doesn't, create a dummy personality function.
1634 // (SjLj is not going to call it anyway.)
1635 if (!F.hasPersonalityFn()) {
1636 StringRef PersName = getEHPersonalityName(EHPersonality::Wasm_CXX);
1637 FunctionType *PersType =
1638 FunctionType::get(IRB.getInt32Ty(), /* isVarArg */ true);
1639 Value *PersF = M.getOrInsertFunction(PersName, PersType).getCallee();
1640 F.setPersonalityFn(
1641 cast<Constant>(IRB.CreateBitCast(PersF, IRB.getPtrTy())));
1642 }
1643
1644 // Use the entry BB's debugloc as a fallback
1645 BasicBlock *Entry = &F.getEntryBlock();
1646 DebugLoc FirstDL = getOrCreateDebugLoc(&*Entry->begin(), F.getSubprogram());
1647 IRB.SetCurrentDebugLocation(FirstDL);
1648
1649 // Add setjmp.dispatch BB right after the entry block. Because we have
1650 // initialized functionInvocationId in the entry block and split the
1651 // rest into another BB, here 'OrigEntry' is the function's original entry
1652 // block before the transformation.
1653 //
1654 // entry:
1655 // functionInvocationId initialization
1656 // setjmp.dispatch:
1657 // switch will be inserted here later
1658 // entry.split: (OrigEntry)
1659 // the original function starts here
1660 BasicBlock *OrigEntry = Entry->getNextNode();
1661 BasicBlock *SetjmpDispatchBB =
1662 BasicBlock::Create(C, "setjmp.dispatch", &F, OrigEntry);
1663 cast<UncondBrInst>(Entry->getTerminator())->setSuccessor(SetjmpDispatchBB);
1664
1665 // Create catch.dispatch.longjmp BB and a catchswitch instruction
1666 BasicBlock *CatchDispatchLongjmpBB =
1667 BasicBlock::Create(C, "catch.dispatch.longjmp", &F);
1668 IRB.SetInsertPoint(CatchDispatchLongjmpBB);
1669 CatchSwitchInst *CatchSwitchLongjmp =
1670 IRB.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1);
1671
1672 // Create catch.longjmp BB and a catchpad instruction
1673 BasicBlock *CatchLongjmpBB = BasicBlock::Create(C, "catch.longjmp", &F);
1674 CatchSwitchLongjmp->addHandler(CatchLongjmpBB);
1675 IRB.SetInsertPoint(CatchLongjmpBB);
1676 CatchPadInst *CatchPad = IRB.CreateCatchPad(CatchSwitchLongjmp, {});
1677
1678 // Wasm throw and catch instructions can throw and catch multiple values, but
1679 // that requires multivalue support in the toolchain, which is currently not
1680 // very reliable. We instead throw and catch a pointer to a struct value of
1681 // type 'struct __WasmLongjmpArgs', which is defined in Emscripten.
1682 Instruction *LongjmpArgs =
1683 IRB.CreateCall(CatchF, {IRB.getInt32(WebAssembly::C_LONGJMP)}, "thrown");
1684 Value *EnvField =
1685 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 0, "env_gep");
1686 Value *ValField =
1687 IRB.CreateConstGEP2_32(LongjmpArgsTy, LongjmpArgs, 0, 1, "val_gep");
1688 // void *env = __wasm_longjmp_args.env;
1689 Instruction *Env = IRB.CreateLoad(IRB.getPtrTy(), EnvField, "env");
1690 // int val = __wasm_longjmp_args.val;
1691 Instruction *Val = IRB.CreateLoad(IRB.getInt32Ty(), ValField, "val");
1692
1693 // %label = __wasm_setjmp_test(%env, functionInvocatinoId);
1694 // if (%label == 0)
1695 // __wasm_longjmp(%env, %val)
1696 // catchret to %setjmp.dispatch
1697 BasicBlock *ThenBB = BasicBlock::Create(C, "if.then", &F);
1698 BasicBlock *EndBB = BasicBlock::Create(C, "if.end", &F);
1699 Value *EnvP = IRB.CreateBitCast(Env, getAddrPtrType(&M), "env.p");
1700 Value *Label = IRB.CreateCall(WasmSetjmpTestF, {EnvP, FunctionInvocationId},
1701 OperandBundleDef("funclet", CatchPad), "label");
1702 Value *Cmp = IRB.CreateICmpEQ(Label, IRB.getInt32(0));
1703 IRB.CreateCondBr(Cmp, ThenBB, EndBB);
1704
1705 IRB.SetInsertPoint(ThenBB);
1706 CallInst *WasmLongjmpCI = IRB.CreateCall(
1707 WasmLongjmpF, {Env, Val}, OperandBundleDef("funclet", CatchPad));
1708 IRB.CreateUnreachable();
1709
1710 IRB.SetInsertPoint(EndBB);
1711 // Jump to setjmp.dispatch block
1712 IRB.CreateCatchRet(CatchPad, SetjmpDispatchBB);
1713
1714 // Go back to setjmp.dispatch BB
1715 // setjmp.dispatch:
1716 // switch %label {
1717 // label 1: goto post-setjmp BB 1
1718 // label 2: goto post-setjmp BB 2
1719 // ...
1720 // default: goto split next BB
1721 // }
1722 IRB.SetInsertPoint(SetjmpDispatchBB);
1723 PHINode *LabelPHI = IRB.CreatePHI(IRB.getInt32Ty(), 2, "label.phi");
1724 LabelPHI->addIncoming(Label, EndBB);
1725 LabelPHI->addIncoming(IRB.getInt32(-1), Entry);
1726 SwitchInst *SI = IRB.CreateSwitch(LabelPHI, OrigEntry, SetjmpRetPHIs.size());
1727 // -1 means no longjmp happened, continue normally (will hit the default
1728 // switch case). 0 means a longjmp that is not ours to handle, needs a
1729 // rethrow. Otherwise the index is the same as the index in P+1 (to avoid
1730 // 0).
1731 for (unsigned I = 0; I < SetjmpRetPHIs.size(); I++) {
1732 SI->addCase(IRB.getInt32(I + 1), SetjmpRetPHIs[I]->getParent());
1733 SetjmpRetPHIs[I]->addIncoming(Val, SetjmpDispatchBB);
1734 }
1735
1736 // Convert all longjmpable call instructions to invokes that unwind to the
1737 // newly created catch.dispatch.longjmp BB.
1738 SmallVector<CallInst *, 64> LongjmpableCalls;
1739 for (auto *BB = &*F.begin(); BB; BB = BB->getNextNode()) {
1740 for (auto &I : *BB) {
1741 auto *CI = dyn_cast<CallInst>(&I);
1742 if (!CI)
1743 continue;
1744 const Value *Callee = CI->getCalledOperand();
1745 if (!canLongjmp(Callee))
1746 continue;
1747 if (isEmAsmCall(Callee))
1748 report_fatal_error("Cannot use EM_ASM* alongside setjmp/longjmp in " +
1749 F.getName() +
1750 ". Please consider using EM_JS, or move the "
1751 "EM_ASM into another function.",
1752 false);
1753 // This is __wasm_longjmp() call we inserted in this function, which
1754 // rethrows the longjmp when the longjmp does not correspond to one of
1755 // setjmps in this function. We should not convert this call to an invoke.
1756 if (CI == WasmLongjmpCI)
1757 continue;
1758 LongjmpableCalls.push_back(CI);
1759 }
1760 }
1761
1762 SmallMapVector<BasicBlock *, SmallSetVector<BasicBlock *, 4>, 4>
1763 UnwindDestToNewPreds;
1764 for (auto *CI : LongjmpableCalls) {
1765 // Even if the callee function has attribute 'nounwind', which is true for
1766 // all C functions, it can longjmp, which means it can throw a Wasm
1767 // exception now.
1768 CI->removeFnAttr(Attribute::NoUnwind);
1769 if (Function *CalleeF = CI->getCalledFunction())
1770 CalleeF->removeFnAttr(Attribute::NoUnwind);
1771
1772 // Change it to an invoke and make it unwind to the catch.dispatch.longjmp
1773 // BB. If the call is enclosed in another catchpad/cleanuppad scope, unwind
1774 // to its parent pad's unwind destination instead to preserve the scope
1775 // structure. It will eventually unwind to the catch.dispatch.longjmp.
1776 BasicBlock *UnwindDest = nullptr;
1777 if (auto Bundle = CI->getOperandBundle(LLVMContext::OB_funclet)) {
1778 Instruction *FromPad = cast<Instruction>(Bundle->Inputs[0]);
1779 while (!UnwindDest) {
1780 if (auto *CPI = dyn_cast<CatchPadInst>(FromPad)) {
1781 UnwindDest = CPI->getCatchSwitch()->getUnwindDest();
1782 break;
1783 }
1784 if (auto *CPI = dyn_cast<CleanupPadInst>(FromPad)) {
1785 // getCleanupRetUnwindDest() can return nullptr when
1786 // 1. This cleanuppad's matching cleanupret uwninds to caller
1787 // 2. There is no matching cleanupret because it ends with
1788 // unreachable.
1789 // In case of 2, we need to traverse the parent pad chain.
1790 UnwindDest = getCleanupRetUnwindDest(CPI);
1791 Value *ParentPad = CPI->getParentPad();
1792 if (isa<ConstantTokenNone>(ParentPad))
1793 break;
1794 FromPad = cast<Instruction>(ParentPad);
1795 }
1796 }
1797 }
1798 if (!UnwindDest)
1799 UnwindDest = CatchDispatchLongjmpBB;
1800 // Because we are changing a longjmpable call to an invoke, its unwind
1801 // destination can be an existing EH pad that already have phis, and the BB
1802 // with the newly created invoke will become a new predecessor of that EH
1803 // pad. In this case we need to add the new predecessor to those phis.
1804 UnwindDestToNewPreds[UnwindDest].insert(CI->getParent());
1805 changeToInvokeAndSplitBasicBlock(CI, UnwindDest);
1806 }
1807
1808 SmallVector<Instruction *, 16> ToErase;
1809 for (auto &BB : F) {
1810 if (auto *CSI = dyn_cast<CatchSwitchInst>(BB.getFirstNonPHIIt())) {
1811 if (CSI != CatchSwitchLongjmp && CSI->unwindsToCaller()) {
1812 IRB.SetInsertPoint(CSI);
1813 ToErase.push_back(CSI);
1814 auto *NewCSI = IRB.CreateCatchSwitch(CSI->getParentPad(),
1815 CatchDispatchLongjmpBB, 1);
1816 NewCSI->addHandler(*CSI->handler_begin());
1817 NewCSI->takeName(CSI);
1818 CSI->replaceAllUsesWith(NewCSI);
1819 }
1820 }
1821
1822 if (auto *CRI = dyn_cast<CleanupReturnInst>(BB.getTerminator())) {
1823 if (CRI->unwindsToCaller()) {
1824 IRB.SetInsertPoint(CRI);
1825 ToErase.push_back(CRI);
1826 IRB.CreateCleanupRet(CRI->getCleanupPad(), CatchDispatchLongjmpBB);
1827 }
1828 }
1829 }
1830
1831 for (Instruction *I : ToErase)
1832 I->eraseFromParent();
1833
1834 // Add entries for new predecessors to phis in unwind destinations. We use
1835 // 'poison' as a placeholder value. We should make sure the phis have a valid
1836 // set of predecessors before running SSAUpdater, because SSAUpdater
1837 // internally can use existing phis to gather predecessor info rather than
1838 // scanning the actual CFG (See FindPredecessorBlocks in SSAUpdater.cpp for
1839 // details).
1840 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1841 for (PHINode &PN : UnwindDest->phis()) {
1842 for (auto *NewPred : NewPreds) {
1843 assert(PN.getBasicBlockIndex(NewPred) == -1);
1844 PN.addIncoming(PoisonValue::get(PN.getType()), NewPred);
1845 }
1846 }
1847 }
1848
1849 // For unwind destinations for newly added invokes to longjmpable functions,
1850 // calculate incoming values for the newly added predecessors using
1851 // SSAUpdater. We add existing values in the phis to SSAUpdater as available
1852 // values and let it calculate what the value should be at the end of new
1853 // incoming blocks.
1854 for (auto &[UnwindDest, NewPreds] : UnwindDestToNewPreds) {
1855 for (PHINode &PN : UnwindDest->phis()) {
1856 SSAUpdater SSA;
1857 SSA.Initialize(PN.getType(), PN.getName());
1858 for (unsigned Idx = 0, E = PN.getNumIncomingValues(); Idx != E; ++Idx) {
1859 if (NewPreds.contains(PN.getIncomingBlock(Idx)))
1860 continue;
1861 Value *V = PN.getIncomingValue(Idx);
1862 if (auto *II = dyn_cast<InvokeInst>(V))
1863 SSA.AddAvailableValue(II->getNormalDest(), II);
1864 else if (auto *I = dyn_cast<Instruction>(V))
1865 SSA.AddAvailableValue(I->getParent(), I);
1866 else
1867 SSA.AddAvailableValue(PN.getIncomingBlock(Idx), V);
1868 }
1869 for (auto *NewPred : NewPreds)
1870 PN.setIncomingValueForBlock(NewPred, SSA.GetValueAtEndOfBlock(NewPred));
1871 assert(PN.isComplete());
1872 }
1873 }
1874}
1875
1876bool WebAssemblyLowerEmscriptenEHSjLjLegacy::runOnModule(Module &M) {
1877 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
1878 EnableEmEH, [&](Function &F) -> DominatorTree & {
1879 return getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
1880 });
1881 return Impl.runOnModule(M);
1882}
1883
1884PreservedAnalyses
1887 WebAssemblyLowerEmscriptenEHSjLjImpl Impl(
1888 EnableEmEH, [&](Function &F) -> DominatorTree & {
1889 return MAM.getResult<FunctionAnalysisManagerModuleProxy>(M)
1890 .getManager()
1891 .getResult<DominatorTreeAnalysis>(F);
1892 });
1893 return Impl.runOnModule(M) ? PreservedAnalyses::none()
1895}
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:872
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:640
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:526
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:456
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended from a 64-bit value.
Definition IRBuilder.h:466
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2901
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
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
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:2632
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:2608
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