blob: 84c877cb8d0282424d1eb9a5898f561c2a0bbfb0 [file] [log] [blame]
Sam Cleggbafe6902017-12-15 00:17:10 +00001//===-- 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// Lower @llvm.global_dtors.
Sam Cleggbafe6902017-12-15 00:17:10 +000012///
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"
Heejin Ahnf208f632018-09-05 01:27:38 +000021#include "llvm/ADT/MapVector.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/Module.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000026#include "llvm/Pass.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
Heejin Ahnf208f632018-09-05 01:27:38 +000029#include "llvm/Transforms/Utils/ModuleUtils.h"
Sam Cleggbafe6902017-12-15 00:17:10 +000030using namespace llvm;
31
32#define DEBUG_TYPE "wasm-lower-global-dtors"
33
34namespace {
35class LowerGlobalDtors final : public ModulePass {
36 StringRef getPassName() const override {
37 return "WebAssembly Lower @llvm.global_dtors";
38 }
39
40 void getAnalysisUsage(AnalysisUsage &AU) const override {
41 AU.setPreservesCFG();
42 ModulePass::getAnalysisUsage(AU);
43 }
44
45 bool runOnModule(Module &M) override;
46
47public:
48 static char ID;
49 LowerGlobalDtors() : ModulePass(ID) {}
50};
51} // End anonymous namespace
52
53char LowerGlobalDtors::ID = 0;
Jacob Gravelle40926452018-03-30 20:36:58 +000054INITIALIZE_PASS(LowerGlobalDtors, DEBUG_TYPE,
55 "Lower @llvm.global_dtors for WebAssembly", false, false)
56
Sam Cleggbafe6902017-12-15 00:17:10 +000057ModulePass *llvm::createWebAssemblyLowerGlobalDtors() {
58 return new LowerGlobalDtors();
59}
60
61bool LowerGlobalDtors::runOnModule(Module &M) {
Heejin Ahn569f0902019-01-09 23:05:21 +000062 LLVM_DEBUG(dbgs() << "********** Lower Global Destructors **********\n");
63
Sam Cleggbafe6902017-12-15 00:17:10 +000064 GlobalVariable *GV = M.getGlobalVariable("llvm.global_dtors");
65 if (!GV)
66 return false;
67
68 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
69 if (!InitList)
70 return false;
71
72 // Sanity-check @llvm.global_dtor's type.
73 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
74 if (!ETy || ETy->getNumElements() != 3 ||
75 !ETy->getTypeAtIndex(0U)->isIntegerTy() ||
76 !ETy->getTypeAtIndex(1U)->isPointerTy() ||
77 !ETy->getTypeAtIndex(2U)->isPointerTy())
78 return false; // Not (int, ptr, ptr).
79
80 // Collect the contents of @llvm.global_dtors, collated by priority and
81 // associated symbol.
Heejin Ahnf208f632018-09-05 01:27:38 +000082 std::map<uint16_t, MapVector<Constant *, std::vector<Constant *>>> DtorFuncs;
Sam Cleggbafe6902017-12-15 00:17:10 +000083 for (Value *O : InitList->operands()) {
84 ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
Heejin Ahnf208f632018-09-05 01:27:38 +000085 if (!CS)
86 continue; // Malformed.
Sam Cleggbafe6902017-12-15 00:17:10 +000087
88 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
Heejin Ahnf208f632018-09-05 01:27:38 +000089 if (!Priority)
90 continue; // Malformed.
Sam Cleggbafe6902017-12-15 00:17:10 +000091 uint16_t PriorityValue = Priority->getLimitedValue(UINT16_MAX);
92
93 Constant *DtorFunc = CS->getOperand(1);
94 if (DtorFunc->isNullValue())
Heejin Ahnf208f632018-09-05 01:27:38 +000095 break; // Found a null terminator, skip the rest.
Sam Cleggbafe6902017-12-15 00:17:10 +000096
97 Constant *Associated = CS->getOperand(2);
98 Associated = cast<Constant>(Associated->stripPointerCastsNoFollowAliases());
99
100 DtorFuncs[PriorityValue][Associated].push_back(DtorFunc);
101 }
102 if (DtorFuncs.empty())
103 return false;
104
105 // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
106 LLVMContext &C = M.getContext();
107 PointerType *VoidStar = Type::getInt8PtrTy(C);
Heejin Ahnf208f632018-09-05 01:27:38 +0000108 Type *AtExitFuncArgs[] = {VoidStar};
109 FunctionType *AtExitFuncTy =
110 FunctionType::get(Type::getVoidTy(C), AtExitFuncArgs,
111 /*isVarArg=*/false);
Sam Cleggbafe6902017-12-15 00:17:10 +0000112
Heejin Ahnf208f632018-09-05 01:27:38 +0000113 Type *AtExitArgs[] = {PointerType::get(AtExitFuncTy, 0), VoidStar, VoidStar};
114 FunctionType *AtExitTy = FunctionType::get(Type::getInt32Ty(C), AtExitArgs,
115 /*isVarArg=*/false);
Sam Cleggbafe6902017-12-15 00:17:10 +0000116 Constant *AtExit = M.getOrInsertFunction("__cxa_atexit", AtExitTy);
117
118 // Declare __dso_local.
119 Constant *DsoHandle = M.getNamedValue("__dso_handle");
120 if (!DsoHandle) {
121 Type *DsoHandleTy = Type::getInt8Ty(C);
Heejin Ahnf208f632018-09-05 01:27:38 +0000122 GlobalVariable *Handle = new GlobalVariable(
123 M, DsoHandleTy, /*isConstant=*/true,
124 GlobalVariable::ExternalWeakLinkage, nullptr, "__dso_handle");
Sam Cleggbafe6902017-12-15 00:17:10 +0000125 Handle->setVisibility(GlobalVariable::HiddenVisibility);
126 DsoHandle = Handle;
127 }
128
129 // For each unique priority level and associated symbol, generate a function
130 // to call all the destructors at that level, and a function to register the
131 // first function with __cxa_atexit.
132 for (auto &PriorityAndMore : DtorFuncs) {
133 uint16_t Priority = PriorityAndMore.first;
134 for (auto &AssociatedAndMore : PriorityAndMore.second) {
135 Constant *Associated = AssociatedAndMore.first;
136
137 Function *CallDtors = Function::Create(
Heejin Ahnf208f632018-09-05 01:27:38 +0000138 AtExitFuncTy, Function::PrivateLinkage,
139 "call_dtors" +
140 (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
141 : Twine()) +
142 (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
143 : Twine()),
144 &M);
Sam Cleggbafe6902017-12-15 00:17:10 +0000145 BasicBlock *BB = BasicBlock::Create(C, "body", CallDtors);
146
147 for (auto Dtor : AssociatedAndMore.second)
148 CallInst::Create(Dtor, "", BB);
149 ReturnInst::Create(C, BB);
150
151 FunctionType *VoidVoid = FunctionType::get(Type::getVoidTy(C),
152 /*isVarArg=*/false);
153 Function *RegisterCallDtors = Function::Create(
Heejin Ahnf208f632018-09-05 01:27:38 +0000154 VoidVoid, Function::PrivateLinkage,
155 "register_call_dtors" +
156 (Priority != UINT16_MAX ? (Twine(".") + Twine(Priority))
157 : Twine()) +
158 (!Associated->isNullValue() ? (Twine(".") + Associated->getName())
159 : Twine()),
160 &M);
Sam Cleggbafe6902017-12-15 00:17:10 +0000161 BasicBlock *EntryBB = BasicBlock::Create(C, "entry", RegisterCallDtors);
162 BasicBlock *FailBB = BasicBlock::Create(C, "fail", RegisterCallDtors);
163 BasicBlock *RetBB = BasicBlock::Create(C, "return", RegisterCallDtors);
164
165 Value *Null = ConstantPointerNull::get(VoidStar);
Heejin Ahnf208f632018-09-05 01:27:38 +0000166 Value *Args[] = {CallDtors, Null, DsoHandle};
Sam Cleggbafe6902017-12-15 00:17:10 +0000167 Value *Res = CallInst::Create(AtExit, Args, "call", EntryBB);
168 Value *Cmp = new ICmpInst(*EntryBB, ICmpInst::ICMP_NE, Res,
169 Constant::getNullValue(Res->getType()));
170 BranchInst::Create(FailBB, RetBB, Cmp, EntryBB);
171
172 // If `__cxa_atexit` hits out-of-memory, trap, so that we don't misbehave.
Heejin Ahnf208f632018-09-05 01:27:38 +0000173 // This should be very rare, because if the process is running out of
174 // memory before main has even started, something is wrong.
175 CallInst::Create(Intrinsic::getDeclaration(&M, Intrinsic::trap), "",
176 FailBB);
Sam Cleggbafe6902017-12-15 00:17:10 +0000177 new UnreachableInst(C, FailBB);
178
179 ReturnInst::Create(C, RetBB);
180
181 // Now register the registration function with @llvm.global_ctors.
182 appendToGlobalCtors(M, RegisterCallDtors, Priority, Associated);
183 }
184 }
185
186 // Now that we've lowered everything, remove @llvm.global_dtors.
187 GV->eraseFromParent();
188
189 return true;
190}