blob: 42e22f0d74b69b48cb04382261a12e3148a18560 [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
Peter Collingbournea8341662011-09-26 01:56:30 +000032CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
Timur Iskhodzhanov58776632013-11-05 15:54:58 +000033 : CGM(CGM), ItaniumVTContext(CGM.getContext()) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000034 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
35 // FIXME: Eventually, we should only have one of V*TContexts available.
36 // Today we use both in the Microsoft ABI as MicrosoftVFTableContext
37 // is not completely supported in CodeGen yet.
Timur Iskhodzhanov58776632013-11-05 15:54:58 +000038 MicrosoftVTContext.reset(new MicrosoftVTableContext(CGM.getContext()));
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +000039 }
40}
Peter Collingbournea8341662011-09-26 01:56:30 +000041
Anders Carlssoncd836f02010-03-23 17:17:29 +000042llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000043 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000044 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
45
46 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000047 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000048 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000049 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000050 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000051 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000052 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000053 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
54 Out.flush();
55
Chris Lattner2192fe52011-07-18 04:24:23 +000056 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Anders Carlssonfe8a9932011-02-06 17:15:43 +000057 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000058}
59
John McCallc8bd9c22010-08-04 23:46:35 +000060static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
61 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000062 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000063
John McCallb3732bb2010-08-12 23:36:15 +000064 if (!CGM.getCodeGenOpts().HiddenWeakVTables)
65 return;
66
John McCallc8bd9c22010-08-04 23:46:35 +000067 // If the thunk has weak/linkonce linkage, but the function must be
68 // emitted in every translation unit that references it, then we can
69 // emit its thunks with hidden visibility, since its thunks must be
70 // emitted when the function is.
71
John McCall5513fce92010-08-05 20:39:18 +000072 // This follows CodeGenModule::setTypeVisibility; see the comments
73 // there for explanation.
John McCallc8bd9c22010-08-04 23:46:35 +000074
75 if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
76 Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
77 Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
78 return;
79
John McCalld041a9b2013-02-20 01:54:26 +000080 if (MD->getExplicitVisibility(ValueDecl::VisibilityForValue))
John McCallc8bd9c22010-08-04 23:46:35 +000081 return;
82
83 switch (MD->getTemplateSpecializationKind()) {
John McCallc8bd9c22010-08-04 23:46:35 +000084 case TSK_ExplicitInstantiationDefinition:
85 case TSK_ExplicitInstantiationDeclaration:
86 return;
87
John McCallc8bd9c22010-08-04 23:46:35 +000088 case TSK_Undeclared:
89 break;
90
John McCall5513fce92010-08-05 20:39:18 +000091 case TSK_ExplicitSpecialization:
John McCallc8bd9c22010-08-04 23:46:35 +000092 case TSK_ImplicitInstantiation:
Douglas Gregor47c08962012-10-24 14:11:55 +000093 return;
John McCallc8bd9c22010-08-04 23:46:35 +000094 break;
95 }
96
97 // If there's an explicit definition, and that definition is
98 // out-of-line, then we can't assume that all users will have a
99 // definition to emit.
100 const FunctionDecl *Def = 0;
101 if (MD->hasBody(Def) && Def->isOutOfLine())
102 return;
103
104 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
105}
106
John McCall5fe00962011-03-09 07:12:35 +0000107#ifndef NDEBUG
108static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
109 const ABIArgInfo &infoR, CanQualType typeR) {
110 return (infoL.getKind() == infoR.getKind() &&
111 (typeL == typeR ||
112 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
113 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
114}
115#endif
116
Eli Friedman49a94b12011-05-06 17:27:27 +0000117static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
118 QualType ResultType, RValue RV,
119 const ThunkInfo &Thunk) {
120 // Emit the return adjustment.
121 bool NullCheckValue = !ResultType->isReferenceType();
122
123 llvm::BasicBlock *AdjustNull = 0;
124 llvm::BasicBlock *AdjustNotNull = 0;
125 llvm::BasicBlock *AdjustEnd = 0;
126
127 llvm::Value *ReturnValue = RV.getScalarVal();
128
129 if (NullCheckValue) {
130 AdjustNull = CGF.createBasicBlock("adjust.null");
131 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
132 AdjustEnd = CGF.createBasicBlock("adjust.end");
133
134 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
135 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
136 CGF.EmitBlock(AdjustNotNull);
137 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000138
139 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
140 Thunk.Return);
141
Eli Friedman49a94b12011-05-06 17:27:27 +0000142 if (NullCheckValue) {
143 CGF.Builder.CreateBr(AdjustEnd);
144 CGF.EmitBlock(AdjustNull);
145 CGF.Builder.CreateBr(AdjustEnd);
146 CGF.EmitBlock(AdjustEnd);
147
148 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
149 PHI->addIncoming(ReturnValue, AdjustNotNull);
150 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
151 AdjustNull);
152 ReturnValue = PHI;
153 }
154
155 return RValue::get(ReturnValue);
156}
157
158// This function does roughly the same thing as GenerateThunk, but in a
159// very different way, so that va_start and va_end work correctly.
160// FIXME: This function assumes "this" is the first non-sret LLVM argument of
161// a function, and that there is an alloca built in the entry block
162// for all accesses to "this".
163// FIXME: This function assumes there is only one "ret" statement per function.
164// FIXME: Cloning isn't correct in the presence of indirect goto!
165// FIXME: This implementation of thunks bloats codesize by duplicating the
166// function definition. There are alternatives:
167// 1. Add some sort of stub support to LLVM for cases where we can
168// do a this adjustment, then a sibcall.
169// 2. We could transform the definition to take a va_list instead of an
170// actual variable argument list, then have the thunks (including a
171// no-op thunk for the regular definition) call va_start/va_end.
172// There's a bit of per-call overhead for this solution, but it's
173// better for codesize if the definition is long.
174void CodeGenFunction::GenerateVarArgsThunk(
175 llvm::Function *Fn,
176 const CGFunctionInfo &FnInfo,
177 GlobalDecl GD, const ThunkInfo &Thunk) {
178 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
179 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
180 QualType ResultType = FPT->getResultType();
181
182 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000183 assert(FnInfo.isVariadic());
184 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000185 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
186 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
187
188 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000189 llvm::ValueToValueMapTy VMap;
190 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
191 /*ModuleLevelChanges=*/false);
Eli Friedman49a94b12011-05-06 17:27:27 +0000192 CGM.getModule().getFunctionList().push_back(NewFn);
193 Fn->replaceAllUsesWith(NewFn);
194 NewFn->takeName(Fn);
195 Fn->eraseFromParent();
196 Fn = NewFn;
197
198 // "Initialize" CGF (minimally).
199 CurFn = Fn;
200
201 // Get the "this" value
202 llvm::Function::arg_iterator AI = Fn->arg_begin();
203 if (CGM.ReturnTypeUsesSRet(FnInfo))
204 ++AI;
205
206 // Find the first store of "this", which will be to the alloca associated
207 // with "this".
208 llvm::Value *ThisPtr = &*AI;
209 llvm::BasicBlock *EntryBB = Fn->begin();
210 llvm::Instruction *ThisStore = 0;
211 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
212 I != E; I++) {
213 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
214 ThisStore = cast<llvm::StoreInst>(I);
215 break;
216 }
217 }
218 assert(ThisStore && "Store of this should be in entry block?");
219 // Adjust "this", if necessary.
220 Builder.SetInsertPoint(ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000221 llvm::Value *AdjustedThisPtr =
222 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000223 ThisStore->setOperand(0, AdjustedThisPtr);
224
225 if (!Thunk.Return.isEmpty()) {
226 // Fix up the returned value, if necessary.
227 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
228 llvm::Instruction *T = I->getTerminator();
229 if (isa<llvm::ReturnInst>(T)) {
230 RValue RV = RValue::get(T->getOperand(0));
231 T->eraseFromParent();
232 Builder.SetInsertPoint(&*I);
233 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
234 Builder.CreateRet(RV.getScalarVal());
235 break;
236 }
237 }
238 }
239}
240
Hans Wennborg88497d62013-11-15 17:24:45 +0000241void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
242 const CGFunctionInfo &FnInfo) {
243 assert(!CurGD.getDecl() && "CurGD was already set!");
244 CurGD = GD;
245
246 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000247 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000248 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000249 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000250 QualType ResultType =
251 CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getResultType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000252 FunctionArgList FunctionArgs;
253
Anders Carlssonbad991d2010-03-24 00:39:18 +0000254 // Create the implicit 'this' parameter declaration.
John McCall5d865c322010-08-31 07:33:07 +0000255 CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000256
257 // Add the rest of the parameters.
258 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000259 E = MD->param_end();
260 I != E; ++I)
261 FunctionArgs.push_back(*I);
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000262
Hans Wennborg88497d62013-11-15 17:24:45 +0000263 // Start defining the function.
John McCalla738c252011-03-09 04:27:21 +0000264 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
265 SourceLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000266
Hans Wennborg88497d62013-11-15 17:24:45 +0000267 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000268 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000269 CXXThisValue = CXXABIThisValue;
Hans Wennborg88497d62013-11-15 17:24:45 +0000270}
John McCall5d865c322010-08-31 07:33:07 +0000271
Hans Wennborg88497d62013-11-15 17:24:45 +0000272void CodeGenFunction::EmitCallAndReturnForThunk(GlobalDecl GD,
273 llvm::Value *Callee,
274 const ThunkInfo *Thunk) {
275 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
276 "Please use a new CGF for this thunk");
277 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000278
Hans Wennborg88497d62013-11-15 17:24:45 +0000279 // Adjust the 'this' pointer if necessary
280 llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
281 *this, LoadCXXThis(), Thunk->This)
282 : LoadCXXThis();
283
284 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000285 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000286 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000287 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000288
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000289 if (isa<CXXDestructorDecl>(MD))
290 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, GD, CallArgs);
291
Hans Wennborg88497d62013-11-15 17:24:45 +0000292 // Add the rest of the arguments.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000293 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000294 E = MD->param_end(); I != E; ++I)
295 EmitDelegateCallArg(CallArgs, *I, (*I)->getLocStart());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000296
Hans Wennborg88497d62013-11-15 17:24:45 +0000297 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000298
John McCalla738c252011-03-09 04:27:21 +0000299#ifndef NDEBUG
John McCall8dda7b22012-07-07 06:41:13 +0000300 const CGFunctionInfo &CallFnInfo =
301 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCalla729c622012-02-17 03:33:10 +0000302 RequiredArgs::forPrototypePlus(FPT, 1));
Hans Wennborg88497d62013-11-15 17:24:45 +0000303 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
304 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
305 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000306 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
307 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000308 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
309 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
310 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000311 assert(similar(CallFnInfo.arg_begin()[i].info,
312 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000313 CurFnInfo->arg_begin()[i].info,
314 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000315#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000316
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000317 // Determine whether we have a return value slot to use.
Hans Wennborg88497d62013-11-15 17:24:45 +0000318 QualType ResultType =
319 CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getResultType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000320 ReturnValueSlot Slot;
321 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000322 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000323 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000324 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
325
Anders Carlssonbad991d2010-03-24 00:39:18 +0000326 // Now emit our call.
Hans Wennborg88497d62013-11-15 17:24:45 +0000327 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000328
Hans Wennborg88497d62013-11-15 17:24:45 +0000329 // Consider return adjustment if we have ThunkInfo.
330 if (Thunk && !Thunk->Return.isEmpty())
331 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000332
Hans Wennborg88497d62013-11-15 17:24:45 +0000333 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000334 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000335 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000336
John McCallff755cd2012-07-31 00:33:55 +0000337 // Disable the final ARC autorelease.
338 AutoreleaseResult = false;
339
Anders Carlssonbad991d2010-03-24 00:39:18 +0000340 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000341}
342
343void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
344 const CGFunctionInfo &FnInfo,
345 GlobalDecl GD, const ThunkInfo &Thunk) {
346 StartThunk(Fn, GD, FnInfo);
347
348 // Get our callee.
349 llvm::Type *Ty =
350 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
351 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
352
353 // Make the call and return the result.
354 EmitCallAndReturnForThunk(GD, Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000355
Anders Carlssonbad991d2010-03-24 00:39:18 +0000356 // Set the right linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000357 CGM.setFunctionLinkage(GD, Fn);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000358
359 // Set the right visibility.
Hans Wennborg88497d62013-11-15 17:24:45 +0000360 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCallc8bd9c22010-08-04 23:46:35 +0000361 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000362}
363
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000364void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
365 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000366 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000367
368 // FIXME: re-use FnInfo in this computation.
Anders Carlssonfe8a9932011-02-06 17:15:43 +0000369 llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlssoncd836f02010-03-23 17:17:29 +0000370
Anders Carlsson55e89f82010-03-23 18:18:41 +0000371 // Strip off a bitcast if we got one back.
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000372 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000373 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000374 Entry = CE->getOperand(0);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000375 }
376
Anders Carlsson55e89f82010-03-23 18:18:41 +0000377 // There's already a declaration with the same name, check if it has the same
378 // type or if we need to replace it.
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000379 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000380 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000381 llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000382
383 // If the types mismatch then we have to rewrite the definition.
384 assert(OldThunkFn->isDeclaration() &&
385 "Shouldn't replace non-declaration");
386
387 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000388 OldThunkFn->setName(StringRef());
Anders Carlssonfe8a9932011-02-06 17:15:43 +0000389 Entry = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000390
391 // If needed, replace the old thunk with a bitcast.
392 if (!OldThunkFn->use_empty()) {
393 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000394 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000395 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
396 }
397
398 // Remove the old thunk.
399 OldThunkFn->eraseFromParent();
400 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000401
Anders Carlssonbad991d2010-03-24 00:39:18 +0000402 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000403 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
404 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000405
406 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000407 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000408 // There is already a thunk emitted for this function, do nothing.
409 return;
410 }
411
Anders Carlssone866d442011-02-06 20:09:44 +0000412 // Change the linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000413 CGM.setFunctionLinkage(GD, ThunkFn);
Anders Carlssone866d442011-02-06 20:09:44 +0000414 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000415 }
416
Rafael Espindola86792432012-09-21 20:39:32 +0000417 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
418
Eli Friedman49a94b12011-05-06 17:27:27 +0000419 if (ThunkFn->isVarArg()) {
420 // Varargs thunks are special; we can't just generate a call because
421 // we can't copy the varargs. Our implementation is rather
422 // expensive/sucky at the moment, so don't generate the thunk unless
423 // we have to.
424 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
425 if (!UseAvailableExternallyLinkage)
426 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
427 } else {
428 // Normal thunk body generation.
429 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
430 }
Anders Carlsson8b021832011-02-06 18:31:40 +0000431
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000432 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable);
Anders Carlsson8b021832011-02-06 18:31:40 +0000433}
434
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000435void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
436 const ThunkInfo &Thunk) {
437 // If the ABI has key functions, only the TU with the key function should emit
438 // the thunk. However, we can allow inlining of thunks if we emit them with
439 // available_externally linkage together with vtables when optimizations are
440 // enabled.
441 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
442 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000443 return;
444
445 // We can't emit thunks for member functions with incomplete types.
446 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000447 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000448 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000449 return;
450
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000451 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000452}
453
Anders Carlsson917229c2010-03-23 04:59:02 +0000454void CodeGenVTables::EmitThunks(GlobalDecl GD)
455{
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000456 const CXXMethodDecl *MD =
457 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
458
459 // We don't need to generate thunks for the base destructor.
460 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
461 return;
462
Timur Iskhodzhanove1ebc5f2013-10-09 11:33:51 +0000463 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector;
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000464 if (MicrosoftVTContext.isValid()) {
465 ThunkInfoVector = MicrosoftVTContext->getThunkInfo(GD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000466 } else {
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000467 ThunkInfoVector = ItaniumVTContext.getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000468 }
469
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000470 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000471 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000472
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000473 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000474 emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000475}
476
Anders Carlssona4147142010-03-25 15:26:28 +0000477llvm::Constant *
478CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000479 const VTableComponent *Components,
Anders Carlssona4147142010-03-25 15:26:28 +0000480 unsigned NumComponents,
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000481 const VTableLayout::VTableThunkTy *VTableThunks,
482 unsigned NumVTableThunks) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000483 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlssona4147142010-03-25 15:26:28 +0000484
Chris Lattnerece04092012-02-07 00:39:47 +0000485 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlssona4147142010-03-25 15:26:28 +0000486
Chris Lattner2192fe52011-07-18 04:24:23 +0000487 llvm::Type *PtrDiffTy =
Anders Carlssona5736bd2010-03-25 16:49:53 +0000488 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
489
490 QualType ClassType = CGM.getContext().getTagDeclType(RD);
491 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
492
493 unsigned NextVTableThunkIndex = 0;
494
David Blaikieeb7d5982012-10-16 22:56:05 +0000495 llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0;
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000496
Anders Carlssona4147142010-03-25 15:26:28 +0000497 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000498 VTableComponent Component = Components[I];
Anders Carlssona5736bd2010-03-25 16:49:53 +0000499
500 llvm::Constant *Init = 0;
501
502 switch (Component.getKind()) {
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000503 case VTableComponent::CK_VCallOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000504 Init = llvm::ConstantInt::get(PtrDiffTy,
505 Component.getVCallOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000506 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
507 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000508 case VTableComponent::CK_VBaseOffset:
Ken Dyck872d74a2011-04-02 01:14:48 +0000509 Init = llvm::ConstantInt::get(PtrDiffTy,
510 Component.getVBaseOffset().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000511 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
512 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000513 case VTableComponent::CK_OffsetToTop:
Ken Dyck872d74a2011-04-02 01:14:48 +0000514 Init = llvm::ConstantInt::get(PtrDiffTy,
515 Component.getOffsetToTop().getQuantity());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000516 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
517 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000518 case VTableComponent::CK_RTTI:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000519 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
520 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000521 case VTableComponent::CK_FunctionPointer:
522 case VTableComponent::CK_CompleteDtorPointer:
523 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlssona5736bd2010-03-25 16:49:53 +0000524 GlobalDecl GD;
525
526 // Get the right global decl.
527 switch (Component.getKind()) {
528 default:
529 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000530 case VTableComponent::CK_FunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000531 GD = Component.getFunctionDecl();
532 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000533 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000534 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
535 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000536 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000537 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
538 break;
539 }
540
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000541 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
542 // We have a pure virtual member function.
Joao Matos718a8832012-07-17 19:17:58 +0000543 if (!PureVirtualFn) {
Eli Friedman48a32912012-09-14 01:19:01 +0000544 llvm::FunctionType *Ty =
545 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
546 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
547 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
548 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matos718a8832012-07-17 19:17:58 +0000549 CGM.Int8PtrTy);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000550 }
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000551 Init = PureVirtualFn;
David Blaikieeb7d5982012-10-16 22:56:05 +0000552 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
553 if (!DeletedVirtualFn) {
554 llvm::FunctionType *Ty =
555 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
556 StringRef DeletedCallName =
557 CGM.getCXXABI().GetDeletedVirtualCallName();
558 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
559 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
560 CGM.Int8PtrTy);
561 }
562 Init = DeletedVirtualFn;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000563 } else {
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000564 // Check if we should use a thunk.
Peter Collingbourneaffe1112011-09-26 01:56:50 +0000565 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000566 VTableThunks[NextVTableThunkIndex].first == I) {
567 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlssona5736bd2010-03-25 16:49:53 +0000568
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000569 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramere6b4a162012-03-20 20:18:13 +0000570 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson8b021832011-02-06 18:31:40 +0000571
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000572 NextVTableThunkIndex++;
573 } else {
Chris Lattner2192fe52011-07-18 04:24:23 +0000574 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000575
Anders Carlsson3c239482011-02-05 04:35:53 +0000576 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000577 }
578
579 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000580 }
Anders Carlssona5736bd2010-03-25 16:49:53 +0000581 break;
582 }
583
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000584 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlssona5736bd2010-03-25 16:49:53 +0000585 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
586 break;
587 };
Anders Carlssona4147142010-03-25 15:26:28 +0000588
589 Inits.push_back(Init);
590 }
591
592 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad83be3612011-06-22 09:24:39 +0000593 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlssona4147142010-03-25 15:26:28 +0000594}
595
Anders Carlsson0534b022010-03-25 00:35:49 +0000596llvm::GlobalVariable *
597CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlssona208b392010-03-26 03:56:54 +0000598 const BaseSubobject &Base,
599 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000600 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000601 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000602 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
603 DI->completeClassData(Base.getBase());
604
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000605 OwningPtr<VTableLayout> VTLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000606 ItaniumVTContext.createConstructionVTableLayout(
607 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000608
Anders Carlssona5736bd2010-03-25 16:49:53 +0000609 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000610 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000611
612 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000613 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000614 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000615 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
616 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
617 Base.getBase(), Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +0000618 Out.flush();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000619 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000620
Anders Carlssona4147142010-03-25 15:26:28 +0000621 llvm::ArrayType *ArrayType =
Chris Lattnerece04092012-02-07 00:39:47 +0000622 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlssona4147142010-03-25 15:26:28 +0000623
Richard Smith65fd2a42013-02-16 00:51:21 +0000624 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
625 // guarantee that they actually will be available externally. Instead, when
626 // emitting an available_externally VTT, we provide references to an internal
627 // linkage construction vtable. The ABI only requires complete-object vtables
628 // to be the same for all instances of a type, not construction vtables.
629 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
630 Linkage = llvm::GlobalVariable::InternalLinkage;
631
Anders Carlssona4147142010-03-25 15:26:28 +0000632 // Create the variable that will hold the construction vtable.
633 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000634 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
635 CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
636
637 // V-tables are always unnamed_addr.
638 VTable->setUnnamedAddr(true);
Anders Carlssona4147142010-03-25 15:26:28 +0000639
Anders Carlssona4147142010-03-25 15:26:28 +0000640 // Create and set the initializer.
641 llvm::Constant *Init =
642 CreateVTableInitializer(Base.getBase(),
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000643 VTLayout->vtable_component_begin(),
644 VTLayout->getNumVTableComponents(),
645 VTLayout->vtable_thunk_begin(),
646 VTLayout->getNumVTableThunks());
Anders Carlssona4147142010-03-25 15:26:28 +0000647 VTable->setInitializer(Init);
648
Anders Carlsson0534b022010-03-25 00:35:49 +0000649 return VTable;
650}
651
John McCall6bd2a892013-01-25 22:31:03 +0000652/// Compute the required linkage of the v-table for the given class.
653///
654/// Note that we only call this at the end of the translation unit.
655llvm::GlobalVariable::LinkageTypes
656CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000657 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000658 return llvm::GlobalVariable::InternalLinkage;
659
660 // We're at the end of the translation unit, so the current key
661 // function is fully correct.
662 if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
663 // If this class has a key function, use that to determine the
664 // linkage of the vtable.
665 const FunctionDecl *def = 0;
666 if (keyFunction->hasBody(def))
667 keyFunction = cast<CXXMethodDecl>(def);
668
669 switch (keyFunction->getTemplateSpecializationKind()) {
670 case TSK_Undeclared:
671 case TSK_ExplicitSpecialization:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000672 assert(def && "Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000673 if (keyFunction->isInlined())
674 return !Context.getLangOpts().AppleKext ?
675 llvm::GlobalVariable::LinkOnceODRLinkage :
676 llvm::Function::InternalLinkage;
677
678 return llvm::GlobalVariable::ExternalLinkage;
679
680 case TSK_ImplicitInstantiation:
681 return !Context.getLangOpts().AppleKext ?
682 llvm::GlobalVariable::LinkOnceODRLinkage :
683 llvm::Function::InternalLinkage;
684
685 case TSK_ExplicitInstantiationDefinition:
686 return !Context.getLangOpts().AppleKext ?
687 llvm::GlobalVariable::WeakODRLinkage :
688 llvm::Function::InternalLinkage;
689
690 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000691 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000692 }
693 }
694
695 // -fapple-kext mode does not support weak linkage, so we must use
696 // internal linkage.
697 if (Context.getLangOpts().AppleKext)
698 return llvm::Function::InternalLinkage;
699
700 switch (RD->getTemplateSpecializationKind()) {
701 case TSK_Undeclared:
702 case TSK_ExplicitSpecialization:
703 case TSK_ImplicitInstantiation:
704 return llvm::GlobalVariable::LinkOnceODRLinkage;
705
706 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000707 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000708
709 case TSK_ExplicitInstantiationDefinition:
710 return llvm::GlobalVariable::WeakODRLinkage;
711 }
712
713 llvm_unreachable("Invalid TemplateSpecializationKind!");
714}
715
716/// This is a callback from Sema to tell us that it believes that a
717/// particular v-table is required to be emitted in this translation
718/// unit.
719///
720/// The reason we don't simply trust this callback is because Sema
721/// will happily report that something is used even when it's used
722/// only in code that we don't actually have to emit.
723///
724/// \param isRequired - if true, the v-table is mandatory, e.g.
725/// because the translation unit defines the key function
726void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
727 if (!isRequired) return;
728
729 VTables.GenerateClassData(theClass);
730}
731
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000732void
John McCall6bd2a892013-01-25 22:31:03 +0000733CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000734 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
735 DI->completeClassData(RD);
736
Reid Kleckner7810af02013-06-19 15:20:38 +0000737 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000738 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000739
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000740 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000741}
John McCall6bd2a892013-01-25 22:31:03 +0000742
743/// At this point in the translation unit, does it appear that can we
744/// rely on the vtable being defined elsewhere in the program?
745///
746/// The response is really only definitive when called at the end of
747/// the translation unit.
748///
749/// The only semantic restriction here is that the object file should
750/// not contain a v-table definition when that v-table is defined
751/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
752/// v-tables when unnecessary.
753bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
754 assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
755
756 // If we have an explicit instantiation declaration (and not a
757 // definition), the v-table is defined elsewhere.
758 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
759 if (TSK == TSK_ExplicitInstantiationDeclaration)
760 return true;
761
762 // Otherwise, if the class is an instantiated template, the
763 // v-table must be defined here.
764 if (TSK == TSK_ImplicitInstantiation ||
765 TSK == TSK_ExplicitInstantiationDefinition)
766 return false;
767
768 // Otherwise, if the class doesn't have a key function (possibly
769 // anymore), the v-table must be defined here.
770 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
771 if (!keyFunction)
772 return false;
773
774 // Otherwise, if we don't have a definition of the key function, the
775 // v-table must be defined somewhere else.
776 return !keyFunction->hasBody();
777}
778
779/// Given that we're currently at the end of the translation unit, and
780/// we've emitted a reference to the v-table for this class, should
781/// we define that v-table?
782static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
783 const CXXRecordDecl *RD) {
John McCall6bd2a892013-01-25 22:31:03 +0000784 return !CGM.getVTables().isVTableExternal(RD);
785}
786
787/// Given that at some point we emitted a reference to one or more
788/// v-tables, and that we are now at the end of the translation unit,
789/// decide whether we should emit them.
790void CodeGenModule::EmitDeferredVTables() {
791#ifndef NDEBUG
792 // Remember the size of DeferredVTables, because we're going to assume
793 // that this entire operation doesn't modify it.
794 size_t savedSize = DeferredVTables.size();
795#endif
796
797 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
798 for (const_iterator i = DeferredVTables.begin(),
799 e = DeferredVTables.end(); i != e; ++i) {
800 const CXXRecordDecl *RD = *i;
801 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
802 VTables.GenerateClassData(RD);
803 }
804
805 assert(savedSize == DeferredVTables.size() &&
806 "deferred extra v-tables during v-table emission?");
807 DeferredVTables.clear();
808}