xref: /aosp_15_r20/external/clang/lib/CodeGen/CGVTables.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This contains code dealing with C++ code generation of virtual tables.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li 
14*67e74705SXin Li #include "CodeGenFunction.h"
15*67e74705SXin Li #include "CGCXXABI.h"
16*67e74705SXin Li #include "CodeGenModule.h"
17*67e74705SXin Li #include "clang/AST/CXXInheritance.h"
18*67e74705SXin Li #include "clang/AST/RecordLayout.h"
19*67e74705SXin Li #include "clang/CodeGen/CGFunctionInfo.h"
20*67e74705SXin Li #include "clang/Frontend/CodeGenOptions.h"
21*67e74705SXin Li #include "llvm/ADT/DenseSet.h"
22*67e74705SXin Li #include "llvm/ADT/SetVector.h"
23*67e74705SXin Li #include "llvm/Support/Compiler.h"
24*67e74705SXin Li #include "llvm/Support/Format.h"
25*67e74705SXin Li #include "llvm/Transforms/Utils/Cloning.h"
26*67e74705SXin Li #include <algorithm>
27*67e74705SXin Li #include <cstdio>
28*67e74705SXin Li 
29*67e74705SXin Li using namespace clang;
30*67e74705SXin Li using namespace CodeGen;
31*67e74705SXin Li 
CodeGenVTables(CodeGenModule & CGM)32*67e74705SXin Li CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
33*67e74705SXin Li     : CGM(CGM), VTContext(CGM.getContext().getVTableContext()) {}
34*67e74705SXin Li 
GetAddrOfThunk(GlobalDecl GD,const ThunkInfo & Thunk)35*67e74705SXin Li llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
36*67e74705SXin Li                                               const ThunkInfo &Thunk) {
37*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
38*67e74705SXin Li 
39*67e74705SXin Li   // Compute the mangled name.
40*67e74705SXin Li   SmallString<256> Name;
41*67e74705SXin Li   llvm::raw_svector_ostream Out(Name);
42*67e74705SXin Li   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
43*67e74705SXin Li     getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
44*67e74705SXin Li                                                       Thunk.This, Out);
45*67e74705SXin Li   else
46*67e74705SXin Li     getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
47*67e74705SXin Li 
48*67e74705SXin Li   llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
49*67e74705SXin Li   return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
50*67e74705SXin Li                                  /*DontDefer=*/true, /*IsThunk=*/true);
51*67e74705SXin Li }
52*67e74705SXin Li 
setThunkVisibility(CodeGenModule & CGM,const CXXMethodDecl * MD,const ThunkInfo & Thunk,llvm::Function * Fn)53*67e74705SXin Li static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
54*67e74705SXin Li                                const ThunkInfo &Thunk, llvm::Function *Fn) {
55*67e74705SXin Li   CGM.setGlobalVisibility(Fn, MD);
56*67e74705SXin Li }
57*67e74705SXin Li 
setThunkProperties(CodeGenModule & CGM,const ThunkInfo & Thunk,llvm::Function * ThunkFn,bool ForVTable,GlobalDecl GD)58*67e74705SXin Li static void setThunkProperties(CodeGenModule &CGM, const ThunkInfo &Thunk,
59*67e74705SXin Li                                llvm::Function *ThunkFn, bool ForVTable,
60*67e74705SXin Li                                GlobalDecl GD) {
61*67e74705SXin Li   CGM.setFunctionLinkage(GD, ThunkFn);
62*67e74705SXin Li   CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
63*67e74705SXin Li                                   !Thunk.Return.isEmpty());
64*67e74705SXin Li 
65*67e74705SXin Li   // Set the right visibility.
66*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
67*67e74705SXin Li   setThunkVisibility(CGM, MD, Thunk, ThunkFn);
68*67e74705SXin Li 
69*67e74705SXin Li   if (CGM.supportsCOMDAT() && ThunkFn->isWeakForLinker())
70*67e74705SXin Li     ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
71*67e74705SXin Li }
72*67e74705SXin Li 
73*67e74705SXin Li #ifndef NDEBUG
similar(const ABIArgInfo & infoL,CanQualType typeL,const ABIArgInfo & infoR,CanQualType typeR)74*67e74705SXin Li static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
75*67e74705SXin Li                     const ABIArgInfo &infoR, CanQualType typeR) {
76*67e74705SXin Li   return (infoL.getKind() == infoR.getKind() &&
77*67e74705SXin Li           (typeL == typeR ||
78*67e74705SXin Li            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
79*67e74705SXin Li            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
80*67e74705SXin Li }
81*67e74705SXin Li #endif
82*67e74705SXin Li 
PerformReturnAdjustment(CodeGenFunction & CGF,QualType ResultType,RValue RV,const ThunkInfo & Thunk)83*67e74705SXin Li static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
84*67e74705SXin Li                                       QualType ResultType, RValue RV,
85*67e74705SXin Li                                       const ThunkInfo &Thunk) {
86*67e74705SXin Li   // Emit the return adjustment.
87*67e74705SXin Li   bool NullCheckValue = !ResultType->isReferenceType();
88*67e74705SXin Li 
89*67e74705SXin Li   llvm::BasicBlock *AdjustNull = nullptr;
90*67e74705SXin Li   llvm::BasicBlock *AdjustNotNull = nullptr;
91*67e74705SXin Li   llvm::BasicBlock *AdjustEnd = nullptr;
92*67e74705SXin Li 
93*67e74705SXin Li   llvm::Value *ReturnValue = RV.getScalarVal();
94*67e74705SXin Li 
95*67e74705SXin Li   if (NullCheckValue) {
96*67e74705SXin Li     AdjustNull = CGF.createBasicBlock("adjust.null");
97*67e74705SXin Li     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
98*67e74705SXin Li     AdjustEnd = CGF.createBasicBlock("adjust.end");
99*67e74705SXin Li 
100*67e74705SXin Li     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
101*67e74705SXin Li     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
102*67e74705SXin Li     CGF.EmitBlock(AdjustNotNull);
103*67e74705SXin Li   }
104*67e74705SXin Li 
105*67e74705SXin Li   auto ClassDecl = ResultType->getPointeeType()->getAsCXXRecordDecl();
106*67e74705SXin Li   auto ClassAlign = CGF.CGM.getClassPointerAlignment(ClassDecl);
107*67e74705SXin Li   ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF,
108*67e74705SXin Li                                             Address(ReturnValue, ClassAlign),
109*67e74705SXin Li                                             Thunk.Return);
110*67e74705SXin Li 
111*67e74705SXin Li   if (NullCheckValue) {
112*67e74705SXin Li     CGF.Builder.CreateBr(AdjustEnd);
113*67e74705SXin Li     CGF.EmitBlock(AdjustNull);
114*67e74705SXin Li     CGF.Builder.CreateBr(AdjustEnd);
115*67e74705SXin Li     CGF.EmitBlock(AdjustEnd);
116*67e74705SXin Li 
117*67e74705SXin Li     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
118*67e74705SXin Li     PHI->addIncoming(ReturnValue, AdjustNotNull);
119*67e74705SXin Li     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
120*67e74705SXin Li                      AdjustNull);
121*67e74705SXin Li     ReturnValue = PHI;
122*67e74705SXin Li   }
123*67e74705SXin Li 
124*67e74705SXin Li   return RValue::get(ReturnValue);
125*67e74705SXin Li }
126*67e74705SXin Li 
127*67e74705SXin Li // This function does roughly the same thing as GenerateThunk, but in a
128*67e74705SXin Li // very different way, so that va_start and va_end work correctly.
129*67e74705SXin Li // FIXME: This function assumes "this" is the first non-sret LLVM argument of
130*67e74705SXin Li //        a function, and that there is an alloca built in the entry block
131*67e74705SXin Li //        for all accesses to "this".
132*67e74705SXin Li // FIXME: This function assumes there is only one "ret" statement per function.
133*67e74705SXin Li // FIXME: Cloning isn't correct in the presence of indirect goto!
134*67e74705SXin Li // FIXME: This implementation of thunks bloats codesize by duplicating the
135*67e74705SXin Li //        function definition.  There are alternatives:
136*67e74705SXin Li //        1. Add some sort of stub support to LLVM for cases where we can
137*67e74705SXin Li //           do a this adjustment, then a sibcall.
138*67e74705SXin Li //        2. We could transform the definition to take a va_list instead of an
139*67e74705SXin Li //           actual variable argument list, then have the thunks (including a
140*67e74705SXin Li //           no-op thunk for the regular definition) call va_start/va_end.
141*67e74705SXin Li //           There's a bit of per-call overhead for this solution, but it's
142*67e74705SXin Li //           better for codesize if the definition is long.
143*67e74705SXin Li llvm::Function *
GenerateVarArgsThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk)144*67e74705SXin Li CodeGenFunction::GenerateVarArgsThunk(llvm::Function *Fn,
145*67e74705SXin Li                                       const CGFunctionInfo &FnInfo,
146*67e74705SXin Li                                       GlobalDecl GD, const ThunkInfo &Thunk) {
147*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
148*67e74705SXin Li   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
149*67e74705SXin Li   QualType ResultType = FPT->getReturnType();
150*67e74705SXin Li 
151*67e74705SXin Li   // Get the original function
152*67e74705SXin Li   assert(FnInfo.isVariadic());
153*67e74705SXin Li   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
154*67e74705SXin Li   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
155*67e74705SXin Li   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
156*67e74705SXin Li 
157*67e74705SXin Li   // Clone to thunk.
158*67e74705SXin Li   llvm::ValueToValueMapTy VMap;
159*67e74705SXin Li   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap);
160*67e74705SXin Li   Fn->replaceAllUsesWith(NewFn);
161*67e74705SXin Li   NewFn->takeName(Fn);
162*67e74705SXin Li   Fn->eraseFromParent();
163*67e74705SXin Li   Fn = NewFn;
164*67e74705SXin Li 
165*67e74705SXin Li   // "Initialize" CGF (minimally).
166*67e74705SXin Li   CurFn = Fn;
167*67e74705SXin Li 
168*67e74705SXin Li   // Get the "this" value
169*67e74705SXin Li   llvm::Function::arg_iterator AI = Fn->arg_begin();
170*67e74705SXin Li   if (CGM.ReturnTypeUsesSRet(FnInfo))
171*67e74705SXin Li     ++AI;
172*67e74705SXin Li 
173*67e74705SXin Li   // Find the first store of "this", which will be to the alloca associated
174*67e74705SXin Li   // with "this".
175*67e74705SXin Li   Address ThisPtr(&*AI, CGM.getClassPointerAlignment(MD->getParent()));
176*67e74705SXin Li   llvm::BasicBlock *EntryBB = &Fn->front();
177*67e74705SXin Li   llvm::BasicBlock::iterator ThisStore =
178*67e74705SXin Li       std::find_if(EntryBB->begin(), EntryBB->end(), [&](llvm::Instruction &I) {
179*67e74705SXin Li         return isa<llvm::StoreInst>(I) &&
180*67e74705SXin Li                I.getOperand(0) == ThisPtr.getPointer();
181*67e74705SXin Li       });
182*67e74705SXin Li   assert(ThisStore != EntryBB->end() &&
183*67e74705SXin Li          "Store of this should be in entry block?");
184*67e74705SXin Li   // Adjust "this", if necessary.
185*67e74705SXin Li   Builder.SetInsertPoint(&*ThisStore);
186*67e74705SXin Li   llvm::Value *AdjustedThisPtr =
187*67e74705SXin Li       CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
188*67e74705SXin Li   ThisStore->setOperand(0, AdjustedThisPtr);
189*67e74705SXin Li 
190*67e74705SXin Li   if (!Thunk.Return.isEmpty()) {
191*67e74705SXin Li     // Fix up the returned value, if necessary.
192*67e74705SXin Li     for (llvm::BasicBlock &BB : *Fn) {
193*67e74705SXin Li       llvm::Instruction *T = BB.getTerminator();
194*67e74705SXin Li       if (isa<llvm::ReturnInst>(T)) {
195*67e74705SXin Li         RValue RV = RValue::get(T->getOperand(0));
196*67e74705SXin Li         T->eraseFromParent();
197*67e74705SXin Li         Builder.SetInsertPoint(&BB);
198*67e74705SXin Li         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
199*67e74705SXin Li         Builder.CreateRet(RV.getScalarVal());
200*67e74705SXin Li         break;
201*67e74705SXin Li       }
202*67e74705SXin Li     }
203*67e74705SXin Li   }
204*67e74705SXin Li 
205*67e74705SXin Li   return Fn;
206*67e74705SXin Li }
207*67e74705SXin Li 
StartThunk(llvm::Function * Fn,GlobalDecl GD,const CGFunctionInfo & FnInfo)208*67e74705SXin Li void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
209*67e74705SXin Li                                  const CGFunctionInfo &FnInfo) {
210*67e74705SXin Li   assert(!CurGD.getDecl() && "CurGD was already set!");
211*67e74705SXin Li   CurGD = GD;
212*67e74705SXin Li   CurFuncIsThunk = true;
213*67e74705SXin Li 
214*67e74705SXin Li   // Build FunctionArgs.
215*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
216*67e74705SXin Li   QualType ThisType = MD->getThisType(getContext());
217*67e74705SXin Li   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
218*67e74705SXin Li   QualType ResultType = CGM.getCXXABI().HasThisReturn(GD)
219*67e74705SXin Li                             ? ThisType
220*67e74705SXin Li                             : CGM.getCXXABI().hasMostDerivedReturn(GD)
221*67e74705SXin Li                                   ? CGM.getContext().VoidPtrTy
222*67e74705SXin Li                                   : FPT->getReturnType();
223*67e74705SXin Li   FunctionArgList FunctionArgs;
224*67e74705SXin Li 
225*67e74705SXin Li   // Create the implicit 'this' parameter declaration.
226*67e74705SXin Li   CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
227*67e74705SXin Li 
228*67e74705SXin Li   // Add the rest of the parameters.
229*67e74705SXin Li   FunctionArgs.append(MD->param_begin(), MD->param_end());
230*67e74705SXin Li 
231*67e74705SXin Li   if (isa<CXXDestructorDecl>(MD))
232*67e74705SXin Li     CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
233*67e74705SXin Li 
234*67e74705SXin Li   // Start defining the function.
235*67e74705SXin Li   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
236*67e74705SXin Li                 MD->getLocation(), MD->getLocation());
237*67e74705SXin Li 
238*67e74705SXin Li   // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
239*67e74705SXin Li   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
240*67e74705SXin Li   CXXThisValue = CXXABIThisValue;
241*67e74705SXin Li   CurCodeDecl = MD;
242*67e74705SXin Li   CurFuncDecl = MD;
243*67e74705SXin Li }
244*67e74705SXin Li 
FinishThunk()245*67e74705SXin Li void CodeGenFunction::FinishThunk() {
246*67e74705SXin Li   // Clear these to restore the invariants expected by
247*67e74705SXin Li   // StartFunction/FinishFunction.
248*67e74705SXin Li   CurCodeDecl = nullptr;
249*67e74705SXin Li   CurFuncDecl = nullptr;
250*67e74705SXin Li 
251*67e74705SXin Li   FinishFunction();
252*67e74705SXin Li }
253*67e74705SXin Li 
EmitCallAndReturnForThunk(llvm::Value * Callee,const ThunkInfo * Thunk)254*67e74705SXin Li void CodeGenFunction::EmitCallAndReturnForThunk(llvm::Value *Callee,
255*67e74705SXin Li                                                 const ThunkInfo *Thunk) {
256*67e74705SXin Li   assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
257*67e74705SXin Li          "Please use a new CGF for this thunk");
258*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(CurGD.getDecl());
259*67e74705SXin Li 
260*67e74705SXin Li   // Adjust the 'this' pointer if necessary
261*67e74705SXin Li   llvm::Value *AdjustedThisPtr =
262*67e74705SXin Li     Thunk ? CGM.getCXXABI().performThisAdjustment(
263*67e74705SXin Li                           *this, LoadCXXThisAddress(), Thunk->This)
264*67e74705SXin Li           : LoadCXXThis();
265*67e74705SXin Li 
266*67e74705SXin Li   if (CurFnInfo->usesInAlloca()) {
267*67e74705SXin Li     // We don't handle return adjusting thunks, because they require us to call
268*67e74705SXin Li     // the copy constructor.  For now, fall through and pretend the return
269*67e74705SXin Li     // adjustment was empty so we don't crash.
270*67e74705SXin Li     if (Thunk && !Thunk->Return.isEmpty()) {
271*67e74705SXin Li       CGM.ErrorUnsupported(
272*67e74705SXin Li           MD, "non-trivial argument copy for return-adjusting thunk");
273*67e74705SXin Li     }
274*67e74705SXin Li     EmitMustTailThunk(MD, AdjustedThisPtr, Callee);
275*67e74705SXin Li     return;
276*67e74705SXin Li   }
277*67e74705SXin Li 
278*67e74705SXin Li   // Start building CallArgs.
279*67e74705SXin Li   CallArgList CallArgs;
280*67e74705SXin Li   QualType ThisType = MD->getThisType(getContext());
281*67e74705SXin Li   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
282*67e74705SXin Li 
283*67e74705SXin Li   if (isa<CXXDestructorDecl>(MD))
284*67e74705SXin Li     CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, CurGD, CallArgs);
285*67e74705SXin Li 
286*67e74705SXin Li   // Add the rest of the arguments.
287*67e74705SXin Li   for (const ParmVarDecl *PD : MD->parameters())
288*67e74705SXin Li     EmitDelegateCallArg(CallArgs, PD, PD->getLocStart());
289*67e74705SXin Li 
290*67e74705SXin Li   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
291*67e74705SXin Li 
292*67e74705SXin Li #ifndef NDEBUG
293*67e74705SXin Li   const CGFunctionInfo &CallFnInfo = CGM.getTypes().arrangeCXXMethodCall(
294*67e74705SXin Li       CallArgs, FPT, RequiredArgs::forPrototypePlus(FPT, 1, MD));
295*67e74705SXin Li   assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
296*67e74705SXin Li          CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
297*67e74705SXin Li          CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
298*67e74705SXin Li   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
299*67e74705SXin Li          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
300*67e74705SXin Li                  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
301*67e74705SXin Li   assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
302*67e74705SXin Li   for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
303*67e74705SXin Li     assert(similar(CallFnInfo.arg_begin()[i].info,
304*67e74705SXin Li                    CallFnInfo.arg_begin()[i].type,
305*67e74705SXin Li                    CurFnInfo->arg_begin()[i].info,
306*67e74705SXin Li                    CurFnInfo->arg_begin()[i].type));
307*67e74705SXin Li #endif
308*67e74705SXin Li 
309*67e74705SXin Li   // Determine whether we have a return value slot to use.
310*67e74705SXin Li   QualType ResultType = CGM.getCXXABI().HasThisReturn(CurGD)
311*67e74705SXin Li                             ? ThisType
312*67e74705SXin Li                             : CGM.getCXXABI().hasMostDerivedReturn(CurGD)
313*67e74705SXin Li                                   ? CGM.getContext().VoidPtrTy
314*67e74705SXin Li                                   : FPT->getReturnType();
315*67e74705SXin Li   ReturnValueSlot Slot;
316*67e74705SXin Li   if (!ResultType->isVoidType() &&
317*67e74705SXin Li       CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
318*67e74705SXin Li       !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
319*67e74705SXin Li     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
320*67e74705SXin Li 
321*67e74705SXin Li   // Now emit our call.
322*67e74705SXin Li   llvm::Instruction *CallOrInvoke;
323*67e74705SXin Li   RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD, &CallOrInvoke);
324*67e74705SXin Li 
325*67e74705SXin Li   // Consider return adjustment if we have ThunkInfo.
326*67e74705SXin Li   if (Thunk && !Thunk->Return.isEmpty())
327*67e74705SXin Li     RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
328*67e74705SXin Li   else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
329*67e74705SXin Li     Call->setTailCallKind(llvm::CallInst::TCK_Tail);
330*67e74705SXin Li 
331*67e74705SXin Li   // Emit return.
332*67e74705SXin Li   if (!ResultType->isVoidType() && Slot.isNull())
333*67e74705SXin Li     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
334*67e74705SXin Li 
335*67e74705SXin Li   // Disable the final ARC autorelease.
336*67e74705SXin Li   AutoreleaseResult = false;
337*67e74705SXin Li 
338*67e74705SXin Li   FinishThunk();
339*67e74705SXin Li }
340*67e74705SXin Li 
EmitMustTailThunk(const CXXMethodDecl * MD,llvm::Value * AdjustedThisPtr,llvm::Value * Callee)341*67e74705SXin Li void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
342*67e74705SXin Li                                         llvm::Value *AdjustedThisPtr,
343*67e74705SXin Li                                         llvm::Value *Callee) {
344*67e74705SXin Li   // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
345*67e74705SXin Li   // to translate AST arguments into LLVM IR arguments.  For thunks, we know
346*67e74705SXin Li   // that the caller prototype more or less matches the callee prototype with
347*67e74705SXin Li   // the exception of 'this'.
348*67e74705SXin Li   SmallVector<llvm::Value *, 8> Args;
349*67e74705SXin Li   for (llvm::Argument &A : CurFn->args())
350*67e74705SXin Li     Args.push_back(&A);
351*67e74705SXin Li 
352*67e74705SXin Li   // Set the adjusted 'this' pointer.
353*67e74705SXin Li   const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
354*67e74705SXin Li   if (ThisAI.isDirect()) {
355*67e74705SXin Li     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
356*67e74705SXin Li     int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
357*67e74705SXin Li     llvm::Type *ThisType = Args[ThisArgNo]->getType();
358*67e74705SXin Li     if (ThisType != AdjustedThisPtr->getType())
359*67e74705SXin Li       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
360*67e74705SXin Li     Args[ThisArgNo] = AdjustedThisPtr;
361*67e74705SXin Li   } else {
362*67e74705SXin Li     assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
363*67e74705SXin Li     Address ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
364*67e74705SXin Li     llvm::Type *ThisType = ThisAddr.getElementType();
365*67e74705SXin Li     if (ThisType != AdjustedThisPtr->getType())
366*67e74705SXin Li       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
367*67e74705SXin Li     Builder.CreateStore(AdjustedThisPtr, ThisAddr);
368*67e74705SXin Li   }
369*67e74705SXin Li 
370*67e74705SXin Li   // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
371*67e74705SXin Li   // don't actually want to run them.
372*67e74705SXin Li   llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
373*67e74705SXin Li   Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
374*67e74705SXin Li 
375*67e74705SXin Li   // Apply the standard set of call attributes.
376*67e74705SXin Li   unsigned CallingConv;
377*67e74705SXin Li   CodeGen::AttributeListType AttributeList;
378*67e74705SXin Li   CGM.ConstructAttributeList(Callee->getName(), *CurFnInfo, MD, AttributeList,
379*67e74705SXin Li                              CallingConv, /*AttrOnCallSite=*/true);
380*67e74705SXin Li   llvm::AttributeSet Attrs =
381*67e74705SXin Li       llvm::AttributeSet::get(getLLVMContext(), AttributeList);
382*67e74705SXin Li   Call->setAttributes(Attrs);
383*67e74705SXin Li   Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
384*67e74705SXin Li 
385*67e74705SXin Li   if (Call->getType()->isVoidTy())
386*67e74705SXin Li     Builder.CreateRetVoid();
387*67e74705SXin Li   else
388*67e74705SXin Li     Builder.CreateRet(Call);
389*67e74705SXin Li 
390*67e74705SXin Li   // Finish the function to maintain CodeGenFunction invariants.
391*67e74705SXin Li   // FIXME: Don't emit unreachable code.
392*67e74705SXin Li   EmitBlock(createBasicBlock());
393*67e74705SXin Li   FinishFunction();
394*67e74705SXin Li }
395*67e74705SXin Li 
generateThunk(llvm::Function * Fn,const CGFunctionInfo & FnInfo,GlobalDecl GD,const ThunkInfo & Thunk)396*67e74705SXin Li void CodeGenFunction::generateThunk(llvm::Function *Fn,
397*67e74705SXin Li                                     const CGFunctionInfo &FnInfo,
398*67e74705SXin Li                                     GlobalDecl GD, const ThunkInfo &Thunk) {
399*67e74705SXin Li   StartThunk(Fn, GD, FnInfo);
400*67e74705SXin Li 
401*67e74705SXin Li   // Get our callee.
402*67e74705SXin Li   llvm::Type *Ty =
403*67e74705SXin Li     CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
404*67e74705SXin Li   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
405*67e74705SXin Li 
406*67e74705SXin Li   // Make the call and return the result.
407*67e74705SXin Li   EmitCallAndReturnForThunk(Callee, &Thunk);
408*67e74705SXin Li }
409*67e74705SXin Li 
emitThunk(GlobalDecl GD,const ThunkInfo & Thunk,bool ForVTable)410*67e74705SXin Li void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
411*67e74705SXin Li                                bool ForVTable) {
412*67e74705SXin Li   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
413*67e74705SXin Li 
414*67e74705SXin Li   // FIXME: re-use FnInfo in this computation.
415*67e74705SXin Li   llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
416*67e74705SXin Li   llvm::GlobalValue *Entry;
417*67e74705SXin Li 
418*67e74705SXin Li   // Strip off a bitcast if we got one back.
419*67e74705SXin Li   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
420*67e74705SXin Li     assert(CE->getOpcode() == llvm::Instruction::BitCast);
421*67e74705SXin Li     Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
422*67e74705SXin Li   } else {
423*67e74705SXin Li     Entry = cast<llvm::GlobalValue>(C);
424*67e74705SXin Li   }
425*67e74705SXin Li 
426*67e74705SXin Li   // There's already a declaration with the same name, check if it has the same
427*67e74705SXin Li   // type or if we need to replace it.
428*67e74705SXin Li   if (Entry->getType()->getElementType() !=
429*67e74705SXin Li       CGM.getTypes().GetFunctionTypeForVTable(GD)) {
430*67e74705SXin Li     llvm::GlobalValue *OldThunkFn = Entry;
431*67e74705SXin Li 
432*67e74705SXin Li     // If the types mismatch then we have to rewrite the definition.
433*67e74705SXin Li     assert(OldThunkFn->isDeclaration() &&
434*67e74705SXin Li            "Shouldn't replace non-declaration");
435*67e74705SXin Li 
436*67e74705SXin Li     // Remove the name from the old thunk function and get a new thunk.
437*67e74705SXin Li     OldThunkFn->setName(StringRef());
438*67e74705SXin Li     Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
439*67e74705SXin Li 
440*67e74705SXin Li     // If needed, replace the old thunk with a bitcast.
441*67e74705SXin Li     if (!OldThunkFn->use_empty()) {
442*67e74705SXin Li       llvm::Constant *NewPtrForOldDecl =
443*67e74705SXin Li         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
444*67e74705SXin Li       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
445*67e74705SXin Li     }
446*67e74705SXin Li 
447*67e74705SXin Li     // Remove the old thunk.
448*67e74705SXin Li     OldThunkFn->eraseFromParent();
449*67e74705SXin Li   }
450*67e74705SXin Li 
451*67e74705SXin Li   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
452*67e74705SXin Li   bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
453*67e74705SXin Li   bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
454*67e74705SXin Li 
455*67e74705SXin Li   if (!ThunkFn->isDeclaration()) {
456*67e74705SXin Li     if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
457*67e74705SXin Li       // There is already a thunk emitted for this function, do nothing.
458*67e74705SXin Li       return;
459*67e74705SXin Li     }
460*67e74705SXin Li 
461*67e74705SXin Li     setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
462*67e74705SXin Li     return;
463*67e74705SXin Li   }
464*67e74705SXin Li 
465*67e74705SXin Li   CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
466*67e74705SXin Li 
467*67e74705SXin Li   if (ThunkFn->isVarArg()) {
468*67e74705SXin Li     // Varargs thunks are special; we can't just generate a call because
469*67e74705SXin Li     // we can't copy the varargs.  Our implementation is rather
470*67e74705SXin Li     // expensive/sucky at the moment, so don't generate the thunk unless
471*67e74705SXin Li     // we have to.
472*67e74705SXin Li     // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
473*67e74705SXin Li     if (UseAvailableExternallyLinkage)
474*67e74705SXin Li       return;
475*67e74705SXin Li     ThunkFn =
476*67e74705SXin Li         CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
477*67e74705SXin Li   } else {
478*67e74705SXin Li     // Normal thunk body generation.
479*67e74705SXin Li     CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
480*67e74705SXin Li   }
481*67e74705SXin Li 
482*67e74705SXin Li   setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
483*67e74705SXin Li }
484*67e74705SXin Li 
maybeEmitThunkForVTable(GlobalDecl GD,const ThunkInfo & Thunk)485*67e74705SXin Li void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
486*67e74705SXin Li                                              const ThunkInfo &Thunk) {
487*67e74705SXin Li   // If the ABI has key functions, only the TU with the key function should emit
488*67e74705SXin Li   // the thunk. However, we can allow inlining of thunks if we emit them with
489*67e74705SXin Li   // available_externally linkage together with vtables when optimizations are
490*67e74705SXin Li   // enabled.
491*67e74705SXin Li   if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
492*67e74705SXin Li       !CGM.getCodeGenOpts().OptimizationLevel)
493*67e74705SXin Li     return;
494*67e74705SXin Li 
495*67e74705SXin Li   // We can't emit thunks for member functions with incomplete types.
496*67e74705SXin Li   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
497*67e74705SXin Li   if (!CGM.getTypes().isFuncTypeConvertible(
498*67e74705SXin Li            MD->getType()->castAs<FunctionType>()))
499*67e74705SXin Li     return;
500*67e74705SXin Li 
501*67e74705SXin Li   emitThunk(GD, Thunk, /*ForVTable=*/true);
502*67e74705SXin Li }
503*67e74705SXin Li 
EmitThunks(GlobalDecl GD)504*67e74705SXin Li void CodeGenVTables::EmitThunks(GlobalDecl GD)
505*67e74705SXin Li {
506*67e74705SXin Li   const CXXMethodDecl *MD =
507*67e74705SXin Li     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
508*67e74705SXin Li 
509*67e74705SXin Li   // We don't need to generate thunks for the base destructor.
510*67e74705SXin Li   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
511*67e74705SXin Li     return;
512*67e74705SXin Li 
513*67e74705SXin Li   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
514*67e74705SXin Li       VTContext->getThunkInfo(GD);
515*67e74705SXin Li 
516*67e74705SXin Li   if (!ThunkInfoVector)
517*67e74705SXin Li     return;
518*67e74705SXin Li 
519*67e74705SXin Li   for (const ThunkInfo& Thunk : *ThunkInfoVector)
520*67e74705SXin Li     emitThunk(GD, Thunk, /*ForVTable=*/false);
521*67e74705SXin Li }
522*67e74705SXin Li 
CreateVTableInitializer(const CXXRecordDecl * RD,const VTableComponent * Components,unsigned NumComponents,const VTableLayout::VTableThunkTy * VTableThunks,unsigned NumVTableThunks,llvm::Constant * RTTI)523*67e74705SXin Li llvm::Constant *CodeGenVTables::CreateVTableInitializer(
524*67e74705SXin Li     const CXXRecordDecl *RD, const VTableComponent *Components,
525*67e74705SXin Li     unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
526*67e74705SXin Li     unsigned NumVTableThunks, llvm::Constant *RTTI) {
527*67e74705SXin Li   SmallVector<llvm::Constant *, 64> Inits;
528*67e74705SXin Li 
529*67e74705SXin Li   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
530*67e74705SXin Li 
531*67e74705SXin Li   llvm::Type *PtrDiffTy =
532*67e74705SXin Li     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
533*67e74705SXin Li 
534*67e74705SXin Li   unsigned NextVTableThunkIndex = 0;
535*67e74705SXin Li 
536*67e74705SXin Li   llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
537*67e74705SXin Li 
538*67e74705SXin Li   for (unsigned I = 0; I != NumComponents; ++I) {
539*67e74705SXin Li     VTableComponent Component = Components[I];
540*67e74705SXin Li 
541*67e74705SXin Li     llvm::Constant *Init = nullptr;
542*67e74705SXin Li 
543*67e74705SXin Li     switch (Component.getKind()) {
544*67e74705SXin Li     case VTableComponent::CK_VCallOffset:
545*67e74705SXin Li       Init = llvm::ConstantInt::get(PtrDiffTy,
546*67e74705SXin Li                                     Component.getVCallOffset().getQuantity());
547*67e74705SXin Li       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
548*67e74705SXin Li       break;
549*67e74705SXin Li     case VTableComponent::CK_VBaseOffset:
550*67e74705SXin Li       Init = llvm::ConstantInt::get(PtrDiffTy,
551*67e74705SXin Li                                     Component.getVBaseOffset().getQuantity());
552*67e74705SXin Li       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
553*67e74705SXin Li       break;
554*67e74705SXin Li     case VTableComponent::CK_OffsetToTop:
555*67e74705SXin Li       Init = llvm::ConstantInt::get(PtrDiffTy,
556*67e74705SXin Li                                     Component.getOffsetToTop().getQuantity());
557*67e74705SXin Li       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
558*67e74705SXin Li       break;
559*67e74705SXin Li     case VTableComponent::CK_RTTI:
560*67e74705SXin Li       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
561*67e74705SXin Li       break;
562*67e74705SXin Li     case VTableComponent::CK_FunctionPointer:
563*67e74705SXin Li     case VTableComponent::CK_CompleteDtorPointer:
564*67e74705SXin Li     case VTableComponent::CK_DeletingDtorPointer: {
565*67e74705SXin Li       GlobalDecl GD;
566*67e74705SXin Li 
567*67e74705SXin Li       // Get the right global decl.
568*67e74705SXin Li       switch (Component.getKind()) {
569*67e74705SXin Li       default:
570*67e74705SXin Li         llvm_unreachable("Unexpected vtable component kind");
571*67e74705SXin Li       case VTableComponent::CK_FunctionPointer:
572*67e74705SXin Li         GD = Component.getFunctionDecl();
573*67e74705SXin Li         break;
574*67e74705SXin Li       case VTableComponent::CK_CompleteDtorPointer:
575*67e74705SXin Li         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
576*67e74705SXin Li         break;
577*67e74705SXin Li       case VTableComponent::CK_DeletingDtorPointer:
578*67e74705SXin Li         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
579*67e74705SXin Li         break;
580*67e74705SXin Li       }
581*67e74705SXin Li 
582*67e74705SXin Li       if (CGM.getLangOpts().CUDA) {
583*67e74705SXin Li         // Emit NULL for methods we can't codegen on this
584*67e74705SXin Li         // side. Otherwise we'd end up with vtable with unresolved
585*67e74705SXin Li         // references.
586*67e74705SXin Li         const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
587*67e74705SXin Li         // OK on device side: functions w/ __device__ attribute
588*67e74705SXin Li         // OK on host side: anything except __device__-only functions.
589*67e74705SXin Li         bool CanEmitMethod = CGM.getLangOpts().CUDAIsDevice
590*67e74705SXin Li                                  ? MD->hasAttr<CUDADeviceAttr>()
591*67e74705SXin Li                                  : (MD->hasAttr<CUDAHostAttr>() ||
592*67e74705SXin Li                                     !MD->hasAttr<CUDADeviceAttr>());
593*67e74705SXin Li         if (!CanEmitMethod) {
594*67e74705SXin Li           Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
595*67e74705SXin Li           break;
596*67e74705SXin Li         }
597*67e74705SXin Li         // Method is acceptable, continue processing as usual.
598*67e74705SXin Li       }
599*67e74705SXin Li 
600*67e74705SXin Li       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
601*67e74705SXin Li         // We have a pure virtual member function.
602*67e74705SXin Li         if (!PureVirtualFn) {
603*67e74705SXin Li           llvm::FunctionType *Ty =
604*67e74705SXin Li             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
605*67e74705SXin Li           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
606*67e74705SXin Li           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
607*67e74705SXin Li           if (auto *F = dyn_cast<llvm::Function>(PureVirtualFn))
608*67e74705SXin Li             F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
609*67e74705SXin Li           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
610*67e74705SXin Li                                                          CGM.Int8PtrTy);
611*67e74705SXin Li         }
612*67e74705SXin Li         Init = PureVirtualFn;
613*67e74705SXin Li       } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
614*67e74705SXin Li         if (!DeletedVirtualFn) {
615*67e74705SXin Li           llvm::FunctionType *Ty =
616*67e74705SXin Li             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
617*67e74705SXin Li           StringRef DeletedCallName =
618*67e74705SXin Li             CGM.getCXXABI().GetDeletedVirtualCallName();
619*67e74705SXin Li           DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
620*67e74705SXin Li           if (auto *F = dyn_cast<llvm::Function>(DeletedVirtualFn))
621*67e74705SXin Li             F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
622*67e74705SXin Li           DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
623*67e74705SXin Li                                                          CGM.Int8PtrTy);
624*67e74705SXin Li         }
625*67e74705SXin Li         Init = DeletedVirtualFn;
626*67e74705SXin Li       } else {
627*67e74705SXin Li         // Check if we should use a thunk.
628*67e74705SXin Li         if (NextVTableThunkIndex < NumVTableThunks &&
629*67e74705SXin Li             VTableThunks[NextVTableThunkIndex].first == I) {
630*67e74705SXin Li           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
631*67e74705SXin Li 
632*67e74705SXin Li           maybeEmitThunkForVTable(GD, Thunk);
633*67e74705SXin Li           Init = CGM.GetAddrOfThunk(GD, Thunk);
634*67e74705SXin Li 
635*67e74705SXin Li           NextVTableThunkIndex++;
636*67e74705SXin Li         } else {
637*67e74705SXin Li           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
638*67e74705SXin Li 
639*67e74705SXin Li           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
640*67e74705SXin Li         }
641*67e74705SXin Li 
642*67e74705SXin Li         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
643*67e74705SXin Li       }
644*67e74705SXin Li       break;
645*67e74705SXin Li     }
646*67e74705SXin Li 
647*67e74705SXin Li     case VTableComponent::CK_UnusedFunctionPointer:
648*67e74705SXin Li       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
649*67e74705SXin Li       break;
650*67e74705SXin Li     };
651*67e74705SXin Li 
652*67e74705SXin Li     Inits.push_back(Init);
653*67e74705SXin Li   }
654*67e74705SXin Li 
655*67e74705SXin Li   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
656*67e74705SXin Li   return llvm::ConstantArray::get(ArrayType, Inits);
657*67e74705SXin Li }
658*67e74705SXin Li 
659*67e74705SXin Li llvm::GlobalVariable *
GenerateConstructionVTable(const CXXRecordDecl * RD,const BaseSubobject & Base,bool BaseIsVirtual,llvm::GlobalVariable::LinkageTypes Linkage,VTableAddressPointsMapTy & AddressPoints)660*67e74705SXin Li CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
661*67e74705SXin Li                                       const BaseSubobject &Base,
662*67e74705SXin Li                                       bool BaseIsVirtual,
663*67e74705SXin Li                                    llvm::GlobalVariable::LinkageTypes Linkage,
664*67e74705SXin Li                                       VTableAddressPointsMapTy& AddressPoints) {
665*67e74705SXin Li   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
666*67e74705SXin Li     DI->completeClassData(Base.getBase());
667*67e74705SXin Li 
668*67e74705SXin Li   std::unique_ptr<VTableLayout> VTLayout(
669*67e74705SXin Li       getItaniumVTableContext().createConstructionVTableLayout(
670*67e74705SXin Li           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
671*67e74705SXin Li 
672*67e74705SXin Li   // Add the address points.
673*67e74705SXin Li   AddressPoints = VTLayout->getAddressPoints();
674*67e74705SXin Li 
675*67e74705SXin Li   // Get the mangled construction vtable name.
676*67e74705SXin Li   SmallString<256> OutName;
677*67e74705SXin Li   llvm::raw_svector_ostream Out(OutName);
678*67e74705SXin Li   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
679*67e74705SXin Li       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
680*67e74705SXin Li                            Base.getBase(), Out);
681*67e74705SXin Li   StringRef Name = OutName.str();
682*67e74705SXin Li 
683*67e74705SXin Li   llvm::ArrayType *ArrayType =
684*67e74705SXin Li     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
685*67e74705SXin Li 
686*67e74705SXin Li   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
687*67e74705SXin Li   // guarantee that they actually will be available externally. Instead, when
688*67e74705SXin Li   // emitting an available_externally VTT, we provide references to an internal
689*67e74705SXin Li   // linkage construction vtable. The ABI only requires complete-object vtables
690*67e74705SXin Li   // to be the same for all instances of a type, not construction vtables.
691*67e74705SXin Li   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
692*67e74705SXin Li     Linkage = llvm::GlobalVariable::InternalLinkage;
693*67e74705SXin Li 
694*67e74705SXin Li   // Create the variable that will hold the construction vtable.
695*67e74705SXin Li   llvm::GlobalVariable *VTable =
696*67e74705SXin Li     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
697*67e74705SXin Li   CGM.setGlobalVisibility(VTable, RD);
698*67e74705SXin Li 
699*67e74705SXin Li   // V-tables are always unnamed_addr.
700*67e74705SXin Li   VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
701*67e74705SXin Li 
702*67e74705SXin Li   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
703*67e74705SXin Li       CGM.getContext().getTagDeclType(Base.getBase()));
704*67e74705SXin Li 
705*67e74705SXin Li   // Create and set the initializer.
706*67e74705SXin Li   llvm::Constant *Init = CreateVTableInitializer(
707*67e74705SXin Li       Base.getBase(), VTLayout->vtable_component_begin(),
708*67e74705SXin Li       VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
709*67e74705SXin Li       VTLayout->getNumVTableThunks(), RTTI);
710*67e74705SXin Li   VTable->setInitializer(Init);
711*67e74705SXin Li 
712*67e74705SXin Li   CGM.EmitVTableTypeMetadata(VTable, *VTLayout.get());
713*67e74705SXin Li 
714*67e74705SXin Li   return VTable;
715*67e74705SXin Li }
716*67e74705SXin Li 
shouldEmitAvailableExternallyVTable(const CodeGenModule & CGM,const CXXRecordDecl * RD)717*67e74705SXin Li static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
718*67e74705SXin Li                                                 const CXXRecordDecl *RD) {
719*67e74705SXin Li   return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
720*67e74705SXin Li          CGM.getCXXABI().canSpeculativelyEmitVTable(RD);
721*67e74705SXin Li }
722*67e74705SXin Li 
723*67e74705SXin Li /// Compute the required linkage of the vtable for the given class.
724*67e74705SXin Li ///
725*67e74705SXin Li /// Note that we only call this at the end of the translation unit.
726*67e74705SXin Li llvm::GlobalVariable::LinkageTypes
getVTableLinkage(const CXXRecordDecl * RD)727*67e74705SXin Li CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
728*67e74705SXin Li   if (!RD->isExternallyVisible())
729*67e74705SXin Li     return llvm::GlobalVariable::InternalLinkage;
730*67e74705SXin Li 
731*67e74705SXin Li   // We're at the end of the translation unit, so the current key
732*67e74705SXin Li   // function is fully correct.
733*67e74705SXin Li   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
734*67e74705SXin Li   if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
735*67e74705SXin Li     // If this class has a key function, use that to determine the
736*67e74705SXin Li     // linkage of the vtable.
737*67e74705SXin Li     const FunctionDecl *def = nullptr;
738*67e74705SXin Li     if (keyFunction->hasBody(def))
739*67e74705SXin Li       keyFunction = cast<CXXMethodDecl>(def);
740*67e74705SXin Li 
741*67e74705SXin Li     switch (keyFunction->getTemplateSpecializationKind()) {
742*67e74705SXin Li       case TSK_Undeclared:
743*67e74705SXin Li       case TSK_ExplicitSpecialization:
744*67e74705SXin Li         assert((def || CodeGenOpts.OptimizationLevel > 0) &&
745*67e74705SXin Li                "Shouldn't query vtable linkage without key function or "
746*67e74705SXin Li                "optimizations");
747*67e74705SXin Li         if (!def && CodeGenOpts.OptimizationLevel > 0)
748*67e74705SXin Li           return llvm::GlobalVariable::AvailableExternallyLinkage;
749*67e74705SXin Li 
750*67e74705SXin Li         if (keyFunction->isInlined())
751*67e74705SXin Li           return !Context.getLangOpts().AppleKext ?
752*67e74705SXin Li                    llvm::GlobalVariable::LinkOnceODRLinkage :
753*67e74705SXin Li                    llvm::Function::InternalLinkage;
754*67e74705SXin Li 
755*67e74705SXin Li         return llvm::GlobalVariable::ExternalLinkage;
756*67e74705SXin Li 
757*67e74705SXin Li       case TSK_ImplicitInstantiation:
758*67e74705SXin Li         return !Context.getLangOpts().AppleKext ?
759*67e74705SXin Li                  llvm::GlobalVariable::LinkOnceODRLinkage :
760*67e74705SXin Li                  llvm::Function::InternalLinkage;
761*67e74705SXin Li 
762*67e74705SXin Li       case TSK_ExplicitInstantiationDefinition:
763*67e74705SXin Li         return !Context.getLangOpts().AppleKext ?
764*67e74705SXin Li                  llvm::GlobalVariable::WeakODRLinkage :
765*67e74705SXin Li                  llvm::Function::InternalLinkage;
766*67e74705SXin Li 
767*67e74705SXin Li       case TSK_ExplicitInstantiationDeclaration:
768*67e74705SXin Li         llvm_unreachable("Should not have been asked to emit this");
769*67e74705SXin Li     }
770*67e74705SXin Li   }
771*67e74705SXin Li 
772*67e74705SXin Li   // -fapple-kext mode does not support weak linkage, so we must use
773*67e74705SXin Li   // internal linkage.
774*67e74705SXin Li   if (Context.getLangOpts().AppleKext)
775*67e74705SXin Li     return llvm::Function::InternalLinkage;
776*67e74705SXin Li 
777*67e74705SXin Li   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
778*67e74705SXin Li       llvm::GlobalValue::LinkOnceODRLinkage;
779*67e74705SXin Li   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
780*67e74705SXin Li       llvm::GlobalValue::WeakODRLinkage;
781*67e74705SXin Li   if (RD->hasAttr<DLLExportAttr>()) {
782*67e74705SXin Li     // Cannot discard exported vtables.
783*67e74705SXin Li     DiscardableODRLinkage = NonDiscardableODRLinkage;
784*67e74705SXin Li   } else if (RD->hasAttr<DLLImportAttr>()) {
785*67e74705SXin Li     // Imported vtables are available externally.
786*67e74705SXin Li     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
787*67e74705SXin Li     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
788*67e74705SXin Li   }
789*67e74705SXin Li 
790*67e74705SXin Li   switch (RD->getTemplateSpecializationKind()) {
791*67e74705SXin Li     case TSK_Undeclared:
792*67e74705SXin Li     case TSK_ExplicitSpecialization:
793*67e74705SXin Li     case TSK_ImplicitInstantiation:
794*67e74705SXin Li       return DiscardableODRLinkage;
795*67e74705SXin Li 
796*67e74705SXin Li     case TSK_ExplicitInstantiationDeclaration:
797*67e74705SXin Li       // Explicit instantiations in MSVC do not provide vtables, so we must emit
798*67e74705SXin Li       // our own.
799*67e74705SXin Li       if (getTarget().getCXXABI().isMicrosoft())
800*67e74705SXin Li         return DiscardableODRLinkage;
801*67e74705SXin Li       return shouldEmitAvailableExternallyVTable(*this, RD)
802*67e74705SXin Li                  ? llvm::GlobalVariable::AvailableExternallyLinkage
803*67e74705SXin Li                  : llvm::GlobalVariable::ExternalLinkage;
804*67e74705SXin Li 
805*67e74705SXin Li     case TSK_ExplicitInstantiationDefinition:
806*67e74705SXin Li       return NonDiscardableODRLinkage;
807*67e74705SXin Li   }
808*67e74705SXin Li 
809*67e74705SXin Li   llvm_unreachable("Invalid TemplateSpecializationKind!");
810*67e74705SXin Li }
811*67e74705SXin Li 
812*67e74705SXin Li /// This is a callback from Sema to tell us that that a particular vtable is
813*67e74705SXin Li /// required to be emitted in this translation unit.
814*67e74705SXin Li ///
815*67e74705SXin Li /// This is only called for vtables that _must_ be emitted (mainly due to key
816*67e74705SXin Li /// functions).  For weak vtables, CodeGen tracks when they are needed and
817*67e74705SXin Li /// emits them as-needed.
EmitVTable(CXXRecordDecl * theClass)818*67e74705SXin Li void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
819*67e74705SXin Li   VTables.GenerateClassData(theClass);
820*67e74705SXin Li }
821*67e74705SXin Li 
822*67e74705SXin Li void
GenerateClassData(const CXXRecordDecl * RD)823*67e74705SXin Li CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
824*67e74705SXin Li   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
825*67e74705SXin Li     DI->completeClassData(RD);
826*67e74705SXin Li 
827*67e74705SXin Li   if (RD->getNumVBases())
828*67e74705SXin Li     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
829*67e74705SXin Li 
830*67e74705SXin Li   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
831*67e74705SXin Li }
832*67e74705SXin Li 
833*67e74705SXin Li /// At this point in the translation unit, does it appear that can we
834*67e74705SXin Li /// rely on the vtable being defined elsewhere in the program?
835*67e74705SXin Li ///
836*67e74705SXin Li /// The response is really only definitive when called at the end of
837*67e74705SXin Li /// the translation unit.
838*67e74705SXin Li ///
839*67e74705SXin Li /// The only semantic restriction here is that the object file should
840*67e74705SXin Li /// not contain a vtable definition when that vtable is defined
841*67e74705SXin Li /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
842*67e74705SXin Li /// vtables when unnecessary.
isVTableExternal(const CXXRecordDecl * RD)843*67e74705SXin Li bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
844*67e74705SXin Li   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
845*67e74705SXin Li 
846*67e74705SXin Li   // We always synthesize vtables if they are needed in the MS ABI. MSVC doesn't
847*67e74705SXin Li   // emit them even if there is an explicit template instantiation.
848*67e74705SXin Li   if (CGM.getTarget().getCXXABI().isMicrosoft())
849*67e74705SXin Li     return false;
850*67e74705SXin Li 
851*67e74705SXin Li   // If we have an explicit instantiation declaration (and not a
852*67e74705SXin Li   // definition), the vtable is defined elsewhere.
853*67e74705SXin Li   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
854*67e74705SXin Li   if (TSK == TSK_ExplicitInstantiationDeclaration)
855*67e74705SXin Li     return true;
856*67e74705SXin Li 
857*67e74705SXin Li   // Otherwise, if the class is an instantiated template, the
858*67e74705SXin Li   // vtable must be defined here.
859*67e74705SXin Li   if (TSK == TSK_ImplicitInstantiation ||
860*67e74705SXin Li       TSK == TSK_ExplicitInstantiationDefinition)
861*67e74705SXin Li     return false;
862*67e74705SXin Li 
863*67e74705SXin Li   // Otherwise, if the class doesn't have a key function (possibly
864*67e74705SXin Li   // anymore), the vtable must be defined here.
865*67e74705SXin Li   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
866*67e74705SXin Li   if (!keyFunction)
867*67e74705SXin Li     return false;
868*67e74705SXin Li 
869*67e74705SXin Li   // Otherwise, if we don't have a definition of the key function, the
870*67e74705SXin Li   // vtable must be defined somewhere else.
871*67e74705SXin Li   return !keyFunction->hasBody();
872*67e74705SXin Li }
873*67e74705SXin Li 
874*67e74705SXin Li /// Given that we're currently at the end of the translation unit, and
875*67e74705SXin Li /// we've emitted a reference to the vtable for this class, should
876*67e74705SXin Li /// we define that vtable?
shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule & CGM,const CXXRecordDecl * RD)877*67e74705SXin Li static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
878*67e74705SXin Li                                                    const CXXRecordDecl *RD) {
879*67e74705SXin Li   // If vtable is internal then it has to be done.
880*67e74705SXin Li   if (!CGM.getVTables().isVTableExternal(RD))
881*67e74705SXin Li     return true;
882*67e74705SXin Li 
883*67e74705SXin Li   // If it's external then maybe we will need it as available_externally.
884*67e74705SXin Li   return shouldEmitAvailableExternallyVTable(CGM, RD);
885*67e74705SXin Li }
886*67e74705SXin Li 
887*67e74705SXin Li /// Given that at some point we emitted a reference to one or more
888*67e74705SXin Li /// vtables, and that we are now at the end of the translation unit,
889*67e74705SXin Li /// decide whether we should emit them.
EmitDeferredVTables()890*67e74705SXin Li void CodeGenModule::EmitDeferredVTables() {
891*67e74705SXin Li #ifndef NDEBUG
892*67e74705SXin Li   // Remember the size of DeferredVTables, because we're going to assume
893*67e74705SXin Li   // that this entire operation doesn't modify it.
894*67e74705SXin Li   size_t savedSize = DeferredVTables.size();
895*67e74705SXin Li #endif
896*67e74705SXin Li 
897*67e74705SXin Li   for (const CXXRecordDecl *RD : DeferredVTables)
898*67e74705SXin Li     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
899*67e74705SXin Li       VTables.GenerateClassData(RD);
900*67e74705SXin Li 
901*67e74705SXin Li   assert(savedSize == DeferredVTables.size() &&
902*67e74705SXin Li          "deferred extra vtables during vtable emission?");
903*67e74705SXin Li   DeferredVTables.clear();
904*67e74705SXin Li }
905*67e74705SXin Li 
HasHiddenLTOVisibility(const CXXRecordDecl * RD)906*67e74705SXin Li bool CodeGenModule::HasHiddenLTOVisibility(const CXXRecordDecl *RD) {
907*67e74705SXin Li   LinkageInfo LV = RD->getLinkageAndVisibility();
908*67e74705SXin Li   if (!isExternallyVisible(LV.getLinkage()))
909*67e74705SXin Li     return true;
910*67e74705SXin Li 
911*67e74705SXin Li   if (RD->hasAttr<LTOVisibilityPublicAttr>() || RD->hasAttr<UuidAttr>())
912*67e74705SXin Li     return false;
913*67e74705SXin Li 
914*67e74705SXin Li   if (getTriple().isOSBinFormatCOFF()) {
915*67e74705SXin Li     if (RD->hasAttr<DLLExportAttr>() || RD->hasAttr<DLLImportAttr>())
916*67e74705SXin Li       return false;
917*67e74705SXin Li   } else {
918*67e74705SXin Li     if (LV.getVisibility() != HiddenVisibility)
919*67e74705SXin Li       return false;
920*67e74705SXin Li   }
921*67e74705SXin Li 
922*67e74705SXin Li   if (getCodeGenOpts().LTOVisibilityPublicStd) {
923*67e74705SXin Li     const DeclContext *DC = RD;
924*67e74705SXin Li     while (1) {
925*67e74705SXin Li       auto *D = cast<Decl>(DC);
926*67e74705SXin Li       DC = DC->getParent();
927*67e74705SXin Li       if (isa<TranslationUnitDecl>(DC->getRedeclContext())) {
928*67e74705SXin Li         if (auto *ND = dyn_cast<NamespaceDecl>(D))
929*67e74705SXin Li           if (const IdentifierInfo *II = ND->getIdentifier())
930*67e74705SXin Li             if (II->isStr("std") || II->isStr("stdext"))
931*67e74705SXin Li               return false;
932*67e74705SXin Li         break;
933*67e74705SXin Li       }
934*67e74705SXin Li     }
935*67e74705SXin Li   }
936*67e74705SXin Li 
937*67e74705SXin Li   return true;
938*67e74705SXin Li }
939*67e74705SXin Li 
EmitVTableTypeMetadata(llvm::GlobalVariable * VTable,const VTableLayout & VTLayout)940*67e74705SXin Li void CodeGenModule::EmitVTableTypeMetadata(llvm::GlobalVariable *VTable,
941*67e74705SXin Li                                            const VTableLayout &VTLayout) {
942*67e74705SXin Li   if (!getCodeGenOpts().PrepareForLTO)
943*67e74705SXin Li     return;
944*67e74705SXin Li 
945*67e74705SXin Li   CharUnits PointerWidth =
946*67e74705SXin Li       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
947*67e74705SXin Li 
948*67e74705SXin Li   typedef std::pair<const CXXRecordDecl *, unsigned> BSEntry;
949*67e74705SXin Li   std::vector<BSEntry> BitsetEntries;
950*67e74705SXin Li   // Create a bit set entry for each address point.
951*67e74705SXin Li   for (auto &&AP : VTLayout.getAddressPoints())
952*67e74705SXin Li     BitsetEntries.push_back(std::make_pair(AP.first.getBase(), AP.second));
953*67e74705SXin Li 
954*67e74705SXin Li   // Sort the bit set entries for determinism.
955*67e74705SXin Li   std::sort(BitsetEntries.begin(), BitsetEntries.end(),
956*67e74705SXin Li             [this](const BSEntry &E1, const BSEntry &E2) {
957*67e74705SXin Li     if (&E1 == &E2)
958*67e74705SXin Li       return false;
959*67e74705SXin Li 
960*67e74705SXin Li     std::string S1;
961*67e74705SXin Li     llvm::raw_string_ostream O1(S1);
962*67e74705SXin Li     getCXXABI().getMangleContext().mangleTypeName(
963*67e74705SXin Li         QualType(E1.first->getTypeForDecl(), 0), O1);
964*67e74705SXin Li     O1.flush();
965*67e74705SXin Li 
966*67e74705SXin Li     std::string S2;
967*67e74705SXin Li     llvm::raw_string_ostream O2(S2);
968*67e74705SXin Li     getCXXABI().getMangleContext().mangleTypeName(
969*67e74705SXin Li         QualType(E2.first->getTypeForDecl(), 0), O2);
970*67e74705SXin Li     O2.flush();
971*67e74705SXin Li 
972*67e74705SXin Li     if (S1 < S2)
973*67e74705SXin Li       return true;
974*67e74705SXin Li     if (S1 != S2)
975*67e74705SXin Li       return false;
976*67e74705SXin Li 
977*67e74705SXin Li     return E1.second < E2.second;
978*67e74705SXin Li   });
979*67e74705SXin Li 
980*67e74705SXin Li   for (auto BitsetEntry : BitsetEntries)
981*67e74705SXin Li     AddVTableTypeMetadata(VTable, PointerWidth * BitsetEntry.second,
982*67e74705SXin Li                           BitsetEntry.first);
983*67e74705SXin Li }
984