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