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