218 using namespace llvm;
220 #define DEBUG_TYPE "wasm-lower-em-ehsjlj" 224 cl::desc(
"The list of function names in which Emscripten-style " 225 "exception handling is enabled (see emscripten " 226 "EMSCRIPTEN_CATCHING_WHITELIST options)"),
230 class WebAssemblyLowerEmscriptenEHSjLj final :
public ModulePass {
236 Function *GetTempRet0Func =
nullptr;
237 Function *SetTempRet0Func =
nullptr;
241 Function *EmLongjmpJmpbufF =
nullptr;
251 std::set<std::string> EHWhitelistSet;
254 return "WebAssembly Lower Emscripten Exceptions";
261 template <
typename CallOrInvoke>
Value *wrapInvoke(CallOrInvoke *CI);
265 template <
typename CallOrInvoke>
Function *getInvokeWrapper(CallOrInvoke *CI);
267 bool areAllExceptionsAllowed()
const {
return EHWhitelistSet.empty(); }
268 bool canLongjmp(
Module &M,
const Value *Callee)
const;
269 bool isEmAsmCall(
Module &M,
const Value *Callee)
const;
276 WebAssemblyLowerEmscriptenEHSjLj(
bool EnableEH =
true,
bool EnableSjLj =
true)
277 :
ModulePass(ID), EnableEH(EnableEH), EnableSjLj(EnableSjLj) {
280 bool runOnModule(
Module &M)
override;
290 "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp",
295 return new WebAssemblyLowerEmscriptenEHSjLj(EnableEH, EnableSjLj);
299 if (
const auto *
F = dyn_cast<const Function>(V)) {
301 if (
F->isIntrinsic())
305 if (Name ==
"setjmp" || Name ==
"longjmp")
307 return !
F->doesNotThrow();
336 OS <<
"_" << *ParamTy;
340 Sig.erase(
remove_if(Sig, isspace), Sig.end());
353 WebAssemblyLowerEmscriptenEHSjLj::getFindMatchingCatch(
Module &M,
354 unsigned NumClauses) {
355 if (FindMatchingCatches.
count(NumClauses))
356 return FindMatchingCatches[NumClauses];
362 "__cxa_find_matching_catch_" +
Twine(NumClauses + 2), &M);
363 FindMatchingCatches[NumClauses] =
F;
374 template <
typename CallOrInvoke>
375 Value *WebAssemblyLowerEmscriptenEHSjLj::wrapInvoke(CallOrInvoke *CI) {
381 if (CI->doesNotReturn()) {
382 if (
auto *
F = dyn_cast<Function>(CI->getCalledValue()))
383 F->removeFnAttr(Attribute::NoReturn);
399 Args.
append(CI->arg_begin(), CI->arg_end());
413 for (
unsigned I = 0,
E = CI->getNumArgOperands();
I <
E; ++
I)
417 if (FnAttrs.contains(Attribute::AllocSize)) {
422 std::tie(SizeArg, NEltArg) = FnAttrs.getAllocSizeArgs();
426 FnAttrs.addAllocSizeAttr(SizeArg, NEltArg);
435 CI->replaceAllUsesWith(NewCall);
446 template <
typename CallOrInvoke>
447 Function *WebAssemblyLowerEmscriptenEHSjLj::getInvokeWrapper(CallOrInvoke *CI) {
448 Module *M = CI->getModule();
452 if (
auto *
F = dyn_cast<Function>(Callee))
453 CalleeFTy =
F->getFunctionType();
455 auto *CalleeTy = cast<PointerType>(Callee->
getType())->getElementType();
456 CalleeFTy = cast<FunctionType>(CalleeTy);
460 if (InvokeWrappers.
find(Sig) != InvokeWrappers.
end())
461 return InvokeWrappers[Sig];
472 InvokeWrappers[Sig] =
F;
476 bool WebAssemblyLowerEmscriptenEHSjLj::canLongjmp(
Module &M,
478 if (
auto *CalleeF = dyn_cast<Function>(Callee))
479 if (CalleeF->isIntrinsic())
486 if (isa<InlineAsm>(Callee))
492 if (CalleeName ==
"setjmp" || CalleeName ==
"malloc" || CalleeName ==
"free")
496 if (CalleeName ==
"__resumeException" || CalleeName ==
"llvm_eh_typeid_for" ||
497 CalleeName ==
"saveSetjmp" || CalleeName ==
"testSetjmp" ||
498 CalleeName ==
"getTempRet0" || CalleeName ==
"setTempRet0")
506 if (CalleeName ==
"__cxa_begin_catch" || CalleeName ==
"__cxa_end_catch" ||
507 CalleeName ==
"__cxa_allocate_exception" || CalleeName ==
"__cxa_throw" ||
508 CalleeName ==
"__clang_call_terminate")
515 bool WebAssemblyLowerEmscriptenEHSjLj::isEmAsmCall(
Module &M,
516 const Value *Callee)
const {
519 return CalleeName ==
"emscripten_asm_const_int" ||
520 CalleeName ==
"emscripten_asm_const_double" ||
521 CalleeName ==
"emscripten_asm_const_int_sync_on_main_thread" ||
522 CalleeName ==
"emscripten_asm_const_double_sync_on_main_thread" ||
523 CalleeName ==
"emscripten_asm_const_async_on_main_thread";
540 void WebAssemblyLowerEmscriptenEHSjLj::wrapTestSetjmp(
556 ThrewValueGV->
getName() +
".val");
569 ThrewInt->
getName() +
".loaded");
571 TestSetjmpF, {LoadedThrew, SetjmpTable, SetjmpTableSize},
"label");
577 IRB.
CreateCall(EmLongjmpF, {Threw, ThrewValue});
598 LongjmpResult = IRB.
CreateCall(GetTempRet0Func,
None,
"longjmp_result");
601 void WebAssemblyLowerEmscriptenEHSjLj::rebuildSSA(
Function &
F) {
602 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
609 for (
auto UI =
I.use_begin(), UE =
I.use_end(); UI != UE;) {
613 if (
auto *UserPN = dyn_cast<PHINode>(
User))
614 if (UserPN->getIncomingBlock(U) == &BB)
625 bool WebAssemblyLowerEmscriptenEHSjLj::runOnModule(
Module &M) {
626 LLVM_DEBUG(
dbgs() <<
"********** Lower Emscripten EH & SjLj **********\n");
633 bool SetjmpUsed = SetjmpF && !SetjmpF->
use_empty();
634 bool LongjmpUsed = LongjmpF && !LongjmpF->
use_empty();
635 bool DoSjLj = EnableSjLj && (SetjmpUsed || LongjmpUsed);
651 bool Changed =
false;
659 "__resumeException", &M);
665 "llvm_eh_typeid_for", &M);
670 Changed |= runEHOnFunction(F);
683 "emscripten_longjmp_jmpbuf", &M);
708 "emscripten_longjmp", &M);
714 auto *UI = cast<Instruction>(U);
715 SetjmpUsers.
insert(UI->getFunction());
718 runSjLjOnFunction(*F);
740 bool WebAssemblyLowerEmscriptenEHSjLj::runEHOnFunction(
Function &F) {
744 bool Changed =
false;
747 bool AllowExceptions =
748 areAllExceptionsAllowed() || EHWhitelistSet.
count(F.
getName());
755 LandingPads.
insert(II->getLandingPadInst());
758 bool NeedInvoke = AllowExceptions &&
canThrow(II->getCalledValue());
761 Value *Threw = wrapInvoke(II);
766 IRB.
CreateCondBr(Cmp, II->getUnwindDest(), II->getNormalDest());
773 IRB.
CreateCall(II->getFunctionType(), II->getCalledValue(),
Args);
774 NewCall->takeName(II);
775 NewCall->setCallingConv(II->getCallingConv());
776 NewCall->setDebugLoc(II->getDebugLoc());
777 NewCall->setAttributes(II->getAttributes());
778 II->replaceAllUsesWith(NewCall);
784 II->getUnwindDest()->removePredecessor(&BB);
798 Value *Input = RI->getValue();
815 const Function *Callee = CI->getCalledFunction();
824 IRB.
CreateCall(EHTypeIDF, CI->getArgOperand(0),
"typeid");
833 if (
auto *LPI = dyn_cast<LandingPadInst>(I))
836 Changed |= !LandingPads.
empty();
843 for (
unsigned I = 0,
E = LPI->getNumClauses();
I <
E; ++
I) {
848 if (LPI->isFilter(
I)) {
849 auto *ATy = cast<ArrayType>(Clause->
getType());
850 for (
unsigned J = 0, E = ATy->getNumElements(); J <
E; ++J) {
859 Function *FMCF = getFindMatchingCatch(M, FMCArgs.
size());
872 I->eraseFromParent();
877 bool WebAssemblyLowerEmscriptenEHSjLj::runSjLjOnFunction(
Function &F) {
883 std::vector<Instruction *> SetjmpTableInsts;
885 std::vector<Instruction *> SetjmpTableSizeInsts;
900 nullptr,
nullptr,
"setjmpTable");
904 SetjmpTableInsts.push_back(SetjmpTable);
905 SetjmpTableSizeInsts.push_back(SetjmpTableSize);
908 std::vector<PHINode *> SetjmpRetPHIs;
931 CI->replaceAllUsesWith(SetjmpRet);
933 SetjmpRetPHIs.push_back(SetjmpRet);
940 SetjmpTable, SetjmpTableSize};
942 IRB.
CreateCall(SaveSetjmpF, Args,
"setjmpTable");
945 SetjmpTableInsts.push_back(NewSetjmpTable);
946 SetjmpTableSizeInsts.push_back(NewSetjmpTableSize);
956 std::vector<BasicBlock *> BBs;
961 for (
unsigned I = 0;
I < BBs.size();
I++) {
969 const Value *Callee = CI->getCalledValue();
970 if (!canLongjmp(M, Callee))
972 if (isEmAsmCall(M, Callee))
975 ". Please consider using EM_JS, or move the " 976 "EM_ASM into another function.",
979 Value *Threw =
nullptr;
990 if (
auto *LI = dyn_cast<LoadInst>(
I))
991 if (
auto *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand()))
993 Threw = ThrewLI = LI;
1001 if (
auto *
SI = dyn_cast<StoreInst>(
I))
1002 if (
auto *GV = dyn_cast<GlobalVariable>(
SI->getPointerOperand()))
1003 if (GV == ThrewGV &&
SI->getValueOperand() == IRB.
getInt32(0)) {
1008 assert(Threw && ThrewLI &&
"Cannot find __THREW__ load after invoke");
1009 assert(ThrewResetSI &&
"Cannot find __THREW__ store after invoke");
1014 Threw = wrapInvoke(CI);
1027 Value *Label =
nullptr;
1028 Value *LongjmpResult =
nullptr;
1030 wrapTestSetjmp(BB, CI, Threw, SetjmpTable, SetjmpTableSize, Label,
1031 LongjmpResult, EndBB);
1032 assert(Label && LongjmpResult && EndBB);
1041 for (
unsigned I = 0;
I < SetjmpRetPHIs.size();
I++) {
1043 SetjmpRetPHIs[
I]->addIncoming(LongjmpResult, EndBB);
1048 BBs.push_back(Tail);
1054 I->eraseFromParent();
1059 if (isa<ReturnInst>(TI))
1084 for (
auto UI = SetjmpTable->use_begin(), UE = SetjmpTable->use_end();
1090 if (
auto *
I = dyn_cast<Instruction>(U.
getUser()))
1091 if (
I->getParent() != &EntryBB)
1094 for (
auto UI = SetjmpTableSize->
use_begin(), UE = SetjmpTableSize->
use_end();
1098 if (
auto *
I = dyn_cast<Instruction>(U.
getUser()))
1099 if (
I->getParent() != &EntryBB)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Helper class for SSA formation on a set of values defined in multiple blocks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
ModulePass * createWebAssemblyLowerEmscriptenEHSjLj(bool DoEH, bool DoSjLj)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
static GlobalVariable * getGlobalVariableI32(Module &M, IRBuilder<> &IRB, const char *Name)
Type * getParamType(unsigned i) const
Parameter type accessors.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
void push_back(const T &Elt)
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
This class represents a function call, abstracting a target machine's calling convention.
static PointerType * getInt32PtrTy(LLVMContext &C, unsigned AS=0)
iterator find(StringRef Key)
Externally visible function.
param_iterator param_end() const
An instruction for reading from memory.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static Instruction * CreateFree(Value *Source, Instruction *InsertBefore)
Generate the IR for a call to the builtin free function.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
static bool canThrow(const Value *V)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
Type * getVoidTy()
Fetch the type representing void.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
const T & getValue() const LLVM_LVALUE_FUNCTION
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
const BasicBlock & getEntryBlock() const
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
void RewriteUseAfterInsertions(Use &U)
Rewrite a use like RewriteUse but handling in-block definitions.
UnreachableInst * CreateUnreachable()
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
Resume the propagation of an exception.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
ArrayRef< Type * > params() const
param_iterator param_begin() const
Represent the analysis usage information of a pass.
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New)
void setCallingConv(CallingConv::ID CC)
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Type * getReturnType() const
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Calling convention for emscripten __invoke_* functions.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
amdgpu Simplify well known AMD library false FunctionCallee Callee
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static Instruction * CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize=nullptr, Function *MallocF=nullptr, const Twine &Name="")
Generate the IR for a call to malloc:
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
static IntegerType * getInt32Ty(LLVMContext &C)
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Tail - This calling convention attemps to make calls as fast as possible while guaranteeing that tail...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
INITIALIZE_PASS(WebAssemblyLowerEmscriptenEHSjLj, DEBUG_TYPE, "WebAssembly Lower Emscripten Exceptions / Setjmp / Longjmp", false, false) ModulePass *llvm
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
static cl::list< std::string > EHWhitelist("emscripten-cxx-exceptions-whitelist", cl::desc("The list of function names in which Emscripten-style " "exception handling is enabled (see emscripten " "EMSCRIPTEN_CATCHING_WHITELIST options)"), cl::CommaSeparated)
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
AttributeSet getFnAttributes() const
The function attributes are returned.
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
static std::string getSignature(FunctionType *FTy)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.