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) : CGM(CGM) {
33   if (CGM.getTarget().getCXXABI().isMicrosoft())
34     VTContext.reset(new MicrosoftVTableContext(CGM.getContext()));
35   else
36     VTContext.reset(new ItaniumVTableContext(CGM.getContext()));
37 }
38 
39 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
40                                               const ThunkInfo &Thunk) {
41   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
42 
43   // Compute the mangled name.
44   SmallString<256> Name;
45   llvm::raw_svector_ostream Out(Name);
46   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
47     getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
48                                                       Thunk.This, Out);
49   else
50     getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
51   Out.flush();
52 
53   llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
54   return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true,
55                                  /*DontDefer*/ true);
56 }
57 
58 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
59                                const ThunkInfo &Thunk, llvm::Function *Fn) {
60   CGM.setGlobalVisibility(Fn, MD);
61 
62   if (!CGM.getCodeGenOpts().HiddenWeakVTables)
63     return;
64 
65   // If the thunk has weak/linkonce linkage, but the function must be
66   // emitted in every translation unit that references it, then we can
67   // emit its thunks with hidden visibility, since its thunks must be
68   // emitted when the function is.
69 
70   // This follows CodeGenModule::setTypeVisibility; see the comments
71   // there for explanation.
72 
73   if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
74        Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
75       Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
76     return;
77 
78   if (MD->getExplicitVisibility(ValueDecl::VisibilityForValue))
79     return;
80 
81   switch (MD->getTemplateSpecializationKind()) {
82   case TSK_ExplicitInstantiationDefinition:
83   case TSK_ExplicitInstantiationDeclaration:
84     return;
85 
86   case TSK_Undeclared:
87     break;
88 
89   case TSK_ExplicitSpecialization:
90   case TSK_ImplicitInstantiation:
91     return;
92     break;
93   }
94 
95   // If there's an explicit definition, and that definition is
96   // out-of-line, then we can't assume that all users will have a
97   // definition to emit.
98   const FunctionDecl *Def = 0;
99   if (MD->hasBody(Def) && Def->isOutOfLine())
100     return;
101 
102   Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
103 }
104 
105 #ifndef NDEBUG
106 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
107                     const ABIArgInfo &infoR, CanQualType typeR) {
108   return (infoL.getKind() == infoR.getKind() &&
109           (typeL == typeR ||
110            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
111            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
112 }
113 #endif
114 
115 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
116                                       QualType ResultType, RValue RV,
117                                       const ThunkInfo &Thunk) {
118   // Emit the return adjustment.
119   bool NullCheckValue = !ResultType->isReferenceType();
120 
121   llvm::BasicBlock *AdjustNull = 0;
122   llvm::BasicBlock *AdjustNotNull = 0;
123   llvm::BasicBlock *AdjustEnd = 0;
124 
125   llvm::Value *ReturnValue = RV.getScalarVal();
126 
127   if (NullCheckValue) {
128     AdjustNull = CGF.createBasicBlock("adjust.null");
129     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
130     AdjustEnd = CGF.createBasicBlock("adjust.end");
131 
132     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
133     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
134     CGF.EmitBlock(AdjustNotNull);
135   }
136 
137   ReturnValue = CGF.CGM.getCXXABI().performReturnAdjustment(CGF, ReturnValue,
138                                                             Thunk.Return);
139 
140   if (NullCheckValue) {
141     CGF.Builder.CreateBr(AdjustEnd);
142     CGF.EmitBlock(AdjustNull);
143     CGF.Builder.CreateBr(AdjustEnd);
144     CGF.EmitBlock(AdjustEnd);
145 
146     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
147     PHI->addIncoming(ReturnValue, AdjustNotNull);
148     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
149                      AdjustNull);
150     ReturnValue = PHI;
151   }
152 
153   return RValue::get(ReturnValue);
154 }
155 
156 // This function does roughly the same thing as GenerateThunk, but in a
157 // very different way, so that va_start and va_end work correctly.
158 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
159 //        a function, and that there is an alloca built in the entry block
160 //        for all accesses to "this".
161 // FIXME: This function assumes there is only one "ret" statement per function.
162 // FIXME: Cloning isn't correct in the presence of indirect goto!
163 // FIXME: This implementation of thunks bloats codesize by duplicating the
164 //        function definition.  There are alternatives:
165 //        1. Add some sort of stub support to LLVM for cases where we can
166 //           do a this adjustment, then a sibcall.
167 //        2. We could transform the definition to take a va_list instead of an
168 //           actual variable argument list, then have the thunks (including a
169 //           no-op thunk for the regular definition) call va_start/va_end.
170 //           There's a bit of per-call overhead for this solution, but it's
171 //           better for codesize if the definition is long.
172 void CodeGenFunction::GenerateVarArgsThunk(
173                                       llvm::Function *Fn,
174                                       const CGFunctionInfo &FnInfo,
175                                       GlobalDecl GD, const ThunkInfo &Thunk) {
176   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
177   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
178   QualType ResultType = FPT->getResultType();
179 
180   // Get the original function
181   assert(FnInfo.isVariadic());
182   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
183   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
184   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
185 
186   // Clone to thunk.
187   llvm::ValueToValueMapTy VMap;
188   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
189                                               /*ModuleLevelChanges=*/false);
190   CGM.getModule().getFunctionList().push_back(NewFn);
191   Fn->replaceAllUsesWith(NewFn);
192   NewFn->takeName(Fn);
193   Fn->eraseFromParent();
194   Fn = NewFn;
195 
196   // "Initialize" CGF (minimally).
197   CurFn = Fn;
198 
199   // Get the "this" value
200   llvm::Function::arg_iterator AI = Fn->arg_begin();
201   if (CGM.ReturnTypeUsesSRet(FnInfo))
202     ++AI;
203 
204   // Find the first store of "this", which will be to the alloca associated
205   // with "this".
206   llvm::Value *ThisPtr = &*AI;
207   llvm::BasicBlock *EntryBB = Fn->begin();
208   llvm::Instruction *ThisStore = 0;
209   for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
210        I != E; I++) {
211     if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
212       ThisStore = cast<llvm::StoreInst>(I);
213       break;
214     }
215   }
216   assert(ThisStore && "Store of this should be in entry block?");
217   // Adjust "this", if necessary.
218   Builder.SetInsertPoint(ThisStore);
219   llvm::Value *AdjustedThisPtr =
220       CGM.getCXXABI().performThisAdjustment(*this, ThisPtr, Thunk.This);
221   ThisStore->setOperand(0, AdjustedThisPtr);
222 
223   if (!Thunk.Return.isEmpty()) {
224     // Fix up the returned value, if necessary.
225     for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
226       llvm::Instruction *T = I->getTerminator();
227       if (isa<llvm::ReturnInst>(T)) {
228         RValue RV = RValue::get(T->getOperand(0));
229         T->eraseFromParent();
230         Builder.SetInsertPoint(&*I);
231         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
232         Builder.CreateRet(RV.getScalarVal());
233         break;
234       }
235     }
236   }
237 }
238 
239 void CodeGenFunction::StartThunk(llvm::Function *Fn, GlobalDecl GD,
240                                  const CGFunctionInfo &FnInfo) {
241   assert(!CurGD.getDecl() && "CurGD was already set!");
242   CurGD = GD;
243 
244   // Build FunctionArgs.
245   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
246   QualType ThisType = MD->getThisType(getContext());
247   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
248   QualType ResultType =
249     CGM.getCXXABI().HasThisReturn(GD) ? ThisType : FPT->getResultType();
250   FunctionArgList FunctionArgs;
251 
252   // Create the implicit 'this' parameter declaration.
253   CGM.getCXXABI().buildThisParam(*this, FunctionArgs);
254 
255   // Add the rest of the parameters.
256   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
257                                           E = MD->param_end();
258        I != E; ++I)
259     FunctionArgs.push_back(*I);
260 
261   if (isa<CXXDestructorDecl>(MD))
262     CGM.getCXXABI().addImplicitStructorParams(*this, ResultType, FunctionArgs);
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       VTContext->getThunkInfo(GD);
467 
468   if (!ThunkInfoVector)
469     return;
470 
471   for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
472     emitThunk(GD, (*ThunkInfoVector)[I], /*ForVTable=*/false);
473 }
474 
475 llvm::Constant *
476 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
477                                         const VTableComponent *Components,
478                                         unsigned NumComponents,
479                                 const VTableLayout::VTableThunkTy *VTableThunks,
480                                         unsigned NumVTableThunks) {
481   SmallVector<llvm::Constant *, 64> Inits;
482 
483   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
484 
485   llvm::Type *PtrDiffTy =
486     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
487 
488   QualType ClassType = CGM.getContext().getTagDeclType(RD);
489   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
490 
491   unsigned NextVTableThunkIndex = 0;
492 
493   llvm::Constant *PureVirtualFn = 0, *DeletedVirtualFn = 0;
494 
495   for (unsigned I = 0; I != NumComponents; ++I) {
496     VTableComponent Component = Components[I];
497 
498     llvm::Constant *Init = 0;
499 
500     switch (Component.getKind()) {
501     case VTableComponent::CK_VCallOffset:
502       Init = llvm::ConstantInt::get(PtrDiffTy,
503                                     Component.getVCallOffset().getQuantity());
504       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
505       break;
506     case VTableComponent::CK_VBaseOffset:
507       Init = llvm::ConstantInt::get(PtrDiffTy,
508                                     Component.getVBaseOffset().getQuantity());
509       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
510       break;
511     case VTableComponent::CK_OffsetToTop:
512       Init = llvm::ConstantInt::get(PtrDiffTy,
513                                     Component.getOffsetToTop().getQuantity());
514       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
515       break;
516     case VTableComponent::CK_RTTI:
517       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
518       break;
519     case VTableComponent::CK_FunctionPointer:
520     case VTableComponent::CK_CompleteDtorPointer:
521     case VTableComponent::CK_DeletingDtorPointer: {
522       GlobalDecl GD;
523 
524       // Get the right global decl.
525       switch (Component.getKind()) {
526       default:
527         llvm_unreachable("Unexpected vtable component kind");
528       case VTableComponent::CK_FunctionPointer:
529         GD = Component.getFunctionDecl();
530         break;
531       case VTableComponent::CK_CompleteDtorPointer:
532         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
533         break;
534       case VTableComponent::CK_DeletingDtorPointer:
535         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
536         break;
537       }
538 
539       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
540         // We have a pure virtual member function.
541         if (!PureVirtualFn) {
542           llvm::FunctionType *Ty =
543             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
544           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
545           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
546           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
547                                                          CGM.Int8PtrTy);
548         }
549         Init = PureVirtualFn;
550       } else if (cast<CXXMethodDecl>(GD.getDecl())->isDeleted()) {
551         if (!DeletedVirtualFn) {
552           llvm::FunctionType *Ty =
553             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
554           StringRef DeletedCallName =
555             CGM.getCXXABI().GetDeletedVirtualCallName();
556           DeletedVirtualFn = CGM.CreateRuntimeFunction(Ty, DeletedCallName);
557           DeletedVirtualFn = llvm::ConstantExpr::getBitCast(DeletedVirtualFn,
558                                                          CGM.Int8PtrTy);
559         }
560         Init = DeletedVirtualFn;
561       } else {
562         // Check if we should use a thunk.
563         if (NextVTableThunkIndex < NumVTableThunks &&
564             VTableThunks[NextVTableThunkIndex].first == I) {
565           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
566 
567           maybeEmitThunkForVTable(GD, Thunk);
568           Init = CGM.GetAddrOfThunk(GD, Thunk);
569 
570           NextVTableThunkIndex++;
571         } else {
572           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
573 
574           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
575         }
576 
577         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
578       }
579       break;
580     }
581 
582     case VTableComponent::CK_UnusedFunctionPointer:
583       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
584       break;
585     };
586 
587     Inits.push_back(Init);
588   }
589 
590   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
591   return llvm::ConstantArray::get(ArrayType, Inits);
592 }
593 
594 llvm::GlobalVariable *
595 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
596                                       const BaseSubobject &Base,
597                                       bool BaseIsVirtual,
598                                    llvm::GlobalVariable::LinkageTypes Linkage,
599                                       VTableAddressPointsMapTy& AddressPoints) {
600   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
601     DI->completeClassData(Base.getBase());
602 
603   OwningPtr<VTableLayout> VTLayout(
604       getItaniumVTableContext().createConstructionVTableLayout(
605           Base.getBase(), Base.getBaseOffset(), BaseIsVirtual, RD));
606 
607   // Add the address points.
608   AddressPoints = VTLayout->getAddressPoints();
609 
610   // Get the mangled construction vtable name.
611   SmallString<256> OutName;
612   llvm::raw_svector_ostream Out(OutName);
613   cast<ItaniumMangleContext>(CGM.getCXXABI().getMangleContext())
614       .mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(),
615                            Base.getBase(), Out);
616   Out.flush();
617   StringRef Name = OutName.str();
618 
619   llvm::ArrayType *ArrayType =
620     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
621 
622   // Construction vtable symbols are not part of the Itanium ABI, so we cannot
623   // guarantee that they actually will be available externally. Instead, when
624   // emitting an available_externally VTT, we provide references to an internal
625   // linkage construction vtable. The ABI only requires complete-object vtables
626   // to be the same for all instances of a type, not construction vtables.
627   if (Linkage == llvm::GlobalVariable::AvailableExternallyLinkage)
628     Linkage = llvm::GlobalVariable::InternalLinkage;
629 
630   // Create the variable that will hold the construction vtable.
631   llvm::GlobalVariable *VTable =
632     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
633   CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
634 
635   // V-tables are always unnamed_addr.
636   VTable->setUnnamedAddr(true);
637 
638   // Create and set the initializer.
639   llvm::Constant *Init =
640     CreateVTableInitializer(Base.getBase(),
641                             VTLayout->vtable_component_begin(),
642                             VTLayout->getNumVTableComponents(),
643                             VTLayout->vtable_thunk_begin(),
644                             VTLayout->getNumVTableThunks());
645   VTable->setInitializer(Init);
646 
647   return VTable;
648 }
649 
650 /// Compute the required linkage of the v-table for the given class.
651 ///
652 /// Note that we only call this at the end of the translation unit.
653 llvm::GlobalVariable::LinkageTypes
654 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
655   if (!RD->isExternallyVisible())
656     return llvm::GlobalVariable::InternalLinkage;
657 
658   // We're at the end of the translation unit, so the current key
659   // function is fully correct.
660   if (const CXXMethodDecl *keyFunction = Context.getCurrentKeyFunction(RD)) {
661     // If this class has a key function, use that to determine the
662     // linkage of the vtable.
663     const FunctionDecl *def = 0;
664     if (keyFunction->hasBody(def))
665       keyFunction = cast<CXXMethodDecl>(def);
666 
667     switch (keyFunction->getTemplateSpecializationKind()) {
668       case TSK_Undeclared:
669       case TSK_ExplicitSpecialization:
670         assert(def && "Should not have been asked to emit this");
671         if (keyFunction->isInlined())
672           return !Context.getLangOpts().AppleKext ?
673                    llvm::GlobalVariable::LinkOnceODRLinkage :
674                    llvm::Function::InternalLinkage;
675 
676         return llvm::GlobalVariable::ExternalLinkage;
677 
678       case TSK_ImplicitInstantiation:
679         return !Context.getLangOpts().AppleKext ?
680                  llvm::GlobalVariable::LinkOnceODRLinkage :
681                  llvm::Function::InternalLinkage;
682 
683       case TSK_ExplicitInstantiationDefinition:
684         return !Context.getLangOpts().AppleKext ?
685                  llvm::GlobalVariable::WeakODRLinkage :
686                  llvm::Function::InternalLinkage;
687 
688       case TSK_ExplicitInstantiationDeclaration:
689         llvm_unreachable("Should not have been asked to emit this");
690     }
691   }
692 
693   // -fapple-kext mode does not support weak linkage, so we must use
694   // internal linkage.
695   if (Context.getLangOpts().AppleKext)
696     return llvm::Function::InternalLinkage;
697 
698   switch (RD->getTemplateSpecializationKind()) {
699   case TSK_Undeclared:
700   case TSK_ExplicitSpecialization:
701   case TSK_ImplicitInstantiation:
702     return llvm::GlobalVariable::LinkOnceODRLinkage;
703 
704   case TSK_ExplicitInstantiationDeclaration:
705     llvm_unreachable("Should not have been asked to emit this");
706 
707   case TSK_ExplicitInstantiationDefinition:
708       return llvm::GlobalVariable::WeakODRLinkage;
709   }
710 
711   llvm_unreachable("Invalid TemplateSpecializationKind!");
712 }
713 
714 /// This is a callback from Sema to tell us that it believes that a
715 /// particular v-table is required to be emitted in this translation
716 /// unit.
717 ///
718 /// The reason we don't simply trust this callback is because Sema
719 /// will happily report that something is used even when it's used
720 /// only in code that we don't actually have to emit.
721 ///
722 /// \param isRequired - if true, the v-table is mandatory, e.g.
723 ///   because the translation unit defines the key function
724 void CodeGenModule::EmitVTable(CXXRecordDecl *theClass, bool isRequired) {
725   if (!isRequired) return;
726 
727   VTables.GenerateClassData(theClass);
728 }
729 
730 void
731 CodeGenVTables::GenerateClassData(const CXXRecordDecl *RD) {
732   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
733     DI->completeClassData(RD);
734 
735   if (RD->getNumVBases())
736     CGM.getCXXABI().emitVirtualInheritanceTables(RD);
737 
738   CGM.getCXXABI().emitVTableDefinitions(*this, RD);
739 }
740 
741 /// At this point in the translation unit, does it appear that can we
742 /// rely on the vtable being defined elsewhere in the program?
743 ///
744 /// The response is really only definitive when called at the end of
745 /// the translation unit.
746 ///
747 /// The only semantic restriction here is that the object file should
748 /// not contain a v-table definition when that v-table is defined
749 /// strongly elsewhere.  Otherwise, we'd just like to avoid emitting
750 /// v-tables when unnecessary.
751 bool CodeGenVTables::isVTableExternal(const CXXRecordDecl *RD) {
752   assert(RD->isDynamicClass() && "Non-dynamic classes have no VTable.");
753 
754   // If we have an explicit instantiation declaration (and not a
755   // definition), the v-table is defined elsewhere.
756   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
757   if (TSK == TSK_ExplicitInstantiationDeclaration)
758     return true;
759 
760   // Otherwise, if the class is an instantiated template, the
761   // v-table must be defined here.
762   if (TSK == TSK_ImplicitInstantiation ||
763       TSK == TSK_ExplicitInstantiationDefinition)
764     return false;
765 
766   // Otherwise, if the class doesn't have a key function (possibly
767   // anymore), the v-table must be defined here.
768   const CXXMethodDecl *keyFunction = CGM.getContext().getCurrentKeyFunction(RD);
769   if (!keyFunction)
770     return false;
771 
772   // Otherwise, if we don't have a definition of the key function, the
773   // v-table must be defined somewhere else.
774   return !keyFunction->hasBody();
775 }
776 
777 /// Given that we're currently at the end of the translation unit, and
778 /// we've emitted a reference to the v-table for this class, should
779 /// we define that v-table?
780 static bool shouldEmitVTableAtEndOfTranslationUnit(CodeGenModule &CGM,
781                                                    const CXXRecordDecl *RD) {
782   return !CGM.getVTables().isVTableExternal(RD);
783 }
784 
785 /// Given that at some point we emitted a reference to one or more
786 /// v-tables, and that we are now at the end of the translation unit,
787 /// decide whether we should emit them.
788 void CodeGenModule::EmitDeferredVTables() {
789 #ifndef NDEBUG
790   // Remember the size of DeferredVTables, because we're going to assume
791   // that this entire operation doesn't modify it.
792   size_t savedSize = DeferredVTables.size();
793 #endif
794 
795   typedef std::vector<const CXXRecordDecl *>::const_iterator const_iterator;
796   for (const_iterator i = DeferredVTables.begin(),
797                       e = DeferredVTables.end(); i != e; ++i) {
798     const CXXRecordDecl *RD = *i;
799     if (shouldEmitVTableAtEndOfTranslationUnit(*this, RD))
800       VTables.GenerateClassData(RD);
801   }
802 
803   assert(savedSize == DeferredVTables.size() &&
804          "deferred extra v-tables during v-table emission?");
805   DeferredVTables.clear();
806 }
807