blob: 48a93ba65d207e245d0aa03fa12d966c9917e725 [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"
Mark Lacey8b549992013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
John McCall7a536902010-08-05 20:39:18 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5dd730a2009-11-26 19:32:45 +000021#include "llvm/ADT/DenseSet.h"
Anders Carlssonb9021e92010-02-27 16:18:19 +000022#include "llvm/ADT/SetVector.h"
Chandler Carruthe087f072010-02-13 10:38:52 +000023#include "llvm/Support/Compiler.h"
Anders Carlsson824d7ea2010-02-11 08:02:13 +000024#include "llvm/Support/Format.h"
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000025#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson5e454aa2010-03-17 20:06:32 +000026#include <algorithm>
Zhongxing Xu7fe26ac2009-11-13 05:46:16 +000027#include <cstdio>
Anders Carlssondbd920c2009-10-11 22:13:54 +000028
29using namespace clang;
30using namespace CodeGen;
31
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000032CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
Stephen Hines651f13c2014-04-23 16:59:28 -070033 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbourne1d2b3172011-09-26 01:56:30 +000034
Anders Carlsson19879c92010-03-23 17:17:29 +000035llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlsson84c49e42011-02-06 17:15:43 +000036 const ThunkInfo &Thunk) {
Anders Carlsson19879c92010-03-23 17:17:29 +000037 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38
39 // Compute the mangled name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000040 SmallString<256> Name;
Rafael Espindolaf0be9792011-02-11 02:52:17 +000041 llvm::raw_svector_ostream Out(Name);
Anders Carlsson19879c92010-03-23 17:17:29 +000042 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall4c40d982010-08-31 07:33:07 +000043 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindolaf0be9792011-02-11 02:52:17 +000044 Thunk.This, Out);
Anders Carlsson19879c92010-03-23 17:17:29 +000045 else
Rafael Espindolaf0be9792011-02-11 02:52:17 +000046 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
47 Out.flush();
48
Chris Lattner2acc6e32011-07-18 04:24:23 +000049 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -070050 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
Stephen Hines176edba2014-12-01 14:53:08 -080051 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlsson19879c92010-03-23 17:17:29 +000052}
53
John McCall65005532010-08-04 23:46:35 +000054static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
55 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +000056 CGM.setGlobalVisibility(Fn, MD);
John McCall65005532010-08-04 23:46:35 +000057}
58
John McCall311b4422011-03-09 07:12:35 +000059#ifndef NDEBUG
60static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61 const ABIArgInfo &infoR, CanQualType typeR) {
62 return (infoL.getKind() == infoR.getKind() &&
63 (typeL == typeR ||
64 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66}
67#endif
68
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000069static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70 QualType ResultType, RValue RV,
71 const ThunkInfo &Thunk) {
72 // Emit the return adjustment.
73 bool NullCheckValue = !ResultType->isReferenceType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070074
75 llvm::BasicBlock *AdjustNull = nullptr;
76 llvm::BasicBlock *AdjustNotNull = nullptr;
77 llvm::BasicBlock *AdjustEnd = nullptr;
78
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000079 llvm::Value *ReturnValue = RV.getScalarVal();
80
81 if (NullCheckValue) {
82 AdjustNull = CGF.createBasicBlock("adjust.null");
83 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84 AdjustEnd = CGF.createBasicBlock("adjust.end");
85
86 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88 CGF.EmitBlock(AdjustNotNull);
89 }
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +000090
91 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
92 Thunk.Return);
93
Eli Friedman7dcdf5b2011-05-06 17:27:27 +000094 if (NullCheckValue) {
95 CGF.Builder.CreateBr(AdjustEnd);
96 CGF.EmitBlock(AdjustNull);
97 CGF.Builder.CreateBr(AdjustEnd);
98 CGF.EmitBlock(AdjustEnd);
99
100 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
101 PHI->addIncoming(ReturnValue, AdjustNotNull);
102 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
103 AdjustNull);
104 ReturnValue = PHI;
105 }
106
107 return RValue::get(ReturnValue);
108}
109
110// This function does roughly the same thing as GenerateThunk, but in a
111// very different way, so that va_start and va_end work correctly.
112// FIXME: This function assumes "this" is the first non-sret LLVM argument of
113// a function, and that there is an alloca built in the entry block
114// for all accesses to "this".
115// FIXME: This function assumes there is only one "ret" statement per function.
116// FIXME: Cloning isn't correct in the presence of indirect goto!
117// FIXME: This implementation of thunks bloats codesize by duplicating the
118// function definition. There are alternatives:
119// 1. Add some sort of stub support to LLVM for cases where we can
120// do a this adjustment, then a sibcall.
121// 2. We could transform the definition to take a va_list instead of an
122// actual variable argument list, then have the thunks (including a
123// no-op thunk for the regular definition) call va_start/va_end.
124// There's a bit of per-call overhead for this solution, but it's
125// better for codesize if the definition is long.
126void CodeGenFunction::GenerateVarArgsThunk(
127 llvm::Function *Fn,
128 const CGFunctionInfo &FnInfo,
129 GlobalDecl GD, const ThunkInfo &Thunk) {
130 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
131 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700132 QualType ResultType = FPT->getReturnType();
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000133
134 // Get the original function
John McCallde5d3c72012-02-17 03:33:10 +0000135 assert(FnInfo.isVariadic());
136 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000137 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
138 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
139
140 // Clone to thunk.
Benjamin Kramer9b5ede52012-09-19 13:13:52 +0000141 llvm::ValueToValueMapTy VMap;
142 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
143 /*ModuleLevelChanges=*/false);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000144 CGM.getModule().getFunctionList().push_back(NewFn);
145 Fn->replaceAllUsesWith(NewFn);
146 NewFn->takeName(Fn);
147 Fn->eraseFromParent();
148 Fn = NewFn;
149
150 // "Initialize" CGF (minimally).
151 CurFn = Fn;
152
153 // Get the "this" value
154 llvm::Function::arg_iterator AI = Fn->arg_begin();
155 if (CGM.ReturnTypeUsesSRet(FnInfo))
156 ++AI;
157
158 // Find the first store of "this", which will be to the alloca associated
159 // with "this".
160 llvm::Value *ThisPtr = &*AI;
161 llvm::BasicBlock *EntryBB = Fn->begin();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700162 llvm::Instruction *ThisStore = nullptr;
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000163 for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
164 I != E; I++) {
165 if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
166 ThisStore = cast<llvm::StoreInst>(I);
167 break;
168 }
169 }
170 assert(ThisStore && "Store of this should be in entry block?");
171 // Adjust "this", if necessary.
172 Builder.SetInsertPoint(ThisStore);
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000173 llvm::Value *AdjustedThisPtr =
174 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000175 ThisStore->setOperand(0, AdjustedThisPtr);
176
177 if (!Thunk.Return.isEmpty()) {
178 // Fix up the returned value, if necessary.
179 for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
180 llvm::Instruction *T = I->getTerminator();
181 if (isa<llvm::ReturnInst>(T)) {
182 RValue RV = RValue::get(T->getOperand(0));
183 T->eraseFromParent();
184 Builder.SetInsertPoint(&*I);
185 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
186 Builder.CreateRet(RV.getScalarVal());
187 break;
188 }
189 }
190 }
191}
192
Hans Wennborg93b717a2013-11-15 17:24:45 +0000193void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
194 const CGFunctionInfo &FnInfo) {
195 assert(!CurGD.getDecl() && "CurGD was already set!");
196 CurGD = GD;
Stephen Hines176edba2014-12-01 14:53:08 -0800197 CurFuncIsThunk = true;
Hans Wennborg93b717a2013-11-15 17:24:45 +0000198
199 // Build FunctionArgs.
Anders Carlsson519c3282010-03-24 00:39:18 +0000200 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlsson519c3282010-03-24 00:39:18 +0000201 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg93b717a2013-11-15 17:24:45 +0000202 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Stephen Hines176edba2014-12-01 14:53:08 -0800203 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
204 ? ThisType
205 : CGM.getCXXABI().hasMostDerivedReturn(GD)
206 ? CGM.getContext().VoidPtrTy
207 : FPT->getReturnType();
Anders Carlsson519c3282010-03-24 00:39:18 +0000208 FunctionArgList FunctionArgs;
209
Anders Carlsson519c3282010-03-24 00:39:18 +0000210 // Create the implicit 'this' parameter declaration.
Stephen Hines651f13c2014-04-23 16:59:28 -0700211 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlsson519c3282010-03-24 00:39:18 +0000212
213 // Add the rest of the parameters.
Stephen Hines176edba2014-12-01 14:53:08 -0800214 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov34b41f82012-10-25 10:18:50 +0000215
Stephen Hines651f13c2014-04-23 16:59:28 -0700216 if (isa<CXXDestructorDecl>(MD))
217 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
218
Hans Wennborg93b717a2013-11-15 17:24:45 +0000219 // Start defining the function.
John McCalld26bc762011-03-09 04:27:21 +0000220 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700221 MD->getLocation(), SourceLocation());
Anders Carlsson519c3282010-03-24 00:39:18 +0000222
Hans Wennborg93b717a2013-11-15 17:24:45 +0000223 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall4c40d982010-08-31 07:33:07 +0000224 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedmancec5ebd2012-02-11 02:57:39 +0000225 CXXThisValue = CXXABIThisValue;
Hans Wennborg93b717a2013-11-15 17:24:45 +0000226}
John McCall4c40d982010-08-31 07:33:07 +0000227
Stephen Hines176edba2014-12-01 14:53:08 -0800228void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
Hans Wennborg93b717a2013-11-15 17:24:45 +0000229 const ThunkInfo *Thunk) {
230 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
231 "Please use a new CGF for this thunk");
Stephen Hines176edba2014-12-01 14:53:08 -0800232 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanovc70cc5d2013-10-30 11:55:43 +0000233
Hans Wennborg93b717a2013-11-15 17:24:45 +0000234 // Adjust the 'this' pointer if necessary
235 llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
236 *this, LoadCXXThis(), Thunk->This)
237 : LoadCXXThis();
238
Stephen Hines176edba2014-12-01 14:53:08 -0800239 if (CurFnInfo->usesInAlloca()) {
240 // We don't handle return adjusting thunks, because they require us to call
241 // the copy constructor. For now, fall through and pretend the return
242 // adjustment was empty so we don't crash.
243 if (Thunk && !Thunk->Return.isEmpty()) {
244 CGM.ErrorUnsupported(
245 MD, "non-trivial argument copy for return-adjusting thunk");
246 }
247 EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
248 return;
249 }
250
Hans Wennborg93b717a2013-11-15 17:24:45 +0000251 // Start building CallArgs.
Anders Carlsson519c3282010-03-24 00:39:18 +0000252 CallArgList CallArgs;
Hans Wennborg93b717a2013-11-15 17:24:45 +0000253 QualType ThisType = MD->getThisType(getContext());
Eli Friedman04c9a492011-05-02 17:57:46 +0000254 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000255
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000256 if (isa<CXXDestructorDecl>(MD))
Stephen Hines176edba2014-12-01 14:53:08 -0800257 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000258
Hans Wennborg93b717a2013-11-15 17:24:45 +0000259 // Add the rest of the arguments.
Stephen Hines176edba2014-12-01 14:53:08 -0800260 for (const ParmVarDecl *PD : MD->params())
261 EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
Anders Carlsson519c3282010-03-24 00:39:18 +0000262
Hans Wennborg93b717a2013-11-15 17:24:45 +0000263 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlsson519c3282010-03-24 00:39:18 +0000264
John McCalld26bc762011-03-09 04:27:21 +0000265#ifndef NDEBUG
John McCall0f3d0972012-07-07 06:41:13 +0000266 const CGFunctionInfo &CallFnInfo =
267 CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
John McCallde5d3c72012-02-17 03:33:10 +0000268 RequiredArgs::forPrototypePlus(FPT, 1));
Hans Wennborg93b717a2013-11-15 17:24:45 +0000269 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
270 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
271 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall0f3d0972012-07-07 06:41:13 +0000272 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
273 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg93b717a2013-11-15 17:24:45 +0000274 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
275 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
276 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall311b4422011-03-09 07:12:35 +0000277 assert(similar(CallFnInfo.arg_begin()[i].info,
278 CallFnInfo.arg_begin()[i].type,
Hans Wennborg93b717a2013-11-15 17:24:45 +0000279 CurFnInfo->arg_begin()[i].info,
280 CurFnInfo->arg_begin()[i].type));
John McCalld26bc762011-03-09 04:27:21 +0000281#endif
Hans Wennborg93b717a2013-11-15 17:24:45 +0000282
Douglas Gregorcb359df2010-05-20 05:54:35 +0000283 // Determine whether we have a return value slot to use.
Stephen Hines176edba2014-12-01 14:53:08 -0800284 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
285 ? ThisType
286 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
287 ? CGM.getContext().VoidPtrTy
288 : FPT->getReturnType();
Douglas Gregorcb359df2010-05-20 05:54:35 +0000289 ReturnValueSlot Slot;
290 if (!ResultType->isVoidType() &&
Hans Wennborg93b717a2013-11-15 17:24:45 +0000291 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +0000292 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregorcb359df2010-05-20 05:54:35 +0000293 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
294
Anders Carlsson519c3282010-03-24 00:39:18 +0000295 // Now emit our call.
Stephen Hines176edba2014-12-01 14:53:08 -0800296 llvm::Instruction *CallOrInvoke;
297 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
298
Hans Wennborg93b717a2013-11-15 17:24:45 +0000299 // Consider return adjustment if we have ThunkInfo.
300 if (Thunk && !Thunk->Return.isEmpty())
301 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000302
Hans Wennborg93b717a2013-11-15 17:24:45 +0000303 // Emit return.
Douglas Gregorcb359df2010-05-20 05:54:35 +0000304 if (!ResultType->isVoidType() && Slot.isNull())
John McCalld16c2cf2011-02-08 08:22:06 +0000305 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlsson519c3282010-03-24 00:39:18 +0000306
John McCallbd9b65a2012-07-31 00:33:55 +0000307 // Disable the final ARC autorelease.
308 AutoreleaseResult = false;
309
Anders Carlsson519c3282010-03-24 00:39:18 +0000310 FinishFunction();
Hans Wennborg93b717a2013-11-15 17:24:45 +0000311}
312
Stephen Hines176edba2014-12-01 14:53:08 -0800313void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
314 llvm::Value *AdjustedThisPtr,
315 llvm::Value *Callee) {
316 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
317 // to translate AST arguments into LLVM IR arguments. For thunks, we know
318 // that the caller prototype more or less matches the callee prototype with
319 // the exception of 'this'.
320 SmallVector<llvm::Value *, 8> Args;
321 for (llvm::Argument &A : CurFn->args())
322 Args.push_back(&A);
323
324 // Set the adjusted 'this' pointer.
325 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
326 if (ThisAI.isDirect()) {
327 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
328 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
329 llvm::Type *ThisType = Args[ThisArgNo]->getType();
330 if (ThisType != AdjustedThisPtr->getType())
331 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
332 Args[ThisArgNo] = AdjustedThisPtr;
333 } else {
334 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
335 llvm::Value *ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
336 llvm::Type *ThisType =
337 cast<llvm::PointerType>(ThisAddr->getType())->getElementType();
338 if (ThisType != AdjustedThisPtr->getType())
339 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
340 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
341 }
342
343 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
344 // don't actually want to run them.
345 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
346 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
347
348 // Apply the standard set of call attributes.
349 unsigned CallingConv;
350 CodeGen::AttributeListType AttributeList;
351 CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
352 /*AttrOnCallSite=*/true);
353 llvm::AttributeSet Attrs =
354 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
355 Call->setAttributes(Attrs);
356 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
357
358 if (Call->getType()->isVoidTy())
359 Builder.CreateRetVoid();
360 else
361 Builder.CreateRet(Call);
362
363 // Finish the function to maintain CodeGenFunction invariants.
364 // FIXME: Don't emit unreachable code.
365 EmitBlock(createBasicBlock());
366 FinishFunction();
367}
368
Hans Wennborg93b717a2013-11-15 17:24:45 +0000369void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
370 const CGFunctionInfo &FnInfo,
371 GlobalDecl GD, const ThunkInfo &Thunk) {
372 StartThunk(Fn, GD, FnInfo);
373
374 // Get our callee.
375 llvm::Type *Ty =
376 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
377 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
378
379 // Make the call and return the result.
Stephen Hines176edba2014-12-01 14:53:08 -0800380 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlsson519c3282010-03-24 00:39:18 +0000381
Anders Carlsson519c3282010-03-24 00:39:18 +0000382 // Set the right linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000383 CGM.setFunctionLinkage(GD, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000384
385 // Set the right visibility.
Hans Wennborg93b717a2013-11-15 17:24:45 +0000386 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
John McCall65005532010-08-04 23:46:35 +0000387 setThunkVisibility(CGM, MD, Thunk, Fn);
Anders Carlsson519c3282010-03-24 00:39:18 +0000388}
389
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000390void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
391 bool ForVTable) {
John McCallde5d3c72012-02-17 03:33:10 +0000392 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalld26bc762011-03-09 04:27:21 +0000393
394 // FIXME: re-use FnInfo in this computation.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700395 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
396 llvm::GlobalValue *Entry;
397
Anders Carlsson7986ad52010-03-23 18:18:41 +0000398 // Strip off a bitcast if we got one back.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700399 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson7986ad52010-03-23 18:18:41 +0000400 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700401 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
402 } else {
403 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson7986ad52010-03-23 18:18:41 +0000404 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700405
Anders Carlsson7986ad52010-03-23 18:18:41 +0000406 // There's already a declaration with the same name, check if it has the same
407 // type or if we need to replace it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700408 if (Entry->getType()->getElementType() !=
John McCall4c40d982010-08-31 07:33:07 +0000409 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700410 llvm::GlobalValue *OldThunkFn = Entry;
411
Anders Carlsson7986ad52010-03-23 18:18:41 +0000412 // If the types mismatch then we have to rewrite the definition.
413 assert(OldThunkFn->isDeclaration() &&
414 "Shouldn't replace non-declaration");
415
416 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000417 OldThunkFn->setName(StringRef());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700418 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Anders Carlsson7986ad52010-03-23 18:18:41 +0000419
420 // If needed, replace the old thunk with a bitcast.
421 if (!OldThunkFn->use_empty()) {
422 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson13d68982010-03-24 00:35:44 +0000423 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson7986ad52010-03-23 18:18:41 +0000424 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
425 }
426
427 // Remove the old thunk.
428 OldThunkFn->eraseFromParent();
429 }
Anders Carlsson519c3282010-03-24 00:39:18 +0000430
Anders Carlsson519c3282010-03-24 00:39:18 +0000431 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000432 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
433 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000434
435 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000436 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000437 // There is already a thunk emitted for this function, do nothing.
438 return;
439 }
440
Anders Carlsson22df7b12011-02-06 20:09:44 +0000441 // Change the linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000442 CGM.setFunctionLinkage(GD, ThunkFn);
Anders Carlsson22df7b12011-02-06 20:09:44 +0000443 return;
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000444 }
445
Rafael Espindola022301b2012-09-21 20:39:32 +0000446 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
447
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000448 if (ThunkFn->isVarArg()) {
449 // Varargs thunks are special; we can't just generate a call because
450 // we can't copy the varargs. Our implementation is rather
451 // expensive/sucky at the moment, so don't generate the thunk unless
452 // we have to.
453 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Bill Wendling8e3eec52013-12-07 21:19:02 +0000454 if (!UseAvailableExternallyLinkage) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000455 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700456 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
457 !Thunk.Return.isEmpty());
Bill Wendling8e3eec52013-12-07 21:19:02 +0000458 }
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000459 } else {
460 // Normal thunk body generation.
461 CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700462 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
463 !Thunk.Return.isEmpty());
Eli Friedman7dcdf5b2011-05-06 17:27:27 +0000464 }
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000465}
466
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000467void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
468 const ThunkInfo &Thunk) {
469 // If the ABI has key functions, only the TU with the key function should emit
470 // the thunk. However, we can allow inlining of thunks if we emit them with
471 // available_externally linkage together with vtables when optimizations are
472 // enabled.
473 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
474 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000475 return;
476
477 // We can't emit thunks for member functions with incomplete types.
478 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattnerf742eb02011-07-10 00:18:59 +0000479 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Kleckner7bb72302013-10-11 20:46:27 +0000480 MD->getType()->castAs<FunctionType>()))
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000481 return;
482
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000483 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000484}
485
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000486void CodeGenVTables::EmitThunks(GlobalDecl GD)
487{
Anders Carlssonfbf6ed42010-03-23 16:36:50 +0000488 const CXXMethodDecl *MD =
489 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
490
491 // We don't need to generate thunks for the base destructor.
492 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
493 return;
494
Stephen Hines651f13c2014-04-23 16:59:28 -0700495 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
496 VTContext->getThunkInfo(GD);
Timur Iskhodzhanov635de282013-07-30 09:46:19 +0000497
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000498 if (!ThunkInfoVector)
Anders Carlssonccd83d72010-03-24 16:42:11 +0000499 return;
Anders Carlssonccd83d72010-03-24 16:42:11 +0000500
Peter Collingbourne84fcc482011-09-26 01:56:41 +0000501 for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000502 emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
Anders Carlssonee5ab9f2010-03-23 04:59:02 +0000503}
504
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700505llvm::Constant *CodeGenVTables::CreateVTableInitializer(
506 const CXXRecordDecl *RD, const VTableComponent *Components,
507 unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
508 unsigned NumVTableThunks, llvm::Constant *RTTI) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000509 SmallVector<llvm::Constant *, 64> Inits;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000510
Chris Lattner8b418682012-02-07 00:39:47 +0000511 llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000512
Chris Lattner2acc6e32011-07-18 04:24:23 +0000513 llvm::Type *PtrDiffTy =
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000514 CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
515
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000516 unsigned NextVTableThunkIndex = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700517
518 llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
Anders Carlsson67d568a2010-03-29 05:40:50 +0000519
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000520 for (unsigned I = 0; I != NumComponents; ++I) {
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000521 VTableComponent Component = Components[I];
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000522
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700523 llvm::Constant *Init = nullptr;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000524
525 switch (Component.getKind()) {
Anders Carlsson94464812010-04-10 19:13:06 +0000526 case VTableComponent::CK_VCallOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000527 Init = llvm::ConstantInt::get(PtrDiffTy,
528 Component.getVCallOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000529 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
530 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000531 case VTableComponent::CK_VBaseOffset:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000532 Init = llvm::ConstantInt::get(PtrDiffTy,
533 Component.getVBaseOffset().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000534 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
535 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000536 case VTableComponent::CK_OffsetToTop:
Ken Dyckc40a3fd2011-04-02 01:14:48 +0000537 Init = llvm::ConstantInt::get(PtrDiffTy,
538 Component.getOffsetToTop().getQuantity());
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000539 Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
540 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000541 case VTableComponent::CK_RTTI:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000542 Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
543 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000544 case VTableComponent::CK_FunctionPointer:
545 case VTableComponent::CK_CompleteDtorPointer:
546 case VTableComponent::CK_DeletingDtorPointer: {
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000547 GlobalDecl GD;
548
549 // Get the right global decl.
550 switch (Component.getKind()) {
551 default:
552 llvm_unreachable("Unexpected vtable component kind");
Anders Carlsson94464812010-04-10 19:13:06 +0000553 case VTableComponent::CK_FunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000554 GD = Component.getFunctionDecl();
555 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000556 case VTableComponent::CK_CompleteDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000557 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
558 break;
Anders Carlsson94464812010-04-10 19:13:06 +0000559 case VTableComponent::CK_DeletingDtorPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000560 GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
561 break;
562 }
563
Anders Carlsson67d568a2010-03-29 05:40:50 +0000564 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
565 // We have a pure virtual member function.
Joao Matose9af3e62012-07-17 19:17:58 +0000566 if (!PureVirtualFn) {
Eli Friedmancf15f172012-09-14 01:19:01 +0000567 llvm::FunctionType *Ty =
568 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
569 StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
570 PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
571 PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
Joao Matose9af3e62012-07-17 19:17:58 +0000572 CGM.Int8PtrTy);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000573 }
Anders Carlsson67d568a2010-03-29 05:40:50 +0000574 Init = PureVirtualFn;
David Blaikie2eb9a952012-10-16 22:56:05 +0000575 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
576 if (!DeletedVirtualFn) {
577 llvm::FunctionType *Ty =
578 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
579 StringRef DeletedCallName =
580 CGM.getCXXABI().GetDeletedVirtualCallName();
581 DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
582 DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
583 CGM.Int8PtrTy);
584 }
585 Init = DeletedVirtualFn;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000586 } else {
Anders Carlsson67d568a2010-03-29 05:40:50 +0000587 // Check if we should use a thunk.
Peter Collingbournee09cdf42011-09-26 01:56:50 +0000588 if (NextVTableThunkIndex < NumVTableThunks &&
Anders Carlsson67d568a2010-03-29 05:40:50 +0000589 VTableThunks[NextVTableThunkIndex].first == I) {
590 const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000591
Timur Iskhodzhanov2cb17a02013-10-09 09:23:58 +0000592 maybeEmitThunkForVTable(GD, Thunk);
Benjamin Kramerfce80092012-03-20 20:18:13 +0000593 Init = CGM.GetAddrOfThunk(GD, Thunk);
Anders Carlsson14e82fd2011-02-06 18:31:40 +0000594
Anders Carlsson67d568a2010-03-29 05:40:50 +0000595 NextVTableThunkIndex++;
596 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000597 llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000598
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000599 Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Anders Carlsson67d568a2010-03-29 05:40:50 +0000600 }
601
602 Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000603 }
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000604 break;
605 }
606
Anders Carlsson94464812010-04-10 19:13:06 +0000607 case VTableComponent::CK_UnusedFunctionPointer:
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000608 Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
609 break;
610 };
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000611
612 Inits.push_back(Init);
613 }
614
615 llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
Jay Foad97357602011-06-22 09:24:39 +0000616 return llvm::ConstantArray::get(ArrayType, Inits);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000617}
618
Anders Carlssonff143f82010-03-25 00:35:49 +0000619llvm::GlobalVariable *
620CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000621 const BaseSubobject &Base,
622 bool BaseIsVirtual,
John McCallbda0d6b2011-03-27 09:00:25 +0000623 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlsson2c822f12010-03-26 03:56:54 +0000624 VTableAddressPointsMapTy& AddressPoints) {
David Blaikie6a29f672013-08-22 15:23:05 +0000625 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
626 DI->completeClassData(Base.getBase());
627
Stephen Hines651f13c2014-04-23 16:59:28 -0700628 std::unique_ptr<VTableLayout> VTLayout(
629 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov5f0db582013-11-05 15:54:58 +0000630 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000631
Anders Carlsson6a5ab5d2010-03-25 16:49:53 +0000632 // Add the address points.
Peter Collingbourneab172b52011-09-26 01:57:04 +0000633 AddressPoints = VTLayout->getAddressPoints();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000634
635 // Get the mangled construction vtable name.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000636 SmallString<256> OutName;
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000637 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov11f22a32013-10-03 06:26:13 +0000638 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
639 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
640 Base.getBase(), Out);
Rafael Espindolaf0be9792011-02-11 02:52:17 +0000641 Out.flush();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000642 StringRef Name = OutName.str();
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000643
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000644 llvm::ArrayType *ArrayType =
Chris Lattner8b418682012-02-07 00:39:47 +0000645 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000646
Richard Smithb4127a22013-02-16 00:51:21 +0000647 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
648 // guarantee that they actually will be available externally. Instead, when
649 // emitting an available_externally VTT, we provide references to an internal
650 // linkage construction vtable. The ABI only requires complete-object vtables
651 // to be the same for all instances of a type, not construction vtables.
652 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
653 Linkage = llvm::GlobalVariable::InternalLinkage;
654
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000655 // Create the variable that will hold the construction vtable.
656 llvm::GlobalVariable *VTable =
John McCallbda0d6b2011-03-27 09:00:25 +0000657 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
Stephen Hines651f13c2014-04-23 16:59:28 -0700658 CGM.setGlobalVisibility(VTable, RD);
John McCallbda0d6b2011-03-27 09:00:25 +0000659
660 // V-tables are always unnamed_addr.
661 VTable->setUnnamedAddr(true);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000662
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700663 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
664 CGM.getContext().getTagDeclType(Base.getBase()));
665
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000666 // Create and set the initializer.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700667 llvm::Constant *Init = CreateVTableInitializer(
668 Base.getBase(), VTLayout->vtable_component_begin(),
669 VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
670 VTLayout->getNumVTableThunks(), RTTI);
Anders Carlsson0d1407e2010-03-25 15:26:28 +0000671 VTable->setInitializer(Init);
672
Anders Carlssonff143f82010-03-25 00:35:49 +0000673 return VTable;
674}
675
John McCalld5617ee2013-01-25 22:31:03 +0000676/// Compute the required linkage of the v-table for the given class.
677///
678/// Note that we only call this at the end of the translation unit.
679llvm::GlobalVariable::LinkageTypes
680CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola181e3ec2013-05-13 00:12:11 +0000681 if (!RD->isExternallyVisible())
John McCalld5617ee2013-01-25 22:31:03 +0000682 return llvm::GlobalVariable::InternalLinkage;
683
684 // We're at the end of the translation unit, so the current key
685 // function is fully correct.
Stephen Hines176edba2014-12-01 14:53:08 -0800686 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
687 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCalld5617ee2013-01-25 22:31:03 +0000688 // If this class has a key function, use that to determine the
689 // linkage of the vtable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700690 const FunctionDecl *def = nullptr;
John McCalld5617ee2013-01-25 22:31:03 +0000691 if (keyFunction->hasBody(def))
692 keyFunction = cast<CXXMethodDecl>(def);
693
694 switch (keyFunction->getTemplateSpecializationKind()) {
695 case TSK_Undeclared:
696 case TSK_ExplicitSpecialization:
Rafael Espindola889a6752013-09-03 21:05:13 +0000697 assert(def && "Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000698 if (keyFunction->isInlined())
699 return !Context.getLangOpts().AppleKext ?
700 llvm::GlobalVariable::LinkOnceODRLinkage :
701 llvm::Function::InternalLinkage;
702
703 return llvm::GlobalVariable::ExternalLinkage;
704
705 case TSK_ImplicitInstantiation:
706 return !Context.getLangOpts().AppleKext ?
707 llvm::GlobalVariable::LinkOnceODRLinkage :
708 llvm::Function::InternalLinkage;
709
710 case TSK_ExplicitInstantiationDefinition:
711 return !Context.getLangOpts().AppleKext ?
712 llvm::GlobalVariable::WeakODRLinkage :
713 llvm::Function::InternalLinkage;
714
715 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola889a6752013-09-03 21:05:13 +0000716 llvm_unreachable("Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000717 }
718 }
719
720 // -fapple-kext mode does not support weak linkage, so we must use
721 // internal linkage.
722 if (Context.getLangOpts().AppleKext)
723 return llvm::Function::InternalLinkage;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700724
725 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
726 llvm::GlobalValue::LinkOnceODRLinkage;
727 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
728 llvm::GlobalValue::WeakODRLinkage;
729 if (RD->hasAttr<DLLExportAttr>()) {
730 // Cannot discard exported vtables.
731 DiscardableODRLinkage = NonDiscardableODRLinkage;
732 } else if (RD->hasAttr<DLLImportAttr>()) {
733 // Imported vtables are available externally.
734 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
735 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
736 }
737
John McCalld5617ee2013-01-25 22:31:03 +0000738 switch (RD->getTemplateSpecializationKind()) {
739 case TSK_Undeclared:
740 case TSK_ExplicitSpecialization:
741 case TSK_ImplicitInstantiation:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700742 return DiscardableODRLinkage;
John McCalld5617ee2013-01-25 22:31:03 +0000743
744 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola889a6752013-09-03 21:05:13 +0000745 llvm_unreachable("Should not have been asked to emit this");
John McCalld5617ee2013-01-25 22:31:03 +0000746
747 case TSK_ExplicitInstantiationDefinition:
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700748 return NonDiscardableODRLinkage;
John McCalld5617ee2013-01-25 22:31:03 +0000749 }
750
751 llvm_unreachable("Invalid TemplateSpecializationKind!");
752}
753
754/// This is a callback from Sema to tell us that it believes that a
755/// particular v-table is required to be emitted in this translation
756/// unit.
757///
758/// The reason we don't simply trust this callback is because Sema
759/// will happily report that something is used even when it's used
760/// only in code that we don't actually have to emit.
761///
762/// \param isRequired - if true, the v-table is mandatory, e.g.
763/// because the translation unit defines the key function
764void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
765 if (!isRequired) return;
766
767 VTables.GenerateClassData(theClass);
768}
769
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000770void
John McCalld5617ee2013-01-25 22:31:03 +0000771CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikie6a29f672013-08-22 15:23:05 +0000772 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
773 DI->completeClassData(RD);
774
Reid Kleckner90633022013-06-19 15:20:38 +0000775 if (RD->getNumVBases())
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000776 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregor1e201b42010-04-08 15:52:03 +0000777
Timur Iskhodzhanova53d7a02013-09-27 14:48:01 +0000778 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona7cde3b2010-03-29 03:38:52 +0000779}
John McCalld5617ee2013-01-25 22:31:03 +0000780
781/// At this point in the translation unit, does it appear that can we
782/// rely on the vtable being defined elsewhere in the program?
783///
784/// The response is really only definitive when called at the end of
785/// the translation unit.
786///
787/// The only semantic restriction here is that the object file should
788/// not contain a v-table definition when that v-table is defined
789/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
790/// v-tables when unnecessary.
791bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700792 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCalld5617ee2013-01-25 22:31:03 +0000793
794 // If we have an explicit instantiation declaration (and not a
795 // definition), the v-table is defined elsewhere.
796 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
797 if (TSK == TSK_ExplicitInstantiationDeclaration)
798 return true;
799
800 // Otherwise, if the class is an instantiated template, the
801 // v-table must be defined here.
802 if (TSK == TSK_ImplicitInstantiation ||
803 TSK == TSK_ExplicitInstantiationDefinition)
804 return false;
805
806 // Otherwise, if the class doesn't have a key function (possibly
807 // anymore), the v-table must be defined here.
808 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
809 if (!keyFunction)
810 return false;
811
812 // Otherwise, if we don't have a definition of the key function, the
813 // v-table must be defined somewhere else.
814 return !keyFunction->hasBody();
815}
816
817/// Given that we're currently at the end of the translation unit, and
818/// we've emitted a reference to the v-table for this class, should
819/// we define that v-table?
820static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
821 const CXXRecordDecl *RD) {
John McCalld5617ee2013-01-25 22:31:03 +0000822 return !CGM.getVTables().isVTableExternal(RD);
823}
824
825/// Given that at some point we emitted a reference to one or more
826/// v-tables, and that we are now at the end of the translation unit,
827/// decide whether we should emit them.
828void CodeGenModule::EmitDeferredVTables() {
829#ifndef NDEBUG
830 // Remember the size of DeferredVTables, because we're going to assume
831 // that this entire operation doesn't modify it.
832 size_t savedSize = DeferredVTables.size();
833#endif
834
835 typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
836 for (const_iterator i = DeferredVTables.begin(),
837 e = DeferredVTables.end(); i != e; ++i) {
838 const CXXRecordDecl *RD = *i;
839 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
840 VTables.GenerateClassData(RD);
841 }
842
843 assert(savedSize == DeferredVTables.size() &&
844 "deferred extra v-tables during v-table emission?");
845 DeferredVTables.clear();
846}