1 //===-- WebAssemblyLowerGlobalDtors.cpp - Lower @llvm.global_dtors --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Lower @llvm.global_dtors.
13 /// WebAssembly doesn't have a builtin way to invoke static destructors.
14 /// Implement @llvm.global_dtors by creating wrapper functions that are
15 /// registered in @llvm.global_ctors and which contain a call to
16 /// `__cxa_atexit` to register their destructor functions.
18 //===----------------------------------------------------------------------===//
20 #include "WebAssembly.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Transforms/Utils/ModuleUtils.h"
26 #include "llvm/Pass.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
32 #define DEBUG_TYPE "wasm-lower-global-dtors"
35 class LowerGlobalDtors final : public ModulePass {
36 StringRef getPassName() const override {
37 return "WebAssembly Lower @llvm.global_dtors";
40 void getAnalysisUsage(AnalysisUsage &AU) const override {
42 ModulePass::getAnalysisUsage(AU);
45 bool runOnModule(Module &M) override;
49 LowerGlobalDtors() : ModulePass(ID) {}
51 } // End anonymous namespace
53 char LowerGlobalDtors::ID = 0;
54 ModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
55 return new LowerGlobalDtors();
58 bool LowerGlobalDtors::runOnModule(Module &M) {
59 GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
63 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
67 // Sanity-check @llvm.global_dtor's type.
68 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
69 if (!ETy || ETy->getNumElements() != 3 ||
70 !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
71 !ETy->getTypeAtIndex(1U)->isPointerTy() ||
72 !ETy->getTypeAtIndex(2U)->isPointerTy())
73 return false; // Not (int, ptr, ptr).
75 // Collect the contents of @llvm.global_dtors, collated by priority and
77 std::map<uint16_t, MapVector<Constant *, std::vector<Constant *> > > DtorFuncs;
78 for (Value *O : InitList->operands()) {
79 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
80 if (!CS) continue; // Malformed.
82 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
83 if (!Priority) continue; // Malformed.
84 uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
86 Constant *DtorFunc = CS->getOperand(1);
87 if (DtorFunc->isNullValue())
88 break; // Found a null terminator, skip the rest.
90 Constant *Associated = CS->getOperand(2);
91 Associated = cast<Constant>(Associated->stripPointerCastsNoFollowAliases());
93 DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
95 if (DtorFuncs.empty())
98 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
99 LLVMContext &C = M.getContext();
100 PointerType *VoidStar = Type::getInt8PtrTy(C);
101 Type *AtExitFuncArgs[] = { VoidStar };
102 FunctionType *AtExitFuncTy = FunctionType::get(
107 Type *AtExitArgs[] = {
108 PointerType::get(AtExitFuncTy, 0),
112 FunctionType *AtExitTy = FunctionType::get(
116 Constant *AtExit = M.getOrInsertFunction("__cxa_atexit", AtExitTy);
118 // Declare __dso_local.
119 Constant *DsoHandle = M.getNamedValue("__dso_handle");
121 Type *DsoHandleTy = Type::getInt8Ty(C);
122 GlobalVariable *Handle =
123 new GlobalVariable(M, DsoHandleTy, /*isConstant=*/true,
124 GlobalVariable::ExternalWeakLinkage,
125 nullptr, "__dso_handle");
126 Handle->setVisibility(GlobalVariable::HiddenVisibility);
130 // For each unique priority level and associated symbol, generate a function
131 // to call all the destructors at that level, and a function to register the
132 // first function with __cxa_atexit.
133 for (auto &PriorityAndMore : DtorFuncs) {
134 uint16_t Priority = PriorityAndMore.first;
135 for (auto &AssociatedAndMore : PriorityAndMore.second) {
136 Constant *Associated = AssociatedAndMore.first;
138 Function *CallDtors = Function::Create(
139 AtExitFuncTy, Function::PrivateLinkage,
141 (Priority != UINT16_MAX ?
142 (Twine(".") + Twine(Priority)) : Twine()) +
143 (!Associated->isNullValue() ?
144 (Twine(".") + Associated->getName()) : Twine()),
146 BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
148 for (auto Dtor : AssociatedAndMore.second)
149 CallInst::Create(Dtor, "", BB);
150 ReturnInst::Create(C, BB);
152 FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
154 Function *RegisterCallDtors = Function::Create(
155 VoidVoid, Function::PrivateLinkage,
156 "register_call_dtors" +
157 (Priority != UINT16_MAX ?
158 (Twine(".") + Twine(Priority)) : Twine()) +
159 (!Associated->isNullValue() ?
160 (Twine(".") + Associated->getName()) : Twine()),
162 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
163 BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
164 BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
166 Value *Null = ConstantPointerNull::get(VoidStar);
167 Value *Args[] = { CallDtors, Null, DsoHandle };
168 Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
169 Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
170 Constant::getNullValue(Res->getType()));
171 BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
173 // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
174 // This should be very rare, because if the process is running out of memory
175 // before main has even started, something is wrong.
176 CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap),
178 new UnreachableInst(C, FailBB);
180 ReturnInst::Create(C, RetBB);
182 // Now register the registration function with @llvm.global_ctors.
183 appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
187 // Now that we've lowered everything, remove @llvm.global_dtors.
188 GV->eraseFromParent();