xref: /openbsd/gnu/llvm/clang/lib/CodeGen/CGVTables.cpp (revision 12c85518)
1e5dd7070Spatrick //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code dealing with C++ code generation of virtual tables.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "CGCXXABI.h"
14e5dd7070Spatrick #include "CodeGenFunction.h"
15e5dd7070Spatrick #include "CodeGenModule.h"
16e5dd7070Spatrick #include "clang/AST/Attr.h"
17e5dd7070Spatrick #include "clang/AST/CXXInheritance.h"
18e5dd7070Spatrick #include "clang/AST/RecordLayout.h"
19e5dd7070Spatrick #include "clang/Basic/CodeGenOptions.h"
20e5dd7070Spatrick #include "clang/CodeGen/CGFunctionInfo.h"
21e5dd7070Spatrick #include "clang/CodeGen/ConstantInitBuilder.h"
22e5dd7070Spatrick #include "llvm/IR/IntrinsicInst.h"
23e5dd7070Spatrick #include "llvm/Support/Format.h"
24e5dd7070Spatrick #include "llvm/Transforms/Utils/Cloning.h"
25e5dd7070Spatrick #include <algorithm>
26e5dd7070Spatrick #include <cstdio>
27e5dd7070Spatrick 
28e5dd7070Spatrick using namespace clang;
29e5dd7070Spatrick using namespace CodeGen;
30e5dd7070Spatrick 
CodeGenVTables(CodeGenModule & CGM)31e5dd7070Spatrick CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32e5dd7070Spatrick     : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
33e5dd7070Spatrick 
GetAddrOfThunk(StringRef Name,llvm::Type * FnTy,GlobalDecl GD)34e5dd7070Spatrick llvm::Constant *CodeGenModule::GetAddrOfThunk(StringRef Name, llvm::Type *FnTy,
35e5dd7070Spatrick                                               GlobalDecl GD) {
36e5dd7070Spatrick   return GetOrCreateLLVMFunction(Name, FnTy, GD, /*ForVTable=*/true,
37e5dd7070Spatrick                                  /*DontDefer=*/true, /*IsThunk=*/true);
38e5dd7070Spatrick }
39e5dd7070Spatrick 
setThunkProperties(CodeGenModule & CGM,const ThunkInfo & Thunk,llvm::Function * ThunkFn,bool ForVTable,GlobalDecl GD)40e5dd7070Spatrick static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
41e5dd7070Spatrick                                llvm::Function *ThunkFn, bool ForVTable,
42e5dd7070Spatrick                                GlobalDecl GD) {
43e5dd7070Spatrick   CGM.setFunctionLinkage(GD, ThunkFn);
44e5dd7070Spatrick   CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
45e5dd7070Spatrick                                   !Thunk.Return.isEmpty());
46e5dd7070Spatrick 
47e5dd7070Spatrick   // Set the right visibility.
48e5dd7070Spatrick   CGM.setGVProperties(ThunkFn, GD);
49e5dd7070Spatrick 
50e5dd7070Spatrick   if (!CGM.getCXXABI().exportThunk()) {
51e5dd7070Spatrick     ThunkFn->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
52e5dd7070Spatrick     ThunkFn->setDSOLocal(true);
53e5dd7070Spatrick   }
54e5dd7070Spatrick 
55e5dd7070Spatrick   if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
56e5dd7070Spatrick     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
57e5dd7070Spatrick }
58e5dd7070Spatrick 
59e5dd7070Spatrick #ifndef NDEBUG
similar(const ABIArgInfo & infoL,CanQualType typeL,const ABIArgInfo & infoR,CanQualType typeR)60e5dd7070Spatrick static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61e5dd7070Spatrick                     const ABIArgInfo &infoR, CanQualType typeR) {
62e5dd7070Spatrick   return (infoL.getKind() == infoR.getKind() &&
63e5dd7070Spatrick           (typeL == typeR ||
64e5dd7070Spatrick            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65e5dd7070Spatrick            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66e5dd7070Spatrick }
67e5dd7070Spatrick #endif
68e5dd7070Spatrick 
PerformReturnAdjustment(CodeGenFunction & CGF,QualType ResultType,RValue RV,const ThunkInfo & Thunk)69e5dd7070Spatrick static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70e5dd7070Spatrick                                       QualType ResultType, RValue RV,
71e5dd7070Spatrick                                       const ThunkInfo &Thunk) {
72e5dd7070Spatrick   // Emit the return adjustment.
73e5dd7070Spatrick   bool NullCheckValue = !ResultType->isReferenceType();
74e5dd7070Spatrick 
75e5dd7070Spatrick   llvm::BasicBlock *AdjustNull = nullptr;
76e5dd7070Spatrick   llvm::BasicBlock *AdjustNotNull = nullptr;
77e5dd7070Spatrick   llvm::BasicBlock *AdjustEnd = nullptr;
78e5dd7070Spatrick 
79e5dd7070Spatrick   llvm::Value *ReturnValue = RV.getScalarVal();
80e5dd7070Spatrick 
81e5dd7070Spatrick   if (NullCheckValue) {
82e5dd7070Spatrick     AdjustNull = CGF.createBasicBlock("adjust.null");
83e5dd7070Spatrick     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84e5dd7070Spatrick     AdjustEnd = CGF.createBasicBlock("adjust.end");
85e5dd7070Spatrick 
86e5dd7070Spatrick     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87e5dd7070Spatrick     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88e5dd7070Spatrick     CGF.EmitBlock(AdjustNotNull);
89e5dd7070Spatrick   }
90e5dd7070Spatrick 
91e5dd7070Spatrick   auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
92e5dd7070Spatrick   auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
93*12c85518Srobert   ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(
94*12c85518Srobert       CGF,
95*12c85518Srobert       Address(ReturnValue, CGF.ConvertTypeForMem(ResultType->getPointeeType()),
96*12c85518Srobert               ClassAlign),
97e5dd7070Spatrick       Thunk.Return);
98e5dd7070Spatrick 
99e5dd7070Spatrick   if (NullCheckValue) {
100e5dd7070Spatrick     CGF.Builder.CreateBr(AdjustEnd);
101e5dd7070Spatrick     CGF.EmitBlock(AdjustNull);
102e5dd7070Spatrick     CGF.Builder.CreateBr(AdjustEnd);
103e5dd7070Spatrick     CGF.EmitBlock(AdjustEnd);
104e5dd7070Spatrick 
105e5dd7070Spatrick     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
106e5dd7070Spatrick     PHI->addIncoming(ReturnValue, AdjustNotNull);
107e5dd7070Spatrick     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
108e5dd7070Spatrick                      AdjustNull);
109e5dd7070Spatrick     ReturnValue = PHI;
110e5dd7070Spatrick   }
111e5dd7070Spatrick 
112e5dd7070Spatrick   return RValue::get(ReturnValue);
113e5dd7070Spatrick }
114e5dd7070Spatrick 
115e5dd7070Spatrick /// This function clones a function's DISubprogram node and enters it into
116e5dd7070Spatrick /// a value map with the intent that the map can be utilized by the cloner
117e5dd7070Spatrick /// to short-circuit Metadata node mapping.
118e5dd7070Spatrick /// Furthermore, the function resolves any DILocalVariable nodes referenced
119e5dd7070Spatrick /// by dbg.value intrinsics so they can be properly mapped during cloning.
resolveTopLevelMetadata(llvm::Function * Fn,llvm::ValueToValueMapTy & VMap)120e5dd7070Spatrick static void resolveTopLevelMetadata(llvm::Function *Fn,
121e5dd7070Spatrick                                     llvm::ValueToValueMapTy &VMap) {
122e5dd7070Spatrick   // Clone the DISubprogram node and put it into the Value map.
123e5dd7070Spatrick   auto *DIS = Fn->getSubprogram();
124e5dd7070Spatrick   if (!DIS)
125e5dd7070Spatrick     return;
126e5dd7070Spatrick   auto *NewDIS = DIS->replaceWithDistinct(DIS->clone());
127e5dd7070Spatrick   VMap.MD()[DIS].reset(NewDIS);
128e5dd7070Spatrick 
129e5dd7070Spatrick   // Find all llvm.dbg.declare intrinsics and resolve the DILocalVariable nodes
130e5dd7070Spatrick   // they are referencing.
131*12c85518Srobert   for (auto &BB : *Fn) {
132e5dd7070Spatrick     for (auto &I : BB) {
133e5dd7070Spatrick       if (auto *DII = dyn_cast<llvm::DbgVariableIntrinsic>(&I)) {
134e5dd7070Spatrick         auto *DILocal = DII->getVariable();
135e5dd7070Spatrick         if (!DILocal->isResolved())
136e5dd7070Spatrick           DILocal->resolve();
137e5dd7070Spatrick       }
138e5dd7070Spatrick     }
139e5dd7070Spatrick   }
140e5dd7070Spatrick }
141e5dd7070Spatrick 
142e5dd7070Spatrick // This function does roughly the same thing as GenerateThunk, but in a
143e5dd7070Spatrick // very different way, so that va_start and va_end work correctly.
144e5dd7070Spatrick // FIXME: This function assumes "this" is the first non-sret LLVM argument of
145e5dd7070Spatrick //        a function, and that there is an alloca built in the entry block
146e5dd7070Spatrick //        for all accesses to "this".
147e5dd7070Spatrick // FIXME: This function assumes there is only one "ret" statement per function.
148e5dd7070Spatrick // FIXME: Cloning isn't correct in the presence of indirect goto!
149e5dd7070Spatrick // FIXME: This implementation of thunks bloats codesize by duplicating the
150e5dd7070Spatrick //        function definition.  There are alternatives:
151e5dd7070Spatrick //        1. Add some sort of stub support to LLVM for cases where we can
152e5dd7070Spatrick //           do a this adjustment, then a sibcall.
153e5dd7070Spatrick //        2. We could transform the definition to take a va_list instead of an
154e5dd7070Spatrick //           actual variable argument list, then have the thunks (including a
155e5dd7070Spatrick //           no-op thunk for the regular definition) call va_start/va_end.
156e5dd7070Spatrick //           There's a bit of per-call overhead for this solution, but it's
157e5dd7070Spatrick //           better for codesize if the definition is long.
158e5dd7070Spatrick llvm::Function *
GenerateVarArgsThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk)159e5dd7070Spatrick CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
160e5dd7070Spatrick                                       const CGFunctionInfo &FnInfo,
161e5dd7070Spatrick                                       GlobalDecl GD, const ThunkInfo &Thunk) {
162e5dd7070Spatrick   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
163e5dd7070Spatrick   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
164e5dd7070Spatrick   QualType ResultType = FPT->getReturnType();
165e5dd7070Spatrick 
166e5dd7070Spatrick   // Get the original function
167e5dd7070Spatrick   assert(FnInfo.isVariadic());
168e5dd7070Spatrick   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
169e5dd7070Spatrick   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
170e5dd7070Spatrick   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
171e5dd7070Spatrick 
172e5dd7070Spatrick   // Cloning can't work if we don't have a definition. The Microsoft ABI may
173e5dd7070Spatrick   // require thunks when a definition is not available. Emit an error in these
174e5dd7070Spatrick   // cases.
175e5dd7070Spatrick   if (!MD->isDefined()) {
176e5dd7070Spatrick     CGM.ErrorUnsupported(MD, "return-adjusting thunk with variadic arguments");
177e5dd7070Spatrick     return Fn;
178e5dd7070Spatrick   }
179e5dd7070Spatrick   assert(!BaseFn->isDeclaration() && "cannot clone undefined variadic method");
180e5dd7070Spatrick 
181e5dd7070Spatrick   // Clone to thunk.
182e5dd7070Spatrick   llvm::ValueToValueMapTy VMap;
183e5dd7070Spatrick 
184e5dd7070Spatrick   // We are cloning a function while some Metadata nodes are still unresolved.
185e5dd7070Spatrick   // Ensure that the value mapper does not encounter any of them.
186e5dd7070Spatrick   resolveTopLevelMetadata(BaseFn, VMap);
187e5dd7070Spatrick   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
188e5dd7070Spatrick   Fn->replaceAllUsesWith(NewFn);
189e5dd7070Spatrick   NewFn->takeName(Fn);
190e5dd7070Spatrick   Fn->eraseFromParent();
191e5dd7070Spatrick   Fn = NewFn;
192e5dd7070Spatrick 
193e5dd7070Spatrick   // "Initialize" CGF (minimally).
194e5dd7070Spatrick   CurFn = Fn;
195e5dd7070Spatrick 
196e5dd7070Spatrick   // Get the "this" value
197e5dd7070Spatrick   llvm::Function::arg_iterator AI = Fn->arg_begin();
198e5dd7070Spatrick   if (CGM.ReturnTypeUsesSRet(FnInfo))
199e5dd7070Spatrick     ++AI;
200e5dd7070Spatrick 
201e5dd7070Spatrick   // Find the first store of "this", which will be to the alloca associated
202e5dd7070Spatrick   // with "this".
203*12c85518Srobert   Address ThisPtr =
204*12c85518Srobert       Address(&*AI, ConvertTypeForMem(MD->getThisType()->getPointeeType()),
205*12c85518Srobert               CGM.getClassPointerAlignment(MD->getParent()));
206e5dd7070Spatrick   llvm::BasicBlock *EntryBB = &Fn->front();
207e5dd7070Spatrick   llvm::BasicBlock::iterator ThisStore =
208*12c85518Srobert       llvm::find_if(*EntryBB, [&](llvm::Instruction &I) {
209e5dd7070Spatrick         return isa<llvm::StoreInst>(I) &&
210e5dd7070Spatrick                I.getOperand(0) == ThisPtr.getPointer();
211e5dd7070Spatrick       });
212e5dd7070Spatrick   assert(ThisStore != EntryBB->end() &&
213e5dd7070Spatrick          "Store of this should be in entry block?");
214e5dd7070Spatrick   // Adjust "this", if necessary.
215e5dd7070Spatrick   Builder.SetInsertPoint(&*ThisStore);
216e5dd7070Spatrick   llvm::Value *AdjustedThisPtr =
217e5dd7070Spatrick       CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
218e5dd7070Spatrick   AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr,
219e5dd7070Spatrick                                           ThisStore->getOperand(0)->getType());
220e5dd7070Spatrick   ThisStore->setOperand(0, AdjustedThisPtr);
221e5dd7070Spatrick 
222e5dd7070Spatrick   if (!Thunk.Return.isEmpty()) {
223e5dd7070Spatrick     // Fix up the returned value, if necessary.
224e5dd7070Spatrick     for (llvm::BasicBlock &BB : *Fn) {
225e5dd7070Spatrick       llvm::Instruction *T = BB.getTerminator();
226e5dd7070Spatrick       if (isa<llvm::ReturnInst>(T)) {
227e5dd7070Spatrick         RValue RV = RValue::get(T->getOperand(0));
228e5dd7070Spatrick         T->eraseFromParent();
229e5dd7070Spatrick         Builder.SetInsertPoint(&BB);
230e5dd7070Spatrick         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
231e5dd7070Spatrick         Builder.CreateRet(RV.getScalarVal());
232e5dd7070Spatrick         break;
233e5dd7070Spatrick       }
234e5dd7070Spatrick     }
235e5dd7070Spatrick   }
236e5dd7070Spatrick 
237e5dd7070Spatrick   return Fn;
238e5dd7070Spatrick }
239e5dd7070Spatrick 
StartThunk(llvm::Function * Fn,GlobalDecl GD,const CGFunctionInfo & FnInfo,bool IsUnprototyped)240e5dd7070Spatrick void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
241e5dd7070Spatrick                                  const CGFunctionInfo &FnInfo,
242e5dd7070Spatrick                                  bool IsUnprototyped) {
243e5dd7070Spatrick   assert(!CurGD.getDecl() && "CurGD was already set!");
244e5dd7070Spatrick   CurGD = GD;
245e5dd7070Spatrick   CurFuncIsThunk = true;
246e5dd7070Spatrick 
247e5dd7070Spatrick   // Build FunctionArgs.
248e5dd7070Spatrick   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
249e5dd7070Spatrick   QualType ThisType = MD->getThisType();
250e5dd7070Spatrick   QualType ResultType;
251e5dd7070Spatrick   if (IsUnprototyped)
252e5dd7070Spatrick     ResultType = CGM.getContext().VoidTy;
253e5dd7070Spatrick   else if (CGM.getCXXABI().HasThisReturn(GD))
254e5dd7070Spatrick     ResultType = ThisType;
255e5dd7070Spatrick   else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
256e5dd7070Spatrick     ResultType = CGM.getContext().VoidPtrTy;
257e5dd7070Spatrick   else
258e5dd7070Spatrick     ResultType = MD->getType()->castAs<FunctionProtoType>()->getReturnType();
259e5dd7070Spatrick   FunctionArgList FunctionArgs;
260e5dd7070Spatrick 
261e5dd7070Spatrick   // Create the implicit 'this' parameter declaration.
262e5dd7070Spatrick   CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
263e5dd7070Spatrick 
264e5dd7070Spatrick   // Add the rest of the parameters, if we have a prototype to work with.
265e5dd7070Spatrick   if (!IsUnprototyped) {
266e5dd7070Spatrick     FunctionArgs.append(MD->param_begin(), MD->param_end());
267e5dd7070Spatrick 
268e5dd7070Spatrick     if (isa<CXXDestructorDecl>(MD))
269e5dd7070Spatrick       CGM.getCXXABI().addImplicitStructorParams(*this, ResultType,
270e5dd7070Spatrick                                                 FunctionArgs);
271e5dd7070Spatrick   }
272e5dd7070Spatrick 
273e5dd7070Spatrick   // Start defining the function.
274e5dd7070Spatrick   auto NL = ApplyDebugLocation::CreateEmpty(*this);
275e5dd7070Spatrick   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
276e5dd7070Spatrick                 MD->getLocation());
277e5dd7070Spatrick   // Create a scope with an artificial location for the body of this function.
278e5dd7070Spatrick   auto AL = ApplyDebugLocation::CreateArtificial(*this);
279e5dd7070Spatrick 
280e5dd7070Spatrick   // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
281e5dd7070Spatrick   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
282e5dd7070Spatrick   CXXThisValue = CXXABIThisValue;
283e5dd7070Spatrick   CurCodeDecl = MD;
284e5dd7070Spatrick   CurFuncDecl = MD;
285e5dd7070Spatrick }
286e5dd7070Spatrick 
FinishThunk()287e5dd7070Spatrick void CodeGenFunction::FinishThunk() {
288e5dd7070Spatrick   // Clear these to restore the invariants expected by
289e5dd7070Spatrick   // StartFunction/FinishFunction.
290e5dd7070Spatrick   CurCodeDecl = nullptr;
291e5dd7070Spatrick   CurFuncDecl = nullptr;
292e5dd7070Spatrick 
293e5dd7070Spatrick   FinishFunction();
294e5dd7070Spatrick }
295e5dd7070Spatrick 
EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,const ThunkInfo * Thunk,bool IsUnprototyped)296e5dd7070Spatrick void CodeGenFunction::EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
297e5dd7070Spatrick                                                 const ThunkInfo *Thunk,
298e5dd7070Spatrick                                                 bool IsUnprototyped) {
299e5dd7070Spatrick   assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
300e5dd7070Spatrick          "Please use a new CGF for this thunk");
301e5dd7070Spatrick   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
302e5dd7070Spatrick 
303e5dd7070Spatrick   // Adjust the 'this' pointer if necessary
304e5dd7070Spatrick   llvm::Value *AdjustedThisPtr =
305e5dd7070Spatrick     Thunk ? CGM.getCXXABI().performThisAdjustment(
306e5dd7070Spatrick                           *this, LoadCXXThisAddress(), Thunk->This)
307e5dd7070Spatrick           : LoadCXXThis();
308e5dd7070Spatrick 
309e5dd7070Spatrick   // If perfect forwarding is required a variadic method, a method using
310e5dd7070Spatrick   // inalloca, or an unprototyped thunk, use musttail. Emit an error if this
311e5dd7070Spatrick   // thunk requires a return adjustment, since that is impossible with musttail.
312e5dd7070Spatrick   if (CurFnInfo->usesInAlloca() || CurFnInfo->isVariadic() || IsUnprototyped) {
313e5dd7070Spatrick     if (Thunk && !Thunk->Return.isEmpty()) {
314e5dd7070Spatrick       if (IsUnprototyped)
315e5dd7070Spatrick         CGM.ErrorUnsupported(
316e5dd7070Spatrick             MD, "return-adjusting thunk with incomplete parameter type");
317e5dd7070Spatrick       else if (CurFnInfo->isVariadic())
318e5dd7070Spatrick         llvm_unreachable("shouldn't try to emit musttail return-adjusting "
319e5dd7070Spatrick                          "thunks for variadic functions");
320e5dd7070Spatrick       else
321e5dd7070Spatrick         CGM.ErrorUnsupported(
322e5dd7070Spatrick             MD, "non-trivial argument copy for return-adjusting thunk");
323e5dd7070Spatrick     }
324e5dd7070Spatrick     EmitMustTailThunk(CurGD, AdjustedThisPtr, Callee);
325e5dd7070Spatrick     return;
326e5dd7070Spatrick   }
327e5dd7070Spatrick 
328e5dd7070Spatrick   // Start building CallArgs.
329e5dd7070Spatrick   CallArgList CallArgs;
330e5dd7070Spatrick   QualType ThisType = MD->getThisType();
331e5dd7070Spatrick   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
332e5dd7070Spatrick 
333e5dd7070Spatrick   if (isa<CXXDestructorDecl>(MD))
334e5dd7070Spatrick     CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
335e5dd7070Spatrick 
336e5dd7070Spatrick #ifndef NDEBUG
337e5dd7070Spatrick   unsigned PrefixArgs = CallArgs.size() - 1;
338e5dd7070Spatrick #endif
339e5dd7070Spatrick   // Add the rest of the arguments.
340e5dd7070Spatrick   for (const ParmVarDecl *PD : MD->parameters())
341e5dd7070Spatrick     EmitDelegateCallArg(CallArgs, PD, SourceLocation());
342e5dd7070Spatrick 
343e5dd7070Spatrick   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
344e5dd7070Spatrick 
345e5dd7070Spatrick #ifndef NDEBUG
346e5dd7070Spatrick   const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
347e5dd7070Spatrick       CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1), PrefixArgs);
348e5dd7070Spatrick   assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
349e5dd7070Spatrick          CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
350e5dd7070Spatrick          CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
351e5dd7070Spatrick   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
352e5dd7070Spatrick          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
353e5dd7070Spatrick                  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
354e5dd7070Spatrick   assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
355e5dd7070Spatrick   for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
356e5dd7070Spatrick     assert(similar(CallFnInfo.arg_begin()[i].info,
357e5dd7070Spatrick                    CallFnInfo.arg_begin()[i].type,
358e5dd7070Spatrick                    CurFnInfo->arg_begin()[i].info,
359e5dd7070Spatrick                    CurFnInfo->arg_begin()[i].type));
360e5dd7070Spatrick #endif
361e5dd7070Spatrick 
362e5dd7070Spatrick   // Determine whether we have a return value slot to use.
363e5dd7070Spatrick   QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
364e5dd7070Spatrick                             ? ThisType
365e5dd7070Spatrick                             : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
366e5dd7070Spatrick                                   ? CGM.getContext().VoidPtrTy
367e5dd7070Spatrick                                   : FPT->getReturnType();
368e5dd7070Spatrick   ReturnValueSlot Slot;
369e5dd7070Spatrick   if (!ResultType->isVoidType() &&
370ec727ea7Spatrick       (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
371ec727ea7Spatrick        hasAggregateEvaluationKind(ResultType)))
372ec727ea7Spatrick     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified(),
373ec727ea7Spatrick                            /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
374e5dd7070Spatrick 
375e5dd7070Spatrick   // Now emit our call.
376e5dd7070Spatrick   llvm::CallBase *CallOrInvoke;
377e5dd7070Spatrick   RValue RV = EmitCall(*CurFnInfo, CGCallee::forDirect(Callee, CurGD), Slot,
378e5dd7070Spatrick                        CallArgs, &CallOrInvoke);
379e5dd7070Spatrick 
380e5dd7070Spatrick   // Consider return adjustment if we have ThunkInfo.
381e5dd7070Spatrick   if (Thunk && !Thunk->Return.isEmpty())
382e5dd7070Spatrick     RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
383e5dd7070Spatrick   else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
384e5dd7070Spatrick     Call->setTailCallKind(llvm::CallInst::TCK_Tail);
385e5dd7070Spatrick 
386e5dd7070Spatrick   // Emit return.
387e5dd7070Spatrick   if (!ResultType->isVoidType() && Slot.isNull())
388e5dd7070Spatrick     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
389e5dd7070Spatrick 
390e5dd7070Spatrick   // Disable the final ARC autorelease.
391e5dd7070Spatrick   AutoreleaseResult = false;
392e5dd7070Spatrick 
393e5dd7070Spatrick   FinishThunk();
394e5dd7070Spatrick }
395e5dd7070Spatrick 
EmitMustTailThunk(GlobalDecl GD,llvm::Value * AdjustedThisPtr,llvm::FunctionCallee Callee)396e5dd7070Spatrick void CodeGenFunction::EmitMustTailThunk(GlobalDecl GD,
397e5dd7070Spatrick                                         llvm::Value *AdjustedThisPtr,
398e5dd7070Spatrick                                         llvm::FunctionCallee Callee) {
399e5dd7070Spatrick   // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
400e5dd7070Spatrick   // to translate AST arguments into LLVM IR arguments.  For thunks, we know
401e5dd7070Spatrick   // that the caller prototype more or less matches the callee prototype with
402e5dd7070Spatrick   // the exception of 'this'.
403*12c85518Srobert   SmallVector<llvm::Value *, 8> Args(llvm::make_pointer_range(CurFn->args()));
404e5dd7070Spatrick 
405e5dd7070Spatrick   // Set the adjusted 'this' pointer.
406e5dd7070Spatrick   const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
407e5dd7070Spatrick   if (ThisAI.isDirect()) {
408e5dd7070Spatrick     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
409e5dd7070Spatrick     int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
410e5dd7070Spatrick     llvm::Type *ThisType = Args[ThisArgNo]->getType();
411e5dd7070Spatrick     if (ThisType != AdjustedThisPtr->getType())
412e5dd7070Spatrick       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
413e5dd7070Spatrick     Args[ThisArgNo] = AdjustedThisPtr;
414e5dd7070Spatrick   } else {
415e5dd7070Spatrick     assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
416e5dd7070Spatrick     Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
417e5dd7070Spatrick     llvm::Type *ThisType = ThisAddr.getElementType();
418e5dd7070Spatrick     if (ThisType != AdjustedThisPtr->getType())
419e5dd7070Spatrick       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
420e5dd7070Spatrick     Builder.CreateStore(AdjustedThisPtr, ThisAddr);
421e5dd7070Spatrick   }
422e5dd7070Spatrick 
423e5dd7070Spatrick   // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
424e5dd7070Spatrick   // don't actually want to run them.
425e5dd7070Spatrick   llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
426e5dd7070Spatrick   Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
427e5dd7070Spatrick 
428e5dd7070Spatrick   // Apply the standard set of call attributes.
429e5dd7070Spatrick   unsigned CallingConv;
430e5dd7070Spatrick   llvm::AttributeList Attrs;
431e5dd7070Spatrick   CGM.ConstructAttributeList(Callee.getCallee()->getName(), *CurFnInfo, GD,
432a9ac8606Spatrick                              Attrs, CallingConv, /*AttrOnCallSite=*/true,
433a9ac8606Spatrick                              /*IsThunk=*/false);
434e5dd7070Spatrick   Call->setAttributes(Attrs);
435e5dd7070Spatrick   Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
436e5dd7070Spatrick 
437e5dd7070Spatrick   if (Call->getType()->isVoidTy())
438e5dd7070Spatrick     Builder.CreateRetVoid();
439e5dd7070Spatrick   else
440e5dd7070Spatrick     Builder.CreateRet(Call);
441e5dd7070Spatrick 
442e5dd7070Spatrick   // Finish the function to maintain CodeGenFunction invariants.
443e5dd7070Spatrick   // FIXME: Don't emit unreachable code.
444e5dd7070Spatrick   EmitBlock(createBasicBlock());
445389bb291Spatrick 
446389bb291Spatrick   FinishThunk();
447e5dd7070Spatrick }
448e5dd7070Spatrick 
generateThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk,bool IsUnprototyped)449e5dd7070Spatrick void CodeGenFunction::generateThunk(llvm::Function *Fn,
450e5dd7070Spatrick                                     const CGFunctionInfo &FnInfo, GlobalDecl GD,
451e5dd7070Spatrick                                     const ThunkInfo &Thunk,
452e5dd7070Spatrick                                     bool IsUnprototyped) {
453e5dd7070Spatrick   StartThunk(Fn, GD, FnInfo, IsUnprototyped);
454e5dd7070Spatrick   // Create a scope with an artificial location for the body of this function.
455e5dd7070Spatrick   auto AL = ApplyDebugLocation::CreateArtificial(*this);
456e5dd7070Spatrick 
457e5dd7070Spatrick   // Get our callee. Use a placeholder type if this method is unprototyped so
458e5dd7070Spatrick   // that CodeGenModule doesn't try to set attributes.
459e5dd7070Spatrick   llvm::Type *Ty;
460e5dd7070Spatrick   if (IsUnprototyped)
461e5dd7070Spatrick     Ty = llvm::StructType::get(getLLVMContext());
462e5dd7070Spatrick   else
463e5dd7070Spatrick     Ty = CGM.getTypes().GetFunctionType(FnInfo);
464e5dd7070Spatrick 
465e5dd7070Spatrick   llvm::Constant *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
466e5dd7070Spatrick 
467e5dd7070Spatrick   // Fix up the function type for an unprototyped musttail call.
468e5dd7070Spatrick   if (IsUnprototyped)
469e5dd7070Spatrick     Callee = llvm::ConstantExpr::getBitCast(Callee, Fn->getType());
470e5dd7070Spatrick 
471e5dd7070Spatrick   // Make the call and return the result.
472e5dd7070Spatrick   EmitCallAndReturnForThunk(llvm::FunctionCallee(Fn->getFunctionType(), Callee),
473e5dd7070Spatrick                             &Thunk, IsUnprototyped);
474e5dd7070Spatrick }
475e5dd7070Spatrick 
shouldEmitVTableThunk(CodeGenModule & CGM,const CXXMethodDecl * MD,bool IsUnprototyped,bool ForVTable)476e5dd7070Spatrick static bool shouldEmitVTableThunk(CodeGenModule &CGM, const CXXMethodDecl *MD,
477e5dd7070Spatrick                                   bool IsUnprototyped, bool ForVTable) {
478e5dd7070Spatrick   // Always emit thunks in the MS C++ ABI. We cannot rely on other TUs to
479e5dd7070Spatrick   // provide thunks for us.
480e5dd7070Spatrick   if (CGM.getTarget().getCXXABI().isMicrosoft())
481e5dd7070Spatrick     return true;
482e5dd7070Spatrick 
483e5dd7070Spatrick   // In the Itanium C++ ABI, vtable thunks are provided by TUs that provide
484e5dd7070Spatrick   // definitions of the main method. Therefore, emitting thunks with the vtable
485e5dd7070Spatrick   // is purely an optimization. Emit the thunk if optimizations are enabled and
486e5dd7070Spatrick   // all of the parameter types are complete.
487e5dd7070Spatrick   if (ForVTable)
488e5dd7070Spatrick     return CGM.getCodeGenOpts().OptimizationLevel && !IsUnprototyped;
489e5dd7070Spatrick 
490e5dd7070Spatrick   // Always emit thunks along with the method definition.
491e5dd7070Spatrick   return true;
492e5dd7070Spatrick }
493e5dd7070Spatrick 
maybeEmitThunk(GlobalDecl GD,const ThunkInfo & TI,bool ForVTable)494e5dd7070Spatrick llvm::Constant *CodeGenVTables::maybeEmitThunk(GlobalDecl GD,
495e5dd7070Spatrick                                                const ThunkInfo &TI,
496e5dd7070Spatrick                                                bool ForVTable) {
497e5dd7070Spatrick   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
498e5dd7070Spatrick 
499e5dd7070Spatrick   // First, get a declaration. Compute the mangled name. Don't worry about
500e5dd7070Spatrick   // getting the function prototype right, since we may only need this
501e5dd7070Spatrick   // declaration to fill in a vtable slot.
502e5dd7070Spatrick   SmallString<256> Name;
503e5dd7070Spatrick   MangleContext &MCtx = CGM.getCXXABI().getMangleContext();
504e5dd7070Spatrick   llvm::raw_svector_ostream Out(Name);
505e5dd7070Spatrick   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
506e5dd7070Spatrick     MCtx.mangleCXXDtorThunk(DD, GD.getDtorType(), TI.This, Out);
507e5dd7070Spatrick   else
508e5dd7070Spatrick     MCtx.mangleThunk(MD, TI, Out);
509e5dd7070Spatrick   llvm::Type *ThunkVTableTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
510e5dd7070Spatrick   llvm::Constant *Thunk = CGM.GetAddrOfThunk(Name, ThunkVTableTy, GD);
511e5dd7070Spatrick 
512e5dd7070Spatrick   // If we don't need to emit a definition, return this declaration as is.
513e5dd7070Spatrick   bool IsUnprototyped = !CGM.getTypes().isFuncTypeConvertible(
514e5dd7070Spatrick       MD->getType()->castAs<FunctionType>());
515e5dd7070Spatrick   if (!shouldEmitVTableThunk(CGM, MD, IsUnprototyped, ForVTable))
516e5dd7070Spatrick     return Thunk;
517e5dd7070Spatrick 
518e5dd7070Spatrick   // Arrange a function prototype appropriate for a function definition. In some
519e5dd7070Spatrick   // cases in the MS ABI, we may need to build an unprototyped musttail thunk.
520e5dd7070Spatrick   const CGFunctionInfo &FnInfo =
521e5dd7070Spatrick       IsUnprototyped ? CGM.getTypes().arrangeUnprototypedMustTailThunk(MD)
522e5dd7070Spatrick                      : CGM.getTypes().arrangeGlobalDeclaration(GD);
523e5dd7070Spatrick   llvm::FunctionType *ThunkFnTy = CGM.getTypes().GetFunctionType(FnInfo);
524e5dd7070Spatrick 
525e5dd7070Spatrick   // If the type of the underlying GlobalValue is wrong, we'll have to replace
526e5dd7070Spatrick   // it. It should be a declaration.
527e5dd7070Spatrick   llvm::Function *ThunkFn = cast<llvm::Function>(Thunk->stripPointerCasts());
528e5dd7070Spatrick   if (ThunkFn->getFunctionType() != ThunkFnTy) {
529e5dd7070Spatrick     llvm::GlobalValue *OldThunkFn = ThunkFn;
530e5dd7070Spatrick 
531e5dd7070Spatrick     assert(OldThunkFn->isDeclaration() && "Shouldn't replace non-declaration");
532e5dd7070Spatrick 
533e5dd7070Spatrick     // Remove the name from the old thunk function and get a new thunk.
534e5dd7070Spatrick     OldThunkFn->setName(StringRef());
535e5dd7070Spatrick     ThunkFn = llvm::Function::Create(ThunkFnTy, llvm::Function::ExternalLinkage,
536e5dd7070Spatrick                                      Name.str(), &CGM.getModule());
537a9ac8606Spatrick     CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, /*IsThunk=*/false);
538e5dd7070Spatrick 
539e5dd7070Spatrick     // If needed, replace the old thunk with a bitcast.
540e5dd7070Spatrick     if (!OldThunkFn->use_empty()) {
541e5dd7070Spatrick       llvm::Constant *NewPtrForOldDecl =
542e5dd7070Spatrick           llvm::ConstantExpr::getBitCast(ThunkFn, OldThunkFn->getType());
543e5dd7070Spatrick       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
544e5dd7070Spatrick     }
545e5dd7070Spatrick 
546e5dd7070Spatrick     // Remove the old thunk.
547e5dd7070Spatrick     OldThunkFn->eraseFromParent();
548e5dd7070Spatrick   }
549e5dd7070Spatrick 
550e5dd7070Spatrick   bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
551e5dd7070Spatrick   bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
552e5dd7070Spatrick 
553e5dd7070Spatrick   if (!ThunkFn->isDeclaration()) {
554e5dd7070Spatrick     if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
555e5dd7070Spatrick       // There is already a thunk emitted for this function, do nothing.
556e5dd7070Spatrick       return ThunkFn;
557e5dd7070Spatrick     }
558e5dd7070Spatrick 
559e5dd7070Spatrick     setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
560e5dd7070Spatrick     return ThunkFn;
561e5dd7070Spatrick   }
562e5dd7070Spatrick 
563e5dd7070Spatrick   // If this will be unprototyped, add the "thunk" attribute so that LLVM knows
564e5dd7070Spatrick   // that the return type is meaningless. These thunks can be used to call
565e5dd7070Spatrick   // functions with differing return types, and the caller is required to cast
566e5dd7070Spatrick   // the prototype appropriately to extract the correct value.
567e5dd7070Spatrick   if (IsUnprototyped)
568e5dd7070Spatrick     ThunkFn->addFnAttr("thunk");
569e5dd7070Spatrick 
570e5dd7070Spatrick   CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
571e5dd7070Spatrick 
572e5dd7070Spatrick   // Thunks for variadic methods are special because in general variadic
573389bb291Spatrick   // arguments cannot be perfectly forwarded. In the general case, clang
574e5dd7070Spatrick   // implements such thunks by cloning the original function body. However, for
575e5dd7070Spatrick   // thunks with no return adjustment on targets that support musttail, we can
576e5dd7070Spatrick   // use musttail to perfectly forward the variadic arguments.
577e5dd7070Spatrick   bool ShouldCloneVarArgs = false;
578e5dd7070Spatrick   if (!IsUnprototyped && ThunkFn->isVarArg()) {
579e5dd7070Spatrick     ShouldCloneVarArgs = true;
580e5dd7070Spatrick     if (TI.Return.isEmpty()) {
581e5dd7070Spatrick       switch (CGM.getTriple().getArch()) {
582e5dd7070Spatrick       case llvm::Triple::x86_64:
583e5dd7070Spatrick       case llvm::Triple::x86:
584e5dd7070Spatrick       case llvm::Triple::aarch64:
585e5dd7070Spatrick         ShouldCloneVarArgs = false;
586e5dd7070Spatrick         break;
587e5dd7070Spatrick       default:
588e5dd7070Spatrick         break;
589e5dd7070Spatrick       }
590e5dd7070Spatrick     }
591e5dd7070Spatrick   }
592e5dd7070Spatrick 
593e5dd7070Spatrick   if (ShouldCloneVarArgs) {
594e5dd7070Spatrick     if (UseAvailableExternallyLinkage)
595e5dd7070Spatrick       return ThunkFn;
596e5dd7070Spatrick     ThunkFn =
597e5dd7070Spatrick         CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, TI);
598e5dd7070Spatrick   } else {
599e5dd7070Spatrick     // Normal thunk body generation.
600e5dd7070Spatrick     CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, TI, IsUnprototyped);
601e5dd7070Spatrick   }
602e5dd7070Spatrick 
603e5dd7070Spatrick   setThunkProperties(CGM, TI, ThunkFn, ForVTable, GD);
604e5dd7070Spatrick   return ThunkFn;
605e5dd7070Spatrick }
606e5dd7070Spatrick 
EmitThunks(GlobalDecl GD)607e5dd7070Spatrick void CodeGenVTables::EmitThunks(GlobalDecl GD) {
608e5dd7070Spatrick   const CXXMethodDecl *MD =
609e5dd7070Spatrick     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
610e5dd7070Spatrick 
611e5dd7070Spatrick   // We don't need to generate thunks for the base destructor.
612e5dd7070Spatrick   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
613e5dd7070Spatrick     return;
614e5dd7070Spatrick 
615e5dd7070Spatrick   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
616e5dd7070Spatrick       VTContext->getThunkInfo(GD);
617e5dd7070Spatrick 
618e5dd7070Spatrick   if (!ThunkInfoVector)
619e5dd7070Spatrick     return;
620e5dd7070Spatrick 
621e5dd7070Spatrick   for (const ThunkInfo& Thunk : *ThunkInfoVector)
622e5dd7070Spatrick     maybeEmitThunk(GD, Thunk, /*ForVTable=*/false);
623e5dd7070Spatrick }
624e5dd7070Spatrick 
addRelativeComponent(ConstantArrayBuilder & builder,llvm::Constant * component,unsigned vtableAddressPoint,bool vtableHasLocalLinkage,bool isCompleteDtor) const625ec727ea7Spatrick void CodeGenVTables::addRelativeComponent(ConstantArrayBuilder &builder,
626ec727ea7Spatrick                                           llvm::Constant *component,
627ec727ea7Spatrick                                           unsigned vtableAddressPoint,
628ec727ea7Spatrick                                           bool vtableHasLocalLinkage,
629ec727ea7Spatrick                                           bool isCompleteDtor) const {
630ec727ea7Spatrick   // No need to get the offset of a nullptr.
631ec727ea7Spatrick   if (component->isNullValue())
632ec727ea7Spatrick     return builder.add(llvm::ConstantInt::get(CGM.Int32Ty, 0));
633e5dd7070Spatrick 
634ec727ea7Spatrick   auto *globalVal =
635ec727ea7Spatrick       cast<llvm::GlobalValue>(component->stripPointerCastsAndAliases());
636ec727ea7Spatrick   llvm::Module &module = CGM.getModule();
637ec727ea7Spatrick 
638ec727ea7Spatrick   // We don't want to copy the linkage of the vtable exactly because we still
639ec727ea7Spatrick   // want the stub/proxy to be emitted for properly calculating the offset.
640ec727ea7Spatrick   // Examples where there would be no symbol emitted are available_externally
641ec727ea7Spatrick   // and private linkages.
642ec727ea7Spatrick   auto stubLinkage = vtableHasLocalLinkage ? llvm::GlobalValue::InternalLinkage
643ec727ea7Spatrick                                            : llvm::GlobalValue::ExternalLinkage;
644ec727ea7Spatrick 
645ec727ea7Spatrick   llvm::Constant *target;
646ec727ea7Spatrick   if (auto *func = dyn_cast<llvm::Function>(globalVal)) {
647a9ac8606Spatrick     target = llvm::DSOLocalEquivalent::get(func);
648ec727ea7Spatrick   } else {
649ec727ea7Spatrick     llvm::SmallString<16> rttiProxyName(globalVal->getName());
650ec727ea7Spatrick     rttiProxyName.append(".rtti_proxy");
651ec727ea7Spatrick 
652ec727ea7Spatrick     // The RTTI component may not always be emitted in the same linkage unit as
653ec727ea7Spatrick     // the vtable. As a general case, we can make a dso_local proxy to the RTTI
654ec727ea7Spatrick     // that points to the actual RTTI struct somewhere. This will result in a
655ec727ea7Spatrick     // GOTPCREL relocation when taking the relative offset to the proxy.
656ec727ea7Spatrick     llvm::GlobalVariable *proxy = module.getNamedGlobal(rttiProxyName);
657ec727ea7Spatrick     if (!proxy) {
658ec727ea7Spatrick       proxy = new llvm::GlobalVariable(module, globalVal->getType(),
659ec727ea7Spatrick                                        /*isConstant=*/true, stubLinkage,
660ec727ea7Spatrick                                        globalVal, rttiProxyName);
661ec727ea7Spatrick       proxy->setDSOLocal(true);
662ec727ea7Spatrick       proxy->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
663ec727ea7Spatrick       if (!proxy->hasLocalLinkage()) {
664ec727ea7Spatrick         proxy->setVisibility(llvm::GlobalValue::HiddenVisibility);
665ec727ea7Spatrick         proxy->setComdat(module.getOrInsertComdat(rttiProxyName));
666ec727ea7Spatrick       }
667*12c85518Srobert       // Do not instrument the rtti proxies with hwasan to avoid a duplicate
668*12c85518Srobert       // symbol error. Aliases generated by hwasan will retain the same namebut
669*12c85518Srobert       // the addresses they are set to may have different tags from different
670*12c85518Srobert       // compilation units. We don't run into this without hwasan because the
671*12c85518Srobert       // proxies are in comdat groups, but those aren't propagated to the alias.
672*12c85518Srobert       RemoveHwasanMetadata(proxy);
673ec727ea7Spatrick     }
674ec727ea7Spatrick     target = proxy;
675ec727ea7Spatrick   }
676ec727ea7Spatrick 
677ec727ea7Spatrick   builder.addRelativeOffsetToPosition(CGM.Int32Ty, target,
678ec727ea7Spatrick                                       /*position=*/vtableAddressPoint);
679ec727ea7Spatrick }
680ec727ea7Spatrick 
UseRelativeLayout(const CodeGenModule & CGM)681*12c85518Srobert static bool UseRelativeLayout(const CodeGenModule &CGM) {
682ec727ea7Spatrick   return CGM.getTarget().getCXXABI().isItaniumFamily() &&
683ec727ea7Spatrick          CGM.getItaniumVTableContext().isRelativeLayout();
684ec727ea7Spatrick }
685ec727ea7Spatrick 
useRelativeLayout() const686*12c85518Srobert bool CodeGenVTables::useRelativeLayout() const {
687*12c85518Srobert   return UseRelativeLayout(CGM);
688*12c85518Srobert }
689*12c85518Srobert 
getVTableComponentType() const690*12c85518Srobert llvm::Type *CodeGenModule::getVTableComponentType() const {
691*12c85518Srobert   if (UseRelativeLayout(*this))
692*12c85518Srobert     return Int32Ty;
693*12c85518Srobert   return Int8PtrTy;
694*12c85518Srobert }
695*12c85518Srobert 
getVTableComponentType() const696ec727ea7Spatrick llvm::Type *CodeGenVTables::getVTableComponentType() const {
697*12c85518Srobert   return CGM.getVTableComponentType();
698ec727ea7Spatrick }
699ec727ea7Spatrick 
AddPointerLayoutOffset(const CodeGenModule & CGM,ConstantArrayBuilder & builder,CharUnits offset)700ec727ea7Spatrick static void AddPointerLayoutOffset(const CodeGenModule &CGM,
701ec727ea7Spatrick                                    ConstantArrayBuilder &builder,
702ec727ea7Spatrick                                    CharUnits offset) {
703e5dd7070Spatrick   builder.add(llvm::ConstantExpr::getIntToPtr(
704e5dd7070Spatrick       llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity()),
705e5dd7070Spatrick       CGM.Int8PtrTy));
706ec727ea7Spatrick }
707ec727ea7Spatrick 
AddRelativeLayoutOffset(const CodeGenModule & CGM,ConstantArrayBuilder & builder,CharUnits offset)708ec727ea7Spatrick static void AddRelativeLayoutOffset(const CodeGenModule &CGM,
709ec727ea7Spatrick                                     ConstantArrayBuilder &builder,
710ec727ea7Spatrick                                     CharUnits offset) {
711ec727ea7Spatrick   builder.add(llvm::ConstantInt::get(CGM.Int32Ty, offset.getQuantity()));
712ec727ea7Spatrick }
713ec727ea7Spatrick 
addVTableComponent(ConstantArrayBuilder & builder,const VTableLayout & layout,unsigned componentIndex,llvm::Constant * rtti,unsigned & nextVTableThunkIndex,unsigned vtableAddressPoint,bool vtableHasLocalLinkage)714ec727ea7Spatrick void CodeGenVTables::addVTableComponent(ConstantArrayBuilder &builder,
715ec727ea7Spatrick                                         const VTableLayout &layout,
716ec727ea7Spatrick                                         unsigned componentIndex,
717ec727ea7Spatrick                                         llvm::Constant *rtti,
718ec727ea7Spatrick                                         unsigned &nextVTableThunkIndex,
719ec727ea7Spatrick                                         unsigned vtableAddressPoint,
720ec727ea7Spatrick                                         bool vtableHasLocalLinkage) {
721ec727ea7Spatrick   auto &component = layout.vtable_components()[componentIndex];
722ec727ea7Spatrick 
723ec727ea7Spatrick   auto addOffsetConstant =
724ec727ea7Spatrick       useRelativeLayout() ? AddRelativeLayoutOffset : AddPointerLayoutOffset;
725e5dd7070Spatrick 
726e5dd7070Spatrick   switch (component.getKind()) {
727e5dd7070Spatrick   case VTableComponent::CK_VCallOffset:
728ec727ea7Spatrick     return addOffsetConstant(CGM, builder, component.getVCallOffset());
729e5dd7070Spatrick 
730e5dd7070Spatrick   case VTableComponent::CK_VBaseOffset:
731ec727ea7Spatrick     return addOffsetConstant(CGM, builder, component.getVBaseOffset());
732e5dd7070Spatrick 
733e5dd7070Spatrick   case VTableComponent::CK_OffsetToTop:
734ec727ea7Spatrick     return addOffsetConstant(CGM, builder, component.getOffsetToTop());
735e5dd7070Spatrick 
736e5dd7070Spatrick   case VTableComponent::CK_RTTI:
737ec727ea7Spatrick     if (useRelativeLayout())
738ec727ea7Spatrick       return addRelativeComponent(builder, rtti, vtableAddressPoint,
739ec727ea7Spatrick                                   vtableHasLocalLinkage,
740ec727ea7Spatrick                                   /*isCompleteDtor=*/false);
741ec727ea7Spatrick     else
742e5dd7070Spatrick       return builder.add(llvm::ConstantExpr::getBitCast(rtti, CGM.Int8PtrTy));
743e5dd7070Spatrick 
744e5dd7070Spatrick   case VTableComponent::CK_FunctionPointer:
745e5dd7070Spatrick   case VTableComponent::CK_CompleteDtorPointer:
746e5dd7070Spatrick   case VTableComponent::CK_DeletingDtorPointer: {
747a9ac8606Spatrick     GlobalDecl GD = component.getGlobalDecl();
748e5dd7070Spatrick 
749e5dd7070Spatrick     if (CGM.getLangOpts().CUDA) {
750e5dd7070Spatrick       // Emit NULL for methods we can't codegen on this
751e5dd7070Spatrick       // side. Otherwise we'd end up with vtable with unresolved
752e5dd7070Spatrick       // references.
753e5dd7070Spatrick       const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
754e5dd7070Spatrick       // OK on device side: functions w/ __device__ attribute
755e5dd7070Spatrick       // OK on host side: anything except __device__-only functions.
756e5dd7070Spatrick       bool CanEmitMethod =
757e5dd7070Spatrick           CGM.getLangOpts().CUDAIsDevice
758e5dd7070Spatrick               ? MD->hasAttr<CUDADeviceAttr>()
759e5dd7070Spatrick               : (MD->hasAttr<CUDAHostAttr>() || !MD->hasAttr<CUDADeviceAttr>());
760e5dd7070Spatrick       if (!CanEmitMethod)
761ec727ea7Spatrick         return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int8PtrTy));
762e5dd7070Spatrick       // Method is acceptable, continue processing as usual.
763e5dd7070Spatrick     }
764e5dd7070Spatrick 
765e5dd7070Spatrick     auto getSpecialVirtualFn = [&](StringRef name) -> llvm::Constant * {
766ec727ea7Spatrick       // FIXME(PR43094): When merging comdat groups, lld can select a local
767ec727ea7Spatrick       // symbol as the signature symbol even though it cannot be accessed
768ec727ea7Spatrick       // outside that symbol's TU. The relative vtables ABI would make
769ec727ea7Spatrick       // __cxa_pure_virtual and __cxa_deleted_virtual local symbols, and
770ec727ea7Spatrick       // depending on link order, the comdat groups could resolve to the one
771ec727ea7Spatrick       // with the local symbol. As a temporary solution, fill these components
772ec727ea7Spatrick       // with zero. We shouldn't be calling these in the first place anyway.
773ec727ea7Spatrick       if (useRelativeLayout())
774ec727ea7Spatrick         return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
775ec727ea7Spatrick 
776e5dd7070Spatrick       // For NVPTX devices in OpenMP emit special functon as null pointers,
777e5dd7070Spatrick       // otherwise linking ends up with unresolved references.
778e5dd7070Spatrick       if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPIsDevice &&
779e5dd7070Spatrick           CGM.getTriple().isNVPTX())
780e5dd7070Spatrick         return llvm::ConstantPointerNull::get(CGM.Int8PtrTy);
781e5dd7070Spatrick       llvm::FunctionType *fnTy =
782e5dd7070Spatrick           llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
783e5dd7070Spatrick       llvm::Constant *fn = cast<llvm::Constant>(
784e5dd7070Spatrick           CGM.CreateRuntimeFunction(fnTy, name).getCallee());
785e5dd7070Spatrick       if (auto f = dyn_cast<llvm::Function>(fn))
786e5dd7070Spatrick         f->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
787e5dd7070Spatrick       return llvm::ConstantExpr::getBitCast(fn, CGM.Int8PtrTy);
788e5dd7070Spatrick     };
789e5dd7070Spatrick 
790e5dd7070Spatrick     llvm::Constant *fnPtr;
791e5dd7070Spatrick 
792e5dd7070Spatrick     // Pure virtual member functions.
793e5dd7070Spatrick     if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
794e5dd7070Spatrick       if (!PureVirtualFn)
795e5dd7070Spatrick         PureVirtualFn =
796e5dd7070Spatrick             getSpecialVirtualFn(CGM.getCXXABI().GetPureVirtualCallName());
797e5dd7070Spatrick       fnPtr = PureVirtualFn;
798e5dd7070Spatrick 
799e5dd7070Spatrick     // Deleted virtual member functions.
800e5dd7070Spatrick     } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
801e5dd7070Spatrick       if (!DeletedVirtualFn)
802e5dd7070Spatrick         DeletedVirtualFn =
803e5dd7070Spatrick             getSpecialVirtualFn(CGM.getCXXABI().GetDeletedVirtualCallName());
804e5dd7070Spatrick       fnPtr = DeletedVirtualFn;
805e5dd7070Spatrick 
806e5dd7070Spatrick     // Thunks.
807e5dd7070Spatrick     } else if (nextVTableThunkIndex < layout.vtable_thunks().size() &&
808ec727ea7Spatrick                layout.vtable_thunks()[nextVTableThunkIndex].first ==
809ec727ea7Spatrick                    componentIndex) {
810e5dd7070Spatrick       auto &thunkInfo = layout.vtable_thunks()[nextVTableThunkIndex].second;
811e5dd7070Spatrick 
812e5dd7070Spatrick       nextVTableThunkIndex++;
813e5dd7070Spatrick       fnPtr = maybeEmitThunk(GD, thunkInfo, /*ForVTable=*/true);
814e5dd7070Spatrick 
815e5dd7070Spatrick     // Otherwise we can use the method definition directly.
816e5dd7070Spatrick     } else {
817e5dd7070Spatrick       llvm::Type *fnTy = CGM.getTypes().GetFunctionTypeForVTable(GD);
818e5dd7070Spatrick       fnPtr = CGM.GetAddrOfFunction(GD, fnTy, /*ForVTable=*/true);
819e5dd7070Spatrick     }
820e5dd7070Spatrick 
821ec727ea7Spatrick     if (useRelativeLayout()) {
822ec727ea7Spatrick       return addRelativeComponent(
823ec727ea7Spatrick           builder, fnPtr, vtableAddressPoint, vtableHasLocalLinkage,
824ec727ea7Spatrick           component.getKind() == VTableComponent::CK_CompleteDtorPointer);
825ec727ea7Spatrick     } else
826ec727ea7Spatrick       return builder.add(llvm::ConstantExpr::getBitCast(fnPtr, CGM.Int8PtrTy));
827e5dd7070Spatrick   }
828e5dd7070Spatrick 
829e5dd7070Spatrick   case VTableComponent::CK_UnusedFunctionPointer:
830ec727ea7Spatrick     if (useRelativeLayout())
831ec727ea7Spatrick       return builder.add(llvm::ConstantExpr::getNullValue(CGM.Int32Ty));
832ec727ea7Spatrick     else
833e5dd7070Spatrick       return builder.addNullPointer(CGM.Int8PtrTy);
834e5dd7070Spatrick   }
835e5dd7070Spatrick 
836e5dd7070Spatrick   llvm_unreachable("Unexpected vtable component kind");
837e5dd7070Spatrick }
838e5dd7070Spatrick 
getVTableType(const VTableLayout & layout)839e5dd7070Spatrick llvm::Type *CodeGenVTables::getVTableType(const VTableLayout &layout) {
840e5dd7070Spatrick   SmallVector<llvm::Type *, 4> tys;
841ec727ea7Spatrick   llvm::Type *componentType = getVTableComponentType();
842ec727ea7Spatrick   for (unsigned i = 0, e = layout.getNumVTables(); i != e; ++i)
843ec727ea7Spatrick     tys.push_back(llvm::ArrayType::get(componentType, layout.getVTableSize(i)));
844e5dd7070Spatrick 
845e5dd7070Spatrick   return llvm::StructType::get(CGM.getLLVMContext(), tys);
846e5dd7070Spatrick }
847e5dd7070Spatrick 
createVTableInitializer(ConstantStructBuilder & builder,const VTableLayout & layout,llvm::Constant * rtti,bool vtableHasLocalLinkage)848e5dd7070Spatrick void CodeGenVTables::createVTableInitializer(ConstantStructBuilder &builder,
849e5dd7070Spatrick                                              const VTableLayout &layout,
850ec727ea7Spatrick                                              llvm::Constant *rtti,
851ec727ea7Spatrick                                              bool vtableHasLocalLinkage) {
852ec727ea7Spatrick   llvm::Type *componentType = getVTableComponentType();
853ec727ea7Spatrick 
854ec727ea7Spatrick   const auto &addressPoints = layout.getAddressPointIndices();
855e5dd7070Spatrick   unsigned nextVTableThunkIndex = 0;
856ec727ea7Spatrick   for (unsigned vtableIndex = 0, endIndex = layout.getNumVTables();
857ec727ea7Spatrick        vtableIndex != endIndex; ++vtableIndex) {
858ec727ea7Spatrick     auto vtableElem = builder.beginArray(componentType);
859ec727ea7Spatrick 
860ec727ea7Spatrick     size_t vtableStart = layout.getVTableOffset(vtableIndex);
861ec727ea7Spatrick     size_t vtableEnd = vtableStart + layout.getVTableSize(vtableIndex);
862ec727ea7Spatrick     for (size_t componentIndex = vtableStart; componentIndex < vtableEnd;
863ec727ea7Spatrick          ++componentIndex) {
864ec727ea7Spatrick       addVTableComponent(vtableElem, layout, componentIndex, rtti,
865ec727ea7Spatrick                          nextVTableThunkIndex, addressPoints[vtableIndex],
866ec727ea7Spatrick                          vtableHasLocalLinkage);
867e5dd7070Spatrick     }
868e5dd7070Spatrick     vtableElem.finishAndAddTo(builder);
869e5dd7070Spatrick   }
870e5dd7070Spatrick }
871e5dd7070Spatrick 
GenerateConstructionVTable(const CXXRecordDecl * RD,const BaseSubobject & Base,bool BaseIsVirtual,llvm::GlobalVariable::LinkageTypes Linkage,VTableAddressPointsMapTy & AddressPoints)872ec727ea7Spatrick llvm::GlobalVariable *CodeGenVTables::GenerateConstructionVTable(
873ec727ea7Spatrick     const CXXRecordDecl *RD, const BaseSubobject &Base, bool BaseIsVirtual,
874e5dd7070Spatrick     llvm::GlobalVariable::LinkageTypes Linkage,
875e5dd7070Spatrick     VTableAddressPointsMapTy &AddressPoints) {
876e5dd7070Spatrick   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
877e5dd7070Spatrick     DI->completeClassData(Base.getBase());
878e5dd7070Spatrick 
879e5dd7070Spatrick   std::unique_ptr<VTableLayout> VTLayout(
880e5dd7070Spatrick       getItaniumVTableContext().createConstructionVTableLayout(
881e5dd7070Spatrick           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
882e5dd7070Spatrick 
883e5dd7070Spatrick   // Add the address points.
884e5dd7070Spatrick   AddressPoints = VTLayout->getAddressPoints();
885e5dd7070Spatrick 
886e5dd7070Spatrick   // Get the mangled construction vtable name.
887e5dd7070Spatrick   SmallString<256> OutName;
888e5dd7070Spatrick   llvm::raw_svector_ostream Out(OutName);
889e5dd7070Spatrick   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
890e5dd7070Spatrick       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
891e5dd7070Spatrick                            Base.getBase(), Out);
892ec727ea7Spatrick   SmallString<256> Name(OutName);
893ec727ea7Spatrick 
894ec727ea7Spatrick   bool UsingRelativeLayout = getItaniumVTableContext().isRelativeLayout();
895ec727ea7Spatrick   bool VTableAliasExists =
896ec727ea7Spatrick       UsingRelativeLayout && CGM.getModule().getNamedAlias(Name);
897ec727ea7Spatrick   if (VTableAliasExists) {
898ec727ea7Spatrick     // We previously made the vtable hidden and changed its name.
899ec727ea7Spatrick     Name.append(".local");
900ec727ea7Spatrick   }
901e5dd7070Spatrick 
902e5dd7070Spatrick   llvm::Type *VTType = getVTableType(*VTLayout);
903e5dd7070Spatrick 
904e5dd7070Spatrick   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
905e5dd7070Spatrick   // guarantee that they actually will be available externally. Instead, when
906e5dd7070Spatrick   // emitting an available_externally VTT, we provide references to an internal
907e5dd7070Spatrick   // linkage construction vtable. The ABI only requires complete-object vtables
908e5dd7070Spatrick   // to be the same for all instances of a type, not construction vtables.
909e5dd7070Spatrick   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
910e5dd7070Spatrick     Linkage = llvm::GlobalVariable::InternalLinkage;
911e5dd7070Spatrick 
912*12c85518Srobert   llvm::Align Align = CGM.getDataLayout().getABITypeAlign(VTType);
913e5dd7070Spatrick 
914e5dd7070Spatrick   // Create the variable that will hold the construction vtable.
915e5dd7070Spatrick   llvm::GlobalVariable *VTable =
916e5dd7070Spatrick       CGM.CreateOrReplaceCXXRuntimeVariable(Name, VTType, Linkage, Align);
917e5dd7070Spatrick 
918e5dd7070Spatrick   // V-tables are always unnamed_addr.
919e5dd7070Spatrick   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
920e5dd7070Spatrick 
921e5dd7070Spatrick   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
922e5dd7070Spatrick       CGM.getContext().getTagDeclType(Base.getBase()));
923e5dd7070Spatrick 
924e5dd7070Spatrick   // Create and set the initializer.
925e5dd7070Spatrick   ConstantInitBuilder builder(CGM);
926e5dd7070Spatrick   auto components = builder.beginStruct();
927ec727ea7Spatrick   createVTableInitializer(components, *VTLayout, RTTI,
928ec727ea7Spatrick                           VTable->hasLocalLinkage());
929e5dd7070Spatrick   components.finishAndSetAsInitializer(VTable);
930e5dd7070Spatrick 
931e5dd7070Spatrick   // Set properties only after the initializer has been set to ensure that the
932e5dd7070Spatrick   // GV is treated as definition and not declaration.
933e5dd7070Spatrick   assert(!VTable->isDeclaration() && "Shouldn't set properties on declaration");
934e5dd7070Spatrick   CGM.setGVProperties(VTable, RD);
935e5dd7070Spatrick 
936e5dd7070Spatrick   CGM.EmitVTableTypeMetadata(RD, VTable, *VTLayout.get());
937e5dd7070Spatrick 
938*12c85518Srobert   if (UsingRelativeLayout) {
939*12c85518Srobert     RemoveHwasanMetadata(VTable);
940*12c85518Srobert     if (!VTable->isDSOLocal())
941ec727ea7Spatrick       GenerateRelativeVTableAlias(VTable, OutName);
942*12c85518Srobert   }
943ec727ea7Spatrick 
944e5dd7070Spatrick   return VTable;
945e5dd7070Spatrick }
946e5dd7070Spatrick 
947*12c85518Srobert // Ensure this vtable is not instrumented by hwasan. That is, a global alias is
948*12c85518Srobert // not generated for it. This is mainly used by the relative-vtables ABI where
949*12c85518Srobert // vtables instead contain 32-bit offsets between the vtable and function
950*12c85518Srobert // pointers. Hwasan is disabled for these vtables for now because the tag in a
951*12c85518Srobert // vtable pointer may fail the overflow check when resolving 32-bit PLT
952*12c85518Srobert // relocations. A future alternative for this would be finding which usages of
953*12c85518Srobert // the vtable can continue to use the untagged hwasan value without any loss of
954*12c85518Srobert // value in hwasan.
RemoveHwasanMetadata(llvm::GlobalValue * GV) const955*12c85518Srobert void CodeGenVTables::RemoveHwasanMetadata(llvm::GlobalValue *GV) const {
956*12c85518Srobert   if (CGM.getLangOpts().Sanitize.has(SanitizerKind::HWAddress)) {
957*12c85518Srobert     llvm::GlobalValue::SanitizerMetadata Meta;
958*12c85518Srobert     if (GV->hasSanitizerMetadata())
959*12c85518Srobert       Meta = GV->getSanitizerMetadata();
960*12c85518Srobert     Meta.NoHWAddress = true;
961*12c85518Srobert     GV->setSanitizerMetadata(Meta);
962*12c85518Srobert   }
963*12c85518Srobert }
964*12c85518Srobert 
965ec727ea7Spatrick // If the VTable is not dso_local, then we will not be able to indicate that
966ec727ea7Spatrick // the VTable does not need a relocation and move into rodata. A frequent
967ec727ea7Spatrick // time this can occur is for classes that should be made public from a DSO
968ec727ea7Spatrick // (like in libc++). For cases like these, we can make the vtable hidden or
969ec727ea7Spatrick // private and create a public alias with the same visibility and linkage as
970ec727ea7Spatrick // the original vtable type.
GenerateRelativeVTableAlias(llvm::GlobalVariable * VTable,llvm::StringRef AliasNameRef)971ec727ea7Spatrick void CodeGenVTables::GenerateRelativeVTableAlias(llvm::GlobalVariable *VTable,
972ec727ea7Spatrick                                                  llvm::StringRef AliasNameRef) {
973ec727ea7Spatrick   assert(getItaniumVTableContext().isRelativeLayout() &&
974ec727ea7Spatrick          "Can only use this if the relative vtable ABI is used");
975ec727ea7Spatrick   assert(!VTable->isDSOLocal() && "This should be called only if the vtable is "
976ec727ea7Spatrick                                   "not guaranteed to be dso_local");
977ec727ea7Spatrick 
978ec727ea7Spatrick   // If the vtable is available_externally, we shouldn't (or need to) generate
979ec727ea7Spatrick   // an alias for it in the first place since the vtable won't actually by
980ec727ea7Spatrick   // emitted in this compilation unit.
981ec727ea7Spatrick   if (VTable->hasAvailableExternallyLinkage())
982ec727ea7Spatrick     return;
983ec727ea7Spatrick 
984ec727ea7Spatrick   // Create a new string in the event the alias is already the name of the
985ec727ea7Spatrick   // vtable. Using the reference directly could lead to use of an inititialized
986ec727ea7Spatrick   // value in the module's StringMap.
987ec727ea7Spatrick   llvm::SmallString<256> AliasName(AliasNameRef);
988ec727ea7Spatrick   VTable->setName(AliasName + ".local");
989ec727ea7Spatrick 
990ec727ea7Spatrick   auto Linkage = VTable->getLinkage();
991ec727ea7Spatrick   assert(llvm::GlobalAlias::isValidLinkage(Linkage) &&
992ec727ea7Spatrick          "Invalid vtable alias linkage");
993ec727ea7Spatrick 
994ec727ea7Spatrick   llvm::GlobalAlias *VTableAlias = CGM.getModule().getNamedAlias(AliasName);
995ec727ea7Spatrick   if (!VTableAlias) {
996ec727ea7Spatrick     VTableAlias = llvm::GlobalAlias::create(VTable->getValueType(),
997ec727ea7Spatrick                                             VTable->getAddressSpace(), Linkage,
998ec727ea7Spatrick                                             AliasName, &CGM.getModule());
999ec727ea7Spatrick   } else {
1000ec727ea7Spatrick     assert(VTableAlias->getValueType() == VTable->getValueType());
1001ec727ea7Spatrick     assert(VTableAlias->getLinkage() == Linkage);
1002ec727ea7Spatrick   }
1003ec727ea7Spatrick   VTableAlias->setVisibility(VTable->getVisibility());
1004ec727ea7Spatrick   VTableAlias->setUnnamedAddr(VTable->getUnnamedAddr());
1005ec727ea7Spatrick 
1006ec727ea7Spatrick   // Both of these imply dso_local for the vtable.
1007ec727ea7Spatrick   if (!VTable->hasComdat()) {
1008ec727ea7Spatrick     // If this is in a comdat, then we shouldn't make the linkage private due to
1009ec727ea7Spatrick     // an issue in lld where private symbols can be used as the key symbol when
1010ec727ea7Spatrick     // choosing the prevelant group. This leads to "relocation refers to a
1011ec727ea7Spatrick     // symbol in a discarded section".
1012ec727ea7Spatrick     VTable->setLinkage(llvm::GlobalValue::PrivateLinkage);
1013ec727ea7Spatrick   } else {
1014ec727ea7Spatrick     // We should at least make this hidden since we don't want to expose it.
1015ec727ea7Spatrick     VTable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1016ec727ea7Spatrick   }
1017ec727ea7Spatrick 
1018ec727ea7Spatrick   VTableAlias->setAliasee(VTable);
1019ec727ea7Spatrick }
1020ec727ea7Spatrick 
shouldEmitAvailableExternallyVTable(const CodeGenModule & CGM,const CXXRecordDecl * RD)1021e5dd7070Spatrick static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
1022e5dd7070Spatrick                                                 const CXXRecordDecl *RD) {
1023e5dd7070Spatrick   return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1024e5dd7070Spatrick          CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
1025e5dd7070Spatrick }
1026e5dd7070Spatrick 
1027e5dd7070Spatrick /// Compute the required linkage of the vtable for the given class.
1028e5dd7070Spatrick ///
1029e5dd7070Spatrick /// Note that we only call this at the end of the translation unit.
1030e5dd7070Spatrick llvm::GlobalVariable::LinkageTypes
getVTableLinkage(const CXXRecordDecl * RD)1031e5dd7070Spatrick CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1032e5dd7070Spatrick   if (!RD->isExternallyVisible())
1033e5dd7070Spatrick     return llvm::GlobalVariable::InternalLinkage;
1034e5dd7070Spatrick 
1035e5dd7070Spatrick   // We're at the end of the translation unit, so the current key
1036e5dd7070Spatrick   // function is fully correct.
1037e5dd7070Spatrick   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
1038e5dd7070Spatrick   if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
1039e5dd7070Spatrick     // If this class has a key function, use that to determine the
1040e5dd7070Spatrick     // linkage of the vtable.
1041e5dd7070Spatrick     const FunctionDecl *def = nullptr;
1042e5dd7070Spatrick     if (keyFunction->hasBody(def))
1043e5dd7070Spatrick       keyFunction = cast<CXXMethodDecl>(def);
1044e5dd7070Spatrick 
1045e5dd7070Spatrick     switch (keyFunction->getTemplateSpecializationKind()) {
1046e5dd7070Spatrick       case TSK_Undeclared:
1047e5dd7070Spatrick       case TSK_ExplicitSpecialization:
1048e5dd7070Spatrick         assert((def || CodeGenOpts.OptimizationLevel > 0 ||
1049e5dd7070Spatrick                 CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo) &&
1050e5dd7070Spatrick                "Shouldn't query vtable linkage without key function, "
1051e5dd7070Spatrick                "optimizations, or debug info");
1052e5dd7070Spatrick         if (!def && CodeGenOpts.OptimizationLevel > 0)
1053e5dd7070Spatrick           return llvm::GlobalVariable::AvailableExternallyLinkage;
1054e5dd7070Spatrick 
1055e5dd7070Spatrick         if (keyFunction->isInlined())
1056e5dd7070Spatrick           return !Context.getLangOpts().AppleKext ?
1057e5dd7070Spatrick                    llvm::GlobalVariable::LinkOnceODRLinkage :
1058e5dd7070Spatrick                    llvm::Function::InternalLinkage;
1059e5dd7070Spatrick 
1060e5dd7070Spatrick         return llvm::GlobalVariable::ExternalLinkage;
1061e5dd7070Spatrick 
1062e5dd7070Spatrick       case TSK_ImplicitInstantiation:
1063e5dd7070Spatrick         return !Context.getLangOpts().AppleKext ?
1064e5dd7070Spatrick                  llvm::GlobalVariable::LinkOnceODRLinkage :
1065e5dd7070Spatrick                  llvm::Function::InternalLinkage;
1066e5dd7070Spatrick 
1067e5dd7070Spatrick       case TSK_ExplicitInstantiationDefinition:
1068e5dd7070Spatrick         return !Context.getLangOpts().AppleKext ?
1069e5dd7070Spatrick                  llvm::GlobalVariable::WeakODRLinkage :
1070e5dd7070Spatrick                  llvm::Function::InternalLinkage;
1071e5dd7070Spatrick 
1072e5dd7070Spatrick       case TSK_ExplicitInstantiationDeclaration:
1073e5dd7070Spatrick         llvm_unreachable("Should not have been asked to emit this");
1074e5dd7070Spatrick     }
1075e5dd7070Spatrick   }
1076e5dd7070Spatrick 
1077e5dd7070Spatrick   // -fapple-kext mode does not support weak linkage, so we must use
1078e5dd7070Spatrick   // internal linkage.
1079e5dd7070Spatrick   if (Context.getLangOpts().AppleKext)
1080e5dd7070Spatrick     return llvm::Function::InternalLinkage;
1081e5dd7070Spatrick 
1082e5dd7070Spatrick   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
1083e5dd7070Spatrick       llvm::GlobalValue::LinkOnceODRLinkage;
1084e5dd7070Spatrick   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
1085e5dd7070Spatrick       llvm::GlobalValue::WeakODRLinkage;
1086e5dd7070Spatrick   if (RD->hasAttr<DLLExportAttr>()) {
1087e5dd7070Spatrick     // Cannot discard exported vtables.
1088e5dd7070Spatrick     DiscardableODRLinkage = NonDiscardableODRLinkage;
1089e5dd7070Spatrick   } else if (RD->hasAttr<DLLImportAttr>()) {
1090e5dd7070Spatrick     // Imported vtables are available externally.
1091e5dd7070Spatrick     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1092e5dd7070Spatrick     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
1093e5dd7070Spatrick   }
1094e5dd7070Spatrick 
1095e5dd7070Spatrick   switch (RD->getTemplateSpecializationKind()) {
1096e5dd7070Spatrick     case TSK_Undeclared:
1097e5dd7070Spatrick     case TSK_ExplicitSpecialization:
1098e5dd7070Spatrick     case TSK_ImplicitInstantiation:
1099e5dd7070Spatrick       return DiscardableODRLinkage;
1100e5dd7070Spatrick 
1101e5dd7070Spatrick     case TSK_ExplicitInstantiationDeclaration:
1102e5dd7070Spatrick       // Explicit instantiations in MSVC do not provide vtables, so we must emit
1103e5dd7070Spatrick       // our own.
1104e5dd7070Spatrick       if (getTarget().getCXXABI().isMicrosoft())
1105e5dd7070Spatrick         return DiscardableODRLinkage;
1106e5dd7070Spatrick       return shouldEmitAvailableExternallyVTable(*this, RD)
1107e5dd7070Spatrick                  ? llvm::GlobalVariable::AvailableExternallyLinkage
1108e5dd7070Spatrick                  : llvm::GlobalVariable::ExternalLinkage;
1109e5dd7070Spatrick 
1110e5dd7070Spatrick     case TSK_ExplicitInstantiationDefinition:
1111e5dd7070Spatrick       return NonDiscardableODRLinkage;
1112e5dd7070Spatrick   }
1113e5dd7070Spatrick 
1114e5dd7070Spatrick   llvm_unreachable("Invalid TemplateSpecializationKind!");
1115e5dd7070Spatrick }
1116e5dd7070Spatrick 
1117e5dd7070Spatrick /// This is a callback from Sema to tell us that a particular vtable is
1118e5dd7070Spatrick /// required to be emitted in this translation unit.
1119e5dd7070Spatrick ///
1120e5dd7070Spatrick /// This is only called for vtables that _must_ be emitted (mainly due to key
1121e5dd7070Spatrick /// functions).  For weak vtables, CodeGen tracks when they are needed and
1122e5dd7070Spatrick /// emits them as-needed.
EmitVTable(CXXRecordDecl * theClass)1123e5dd7070Spatrick void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
1124e5dd7070Spatrick   VTables.GenerateClassData(theClass);
1125e5dd7070Spatrick }
1126e5dd7070Spatrick 
1127e5dd7070Spatrick void
GenerateClassData(const CXXRecordDecl * RD)1128e5dd7070Spatrick CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
1129e5dd7070Spatrick   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
1130e5dd7070Spatrick     DI->completeClassData(RD);
1131e5dd7070Spatrick 
1132e5dd7070Spatrick   if (RD->getNumVBases())
1133e5dd7070Spatrick     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
1134e5dd7070Spatrick 
1135e5dd7070Spatrick   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
1136e5dd7070Spatrick }
1137e5dd7070Spatrick 
1138e5dd7070Spatrick /// At this point in the translation unit, does it appear that can we
1139e5dd7070Spatrick /// rely on the vtable being defined elsewhere in the program?
1140e5dd7070Spatrick ///
1141e5dd7070Spatrick /// The response is really only definitive when called at the end of
1142e5dd7070Spatrick /// the translation unit.
1143e5dd7070Spatrick ///
1144e5dd7070Spatrick /// The only semantic restriction here is that the object file should
1145e5dd7070Spatrick /// not contain a vtable definition when that vtable is defined
1146e5dd7070Spatrick /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
1147e5dd7070Spatrick /// vtables when unnecessary.
isVTableExternal(const CXXRecordDecl * RD)1148e5dd7070Spatrick bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
1149e5dd7070Spatrick   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
1150e5dd7070Spatrick 
1151e5dd7070Spatrick   // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
1152e5dd7070Spatrick   // emit them even if there is an explicit template instantiation.
1153e5dd7070Spatrick   if (CGM.getTarget().getCXXABI().isMicrosoft())
1154e5dd7070Spatrick     return false;
1155e5dd7070Spatrick 
1156e5dd7070Spatrick   // If we have an explicit instantiation declaration (and not a
1157e5dd7070Spatrick   // definition), the vtable is defined elsewhere.
1158e5dd7070Spatrick   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1159e5dd7070Spatrick   if (TSK == TSK_ExplicitInstantiationDeclaration)
1160e5dd7070Spatrick     return true;
1161e5dd7070Spatrick 
1162e5dd7070Spatrick   // Otherwise, if the class is an instantiated template, the
1163e5dd7070Spatrick   // vtable must be defined here.
1164e5dd7070Spatrick   if (TSK == TSK_ImplicitInstantiation ||
1165e5dd7070Spatrick       TSK == TSK_ExplicitInstantiationDefinition)
1166e5dd7070Spatrick     return false;
1167e5dd7070Spatrick 
1168e5dd7070Spatrick   // Otherwise, if the class doesn't have a key function (possibly
1169e5dd7070Spatrick   // anymore), the vtable must be defined here.
1170e5dd7070Spatrick   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
1171e5dd7070Spatrick   if (!keyFunction)
1172e5dd7070Spatrick     return false;
1173e5dd7070Spatrick 
1174e5dd7070Spatrick   // Otherwise, if we don't have a definition of the key function, the
1175e5dd7070Spatrick   // vtable must be defined somewhere else.
1176e5dd7070Spatrick   return !keyFunction->hasBody();
1177e5dd7070Spatrick }
1178e5dd7070Spatrick 
1179e5dd7070Spatrick /// Given that we're currently at the end of the translation unit, and
1180e5dd7070Spatrick /// we've emitted a reference to the vtable for this class, should
1181e5dd7070Spatrick /// we define that vtable?
shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule & CGM,const CXXRecordDecl * RD)1182e5dd7070Spatrick static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
1183e5dd7070Spatrick                                                    const CXXRecordDecl *RD) {
1184e5dd7070Spatrick   // If vtable is internal then it has to be done.
1185e5dd7070Spatrick   if (!CGM.getVTables().isVTableExternal(RD))
1186e5dd7070Spatrick     return true;
1187e5dd7070Spatrick 
1188e5dd7070Spatrick   // If it's external then maybe we will need it as available_externally.
1189e5dd7070Spatrick   return shouldEmitAvailableExternallyVTable(CGM, RD);
1190e5dd7070Spatrick }
1191e5dd7070Spatrick 
1192e5dd7070Spatrick /// Given that at some point we emitted a reference to one or more
1193e5dd7070Spatrick /// vtables, and that we are now at the end of the translation unit,
1194e5dd7070Spatrick /// decide whether we should emit them.
EmitDeferredVTables()1195e5dd7070Spatrick void CodeGenModule::EmitDeferredVTables() {
1196e5dd7070Spatrick #ifndef NDEBUG
1197e5dd7070Spatrick   // Remember the size of DeferredVTables, because we're going to assume
1198e5dd7070Spatrick   // that this entire operation doesn't modify it.
1199e5dd7070Spatrick   size_t savedSize = DeferredVTables.size();
1200e5dd7070Spatrick #endif
1201e5dd7070Spatrick 
1202e5dd7070Spatrick   for (const CXXRecordDecl *RD : DeferredVTables)
1203e5dd7070Spatrick     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
1204e5dd7070Spatrick       VTables.GenerateClassData(RD);
1205e5dd7070Spatrick     else if (shouldOpportunisticallyEmitVTables())
1206e5dd7070Spatrick       OpportunisticVTables.push_back(RD);
1207e5dd7070Spatrick 
1208e5dd7070Spatrick   assert(savedSize == DeferredVTables.size() &&
1209e5dd7070Spatrick          "deferred extra vtables during vtable emission?");
1210e5dd7070Spatrick   DeferredVTables.clear();
1211e5dd7070Spatrick }
1212e5dd7070Spatrick 
AlwaysHasLTOVisibilityPublic(const CXXRecordDecl * RD)1213*12c85518Srobert bool CodeGenModule::AlwaysHasLTOVisibilityPublic(const CXXRecordDecl *RD) {
1214*12c85518Srobert   if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
1215*12c85518Srobert     return true;
1216*12c85518Srobert 
1217ec727ea7Spatrick   if (!getCodeGenOpts().LTOVisibilityPublicStd)
1218ec727ea7Spatrick     return false;
1219ec727ea7Spatrick 
1220ec727ea7Spatrick   const DeclContext *DC = RD;
1221*12c85518Srobert   while (true) {
1222ec727ea7Spatrick     auto *D = cast<Decl>(DC);
1223ec727ea7Spatrick     DC = DC->getParent();
1224ec727ea7Spatrick     if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
1225ec727ea7Spatrick       if (auto *ND = dyn_cast<NamespaceDecl>(D))
1226ec727ea7Spatrick         if (const IdentifierInfo *II = ND->getIdentifier())
1227ec727ea7Spatrick           if (II->isStr("std") || II->isStr("stdext"))
1228ec727ea7Spatrick             return true;
1229ec727ea7Spatrick       break;
1230ec727ea7Spatrick     }
1231ec727ea7Spatrick   }
1232ec727ea7Spatrick 
1233ec727ea7Spatrick   return false;
1234ec727ea7Spatrick }
1235ec727ea7Spatrick 
HasHiddenLTOVisibility(const CXXRecordDecl * RD)1236e5dd7070Spatrick bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
1237e5dd7070Spatrick   LinkageInfo LV = RD->getLinkageAndVisibility();
1238e5dd7070Spatrick   if (!isExternallyVisible(LV.getLinkage()))
1239e5dd7070Spatrick     return true;
1240e5dd7070Spatrick 
1241e5dd7070Spatrick   if (getTriple().isOSBinFormatCOFF()) {
1242e5dd7070Spatrick     if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
1243e5dd7070Spatrick       return false;
1244e5dd7070Spatrick   } else {
1245e5dd7070Spatrick     if (LV.getVisibility() != HiddenVisibility)
1246e5dd7070Spatrick       return false;
1247e5dd7070Spatrick   }
1248e5dd7070Spatrick 
1249*12c85518Srobert   return !AlwaysHasLTOVisibilityPublic(RD);
1250e5dd7070Spatrick }
1251e5dd7070Spatrick 
GetVCallVisibilityLevel(const CXXRecordDecl * RD,llvm::DenseSet<const CXXRecordDecl * > & Visited)1252a9ac8606Spatrick llvm::GlobalObject::VCallVisibility CodeGenModule::GetVCallVisibilityLevel(
1253a9ac8606Spatrick     const CXXRecordDecl *RD, llvm::DenseSet<const CXXRecordDecl *> &Visited) {
1254a9ac8606Spatrick   // If we have already visited this RD (which means this is a recursive call
1255a9ac8606Spatrick   // since the initial call should have an empty Visited set), return the max
1256a9ac8606Spatrick   // visibility. The recursive calls below compute the min between the result
1257a9ac8606Spatrick   // of the recursive call and the current TypeVis, so returning the max here
1258a9ac8606Spatrick   // ensures that it will have no effect on the current TypeVis.
1259a9ac8606Spatrick   if (!Visited.insert(RD).second)
1260a9ac8606Spatrick     return llvm::GlobalObject::VCallVisibilityTranslationUnit;
1261a9ac8606Spatrick 
1262e5dd7070Spatrick   LinkageInfo LV = RD->getLinkageAndVisibility();
1263e5dd7070Spatrick   llvm::GlobalObject::VCallVisibility TypeVis;
1264e5dd7070Spatrick   if (!isExternallyVisible(LV.getLinkage()))
1265e5dd7070Spatrick     TypeVis = llvm::GlobalObject::VCallVisibilityTranslationUnit;
1266e5dd7070Spatrick   else if (HasHiddenLTOVisibility(RD))
1267e5dd7070Spatrick     TypeVis = llvm::GlobalObject::VCallVisibilityLinkageUnit;
1268e5dd7070Spatrick   else
1269e5dd7070Spatrick     TypeVis = llvm::GlobalObject::VCallVisibilityPublic;
1270e5dd7070Spatrick 
1271e5dd7070Spatrick   for (auto B : RD->bases())
1272e5dd7070Spatrick     if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1273a9ac8606Spatrick       TypeVis = std::min(
1274a9ac8606Spatrick           TypeVis,
1275a9ac8606Spatrick           GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1276e5dd7070Spatrick 
1277e5dd7070Spatrick   for (auto B : RD->vbases())
1278e5dd7070Spatrick     if (B.getType()->getAsCXXRecordDecl()->isDynamicClass())
1279a9ac8606Spatrick       TypeVis = std::min(
1280a9ac8606Spatrick           TypeVis,
1281a9ac8606Spatrick           GetVCallVisibilityLevel(B.getType()->getAsCXXRecordDecl(), Visited));
1282e5dd7070Spatrick 
1283e5dd7070Spatrick   return TypeVis;
1284e5dd7070Spatrick }
1285e5dd7070Spatrick 
EmitVTableTypeMetadata(const CXXRecordDecl * RD,llvm::GlobalVariable * VTable,const VTableLayout & VTLayout)1286e5dd7070Spatrick void CodeGenModule::EmitVTableTypeMetadata(const CXXRecordDecl *RD,
1287e5dd7070Spatrick                                            llvm::GlobalVariable *VTable,
1288e5dd7070Spatrick                                            const VTableLayout &VTLayout) {
1289e5dd7070Spatrick   if (!getCodeGenOpts().LTOUnit)
1290e5dd7070Spatrick     return;
1291e5dd7070Spatrick 
1292*12c85518Srobert   CharUnits ComponentWidth = GetTargetTypeStoreSize(getVTableComponentType());
1293e5dd7070Spatrick 
1294e5dd7070Spatrick   typedef std::pair<const CXXRecordDecl *, unsigned> AddressPoint;
1295e5dd7070Spatrick   std::vector<AddressPoint> AddressPoints;
1296e5dd7070Spatrick   for (auto &&AP : VTLayout.getAddressPoints())
1297e5dd7070Spatrick     AddressPoints.push_back(std::make_pair(
1298e5dd7070Spatrick         AP.first.getBase(), VTLayout.getVTableOffset(AP.second.VTableIndex) +
1299e5dd7070Spatrick                                 AP.second.AddressPointIndex));
1300e5dd7070Spatrick 
1301e5dd7070Spatrick   // Sort the address points for determinism.
1302e5dd7070Spatrick   llvm::sort(AddressPoints, [this](const AddressPoint &AP1,
1303e5dd7070Spatrick                                    const AddressPoint &AP2) {
1304e5dd7070Spatrick     if (&AP1 == &AP2)
1305e5dd7070Spatrick       return false;
1306e5dd7070Spatrick 
1307e5dd7070Spatrick     std::string S1;
1308e5dd7070Spatrick     llvm::raw_string_ostream O1(S1);
1309e5dd7070Spatrick     getCXXABI().getMangleContext().mangleTypeName(
1310e5dd7070Spatrick         QualType(AP1.first->getTypeForDecl(), 0), O1);
1311e5dd7070Spatrick     O1.flush();
1312e5dd7070Spatrick 
1313e5dd7070Spatrick     std::string S2;
1314e5dd7070Spatrick     llvm::raw_string_ostream O2(S2);
1315e5dd7070Spatrick     getCXXABI().getMangleContext().mangleTypeName(
1316e5dd7070Spatrick         QualType(AP2.first->getTypeForDecl(), 0), O2);
1317e5dd7070Spatrick     O2.flush();
1318e5dd7070Spatrick 
1319e5dd7070Spatrick     if (S1 < S2)
1320e5dd7070Spatrick       return true;
1321e5dd7070Spatrick     if (S1 != S2)
1322e5dd7070Spatrick       return false;
1323e5dd7070Spatrick 
1324e5dd7070Spatrick     return AP1.second < AP2.second;
1325e5dd7070Spatrick   });
1326e5dd7070Spatrick 
1327e5dd7070Spatrick   ArrayRef<VTableComponent> Comps = VTLayout.vtable_components();
1328e5dd7070Spatrick   for (auto AP : AddressPoints) {
1329e5dd7070Spatrick     // Create type metadata for the address point.
1330*12c85518Srobert     AddVTableTypeMetadata(VTable, ComponentWidth * AP.second, AP.first);
1331e5dd7070Spatrick 
1332e5dd7070Spatrick     // The class associated with each address point could also potentially be
1333e5dd7070Spatrick     // used for indirect calls via a member function pointer, so we need to
1334e5dd7070Spatrick     // annotate the address of each function pointer with the appropriate member
1335e5dd7070Spatrick     // function pointer type.
1336e5dd7070Spatrick     for (unsigned I = 0; I != Comps.size(); ++I) {
1337e5dd7070Spatrick       if (Comps[I].getKind() != VTableComponent::CK_FunctionPointer)
1338e5dd7070Spatrick         continue;
1339e5dd7070Spatrick       llvm::Metadata *MD = CreateMetadataIdentifierForVirtualMemPtrType(
1340e5dd7070Spatrick           Context.getMemberPointerType(
1341e5dd7070Spatrick               Comps[I].getFunctionDecl()->getType(),
1342e5dd7070Spatrick               Context.getRecordType(AP.first).getTypePtr()));
1343*12c85518Srobert       VTable->addTypeMetadata((ComponentWidth * I).getQuantity(), MD);
1344e5dd7070Spatrick     }
1345e5dd7070Spatrick   }
1346e5dd7070Spatrick 
1347ec727ea7Spatrick   if (getCodeGenOpts().VirtualFunctionElimination ||
1348ec727ea7Spatrick       getCodeGenOpts().WholeProgramVTables) {
1349a9ac8606Spatrick     llvm::DenseSet<const CXXRecordDecl *> Visited;
1350a9ac8606Spatrick     llvm::GlobalObject::VCallVisibility TypeVis =
1351a9ac8606Spatrick         GetVCallVisibilityLevel(RD, Visited);
1352e5dd7070Spatrick     if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
1353ec727ea7Spatrick       VTable->setVCallVisibilityMetadata(TypeVis);
1354e5dd7070Spatrick   }
1355e5dd7070Spatrick }
1356