blob: 38ebe4c0dc54d4367a617f1e38c0b28ebdbadcb7 [file] [log] [blame]
Anders Carlsson11e51402010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlsson2bb27f52009-10-11 22:13:54 +00002//
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// This contains code dealing with C++ code generation of virtual tables.
11//
12//===----------------------------------------------------------------------===//
13
Anders Carlsson2bb27f52009-10-11 22:13:54 +000014#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000019#include "clang/Basic/CodeGenOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlssond420a312009-11-26 19:32:45 +000021#include "llvm/ADT/DenseSet.h"
Anders Carlssond46ed892010-02-27 16:18:19 +000022#include "llvm/ADT/SetVector.h"
Chandler Carruth94eab4a2010-02-13 10:38:52 +000023#include "llvm/Support/Compiler.h"
Anders Carlsson5d40c6f2010-02-11 08:02:13 +000024#include "llvm/Support/Format.h"
Eli Friedman49a94b12011-05-06 17:27:27 +000025#include "llvm/Transforms/Utils/Cloning.h"
Saleem Abdulrasool94cfc602016-04-07 17:49:44 +000026
Anders Carlsson56446142010-03-17 20:06:32 +000027#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000028#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000029
30using namespace clang;
31using namespace CodeGen;
32
Reid Kleckner96f8f932014-02-05 17:27:08 +000033CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
34 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000035
Anders Carlssoncd836f02010-03-23 17:17:29 +000036llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000037 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000038 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
39
40 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000041 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000042 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000043 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000044 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000045 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000046 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000047 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +000048
Chris Lattner2192fe52011-07-18 04:24:23 +000049 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +000050 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000051 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000052}
53
John McCallc8bd9c22010-08-04 23:46:35 +000054static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
55 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000056 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000057}
58
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000059static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
60 llvm::Function *ThunkFn, bool ForVTable,
61 GlobalDecl GD) {
62 CGM.setFunctionLinkage(GD, ThunkFn);
63 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
64 !Thunk.Return.isEmpty());
65
66 // Set the right visibility.
67 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
68 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
69
70 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
71 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
72}
73
John McCall5fe00962011-03-09 07:12:35 +000074#ifndef NDEBUG
75static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
76 const ABIArgInfo &infoR, CanQualType typeR) {
77 return (infoL.getKind() == infoR.getKind() &&
78 (typeL == typeR ||
79 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
80 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
81}
82#endif
83
Eli Friedman49a94b12011-05-06 17:27:27 +000084static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
85 QualType ResultType, RValue RV,
86 const ThunkInfo &Thunk) {
87 // Emit the return adjustment.
88 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000089
90 llvm::BasicBlock *AdjustNull = nullptr;
91 llvm::BasicBlock *AdjustNotNull = nullptr;
92 llvm::BasicBlock *AdjustEnd = nullptr;
93
Eli Friedman49a94b12011-05-06 17:27:27 +000094 llvm::Value *ReturnValue = RV.getScalarVal();
95
96 if (NullCheckValue) {
97 AdjustNull = CGF.createBasicBlock("adjust.null");
98 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
99 AdjustEnd = CGF.createBasicBlock("adjust.end");
100
101 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
102 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
103 CGF.EmitBlock(AdjustNotNull);
104 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000105
John McCall7f416cc2015-09-08 08:05:57 +0000106 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
107 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
108 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
109 Address(ReturnValue, ClassAlign),
110 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000111
Eli Friedman49a94b12011-05-06 17:27:27 +0000112 if (NullCheckValue) {
113 CGF.Builder.CreateBr(AdjustEnd);
114 CGF.EmitBlock(AdjustNull);
115 CGF.Builder.CreateBr(AdjustEnd);
116 CGF.EmitBlock(AdjustEnd);
117
118 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
119 PHI->addIncoming(ReturnValue, AdjustNotNull);
120 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
121 AdjustNull);
122 ReturnValue = PHI;
123 }
124
125 return RValue::get(ReturnValue);
126}
127
128// This function does roughly the same thing as GenerateThunk, but in a
129// very different way, so that va_start and va_end work correctly.
130// FIXME: This function assumes "this" is the first non-sret LLVM argument of
131// a function, and that there is an alloca built in the entry block
132// for all accesses to "this".
133// FIXME: This function assumes there is only one "ret" statement per function.
134// FIXME: Cloning isn't correct in the presence of indirect goto!
135// FIXME: This implementation of thunks bloats codesize by duplicating the
136// function definition. There are alternatives:
137// 1. Add some sort of stub support to LLVM for cases where we can
138// do a this adjustment, then a sibcall.
139// 2. We could transform the definition to take a va_list instead of an
140// actual variable argument list, then have the thunks (including a
141// no-op thunk for the regular definition) call va_start/va_end.
142// There's a bit of per-call overhead for this solution, but it's
143// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000144llvm::Function *
145CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000146 const CGFunctionInfo &FnInfo,
147 GlobalDecl GD, const ThunkInfo &Thunk) {
148 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
149 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000150 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000151
152 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000153 assert(FnInfo.isVariadic());
154 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000155 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
156 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
157
158 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000159 llvm::ValueToValueMapTy VMap;
160 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
161 /*ModuleLevelChanges=*/false);
Eli Friedman49a94b12011-05-06 17:27:27 +0000162 CGM.getModule().getFunctionList().push_back(NewFn);
163 Fn->replaceAllUsesWith(NewFn);
164 NewFn->takeName(Fn);
165 Fn->eraseFromParent();
166 Fn = NewFn;
167
168 // "Initialize" CGF (minimally).
169 CurFn = Fn;
170
171 // Get the "this" value
172 llvm::Function::arg_iterator AI = Fn->arg_begin();
173 if (CGM.ReturnTypeUsesSRet(FnInfo))
174 ++AI;
175
176 // Find the first store of "this", which will be to the alloca associated
177 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000178 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000179 llvm::BasicBlock *EntryBB = &Fn->front();
180 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000181 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000182 return isa<llvm::StoreInst>(I) &&
183 I.getOperand(0) == ThisPtr.getPointer();
184 });
185 assert(ThisStore != EntryBB->end() &&
186 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000187 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000188 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000189 llvm::Value *AdjustedThisPtr =
190 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000191 ThisStore->setOperand(0, AdjustedThisPtr);
192
193 if (!Thunk.Return.isEmpty()) {
194 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000195 for (llvm::BasicBlock &BB : *Fn) {
196 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000197 if (isa<llvm::ReturnInst>(T)) {
198 RValue RV = RValue::get(T->getOperand(0));
199 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000200 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000201 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
202 Builder.CreateRet(RV.getScalarVal());
203 break;
204 }
205 }
206 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000207
208 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000209}
210
Hans Wennborg88497d62013-11-15 17:24:45 +0000211void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
212 const CGFunctionInfo &FnInfo) {
213 assert(!CurGD.getDecl() && "CurGD was already set!");
214 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000215 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000216
217 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000218 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000219 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000220 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000221 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
222 ? ThisType
223 : CGM.getCXXABI().hasMostDerivedReturn(GD)
224 ? CGM.getContext().VoidPtrTy
225 : FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000226 FunctionArgList FunctionArgs;
227
Anders Carlssonbad991d2010-03-24 00:39:18 +0000228 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000229 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000230
231 // Add the rest of the parameters.
Alexey Samsonov3551e312014-08-13 20:06:24 +0000232 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000233
Reid Kleckner89077a12013-12-17 19:46:40 +0000234 if (isa<CXXDestructorDecl>(MD))
235 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
236
Hans Wennborg88497d62013-11-15 17:24:45 +0000237 // Start defining the function.
John McCalla738c252011-03-09 04:27:21 +0000238 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
David Blaikie4d5c7282014-12-29 22:53:52 +0000239 MD->getLocation(), MD->getLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000240
Hans Wennborg88497d62013-11-15 17:24:45 +0000241 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000242 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000243 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000244 CurCodeDecl = MD;
245 CurFuncDecl = MD;
246}
247
248void CodeGenFunction::FinishThunk() {
249 // Clear these to restore the invariants expected by
250 // StartFunction/FinishFunction.
251 CurCodeDecl = nullptr;
252 CurFuncDecl = nullptr;
253
254 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000255}
John McCall5d865c322010-08-31 07:33:07 +0000256
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000257void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg88497d62013-11-15 17:24:45 +0000258 const ThunkInfo *Thunk) {
259 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
260 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000261 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000262
Hans Wennborg88497d62013-11-15 17:24:45 +0000263 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000264 llvm::Value *AdjustedThisPtr =
265 Thunk ? CGM.getCXXABI().performThisAdjustment(
266 *this, LoadCXXThisAddress(), Thunk->This)
267 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000268
Reid Klecknerab2090d2014-07-26 01:34:32 +0000269 if (CurFnInfo->usesInAlloca()) {
270 // We don't handle return adjusting thunks, because they require us to call
271 // the copy constructor. For now, fall through and pretend the return
272 // adjustment was empty so we don't crash.
273 if (Thunk && !Thunk->Return.isEmpty()) {
274 CGM.ErrorUnsupported(
275 MD, "non-trivial argument copy for return-adjusting thunk");
276 }
277 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
278 return;
279 }
280
Hans Wennborg88497d62013-11-15 17:24:45 +0000281 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000282 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000283 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000284 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000285
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000286 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000287 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000288
Hans Wennborg88497d62013-11-15 17:24:45 +0000289 // Add the rest of the arguments.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000290 for (const ParmVarDecl *PD : MD->params())
291 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000292
Hans Wennborg88497d62013-11-15 17:24:45 +0000293 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000294
John McCalla738c252011-03-09 04:27:21 +0000295#ifndef NDEBUG
John McCall8dda7b22012-07-07 06:41:13 +0000296 const CGFunctionInfo &CallFnInfo =
297 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCalla729c622012-02-17 03:33:10 +0000298 RequiredArgs::forPrototypePlus(FPT, 1));
Hans Wennborg88497d62013-11-15 17:24:45 +0000299 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
300 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
301 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000302 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
303 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000304 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
305 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
306 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000307 assert(similar(CallFnInfo.arg_begin()[i].info,
308 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000309 CurFnInfo->arg_begin()[i].info,
310 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000311#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000312
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000313 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000314 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
315 ? ThisType
316 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
317 ? CGM.getContext().VoidPtrTy
318 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000319 ReturnValueSlot Slot;
320 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000321 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000322 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000323 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
324
Anders Carlssonbad991d2010-03-24 00:39:18 +0000325 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000326 llvm::Instruction *CallOrInvoke;
327 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
328
Hans Wennborg88497d62013-11-15 17:24:45 +0000329 // Consider return adjustment if we have ThunkInfo.
330 if (Thunk && !Thunk->Return.isEmpty())
331 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000332 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
333 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000334
Hans Wennborg88497d62013-11-15 17:24:45 +0000335 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000336 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000337 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000338
John McCallff755cd2012-07-31 00:33:55 +0000339 // Disable the final ARC autorelease.
340 AutoreleaseResult = false;
341
John McCall7f416cc2015-09-08 08:05:57 +0000342 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000343}
344
Reid Klecknerab2090d2014-07-26 01:34:32 +0000345void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
346 llvm::Value *AdjustedThisPtr,
347 llvm::Value *Callee) {
348 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
349 // to translate AST arguments into LLVM IR arguments. For thunks, we know
350 // that the caller prototype more or less matches the callee prototype with
351 // the exception of 'this'.
352 SmallVector<llvm::Value *, 8> Args;
353 for (llvm::Argument &A : CurFn->args())
354 Args.push_back(&A);
355
356 // Set the adjusted 'this' pointer.
357 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
358 if (ThisAI.isDirect()) {
359 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
360 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
361 llvm::Type *ThisType = Args[ThisArgNo]->getType();
362 if (ThisType != AdjustedThisPtr->getType())
363 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
364 Args[ThisArgNo] = AdjustedThisPtr;
365 } else {
366 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000367 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
368 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000369 if (ThisType != AdjustedThisPtr->getType())
370 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
371 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
372 }
373
374 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
375 // don't actually want to run them.
376 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
377 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
378
379 // Apply the standard set of call attributes.
380 unsigned CallingConv;
381 CodeGen::AttributeListType AttributeList;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000382 CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
383 CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000384 llvm::AttributeSet Attrs =
385 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
386 Call->setAttributes(Attrs);
387 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
388
389 if (Call->getType()->isVoidTy())
390 Builder.CreateRetVoid();
391 else
392 Builder.CreateRet(Call);
393
394 // Finish the function to maintain CodeGenFunction invariants.
395 // FIXME: Don't emit unreachable code.
396 EmitBlock(createBasicBlock());
397 FinishFunction();
398}
399
Rafael Espindolad6e66942015-07-13 06:07:58 +0000400void CodeGenFunction::generateThunk(llvm::Function *Fn,
Hans Wennborg88497d62013-11-15 17:24:45 +0000401 const CGFunctionInfo &FnInfo,
402 GlobalDecl GD, const ThunkInfo &Thunk) {
403 StartThunk(Fn, GD, FnInfo);
404
405 // Get our callee.
406 llvm::Type *Ty =
407 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
408 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
409
410 // Make the call and return the result.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000411 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000412}
413
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000414void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
415 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000416 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000417
418 // FIXME: re-use FnInfo in this computation.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000419 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
420 llvm::GlobalValue *Entry;
421
Anders Carlsson55e89f82010-03-23 18:18:41 +0000422 // Strip off a bitcast if we got one back.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000423 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000424 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000425 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
426 } else {
427 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000428 }
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000429
Anders Carlsson55e89f82010-03-23 18:18:41 +0000430 // There's already a declaration with the same name, check if it has the same
431 // type or if we need to replace it.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000432 if (Entry->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000433 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000434 llvm::GlobalValue *OldThunkFn = Entry;
435
Anders Carlsson55e89f82010-03-23 18:18:41 +0000436 // If the types mismatch then we have to rewrite the definition.
437 assert(OldThunkFn->isDeclaration() &&
438 "Shouldn't replace non-declaration");
439
440 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000441 OldThunkFn->setName(StringRef());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000442 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson55e89f82010-03-23 18:18:41 +0000443
444 // If needed, replace the old thunk with a bitcast.
445 if (!OldThunkFn->use_empty()) {
446 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000447 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000448 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
449 }
450
451 // Remove the old thunk.
452 OldThunkFn->eraseFromParent();
453 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000454
Anders Carlssonbad991d2010-03-24 00:39:18 +0000455 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000456 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
457 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000458
459 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000460 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000461 // There is already a thunk emitted for this function, do nothing.
462 return;
463 }
464
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000465 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlssone866d442011-02-06 20:09:44 +0000466 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000467 }
468
Rafael Espindola86792432012-09-21 20:39:32 +0000469 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
470
Eli Friedman49a94b12011-05-06 17:27:27 +0000471 if (ThunkFn->isVarArg()) {
472 // Varargs thunks are special; we can't just generate a call because
473 // we can't copy the varargs. Our implementation is rather
474 // expensive/sucky at the moment, so don't generate the thunk unless
475 // we have to.
476 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Peter Collingbourne45a24012015-06-30 19:07:26 +0000477 if (UseAvailableExternallyLinkage)
478 return;
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000479 ThunkFn =
480 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000481 } else {
482 // Normal thunk body generation.
Rafael Espindolad6e66942015-07-13 06:07:58 +0000483 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000484 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000485
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000486 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlsson8b021832011-02-06 18:31:40 +0000487}
488
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000489void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
490 const ThunkInfo &Thunk) {
491 // If the ABI has key functions, only the TU with the key function should emit
492 // the thunk. However, we can allow inlining of thunks if we emit them with
493 // available_externally linkage together with vtables when optimizations are
494 // enabled.
495 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
496 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000497 return;
498
499 // We can't emit thunks for member functions with incomplete types.
500 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000501 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000502 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000503 return;
504
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000505 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000506}
507
Anders Carlsson917229c2010-03-23 04:59:02 +0000508void CodeGenVTables::EmitThunks(GlobalDecl GD)
509{
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000510 const CXXMethodDecl *MD =
511 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
512
513 // We don't need to generate thunks for the base destructor.
514 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
515 return;
516
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000517 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
518 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000519
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000520 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000521 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000522
Yaron Kerenede60302015-08-01 19:11:36 +0000523 for (const ThunkInfo& Thunk : *ThunkInfoVector)
524 emitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000525}
526
David Majnemerd905da42014-07-01 20:30:31 +0000527llvm::Constant *CodeGenVTables::CreateVTableInitializer(
528 const CXXRecordDecl *RD, const VTableComponent *Components,
529 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
530 unsigned NumVTableThunks, llvm::Constant *RTTI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000531 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlssona4147142010-03-25 15:26:28 +0000532
Chris Lattnerece04092012-02-07 00:39:47 +0000533 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlssona4147142010-03-25 15:26:28 +0000534
Chris Lattner2192fe52011-07-18 04:24:23 +0000535 llvm::Type *PtrDiffTy =
Anders Carlssona5736bd2010-03-25 16:49:53 +0000536 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
537
Anders Carlssona5736bd2010-03-25 16:49:53 +0000538 unsigned NextVTableThunkIndex = 0;
Craig Topper8a13c412014-05-21 05:09:00 +0000539
540 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000541
Anders Carlssona4147142010-03-25 15:26:28 +0000542 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000543 VTableComponent Component = Components[I];
Anders Carlssona5736bd2010-03-25 16:49:53 +0000544
Craig Topper8a13c412014-05-21 05:09:00 +0000545 llvm::Constant *Init = nullptr;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000546
547 switch (Component.getKind()) {
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000548 case VTableComponent::CK_VCallOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000549 Init = llvm::ConstantInt::get(PtrDiffTy,
550 Component.getVCallOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000551 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
552 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000553 case VTableComponent::CK_VBaseOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000554 Init = llvm::ConstantInt::get(PtrDiffTy,
555 Component.getVBaseOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000556 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
557 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000558 case VTableComponent::CK_OffsetToTop:
Ken Dyck872d74a2011-04-02 01:14:48 +0000559 Init = llvm::ConstantInt::get(PtrDiffTy,
560 Component.getOffsetToTop().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000561 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
562 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000563 case VTableComponent::CK_RTTI:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000564 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
565 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000566 case VTableComponent::CK_FunctionPointer:
567 case VTableComponent::CK_CompleteDtorPointer:
568 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlssona5736bd2010-03-25 16:49:53 +0000569 GlobalDecl GD;
570
571 // Get the right global decl.
572 switch (Component.getKind()) {
573 default:
574 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000575 case VTableComponent::CK_FunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000576 GD = Component.getFunctionDecl();
577 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000578 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000579 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
580 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000581 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000582 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
583 break;
584 }
585
Artem Belevich9b929462015-12-17 18:12:36 +0000586 if (CGM.getLangOpts().CUDA) {
587 // Emit NULL for methods we can't codegen on this
588 // side. Otherwise we'd end up with vtable with unresolved
589 // references.
590 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
591 // OK on device side: functions w/ __device__ attribute
592 // OK on host side: anything except __device__-only functions.
593 bool CanEmitMethod = CGM.getLangOpts().CUDAIsDevice
594 ? MD->hasAttr<CUDADeviceAttr>()
595 : (MD->hasAttr<CUDAHostAttr>() ||
596 !MD->hasAttr<CUDADeviceAttr>());
597 if (!CanEmitMethod) {
598 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
599 break;
600 }
601 // Method is acceptable, continue processing as usual.
602 }
603
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000604 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
605 // We have a pure virtual member function.
Joao Matos718a8832012-07-17 19:17:58 +0000606 if (!PureVirtualFn) {
Eli Friedman48a32912012-09-14 01:19:01 +0000607 llvm::FunctionType *Ty =
608 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
609 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
610 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +0000611 if (auto *F = dyn_cast<llvm::Function>(PureVirtualFn))
612 F->setUnnamedAddr(true);
Eli Friedman48a32912012-09-14 01:19:01 +0000613 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matos718a8832012-07-17 19:17:58 +0000614 CGM.Int8PtrTy);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000615 }
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000616 Init = PureVirtualFn;
David Blaikieeb7d5982012-10-16 22:56:05 +0000617 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
618 if (!DeletedVirtualFn) {
619 llvm::FunctionType *Ty =
620 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
621 StringRef DeletedCallName =
622 CGM.getCXXABI().GetDeletedVirtualCallName();
623 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +0000624 if (auto *F = dyn_cast<llvm::Function>(DeletedVirtualFn))
625 F->setUnnamedAddr(true);
David Blaikieeb7d5982012-10-16 22:56:05 +0000626 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
627 CGM.Int8PtrTy);
628 }
629 Init = DeletedVirtualFn;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000630 } else {
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000631 // Check if we should use a thunk.
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000632 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000633 VTableThunks[NextVTableThunkIndex].first == I) {
634 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000635
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000636 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramere6b4a162012-03-20 20:18:13 +0000637 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson8b021832011-02-06 18:31:40 +0000638
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000639 NextVTableThunkIndex++;
640 } else {
Chris Lattner2192fe52011-07-18 04:24:23 +0000641 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000642
Anders Carlsson3c239482011-02-05 04:35:53 +0000643 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000644 }
645
646 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000647 }
Anders Carlssona5736bd2010-03-25 16:49:53 +0000648 break;
649 }
650
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000651 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000652 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
653 break;
654 };
Anders Carlssona4147142010-03-25 15:26:28 +0000655
656 Inits.push_back(Init);
657 }
658
659 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad83be3612011-06-22 09:24:39 +0000660 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlssona4147142010-03-25 15:26:28 +0000661}
662
Anders Carlsson0534b022010-03-25 00:35:49 +0000663llvm::GlobalVariable *
664CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlssona208b392010-03-26 03:56:54 +0000665 const BaseSubobject &Base,
666 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000667 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000668 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000669 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
670 DI->completeClassData(Base.getBase());
671
Ahmed Charlesb8984322014-03-07 20:03:18 +0000672 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000673 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000674 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000675
Anders Carlssona5736bd2010-03-25 16:49:53 +0000676 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000677 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000678
679 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000680 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000681 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000682 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
683 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
684 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000685 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000686
Anders Carlssona4147142010-03-25 15:26:28 +0000687 llvm::ArrayType *ArrayType =
Chris Lattnerece04092012-02-07 00:39:47 +0000688 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlssona4147142010-03-25 15:26:28 +0000689
Richard Smith65fd2a42013-02-16 00:51:21 +0000690 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
691 // guarantee that they actually will be available externally. Instead, when
692 // emitting an available_externally VTT, we provide references to an internal
693 // linkage construction vtable. The ABI only requires complete-object vtables
694 // to be the same for all instances of a type, not construction vtables.
695 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
696 Linkage = llvm::GlobalVariable::InternalLinkage;
697
Anders Carlssona4147142010-03-25 15:26:28 +0000698 // Create the variable that will hold the construction vtable.
699 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000700 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
John McCall8f80a612014-02-08 00:41:16 +0000701 CGM.setGlobalVisibility(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000702
703 // V-tables are always unnamed_addr.
704 VTable->setUnnamedAddr(true);
Anders Carlssona4147142010-03-25 15:26:28 +0000705
David Majnemerd905da42014-07-01 20:30:31 +0000706 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
707 CGM.getContext().getTagDeclType(Base.getBase()));
708
Anders Carlssona4147142010-03-25 15:26:28 +0000709 // Create and set the initializer.
David Majnemerd905da42014-07-01 20:30:31 +0000710 llvm::Constant *Init = CreateVTableInitializer(
711 Base.getBase(), VTLayout->vtable_component_begin(),
712 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
713 VTLayout->getNumVTableThunks(), RTTI);
Anders Carlssona4147142010-03-25 15:26:28 +0000714 VTable->setInitializer(Init);
715
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000716 CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
717
Anders Carlsson0534b022010-03-25 00:35:49 +0000718 return VTable;
719}
720
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000721static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
722 const CXXRecordDecl *RD) {
723 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000724 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000725}
726
Eric Christopherd160c502016-01-29 01:35:53 +0000727/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +0000728///
729/// Note that we only call this at the end of the translation unit.
730llvm::GlobalVariable::LinkageTypes
731CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000732 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000733 return llvm::GlobalVariable::InternalLinkage;
734
735 // We're at the end of the translation unit, so the current key
736 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000737 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
738 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000739 // If this class has a key function, use that to determine the
740 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000741 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000742 if (keyFunction->hasBody(def))
743 keyFunction = cast<CXXMethodDecl>(def);
744
745 switch (keyFunction->getTemplateSpecializationKind()) {
746 case TSK_Undeclared:
747 case TSK_ExplicitSpecialization:
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000748 assert((def || CodeGenOpts.OptimizationLevel > 0) &&
749 "Shouldn't query vtable linkage without key function or "
750 "optimizations");
751 if (!def && CodeGenOpts.OptimizationLevel > 0)
752 return llvm::GlobalVariable::AvailableExternallyLinkage;
753
John McCall6bd2a892013-01-25 22:31:03 +0000754 if (keyFunction->isInlined())
755 return !Context.getLangOpts().AppleKext ?
756 llvm::GlobalVariable::LinkOnceODRLinkage :
757 llvm::Function::InternalLinkage;
758
759 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000760
John McCall6bd2a892013-01-25 22:31:03 +0000761 case TSK_ImplicitInstantiation:
762 return !Context.getLangOpts().AppleKext ?
763 llvm::GlobalVariable::LinkOnceODRLinkage :
764 llvm::Function::InternalLinkage;
765
766 case TSK_ExplicitInstantiationDefinition:
767 return !Context.getLangOpts().AppleKext ?
768 llvm::GlobalVariable::WeakODRLinkage :
769 llvm::Function::InternalLinkage;
770
771 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000772 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000773 }
774 }
775
776 // -fapple-kext mode does not support weak linkage, so we must use
777 // internal linkage.
778 if (Context.getLangOpts().AppleKext)
779 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000780
781 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
782 llvm::GlobalValue::LinkOnceODRLinkage;
783 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
784 llvm::GlobalValue::WeakODRLinkage;
785 if (RD->hasAttr<DLLExportAttr>()) {
786 // Cannot discard exported vtables.
787 DiscardableODRLinkage = NonDiscardableODRLinkage;
788 } else if (RD->hasAttr<DLLImportAttr>()) {
789 // Imported vtables are available externally.
790 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
791 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
792 }
793
John McCall6bd2a892013-01-25 22:31:03 +0000794 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000795 case TSK_Undeclared:
796 case TSK_ExplicitSpecialization:
797 case TSK_ImplicitInstantiation:
798 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000799
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000800 case TSK_ExplicitInstantiationDeclaration:
801 return shouldEmitAvailableExternallyVTable(*this, RD)
802 ? llvm::GlobalVariable::AvailableExternallyLinkage
803 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000804
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000805 case TSK_ExplicitInstantiationDefinition:
806 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000807 }
808
809 llvm_unreachable("Invalid TemplateSpecializationKind!");
810}
811
Eric Christopherd160c502016-01-29 01:35:53 +0000812/// This is a callback from Sema to tell us that that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +0000813/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000814///
Nico Weberb6a5d052015-01-15 04:07:35 +0000815/// This is only called for vtables that _must_ be emitted (mainly due to key
816/// functions). For weak vtables, CodeGen tracks when they are needed and
817/// emits them as-needed.
818void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000819 VTables.GenerateClassData(theClass);
820}
821
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000822void
John McCall6bd2a892013-01-25 22:31:03 +0000823CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000824 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
825 DI->completeClassData(RD);
826
Reid Kleckner7810af02013-06-19 15:20:38 +0000827 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000828 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000829
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000830 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000831}
John McCall6bd2a892013-01-25 22:31:03 +0000832
833/// At this point in the translation unit, does it appear that can we
834/// rely on the vtable being defined elsewhere in the program?
835///
836/// The response is really only definitive when called at the end of
837/// the translation unit.
838///
839/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +0000840/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +0000841/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +0000842/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +0000843bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000844 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000845
David Majnemer2d8b2002016-02-11 17:49:28 +0000846 // We always synthesize vtables on the import side regardless of whether or
847 // not it is an explicit instantiation declaration.
848 if (CGM.getTarget().getCXXABI().isMicrosoft() && RD->hasAttr<DLLImportAttr>())
849 return false;
850
John McCall6bd2a892013-01-25 22:31:03 +0000851 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +0000852 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +0000853 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
854 if (TSK == TSK_ExplicitInstantiationDeclaration)
855 return true;
856
857 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +0000858 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000859 if (TSK == TSK_ImplicitInstantiation ||
860 TSK == TSK_ExplicitInstantiationDefinition)
861 return false;
862
863 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +0000864 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000865 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
866 if (!keyFunction)
867 return false;
868
869 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +0000870 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +0000871 return !keyFunction->hasBody();
872}
873
874/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +0000875/// we've emitted a reference to the vtable for this class, should
876/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +0000877static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
878 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000879 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000880 if (!CGM.getVTables().isVTableExternal(RD))
881 return true;
882
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000883 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000884 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000885}
886
887/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +0000888/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +0000889/// decide whether we should emit them.
890void CodeGenModule::EmitDeferredVTables() {
891#ifndef NDEBUG
892 // Remember the size of DeferredVTables, because we're going to assume
893 // that this entire operation doesn't modify it.
894 size_t savedSize = DeferredVTables.size();
895#endif
896
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000897 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000898 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
899 VTables.GenerateClassData(RD);
John McCall6bd2a892013-01-25 22:31:03 +0000900
901 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +0000902 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +0000903 DeferredVTables.clear();
904}
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000905
Peter Collingbournefb532b92016-02-24 20:46:36 +0000906bool CodeGenModule::NeedVTableBitSets() {
907 return getCodeGenOpts().WholeProgramVTables ||
908 getLangOpts().Sanitize.has(SanitizerKind::CFIVCall) ||
909 getLangOpts().Sanitize.has(SanitizerKind::CFINVCall) ||
910 getLangOpts().Sanitize.has(SanitizerKind::CFIDerivedCast) ||
911 getLangOpts().Sanitize.has(SanitizerKind::CFIUnrelatedCast);
912}
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000913
Peter Collingbournefb532b92016-02-24 20:46:36 +0000914bool CodeGenModule::IsBitSetBlacklistedRecord(const CXXRecordDecl *RD) {
915 std::string TypeName = RD->getQualifiedNameAsString();
916 auto isInBlacklist = [&](const SanitizerBlacklist &BL) {
917 if (RD->hasAttr<UuidAttr>() && BL.isBlacklistedType("attr:uuid"))
918 return true;
919
920 return BL.isBlacklistedType(TypeName);
921 };
922
923 return isInBlacklist(WholeProgramVTablesBlacklist) ||
924 ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) ||
925 LangOpts.Sanitize.has(SanitizerKind::CFINVCall) ||
926 LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) ||
927 LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast)) &&
928 isInBlacklist(getContext().getSanitizerBlacklist()));
Peter Collingbournee5706442015-07-09 19:56:14 +0000929}
930
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000931void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
932 const VTableLayout &VTLayout) {
Peter Collingbournefb532b92016-02-24 20:46:36 +0000933 if (!NeedVTableBitSets())
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000934 return;
935
Peter Collingbourne86d34a72015-06-17 19:08:05 +0000936 CharUnits PointerWidth =
937 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000938
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000939 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
940 std::vector<BSEntry> BitsetEntries;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000941 // Create a bit set entry for each address point.
942 for (auto &&AP : VTLayout.getAddressPoints()) {
Peter Collingbournefb532b92016-02-24 20:46:36 +0000943 if (IsBitSetBlacklistedRecord(AP.first.getBase()))
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000944 continue;
945
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000946 BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000947 }
948
949 // Sort the bit set entries for determinism.
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000950 std::sort(BitsetEntries.begin(), BitsetEntries.end(),
951 [this](const BSEntry &E1, const BSEntry &E2) {
952 if (&E1 == &E2)
Peter Collingbourne47941902015-02-24 01:12:53 +0000953 return false;
954
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000955 std::string S1;
956 llvm::raw_string_ostream O1(S1);
957 getCXXABI().getMangleContext().mangleTypeName(
958 QualType(E1.first->getTypeForDecl(), 0), O1);
959 O1.flush();
960
961 std::string S2;
962 llvm::raw_string_ostream O2(S2);
963 getCXXABI().getMangleContext().mangleTypeName(
964 QualType(E2.first->getTypeForDecl(), 0), O2);
965 O2.flush();
966
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000967 if (S1 < S2)
968 return true;
969 if (S1 != S2)
970 return false;
971
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000972 return E1.second < E2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000973 });
974
975 llvm::NamedMDNode *BitsetsMD =
976 getModule().getOrInsertNamedMetadata("llvm.bitsets");
977 for (auto BitsetEntry : BitsetEntries)
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000978 CreateVTableBitSetEntry(BitsetsMD, VTable,
979 PointerWidth * BitsetEntry.second,
980 BitsetEntry.first);
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000981}