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