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