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