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);
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 #ifndef NDEBUG
60 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
61                     const ABIArgInfo &infoR, CanQualType typeR) {
62   return (infoL.getKind() == infoR.getKind() &&
63           (typeL == typeR ||
64            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
65            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
66 }
67 #endif
68 
69 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
70                                       QualType ResultType, RValue RV,
71                                       const ThunkInfo &Thunk) {
72   // Emit the return adjustment.
73   bool NullCheckValue = !ResultType->isReferenceType();
74 
75   llvm::BasicBlock *AdjustNull = nullptr;
76   llvm::BasicBlock *AdjustNotNull = nullptr;
77   llvm::BasicBlock *AdjustEnd = nullptr;
78 
79   llvm::Value *ReturnValue = RV.getScalarVal();
80 
81   if (NullCheckValue) {
82     AdjustNull = CGF.createBasicBlock("adjust.null");
83     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
84     AdjustEnd = CGF.createBasicBlock("adjust.end");
85 
86     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
87     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
88     CGF.EmitBlock(AdjustNotNull);
89   }
90 
91   ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
92                                                             Thunk.Return);
93 
94   if (NullCheckValue) {
95     CGF.Builder.CreateBr(AdjustEnd);
96     CGF.EmitBlock(AdjustNull);
97     CGF.Builder.CreateBr(AdjustEnd);
98     CGF.EmitBlock(AdjustEnd);
99 
100     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
101     PHI->addIncoming(ReturnValue, AdjustNotNull);
102     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
103                      AdjustNull);
104     ReturnValue = PHI;
105   }
106 
107   return RValue::get(ReturnValue);
108 }
109 
110 // This function does roughly the same thing as GenerateThunk, but in a
111 // very different way, so that va_start and va_end work correctly.
112 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
113 //        a function, and that there is an alloca built in the entry block
114 //        for all accesses to "this".
115 // FIXME: This function assumes there is only one "ret" statement per function.
116 // FIXME: Cloning isn't correct in the presence of indirect goto!
117 // FIXME: This implementation of thunks bloats codesize by duplicating the
118 //        function definition.  There are alternatives:
119 //        1. Add some sort of stub support to LLVM for cases where we can
120 //           do a this adjustment, then a sibcall.
121 //        2. We could transform the definition to take a va_list instead of an
122 //           actual variable argument list, then have the thunks (including a
123 //           no-op thunk for the regular definition) call va_start/va_end.
124 //           There's a bit of per-call overhead for this solution, but it's
125 //           better for codesize if the definition is long.
126 void CodeGenFunction::GenerateVarArgsThunk(
127                                       llvm::Function *Fn,
128                                       const CGFunctionInfo &FnInfo,
129                                       GlobalDecl GD, const ThunkInfo &Thunk) {
130   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
131   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
132   QualType ResultType = FPT->getReturnType();
133 
134   // Get the original function
135   assert(FnInfo.isVariadic());
136   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
137   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
138   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
139 
140   // Clone to thunk.
141   llvm::ValueToValueMapTy VMap;
142   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
143                                               /*ModuleLevelChanges=*/false);
144   CGM.getModule().getFunctionList().push_back(NewFn);
145   Fn->replaceAllUsesWith(NewFn);
146   NewFn->takeName(Fn);
147   Fn->eraseFromParent();
148   Fn = NewFn;
149 
150   // "Initialize" CGF (minimally).
151   CurFn = Fn;
152 
153   // Get the "this" value
154   llvm::Function::arg_iterator AI = Fn->arg_begin();
155   if (CGM.ReturnTypeUsesSRet(FnInfo))
156     ++AI;
157 
158   // Find the first store of "this", which will be to the alloca associated
159   // with "this".
160   llvm::Value *ThisPtr = &*AI;
161   llvm::BasicBlock *EntryBB = Fn->begin();
162   llvm::Instruction *ThisStore = nullptr;
163   for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
164        I != E; I++) {
165     if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
166       ThisStore = cast<llvm::StoreInst>(I);
167       break;
168     }
169   }
170   assert(ThisStore && "Store of this should be in entry block?");
171   // Adjust "this", if necessary.
172   Builder.SetInsertPoint(ThisStore);
173   llvm::Value *AdjustedThisPtr =
174       CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
175   ThisStore->setOperand(0, AdjustedThisPtr);
176 
177   if (!Thunk.Return.isEmpty()) {
178     // Fix up the returned value, if necessary.
179     for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
180       llvm::Instruction *T = I->getTerminator();
181       if (isa<llvm::ReturnInst>(T)) {
182         RValue RV = RValue::get(T->getOperand(0));
183         T->eraseFromParent();
184         Builder.SetInsertPoint(&*I);
185         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
186         Builder.CreateRet(RV.getScalarVal());
187         break;
188       }
189     }
190   }
191 }
192 
193 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
194                                  const CGFunctionInfo &FnInfo) {
195   assert(!CurGD.getDecl() && "CurGD was already set!");
196   CurGD = GD;
197 
198   // Build FunctionArgs.
199   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
200   QualType ThisType = MD->getThisType(getContext());
201   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
202   QualType ResultType =
203       CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getReturnType();
204   FunctionArgList FunctionArgs;
205 
206   // Create the implicit 'this' parameter declaration.
207   CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
208 
209   // Add the rest of the parameters.
210   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
211                                           E = MD->param_end();
212        I != E; ++I)
213     FunctionArgs.push_back(*I);
214 
215   if (isa<CXXDestructorDecl>(MD))
216     CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
217 
218   // Start defining the function.
219   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
220                 MD->getLocation(), SourceLocation());
221 
222   // Since we didn't pass a GlobalDecl to StartFunction, do this ourselves.
223   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
224   CXXThisValue = CXXABIThisValue;
225 }
226 
227 void CodeGenFunction::EmitCallAndReturnForThunk(GlobalDecl GD,
228                                                 llvm::Value *Callee,
229                                                 const ThunkInfo *Thunk) {
230   assert(isa<CXXMethodDecl>(CurGD.getDecl()) &&
231          "Please use a new CGF for this thunk");
232   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
233 
234   // Adjust the 'this' pointer if necessary
235   llvm::Value *AdjustedThisPtr = Thunk ? CGM.getCXXABI().performThisAdjustment(
236                                              *this, LoadCXXThis(), Thunk->This)
237                                        : LoadCXXThis();
238 
239   // Start building CallArgs.
240   CallArgList CallArgs;
241   QualType ThisType = MD->getThisType(getContext());
242   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
243 
244   if (isa<CXXDestructorDecl>(MD))
245     CGM.getCXXABI().adjustCallArgsForDestructorThunk(*this, GD, CallArgs);
246 
247   // Add the rest of the arguments.
248   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
249        E = MD->param_end(); I != E; ++I)
250     EmitDelegateCallArg(CallArgs, *I, (*I)->getLocStart());
251 
252   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
253 
254 #ifndef NDEBUG
255   const CGFunctionInfo &CallFnInfo =
256     CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
257                                        RequiredArgs::forPrototypePlus(FPT, 1));
258   assert(CallFnInfo.getRegParm() == CurFnInfo->getRegParm() &&
259          CallFnInfo.isNoReturn() == CurFnInfo->isNoReturn() &&
260          CallFnInfo.getCallingConvention() == CurFnInfo->getCallingConvention());
261   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
262          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
263                  CurFnInfo->getReturnInfo(), CurFnInfo->getReturnType()));
264   assert(CallFnInfo.arg_size() == CurFnInfo->arg_size());
265   for (unsigned i = 0, e = CurFnInfo->arg_size(); i != e; ++i)
266     assert(similar(CallFnInfo.arg_begin()[i].info,
267                    CallFnInfo.arg_begin()[i].type,
268                    CurFnInfo->arg_begin()[i].info,
269                    CurFnInfo->arg_begin()[i].type));
270 #endif
271 
272   // Determine whether we have a return value slot to use.
273   QualType ResultType =
274       CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getReturnType();
275   ReturnValueSlot Slot;
276   if (!ResultType->isVoidType() &&
277       CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
278       !hasScalarEvaluationKind(CurFnInfo->getReturnType()))
279     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
280 
281   // Now emit our call.
282   RValue RV = EmitCall(*CurFnInfo, Callee, Slot, CallArgs, MD);
283 
284   // Consider return adjustment if we have ThunkInfo.
285   if (Thunk && !Thunk->Return.isEmpty())
286     RV = PerformReturnAdjustment(*this, ResultType, RV, *Thunk);
287 
288   // Emit return.
289   if (!ResultType->isVoidType() && Slot.isNull())
290     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
291 
292   // Disable the final ARC autorelease.
293   AutoreleaseResult = false;
294 
295   FinishFunction();
296 }
297 
298 void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
299                                     const CGFunctionInfo &FnInfo,
300                                     GlobalDecl GD, const ThunkInfo &Thunk) {
301   StartThunk(Fn, GD, FnInfo);
302 
303   // Get our callee.
304   llvm::Type *Ty =
305     CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
306   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
307 
308   // Make the call and return the result.
309   EmitCallAndReturnForThunk(GD, Callee, &Thunk);
310 
311   // Set the right linkage.
312   CGM.setFunctionLinkage(GD, Fn);
313 
314   // Set the right visibility.
315   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
316   setThunkVisibility(CGM, MD, Thunk, Fn);
317 }
318 
319 void CodeGenVTables::emitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
320                                bool ForVTable) {
321   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
322 
323   // FIXME: re-use FnInfo in this computation.
324   llvm::Constant *C = CGM.GetAddrOfThunk(GD, Thunk);
325   llvm::GlobalValue *Entry;
326 
327   // Strip off a bitcast if we got one back.
328   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(C)) {
329     assert(CE->getOpcode() == llvm::Instruction::BitCast);
330     Entry = cast<llvm::GlobalValue>(CE->getOperand(0));
331   } else {
332     Entry = cast<llvm::GlobalValue>(C);
333   }
334 
335   // There's already a declaration with the same name, check if it has the same
336   // type or if we need to replace it.
337   if (Entry->getType()->getElementType() !=
338       CGM.getTypes().GetFunctionTypeForVTable(GD)) {
339     llvm::GlobalValue *OldThunkFn = Entry;
340 
341     // If the types mismatch then we have to rewrite the definition.
342     assert(OldThunkFn->isDeclaration() &&
343            "Shouldn't replace non-declaration");
344 
345     // Remove the name from the old thunk function and get a new thunk.
346     OldThunkFn->setName(StringRef());
347     Entry = cast<llvm::GlobalValue>(CGM.GetAddrOfThunk(GD, Thunk));
348 
349     // If needed, replace the old thunk with a bitcast.
350     if (!OldThunkFn->use_empty()) {
351       llvm::Constant *NewPtrForOldDecl =
352         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
353       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
354     }
355 
356     // Remove the old thunk.
357     OldThunkFn->eraseFromParent();
358   }
359 
360   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
361   bool ABIHasKeyFunctions = CGM.getTarget().getCXXABI().hasKeyFunctions();
362   bool UseAvailableExternallyLinkage = ForVTable && ABIHasKeyFunctions;
363 
364   if (!ThunkFn->isDeclaration()) {
365     if (!ABIHasKeyFunctions || UseAvailableExternallyLinkage) {
366       // There is already a thunk emitted for this function, do nothing.
367       return;
368     }
369 
370     // Change the linkage.
371     CGM.setFunctionLinkage(GD, ThunkFn);
372     return;
373   }
374 
375   CGM.SetLLVMFunctionAttributesForDefinition(GD.getDecl(), ThunkFn);
376 
377   if (ThunkFn->isVarArg()) {
378     // Varargs thunks are special; we can't just generate a call because
379     // we can't copy the varargs.  Our implementation is rather
380     // expensive/sucky at the moment, so don't generate the thunk unless
381     // we have to.
382     // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
383     if (!UseAvailableExternallyLinkage) {
384       CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
385       CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable);
386     }
387   } else {
388     // Normal thunk body generation.
389     CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
390     CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable);
391   }
392 }
393 
394 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
395                                              const ThunkInfo &Thunk) {
396   // If the ABI has key functions, only the TU with the key function should emit
397   // the thunk. However, we can allow inlining of thunks if we emit them with
398   // available_externally linkage together with vtables when optimizations are
399   // enabled.
400   if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
401       !CGM.getCodeGenOpts().OptimizationLevel)
402     return;
403 
404   // We can't emit thunks for member functions with incomplete types.
405   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
406   if (!CGM.getTypes().isFuncTypeConvertible(
407            MD->getType()->castAs<FunctionType>()))
408     return;
409 
410   emitThunk(GD, Thunk, /*ForVTable=*/true);
411 }
412 
413 void CodeGenVTables::EmitThunks(GlobalDecl GD)
414 {
415   const CXXMethodDecl *MD =
416     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
417 
418   // We don't need to generate thunks for the base destructor.
419   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
420     return;
421 
422   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
423       VTContext->getThunkInfo(GD);
424 
425   if (!ThunkInfoVector)
426     return;
427 
428   for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
429     emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
430 }
431 
432 llvm::Constant *
433 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
434                                         const VTableComponent *Components,
435                                         unsigned NumComponents,
436                                 const VTableLayout::VTableThunkTy *VTableThunks,
437                                         unsigned NumVTableThunks) {
438   SmallVector<llvm::Constant *, 64> Inits;
439 
440   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
441 
442   llvm::Type *PtrDiffTy =
443     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
444 
445   QualType ClassType = CGM.getContext().getTagDeclType(RD);
446   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
447 
448   unsigned NextVTableThunkIndex = 0;
449 
450   llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
451 
452   for (unsigned I = 0; I != NumComponents; ++I) {
453     VTableComponent Component = Components[I];
454 
455     llvm::Constant *Init = nullptr;
456 
457     switch (Component.getKind()) {
458     case VTableComponent::CK_VCallOffset:
459       Init = llvm::ConstantInt::get(PtrDiffTy,
460                                     Component.getVCallOffset().getQuantity());
461       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
462       break;
463     case VTableComponent::CK_VBaseOffset:
464       Init = llvm::ConstantInt::get(PtrDiffTy,
465                                     Component.getVBaseOffset().getQuantity());
466       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
467       break;
468     case VTableComponent::CK_OffsetToTop:
469       Init = llvm::ConstantInt::get(PtrDiffTy,
470                                     Component.getOffsetToTop().getQuantity());
471       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
472       break;
473     case VTableComponent::CK_RTTI:
474       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
475       break;
476     case VTableComponent::CK_FunctionPointer:
477     case VTableComponent::CK_CompleteDtorPointer:
478     case VTableComponent::CK_DeletingDtorPointer: {
479       GlobalDecl GD;
480 
481       // Get the right global decl.
482       switch (Component.getKind()) {
483       default:
484         llvm_unreachable("Unexpected vtable component kind");
485       case VTableComponent::CK_FunctionPointer:
486         GD = Component.getFunctionDecl();
487         break;
488       case VTableComponent::CK_CompleteDtorPointer:
489         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
490         break;
491       case VTableComponent::CK_DeletingDtorPointer:
492         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
493         break;
494       }
495 
496       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
497         // We have a pure virtual member function.
498         if (!PureVirtualFn) {
499           llvm::FunctionType *Ty =
500             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
501           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
502           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
503           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
504                                                          CGM.Int8PtrTy);
505         }
506         Init = PureVirtualFn;
507       } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
508         if (!DeletedVirtualFn) {
509           llvm::FunctionType *Ty =
510             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
511           StringRef DeletedCallName =
512             CGM.getCXXABI().GetDeletedVirtualCallName();
513           DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
514           DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
515                                                          CGM.Int8PtrTy);
516         }
517         Init = DeletedVirtualFn;
518       } else {
519         // Check if we should use a thunk.
520         if (NextVTableThunkIndex < NumVTableThunks &&
521             VTableThunks[NextVTableThunkIndex].first == I) {
522           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
523 
524           maybeEmitThunkForVTable(GD, Thunk);
525           Init = CGM.GetAddrOfThunk(GD, Thunk);
526 
527           NextVTableThunkIndex++;
528         } else {
529           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
530 
531           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
532         }
533 
534         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
535       }
536       break;
537     }
538 
539     case VTableComponent::CK_UnusedFunctionPointer:
540       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
541       break;
542     };
543 
544     Inits.push_back(Init);
545   }
546 
547   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
548   return llvm::ConstantArray::get(ArrayType, Inits);
549 }
550 
551 llvm::GlobalVariable *
552 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
553                                       const BaseSubobject &Base,
554                                       bool BaseIsVirtual,
555                                    llvm::GlobalVariable::LinkageTypes Linkage,
556                                       VTableAddressPointsMapTy& AddressPoints) {
557   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
558     DI->completeClassData(Base.getBase());
559 
560   std::unique_ptr<VTableLayout> VTLayout(
561       getItaniumVTableContext().createConstructionVTableLayout(
562           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
563 
564   // Add the address points.
565   AddressPoints = VTLayout->getAddressPoints();
566 
567   // Get the mangled construction vtable name.
568   SmallString<256> OutName;
569   llvm::raw_svector_ostream Out(OutName);
570   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
571       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
572                            Base.getBase(), Out);
573   Out.flush();
574   StringRef Name = OutName.str();
575 
576   llvm::ArrayType *ArrayType =
577     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
578 
579   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
580   // guarantee that they actually will be available externally. Instead, when
581   // emitting an available_externally VTT, we provide references to an internal
582   // linkage construction vtable. The ABI only requires complete-object vtables
583   // to be the same for all instances of a type, not construction vtables.
584   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
585     Linkage = llvm::GlobalVariable::InternalLinkage;
586 
587   // Create the variable that will hold the construction vtable.
588   llvm::GlobalVariable *VTable =
589     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
590   CGM.setGlobalVisibility(VTable, RD);
591 
592   // V-tables are always unnamed_addr.
593   VTable->setUnnamedAddr(true);
594 
595   // Create and set the initializer.
596   llvm::Constant *Init =
597     CreateVTableInitializer(Base.getBase(),
598                             VTLayout->vtable_component_begin(),
599                             VTLayout->getNumVTableComponents(),
600                             VTLayout->vtable_thunk_begin(),
601                             VTLayout->getNumVTableThunks());
602   VTable->setInitializer(Init);
603 
604   return VTable;
605 }
606 
607 /// Compute the required linkage of the v-table for the given class.
608 ///
609 /// Note that we only call this at the end of the translation unit.
610 llvm::GlobalVariable::LinkageTypes
611 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
612   if (!RD->isExternallyVisible())
613     return llvm::GlobalVariable::InternalLinkage;
614 
615   // We're at the end of the translation unit, so the current key
616   // function is fully correct.
617   if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
618     // If this class has a key function, use that to determine the
619     // linkage of the vtable.
620     const FunctionDecl *def = nullptr;
621     if (keyFunction->hasBody(def))
622       keyFunction = cast<CXXMethodDecl>(def);
623 
624     switch (keyFunction->getTemplateSpecializationKind()) {
625       case TSK_Undeclared:
626       case TSK_ExplicitSpecialization:
627         assert(def && "Should not have been asked to emit this");
628         if (keyFunction->isInlined())
629           return !Context.getLangOpts().AppleKext ?
630                    llvm::GlobalVariable::LinkOnceODRLinkage :
631                    llvm::Function::InternalLinkage;
632 
633         return llvm::GlobalVariable::ExternalLinkage;
634 
635       case TSK_ImplicitInstantiation:
636         return !Context.getLangOpts().AppleKext ?
637                  llvm::GlobalVariable::LinkOnceODRLinkage :
638                  llvm::Function::InternalLinkage;
639 
640       case TSK_ExplicitInstantiationDefinition:
641         return !Context.getLangOpts().AppleKext ?
642                  llvm::GlobalVariable::WeakODRLinkage :
643                  llvm::Function::InternalLinkage;
644 
645       case TSK_ExplicitInstantiationDeclaration:
646         llvm_unreachable("Should not have been asked to emit this");
647     }
648   }
649 
650   // -fapple-kext mode does not support weak linkage, so we must use
651   // internal linkage.
652   if (Context.getLangOpts().AppleKext)
653     return llvm::Function::InternalLinkage;
654 
655   switch (RD->getTemplateSpecializationKind()) {
656   case TSK_Undeclared:
657   case TSK_ExplicitSpecialization:
658   case TSK_ImplicitInstantiation:
659     return llvm::GlobalVariable::LinkOnceODRLinkage;
660 
661   case TSK_ExplicitInstantiationDeclaration:
662     llvm_unreachable("Should not have been asked to emit this");
663 
664   case TSK_ExplicitInstantiationDefinition:
665       return llvm::GlobalVariable::WeakODRLinkage;
666   }
667 
668   llvm_unreachable("Invalid TemplateSpecializationKind!");
669 }
670 
671 /// This is a callback from Sema to tell us that it believes that a
672 /// particular v-table is required to be emitted in this translation
673 /// unit.
674 ///
675 /// The reason we don't simply trust this callback is because Sema
676 /// will happily report that something is used even when it's used
677 /// only in code that we don't actually have to emit.
678 ///
679 /// \param isRequired - if true, the v-table is mandatory, e.g.
680 ///   because the translation unit defines the key function
681 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
682   if (!isRequired) return;
683 
684   VTables.GenerateClassData(theClass);
685 }
686 
687 void
688 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
689   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
690     DI->completeClassData(RD);
691 
692   if (RD->getNumVBases())
693     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
694 
695   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
696 }
697 
698 /// At this point in the translation unit, does it appear that can we
699 /// rely on the vtable being defined elsewhere in the program?
700 ///
701 /// The response is really only definitive when called at the end of
702 /// the translation unit.
703 ///
704 /// The only semantic restriction here is that the object file should
705 /// not contain a v-table definition when that v-table is defined
706 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
707 /// v-tables when unnecessary.
708 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
709   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
710 
711   // If we have an explicit instantiation declaration (and not a
712   // definition), the v-table is defined elsewhere.
713   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
714   if (TSK == TSK_ExplicitInstantiationDeclaration)
715     return true;
716 
717   // Otherwise, if the class is an instantiated template, the
718   // v-table must be defined here.
719   if (TSK == TSK_ImplicitInstantiation ||
720       TSK == TSK_ExplicitInstantiationDefinition)
721     return false;
722 
723   // Otherwise, if the class doesn't have a key function (possibly
724   // anymore), the v-table must be defined here.
725   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
726   if (!keyFunction)
727     return false;
728 
729   // Otherwise, if we don't have a definition of the key function, the
730   // v-table must be defined somewhere else.
731   return !keyFunction->hasBody();
732 }
733 
734 /// Given that we're currently at the end of the translation unit, and
735 /// we've emitted a reference to the v-table for this class, should
736 /// we define that v-table?
737 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
738                                                    const CXXRecordDecl *RD) {
739   return !CGM.getVTables().isVTableExternal(RD);
740 }
741 
742 /// Given that at some point we emitted a reference to one or more
743 /// v-tables, and that we are now at the end of the translation unit,
744 /// decide whether we should emit them.
745 void CodeGenModule::EmitDeferredVTables() {
746 #ifndef NDEBUG
747   // Remember the size of DeferredVTables, because we're going to assume
748   // that this entire operation doesn't modify it.
749   size_t savedSize = DeferredVTables.size();
750 #endif
751 
752   typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
753   for (const_iterator i = DeferredVTables.begin(),
754                       e = DeferredVTables.end(); i != e; ++i) {
755     const CXXRecordDecl *RD = *i;
756     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
757       VTables.GenerateClassData(RD);
758   }
759 
760   assert(savedSize == DeferredVTables.size() &&
761          "deferred extra v-tables during v-table emission?");
762   DeferredVTables.clear();
763 }
764