blob: a74905fd70fd44b3f52bc00117bf6a9950ea0525 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson2bb27f52009-10-11 22:13:54 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of virtual tables.
10//
11//===----------------------------------------------------------------------===//
12
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CodeGenModule.h"
Anders Carlssonf942ee02009-11-27 20:47:55 +000016#include "clang/AST/CXXInheritance.h"
Anders Carlsson2bb27f52009-10-11 22:13:54 +000017#include "clang/AST/RecordLayout.h"
Richard Trieu63688182018-12-11 03:18:39 +000018#include "clang/Basic/CodeGenOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Wolfgang Pieba347c472017-10-31 22:49:48 +000020#include "clang/CodeGen/ConstantInitBuilder.h"
Wolfgang Pieba347c472017-10-31 22:49:48 +000021#include "llvm/IR/IntrinsicInst.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
Reid Kleckner399d96e2018-04-02 20:20:33 +000033llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
34 GlobalDecl GD) {
35 return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
David Majnemerb9bd6fb2014-11-01 05:42:23 +000036 /*DontDefer=*/true, /*IsThunk=*/true);
Anders Carlssoncd836f02010-03-23 17:17:29 +000037}
38
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000039static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
40 llvm::Function *ThunkFn, bool ForVTable,
41 GlobalDecl GD) {
42 CGM.setFunctionLinkage(GD, ThunkFn);
43 CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
44 !Thunk.Return.isEmpty());
45
46 // Set the right visibility.
Rafael Espindolab7350042018-03-01 00:35:47 +000047 CGM.setGVProperties(ThunkFn, GD);
48
49 if (!CGM.getCXXABI().exportThunk()) {
50 ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
51 ThunkFn->setDSOLocal(true);
52 }
Rafael Espindola6bedf4a2015-07-15 14:48:06 +000053
54 if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
55 ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
56}
57
John McCall5fe00962011-03-09 07:12:35 +000058#ifndef NDEBUG
59static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
60 const ABIArgInfo &infoR, CanQualType typeR) {
61 return (infoL.getKind() == infoR.getKind() &&
62 (typeL == typeR ||
63 (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
64 (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
65}
66#endif
67
Eli Friedman49a94b12011-05-06 17:27:27 +000068static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
69 QualType ResultType, RValue RV,
70 const ThunkInfo &Thunk) {
71 // Emit the return adjustment.
72 bool NullCheckValue = !ResultType->isReferenceType();
Craig Topper8a13c412014-05-21 05:09:00 +000073
74 llvm::BasicBlock *AdjustNull = nullptr;
75 llvm::BasicBlock *AdjustNotNull = nullptr;
76 llvm::BasicBlock *AdjustEnd = nullptr;
77
Eli Friedman49a94b12011-05-06 17:27:27 +000078 llvm::Value *ReturnValue = RV.getScalarVal();
79
80 if (NullCheckValue) {
81 AdjustNull = CGF.createBasicBlock("adjust.null");
82 AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
83 AdjustEnd = CGF.createBasicBlock("adjust.end");
Simon Pilgrim48c32b12016-09-08 09:59:58 +000084
Eli Friedman49a94b12011-05-06 17:27:27 +000085 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
86 CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
87 CGF.EmitBlock(AdjustNotNull);
88 }
Timur Iskhodzhanov02014322013-10-30 11:55:43 +000089
John McCall7f416cc2015-09-08 08:05:57 +000090 auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
91 auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
92 ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
93 Address(ReturnValue, ClassAlign),
94 Thunk.Return);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +000095
Eli Friedman49a94b12011-05-06 17:27:27 +000096 if (NullCheckValue) {
97 CGF.Builder.CreateBr(AdjustEnd);
98 CGF.EmitBlock(AdjustNull);
99 CGF.Builder.CreateBr(AdjustEnd);
100 CGF.EmitBlock(AdjustEnd);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000101
Eli Friedman49a94b12011-05-06 17:27:27 +0000102 llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
103 PHI->addIncoming(ReturnValue, AdjustNotNull);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000104 PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
Eli Friedman49a94b12011-05-06 17:27:27 +0000105 AdjustNull);
106 ReturnValue = PHI;
107 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000108
Eli Friedman49a94b12011-05-06 17:27:27 +0000109 return RValue::get(ReturnValue);
110}
111
Fangrui Song6907ce22018-07-30 19:24:48 +0000112/// This function clones a function's DISubprogram node and enters it into
Wolfgang Pieba347c472017-10-31 22:49:48 +0000113/// a value map with the intent that the map can be utilized by the cloner
114/// to short-circuit Metadata node mapping.
115/// Furthermore, the function resolves any DILocalVariable nodes referenced
116/// by dbg.value intrinsics so they can be properly mapped during cloning.
117static void resolveTopLevelMetadata(llvm::Function *Fn,
118 llvm::ValueToValueMapTy &VMap) {
119 // Clone the DISubprogram node and put it into the Value map.
120 auto *DIS = Fn->getSubprogram();
121 if (!DIS)
122 return;
123 auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
124 VMap.MD()[DIS].reset(NewDIS);
125
126 // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
127 // they are referencing.
128 for (auto &BB : Fn->getBasicBlockList()) {
129 for (auto &I : BB) {
Hsiangkai Wange7b3da22018-08-06 04:00:08 +0000130 if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
Wolfgang Pieba347c472017-10-31 22:49:48 +0000131 auto *DILocal = DII->getVariable();
132 if (!DILocal->isResolved())
133 DILocal->resolve();
134 }
135 }
136 }
137}
138
Eli Friedman49a94b12011-05-06 17:27:27 +0000139// This function does roughly the same thing as GenerateThunk, but in a
140// very different way, so that va_start and va_end work correctly.
141// FIXME: This function assumes "this" is the first non-sret LLVM argument of
142// a function, and that there is an alloca built in the entry block
143// for all accesses to "this".
144// FIXME: This function assumes there is only one "ret" statement per function.
145// FIXME: Cloning isn't correct in the presence of indirect goto!
146// FIXME: This implementation of thunks bloats codesize by duplicating the
147// function definition. There are alternatives:
148// 1. Add some sort of stub support to LLVM for cases where we can
149// do a this adjustment, then a sibcall.
150// 2. We could transform the definition to take a va_list instead of an
151// actual variable argument list, then have the thunks (including a
152// no-op thunk for the regular definition) call va_start/va_end.
153// There's a bit of per-call overhead for this solution, but it's
154// better for codesize if the definition is long.
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000155llvm::Function *
156CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
Eli Friedman49a94b12011-05-06 17:27:27 +0000157 const CGFunctionInfo &FnInfo,
158 GlobalDecl GD, const ThunkInfo &Thunk) {
159 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Simon Pilgrim5e0a0b72019-10-01 22:02:46 +0000160 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +0000161 QualType ResultType = FPT->getReturnType();
Eli Friedman49a94b12011-05-06 17:27:27 +0000162
163 // Get the original function
John McCalla729c622012-02-17 03:33:10 +0000164 assert(FnInfo.isVariadic());
165 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
Eli Friedman49a94b12011-05-06 17:27:27 +0000166 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
167 llvm::Function *BaseFn = cast<llvm::Function>(Callee);
168
Reid Kleckner28328c32019-09-06 22:55:26 +0000169 // Cloning can't work if we don't have a definition. The Microsoft ABI may
170 // require thunks when a definition is not available. Emit an error in these
171 // cases.
172 if (!MD->isDefined()) {
173 CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
174 return Fn;
175 }
176 assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
177
Eli Friedman49a94b12011-05-06 17:27:27 +0000178 // Clone to thunk.
Benjamin Kramer6ca42102012-09-19 13:13:52 +0000179 llvm::ValueToValueMapTy VMap;
Wolfgang Pieba347c472017-10-31 22:49:48 +0000180
181 // We are cloning a function while some Metadata nodes are still unresolved.
182 // Ensure that the value mapper does not encounter any of them.
183 resolveTopLevelMetadata(BaseFn, VMap);
Peter Collingbourne7d6e81d2016-05-10 20:23:29 +0000184 llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
Eli Friedman49a94b12011-05-06 17:27:27 +0000185 Fn->replaceAllUsesWith(NewFn);
186 NewFn->takeName(Fn);
187 Fn->eraseFromParent();
188 Fn = NewFn;
189
190 // "Initialize" CGF (minimally).
191 CurFn = Fn;
192
193 // Get the "this" value
194 llvm::Function::arg_iterator AI = Fn->arg_begin();
195 if (CGM.ReturnTypeUsesSRet(FnInfo))
196 ++AI;
197
198 // Find the first store of "this", which will be to the alloca associated
199 // with "this".
John McCall7f416cc2015-09-08 08:05:57 +0000200 Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000201 llvm::BasicBlock *EntryBB = &Fn->front();
202 llvm::BasicBlock::iterator ThisStore =
David Blaikiea629c0f2014-12-29 22:39:45 +0000203 std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000204 return isa<llvm::StoreInst>(I) &&
205 I.getOperand(0) == ThisPtr.getPointer();
206 });
207 assert(ThisStore != EntryBB->end() &&
208 "Store of this should be in entry block?");
Eli Friedman49a94b12011-05-06 17:27:27 +0000209 // Adjust "this", if necessary.
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000210 Builder.SetInsertPoint(&*ThisStore);
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000211 llvm::Value *AdjustedThisPtr =
212 CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
Reid Kleckner28328c32019-09-06 22:55:26 +0000213 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
214 ThisStore->getOperand(0)->getType());
Eli Friedman49a94b12011-05-06 17:27:27 +0000215 ThisStore->setOperand(0, AdjustedThisPtr);
216
217 if (!Thunk.Return.isEmpty()) {
218 // Fix up the returned value, if necessary.
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000219 for (llvm::BasicBlock &BB : *Fn) {
220 llvm::Instruction *T = BB.getTerminator();
Eli Friedman49a94b12011-05-06 17:27:27 +0000221 if (isa<llvm::ReturnInst>(T)) {
222 RValue RV = RValue::get(T->getOperand(0));
223 T->eraseFromParent();
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000224 Builder.SetInsertPoint(&BB);
Eli Friedman49a94b12011-05-06 17:27:27 +0000225 RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
226 Builder.CreateRet(RV.getScalarVal());
227 break;
228 }
229 }
230 }
Peter Collingbournee286b0e2015-06-30 22:08:44 +0000231
232 return Fn;
Eli Friedman49a94b12011-05-06 17:27:27 +0000233}
234
Hans Wennborg88497d62013-11-15 17:24:45 +0000235void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000236 const CGFunctionInfo &FnInfo,
237 bool IsUnprototyped) {
Hans Wennborg88497d62013-11-15 17:24:45 +0000238 assert(!CurGD.getDecl() && "CurGD was already set!");
239 CurGD = GD;
Reid Kleckner19819442014-07-25 21:39:46 +0000240 CurFuncIsThunk = true;
Hans Wennborg88497d62013-11-15 17:24:45 +0000241
242 // Build FunctionArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000243 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Brian Gesiak5488ab42019-01-11 01:54:53 +0000244 QualType ThisType = MD->getThisType();
Reid Kleckner54a33d72018-04-18 23:21:32 +0000245 QualType ResultType;
246 if (IsUnprototyped)
247 ResultType = CGM.getContext().VoidTy;
248 else if (CGM.getCXXABI().HasThisReturn(GD))
249 ResultType = ThisType;
250 else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
251 ResultType = CGM.getContext().VoidPtrTy;
252 else
Simon Pilgrim5e0a0b72019-10-01 22:02:46 +0000253 ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000254 FunctionArgList FunctionArgs;
255
Anders Carlssonbad991d2010-03-24 00:39:18 +0000256 // Create the implicit 'this' parameter declaration.
Reid Kleckner89077a12013-12-17 19:46:40 +0000257 CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000258
Reid Kleckner399d96e2018-04-02 20:20:33 +0000259 // Add the rest of the parameters, if we have a prototype to work with.
260 if (!IsUnprototyped) {
261 FunctionArgs.append(MD->param_begin(), MD->param_end());
Alexey Samsonov9b502e52012-10-25 10:18:50 +0000262
Reid Kleckner399d96e2018-04-02 20:20:33 +0000263 if (isa<CXXDestructorDecl>(MD))
264 CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
265 FunctionArgs);
266 }
Reid Kleckner89077a12013-12-17 19:46:40 +0000267
Hans Wennborg88497d62013-11-15 17:24:45 +0000268 // Start defining the function.
Adrian Prantldb763572016-11-09 21:43:51 +0000269 auto NL = ApplyDebugLocation::CreateEmpty(*this);
John McCalla738c252011-03-09 04:27:21 +0000270 StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
Adrian Prantldb763572016-11-09 21:43:51 +0000271 MD->getLocation());
272 // Create a scope with an artificial location for the body of this function.
273 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000274
Hans Wennborg88497d62013-11-15 17:24:45 +0000275 // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
John McCall5d865c322010-08-31 07:33:07 +0000276 CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
Eli Friedman9fbeba02012-02-11 02:57:39 +0000277 CXXThisValue = CXXABIThisValue;
John McCall7f416cc2015-09-08 08:05:57 +0000278 CurCodeDecl = MD;
279 CurFuncDecl = MD;
280}
281
282void CodeGenFunction::FinishThunk() {
283 // Clear these to restore the invariants expected by
284 // StartFunction/FinishFunction.
285 CurCodeDecl = nullptr;
286 CurFuncDecl = nullptr;
287
288 FinishFunction();
Hans Wennborg88497d62013-11-15 17:24:45 +0000289}
John McCall5d865c322010-08-31 07:33:07 +0000290
James Y Knight76f78742019-02-05 19:17:50 +0000291void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000292 const ThunkInfo *Thunk,
293 bool IsUnprototyped) {
Hans Wennborg88497d62013-11-15 17:24:45 +0000294 assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
295 "Please use a new CGF for this thunk");
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000296 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
Timur Iskhodzhanov02014322013-10-30 11:55:43 +0000297
Hans Wennborg88497d62013-11-15 17:24:45 +0000298 // Adjust the 'this' pointer if necessary
John McCall7f416cc2015-09-08 08:05:57 +0000299 llvm::Value *AdjustedThisPtr =
300 Thunk ? CGM.getCXXABI().performThisAdjustment(
301 *this, LoadCXXThisAddress(), Thunk->This)
302 : LoadCXXThis();
Hans Wennborg88497d62013-11-15 17:24:45 +0000303
Reid Kleckner28328c32019-09-06 22:55:26 +0000304 // If perfect forwarding is required a variadic method, a method using
305 // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
306 // thunk requires a return adjustment, since that is impossible with musttail.
307 if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000308 if (Thunk && !Thunk->Return.isEmpty()) {
Reid Kleckner399d96e2018-04-02 20:20:33 +0000309 if (IsUnprototyped)
310 CGM.ErrorUnsupported(
311 MD, "return-adjusting thunk with incomplete parameter type");
Reid Kleckner28328c32019-09-06 22:55:26 +0000312 else if (CurFnInfo->isVariadic())
313 llvm_unreachable("shouldn't try to emit musttail return-adjusting "
314 "thunks for variadic functions");
Reid Kleckner399d96e2018-04-02 20:20:33 +0000315 else
316 CGM.ErrorUnsupported(
317 MD, "non-trivial argument copy for return-adjusting thunk");
Reid Klecknerab2090d2014-07-26 01:34:32 +0000318 }
James Y Knight76f78742019-02-05 19:17:50 +0000319 EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000320 return;
321 }
322
Hans Wennborg88497d62013-11-15 17:24:45 +0000323 // Start building CallArgs.
Anders Carlssonbad991d2010-03-24 00:39:18 +0000324 CallArgList CallArgs;
Brian Gesiak5488ab42019-01-11 01:54:53 +0000325 QualType ThisType = MD->getThisType();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000326 CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000327
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000328 if (isa<CXXDestructorDecl>(MD))
Reid Kleckner3f76ac72014-07-26 01:30:05 +0000329 CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000330
Benjamin Kramerd12317e2017-02-23 22:47:56 +0000331#ifndef NDEBUG
George Burgess IVd0a9e802017-02-23 22:07:35 +0000332 unsigned PrefixArgs = CallArgs.size() - 1;
Benjamin Kramerd12317e2017-02-23 22:47:56 +0000333#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000334 // Add the rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +0000335 for (const ParmVarDecl *PD : MD->parameters())
Adrian Prantldb763572016-11-09 21:43:51 +0000336 EmitDelegateCallArg(CallArgs, PD, SourceLocation());
Anders Carlssonbad991d2010-03-24 00:39:18 +0000337
Hans Wennborg88497d62013-11-15 17:24:45 +0000338 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Anders Carlssonbad991d2010-03-24 00:39:18 +0000339
John McCalla738c252011-03-09 04:27:21 +0000340#ifndef NDEBUG
George Burgess IV419996c2016-06-16 23:06:04 +0000341 const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
James Y Knight916db652019-02-02 01:48:23 +0000342 CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
Hans Wennborg88497d62013-11-15 17:24:45 +0000343 assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
344 CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
345 CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
John McCall8dda7b22012-07-07 06:41:13 +0000346 assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
347 similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
Hans Wennborg88497d62013-11-15 17:24:45 +0000348 CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
349 assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
350 for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
John McCall5fe00962011-03-09 07:12:35 +0000351 assert(similar(CallFnInfo.arg_begin()[i].info,
352 CallFnInfo.arg_begin()[i].type,
Hans Wennborg88497d62013-11-15 17:24:45 +0000353 CurFnInfo->arg_begin()[i].info,
354 CurFnInfo->arg_begin()[i].type));
John McCalla738c252011-03-09 04:27:21 +0000355#endif
Hans Wennborg88497d62013-11-15 17:24:45 +0000356
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000357 // Determine whether we have a return value slot to use.
David Majnemer0c0b6d92014-10-31 20:09:12 +0000358 QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
359 ? ThisType
360 : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
361 ? CGM.getContext().VoidPtrTy
362 : FPT->getReturnType();
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000363 ReturnValueSlot Slot;
364 if (!ResultType->isVoidType() &&
Hans Wennborg86aba5e2018-12-07 08:17:26 +0000365 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect)
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000366 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000367
Anders Carlssonbad991d2010-03-24 00:39:18 +0000368 // Now emit our call.
James Y Knight3933add2019-01-30 02:54:28 +0000369 llvm::CallBase *CallOrInvoke;
James Y Knight76f78742019-02-05 19:17:50 +0000370 RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
371 CallArgs, &CallOrInvoke);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000372
Hans Wennborg88497d62013-11-15 17:24:45 +0000373 // Consider return adjustment if we have ThunkInfo.
374 if (Thunk && !Thunk->Return.isEmpty())
375 RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
Michael Kuperstein819ad332015-08-06 11:57:15 +0000376 else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
377 Call->setTailCallKind(llvm::CallInst::TCK_Tail);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000378
Hans Wennborg88497d62013-11-15 17:24:45 +0000379 // Emit return.
Douglas Gregoraa2ac802010-05-20 05:54:35 +0000380 if (!ResultType->isVoidType() && Slot.isNull())
John McCallad7c5c12011-02-08 08:22:06 +0000381 CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000382
John McCallff755cd2012-07-31 00:33:55 +0000383 // Disable the final ARC autorelease.
384 AutoreleaseResult = false;
385
John McCall7f416cc2015-09-08 08:05:57 +0000386 FinishThunk();
Hans Wennborg88497d62013-11-15 17:24:45 +0000387}
388
Erich Keanede6480a32018-11-13 15:48:08 +0000389void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
Reid Klecknerab2090d2014-07-26 01:34:32 +0000390 llvm::Value *AdjustedThisPtr,
James Y Knight76f78742019-02-05 19:17:50 +0000391 llvm::FunctionCallee Callee) {
Reid Klecknerab2090d2014-07-26 01:34:32 +0000392 // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
393 // to translate AST arguments into LLVM IR arguments. For thunks, we know
394 // that the caller prototype more or less matches the callee prototype with
395 // the exception of 'this'.
396 SmallVector<llvm::Value *, 8> Args;
397 for (llvm::Argument &A : CurFn->args())
398 Args.push_back(&A);
399
400 // Set the adjusted 'this' pointer.
401 const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
402 if (ThisAI.isDirect()) {
403 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
404 int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
405 llvm::Type *ThisType = Args[ThisArgNo]->getType();
406 if (ThisType != AdjustedThisPtr->getType())
407 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
408 Args[ThisArgNo] = AdjustedThisPtr;
409 } else {
410 assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
John McCall7f416cc2015-09-08 08:05:57 +0000411 Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
412 llvm::Type *ThisType = ThisAddr.getElementType();
Reid Klecknerab2090d2014-07-26 01:34:32 +0000413 if (ThisType != AdjustedThisPtr->getType())
414 AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
415 Builder.CreateStore(AdjustedThisPtr, ThisAddr);
416 }
417
418 // Emit the musttail call manually. Even if the prologue pushed cleanups, we
419 // don't actually want to run them.
James Y Knight76f78742019-02-05 19:17:50 +0000420 llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000421 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
422
423 // Apply the standard set of call attributes.
424 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +0000425 llvm::AttributeList Attrs;
James Y Knight76f78742019-02-05 19:17:50 +0000426 CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
427 Attrs, CallingConv, /*AttrOnCallSite=*/true);
Reid Klecknerab2090d2014-07-26 01:34:32 +0000428 Call->setAttributes(Attrs);
429 Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
430
431 if (Call->getType()->isVoidTy())
432 Builder.CreateRetVoid();
433 else
434 Builder.CreateRet(Call);
435
436 // Finish the function to maintain CodeGenFunction invariants.
437 // FIXME: Don't emit unreachable code.
438 EmitBlock(createBasicBlock());
439 FinishFunction();
440}
441
Rafael Espindolad6e66942015-07-13 06:07:58 +0000442void CodeGenFunction::generateThunk(llvm::Function *Fn,
Reid Kleckner399d96e2018-04-02 20:20:33 +0000443 const CGFunctionInfo &FnInfo, GlobalDecl GD,
444 const ThunkInfo &Thunk,
445 bool IsUnprototyped) {
446 StartThunk(Fn, GD, FnInfo, IsUnprototyped);
Adrian Prantldb763572016-11-09 21:43:51 +0000447 // Create a scope with an artificial location for the body of this function.
448 auto AL = ApplyDebugLocation::CreateArtificial(*this);
Hans Wennborg88497d62013-11-15 17:24:45 +0000449
Reid Kleckner399d96e2018-04-02 20:20:33 +0000450 // Get our callee. Use a placeholder type if this method is unprototyped so
451 // that CodeGenModule doesn't try to set attributes.
452 llvm::Type *Ty;
453 if (IsUnprototyped)
454 Ty = llvm::StructType::get(getLLVMContext());
455 else
456 Ty = CGM.getTypes().GetFunctionType(FnInfo);
457
John McCallb92ab1a2016-10-26 23:46:34 +0000458 llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
Hans Wennborg88497d62013-11-15 17:24:45 +0000459
Reid Kleckner399d96e2018-04-02 20:20:33 +0000460 // Fix up the function type for an unprototyped musttail call.
461 if (IsUnprototyped)
462 Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
463
Hans Wennborg88497d62013-11-15 17:24:45 +0000464 // Make the call and return the result.
James Y Knight76f78742019-02-05 19:17:50 +0000465 EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
466 &Thunk, IsUnprototyped);
Anders Carlssonbad991d2010-03-24 00:39:18 +0000467}
468
Reid Kleckner399d96e2018-04-02 20:20:33 +0000469static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
470 bool IsUnprototyped, bool ForVTable) {
471 // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
472 // provide thunks for us.
473 if (CGM.getTarget().getCXXABI().isMicrosoft())
474 return true;
John McCalla738c252011-03-09 04:27:21 +0000475
Reid Kleckner399d96e2018-04-02 20:20:33 +0000476 // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
477 // definitions of the main method. Therefore, emitting thunks with the vtable
478 // is purely an optimization. Emit the thunk if optimizations are enabled and
479 // all of the parameter types are complete.
480 if (ForVTable)
481 return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000482
Reid Kleckner399d96e2018-04-02 20:20:33 +0000483 // Always emit thunks along with the method definition.
484 return true;
485}
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000486
Reid Kleckner399d96e2018-04-02 20:20:33 +0000487llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
488 const ThunkInfo &TI,
489 bool ForVTable) {
490 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
Rafael Espindolabf6e67f2014-05-08 15:44:45 +0000491
Reid Kleckner399d96e2018-04-02 20:20:33 +0000492 // First, get a declaration. Compute the mangled name. Don't worry about
493 // getting the function prototype right, since we may only need this
494 // declaration to fill in a vtable slot.
495 SmallString<256> Name;
496 MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
497 llvm::raw_svector_ostream Out(Name);
498 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
499 MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
500 else
501 MCtx.mangleThunk(MD, TI, Out);
502 llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
503 llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
504
505 // If we don't need to emit a definition, return this declaration as is.
506 bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
507 MD->getType()->castAs<FunctionType>());
508 if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
509 return Thunk;
510
511 // Arrange a function prototype appropriate for a function definition. In some
512 // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
513 const CGFunctionInfo &FnInfo =
514 IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
515 : CGM.getTypes().arrangeGlobalDeclaration(GD);
516 llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
517
518 // If the type of the underlying GlobalValue is wrong, we'll have to replace
519 // it. It should be a declaration.
520 llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
521 if (ThunkFn->getFunctionType() != ThunkFnTy) {
522 llvm::GlobalValue *OldThunkFn = ThunkFn;
523
524 assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
Anders Carlsson55e89f82010-03-23 18:18:41 +0000525
526 // Remove the name from the old thunk function and get a new thunk.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000527 OldThunkFn->setName(StringRef());
Reid Kleckner399d96e2018-04-02 20:20:33 +0000528 ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
529 Name.str(), &CGM.getModule());
530 CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000531
Anders Carlsson55e89f82010-03-23 18:18:41 +0000532 // If needed, replace the old thunk with a bitcast.
533 if (!OldThunkFn->use_empty()) {
534 llvm::Constant *NewPtrForOldDecl =
Reid Kleckner399d96e2018-04-02 20:20:33 +0000535 llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
Anders Carlsson55e89f82010-03-23 18:18:41 +0000536 OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
537 }
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000538
Anders Carlsson55e89f82010-03-23 18:18:41 +0000539 // Remove the old thunk.
540 OldThunkFn->eraseFromParent();
541 }
Anders Carlssonbad991d2010-03-24 00:39:18 +0000542
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000543 bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
544 bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
Anders Carlsson8b021832011-02-06 18:31:40 +0000545
546 if (!ThunkFn->isDeclaration()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +0000547 if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
Anders Carlsson8b021832011-02-06 18:31:40 +0000548 // There is already a thunk emitted for this function, do nothing.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000549 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000550 }
551
Reid Kleckner399d96e2018-04-02 20:20:33 +0000552 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
553 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000554 }
555
Reid Kleckner399d96e2018-04-02 20:20:33 +0000556 // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
557 // that the return type is meaningless. These thunks can be used to call
558 // functions with differing return types, and the caller is required to cast
559 // the prototype appropriately to extract the correct value.
560 if (IsUnprototyped)
561 ThunkFn->addFnAttr("thunk");
562
Rafael Espindola86792432012-09-21 20:39:32 +0000563 CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
564
Reid Kleckner28328c32019-09-06 22:55:26 +0000565 // Thunks for variadic methods are special because in general variadic
566 // arguments cannot be perferctly forwarded. In the general case, clang
567 // implements such thunks by cloning the original function body. However, for
568 // thunks with no return adjustment on targets that support musttail, we can
569 // use musttail to perfectly forward the variadic arguments.
570 bool ShouldCloneVarArgs = false;
Reid Kleckner399d96e2018-04-02 20:20:33 +0000571 if (!IsUnprototyped && ThunkFn->isVarArg()) {
Reid Kleckner28328c32019-09-06 22:55:26 +0000572 ShouldCloneVarArgs = true;
573 if (TI.Return.isEmpty()) {
574 switch (CGM.getTriple().getArch()) {
575 case llvm::Triple::x86_64:
576 case llvm::Triple::x86:
577 case llvm::Triple::aarch64:
578 ShouldCloneVarArgs = false;
579 break;
580 default:
581 break;
582 }
583 }
584 }
585
586 if (ShouldCloneVarArgs) {
Peter Collingbourne45a24012015-06-30 19:07:26 +0000587 if (UseAvailableExternallyLinkage)
Reid Kleckner399d96e2018-04-02 20:20:33 +0000588 return ThunkFn;
Reid Kleckner28328c32019-09-06 22:55:26 +0000589 ThunkFn =
590 CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
Eli Friedman49a94b12011-05-06 17:27:27 +0000591 } else {
592 // Normal thunk body generation.
Reid Kleckner399d96e2018-04-02 20:20:33 +0000593 CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
Eli Friedman49a94b12011-05-06 17:27:27 +0000594 }
Peter Collingbourne45a24012015-06-30 19:07:26 +0000595
Reid Kleckner399d96e2018-04-02 20:20:33 +0000596 setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
597 return ThunkFn;
Anders Carlsson8b021832011-02-06 18:31:40 +0000598}
599
Reid Kleckner399d96e2018-04-02 20:20:33 +0000600void CodeGenVTables::EmitThunks(GlobalDecl GD) {
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000601 const CXXMethodDecl *MD =
Anders Carlsson5c5abad2010-03-23 16:36:50 +0000602 cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
603
604 // We don't need to generate thunks for the base destructor.
605 if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
606 return;
607
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000608 const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
609 VTContext->getThunkInfo(GD);
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +0000610
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +0000611 if (!ThunkInfoVector)
Anders Carlssone90954d2010-03-24 16:42:11 +0000612 return;
Anders Carlssone90954d2010-03-24 16:42:11 +0000613
Yaron Kerenede60302015-08-01 19:11:36 +0000614 for (const ThunkInfo& Thunk : *ThunkInfoVector)
Reid Kleckner399d96e2018-04-02 20:20:33 +0000615 maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
Anders Carlsson917229c2010-03-23 04:59:02 +0000616}
617
John McCall9c6cb762016-11-28 22:18:33 +0000618void CodeGenVTables::addVTableComponent(
619 ConstantArrayBuilder &builder, const VTableLayout &layout,
620 unsigned idx, llvm::Constant *rtti, unsigned &nextVTableThunkIndex) {
621 auto &component = layout.vtable_components()[idx];
Anders Carlssona4147142010-03-25 15:26:28 +0000622
John McCall9c6cb762016-11-28 22:18:33 +0000623 auto addOffsetConstant = [&](CharUnits offset) {
624 builder.add(llvm::ConstantExpr::getIntToPtr(
625 llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
626 CGM.Int8PtrTy));
Peter Collingbournee53683f2016-09-08 01:14:39 +0000627 };
Anders Carlssona5736bd2010-03-25 16:49:53 +0000628
John McCall9c6cb762016-11-28 22:18:33 +0000629 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000630 case VTableComponent::CK_VCallOffset:
John McCall9c6cb762016-11-28 22:18:33 +0000631 return addOffsetConstant(component.getVCallOffset());
Craig Topper8a13c412014-05-21 05:09:00 +0000632
Peter Collingbournee53683f2016-09-08 01:14:39 +0000633 case VTableComponent::CK_VBaseOffset:
John McCall9c6cb762016-11-28 22:18:33 +0000634 return addOffsetConstant(component.getVBaseOffset());
Anders Carlssoncb6207f2010-03-29 05:40:50 +0000635
Peter Collingbournee53683f2016-09-08 01:14:39 +0000636 case VTableComponent::CK_OffsetToTop:
John McCall9c6cb762016-11-28 22:18:33 +0000637 return addOffsetConstant(component.getOffsetToTop());
Anders Carlssona5736bd2010-03-25 16:49:53 +0000638
Peter Collingbournee53683f2016-09-08 01:14:39 +0000639 case VTableComponent::CK_RTTI:
John McCall9c6cb762016-11-28 22:18:33 +0000640 return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
Anders Carlssona5736bd2010-03-25 16:49:53 +0000641
Peter Collingbournee53683f2016-09-08 01:14:39 +0000642 case VTableComponent::CK_FunctionPointer:
643 case VTableComponent::CK_CompleteDtorPointer:
644 case VTableComponent::CK_DeletingDtorPointer: {
645 GlobalDecl GD;
646
647 // Get the right global decl.
John McCall9c6cb762016-11-28 22:18:33 +0000648 switch (component.getKind()) {
Peter Collingbournee53683f2016-09-08 01:14:39 +0000649 default:
650 llvm_unreachable("Unexpected vtable component kind");
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000651 case VTableComponent::CK_FunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000652 GD = component.getFunctionDecl();
Peter Collingbournee53683f2016-09-08 01:14:39 +0000653 break;
Anders Carlssonbe1b9cb2010-04-10 19:13:06 +0000654 case VTableComponent::CK_CompleteDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000655 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Complete);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000656 break;
657 case VTableComponent::CK_DeletingDtorPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000658 GD = GlobalDecl(component.getDestructorDecl(), Dtor_Deleting);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000659 break;
660 }
661
Peter Collingbournee53683f2016-09-08 01:14:39 +0000662 if (CGM.getLangOpts().CUDA) {
663 // Emit NULL for methods we can't codegen on this
664 // side. Otherwise we'd end up with vtable with unresolved
665 // references.
666 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
667 // OK on device side: functions w/ __device__ attribute
668 // OK on host side: anything except __device__-only functions.
669 bool CanEmitMethod =
670 CGM.getLangOpts().CUDAIsDevice
671 ? MD->hasAttr<CUDADeviceAttr>()
672 : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
673 if (!CanEmitMethod)
John McCall9c6cb762016-11-28 22:18:33 +0000674 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000675 // Method is acceptable, continue processing as usual.
676 }
677
John McCall9c6cb762016-11-28 22:18:33 +0000678 auto getSpecialVirtualFn = [&](StringRef name) {
679 llvm::FunctionType *fnTy =
680 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
James Y Knight9871db02019-02-05 16:42:33 +0000681 llvm::Constant *fn = cast<llvm::Constant>(
682 CGM.CreateRuntimeFunction(fnTy, name).getCallee());
John McCall9c6cb762016-11-28 22:18:33 +0000683 if (auto f = dyn_cast<llvm::Function>(fn))
684 f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
685 return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
Anders Carlssona5736bd2010-03-25 16:49:53 +0000686 };
Peter Collingbournee53683f2016-09-08 01:14:39 +0000687
John McCall9c6cb762016-11-28 22:18:33 +0000688 llvm::Constant *fnPtr;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000689
John McCall9c6cb762016-11-28 22:18:33 +0000690 // Pure virtual member functions.
691 if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
692 if (!PureVirtualFn)
693 PureVirtualFn =
694 getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
695 fnPtr = PureVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000696
John McCall9c6cb762016-11-28 22:18:33 +0000697 // Deleted virtual member functions.
698 } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
699 if (!DeletedVirtualFn)
700 DeletedVirtualFn =
701 getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
702 fnPtr = DeletedVirtualFn;
Peter Collingbournee53683f2016-09-08 01:14:39 +0000703
John McCall9c6cb762016-11-28 22:18:33 +0000704 // Thunks.
705 } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
706 layout.vtable_thunks()[nextVTableThunkIndex].first == idx) {
707 auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
708
John McCall9c6cb762016-11-28 22:18:33 +0000709 nextVTableThunkIndex++;
Reid Kleckner399d96e2018-04-02 20:20:33 +0000710 fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
John McCall9c6cb762016-11-28 22:18:33 +0000711
712 // Otherwise we can use the method definition directly.
713 } else {
714 llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
715 fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000716 }
717
John McCall9c6cb762016-11-28 22:18:33 +0000718 fnPtr = llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy);
719 builder.add(fnPtr);
720 return;
Anders Carlssona4147142010-03-25 15:26:28 +0000721 }
Peter Collingbournee53683f2016-09-08 01:14:39 +0000722
723 case VTableComponent::CK_UnusedFunctionPointer:
John McCall9c6cb762016-11-28 22:18:33 +0000724 return builder.addNullPointer(CGM.Int8PtrTy);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000725 }
Simon Pilgrim4acc49e2016-09-08 11:03:41 +0000726
727 llvm_unreachable("Unexpected vtable component kind");
Peter Collingbournee53683f2016-09-08 01:14:39 +0000728}
729
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000730llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
731 SmallVector<llvm::Type *, 4> tys;
732 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
733 tys.push_back(llvm::ArrayType::get(CGM.Int8PtrTy, layout.getVTableSize(i)));
734 }
735
736 return llvm::StructType::get(CGM.getLLVMContext(), tys);
737}
738
739void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
John McCall9c6cb762016-11-28 22:18:33 +0000740 const VTableLayout &layout,
741 llvm::Constant *rtti) {
742 unsigned nextVTableThunkIndex = 0;
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000743 for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i) {
744 auto vtableElem = builder.beginArray(CGM.Int8PtrTy);
745 size_t thisIndex = layout.getVTableOffset(i);
746 size_t nextIndex = thisIndex + layout.getVTableSize(i);
747 for (unsigned i = thisIndex; i != nextIndex; ++i) {
748 addVTableComponent(vtableElem, layout, i, rtti, nextVTableThunkIndex);
749 }
750 vtableElem.finishAndAddTo(builder);
Peter Collingbournee53683f2016-09-08 01:14:39 +0000751 }
Anders Carlssona4147142010-03-25 15:26:28 +0000752}
753
Anders Carlsson0534b022010-03-25 00:35:49 +0000754llvm::GlobalVariable *
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000755CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
756 const BaseSubobject &Base,
757 bool BaseIsVirtual,
John McCall358d0562011-03-27 09:00:25 +0000758 llvm::GlobalVariable::LinkageTypes Linkage,
Anders Carlssona208b392010-03-26 03:56:54 +0000759 VTableAddressPointsMapTy& AddressPoints) {
David Blaikied89b99d2013-08-22 15:23:05 +0000760 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
761 DI->completeClassData(Base.getBase());
762
Ahmed Charlesb8984322014-03-07 20:03:18 +0000763 std::unique_ptr<VTableLayout> VTLayout(
Reid Klecknerb60a3d52013-12-20 23:58:52 +0000764 getItaniumVTableContext().createConstructionVTableLayout(
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000765 Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
Anders Carlssona4147142010-03-25 15:26:28 +0000766
Anders Carlssona5736bd2010-03-25 16:49:53 +0000767 // Add the address points.
Peter Collingbourne1c593c62011-09-26 01:57:04 +0000768 AddressPoints = VTLayout->getAddressPoints();
Anders Carlssona4147142010-03-25 15:26:28 +0000769
770 // Get the mangled construction vtable name.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000771 SmallString<256> OutName;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000772 llvm::raw_svector_ostream Out(OutName);
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000773 cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
774 .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
775 Base.getBase(), Out);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000776 StringRef Name = OutName.str();
Anders Carlssona4147142010-03-25 15:26:28 +0000777
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000778 llvm::Type *VTType = getVTableType(*VTLayout);
Anders Carlssona4147142010-03-25 15:26:28 +0000779
Richard Smith65fd2a42013-02-16 00:51:21 +0000780 // Construction vtable symbols are not part of the Itanium ABI, so we cannot
781 // guarantee that they actually will be available externally. Instead, when
782 // emitting an available_externally VTT, we provide references to an internal
783 // linkage construction vtable. The ABI only requires complete-object vtables
784 // to be the same for all instances of a type, not construction vtables.
785 if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
786 Linkage = llvm::GlobalVariable::InternalLinkage;
787
David Greenbe0c5b62018-09-12 14:09:06 +0000788 unsigned Align = CGM.getDataLayout().getABITypeAlignment(VTType);
789
Anders Carlssona4147142010-03-25 15:26:28 +0000790 // Create the variable that will hold the construction vtable.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000791 llvm::GlobalVariable *VTable =
David Greenbe0c5b62018-09-12 14:09:06 +0000792 CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
John McCall358d0562011-03-27 09:00:25 +0000793
794 // V-tables are always unnamed_addr.
Peter Collingbournebcf909d2016-06-14 21:02:05 +0000795 VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Anders Carlssona4147142010-03-25 15:26:28 +0000796
David Majnemerd905da42014-07-01 20:30:31 +0000797 llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
798 CGM.getContext().getTagDeclType(Base.getBase()));
799
Anders Carlssona4147142010-03-25 15:26:28 +0000800 // Create and set the initializer.
John McCall9c6cb762016-11-28 22:18:33 +0000801 ConstantInitBuilder builder(CGM);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000802 auto components = builder.beginStruct();
John McCall9c6cb762016-11-28 22:18:33 +0000803 createVTableInitializer(components, *VTLayout, RTTI);
804 components.finishAndSetAsInitializer(VTable);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000805
Petr Hosek7c895212019-02-11 20:13:42 +0000806 // Set properties only after the initializer has been set to ensure that the
807 // GV is treated as definition and not declaration.
808 assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
809 CGM.setGVProperties(VTable, RD);
810
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000811 CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000812
Anders Carlsson0534b022010-03-25 00:35:49 +0000813 return VTable;
814}
815
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000816static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
817 const CXXRecordDecl *RD) {
818 return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000819 CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000820}
821
Eric Christopherd160c502016-01-29 01:35:53 +0000822/// Compute the required linkage of the vtable for the given class.
John McCall6bd2a892013-01-25 22:31:03 +0000823///
824/// Note that we only call this at the end of the translation unit.
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000825llvm::GlobalVariable::LinkageTypes
John McCall6bd2a892013-01-25 22:31:03 +0000826CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +0000827 if (!RD->isExternallyVisible())
John McCall6bd2a892013-01-25 22:31:03 +0000828 return llvm::GlobalVariable::InternalLinkage;
829
830 // We're at the end of the translation unit, so the current key
831 // function is fully correct.
Hans Wennborgec53c292014-10-23 22:40:46 +0000832 const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
833 if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
John McCall6bd2a892013-01-25 22:31:03 +0000834 // If this class has a key function, use that to determine the
835 // linkage of the vtable.
Craig Topper8a13c412014-05-21 05:09:00 +0000836 const FunctionDecl *def = nullptr;
John McCall6bd2a892013-01-25 22:31:03 +0000837 if (keyFunction->hasBody(def))
838 keyFunction = cast<CXXMethodDecl>(def);
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000839
John McCall6bd2a892013-01-25 22:31:03 +0000840 switch (keyFunction->getTemplateSpecializationKind()) {
841 case TSK_Undeclared:
842 case TSK_ExplicitSpecialization:
David Blaikieb11c8732017-01-30 06:36:08 +0000843 assert((def || CodeGenOpts.OptimizationLevel > 0 ||
844 CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
845 "Shouldn't query vtable linkage without key function, "
846 "optimizations, or debug info");
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000847 if (!def && CodeGenOpts.OptimizationLevel > 0)
848 return llvm::GlobalVariable::AvailableExternallyLinkage;
849
John McCall6bd2a892013-01-25 22:31:03 +0000850 if (keyFunction->isInlined())
851 return !Context.getLangOpts().AppleKext ?
852 llvm::GlobalVariable::LinkOnceODRLinkage :
853 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000854
John McCall6bd2a892013-01-25 22:31:03 +0000855 return llvm::GlobalVariable::ExternalLinkage;
Yaron Keren07d4496a2015-07-02 14:44:35 +0000856
John McCall6bd2a892013-01-25 22:31:03 +0000857 case TSK_ImplicitInstantiation:
858 return !Context.getLangOpts().AppleKext ?
859 llvm::GlobalVariable::LinkOnceODRLinkage :
860 llvm::Function::InternalLinkage;
861
862 case TSK_ExplicitInstantiationDefinition:
863 return !Context.getLangOpts().AppleKext ?
864 llvm::GlobalVariable::WeakODRLinkage :
865 llvm::Function::InternalLinkage;
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000866
John McCall6bd2a892013-01-25 22:31:03 +0000867 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolaee6aa0c2013-09-03 21:05:13 +0000868 llvm_unreachable("Should not have been asked to emit this");
John McCall6bd2a892013-01-25 22:31:03 +0000869 }
870 }
871
872 // -fapple-kext mode does not support weak linkage, so we must use
873 // internal linkage.
874 if (Context.getLangOpts().AppleKext)
875 return llvm::Function::InternalLinkage;
Hans Wennborg853ae942014-05-30 16:59:42 +0000876
877 llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
878 llvm::GlobalValue::LinkOnceODRLinkage;
879 llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
880 llvm::GlobalValue::WeakODRLinkage;
881 if (RD->hasAttr<DLLExportAttr>()) {
882 // Cannot discard exported vtables.
883 DiscardableODRLinkage = NonDiscardableODRLinkage;
884 } else if (RD->hasAttr<DLLImportAttr>()) {
885 // Imported vtables are available externally.
886 DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
887 NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
888 }
889
John McCall6bd2a892013-01-25 22:31:03 +0000890 switch (RD->getTemplateSpecializationKind()) {
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000891 case TSK_Undeclared:
892 case TSK_ExplicitSpecialization:
893 case TSK_ImplicitInstantiation:
894 return DiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000895
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000896 case TSK_ExplicitInstantiationDeclaration:
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000897 // Explicit instantiations in MSVC do not provide vtables, so we must emit
898 // our own.
899 if (getTarget().getCXXABI().isMicrosoft())
900 return DiscardableODRLinkage;
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000901 return shouldEmitAvailableExternallyVTable(*this, RD)
902 ? llvm::GlobalVariable::AvailableExternallyLinkage
903 : llvm::GlobalVariable::ExternalLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000904
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000905 case TSK_ExplicitInstantiationDefinition:
906 return NonDiscardableODRLinkage;
John McCall6bd2a892013-01-25 22:31:03 +0000907 }
908
909 llvm_unreachable("Invalid TemplateSpecializationKind!");
910}
911
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000912/// This is a callback from Sema to tell us that a particular vtable is
Nico Weberb6a5d052015-01-15 04:07:35 +0000913/// required to be emitted in this translation unit.
John McCall6bd2a892013-01-25 22:31:03 +0000914///
Nico Weberb6a5d052015-01-15 04:07:35 +0000915/// This is only called for vtables that _must_ be emitted (mainly due to key
916/// functions). For weak vtables, CodeGen tracks when they are needed and
917/// emits them as-needed.
918void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
John McCall6bd2a892013-01-25 22:31:03 +0000919 VTables.GenerateClassData(theClass);
920}
921
Simon Pilgrim48c32b12016-09-08 09:59:58 +0000922void
John McCall6bd2a892013-01-25 22:31:03 +0000923CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
David Blaikied89b99d2013-08-22 15:23:05 +0000924 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
925 DI->completeClassData(RD);
926
Reid Kleckner7810af02013-06-19 15:20:38 +0000927 if (RD->getNumVBases())
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000928 CGM.getCXXABI().emitVirtualInheritanceTables(RD);
Douglas Gregoreadd3ca2010-04-08 15:52:03 +0000929
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000930 CGM.getCXXABI().emitVTableDefinitions(*this, RD);
Anders Carlssona627ac7e2010-03-29 03:38:52 +0000931}
John McCall6bd2a892013-01-25 22:31:03 +0000932
933/// At this point in the translation unit, does it appear that can we
934/// rely on the vtable being defined elsewhere in the program?
935///
936/// The response is really only definitive when called at the end of
937/// the translation unit.
938///
939/// The only semantic restriction here is that the object file should
Eric Christopherd160c502016-01-29 01:35:53 +0000940/// not contain a vtable definition when that vtable is defined
John McCall6bd2a892013-01-25 22:31:03 +0000941/// strongly elsewhere. Otherwise, we'd just like to avoid emitting
Eric Christopherd160c502016-01-29 01:35:53 +0000942/// vtables when unnecessary.
John McCall6bd2a892013-01-25 22:31:03 +0000943bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
Alp Tokerd4733632013-12-05 04:47:09 +0000944 assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
John McCall6bd2a892013-01-25 22:31:03 +0000945
Reid Klecknerad1e22b2016-06-29 18:29:21 +0000946 // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
947 // emit them even if there is an explicit template instantiation.
948 if (CGM.getTarget().getCXXABI().isMicrosoft())
David Majnemer2d8b2002016-02-11 17:49:28 +0000949 return false;
950
John McCall6bd2a892013-01-25 22:31:03 +0000951 // If we have an explicit instantiation declaration (and not a
Eric Christopherd160c502016-01-29 01:35:53 +0000952 // definition), the vtable is defined elsewhere.
John McCall6bd2a892013-01-25 22:31:03 +0000953 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
954 if (TSK == TSK_ExplicitInstantiationDeclaration)
955 return true;
956
957 // Otherwise, if the class is an instantiated template, the
Eric Christopherd160c502016-01-29 01:35:53 +0000958 // vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000959 if (TSK == TSK_ImplicitInstantiation ||
960 TSK == TSK_ExplicitInstantiationDefinition)
961 return false;
962
963 // Otherwise, if the class doesn't have a key function (possibly
Eric Christopherd160c502016-01-29 01:35:53 +0000964 // anymore), the vtable must be defined here.
John McCall6bd2a892013-01-25 22:31:03 +0000965 const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
966 if (!keyFunction)
967 return false;
968
969 // Otherwise, if we don't have a definition of the key function, the
Eric Christopherd160c502016-01-29 01:35:53 +0000970 // vtable must be defined somewhere else.
John McCall6bd2a892013-01-25 22:31:03 +0000971 return !keyFunction->hasBody();
972}
973
974/// Given that we're currently at the end of the translation unit, and
Eric Christopherd160c502016-01-29 01:35:53 +0000975/// we've emitted a reference to the vtable for this class, should
976/// we define that vtable?
John McCall6bd2a892013-01-25 22:31:03 +0000977static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
978 const CXXRecordDecl *RD) {
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000979 // If vtable is internal then it has to be done.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000980 if (!CGM.getVTables().isVTableExternal(RD))
981 return true;
982
Piotr Padlewskid679d7e2015-09-15 00:37:06 +0000983 // If it's external then maybe we will need it as available_externally.
Piotr Padlewskia68a7872015-07-24 04:04:49 +0000984 return shouldEmitAvailableExternallyVTable(CGM, RD);
John McCall6bd2a892013-01-25 22:31:03 +0000985}
986
987/// Given that at some point we emitted a reference to one or more
Eric Christopherd160c502016-01-29 01:35:53 +0000988/// vtables, and that we are now at the end of the translation unit,
John McCall6bd2a892013-01-25 22:31:03 +0000989/// decide whether we should emit them.
990void CodeGenModule::EmitDeferredVTables() {
991#ifndef NDEBUG
992 // Remember the size of DeferredVTables, because we're going to assume
993 // that this entire operation doesn't modify it.
994 size_t savedSize = DeferredVTables.size();
995#endif
996
Piotr Padlewski44b4ce82015-07-28 16:10:58 +0000997 for (const CXXRecordDecl *RD : DeferredVTables)
John McCall6bd2a892013-01-25 22:31:03 +0000998 if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
999 VTables.GenerateClassData(RD);
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001000 else if (shouldOpportunisticallyEmitVTables())
1001 OpportunisticVTables.push_back(RD);
John McCall6bd2a892013-01-25 22:31:03 +00001002
1003 assert(savedSize == DeferredVTables.size() &&
Eric Christopherd160c502016-01-29 01:35:53 +00001004 "deferred extra vtables during vtable emission?");
John McCall6bd2a892013-01-25 22:31:03 +00001005 DeferredVTables.clear();
1006}
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001007
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001008bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1009 LinkageInfo LV = RD->getLinkageAndVisibility();
1010 if (!isExternallyVisible(LV.getLinkage()))
1011 return true;
Peter Collingbourne6fccf952015-07-15 12:15:56 +00001012
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001013 if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
1014 return false;
Peter Collingbournefb532b92016-02-24 20:46:36 +00001015
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001016 if (getTriple().isOSBinFormatCOFF()) {
1017 if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1018 return false;
1019 } else {
1020 if (LV.getVisibility() != HiddenVisibility)
1021 return false;
1022 }
Peter Collingbournefb532b92016-02-24 20:46:36 +00001023
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001024 if (getCodeGenOpts().LTOVisibilityPublicStd) {
1025 const DeclContext *DC = RD;
1026 while (1) {
1027 auto *D = cast<Decl>(DC);
1028 DC = DC->getParent();
1029 if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1030 if (auto *ND = dyn_cast<NamespaceDecl>(D))
1031 if (const IdentifierInfo *II = ND->getIdentifier())
1032 if (II->isStr("std") || II->isStr("stdext"))
1033 return false;
1034 break;
1035 }
1036 }
1037 }
1038
1039 return true;
Peter Collingbournee5706442015-07-09 19:56:14 +00001040}
1041
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001042void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
1043 const VTableLayout &VTLayout) {
Peter Collingbourne1e1475a2017-01-18 23:55:27 +00001044 if (!getCodeGenOpts().LTOUnit)
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001045 return;
1046
Peter Collingbourne86d34a72015-06-17 19:08:05 +00001047 CharUnits PointerWidth =
1048 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001049
Peter Collingbournee44acad2018-06-26 02:15:47 +00001050 typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1051 std::vector<AddressPoint> AddressPoints;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00001052 for (auto &&AP : VTLayout.getAddressPoints())
Peter Collingbournee44acad2018-06-26 02:15:47 +00001053 AddressPoints.push_back(std::make_pair(
Peter Collingbourneac94ca52018-05-30 22:29:08 +00001054 AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1055 AP.second.AddressPointIndex));
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001056
Peter Collingbournee44acad2018-06-26 02:15:47 +00001057 // Sort the address points for determinism.
Fangrui Song55fab262018-09-26 22:16:28 +00001058 llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1059 const AddressPoint &AP2) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00001060 if (&AP1 == &AP2)
Peter Collingbourne47941902015-02-24 01:12:53 +00001061 return false;
1062
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001063 std::string S1;
1064 llvm::raw_string_ostream O1(S1);
1065 getCXXABI().getMangleContext().mangleTypeName(
Peter Collingbournee44acad2018-06-26 02:15:47 +00001066 QualType(AP1.first->getTypeForDecl(), 0), O1);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001067 O1.flush();
1068
1069 std::string S2;
1070 llvm::raw_string_ostream O2(S2);
1071 getCXXABI().getMangleContext().mangleTypeName(
Peter Collingbournee44acad2018-06-26 02:15:47 +00001072 QualType(AP2.first->getTypeForDecl(), 0), O2);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001073 O2.flush();
1074
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001075 if (S1 < S2)
1076 return true;
1077 if (S1 != S2)
1078 return false;
1079
Peter Collingbournee44acad2018-06-26 02:15:47 +00001080 return AP1.second < AP2.second;
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001081 });
1082
Peter Collingbournee44acad2018-06-26 02:15:47 +00001083 ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1084 for (auto AP : AddressPoints) {
1085 // Create type metadata for the address point.
1086 AddVTableTypeMetadata(VTable, PointerWidth * AP.second, AP.first);
1087
1088 // The class associated with each address point could also potentially be
1089 // used for indirect calls via a member function pointer, so we need to
1090 // annotate the address of each function pointer with the appropriate member
1091 // function pointer type.
1092 for (unsigned I = 0; I != Comps.size(); ++I) {
1093 if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1094 continue;
1095 llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1096 Context.getMemberPointerType(
1097 Comps[I].getFunctionDecl()->getType(),
1098 Context.getRecordType(AP.first).getTypePtr()));
1099 VTable->addTypeMetadata((PointerWidth * I).getQuantity(), MD);
1100 }
1101 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00001102}