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