blob: be9c3115126e7b1515bfc7f7c36baa864af6e4ee [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
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000015#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
John McCall9c6cb762016-11-28 22:18:33 +000017#include "ConstantBuilder.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000019#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000021#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson5d40c6f2010-02-11 08:02:13 +000022#include "llvm/Support/Format.h"
Eli Friedman49a94b12011-05-06 17:27:27 +000023#include "llvm/Transforms/Utils/Cloning.h"
Anders Carlsson56446142010-03-17 20:06:32 +000024#include <algorithm>
Zhongxing Xu1721ef72009-11-13 05:46:16 +000025#include <cstdio>
Anders Carlsson2bb27f52009-10-11 22:13:54 +000026
27using namespace clang;
28using namespace CodeGen;
29
Reid Kleckner96f8f932014-02-05 17:27:08 +000030CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
31 : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
Peter Collingbournea8341662011-09-26 01:56:30 +000032
Simon Pilgrim48c32b12016-09-08 09:59:58 +000033llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
Anders Carlssonfe8a9932011-02-06 17:15:43 +000034 const ThunkInfo &Thunk) {
Anders Carlssoncd836f02010-03-23 17:17:29 +000035 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
36
37 // Compute the mangled name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000038 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +000039 llvm::raw_svector_ostream Out(Name);
Anders Carlssoncd836f02010-03-23 17:17:29 +000040 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
John McCall5d865c322010-08-31 07:33:07 +000041 getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
Rafael Espindola3968cd02011-02-11 02:52:17 +000042 Thunk.This, Out);
Anders Carlssoncd836f02010-03-23 17:17:29 +000043 else
Rafael Espindola3968cd02011-02-11 02:52:17 +000044 getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
Rafael Espindola3968cd02011-02-11 02:52:17 +000045
Chris Lattner2192fe52011-07-18 04:24:23 +000046 llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +000047 return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000048 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000049}
50
John McCallc8bd9c22010-08-04 23:46:35 +000051static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
52 const ThunkInfo &Thunk, llvm::Function *Fn) {
Anders Carlssonc6a47892011-01-29 19:39:23 +000053 CGM.setGlobalVisibility(Fn, MD);
John McCallc8bd9c22010-08-04 23:46:35 +000054}
55
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000056static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
57 llvm::Function *ThunkFn, bool ForVTable,
58 GlobalDecl GD) {
59 CGM.setFunctionLinkage(GD, ThunkFn);
60 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
61 !Thunk.Return.isEmpty());
62
63 // Set the right visibility.
64 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
65 setThunkVisibility(CGM, MD, Thunk, ThunkFn);
66
67 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
68 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
69}
70
John McCall5fe00962011-03-09 07:12:35 +000071#ifndef NDEBUG
72static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
73 const ABIArgInfo &infoR, CanQualType typeR) {
74 return (infoL.getKind() == infoR.getKind() &&
75 (typeL == typeR ||
76 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
77 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
78}
79#endif
80
Eli Friedman49a94b12011-05-06 17:27:27 +000081static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
82 QualType ResultType, RValue RV,
83 const ThunkInfo &Thunk) {
84 // Emit the return adjustment.
85 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000086
87 llvm::BasicBlock *AdjustNull = nullptr;
88 llvm::BasicBlock *AdjustNotNull = nullptr;
89 llvm::BasicBlock *AdjustEnd = nullptr;
90
Eli Friedman49a94b12011-05-06 17:27:27 +000091 llvm::Value *ReturnValue = RV.getScalarVal();
92
93 if (NullCheckValue) {
94 AdjustNull = CGF.createBasicBlock("adjust.null");
95 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
96 AdjustEnd = CGF.createBasicBlock("adjust.end");
Simon Pilgrim48c32b12016-09-08 09:59:58 +000097
Eli Friedman49a94b12011-05-06 17:27:27 +000098 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
99 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
100 CGF.EmitBlock(AdjustNotNull);
101 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000102
John McCall7f416cc2015-09-08 08:05:57 +0000103 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
104 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
105 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
106 Address(ReturnValue, ClassAlign),
107 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000108
Eli Friedman49a94b12011-05-06 17:27:27 +0000109 if (NullCheckValue) {
110 CGF.Builder.CreateBr(AdjustEnd);
111 CGF.EmitBlock(AdjustNull);
112 CGF.Builder.CreateBr(AdjustEnd);
113 CGF.EmitBlock(AdjustEnd);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000114
Eli Friedman49a94b12011-05-06 17:27:27 +0000115 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
116 PHI->addIncoming(ReturnValue, AdjustNotNull);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000117 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
Eli Friedman49a94b12011-05-06 17:27:27 +0000118 AdjustNull);
119 ReturnValue = PHI;
120 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000121
Eli Friedman49a94b12011-05-06 17:27:27 +0000122 return RValue::get(ReturnValue);
123}
124
125// This function does roughly the same thing as GenerateThunk, but in a
126// very different way, so that va_start and va_end work correctly.
127// FIXME: This function assumes "this" is the first non-sret LLVM argument of
128// a function, and that there is an alloca built in the entry block
129// for all accesses to "this".
130// FIXME: This function assumes there is only one "ret" statement per function.
131// FIXME: Cloning isn't correct in the presence of indirect goto!
132// FIXME: This implementation of thunks bloats codesize by duplicating the
133// function definition. There are alternatives:
134// 1. Add some sort of stub support to LLVM for cases where we can
135// do a this adjustment, then a sibcall.
136// 2. We could transform the definition to take a va_list instead of an
137// actual variable argument list, then have the thunks (including a
138// no-op thunk for the regular definition) call va_start/va_end.
139// There's a bit of per-call overhead for this solution, but it's
140// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000141llvm::Function *
142CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000143 const CGFunctionInfo &FnInfo,
144 GlobalDecl GD, const ThunkInfo &Thunk) {
145 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
146 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000147 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000148
149 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000150 assert(FnInfo.isVariadic());
151 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000152 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
153 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
154
155 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000156 llvm::ValueToValueMapTy VMap;
Peter Collingbourne7d6e81d2016-05-10 20:23:29 +0000157 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Eli Friedman49a94b12011-05-06 17:27:27 +0000158 Fn->replaceAllUsesWith(NewFn);
159 NewFn->takeName(Fn);
160 Fn->eraseFromParent();
161 Fn = NewFn;
162
163 // "Initialize" CGF (minimally).
164 CurFn = Fn;
165
166 // Get the "this" value
167 llvm::Function::arg_iterator AI = Fn->arg_begin();
168 if (CGM.ReturnTypeUsesSRet(FnInfo))
169 ++AI;
170
171 // Find the first store of "this", which will be to the alloca associated
172 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000173 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000174 llvm::BasicBlock *EntryBB = &Fn->front();
175 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000176 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000177 return isa<llvm::StoreInst>(I) &&
178 I.getOperand(0) == ThisPtr.getPointer();
179 });
180 assert(ThisStore != EntryBB->end() &&
181 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000182 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000183 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000184 llvm::Value *AdjustedThisPtr =
185 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Eli Friedman49a94b12011-05-06 17:27:27 +0000186 ThisStore->setOperand(0, AdjustedThisPtr);
187
188 if (!Thunk.Return.isEmpty()) {
189 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000190 for (llvm::BasicBlock &BB : *Fn) {
191 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000192 if (isa<llvm::ReturnInst>(T)) {
193 RValue RV = RValue::get(T->getOperand(0));
194 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000195 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000196 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
197 Builder.CreateRet(RV.getScalarVal());
198 break;
199 }
200 }
201 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000202
203 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000204}
205
Hans Wennborg88497d62013-11-15 17:24:45 +0000206void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
207 const CGFunctionInfo &FnInfo) {
208 assert(!CurGD.getDecl() && "CurGD was already set!");
209 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000210 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000211
212 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000213 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000214 QualType ThisType = MD->getThisType(getContext());
Hans Wennborg88497d62013-11-15 17:24:45 +0000215 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
David Majnemer0c0b6d92014-10-31 20:09:12 +0000216 QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
217 ? ThisType
218 : CGM.getCXXABI().hasMostDerivedReturn(GD)
219 ? CGM.getContext().VoidPtrTy
220 : FPT->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000221 FunctionArgList FunctionArgs;
222
Anders Carlssonbad991d2010-03-24 00:39:18 +0000223 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000224 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000225
226 // Add the rest of the parameters.
Alexey Samsonov3551e312014-08-13 20:06:24 +0000227 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000228
Reid Kleckner89077a12013-12-17 19:46:40 +0000229 if (isa<CXXDestructorDecl>(MD))
230 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
231
Hans Wennborg88497d62013-11-15 17:24:45 +0000232 // Start defining the function.
Adrian Prantldb763572016-11-09 21:43:51 +0000233 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCalla738c252011-03-09 04:27:21 +0000234 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Adrian Prantldb763572016-11-09 21:43:51 +0000235 MD->getLocation());
236 // Create a scope with an artificial location for the body of this function.
237 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000238
Hans Wennborg88497d62013-11-15 17:24:45 +0000239 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000240 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000241 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000242 CurCodeDecl = MD;
243 CurFuncDecl = MD;
244}
245
246void CodeGenFunction::FinishThunk() {
247 // Clear these to restore the invariants expected by
248 // StartFunction/FinishFunction.
249 CurCodeDecl = nullptr;
250 CurFuncDecl = nullptr;
251
252 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000253}
John McCall5d865c322010-08-31 07:33:07 +0000254
John McCallb92ab1a2016-10-26 23:46:34 +0000255void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Constant *CalleePtr,
Hans Wennborg88497d62013-11-15 17:24:45 +0000256 const ThunkInfo *Thunk) {
257 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
258 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000259 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000260
Hans Wennborg88497d62013-11-15 17:24:45 +0000261 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000262 llvm::Value *AdjustedThisPtr =
263 Thunk ? CGM.getCXXABI().performThisAdjustment(
264 *this, LoadCXXThisAddress(), Thunk->This)
265 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000266
Reid Klecknerab2090d2014-07-26 01:34:32 +0000267 if (CurFnInfo->usesInAlloca()) {
268 // We don't handle return adjusting thunks, because they require us to call
269 // the copy constructor. For now, fall through and pretend the return
270 // adjustment was empty so we don't crash.
271 if (Thunk && !Thunk->Return.isEmpty()) {
272 CGM.ErrorUnsupported(
273 MD, "non-trivial argument copy for return-adjusting thunk");
274 }
John McCallb92ab1a2016-10-26 23:46:34 +0000275 EmitMustTailThunk(MD, AdjustedThisPtr, CalleePtr);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000276 return;
277 }
278
Hans Wennborg88497d62013-11-15 17:24:45 +0000279 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000280 CallArgList CallArgs;
Hans Wennborg88497d62013-11-15 17:24:45 +0000281 QualType ThisType = MD->getThisType(getContext());
Eli Friedman43dca6a2011-05-02 17:57:46 +0000282 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000283
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000284 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000285 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000286
Hans Wennborg88497d62013-11-15 17:24:45 +0000287 // Add the rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +0000288 for (const ParmVarDecl *PD : MD->parameters())
Adrian Prantldb763572016-11-09 21:43:51 +0000289 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000290
Hans Wennborg88497d62013-11-15 17:24:45 +0000291 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000292
John McCalla738c252011-03-09 04:27:21 +0000293#ifndef NDEBUG
George Burgess IV419996c2016-06-16 23:06:04 +0000294 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
295 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD));
Hans Wennborg88497d62013-11-15 17:24:45 +0000296 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
297 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
298 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000299 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
300 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000301 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
302 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
303 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000304 assert(similar(CallFnInfo.arg_begin()[i].info,
305 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000306 CurFnInfo->arg_begin()[i].info,
307 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000308#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000309
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000310 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000311 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
312 ? ThisType
313 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
314 ? CGM.getContext().VoidPtrTy
315 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000316 ReturnValueSlot Slot;
317 if (!ResultType->isVoidType() &&
Hans Wennborg88497d62013-11-15 17:24:45 +0000318 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +0000319 !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000320 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000321
Anders Carlssonbad991d2010-03-24 00:39:18 +0000322 // Now emit our call.
Reid Klecknerab2090d2014-07-26 01:34:32 +0000323 llvm::Instruction *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +0000324 CGCallee Callee = CGCallee::forDirect(CalleePtr, MD);
325 RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, &CallOrInvoke);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000326
Hans Wennborg88497d62013-11-15 17:24:45 +0000327 // Consider return adjustment if we have ThunkInfo.
328 if (Thunk && !Thunk->Return.isEmpty())
329 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000330 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
331 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
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
John McCall7f416cc2015-09-08 08:05:57 +0000340 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000341}
342
Reid Klecknerab2090d2014-07-26 01:34:32 +0000343void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
344 llvm::Value *AdjustedThisPtr,
John McCallb92ab1a2016-10-26 23:46:34 +0000345 llvm::Value *CalleePtr) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000346 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
347 // to translate AST arguments into LLVM IR arguments. For thunks, we know
348 // that the caller prototype more or less matches the callee prototype with
349 // the exception of 'this'.
350 SmallVector<llvm::Value *, 8> Args;
351 for (llvm::Argument &A : CurFn->args())
352 Args.push_back(&A);
353
354 // Set the adjusted 'this' pointer.
355 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
356 if (ThisAI.isDirect()) {
357 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
358 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
359 llvm::Type *ThisType = Args[ThisArgNo]->getType();
360 if (ThisType != AdjustedThisPtr->getType())
361 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
362 Args[ThisArgNo] = AdjustedThisPtr;
363 } else {
364 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000365 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
366 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000367 if (ThisType != AdjustedThisPtr->getType())
368 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
369 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
370 }
371
372 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
373 // don't actually want to run them.
John McCallb92ab1a2016-10-26 23:46:34 +0000374 llvm::CallInst *Call = Builder.CreateCall(CalleePtr, Args);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000375 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
376
377 // Apply the standard set of call attributes.
378 unsigned CallingConv;
379 CodeGen::AttributeListType AttributeList;
John McCallb92ab1a2016-10-26 23:46:34 +0000380 CGM.ConstructAttributeList(CalleePtr->getName(),
381 *CurFnInfo, MD, AttributeList,
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000382 CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000383 llvm::AttributeSet Attrs =
384 llvm::AttributeSet::get(getLLVMContext(), AttributeList);
385 Call->setAttributes(Attrs);
386 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
387
388 if (Call->getType()->isVoidTy())
389 Builder.CreateRetVoid();
390 else
391 Builder.CreateRet(Call);
392
393 // Finish the function to maintain CodeGenFunction invariants.
394 // FIXME: Don't emit unreachable code.
395 EmitBlock(createBasicBlock());
396 FinishFunction();
397}
398
Rafael Espindolad6e66942015-07-13 06:07:58 +0000399void CodeGenFunction::generateThunk(llvm::Function *Fn,
Hans Wennborg88497d62013-11-15 17:24:45 +0000400 const CGFunctionInfo &FnInfo,
401 GlobalDecl GD, const ThunkInfo &Thunk) {
402 StartThunk(Fn, GD, FnInfo);
Adrian Prantldb763572016-11-09 21:43:51 +0000403 // Create a scope with an artificial location for the body of this function.
404 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Hans Wennborg88497d62013-11-15 17:24:45 +0000405
406 // Get our callee.
407 llvm::Type *Ty =
408 CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
John McCallb92ab1a2016-10-26 23:46:34 +0000409 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Hans Wennborg88497d62013-11-15 17:24:45 +0000410
411 // Make the call and return the result.
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000412 EmitCallAndReturnForThunk(Callee, &Thunk);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000413}
414
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000415void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
416 bool ForVTable) {
John McCalla729c622012-02-17 03:33:10 +0000417 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
John McCalla738c252011-03-09 04:27:21 +0000418
419 // FIXME: re-use FnInfo in this computation.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000420 llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
421 llvm::GlobalValue *Entry;
422
Anders Carlsson55e89f82010-03-23 18:18:41 +0000423 // Strip off a bitcast if we got one back.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000424 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
Anders Carlsson55e89f82010-03-23 18:18:41 +0000425 assert(CE->getOpcode() == llvm::Instruction::BitCast);
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000426 Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
427 } else {
428 Entry = cast<llvm::GlobalValue>(C);
Anders Carlsson55e89f82010-03-23 18:18:41 +0000429 }
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000430
Anders Carlsson55e89f82010-03-23 18:18:41 +0000431 // There's already a declaration with the same name, check if it has the same
432 // type or if we need to replace it.
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000433 if (Entry->getType()->getElementType() !=
John McCall5d865c322010-08-31 07:33:07 +0000434 CGM.getTypes().GetFunctionTypeForVTable(GD)) {
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000435 llvm::GlobalValue *OldThunkFn = Entry;
436
Anders Carlsson55e89f82010-03-23 18:18:41 +0000437 // If the types mismatch then we have to rewrite the definition.
438 assert(OldThunkFn->isDeclaration() &&
439 "Shouldn't replace non-declaration");
440
441 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000442 OldThunkFn->setName(StringRef());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000443 Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000444
Anders Carlsson55e89f82010-03-23 18:18:41 +0000445 // If needed, replace the old thunk with a bitcast.
446 if (!OldThunkFn->use_empty()) {
447 llvm::Constant *NewPtrForOldDecl =
Anders Carlsson4a3cdf52010-03-24 00:35:44 +0000448 llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000449 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
450 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000451
Anders Carlsson55e89f82010-03-23 18:18:41 +0000452 // Remove the old thunk.
453 OldThunkFn->eraseFromParent();
454 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000455
Anders Carlssonbad991d2010-03-24 00:39:18 +0000456 llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000457 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
458 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000459
460 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000461 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000462 // There is already a thunk emitted for this function, do nothing.
463 return;
464 }
465
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000466 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlssone866d442011-02-06 20:09:44 +0000467 return;
Anders Carlsson8b021832011-02-06 18:31:40 +0000468 }
469
Rafael Espindola86792432012-09-21 20:39:32 +0000470 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
471
Eli Friedman49a94b12011-05-06 17:27:27 +0000472 if (ThunkFn->isVarArg()) {
473 // Varargs thunks are special; we can't just generate a call because
474 // we can't copy the varargs. Our implementation is rather
475 // expensive/sucky at the moment, so don't generate the thunk unless
476 // we have to.
477 // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
Peter Collingbourne45a24012015-06-30 19:07:26 +0000478 if (UseAvailableExternallyLinkage)
479 return;
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000480 ThunkFn =
481 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000482 } else {
483 // Normal thunk body generation.
Rafael Espindolad6e66942015-07-13 06:07:58 +0000484 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
Eli Friedman49a94b12011-05-06 17:27:27 +0000485 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000486
Rafael Espindola6bedf4a2015-07-15 14:48:06 +0000487 setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
Anders Carlsson8b021832011-02-06 18:31:40 +0000488}
489
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000490void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
491 const ThunkInfo &Thunk) {
492 // If the ABI has key functions, only the TU with the key function should emit
493 // the thunk. However, we can allow inlining of thunks if we emit them with
494 // available_externally linkage together with vtables when optimizations are
495 // enabled.
496 if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
497 !CGM.getCodeGenOpts().OptimizationLevel)
Anders Carlsson8b021832011-02-06 18:31:40 +0000498 return;
499
500 // We can't emit thunks for member functions with incomplete types.
501 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Chris Lattner8806e322011-07-10 00:18:59 +0000502 if (!CGM.getTypes().isFuncTypeConvertible(
Reid Klecknerfe56be52013-10-11 20:46:27 +0000503 MD->getType()->castAs<FunctionType>()))
Anders Carlsson8b021832011-02-06 18:31:40 +0000504 return;
505
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000506 emitThunk(GD, Thunk, /*ForVTable=*/true);
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000507}
508
Anders Carlsson917229c2010-03-23 04:59:02 +0000509void CodeGenVTables::EmitThunks(GlobalDecl GD)
510{
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000511 const CXXMethodDecl *MD =
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000512 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
513
514 // We don't need to generate thunks for the base destructor.
515 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
516 return;
517
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000518 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
519 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000520
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000521 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000522 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000523
Yaron Kerenede60302015-08-01 19:11:36 +0000524 for (const ThunkInfo& Thunk : *ThunkInfoVector)
525 emitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000526}
527
John McCall9c6cb762016-11-28 22:18:33 +0000528void CodeGenVTables::addVTableComponent(
529 ConstantArrayBuilder &builder, const VTableLayout &layout,
530 unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
531 auto &component = layout.vtable_components()[idx];
Anders Carlssona4147142010-03-25 15:26:28 +0000532
John McCall9c6cb762016-11-28 22:18:33 +0000533 auto addOffsetConstant = [&](CharUnits offset) {
534 builder.add(llvm::ConstantExpr::getIntToPtr(
535 llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
536 CGM.Int8PtrTy));
Peter Collingbournee53683f2016-09-08 01:14:39 +0000537 };
Anders Carlssona5736bd2010-03-25 16:49:53 +0000538
John McCall9c6cb762016-11-28 22:18:33 +0000539 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000540 case VTableComponent::CK_VCallOffset:
John McCall9c6cb762016-11-28 22:18:33 +0000541 return addOffsetConstant(component.getVCallOffset());
Craig Topper8a13c412014-05-21 05:09:00 +0000542
Peter Collingbournee53683f2016-09-08 01:14:39 +0000543 case VTableComponent::CK_VBaseOffset:
John McCall9c6cb762016-11-28 22:18:33 +0000544 return addOffsetConstant(component.getVBaseOffset());
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000545
Peter Collingbournee53683f2016-09-08 01:14:39 +0000546 case VTableComponent::CK_OffsetToTop:
John McCall9c6cb762016-11-28 22:18:33 +0000547 return addOffsetConstant(component.getOffsetToTop());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000548
Peter Collingbournee53683f2016-09-08 01:14:39 +0000549 case VTableComponent::CK_RTTI:
John McCall9c6cb762016-11-28 22:18:33 +0000550 return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
Anders Carlssona5736bd2010-03-25 16:49:53 +0000551
Peter Collingbournee53683f2016-09-08 01:14:39 +0000552 case VTableComponent::CK_FunctionPointer:
553 case VTableComponent::CK_CompleteDtorPointer:
554 case VTableComponent::CK_DeletingDtorPointer: {
555 GlobalDecl GD;
556
557 // Get the right global decl.
John McCall9c6cb762016-11-28 22:18:33 +0000558 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000559 default:
560 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000561 case VTableComponent::CK_FunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000562 GD = component.getFunctionDecl();
Peter Collingbournee53683f2016-09-08 01:14:39 +0000563 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000564 case VTableComponent::CK_CompleteDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000565 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000566 break;
567 case VTableComponent::CK_DeletingDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000568 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000569 break;
570 }
571
Peter Collingbournee53683f2016-09-08 01:14:39 +0000572 if (CGM.getLangOpts().CUDA) {
573 // Emit NULL for methods we can't codegen on this
574 // side. Otherwise we'd end up with vtable with unresolved
575 // references.
576 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
577 // OK on device side: functions w/ __device__ attribute
578 // OK on host side: anything except __device__-only functions.
579 bool CanEmitMethod =
580 CGM.getLangOpts().CUDAIsDevice
581 ? MD->hasAttr<CUDADeviceAttr>()
582 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
583 if (!CanEmitMethod)
John McCall9c6cb762016-11-28 22:18:33 +0000584 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000585 // Method is acceptable, continue processing as usual.
586 }
587
John McCall9c6cb762016-11-28 22:18:33 +0000588 auto getSpecialVirtualFn = [&](StringRef name) {
589 llvm::FunctionType *fnTy =
590 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
591 llvm::Constant *fn = CGM.CreateRuntimeFunction(fnTy, name);
592 if (auto f = dyn_cast<llvm::Function>(fn))
593 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
594 return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000595 };
Peter Collingbournee53683f2016-09-08 01:14:39 +0000596
John McCall9c6cb762016-11-28 22:18:33 +0000597 llvm::Constant *fnPtr;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000598
John McCall9c6cb762016-11-28 22:18:33 +0000599 // Pure virtual member functions.
600 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
601 if (!PureVirtualFn)
602 PureVirtualFn =
603 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
604 fnPtr = PureVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000605
John McCall9c6cb762016-11-28 22:18:33 +0000606 // Deleted virtual member functions.
607 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
608 if (!DeletedVirtualFn)
609 DeletedVirtualFn =
610 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
611 fnPtr = DeletedVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000612
John McCall9c6cb762016-11-28 22:18:33 +0000613 // Thunks.
614 } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
615 layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
616 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
617
618 maybeEmitThunkForVTable(GD, thunkInfo);
619 nextVTableThunkIndex++;
620 fnPtr = CGM.GetAddrOfThunk(GD, thunkInfo);
621
622 // Otherwise we can use the method definition directly.
623 } else {
624 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
625 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000626 }
627
John McCall9c6cb762016-11-28 22:18:33 +0000628 fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
629 builder.add(fnPtr);
630 return;
Anders Carlssona4147142010-03-25 15:26:28 +0000631 }
Peter Collingbournee53683f2016-09-08 01:14:39 +0000632
633 case VTableComponent::CK_UnusedFunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000634 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000635 }
Simon Pilgrim4acc49e2016-09-08 11:03:41 +0000636
637 llvm_unreachable("Unexpected vtable component kind");
Peter Collingbournee53683f2016-09-08 01:14:39 +0000638}
639
John McCall9c6cb762016-11-28 22:18:33 +0000640void CodeGenVTables::createVTableInitializer(ConstantArrayBuilder &builder,
641 const VTableLayout &layout,
642 llvm::Constant *rtti) {
643 unsigned nextVTableThunkIndex = 0;
644 for (unsigned i = 0, e = layout.vtable_components().size(); i != e; ++i) {
645 addVTableComponent(builder, layout, i, rtti, nextVTableThunkIndex);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000646 }
Anders Carlssona4147142010-03-25 15:26:28 +0000647}
648
Anders Carlsson0534b022010-03-25 00:35:49 +0000649llvm::GlobalVariable *
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000650CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
651 const BaseSubobject &Base,
652 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000653 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000654 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000655 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
656 DI->completeClassData(Base.getBase());
657
Ahmed Charlesb8984322014-03-07 20:03:18 +0000658 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000659 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000660 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000661
Anders Carlssona5736bd2010-03-25 16:49:53 +0000662 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000663 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000664
665 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000666 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000667 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000668 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
669 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
670 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000671 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000672
Peter Collingbournee53683f2016-09-08 01:14:39 +0000673 llvm::ArrayType *ArrayType =
674 llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->vtable_components().size());
Anders Carlssona4147142010-03-25 15:26:28 +0000675
Richard Smith65fd2a42013-02-16 00:51:21 +0000676 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
677 // guarantee that they actually will be available externally. Instead, when
678 // emitting an available_externally VTT, we provide references to an internal
679 // linkage construction vtable. The ABI only requires complete-object vtables
680 // to be the same for all instances of a type, not construction vtables.
681 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
682 Linkage = llvm::GlobalVariable::InternalLinkage;
683
Anders Carlssona4147142010-03-25 15:26:28 +0000684 // Create the variable that will hold the construction vtable.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000685 llvm::GlobalVariable *VTable =
John McCall358d0562011-03-27 09:00:25 +0000686 CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
John McCall8f80a612014-02-08 00:41:16 +0000687 CGM.setGlobalVisibility(VTable, RD);
John McCall358d0562011-03-27 09:00:25 +0000688
689 // V-tables are always unnamed_addr.
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000690 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Anders Carlssona4147142010-03-25 15:26:28 +0000691
David Majnemerd905da42014-07-01 20:30:31 +0000692 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
693 CGM.getContext().getTagDeclType(Base.getBase()));
694
Anders Carlssona4147142010-03-25 15:26:28 +0000695 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +0000696 ConstantInitBuilder builder(CGM);
697 auto components = builder.beginArray(CGM.Int8PtrTy);
698 createVTableInitializer(components, *VTLayout, RTTI);
699 components.finishAndSetAsInitializer(VTable);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000700
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000701 CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000702
Anders Carlsson0534b022010-03-25 00:35:49 +0000703 return VTable;
704}
705
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000706static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
707 const CXXRecordDecl *RD) {
708 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000709 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000710}
711
Eric Christopherd160c502016-01-29 01:35:53 +0000712/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +0000713///
714/// Note that we only call this at the end of the translation unit.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000715llvm::GlobalVariable::LinkageTypes
John McCall6bd2a892013-01-25 22:31:03 +0000716CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000717 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000718 return llvm::GlobalVariable::InternalLinkage;
719
720 // We're at the end of the translation unit, so the current key
721 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000722 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
723 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000724 // If this class has a key function, use that to determine the
725 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000726 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000727 if (keyFunction->hasBody(def))
728 keyFunction = cast<CXXMethodDecl>(def);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000729
John McCall6bd2a892013-01-25 22:31:03 +0000730 switch (keyFunction->getTemplateSpecializationKind()) {
731 case TSK_Undeclared:
732 case TSK_ExplicitSpecialization:
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000733 assert((def || CodeGenOpts.OptimizationLevel > 0) &&
734 "Shouldn't query vtable linkage without key function or "
735 "optimizations");
736 if (!def && CodeGenOpts.OptimizationLevel > 0)
737 return llvm::GlobalVariable::AvailableExternallyLinkage;
738
John McCall6bd2a892013-01-25 22:31:03 +0000739 if (keyFunction->isInlined())
740 return !Context.getLangOpts().AppleKext ?
741 llvm::GlobalVariable::LinkOnceODRLinkage :
742 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000743
John McCall6bd2a892013-01-25 22:31:03 +0000744 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000745
John McCall6bd2a892013-01-25 22:31:03 +0000746 case TSK_ImplicitInstantiation:
747 return !Context.getLangOpts().AppleKext ?
748 llvm::GlobalVariable::LinkOnceODRLinkage :
749 llvm::Function::InternalLinkage;
750
751 case TSK_ExplicitInstantiationDefinition:
752 return !Context.getLangOpts().AppleKext ?
753 llvm::GlobalVariable::WeakODRLinkage :
754 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000755
John McCall6bd2a892013-01-25 22:31:03 +0000756 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000757 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000758 }
759 }
760
761 // -fapple-kext mode does not support weak linkage, so we must use
762 // internal linkage.
763 if (Context.getLangOpts().AppleKext)
764 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000765
766 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
767 llvm::GlobalValue::LinkOnceODRLinkage;
768 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
769 llvm::GlobalValue::WeakODRLinkage;
770 if (RD->hasAttr<DLLExportAttr>()) {
771 // Cannot discard exported vtables.
772 DiscardableODRLinkage = NonDiscardableODRLinkage;
773 } else if (RD->hasAttr<DLLImportAttr>()) {
774 // Imported vtables are available externally.
775 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
776 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
777 }
778
John McCall6bd2a892013-01-25 22:31:03 +0000779 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000780 case TSK_Undeclared:
781 case TSK_ExplicitSpecialization:
782 case TSK_ImplicitInstantiation:
783 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000784
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000785 case TSK_ExplicitInstantiationDeclaration:
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000786 // Explicit instantiations in MSVC do not provide vtables, so we must emit
787 // our own.
788 if (getTarget().getCXXABI().isMicrosoft())
789 return DiscardableODRLinkage;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000790 return shouldEmitAvailableExternallyVTable(*this, RD)
791 ? llvm::GlobalVariable::AvailableExternallyLinkage
792 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000793
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000794 case TSK_ExplicitInstantiationDefinition:
795 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000796 }
797
798 llvm_unreachable("Invalid TemplateSpecializationKind!");
799}
800
Eric Christopherd160c502016-01-29 01:35:53 +0000801/// This is a callback from Sema to tell us that that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +0000802/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000803///
Nico Weberb6a5d052015-01-15 04:07:35 +0000804/// This is only called for vtables that _must_ be emitted (mainly due to key
805/// functions). For weak vtables, CodeGen tracks when they are needed and
806/// emits them as-needed.
807void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000808 VTables.GenerateClassData(theClass);
809}
810
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000811void
John McCall6bd2a892013-01-25 22:31:03 +0000812CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000813 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
814 DI->completeClassData(RD);
815
Reid Kleckner7810af02013-06-19 15:20:38 +0000816 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000817 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000818
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000819 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000820}
John McCall6bd2a892013-01-25 22:31:03 +0000821
822/// At this point in the translation unit, does it appear that can we
823/// rely on the vtable being defined elsewhere in the program?
824///
825/// The response is really only definitive when called at the end of
826/// the translation unit.
827///
828/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +0000829/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +0000830/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +0000831/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +0000832bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000833 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000834
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000835 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
836 // emit them even if there is an explicit template instantiation.
837 if (CGM.getTarget().getCXXABI().isMicrosoft())
David Majnemer2d8b2002016-02-11 17:49:28 +0000838 return false;
839
John McCall6bd2a892013-01-25 22:31:03 +0000840 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +0000841 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +0000842 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
843 if (TSK == TSK_ExplicitInstantiationDeclaration)
844 return true;
845
846 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +0000847 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000848 if (TSK == TSK_ImplicitInstantiation ||
849 TSK == TSK_ExplicitInstantiationDefinition)
850 return false;
851
852 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +0000853 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000854 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
855 if (!keyFunction)
856 return false;
857
858 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +0000859 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +0000860 return !keyFunction->hasBody();
861}
862
863/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +0000864/// we've emitted a reference to the vtable for this class, should
865/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +0000866static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
867 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000868 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000869 if (!CGM.getVTables().isVTableExternal(RD))
870 return true;
871
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000872 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000873 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000874}
875
876/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +0000877/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +0000878/// decide whether we should emit them.
879void CodeGenModule::EmitDeferredVTables() {
880#ifndef NDEBUG
881 // Remember the size of DeferredVTables, because we're going to assume
882 // that this entire operation doesn't modify it.
883 size_t savedSize = DeferredVTables.size();
884#endif
885
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000886 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000887 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
888 VTables.GenerateClassData(RD);
John McCall6bd2a892013-01-25 22:31:03 +0000889
890 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +0000891 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +0000892 DeferredVTables.clear();
893}
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000894
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000895bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
896 LinkageInfo LV = RD->getLinkageAndVisibility();
897 if (!isExternallyVisible(LV.getLinkage()))
898 return true;
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000899
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000900 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
901 return false;
Peter Collingbournefb532b92016-02-24 20:46:36 +0000902
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000903 if (getTriple().isOSBinFormatCOFF()) {
904 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
905 return false;
906 } else {
907 if (LV.getVisibility() != HiddenVisibility)
908 return false;
909 }
Peter Collingbournefb532b92016-02-24 20:46:36 +0000910
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000911 if (getCodeGenOpts().LTOVisibilityPublicStd) {
912 const DeclContext *DC = RD;
913 while (1) {
914 auto *D = cast<Decl>(DC);
915 DC = DC->getParent();
916 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
917 if (auto *ND = dyn_cast<NamespaceDecl>(D))
918 if (const IdentifierInfo *II = ND->getIdentifier())
919 if (II->isStr("std") || II->isStr("stdext"))
920 return false;
921 break;
922 }
923 }
924 }
925
926 return true;
Peter Collingbournee5706442015-07-09 19:56:14 +0000927}
928
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000929void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
930 const VTableLayout &VTLayout) {
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000931 if (!getCodeGenOpts().PrepareForLTO)
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000932 return;
933
Peter Collingbourne86d34a72015-06-17 19:08:05 +0000934 CharUnits PointerWidth =
935 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000936
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000937 typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
938 std::vector<BSEntry> BitsetEntries;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000939 // Create a bit set entry for each address point.
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000940 for (auto &&AP : VTLayout.getAddressPoints())
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000941 BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000942
943 // Sort the bit set entries for determinism.
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000944 std::sort(BitsetEntries.begin(), BitsetEntries.end(),
945 [this](const BSEntry &E1, const BSEntry &E2) {
946 if (&E1 == &E2)
Peter Collingbourne47941902015-02-24 01:12:53 +0000947 return false;
948
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000949 std::string S1;
950 llvm::raw_string_ostream O1(S1);
951 getCXXABI().getMangleContext().mangleTypeName(
952 QualType(E1.first->getTypeForDecl(), 0), O1);
953 O1.flush();
954
955 std::string S2;
956 llvm::raw_string_ostream O2(S2);
957 getCXXABI().getMangleContext().mangleTypeName(
958 QualType(E2.first->getTypeForDecl(), 0), O2);
959 O2.flush();
960
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000961 if (S1 < S2)
962 return true;
963 if (S1 != S2)
964 return false;
965
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +0000966 return E1.second < E2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000967 });
968
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000969 for (auto BitsetEntry : BitsetEntries)
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000970 AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
971 BitsetEntry.first);
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000972}