blob: 5c639a3b3d8bcff9eb6e375b8e726df08e2b783f [file] [log] [blame]
Anders Carlsson046c2942010-04-17 20:15:18 +00001//===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
Anders Carlssondbd920c2009-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 Carlssondbd920c2009-10-11 22:13:54 +000014#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Anders Carlssond6b07fb2009-11-27 20:47:55 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssondbd920c2009-10-11 22:13:54 +000018#include "clang/AST/RecordLayout.h"
John McCall7a536902010-08-05 20:39:18 +000019#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000020#include "llvm/ADT/DenseSet.h"
Anders Carlssonb9021e92010-02-27 16:18:19 +000021#include "llvm/ADT/SetVector.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000022#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000023#include "llvm/Support/Format.h"
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000024#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson5e454aa2010-03-17 20:06:32 +000025#include <algorithm>
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000026#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000027
28using namespace clang;
29using namespace CodeGen;
30
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000031CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
Timur Iskhodzhanov635de282013-07-30 09:46:19 +000032 : CGM(CGM), VTContext(CGM.getContext()) {
33 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
34 // FIXME: Eventually, we should only have one of V*TContexts available.
35 // Today we use both in the Microsoft ABI as MicrosoftVFTableContext
36 // is not completely supported in CodeGen yet.
37 VFTContext.reset(new MicrosoftVFTableContext(CGM.getContext()));
38 }
39}
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000040
Anders Carlsson19879c92010-03-23 17:17:29 +000041llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlsson84c49e42011-02-06 17:15:43 +000042 const ThunkInfo &Thunk) {
Anders Carlsson19879c92010-03-23 17:17:29 +000043 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
44
45 // Compute the mangled name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000046 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +000047 llvm::raw_svector_ostream Out(Name);
Anders Carlsson19879c92010-03-23 17:17:29 +000048 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall4c40d982010-08-31 07:33:07 +000049 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindolaf0be9792011-02-11 02:52:17 +000050 Thunk.This, Out);
Anders Carlsson19879c92010-03-23 17:17:29 +000051 else
Rafael Espindolaf0be9792011-02-11 02:52:17 +000052 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
53 Out.flush();
54
Chris Lattner2acc6e32011-07-18 04:24:23 +000055 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson84c49e42011-02-06 17:15:43 +000056 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
Anders Carlsson19879c92010-03-23 17:17:29 +000057}
58
John McCall65005532010-08-04 23:46:35 +000059static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
60 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +000061 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +000062
John McCall279b5eb2010-08-12 23:36:15 +000063 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
64 return;
65
John McCall65005532010-08-04 23:46:35 +000066 // If the thunk has weak/linkonce linkage, but the function must be
67 // emitted in every translation unit that references it, then we can
68 // emit its thunks with hidden visibility, since its thunks must be
69 // emitted when the function is.
70
John McCall7a536902010-08-05 20:39:18 +000071 // This follows CodeGenModule::setTypeVisibility; see the comments
72 // there for explanation.
John McCall65005532010-08-04 23:46:35 +000073
74 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
75 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
76 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
77 return;
78
John McCalld4c3d662013-02-20 01:54:26 +000079 if (MD->getExplicitVisibility(ValueDecl::VisibilityForValue))
John McCall65005532010-08-04 23:46:35 +000080 return;
81
82 switch (MD->getTemplateSpecializationKind()) {
John McCall65005532010-08-04 23:46:35 +000083 case TSK_ExplicitInstantiationDefinition:
84 case TSK_ExplicitInstantiationDeclaration:
85 return;
86
John McCall65005532010-08-04 23:46:35 +000087 case TSK_Undeclared:
88 break;
89
John McCall7a536902010-08-05 20:39:18 +000090 case TSK_ExplicitSpecialization:
John McCall65005532010-08-04 23:46:35 +000091 case TSK_ImplicitInstantiation:
Douglas Gregoraafd1112012-10-24 14:11:55 +000092 return;
John McCall65005532010-08-04 23:46:35 +000093 break;
94 }
95
96 // If there's an explicit definition, and that definition is
97 // out-of-line, then we can't assume that all users will have a
98 // definition to emit.
99 const FunctionDecl *Def = 0;
100 if (MD->hasBody(Def) && Def->isOutOfLine())
101 return;
102
103 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
104}
105
John McCall311b4422011-03-09 07:12:35 +0000106#ifndef NDEBUG
107static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
108 const ABIArgInfo &infoR, CanQualType typeR) {
109 return (infoL.getKind() == infoR.getKind() &&
110 (typeL == typeR ||
111 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
112 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
113}
114#endif
115
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000116static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
117 QualType ResultType, RValue RV,
118 const ThunkInfo &Thunk) {
119 // Emit the return adjustment.
120 bool NullCheckValue = !ResultType->isReferenceType();
121
122 llvm::BasicBlock *AdjustNull = 0;
123 llvm::BasicBlock *AdjustNotNull = 0;
124 llvm::BasicBlock *AdjustEnd = 0;
125
126 llvm::Value *ReturnValue = RV.getScalarVal();
127
128 if (NullCheckValue) {
129 AdjustNull = CGF.createBasicBlock("adjust.null");
130 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
131 AdjustEnd = CGF.createBasicBlock("adjust.end");
132
133 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
134 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
135 CGF.EmitBlock(AdjustNotNull);
136 }
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000137
138 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
139 Thunk.Return);
140
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000141 if (NullCheckValue) {
142 CGF.Builder.CreateBr(AdjustEnd);
143 CGF.EmitBlock(AdjustNull);
144 CGF.Builder.CreateBr(AdjustEnd);
145 CGF.EmitBlock(AdjustEnd);
146
147 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
148 PHI->addIncoming(ReturnValue, AdjustNotNull);
149 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
150 AdjustNull);
151 ReturnValue = PHI;
152 }
153
154 return RValue::get(ReturnValue);
155}
156
157// This function does roughly the same thing as GenerateThunk, but in a
158// very different way, so that va_start and va_end work correctly.
159// FIXME: This function assumes "this" is the first non-sret LLVM argument of
160// a function, and that there is an alloca built in the entry block
161// for all accesses to "this".
162// FIXME: This function assumes there is only one "ret" statement per function.
163// FIXME: Cloning isn't correct in the presence of indirect goto!
164// FIXME: This implementation of thunks bloats codesize by duplicating the
165// function definition. There are alternatives:
166// 1. Add some sort of stub support to LLVM for cases where we can
167// do a this adjustment, then a sibcall.
168// 2. We could transform the definition to take a va_list instead of an
169// actual variable argument list, then have the thunks (including a
170// no-op thunk for the regular definition) call va_start/va_end.
171// There's a bit of per-call overhead for this solution, but it's
172// better for codesize if the definition is long.
173void CodeGenFunction::GenerateVarArgsThunk(
174 llvm::Function *Fn,
175 const CGFunctionInfo &FnInfo,
176 GlobalDecl GD, const ThunkInfo &Thunk) {
177 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
178 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
179 QualType ResultType = FPT->getResultType();
180
181 // Get the original function
John McCallde5d3c72012-02-17 03:33:10 +0000182 assert(FnInfo.isVariadic());
183 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000184 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
185 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
186
187 // Clone to thunk.
Benjamin Kramer9b5ede52012-09-19 13:13:52 +0000188 llvm::ValueToValueMapTy VMap;
189 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
190 /*ModuleLevelChanges=*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000191 CGM.getModule().getFunctionList().push_back(NewFn);
192 Fn->replaceAllUsesWith(NewFn);
193 NewFn->takeName(Fn);
194 Fn->eraseFromParent();
195 Fn = NewFn;
196
197 // "Initialize" CGF (minimally).
198 CurFn = Fn;
199
200 // Get the "this" value
201 llvm::Function::arg_iterator AI = Fn->arg_begin();
202 if (CGM.ReturnTypeUsesSRet(FnInfo))
203 ++AI;
204
205 // Find the first store of "this", which will be to the alloca associated
206 // with "this".
207 llvm::Value *ThisPtr = &*AI;
208 llvm::BasicBlock *EntryBB = Fn->begin();
209 llvm::Instruction *ThisStore = 0;
210 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
211 I != E; I++) {
212 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
213 ThisStore = cast<llvm::StoreInst>(I);
214 break;
215 }
216 }
217 assert(ThisStore && "Store of this should be in entry block?");
218 // Adjust "this", if necessary.
219 Builder.SetInsertPoint(ThisStore);
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000220 llvm::Value *AdjustedThisPtr =
221 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000222 ThisStore->setOperand(0, AdjustedThisPtr);
223
224 if (!Thunk.Return.isEmpty()) {
225 // Fix up the returned value, if necessary.
226 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
227 llvm::Instruction *T = I->getTerminator();
228 if (isa<llvm::ReturnInst>(T)) {
229 RValue RV = RValue::get(T->getOperand(0));
230 T->eraseFromParent();
231 Builder.SetInsertPoint(&*I);
232 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
233 Builder.CreateRet(RV.getScalarVal());
234 break;
235 }
236 }
237 }
238}
239
John McCalld26bc762011-03-09 04:27:21 +0000240void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
241 const CGFunctionInfo &FnInfo,
242 GlobalDecl GD, const ThunkInfo &Thunk) {
Anders Carlsson519c3282010-03-24 00:39:18 +0000243 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
244 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlsson519c3282010-03-24 00:39:18 +0000245 QualType ThisType = MD->getThisType(getContext());
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000246 QualType ResultType =
247 CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getResultType();
Anders Carlsson519c3282010-03-24 00:39:18 +0000248
249 FunctionArgList FunctionArgs;
250
251 // FIXME: It would be nice if more of this code could be shared with
252 // CodeGenFunction::GenerateCode.
253
254 // Create the implicit 'this' parameter declaration.
John McCall4c40d982010-08-31 07:33:07 +0000255 CurGD = GD;
256 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000257
258 // Add the rest of the parameters.
259 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
260 E = MD->param_end(); I != E; ++I) {
261 ParmVarDecl *Param = *I;
262
John McCalld26bc762011-03-09 04:27:21 +0000263 FunctionArgs.push_back(Param);
Anders Carlsson519c3282010-03-24 00:39:18 +0000264 }
Alexey Samsonov34b41f82012-10-25 10:18:50 +0000265
John McCalld26bc762011-03-09 04:27:21 +0000266 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
267 SourceLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000268
John McCall4c40d982010-08-31 07:33:07 +0000269 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000270 CXXThisValue = CXXABIThisValue;
John McCall4c40d982010-08-31 07:33:07 +0000271
Anders Carlsson519c3282010-03-24 00:39:18 +0000272 // Adjust the 'this' pointer if necessary.
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000273 llvm::Value *AdjustedThisPtr =
274 CGM.getCXXABI().performThisAdjustment(*this, LoadCXXThis(), Thunk.This);
275
Anders Carlsson519c3282010-03-24 00:39:18 +0000276 CallArgList CallArgs;
277
278 // Add our adjusted 'this' pointer.
Eli Friedman04c9a492011-05-02 17:57:46 +0000279 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000280
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000281 if (isa<CXXDestructorDecl>(MD))
282 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, GD, CallArgs);
283
Anders Carlsson519c3282010-03-24 00:39:18 +0000284 // Add the rest of the parameters.
285 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
286 E = MD->param_end(); I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +0000287 ParmVarDecl *param = *I;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000288 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Anders Carlsson519c3282010-03-24 00:39:18 +0000289 }
290
291 // Get our callee.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000292 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +0000293 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
Anders Carlsson84c49e42011-02-06 17:15:43 +0000294 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson519c3282010-03-24 00:39:18 +0000295
John McCalld26bc762011-03-09 04:27:21 +0000296#ifndef NDEBUG
John McCall0f3d0972012-07-07 06:41:13 +0000297 const CGFunctionInfo &CallFnInfo =
298 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCallde5d3c72012-02-17 03:33:10 +0000299 RequiredArgs::forPrototypePlus(FPT, 1));
John McCall311b4422011-03-09 07:12:35 +0000300 assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
301 CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
302 CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
John McCall0f3d0972012-07-07 06:41:13 +0000303 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
304 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
John McCall311b4422011-03-09 07:12:35 +0000305 FnInfo.getReturnInfo(), FnInfo.getReturnType()));
306 assert(CallFnInfo.arg_size() == FnInfo.arg_size());
307 for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
308 assert(similar(CallFnInfo.arg_begin()[i].info,
309 CallFnInfo.arg_begin()[i].type,
310 FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000311#endif
Anders Carlsson519c3282010-03-24 00:39:18 +0000312
Douglas Gregorcb359df2010-05-20 05:54:35 +0000313 // Determine whether we have a return value slot to use.
314 ReturnValueSlot Slot;
315 if (!ResultType->isVoidType() &&
316 FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +0000317 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregorcb359df2010-05-20 05:54:35 +0000318 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
319
Anders Carlsson519c3282010-03-24 00:39:18 +0000320 // Now emit our call.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000321 RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
Anders Carlsson519c3282010-03-24 00:39:18 +0000322
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000323 if (!Thunk.Return.isEmpty())
324 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000325
Douglas Gregorcb359df2010-05-20 05:54:35 +0000326 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000327 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000328
John McCallbd9b65a2012-07-31 00:33:55 +0000329 // Disable the final ARC autorelease.
330 AutoreleaseResult = false;
331
Anders Carlsson519c3282010-03-24 00:39:18 +0000332 FinishFunction();
333
Anders Carlsson519c3282010-03-24 00:39:18 +0000334 // Set the right linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000335 CGM.setFunctionLinkage(GD, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000336
337 // Set the right visibility.
John McCall65005532010-08-04 23:46:35 +0000338 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000339}
340
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000341void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
342 bool ForVTable) {
John McCallde5d3c72012-02-17 03:33:10 +0000343 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalld26bc762011-03-09 04:27:21 +0000344
345 // FIXME: re-use FnInfo in this computation.
Anders Carlsson84c49e42011-02-06 17:15:43 +0000346 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson19879c92010-03-23 17:17:29 +0000347
Anders Carlsson7986ad52010-03-23 18:18:41 +0000348 // Strip off a bitcast if we got one back.
Anders Carlsson13d68982010-03-24 00:35:44 +0000349 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000350 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Anders Carlsson13d68982010-03-24 00:35:44 +0000351 Entry = CE->getOperand(0);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000352 }
353
Anders Carlsson7986ad52010-03-23 18:18:41 +0000354 // There's already a declaration with the same name, check if it has the same
355 // type or if we need to replace it.
Anders Carlsson13d68982010-03-24 00:35:44 +0000356 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000357 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Anders Carlsson13d68982010-03-24 00:35:44 +0000358 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000359
360 // If the types mismatch then we have to rewrite the definition.
361 assert(OldThunkFn->isDeclaration() &&
362 "Shouldn't replace non-declaration");
363
364 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000365 OldThunkFn->setName(StringRef());
Anders Carlsson84c49e42011-02-06 17:15:43 +0000366 Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000367
368 // If needed, replace the old thunk with a bitcast.
369 if (!OldThunkFn->use_empty()) {
370 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000371 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000372 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
373 }
374
375 // Remove the old thunk.
376 OldThunkFn->eraseFromParent();
377 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000378
Anders Carlsson519c3282010-03-24 00:39:18 +0000379 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000380 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
381 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000382
383 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000384 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000385 // There is already a thunk emitted for this function, do nothing.
386 return;
387 }
388
Anders Carlsson22df7b12011-02-06 20:09:44 +0000389 // If a function has a body, it should have available_externally linkage.
390 assert(ThunkFn->hasAvailableExternallyLinkage() &&
391 "Function should have available_externally linkage!");
392
393 // Change the linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000394 CGM.setFunctionLinkage(GD, ThunkFn);
Anders Carlsson22df7b12011-02-06 20:09:44 +0000395 return;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000396 }
397
Rafael Espindola022301b2012-09-21 20:39:32 +0000398 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
399
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000400 if (ThunkFn->isVarArg()) {
401 // Varargs thunks are special; we can't just generate a call because
402 // we can't copy the varargs. Our implementation is rather
403 // expensive/sucky at the moment, so don't generate the thunk unless
404 // we have to.
405 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
406 if (!UseAvailableExternallyLinkage)
407 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
408 } else {
409 // Normal thunk body generation.
410 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
411 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000412
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000413 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000414}
415
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000416void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
417 const ThunkInfo &Thunk) {
418 // If the ABI has key functions, only the TU with the key function should emit
419 // the thunk. However, we can allow inlining of thunks if we emit them with
420 // available_externally linkage together with vtables when optimizations are
421 // enabled.
422 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
423 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000424 return;
425
426 // We can't emit thunks for member functions with incomplete types.
427 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000428 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Kleckner7bb72302013-10-11 20:46:27 +0000429 MD->getType()->castAs<FunctionType>()))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000430 return;
431
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000432 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000433}
434
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000435void CodeGenVTables::EmitThunks(GlobalDecl GD)
436{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000437 const CXXMethodDecl *MD =
438 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
439
440 // We don't need to generate thunks for the base destructor.
441 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
442 return;
443
Timur Iskhodzhanovf0746582013-10-09 11:33:51 +0000444 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector;
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000445 if (VFTContext.isValid()) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000446 ThunkInfoVector = VFTContext->getThunkInfo(GD);
447 } else {
448 ThunkInfoVector = VTContext.getThunkInfo(GD);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000449 }
450
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000451 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000452 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000453
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000454 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000455 emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000456}
457
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000458llvm::Constant *
459CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000460 const VTableComponent *Components,
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000461 unsigned NumComponents,
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000462 const VTableLayout::VTableThunkTy *VTableThunks,
463 unsigned NumVTableThunks) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000465
Chris Lattner8b418682012-02-07 00:39:47 +0000466 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000467
Chris Lattner2acc6e32011-07-18 04:24:23 +0000468 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000469 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
470
471 QualType ClassType = CGM.getContext().getTagDeclType(RD);
472 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
473
474 unsigned NextVTableThunkIndex = 0;
475
David Blaikie2eb9a952012-10-16 22:56:05 +0000476 llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0;
Anders Carlsson67d568a2010-03-29 05:40:50 +0000477
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000478 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000479 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000480
481 llvm::Constant *Init = 0;
482
483 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000484 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000485 Init = llvm::ConstantInt::get(PtrDiffTy,
486 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000487 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
488 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000489 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000490 Init = llvm::ConstantInt::get(PtrDiffTy,
491 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000492 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
493 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000494 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000495 Init = llvm::ConstantInt::get(PtrDiffTy,
496 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000497 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
498 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000499 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000500 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
501 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000502 case VTableComponent::CK_FunctionPointer:
503 case VTableComponent::CK_CompleteDtorPointer:
504 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000505 GlobalDecl GD;
506
507 // Get the right global decl.
508 switch (Component.getKind()) {
509 default:
510 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000511 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000512 GD = Component.getFunctionDecl();
513 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000514 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000515 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
516 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000517 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000518 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
519 break;
520 }
521
Anders Carlsson67d568a2010-03-29 05:40:50 +0000522 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
523 // We have a pure virtual member function.
Joao Matose9af3e62012-07-17 19:17:58 +0000524 if (!PureVirtualFn) {
Eli Friedmancf15f172012-09-14 01:19:01 +0000525 llvm::FunctionType *Ty =
526 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
527 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
528 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
529 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matose9af3e62012-07-17 19:17:58 +0000530 CGM.Int8PtrTy);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000531 }
Anders Carlsson67d568a2010-03-29 05:40:50 +0000532 Init = PureVirtualFn;
David Blaikie2eb9a952012-10-16 22:56:05 +0000533 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
534 if (!DeletedVirtualFn) {
535 llvm::FunctionType *Ty =
536 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
537 StringRef DeletedCallName =
538 CGM.getCXXABI().GetDeletedVirtualCallName();
539 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
540 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
541 CGM.Int8PtrTy);
542 }
543 Init = DeletedVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000544 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000545 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000546 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000547 VTableThunks[NextVTableThunkIndex].first == I) {
548 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000549
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000550 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramerfce80092012-03-20 20:18:13 +0000551 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000552
Anders Carlsson67d568a2010-03-29 05:40:50 +0000553 NextVTableThunkIndex++;
554 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000555 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000556
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000557 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000558 }
559
560 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000561 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000562 break;
563 }
564
Anders Carlsson94464812010-04-10 19:13:06 +0000565 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000566 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
567 break;
568 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000569
570 Inits.push_back(Init);
571 }
572
573 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000574 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000575}
576
Anders Carlssonff143f82010-03-25 00:35:49 +0000577llvm::GlobalVariable *
578CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000579 const BaseSubobject &Base,
580 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000581 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000582 VTableAddressPointsMapTy& AddressPoints) {
David Blaikie6a29f672013-08-22 15:23:05 +0000583 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
584 DI->completeClassData(Base.getBase());
585
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000586 OwningPtr<VTableLayout> VTLayout(
Peter Collingbourneab172b52011-09-26 01:57:04 +0000587 VTContext.createConstructionVTableLayout(Base.getBase(),
588 Base.getBaseOffset(),
589 BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000590
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000591 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000592 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000593
594 // Get the mangled construction vtable name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000595 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000596 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000597 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
598 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
599 Base.getBase(), Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000600 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000601 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000602
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000603 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000604 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000605
Richard Smithb4127a22013-02-16 00:51:21 +0000606 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
607 // guarantee that they actually will be available externally. Instead, when
608 // emitting an available_externally VTT, we provide references to an internal
609 // linkage construction vtable. The ABI only requires complete-object vtables
610 // to be the same for all instances of a type, not construction vtables.
611 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
612 Linkage = llvm::GlobalVariable::InternalLinkage;
613
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000614 // Create the variable that will hold the construction vtable.
615 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000616 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
617 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
618
619 // V-tables are always unnamed_addr.
620 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000621
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000622 // Create and set the initializer.
623 llvm::Constant *Init =
624 CreateVTableInitializer(Base.getBase(),
Peter Collingbourneab172b52011-09-26 01:57:04 +0000625 VTLayout->vtable_component_begin(),
626 VTLayout->getNumVTableComponents(),
627 VTLayout->vtable_thunk_begin(),
628 VTLayout->getNumVTableThunks());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000629 VTable->setInitializer(Init);
630
Anders Carlssonff143f82010-03-25 00:35:49 +0000631 return VTable;
632}
633
John McCalld5617ee2013-01-25 22:31:03 +0000634/// Compute the required linkage of the v-table for the given class.
635///
636/// Note that we only call this at the end of the translation unit.
637llvm::GlobalVariable::LinkageTypes
638CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000639 if (!RD->isExternallyVisible())
John McCalld5617ee2013-01-25 22:31:03 +0000640 return llvm::GlobalVariable::InternalLinkage;
641
642 // We're at the end of the translation unit, so the current key
643 // function is fully correct.
644 if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
645 // If this class has a key function, use that to determine the
646 // linkage of the vtable.
647 const FunctionDecl *def = 0;
648 if (keyFunction->hasBody(def))
649 keyFunction = cast<CXXMethodDecl>(def);
650
651 switch (keyFunction->getTemplateSpecializationKind()) {
652 case TSK_Undeclared:
653 case TSK_ExplicitSpecialization:
Rafael Espindola889a6752013-09-03 21:05:13 +0000654 assert(def && "Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000655 if (keyFunction->isInlined())
656 return !Context.getLangOpts().AppleKext ?
657 llvm::GlobalVariable::LinkOnceODRLinkage :
658 llvm::Function::InternalLinkage;
659
660 return llvm::GlobalVariable::ExternalLinkage;
661
662 case TSK_ImplicitInstantiation:
663 return !Context.getLangOpts().AppleKext ?
664 llvm::GlobalVariable::LinkOnceODRLinkage :
665 llvm::Function::InternalLinkage;
666
667 case TSK_ExplicitInstantiationDefinition:
668 return !Context.getLangOpts().AppleKext ?
669 llvm::GlobalVariable::WeakODRLinkage :
670 llvm::Function::InternalLinkage;
671
672 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola889a6752013-09-03 21:05:13 +0000673 llvm_unreachable("Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000674 }
675 }
676
677 // -fapple-kext mode does not support weak linkage, so we must use
678 // internal linkage.
679 if (Context.getLangOpts().AppleKext)
680 return llvm::Function::InternalLinkage;
681
682 switch (RD->getTemplateSpecializationKind()) {
683 case TSK_Undeclared:
684 case TSK_ExplicitSpecialization:
685 case TSK_ImplicitInstantiation:
686 return llvm::GlobalVariable::LinkOnceODRLinkage;
687
688 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola889a6752013-09-03 21:05:13 +0000689 llvm_unreachable("Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000690
691 case TSK_ExplicitInstantiationDefinition:
692 return llvm::GlobalVariable::WeakODRLinkage;
693 }
694
695 llvm_unreachable("Invalid TemplateSpecializationKind!");
696}
697
698/// This is a callback from Sema to tell us that it believes that a
699/// particular v-table is required to be emitted in this translation
700/// unit.
701///
702/// The reason we don't simply trust this callback is because Sema
703/// will happily report that something is used even when it's used
704/// only in code that we don't actually have to emit.
705///
706/// \param isRequired - if true, the v-table is mandatory, e.g.
707/// because the translation unit defines the key function
708void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
709 if (!isRequired) return;
710
711 VTables.GenerateClassData(theClass);
712}
713
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000714void
John McCalld5617ee2013-01-25 22:31:03 +0000715CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikie6a29f672013-08-22 15:23:05 +0000716 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
717 DI->completeClassData(RD);
718
Reid Kleckner90633022013-06-19 15:20:38 +0000719 if (RD->getNumVBases())
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000720 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregor1e201b42010-04-08 15:52:03 +0000721
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000722 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000723}
John McCalld5617ee2013-01-25 22:31:03 +0000724
725/// At this point in the translation unit, does it appear that can we
726/// rely on the vtable being defined elsewhere in the program?
727///
728/// The response is really only definitive when called at the end of
729/// the translation unit.
730///
731/// The only semantic restriction here is that the object file should
732/// not contain a v-table definition when that v-table is defined
733/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
734/// v-tables when unnecessary.
735bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
736 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
737
738 // If we have an explicit instantiation declaration (and not a
739 // definition), the v-table is defined elsewhere.
740 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
741 if (TSK == TSK_ExplicitInstantiationDeclaration)
742 return true;
743
744 // Otherwise, if the class is an instantiated template, the
745 // v-table must be defined here.
746 if (TSK == TSK_ImplicitInstantiation ||
747 TSK == TSK_ExplicitInstantiationDefinition)
748 return false;
749
750 // Otherwise, if the class doesn't have a key function (possibly
751 // anymore), the v-table must be defined here.
752 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
753 if (!keyFunction)
754 return false;
755
756 // Otherwise, if we don't have a definition of the key function, the
757 // v-table must be defined somewhere else.
758 return !keyFunction->hasBody();
759}
760
761/// Given that we're currently at the end of the translation unit, and
762/// we've emitted a reference to the v-table for this class, should
763/// we define that v-table?
764static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
765 const CXXRecordDecl *RD) {
John McCalld5617ee2013-01-25 22:31:03 +0000766 return !CGM.getVTables().isVTableExternal(RD);
767}
768
769/// Given that at some point we emitted a reference to one or more
770/// v-tables, and that we are now at the end of the translation unit,
771/// decide whether we should emit them.
772void CodeGenModule::EmitDeferredVTables() {
773#ifndef NDEBUG
774 // Remember the size of DeferredVTables, because we're going to assume
775 // that this entire operation doesn't modify it.
776 size_t savedSize = DeferredVTables.size();
777#endif
778
779 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
780 for (const_iterator i = DeferredVTables.begin(),
781 e = DeferredVTables.end(); i != e; ++i) {
782 const CXXRecordDecl *RD = *i;
783 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
784 VTables.GenerateClassData(RD);
785 }
786
787 assert(savedSize == DeferredVTables.size() &&
788 "deferred extra v-tables during v-table emission?");
789 DeferredVTables.clear();
790}