blob: 4c3202ca656f18d09ae91f4caf2ee58f34125a71 [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"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
John McCall5513fce92010-08-05 20:39:18 +000020#include "clang/Frontend/CodeGenOptions.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"
Anders Carlsson56446142010-03-17 20:06:32 +000026#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000027#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000028
29using namespace clang;
30using namespace CodeGen;
31
Reid Kleckner96f8f932014-02-05 17:27:08 +000032CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000034
Anders Carlssoncd836f02010-03-23 17:17:29 +000035llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000036 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000037 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38
39 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000040 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000041 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000042 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000043 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000044 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000045 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000046 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +000047
Chris Lattner2192fe52011-07-18 04:24:23 +000048 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +000049 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000050 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000051}
52
John McCallc8bd9c22010-08-04 23:46:35 +000053static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
54 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000055 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000056}
57
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000058static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
59 llvm::Function *ThunkFn, bool ForVTable,
60 GlobalDecl GD) {
61 CGM.setFunctionLinkage(GD, ThunkFn);
62 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
63 !Thunk.Return.isEmpty());
64
65 // Set the right visibility.
66 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
67 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
68
69 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
70 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
71}
72
John McCall5fe00962011-03-09 07:12:35 +000073#ifndef NDEBUG
74static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
75 const ABIArgInfo &infoR, CanQualType typeR) {
76 return (infoL.getKind() == infoR.getKind() &&
77 (typeL == typeR ||
78 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
79 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
80}
81#endif
82
Eli Friedman49a94b12011-05-06 17:27:27 +000083static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
84 QualType ResultType, RValue RV,
85 const ThunkInfo &Thunk) {
86 // Emit the return adjustment.
87 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000088
89 llvm::BasicBlock *AdjustNull = nullptr;
90 llvm::BasicBlock *AdjustNotNull = nullptr;
91 llvm::BasicBlock *AdjustEnd = nullptr;
92
Eli Friedman49a94b12011-05-06 17:27:27 +000093 llvm::Value *ReturnValue = RV.getScalarVal();
94
95 if (NullCheckValue) {
96 AdjustNull = CGF.createBasicBlock("adjust.null");
97 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
98 AdjustEnd = CGF.createBasicBlock("adjust.end");
99
100 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
101 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
102 CGF.EmitBlock(AdjustNotNull);
103 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000104
John McCall7f416cc2015-09-08 08:05:57 +0000105 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
106 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
107 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
108 Address(ReturnValue, ClassAlign),
109 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000110
Eli Friedman49a94b12011-05-06 17:27:27 +0000111 if (NullCheckValue) {
112 CGF.Builder.CreateBr(AdjustEnd);
113 CGF.EmitBlock(AdjustNull);
114 CGF.Builder.CreateBr(AdjustEnd);
115 CGF.EmitBlock(AdjustEnd);
116
117 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
118 PHI->addIncoming(ReturnValue, AdjustNotNull);
119 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
120 AdjustNull);
121 ReturnValue = PHI;
122 }
123
124 return RValue::get(ReturnValue);
125}
126
127// This function does roughly the same thing as GenerateThunk, but in a
128// very different way, so that va_start and va_end work correctly.
129// FIXME: This function assumes "this" is the first non-sret LLVM argument of
130// a function, and that there is an alloca built in the entry block
131// for all accesses to "this".
132// FIXME: This function assumes there is only one "ret" statement per function.
133// FIXME: Cloning isn't correct in the presence of indirect goto!
134// FIXME: This implementation of thunks bloats codesize by duplicating the
135// function definition. There are alternatives:
136// 1. Add some sort of stub support to LLVM for cases where we can
137// do a this adjustment, then a sibcall.
138// 2. We could transform the definition to take a va_list instead of an
139// actual variable argument list, then have the thunks (including a
140// no-op thunk for the regular definition) call va_start/va_end.
141// There's a bit of per-call overhead for this solution, but it's
142// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000143llvm::Function *
144CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000145 const CGFunctionInfo &FnInfo,
146 GlobalDecl GD, const ThunkInfo &Thunk) {
147 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
148 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000149 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000150
151 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000152 assert(FnInfo.isVariadic());
153 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000154 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
155 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
156
157 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000158 llvm::ValueToValueMapTy VMap;
159 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
160 /*ModuleLevelChanges=*/false);
Eli Friedman49a94b12011-05-06 17:27:27 +0000161 CGM.getModule().getFunctionList().push_back(NewFn);
162 Fn->replaceAllUsesWith(NewFn);
163 NewFn->takeName(Fn);
164 Fn->eraseFromParent();
165 Fn = NewFn;
166
167 // "Initialize" CGF (minimally).
168 CurFn = Fn;
169
170 // Get the "this" value
171 llvm::Function::arg_iterator AI = Fn->arg_begin();
172 if (CGM.ReturnTypeUsesSRet(FnInfo))
173 ++AI;
174
175 // Find the first store of "this", which will be to the alloca associated
176 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000177 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Eli Friedman49a94b12011-05-06 17:27:27 +0000178 llvm::BasicBlock *EntryBB = Fn->begin();
David Blaikiea629c0f2014-12-29 22:39:45 +0000179 llvm::Instruction *ThisStore =
180 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
John McCall7f416cc2015-09-08 08:05:57 +0000181 return isa<llvm::StoreInst>(I) && I.getOperand(0) == ThisPtr.getPointer();
David Blaikiea629c0f2014-12-29 22:39:45 +0000182 });
Eli Friedman49a94b12011-05-06 17:27:27 +0000183 assert(ThisStore && "Store of this should be in entry block?");
184 // Adjust "this", if necessary.
185 Builder.SetInsertPoint(ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000186 llvm::Value *AdjustedThisPtr =
187 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000188 ThisStore->setOperand(0, AdjustedThisPtr);
189
190 if (!Thunk.Return.isEmpty()) {
191 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000192 for (llvm::BasicBlock &BB : *Fn) {
193 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000194 if (isa<llvm::ReturnInst>(T)) {
195 RValue RV = RValue::get(T->getOperand(0));
196 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000197 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000198 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
199 Builder.CreateRet(RV.getScalarVal());
200 break;
201 }
202 }
203 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000204
205 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000206}
207
Hans Wennborg88497d62013-11-15 17:24:45 +0000208void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
209 const CGFunctionInfo &FnInfo) {
210 assert(!CurGD.getDecl() && "CurGD was already set!");
211 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000212 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000213
214 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000215 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000216 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000217 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000218 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
219 ? ThisType
220 : CGM.getCXXABI().hasMostDerivedReturn(GD)
221 ? CGM.getContext().VoidPtrTy
222 : FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000223 FunctionArgList FunctionArgs;
224
Anders Carlssonbad991d2010-03-24 00:39:18 +0000225 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000226 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000227
228 // Add the rest of the parameters.
Alexey Samsonov3551e312014-08-13 20:06:24 +0000229 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000230
Reid Kleckner89077a12013-12-17 19:46:40 +0000231 if (isa<CXXDestructorDecl>(MD))
232 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
233
Hans Wennborg88497d62013-11-15 17:24:45 +0000234 // Start defining the function.
John McCalla738c252011-03-09 04:27:21 +0000235 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
David Blaikie4d5c7282014-12-29 22:53:52 +0000236 MD->getLocation(), MD->getLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000237
Hans Wennborg88497d62013-11-15 17:24:45 +0000238 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000239 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000240 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000241 CurCodeDecl = MD;
242 CurFuncDecl = MD;
243}
244
245void CodeGenFunction::FinishThunk() {
246 // Clear these to restore the invariants expected by
247 // StartFunction/FinishFunction.
248 CurCodeDecl = nullptr;
249 CurFuncDecl = nullptr;
250
251 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000252}
John McCall5d865c322010-08-31 07:33:07 +0000253
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000254void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg88497d62013-11-15 17:24:45 +0000255 const ThunkInfo *Thunk) {
256 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
257 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000258 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000259
Hans Wennborg88497d62013-11-15 17:24:45 +0000260 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000261 llvm::Value *AdjustedThisPtr =
262 Thunk ? CGM.getCXXABI().performThisAdjustment(
263 *this, LoadCXXThisAddress(), Thunk->This)
264 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000265
Reid Klecknerab2090d2014-07-26 01:34:32 +0000266 if (CurFnInfo->usesInAlloca()) {
267 // We don't handle return adjusting thunks, because they require us to call
268 // the copy constructor. For now, fall through and pretend the return
269 // adjustment was empty so we don't crash.
270 if (Thunk && !Thunk->Return.isEmpty()) {
271 CGM.ErrorUnsupported(
272 MD, "non-trivial argument copy for return-adjusting thunk");
273 }
274 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
275 return;
276 }
277
Hans Wennborg88497d62013-11-15 17:24:45 +0000278 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000279 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000280 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000281 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000282
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000283 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000284 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000285
Hans Wennborg88497d62013-11-15 17:24:45 +0000286 // Add the rest of the arguments.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000287 for (const ParmVarDecl *PD : MD->params())
288 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000289
Hans Wennborg88497d62013-11-15 17:24:45 +0000290 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000291
John McCalla738c252011-03-09 04:27:21 +0000292#ifndef NDEBUG
John McCall8dda7b22012-07-07 06:41:13 +0000293 const CGFunctionInfo &CallFnInfo =
294 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCalla729c622012-02-17 03:33:10 +0000295 RequiredArgs::forPrototypePlus(FPT, 1));
Hans Wennborg88497d62013-11-15 17:24:45 +0000296 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
297 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
298 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000299 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
300 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000301 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
302 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
303 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000304 assert(similar(CallFnInfo.arg_begin()[i].info,
305 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000306 CurFnInfo->arg_begin()[i].info,
307 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000308#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000309
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000310 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000311 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
312 ? ThisType
313 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
314 ? CGM.getContext().VoidPtrTy
315 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000316 ReturnValueSlot Slot;
317 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000318 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000319 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000320 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
321
Anders Carlssonbad991d2010-03-24 00:39:18 +0000322 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000323 llvm::Instruction *CallOrInvoke;
324 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
325
Hans Wennborg88497d62013-11-15 17:24:45 +0000326 // Consider return adjustment if we have ThunkInfo.
327 if (Thunk && !Thunk->Return.isEmpty())
328 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000329 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
330 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000331
Hans Wennborg88497d62013-11-15 17:24:45 +0000332 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000333 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000334 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000335
John McCallff755cd2012-07-31 00:33:55 +0000336 // Disable the final ARC autorelease.
337 AutoreleaseResult = false;
338
John McCall7f416cc2015-09-08 08:05:57 +0000339 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000340}
341
Reid Klecknerab2090d2014-07-26 01:34:32 +0000342void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
343 llvm::Value *AdjustedThisPtr,
344 llvm::Value *Callee) {
345 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
346 // to translate AST arguments into LLVM IR arguments. For thunks, we know
347 // that the caller prototype more or less matches the callee prototype with
348 // the exception of 'this'.
349 SmallVector<llvm::Value *, 8> Args;
350 for (llvm::Argument &A : CurFn->args())
351 Args.push_back(&A);
352
353 // Set the adjusted 'this' pointer.
354 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
355 if (ThisAI.isDirect()) {
356 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
357 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
358 llvm::Type *ThisType = Args[ThisArgNo]->getType();
359 if (ThisType != AdjustedThisPtr->getType())
360 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
361 Args[ThisArgNo] = AdjustedThisPtr;
362 } else {
363 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000364 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
365 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000366 if (ThisType != AdjustedThisPtr->getType())
367 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
368 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
369 }
370
371 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
372 // don't actually want to run them.
373 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
374 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
375
376 // Apply the standard set of call attributes.
377 unsigned CallingConv;
378 CodeGen::AttributeListType AttributeList;
379 CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
380 /*AttrOnCallSite=*/true);
381 llvm::AttributeSet Attrs =
382 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
383 Call->setAttributes(Attrs);
384 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
385
386 if (Call->getType()->isVoidTy())
387 Builder.CreateRetVoid();
388 else
389 Builder.CreateRet(Call);
390
391 // Finish the function to maintain CodeGenFunction invariants.
392 // FIXME: Don't emit unreachable code.
393 EmitBlock(createBasicBlock());
394 FinishFunction();
395}
396
Rafael Espindolad6e66942015-07-13 06:07:58 +0000397void CodeGenFunction::generateThunk(llvm::Function *Fn,
Hans Wennborg88497d62013-11-15 17:24:45 +0000398 const CGFunctionInfo &FnInfo,
399 GlobalDecl GD, const ThunkInfo &Thunk) {
400 StartThunk(Fn, GD, FnInfo);
401
402 // Get our callee.
403 llvm::Type *Ty =
404 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
405 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
406
407 // Make the call and return the result.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000408 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000409}
410
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000411void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
412 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000413 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000414
415 // FIXME: re-use FnInfo in this computation.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000416 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
417 llvm::GlobalValue *Entry;
418
Anders Carlsson55e89f82010-03-23 18:18:41 +0000419 // Strip off a bitcast if we got one back.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000420 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000421 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000422 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
423 } else {
424 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000425 }
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000426
Anders Carlsson55e89f82010-03-23 18:18:41 +0000427 // There's already a declaration with the same name, check if it has the same
428 // type or if we need to replace it.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000429 if (Entry->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000430 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000431 llvm::GlobalValue *OldThunkFn = Entry;
432
Anders Carlsson55e89f82010-03-23 18:18:41 +0000433 // If the types mismatch then we have to rewrite the definition.
434 assert(OldThunkFn->isDeclaration() &&
435 "Shouldn't replace non-declaration");
436
437 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000438 OldThunkFn->setName(StringRef());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000439 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson55e89f82010-03-23 18:18:41 +0000440
441 // If needed, replace the old thunk with a bitcast.
442 if (!OldThunkFn->use_empty()) {
443 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000444 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000445 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
446 }
447
448 // Remove the old thunk.
449 OldThunkFn->eraseFromParent();
450 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000451
Anders Carlssonbad991d2010-03-24 00:39:18 +0000452 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000453 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
454 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000455
456 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000457 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000458 // There is already a thunk emitted for this function, do nothing.
459 return;
460 }
461
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000462 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlssone866d442011-02-06 20:09:44 +0000463 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000464 }
465
Rafael Espindola86792432012-09-21 20:39:32 +0000466 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
467
Eli Friedman49a94b12011-05-06 17:27:27 +0000468 if (ThunkFn->isVarArg()) {
469 // Varargs thunks are special; we can't just generate a call because
470 // we can't copy the varargs. Our implementation is rather
471 // expensive/sucky at the moment, so don't generate the thunk unless
472 // we have to.
473 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Peter Collingbourne45a24012015-06-30 19:07:26 +0000474 if (UseAvailableExternallyLinkage)
475 return;
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000476 ThunkFn =
477 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000478 } else {
479 // Normal thunk body generation.
Rafael Espindolad6e66942015-07-13 06:07:58 +0000480 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000481 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000482
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000483 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlsson8b021832011-02-06 18:31:40 +0000484}
485
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000486void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
487 const ThunkInfo &Thunk) {
488 // If the ABI has key functions, only the TU with the key function should emit
489 // the thunk. However, we can allow inlining of thunks if we emit them with
490 // available_externally linkage together with vtables when optimizations are
491 // enabled.
492 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
493 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000494 return;
495
496 // We can't emit thunks for member functions with incomplete types.
497 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000498 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000499 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000500 return;
501
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000502 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000503}
504
Anders Carlsson917229c2010-03-23 04:59:02 +0000505void CodeGenVTables::EmitThunks(GlobalDecl GD)
506{
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000507 const CXXMethodDecl *MD =
508 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
509
510 // We don't need to generate thunks for the base destructor.
511 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
512 return;
513
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000514 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
515 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000516
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000517 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000518 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000519
Yaron Kerenede60302015-08-01 19:11:36 +0000520 for (const ThunkInfo& Thunk : *ThunkInfoVector)
521 emitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000522}
523
David Majnemerd905da42014-07-01 20:30:31 +0000524llvm::Constant *CodeGenVTables::CreateVTableInitializer(
525 const CXXRecordDecl *RD, const VTableComponent *Components,
526 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
527 unsigned NumVTableThunks, llvm::Constant *RTTI) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000528 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlssona4147142010-03-25 15:26:28 +0000529
Chris Lattnerece04092012-02-07 00:39:47 +0000530 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlssona4147142010-03-25 15:26:28 +0000531
Chris Lattner2192fe52011-07-18 04:24:23 +0000532 llvm::Type *PtrDiffTy =
Anders Carlssona5736bd2010-03-25 16:49:53 +0000533 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
534
Anders Carlssona5736bd2010-03-25 16:49:53 +0000535 unsigned NextVTableThunkIndex = 0;
Craig Topper8a13c412014-05-21 05:09:00 +0000536
537 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000538
Anders Carlssona4147142010-03-25 15:26:28 +0000539 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000540 VTableComponent Component = Components[I];
Anders Carlssona5736bd2010-03-25 16:49:53 +0000541
Craig Topper8a13c412014-05-21 05:09:00 +0000542 llvm::Constant *Init = nullptr;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000543
544 switch (Component.getKind()) {
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000545 case VTableComponent::CK_VCallOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000546 Init = llvm::ConstantInt::get(PtrDiffTy,
547 Component.getVCallOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000548 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
549 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000550 case VTableComponent::CK_VBaseOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000551 Init = llvm::ConstantInt::get(PtrDiffTy,
552 Component.getVBaseOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000553 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
554 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000555 case VTableComponent::CK_OffsetToTop:
Ken Dyck872d74a2011-04-02 01:14:48 +0000556 Init = llvm::ConstantInt::get(PtrDiffTy,
557 Component.getOffsetToTop().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000558 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
559 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000560 case VTableComponent::CK_RTTI:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000561 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
562 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000563 case VTableComponent::CK_FunctionPointer:
564 case VTableComponent::CK_CompleteDtorPointer:
565 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlssona5736bd2010-03-25 16:49:53 +0000566 GlobalDecl GD;
567
568 // Get the right global decl.
569 switch (Component.getKind()) {
570 default:
571 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000572 case VTableComponent::CK_FunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000573 GD = Component.getFunctionDecl();
574 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000575 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000576 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
577 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000578 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000579 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
580 break;
581 }
582
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000583 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
584 // We have a pure virtual member function.
Joao Matos718a8832012-07-17 19:17:58 +0000585 if (!PureVirtualFn) {
Eli Friedman48a32912012-09-14 01:19:01 +0000586 llvm::FunctionType *Ty =
587 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
588 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
589 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
590 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matos718a8832012-07-17 19:17:58 +0000591 CGM.Int8PtrTy);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000592 }
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000593 Init = PureVirtualFn;
David Blaikieeb7d5982012-10-16 22:56:05 +0000594 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
595 if (!DeletedVirtualFn) {
596 llvm::FunctionType *Ty =
597 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
598 StringRef DeletedCallName =
599 CGM.getCXXABI().GetDeletedVirtualCallName();
600 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
601 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
602 CGM.Int8PtrTy);
603 }
604 Init = DeletedVirtualFn;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000605 } else {
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000606 // Check if we should use a thunk.
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000607 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000608 VTableThunks[NextVTableThunkIndex].first == I) {
609 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000610
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000611 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramere6b4a162012-03-20 20:18:13 +0000612 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson8b021832011-02-06 18:31:40 +0000613
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000614 NextVTableThunkIndex++;
615 } else {
Chris Lattner2192fe52011-07-18 04:24:23 +0000616 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000617
Anders Carlsson3c239482011-02-05 04:35:53 +0000618 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000619 }
620
621 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000622 }
Anders Carlssona5736bd2010-03-25 16:49:53 +0000623 break;
624 }
625
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000626 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000627 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
628 break;
629 };
Anders Carlssona4147142010-03-25 15:26:28 +0000630
631 Inits.push_back(Init);
632 }
633
634 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad83be3612011-06-22 09:24:39 +0000635 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlssona4147142010-03-25 15:26:28 +0000636}
637
Anders Carlsson0534b022010-03-25 00:35:49 +0000638llvm::GlobalVariable *
639CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlssona208b392010-03-26 03:56:54 +0000640 const BaseSubobject &Base,
641 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000642 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000643 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000644 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
645 DI->completeClassData(Base.getBase());
646
Ahmed Charlesb8984322014-03-07 20:03:18 +0000647 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000648 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000649 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000650
Anders Carlssona5736bd2010-03-25 16:49:53 +0000651 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000652 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000653
654 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000655 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000656 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000657 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
658 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
659 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000660 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000661
Anders Carlssona4147142010-03-25 15:26:28 +0000662 llvm::ArrayType *ArrayType =
Chris Lattnerece04092012-02-07 00:39:47 +0000663 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlssona4147142010-03-25 15:26:28 +0000664
Richard Smith65fd2a42013-02-16 00:51:21 +0000665 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
666 // guarantee that they actually will be available externally. Instead, when
667 // emitting an available_externally VTT, we provide references to an internal
668 // linkage construction vtable. The ABI only requires complete-object vtables
669 // to be the same for all instances of a type, not construction vtables.
670 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
671 Linkage = llvm::GlobalVariable::InternalLinkage;
672
Anders Carlssona4147142010-03-25 15:26:28 +0000673 // Create the variable that will hold the construction vtable.
674 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000675 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
John McCall8f80a612014-02-08 00:41:16 +0000676 CGM.setGlobalVisibility(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000677
678 // V-tables are always unnamed_addr.
679 VTable->setUnnamedAddr(true);
Anders Carlssona4147142010-03-25 15:26:28 +0000680
David Majnemerd905da42014-07-01 20:30:31 +0000681 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
682 CGM.getContext().getTagDeclType(Base.getBase()));
683
Anders Carlssona4147142010-03-25 15:26:28 +0000684 // Create and set the initializer.
David Majnemerd905da42014-07-01 20:30:31 +0000685 llvm::Constant *Init = CreateVTableInitializer(
686 Base.getBase(), VTLayout->vtable_component_begin(),
687 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
688 VTLayout->getNumVTableThunks(), RTTI);
Anders Carlssona4147142010-03-25 15:26:28 +0000689 VTable->setInitializer(Init);
690
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000691 CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
692
Anders Carlsson0534b022010-03-25 00:35:49 +0000693 return VTable;
694}
695
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000696static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
697 const CXXRecordDecl *RD) {
698 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000699 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000700}
701
John McCall6bd2a892013-01-25 22:31:03 +0000702/// Compute the required linkage of the v-table for the given class.
703///
704/// Note that we only call this at the end of the translation unit.
705llvm::GlobalVariable::LinkageTypes
706CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000707 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000708 return llvm::GlobalVariable::InternalLinkage;
709
710 // We're at the end of the translation unit, so the current key
711 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000712 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
713 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000714 // If this class has a key function, use that to determine the
715 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000716 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000717 if (keyFunction->hasBody(def))
718 keyFunction = cast<CXXMethodDecl>(def);
719
720 switch (keyFunction->getTemplateSpecializationKind()) {
721 case TSK_Undeclared:
722 case TSK_ExplicitSpecialization:
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000723 assert((def || CodeGenOpts.OptimizationLevel > 0) &&
724 "Shouldn't query vtable linkage without key function or "
725 "optimizations");
726 if (!def && CodeGenOpts.OptimizationLevel > 0)
727 return llvm::GlobalVariable::AvailableExternallyLinkage;
728
John McCall6bd2a892013-01-25 22:31:03 +0000729 if (keyFunction->isInlined())
730 return !Context.getLangOpts().AppleKext ?
731 llvm::GlobalVariable::LinkOnceODRLinkage :
732 llvm::Function::InternalLinkage;
733
734 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000735
John McCall6bd2a892013-01-25 22:31:03 +0000736 case TSK_ImplicitInstantiation:
737 return !Context.getLangOpts().AppleKext ?
738 llvm::GlobalVariable::LinkOnceODRLinkage :
739 llvm::Function::InternalLinkage;
740
741 case TSK_ExplicitInstantiationDefinition:
742 return !Context.getLangOpts().AppleKext ?
743 llvm::GlobalVariable::WeakODRLinkage :
744 llvm::Function::InternalLinkage;
745
746 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000747 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000748 }
749 }
750
751 // -fapple-kext mode does not support weak linkage, so we must use
752 // internal linkage.
753 if (Context.getLangOpts().AppleKext)
754 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000755
756 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
757 llvm::GlobalValue::LinkOnceODRLinkage;
758 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
759 llvm::GlobalValue::WeakODRLinkage;
760 if (RD->hasAttr<DLLExportAttr>()) {
761 // Cannot discard exported vtables.
762 DiscardableODRLinkage = NonDiscardableODRLinkage;
763 } else if (RD->hasAttr<DLLImportAttr>()) {
764 // Imported vtables are available externally.
765 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
766 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
767 }
768
John McCall6bd2a892013-01-25 22:31:03 +0000769 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000770 case TSK_Undeclared:
771 case TSK_ExplicitSpecialization:
772 case TSK_ImplicitInstantiation:
773 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000774
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000775 case TSK_ExplicitInstantiationDeclaration:
776 return shouldEmitAvailableExternallyVTable(*this, RD)
777 ? llvm::GlobalVariable::AvailableExternallyLinkage
778 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000779
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000780 case TSK_ExplicitInstantiationDefinition:
781 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000782 }
783
784 llvm_unreachable("Invalid TemplateSpecializationKind!");
785}
786
Nico Weberb6a5d052015-01-15 04:07:35 +0000787/// This is a callback from Sema to tell us that that a particular v-table is
788/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000789///
Nico Weberb6a5d052015-01-15 04:07:35 +0000790/// This is only called for vtables that _must_ be emitted (mainly due to key
791/// functions). For weak vtables, CodeGen tracks when they are needed and
792/// emits them as-needed.
793void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000794 VTables.GenerateClassData(theClass);
795}
796
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000797void
John McCall6bd2a892013-01-25 22:31:03 +0000798CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000799 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
800 DI->completeClassData(RD);
801
Reid Kleckner7810af02013-06-19 15:20:38 +0000802 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000803 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000804
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000805 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000806}
John McCall6bd2a892013-01-25 22:31:03 +0000807
808/// At this point in the translation unit, does it appear that can we
809/// rely on the vtable being defined elsewhere in the program?
810///
811/// The response is really only definitive when called at the end of
812/// the translation unit.
813///
814/// The only semantic restriction here is that the object file should
815/// not contain a v-table definition when that v-table is defined
816/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
817/// v-tables when unnecessary.
818bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000819 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000820
821 // If we have an explicit instantiation declaration (and not a
822 // definition), the v-table is defined elsewhere.
823 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
824 if (TSK == TSK_ExplicitInstantiationDeclaration)
825 return true;
826
827 // Otherwise, if the class is an instantiated template, the
828 // v-table must be defined here.
829 if (TSK == TSK_ImplicitInstantiation ||
830 TSK == TSK_ExplicitInstantiationDefinition)
831 return false;
832
833 // Otherwise, if the class doesn't have a key function (possibly
834 // anymore), the v-table must be defined here.
835 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
836 if (!keyFunction)
837 return false;
838
839 // Otherwise, if we don't have a definition of the key function, the
840 // v-table must be defined somewhere else.
841 return !keyFunction->hasBody();
842}
843
844/// Given that we're currently at the end of the translation unit, and
845/// we've emitted a reference to the v-table for this class, should
846/// we define that v-table?
847static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
848 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000849 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000850 if (!CGM.getVTables().isVTableExternal(RD))
851 return true;
852
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000853 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000854 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000855}
856
857/// Given that at some point we emitted a reference to one or more
858/// v-tables, and that we are now at the end of the translation unit,
859/// decide whether we should emit them.
860void CodeGenModule::EmitDeferredVTables() {
861#ifndef NDEBUG
862 // Remember the size of DeferredVTables, because we're going to assume
863 // that this entire operation doesn't modify it.
864 size_t savedSize = DeferredVTables.size();
865#endif
866
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000867 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000868 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
869 VTables.GenerateClassData(RD);
John McCall6bd2a892013-01-25 22:31:03 +0000870
871 assert(savedSize == DeferredVTables.size() &&
872 "deferred extra v-tables during v-table emission?");
873 DeferredVTables.clear();
874}
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000875
Peter Collingbournee5706442015-07-09 19:56:14 +0000876bool CodeGenModule::IsCFIBlacklistedRecord(const CXXRecordDecl *RD) {
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000877 if (RD->hasAttr<UuidAttr>() &&
878 getContext().getSanitizerBlacklist().isBlacklistedType("attr:uuid"))
879 return true;
880
881 return getContext().getSanitizerBlacklist().isBlacklistedType(
882 RD->getQualifiedNameAsString());
Peter Collingbournee5706442015-07-09 19:56:14 +0000883}
884
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000885void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
886 const VTableLayout &VTLayout) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000887 if (!LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
888 !LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
889 !LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
890 !LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000891 return;
892
Peter Collingbourne86d34a72015-06-17 19:08:05 +0000893 CharUnits PointerWidth =
894 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000895
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000896 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
897 std::vector<BSEntry> BitsetEntries;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000898 // Create a bit set entry for each address point.
899 for (auto &&AP : VTLayout.getAddressPoints()) {
Peter Collingbournee5706442015-07-09 19:56:14 +0000900 if (IsCFIBlacklistedRecord(AP.first.getBase()))
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000901 continue;
902
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000903 BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000904 }
905
906 // Sort the bit set entries for determinism.
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000907 std::sort(BitsetEntries.begin(), BitsetEntries.end(),
908 [this](const BSEntry &E1, const BSEntry &E2) {
909 if (&E1 == &E2)
Peter Collingbourne47941902015-02-24 01:12:53 +0000910 return false;
911
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000912 std::string S1;
913 llvm::raw_string_ostream O1(S1);
914 getCXXABI().getMangleContext().mangleTypeName(
915 QualType(E1.first->getTypeForDecl(), 0), O1);
916 O1.flush();
917
918 std::string S2;
919 llvm::raw_string_ostream O2(S2);
920 getCXXABI().getMangleContext().mangleTypeName(
921 QualType(E2.first->getTypeForDecl(), 0), O2);
922 O2.flush();
923
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000924 if (S1 < S2)
925 return true;
926 if (S1 != S2)
927 return false;
928
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000929 return E1.second < E2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000930 });
931
932 llvm::NamedMDNode *BitsetsMD =
933 getModule().getOrInsertNamedMetadata("llvm.bitsets");
934 for (auto BitsetEntry : BitsetEntries)
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000935 BitsetsMD->addOperand(CreateVTableBitSetEntry(
936 VTable, PointerWidth * BitsetEntry.second, BitsetEntry.first));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000937}