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