• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- WebAssemblyLowerGlobalDtors.cpp - Lower @llvm.global_dtors --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// Lower @llvm.global_dtors.
12 ///
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.
17 ///
18 //===----------------------------------------------------------------------===//
19 
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"
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "wasm-lower-global-dtors"
33 
34 namespace {
35 class LowerGlobalDtors final : public ModulePass {
getPassName() const36   StringRef getPassName() const override {
37     return "WebAssembly Lower @llvm.global_dtors";
38   }
39 
getAnalysisUsage(AnalysisUsage & AU) const40   void getAnalysisUsage(AnalysisUsage &AU) const override {
41     AU.setPreservesCFG();
42     ModulePass::getAnalysisUsage(AU);
43   }
44 
45   bool runOnModule(Module &M) override;
46 
47 public:
48   static char ID;
LowerGlobalDtors()49   LowerGlobalDtors() : ModulePass(ID) {}
50 };
51 } // End anonymous namespace
52 
53 char LowerGlobalDtors::ID = 0;
54 INITIALIZE_PASS(LowerGlobalDtors, DEBUG_TYPE,
55                 "Lower @llvm.global_dtors for WebAssembly", false, false)
56 
createWebAssemblyLowerGlobalDtors()57 ModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
58   return new LowerGlobalDtors();
59 }
60 
runOnModule(Module & M)61 bool LowerGlobalDtors::runOnModule(Module &M) {
62   GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
63   if (!GV)
64     return false;
65 
66   const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
67   if (!InitList)
68     return false;
69 
70   // Sanity-check @llvm.global_dtor's type.
71   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
72   if (!ETy || ETy->getNumElements() != 3 ||
73       !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
74       !ETy->getTypeAtIndex(1U)->isPointerTy() ||
75       !ETy->getTypeAtIndex(2U)->isPointerTy())
76     return false; // Not (int, ptr, ptr).
77 
78   // Collect the contents of @llvm.global_dtors, collated by priority and
79   // associated symbol.
80   std::map<uint16_t, MapVector<Constant *, std::vector<Constant *> > > DtorFuncs;
81   for (Value *O : InitList->operands()) {
82     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
83     if (!CS) continue; // Malformed.
84 
85     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
86     if (!Priority) continue; // Malformed.
87     uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
88 
89     Constant *DtorFunc = CS->getOperand(1);
90     if (DtorFunc->isNullValue())
91       break;  // Found a null terminator, skip the rest.
92 
93     Constant *Associated = CS->getOperand(2);
94     Associated = cast<Constant>(Associated->stripPointerCastsNoFollowAliases());
95 
96     DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
97   }
98   if (DtorFuncs.empty())
99     return false;
100 
101   // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
102   LLVMContext &C = M.getContext();
103   PointerType *VoidStar = Type::getInt8PtrTy(C);
104   Type *AtExitFuncArgs[] = { VoidStar };
105   FunctionType *AtExitFuncTy = FunctionType::get(
106           Type::getVoidTy(C),
107           AtExitFuncArgs,
108           /*isVarArg=*/false);
109 
110   Type *AtExitArgs[] = {
111     PointerType::get(AtExitFuncTy, 0),
112     VoidStar,
113     VoidStar
114   };
115   FunctionType *AtExitTy = FunctionType::get(
116           Type::getInt32Ty(C),
117           AtExitArgs,
118           /*isVarArg=*/false);
119   Constant *AtExit = M.getOrInsertFunction("__cxa_atexit", AtExitTy);
120 
121   // Declare __dso_local.
122   Constant *DsoHandle = M.getNamedValue("__dso_handle");
123   if (!DsoHandle) {
124     Type *DsoHandleTy = Type::getInt8Ty(C);
125     GlobalVariable *Handle =
126         new GlobalVariable(M, DsoHandleTy, /*isConstant=*/true,
127                            GlobalVariable::ExternalWeakLinkage,
128                            nullptr, "__dso_handle");
129     Handle->setVisibility(GlobalVariable::HiddenVisibility);
130     DsoHandle = Handle;
131   }
132 
133   // For each unique priority level and associated symbol, generate a function
134   // to call all the destructors at that level, and a function to register the
135   // first function with __cxa_atexit.
136   for (auto &PriorityAndMore : DtorFuncs) {
137     uint16_t Priority = PriorityAndMore.first;
138     for (auto &AssociatedAndMore : PriorityAndMore.second) {
139       Constant *Associated = AssociatedAndMore.first;
140 
141       Function *CallDtors = Function::Create(
142               AtExitFuncTy, Function::PrivateLinkage,
143               "call_dtors" +
144               (Priority != UINT16_MAX ?
145                  (Twine(".") + Twine(Priority)) : Twine()) +
146               (!Associated->isNullValue() ?
147                  (Twine(".") + Associated->getName()) : Twine()),
148               &M);
149       BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
150 
151       for (auto Dtor : AssociatedAndMore.second)
152         CallInst::Create(Dtor, "", BB);
153       ReturnInst::Create(C, BB);
154 
155       FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
156                                                  /*isVarArg=*/false);
157       Function *RegisterCallDtors = Function::Create(
158               VoidVoid, Function::PrivateLinkage,
159               "register_call_dtors" +
160               (Priority != UINT16_MAX ?
161                  (Twine(".") + Twine(Priority)) : Twine()) +
162               (!Associated->isNullValue() ?
163                  (Twine(".") + Associated->getName()) : Twine()),
164               &M);
165       BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
166       BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
167       BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
168 
169       Value *Null = ConstantPointerNull::get(VoidStar);
170       Value *Args[] = { CallDtors, Null, DsoHandle };
171       Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
172       Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
173                                 Constant::getNullValue(Res->getType()));
174       BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
175 
176       // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
177       // This should be very rare, because if the process is running out of memory
178       // before main has even started, something is wrong.
179       CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap),
180                        "", FailBB);
181       new UnreachableInst(C, FailBB);
182 
183       ReturnInst::Create(C, RetBB);
184 
185       // Now register the registration function with @llvm.global_ctors.
186       appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
187     }
188   }
189 
190   // Now that we've lowered everything, remove @llvm.global_dtors.
191   GV->eraseFromParent();
192 
193   return true;
194 }
195