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::BasicBlock &BB : *Fn) {
191       llvm::Instruction *T = BB.getTerminator();
192       if (isa<llvm::ReturnInst>(T)) {
193         RValue RV = RValue::get(T->getOperand(0));
194         T->eraseFromParent();
195         Builder.SetInsertPoint(&BB);
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   else if (llvm::CallInst* Call = dyn_cast<llvm::CallInst>(CallOrInvoke))
316     Call->setTailCallKind(llvm::CallInst::TCK_Tail);
317 
318   // Emit return.
319   if (!ResultType->isVoidType() && Slot.isNull())
320     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
321 
322   // Disable the final ARC autorelease.
323   AutoreleaseResult = false;
324 
325   FinishFunction();
326 }
327 
328 void CodeGenFunction::EmitMustTailThunk(const CXXMethodDecl *MD,
329                                         llvm::Value *AdjustedThisPtr,
330                                         llvm::Value *Callee) {
331   // Emitting a musttail call thunk doesn't use any of the CGCall.cpp machinery
332   // to translate AST arguments into LLVM IR arguments.  For thunks, we know
333   // that the caller prototype more or less matches the callee prototype with
334   // the exception of 'this'.
335   SmallVector<llvm::Value *, 8> Args;
336   for (llvm::Argument &A : CurFn->args())
337     Args.push_back(&A);
338 
339   // Set the adjusted 'this' pointer.
340   const ABIArgInfo &ThisAI = CurFnInfo->arg_begin()->info;
341   if (ThisAI.isDirect()) {
342     const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
343     int ThisArgNo = RetAI.isIndirect() && !RetAI.isSRetAfterThis() ? 1 : 0;
344     llvm::Type *ThisType = Args[ThisArgNo]->getType();
345     if (ThisType != AdjustedThisPtr->getType())
346       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
347     Args[ThisArgNo] = AdjustedThisPtr;
348   } else {
349     assert(ThisAI.isInAlloca() && "this is passed directly or inalloca");
350     llvm::Value *ThisAddr = GetAddrOfLocalVar(CXXABIThisDecl);
351     llvm::Type *ThisType =
352         cast<llvm::PointerType>(ThisAddr->getType())->getElementType();
353     if (ThisType != AdjustedThisPtr->getType())
354       AdjustedThisPtr = Builder.CreateBitCast(AdjustedThisPtr, ThisType);
355     Builder.CreateStore(AdjustedThisPtr, ThisAddr);
356   }
357 
358   // Emit the musttail call manually.  Even if the prologue pushed cleanups, we
359   // don't actually want to run them.
360   llvm::CallInst *Call = Builder.CreateCall(Callee, Args);
361   Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
362 
363   // Apply the standard set of call attributes.
364   unsigned CallingConv;
365   CodeGen::AttributeListType AttributeList;
366   CGM.ConstructAttributeList(*CurFnInfo, MD, AttributeList, CallingConv,
367                              /*AttrOnCallSite=*/true);
368   llvm::AttributeSet Attrs =
369       llvm::AttributeSet::get(getLLVMContext(), AttributeList);
370   Call->setAttributes(Attrs);
371   Call->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
372 
373   if (Call->getType()->isVoidTy())
374     Builder.CreateRetVoid();
375   else
376     Builder.CreateRet(Call);
377 
378   // Finish the function to maintain CodeGenFunction invariants.
379   // FIXME: Don't emit unreachable code.
380   EmitBlock(createBasicBlock());
381   FinishFunction();
382 }
383 
384 void CodeGenFunction::generateThunk(llvm::Function *Fn,
385                                     const CGFunctionInfo &FnInfo,
386                                     GlobalDecl GD, const ThunkInfo &Thunk) {
387   StartThunk(Fn, GD, FnInfo);
388 
389   // Get our callee.
390   llvm::Type *Ty =
391     CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
392   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
393 
394   // Make the call and return the result.
395   EmitCallAndReturnForThunk(Callee, &Thunk);
396 }
397 
398 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
399                                bool ForVTable) {
400   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
401 
402   // FIXME: re-use FnInfo in this computation.
403   llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
404   llvm::GlobalValue *Entry;
405 
406   // Strip off a bitcast if we got one back.
407   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
408     assert(CE->getOpcode() == llvm::Instruction::BitCast);
409     Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
410   } else {
411     Entry = cast<llvm::GlobalValue>(C);
412   }
413 
414   // There's already a declaration with the same name, check if it has the same
415   // type or if we need to replace it.
416   if (Entry->getType()->getElementType() !=
417       CGM.getTypes().GetFunctionTypeForVTable(GD)) {
418     llvm::GlobalValue *OldThunkFn = Entry;
419 
420     // If the types mismatch then we have to rewrite the definition.
421     assert(OldThunkFn->isDeclaration() &&
422            "Shouldn't replace non-declaration");
423 
424     // Remove the name from the old thunk function and get a new thunk.
425     OldThunkFn->setName(StringRef());
426     Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
427 
428     // If needed, replace the old thunk with a bitcast.
429     if (!OldThunkFn->use_empty()) {
430       llvm::Constant *NewPtrForOldDecl =
431         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
432       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
433     }
434 
435     // Remove the old thunk.
436     OldThunkFn->eraseFromParent();
437   }
438 
439   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
440   bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
441   bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
442 
443   if (!ThunkFn->isDeclaration()) {
444     if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
445       // There is already a thunk emitted for this function, do nothing.
446       return;
447     }
448 
449     setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
450     return;
451   }
452 
453   CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
454 
455   if (ThunkFn->isVarArg()) {
456     // Varargs thunks are special; we can't just generate a call because
457     // we can't copy the varargs.  Our implementation is rather
458     // expensive/sucky at the moment, so don't generate the thunk unless
459     // we have to.
460     // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
461     if (UseAvailableExternallyLinkage)
462       return;
463     ThunkFn =
464         CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
465   } else {
466     // Normal thunk body generation.
467     CodeGenFunction(CGM).generateThunk(ThunkFn, FnInfo, GD, Thunk);
468   }
469 
470   setThunkProperties(CGM, Thunk, ThunkFn, ForVTable, GD);
471 }
472 
473 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
474                                              const ThunkInfo &Thunk) {
475   // If the ABI has key functions, only the TU with the key function should emit
476   // the thunk. However, we can allow inlining of thunks if we emit them with
477   // available_externally linkage together with vtables when optimizations are
478   // enabled.
479   if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
480       !CGM.getCodeGenOpts().OptimizationLevel)
481     return;
482 
483   // We can't emit thunks for member functions with incomplete types.
484   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
485   if (!CGM.getTypes().isFuncTypeConvertible(
486            MD->getType()->castAs<FunctionType>()))
487     return;
488 
489   emitThunk(GD, Thunk, /*ForVTable=*/true);
490 }
491 
492 void CodeGenVTables::EmitThunks(GlobalDecl GD)
493 {
494   const CXXMethodDecl *MD =
495     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
496 
497   // We don't need to generate thunks for the base destructor.
498   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
499     return;
500 
501   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
502       VTContext->getThunkInfo(GD);
503 
504   if (!ThunkInfoVector)
505     return;
506 
507   for (const ThunkInfo& Thunk : *ThunkInfoVector)
508     emitThunk(GD, Thunk, /*ForVTable=*/false);
509 }
510 
511 llvm::Constant *CodeGenVTables::CreateVTableInitializer(
512     const CXXRecordDecl *RD, const VTableComponent *Components,
513     unsigned NumComponents, const VTableLayout::VTableThunkTy *VTableThunks,
514     unsigned NumVTableThunks, llvm::Constant *RTTI) {
515   SmallVector<llvm::Constant *, 64> Inits;
516 
517   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
518 
519   llvm::Type *PtrDiffTy =
520     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
521 
522   unsigned NextVTableThunkIndex = 0;
523 
524   llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
525 
526   for (unsigned I = 0; I != NumComponents; ++I) {
527     VTableComponent Component = Components[I];
528 
529     llvm::Constant *Init = nullptr;
530 
531     switch (Component.getKind()) {
532     case VTableComponent::CK_VCallOffset:
533       Init = llvm::ConstantInt::get(PtrDiffTy,
534                                     Component.getVCallOffset().getQuantity());
535       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
536       break;
537     case VTableComponent::CK_VBaseOffset:
538       Init = llvm::ConstantInt::get(PtrDiffTy,
539                                     Component.getVBaseOffset().getQuantity());
540       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
541       break;
542     case VTableComponent::CK_OffsetToTop:
543       Init = llvm::ConstantInt::get(PtrDiffTy,
544                                     Component.getOffsetToTop().getQuantity());
545       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
546       break;
547     case VTableComponent::CK_RTTI:
548       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
549       break;
550     case VTableComponent::CK_FunctionPointer:
551     case VTableComponent::CK_CompleteDtorPointer:
552     case VTableComponent::CK_DeletingDtorPointer: {
553       GlobalDecl GD;
554 
555       // Get the right global decl.
556       switch (Component.getKind()) {
557       default:
558         llvm_unreachable("Unexpected vtable component kind");
559       case VTableComponent::CK_FunctionPointer:
560         GD = Component.getFunctionDecl();
561         break;
562       case VTableComponent::CK_CompleteDtorPointer:
563         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
564         break;
565       case VTableComponent::CK_DeletingDtorPointer:
566         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
567         break;
568       }
569 
570       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
571         // We have a pure virtual member function.
572         if (!PureVirtualFn) {
573           llvm::FunctionType *Ty =
574             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
575           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
576           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
577           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
578                                                          CGM.Int8PtrTy);
579         }
580         Init = PureVirtualFn;
581       } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
582         if (!DeletedVirtualFn) {
583           llvm::FunctionType *Ty =
584             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
585           StringRef DeletedCallName =
586             CGM.getCXXABI().GetDeletedVirtualCallName();
587           DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
588           DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
589                                                          CGM.Int8PtrTy);
590         }
591         Init = DeletedVirtualFn;
592       } else {
593         // Check if we should use a thunk.
594         if (NextVTableThunkIndex < NumVTableThunks &&
595             VTableThunks[NextVTableThunkIndex].first == I) {
596           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
597 
598           maybeEmitThunkForVTable(GD, Thunk);
599           Init = CGM.GetAddrOfThunk(GD, Thunk);
600 
601           NextVTableThunkIndex++;
602         } else {
603           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
604 
605           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
606         }
607 
608         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
609       }
610       break;
611     }
612 
613     case VTableComponent::CK_UnusedFunctionPointer:
614       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
615       break;
616     };
617 
618     Inits.push_back(Init);
619   }
620 
621   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
622   return llvm::ConstantArray::get(ArrayType, Inits);
623 }
624 
625 llvm::GlobalVariable *
626 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
627                                       const BaseSubobject &Base,
628                                       bool BaseIsVirtual,
629                                    llvm::GlobalVariable::LinkageTypes Linkage,
630                                       VTableAddressPointsMapTy& AddressPoints) {
631   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
632     DI->completeClassData(Base.getBase());
633 
634   std::unique_ptr<VTableLayout> VTLayout(
635       getItaniumVTableContext().createConstructionVTableLayout(
636           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
637 
638   // Add the address points.
639   AddressPoints = VTLayout->getAddressPoints();
640 
641   // Get the mangled construction vtable name.
642   SmallString<256> OutName;
643   llvm::raw_svector_ostream Out(OutName);
644   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
645       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
646                            Base.getBase(), Out);
647   Out.flush();
648   StringRef Name = OutName.str();
649 
650   llvm::ArrayType *ArrayType =
651     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
652 
653   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
654   // guarantee that they actually will be available externally. Instead, when
655   // emitting an available_externally VTT, we provide references to an internal
656   // linkage construction vtable. The ABI only requires complete-object vtables
657   // to be the same for all instances of a type, not construction vtables.
658   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
659     Linkage = llvm::GlobalVariable::InternalLinkage;
660 
661   // Create the variable that will hold the construction vtable.
662   llvm::GlobalVariable *VTable =
663     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
664   CGM.setGlobalVisibility(VTable, RD);
665 
666   // V-tables are always unnamed_addr.
667   VTable->setUnnamedAddr(true);
668 
669   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(
670       CGM.getContext().getTagDeclType(Base.getBase()));
671 
672   // Create and set the initializer.
673   llvm::Constant *Init = CreateVTableInitializer(
674       Base.getBase(), VTLayout->vtable_component_begin(),
675       VTLayout->getNumVTableComponents(), VTLayout->vtable_thunk_begin(),
676       VTLayout->getNumVTableThunks(), RTTI);
677   VTable->setInitializer(Init);
678 
679   CGM.EmitVTableBitSetEntries(VTable, *VTLayout.get());
680 
681   return VTable;
682 }
683 
684 static bool shouldEmitAvailableExternallyVTable(const CodeGenModule &CGM,
685                                                 const CXXRecordDecl *RD) {
686   return CGM.getCodeGenOpts().OptimizationLevel > 0 &&
687             CGM.getCXXABI().canEmitAvailableExternallyVTable(RD);
688 }
689 
690 /// Compute the required linkage of the v-table for the given class.
691 ///
692 /// Note that we only call this at the end of the translation unit.
693 llvm::GlobalVariable::LinkageTypes
694 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
695   if (!RD->isExternallyVisible())
696     return llvm::GlobalVariable::InternalLinkage;
697 
698   // We're at the end of the translation unit, so the current key
699   // function is fully correct.
700   const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD);
701   if (keyFunction && !RD->hasAttr<DLLImportAttr>()) {
702     // If this class has a key function, use that to determine the
703     // linkage of the vtable.
704     const FunctionDecl *def = nullptr;
705     if (keyFunction->hasBody(def))
706       keyFunction = cast<CXXMethodDecl>(def);
707 
708     switch (keyFunction->getTemplateSpecializationKind()) {
709       case TSK_Undeclared:
710       case TSK_ExplicitSpecialization:
711         assert((def || CodeGenOpts.OptimizationLevel > 0) &&
712                "Shouldn't query vtable linkage without key function or "
713                "optimizations");
714         if (!def && CodeGenOpts.OptimizationLevel > 0)
715           return llvm::GlobalVariable::AvailableExternallyLinkage;
716 
717         if (keyFunction->isInlined())
718           return !Context.getLangOpts().AppleKext ?
719                    llvm::GlobalVariable::LinkOnceODRLinkage :
720                    llvm::Function::InternalLinkage;
721 
722         return llvm::GlobalVariable::ExternalLinkage;
723 
724       case TSK_ImplicitInstantiation:
725         return !Context.getLangOpts().AppleKext ?
726                  llvm::GlobalVariable::LinkOnceODRLinkage :
727                  llvm::Function::InternalLinkage;
728 
729       case TSK_ExplicitInstantiationDefinition:
730         return !Context.getLangOpts().AppleKext ?
731                  llvm::GlobalVariable::WeakODRLinkage :
732                  llvm::Function::InternalLinkage;
733 
734       case TSK_ExplicitInstantiationDeclaration:
735         llvm_unreachable("Should not have been asked to emit this");
736     }
737   }
738 
739   // -fapple-kext mode does not support weak linkage, so we must use
740   // internal linkage.
741   if (Context.getLangOpts().AppleKext)
742     return llvm::Function::InternalLinkage;
743 
744   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
745       llvm::GlobalValue::LinkOnceODRLinkage;
746   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
747       llvm::GlobalValue::WeakODRLinkage;
748   if (RD->hasAttr<DLLExportAttr>()) {
749     // Cannot discard exported vtables.
750     DiscardableODRLinkage = NonDiscardableODRLinkage;
751   } else if (RD->hasAttr<DLLImportAttr>()) {
752     // Imported vtables are available externally.
753     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
754     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
755   }
756 
757   switch (RD->getTemplateSpecializationKind()) {
758     case TSK_Undeclared:
759     case TSK_ExplicitSpecialization:
760     case TSK_ImplicitInstantiation:
761       return DiscardableODRLinkage;
762 
763     case TSK_ExplicitInstantiationDeclaration:
764       return shouldEmitAvailableExternallyVTable(*this, RD)
765                  ? llvm::GlobalVariable::AvailableExternallyLinkage
766                  : llvm::GlobalVariable::ExternalLinkage;
767 
768     case TSK_ExplicitInstantiationDefinition:
769       return NonDiscardableODRLinkage;
770   }
771 
772   llvm_unreachable("Invalid TemplateSpecializationKind!");
773 }
774 
775 /// This is a callback from Sema to tell us that that a particular v-table is
776 /// required to be emitted in this translation unit.
777 ///
778 /// This is only called for vtables that _must_ be emitted (mainly due to key
779 /// functions).  For weak vtables, CodeGen tracks when they are needed and
780 /// emits them as-needed.
781 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass) {
782   VTables.GenerateClassData(theClass);
783 }
784 
785 void
786 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
787   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
788     DI->completeClassData(RD);
789 
790   if (RD->getNumVBases())
791     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
792 
793   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
794 }
795 
796 /// At this point in the translation unit, does it appear that can we
797 /// rely on the vtable being defined elsewhere in the program?
798 ///
799 /// The response is really only definitive when called at the end of
800 /// the translation unit.
801 ///
802 /// The only semantic restriction here is that the object file should
803 /// not contain a v-table definition when that v-table is defined
804 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
805 /// v-tables when unnecessary.
806 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
807   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
808 
809   // If we have an explicit instantiation declaration (and not a
810   // definition), the v-table is defined elsewhere.
811   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
812   if (TSK == TSK_ExplicitInstantiationDeclaration)
813     return true;
814 
815   // Otherwise, if the class is an instantiated template, the
816   // v-table must be defined here.
817   if (TSK == TSK_ImplicitInstantiation ||
818       TSK == TSK_ExplicitInstantiationDefinition)
819     return false;
820 
821   // Otherwise, if the class doesn't have a key function (possibly
822   // anymore), the v-table must be defined here.
823   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
824   if (!keyFunction)
825     return false;
826 
827   // Otherwise, if we don't have a definition of the key function, the
828   // v-table must be defined somewhere else.
829   return !keyFunction->hasBody();
830 }
831 
832 /// Given that we're currently at the end of the translation unit, and
833 /// we've emitted a reference to the v-table for this class, should
834 /// we define that v-table?
835 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
836                                                    const CXXRecordDecl *RD) {
837   // If vtable is internal then it has to be done
838   if (!CGM.getVTables().isVTableExternal(RD))
839     return true;
840 
841   // If it's external then maybe we will need it as available_externally
842   return shouldEmitAvailableExternallyVTable(CGM, RD);
843 }
844 
845 /// Given that at some point we emitted a reference to one or more
846 /// v-tables, and that we are now at the end of the translation unit,
847 /// decide whether we should emit them.
848 void CodeGenModule::EmitDeferredVTables() {
849 #ifndef NDEBUG
850   // Remember the size of DeferredVTables, because we're going to assume
851   // that this entire operation doesn't modify it.
852   size_t savedSize = DeferredVTables.size();
853 #endif
854 
855   for (const CXXRecordDecl *RD : DeferredVTables)
856     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
857       VTables.GenerateClassData(RD);
858 
859   assert(savedSize == DeferredVTables.size() &&
860          "deferred extra v-tables during v-table emission?");
861   DeferredVTables.clear();
862 }
863 
864 bool CodeGenModule::IsCFIBlacklistedRecord(const CXXRecordDecl *RD) {
865   if (RD->hasAttr<UuidAttr>() &&
866       getContext().getSanitizerBlacklist().isBlacklistedType("attr:uuid"))
867     return true;
868 
869   return getContext().getSanitizerBlacklist().isBlacklistedType(
870       RD->getQualifiedNameAsString());
871 }
872 
873 void CodeGenModule::EmitVTableBitSetEntries(llvm::GlobalVariable *VTable,
874                                             const VTableLayout &VTLayout) {
875   if (!LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
876       !LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
877       !LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
878       !LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast))
879     return;
880 
881   CharUnits PointerWidth =
882       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
883 
884   std::vector<llvm::MDTuple *> BitsetEntries;
885   // Create a bit set entry for each address point.
886   for (auto &&AP : VTLayout.getAddressPoints()) {
887     if (IsCFIBlacklistedRecord(AP.first.getBase()))
888       continue;
889 
890     BitsetEntries.push_back(CreateVTableBitSetEntry(
891         VTable, PointerWidth * AP.second, AP.first.getBase()));
892   }
893 
894   // Sort the bit set entries for determinism.
895   std::sort(BitsetEntries.begin(), BitsetEntries.end(), [](llvm::MDTuple *T1,
896                                                            llvm::MDTuple *T2) {
897     if (T1 == T2)
898       return false;
899 
900     StringRef S1 = cast<llvm::MDString>(T1->getOperand(0))->getString();
901     StringRef S2 = cast<llvm::MDString>(T2->getOperand(0))->getString();
902     if (S1 < S2)
903       return true;
904     if (S1 != S2)
905       return false;
906 
907     uint64_t Offset1 = cast<llvm::ConstantInt>(
908                            cast<llvm::ConstantAsMetadata>(T1->getOperand(2))
909                                ->getValue())->getZExtValue();
910     uint64_t Offset2 = cast<llvm::ConstantInt>(
911                            cast<llvm::ConstantAsMetadata>(T2->getOperand(2))
912                                ->getValue())->getZExtValue();
913     assert(Offset1 != Offset2);
914     return Offset1 < Offset2;
915   });
916 
917   llvm::NamedMDNode *BitsetsMD =
918       getModule().getOrInsertNamedMetadata("llvm.bitsets");
919   for (auto BitsetEntry : BitsetEntries)
920     BitsetsMD->addOperand(BitsetEntry);
921 }
922