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, GD,
386                                       !Thunk.Return.isEmpty());
387     }
388   } else {
389     // Normal thunk body generation.
390     CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
391     CGM.getCXXABI().setThunkLinkage(ThunkFn, ForVTable, GD,
392                                     !Thunk.Return.isEmpty());
393   }
394 }
395 
396 void CodeGenVTables::maybeEmitThunkForVTable(GlobalDecl GD,
397                                              const ThunkInfo &Thunk) {
398   // If the ABI has key functions, only the TU with the key function should emit
399   // the thunk. However, we can allow inlining of thunks if we emit them with
400   // available_externally linkage together with vtables when optimizations are
401   // enabled.
402   if (CGM.getTarget().getCXXABI().hasKeyFunctions() &&
403       !CGM.getCodeGenOpts().OptimizationLevel)
404     return;
405 
406   // We can't emit thunks for member functions with incomplete types.
407   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
408   if (!CGM.getTypes().isFuncTypeConvertible(
409            MD->getType()->castAs<FunctionType>()))
410     return;
411 
412   emitThunk(GD, Thunk, /*ForVTable=*/true);
413 }
414 
415 void CodeGenVTables::EmitThunks(GlobalDecl GD)
416 {
417   const CXXMethodDecl *MD =
418     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
419 
420   // We don't need to generate thunks for the base destructor.
421   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
422     return;
423 
424   const VTableContextBase::ThunkInfoVectorTy *ThunkInfoVector =
425       VTContext->getThunkInfo(GD);
426 
427   if (!ThunkInfoVector)
428     return;
429 
430   for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
431     emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
432 }
433 
434 llvm::Constant *
435 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
436                                         const VTableComponent *Components,
437                                         unsigned NumComponents,
438                                 const VTableLayout::VTableThunkTy *VTableThunks,
439                                         unsigned NumVTableThunks) {
440   SmallVector<llvm::Constant *, 64> Inits;
441 
442   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
443 
444   llvm::Type *PtrDiffTy =
445     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
446 
447   QualType ClassType = CGM.getContext().getTagDeclType(RD);
448   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
449 
450   unsigned NextVTableThunkIndex = 0;
451 
452   llvm::Constant *PureVirtualFn = nullptr, *DeletedVirtualFn = nullptr;
453 
454   for (unsigned I = 0; I != NumComponents; ++I) {
455     VTableComponent Component = Components[I];
456 
457     llvm::Constant *Init = nullptr;
458 
459     switch (Component.getKind()) {
460     case VTableComponent::CK_VCallOffset:
461       Init = llvm::ConstantInt::get(PtrDiffTy,
462                                     Component.getVCallOffset().getQuantity());
463       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
464       break;
465     case VTableComponent::CK_VBaseOffset:
466       Init = llvm::ConstantInt::get(PtrDiffTy,
467                                     Component.getVBaseOffset().getQuantity());
468       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
469       break;
470     case VTableComponent::CK_OffsetToTop:
471       Init = llvm::ConstantInt::get(PtrDiffTy,
472                                     Component.getOffsetToTop().getQuantity());
473       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
474       break;
475     case VTableComponent::CK_RTTI:
476       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
477       break;
478     case VTableComponent::CK_FunctionPointer:
479     case VTableComponent::CK_CompleteDtorPointer:
480     case VTableComponent::CK_DeletingDtorPointer: {
481       GlobalDecl GD;
482 
483       // Get the right global decl.
484       switch (Component.getKind()) {
485       default:
486         llvm_unreachable("Unexpected vtable component kind");
487       case VTableComponent::CK_FunctionPointer:
488         GD = Component.getFunctionDecl();
489         break;
490       case VTableComponent::CK_CompleteDtorPointer:
491         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
492         break;
493       case VTableComponent::CK_DeletingDtorPointer:
494         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
495         break;
496       }
497 
498       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
499         // We have a pure virtual member function.
500         if (!PureVirtualFn) {
501           llvm::FunctionType *Ty =
502             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
503           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
504           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
505           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
506                                                          CGM.Int8PtrTy);
507         }
508         Init = PureVirtualFn;
509       } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
510         if (!DeletedVirtualFn) {
511           llvm::FunctionType *Ty =
512             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
513           StringRef DeletedCallName =
514             CGM.getCXXABI().GetDeletedVirtualCallName();
515           DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
516           DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
517                                                          CGM.Int8PtrTy);
518         }
519         Init = DeletedVirtualFn;
520       } else {
521         // Check if we should use a thunk.
522         if (NextVTableThunkIndex < NumVTableThunks &&
523             VTableThunks[NextVTableThunkIndex].first == I) {
524           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
525 
526           maybeEmitThunkForVTable(GD, Thunk);
527           Init = CGM.GetAddrOfThunk(GD, Thunk);
528 
529           NextVTableThunkIndex++;
530         } else {
531           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
532 
533           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
534         }
535 
536         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
537       }
538       break;
539     }
540 
541     case VTableComponent::CK_UnusedFunctionPointer:
542       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
543       break;
544     };
545 
546     Inits.push_back(Init);
547   }
548 
549   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
550   return llvm::ConstantArray::get(ArrayType, Inits);
551 }
552 
553 llvm::GlobalVariable *
554 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
555                                       const BaseSubobject &Base,
556                                       bool BaseIsVirtual,
557                                    llvm::GlobalVariable::LinkageTypes Linkage,
558                                       VTableAddressPointsMapTy& AddressPoints) {
559   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
560     DI->completeClassData(Base.getBase());
561 
562   std::unique_ptr<VTableLayout> VTLayout(
563       getItaniumVTableContext().createConstructionVTableLayout(
564           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
565 
566   // Add the address points.
567   AddressPoints = VTLayout->getAddressPoints();
568 
569   // Get the mangled construction vtable name.
570   SmallString<256> OutName;
571   llvm::raw_svector_ostream Out(OutName);
572   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
573       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
574                            Base.getBase(), Out);
575   Out.flush();
576   StringRef Name = OutName.str();
577 
578   llvm::ArrayType *ArrayType =
579     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
580 
581   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
582   // guarantee that they actually will be available externally. Instead, when
583   // emitting an available_externally VTT, we provide references to an internal
584   // linkage construction vtable. The ABI only requires complete-object vtables
585   // to be the same for all instances of a type, not construction vtables.
586   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
587     Linkage = llvm::GlobalVariable::InternalLinkage;
588 
589   // Create the variable that will hold the construction vtable.
590   llvm::GlobalVariable *VTable =
591     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
592   CGM.setGlobalVisibility(VTable, RD);
593 
594   // V-tables are always unnamed_addr.
595   VTable->setUnnamedAddr(true);
596 
597   // Create and set the initializer.
598   llvm::Constant *Init =
599     CreateVTableInitializer(Base.getBase(),
600                             VTLayout->vtable_component_begin(),
601                             VTLayout->getNumVTableComponents(),
602                             VTLayout->vtable_thunk_begin(),
603                             VTLayout->getNumVTableThunks());
604   VTable->setInitializer(Init);
605 
606   return VTable;
607 }
608 
609 /// Compute the required linkage of the v-table for the given class.
610 ///
611 /// Note that we only call this at the end of the translation unit.
612 llvm::GlobalVariable::LinkageTypes
613 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
614   if (!RD->isExternallyVisible())
615     return llvm::GlobalVariable::InternalLinkage;
616 
617   // We're at the end of the translation unit, so the current key
618   // function is fully correct.
619   if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
620     // If this class has a key function, use that to determine the
621     // linkage of the vtable.
622     const FunctionDecl *def = nullptr;
623     if (keyFunction->hasBody(def))
624       keyFunction = cast<CXXMethodDecl>(def);
625 
626     switch (keyFunction->getTemplateSpecializationKind()) {
627       case TSK_Undeclared:
628       case TSK_ExplicitSpecialization:
629         assert(def && "Should not have been asked to emit this");
630         if (keyFunction->isInlined())
631           return !Context.getLangOpts().AppleKext ?
632                    llvm::GlobalVariable::LinkOnceODRLinkage :
633                    llvm::Function::InternalLinkage;
634 
635         return llvm::GlobalVariable::ExternalLinkage;
636 
637       case TSK_ImplicitInstantiation:
638         return !Context.getLangOpts().AppleKext ?
639                  llvm::GlobalVariable::LinkOnceODRLinkage :
640                  llvm::Function::InternalLinkage;
641 
642       case TSK_ExplicitInstantiationDefinition:
643         return !Context.getLangOpts().AppleKext ?
644                  llvm::GlobalVariable::WeakODRLinkage :
645                  llvm::Function::InternalLinkage;
646 
647       case TSK_ExplicitInstantiationDeclaration:
648         llvm_unreachable("Should not have been asked to emit this");
649     }
650   }
651 
652   // -fapple-kext mode does not support weak linkage, so we must use
653   // internal linkage.
654   if (Context.getLangOpts().AppleKext)
655     return llvm::Function::InternalLinkage;
656 
657   llvm::GlobalVariable::LinkageTypes DiscardableODRLinkage =
658       llvm::GlobalValue::LinkOnceODRLinkage;
659   llvm::GlobalVariable::LinkageTypes NonDiscardableODRLinkage =
660       llvm::GlobalValue::WeakODRLinkage;
661   if (RD->hasAttr<DLLExportAttr>()) {
662     // Cannot discard exported vtables.
663     DiscardableODRLinkage = NonDiscardableODRLinkage;
664   } else if (RD->hasAttr<DLLImportAttr>()) {
665     // Imported vtables are available externally.
666     DiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
667     NonDiscardableODRLinkage = llvm::GlobalVariable::AvailableExternallyLinkage;
668   }
669 
670   switch (RD->getTemplateSpecializationKind()) {
671   case TSK_Undeclared:
672   case TSK_ExplicitSpecialization:
673   case TSK_ImplicitInstantiation:
674     return DiscardableODRLinkage;
675 
676   case TSK_ExplicitInstantiationDeclaration:
677     llvm_unreachable("Should not have been asked to emit this");
678 
679   case TSK_ExplicitInstantiationDefinition:
680     return NonDiscardableODRLinkage;
681   }
682 
683   llvm_unreachable("Invalid TemplateSpecializationKind!");
684 }
685 
686 /// This is a callback from Sema to tell us that it believes that a
687 /// particular v-table is required to be emitted in this translation
688 /// unit.
689 ///
690 /// The reason we don't simply trust this callback is because Sema
691 /// will happily report that something is used even when it's used
692 /// only in code that we don't actually have to emit.
693 ///
694 /// \param isRequired - if true, the v-table is mandatory, e.g.
695 ///   because the translation unit defines the key function
696 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
697   if (!isRequired) return;
698 
699   VTables.GenerateClassData(theClass);
700 }
701 
702 void
703 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
704   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
705     DI->completeClassData(RD);
706 
707   if (RD->getNumVBases())
708     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
709 
710   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
711 }
712 
713 /// At this point in the translation unit, does it appear that can we
714 /// rely on the vtable being defined elsewhere in the program?
715 ///
716 /// The response is really only definitive when called at the end of
717 /// the translation unit.
718 ///
719 /// The only semantic restriction here is that the object file should
720 /// not contain a v-table definition when that v-table is defined
721 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
722 /// v-tables when unnecessary.
723 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
724   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
725 
726   // If we have an explicit instantiation declaration (and not a
727   // definition), the v-table is defined elsewhere.
728   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
729   if (TSK == TSK_ExplicitInstantiationDeclaration)
730     return true;
731 
732   // Otherwise, if the class is an instantiated template, the
733   // v-table must be defined here.
734   if (TSK == TSK_ImplicitInstantiation ||
735       TSK == TSK_ExplicitInstantiationDefinition)
736     return false;
737 
738   // Otherwise, if the class doesn't have a key function (possibly
739   // anymore), the v-table must be defined here.
740   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
741   if (!keyFunction)
742     return false;
743 
744   // Otherwise, if we don't have a definition of the key function, the
745   // v-table must be defined somewhere else.
746   return !keyFunction->hasBody();
747 }
748 
749 /// Given that we're currently at the end of the translation unit, and
750 /// we've emitted a reference to the v-table for this class, should
751 /// we define that v-table?
752 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
753                                                    const CXXRecordDecl *RD) {
754   return !CGM.getVTables().isVTableExternal(RD);
755 }
756 
757 /// Given that at some point we emitted a reference to one or more
758 /// v-tables, and that we are now at the end of the translation unit,
759 /// decide whether we should emit them.
760 void CodeGenModule::EmitDeferredVTables() {
761 #ifndef NDEBUG
762   // Remember the size of DeferredVTables, because we're going to assume
763   // that this entire operation doesn't modify it.
764   size_t savedSize = DeferredVTables.size();
765 #endif
766 
767   typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
768   for (const_iterator i = DeferredVTables.begin(),
769                       e = DeferredVTables.end(); i != e; ++i) {
770     const CXXRecordDecl *RD = *i;
771     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
772       VTables.GenerateClassData(RD);
773   }
774 
775   assert(savedSize == DeferredVTables.size() &&
776          "deferred extra v-tables during v-table emission?");
777   DeferredVTables.clear();
778 }
779