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