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 "CodeGenModule.h"
15 #include "CodeGenFunction.h"
16 #include "CGCXXABI.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/RecordLayout.h"
19 #include "clang/Frontend/CodeGenOptions.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
25 #include <algorithm>
26 #include <cstdio>
27 
28 using namespace clang;
29 using namespace CodeGen;
30 
31 CodeGenVTables::CodeGenVTables(CodeGenModule &CGM)
32   : CGM(CGM), VTContext(CGM.getContext()) { }
33 
34 bool CodeGenVTables::ShouldEmitVTableInThisTU(const CXXRecordDecl *RD) {
35   assert(RD->isDynamicClass() && "Non dynamic classes have no VTable.");
36 
37   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
38   if (TSK == TSK_ExplicitInstantiationDeclaration)
39     return false;
40 
41   const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
42   if (!KeyFunction)
43     return true;
44 
45   // Itanium C++ ABI, 5.2.6 Instantiated Templates:
46   //    An instantiation of a class template requires:
47   //        - In the object where instantiated, the virtual table...
48   if (TSK == TSK_ImplicitInstantiation ||
49       TSK == TSK_ExplicitInstantiationDefinition)
50     return true;
51 
52   // If we're building with optimization, we always emit VTables since that
53   // allows for virtual function calls to be devirtualized.
54   // (We don't want to do this in -fapple-kext mode however).
55   if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOpts().AppleKext)
56     return true;
57 
58   return KeyFunction->hasBody();
59 }
60 
61 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD,
62                                               const ThunkInfo &Thunk) {
63   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
64 
65   // Compute the mangled name.
66   SmallString<256> Name;
67   llvm::raw_svector_ostream Out(Name);
68   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
69     getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
70                                                       Thunk.This, Out);
71   else
72     getCXXABI().getMangleContext().mangleThunk(MD, Thunk, Out);
73   Out.flush();
74 
75   llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(GD);
76   return GetOrCreateLLVMFunction(Name, Ty, GD, /*ForVTable=*/true);
77 }
78 
79 static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
80                                           llvm::Value *Ptr,
81                                           int64_t NonVirtualAdjustment,
82                                           int64_t VirtualAdjustment,
83                                           bool IsReturnAdjustment) {
84   if (!NonVirtualAdjustment && !VirtualAdjustment)
85     return Ptr;
86 
87   llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
88   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
89 
90   if (NonVirtualAdjustment && !IsReturnAdjustment) {
91     // Perform the non-virtual adjustment for a base-to-derived cast.
92     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
93   }
94 
95   if (VirtualAdjustment) {
96     llvm::Type *PtrDiffTy =
97       CGF.ConvertType(CGF.getContext().getPointerDiffType());
98 
99     // Perform the virtual adjustment.
100     llvm::Value *VTablePtrPtr =
101       CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
102 
103     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
104 
105     llvm::Value *OffsetPtr =
106       CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
107 
108     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
109 
110     // Load the adjustment offset from the vtable.
111     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
112 
113     // Adjust our pointer.
114     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
115   }
116 
117   if (NonVirtualAdjustment && IsReturnAdjustment) {
118     // Perform the non-virtual adjustment for a derived-to-base cast.
119     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
120   }
121 
122   // Cast back to the original type.
123   return CGF.Builder.CreateBitCast(V, Ptr->getType());
124 }
125 
126 static void setThunkVisibility(CodeGenModule &CGM, const CXXMethodDecl *MD,
127                                const ThunkInfo &Thunk, llvm::Function *Fn) {
128   CGM.setGlobalVisibility(Fn, MD);
129 
130   if (!CGM.getCodeGenOpts().HiddenWeakVTables)
131     return;
132 
133   // If the thunk has weak/linkonce linkage, but the function must be
134   // emitted in every translation unit that references it, then we can
135   // emit its thunks with hidden visibility, since its thunks must be
136   // emitted when the function is.
137 
138   // This follows CodeGenModule::setTypeVisibility; see the comments
139   // there for explanation.
140 
141   if ((Fn->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage &&
142        Fn->getLinkage() != llvm::GlobalVariable::WeakODRLinkage) ||
143       Fn->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
144     return;
145 
146   if (MD->getExplicitVisibility())
147     return;
148 
149   switch (MD->getTemplateSpecializationKind()) {
150   case TSK_ExplicitInstantiationDefinition:
151   case TSK_ExplicitInstantiationDeclaration:
152     return;
153 
154   case TSK_Undeclared:
155     break;
156 
157   case TSK_ExplicitSpecialization:
158   case TSK_ImplicitInstantiation:
159     if (!CGM.getCodeGenOpts().HiddenWeakTemplateVTables)
160       return;
161     break;
162   }
163 
164   // If there's an explicit definition, and that definition is
165   // out-of-line, then we can't assume that all users will have a
166   // definition to emit.
167   const FunctionDecl *Def = 0;
168   if (MD->hasBody(Def) && Def->isOutOfLine())
169     return;
170 
171   Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
172 }
173 
174 #ifndef NDEBUG
175 static bool similar(const ABIArgInfo &infoL, CanQualType typeL,
176                     const ABIArgInfo &infoR, CanQualType typeR) {
177   return (infoL.getKind() == infoR.getKind() &&
178           (typeL == typeR ||
179            (isa<PointerType>(typeL) && isa<PointerType>(typeR)) ||
180            (isa<ReferenceType>(typeL) && isa<ReferenceType>(typeR))));
181 }
182 #endif
183 
184 static RValue PerformReturnAdjustment(CodeGenFunction &CGF,
185                                       QualType ResultType, RValue RV,
186                                       const ThunkInfo &Thunk) {
187   // Emit the return adjustment.
188   bool NullCheckValue = !ResultType->isReferenceType();
189 
190   llvm::BasicBlock *AdjustNull = 0;
191   llvm::BasicBlock *AdjustNotNull = 0;
192   llvm::BasicBlock *AdjustEnd = 0;
193 
194   llvm::Value *ReturnValue = RV.getScalarVal();
195 
196   if (NullCheckValue) {
197     AdjustNull = CGF.createBasicBlock("adjust.null");
198     AdjustNotNull = CGF.createBasicBlock("adjust.notnull");
199     AdjustEnd = CGF.createBasicBlock("adjust.end");
200 
201     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ReturnValue);
202     CGF.Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
203     CGF.EmitBlock(AdjustNotNull);
204   }
205 
206   ReturnValue = PerformTypeAdjustment(CGF, ReturnValue,
207                                       Thunk.Return.NonVirtual,
208                                       Thunk.Return.VBaseOffsetOffset,
209                                       /*IsReturnAdjustment*/true);
210 
211   if (NullCheckValue) {
212     CGF.Builder.CreateBr(AdjustEnd);
213     CGF.EmitBlock(AdjustNull);
214     CGF.Builder.CreateBr(AdjustEnd);
215     CGF.EmitBlock(AdjustEnd);
216 
217     llvm::PHINode *PHI = CGF.Builder.CreatePHI(ReturnValue->getType(), 2);
218     PHI->addIncoming(ReturnValue, AdjustNotNull);
219     PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()),
220                      AdjustNull);
221     ReturnValue = PHI;
222   }
223 
224   return RValue::get(ReturnValue);
225 }
226 
227 // This function does roughly the same thing as GenerateThunk, but in a
228 // very different way, so that va_start and va_end work correctly.
229 // FIXME: This function assumes "this" is the first non-sret LLVM argument of
230 //        a function, and that there is an alloca built in the entry block
231 //        for all accesses to "this".
232 // FIXME: This function assumes there is only one "ret" statement per function.
233 // FIXME: Cloning isn't correct in the presence of indirect goto!
234 // FIXME: This implementation of thunks bloats codesize by duplicating the
235 //        function definition.  There are alternatives:
236 //        1. Add some sort of stub support to LLVM for cases where we can
237 //           do a this adjustment, then a sibcall.
238 //        2. We could transform the definition to take a va_list instead of an
239 //           actual variable argument list, then have the thunks (including a
240 //           no-op thunk for the regular definition) call va_start/va_end.
241 //           There's a bit of per-call overhead for this solution, but it's
242 //           better for codesize if the definition is long.
243 void CodeGenFunction::GenerateVarArgsThunk(
244                                       llvm::Function *Fn,
245                                       const CGFunctionInfo &FnInfo,
246                                       GlobalDecl GD, const ThunkInfo &Thunk) {
247   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
248   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
249   QualType ResultType = FPT->getResultType();
250 
251   // Get the original function
252   assert(FnInfo.isVariadic());
253   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FnInfo);
254   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
255   llvm::Function *BaseFn = cast<llvm::Function>(Callee);
256 
257   // Clone to thunk.
258   llvm::ValueToValueMapTy VMap;
259   llvm::Function *NewFn = llvm::CloneFunction(BaseFn, VMap,
260                                               /*ModuleLevelChanges=*/false);
261   CGM.getModule().getFunctionList().push_back(NewFn);
262   Fn->replaceAllUsesWith(NewFn);
263   NewFn->takeName(Fn);
264   Fn->eraseFromParent();
265   Fn = NewFn;
266 
267   // "Initialize" CGF (minimally).
268   CurFn = Fn;
269 
270   // Get the "this" value
271   llvm::Function::arg_iterator AI = Fn->arg_begin();
272   if (CGM.ReturnTypeUsesSRet(FnInfo))
273     ++AI;
274 
275   // Find the first store of "this", which will be to the alloca associated
276   // with "this".
277   llvm::Value *ThisPtr = &*AI;
278   llvm::BasicBlock *EntryBB = Fn->begin();
279   llvm::Instruction *ThisStore = 0;
280   for (llvm::BasicBlock::iterator I = EntryBB->begin(), E = EntryBB->end();
281        I != E; I++) {
282     if (isa<llvm::StoreInst>(I) && I->getOperand(0) == ThisPtr) {
283       ThisStore = cast<llvm::StoreInst>(I);
284       break;
285     }
286   }
287   assert(ThisStore && "Store of this should be in entry block?");
288   // Adjust "this", if necessary.
289   Builder.SetInsertPoint(ThisStore);
290   llvm::Value *AdjustedThisPtr =
291     PerformTypeAdjustment(*this, ThisPtr,
292                           Thunk.This.NonVirtual,
293                           Thunk.This.VCallOffsetOffset,
294                           /*IsReturnAdjustment*/false);
295   ThisStore->setOperand(0, AdjustedThisPtr);
296 
297   if (!Thunk.Return.isEmpty()) {
298     // Fix up the returned value, if necessary.
299     for (llvm::Function::iterator I = Fn->begin(), E = Fn->end(); I != E; I++) {
300       llvm::Instruction *T = I->getTerminator();
301       if (isa<llvm::ReturnInst>(T)) {
302         RValue RV = RValue::get(T->getOperand(0));
303         T->eraseFromParent();
304         Builder.SetInsertPoint(&*I);
305         RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
306         Builder.CreateRet(RV.getScalarVal());
307         break;
308       }
309     }
310   }
311 }
312 
313 void CodeGenFunction::GenerateThunk(llvm::Function *Fn,
314                                     const CGFunctionInfo &FnInfo,
315                                     GlobalDecl GD, const ThunkInfo &Thunk) {
316   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
317   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
318   QualType ResultType = FPT->getResultType();
319   QualType ThisType = MD->getThisType(getContext());
320 
321   FunctionArgList FunctionArgs;
322 
323   // FIXME: It would be nice if more of this code could be shared with
324   // CodeGenFunction::GenerateCode.
325 
326   // Create the implicit 'this' parameter declaration.
327   CurGD = GD;
328   CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResultType, FunctionArgs);
329 
330   // Add the rest of the parameters.
331   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
332        E = MD->param_end(); I != E; ++I) {
333     ParmVarDecl *Param = *I;
334 
335     FunctionArgs.push_back(Param);
336   }
337 
338   StartFunction(GlobalDecl(), ResultType, Fn, FnInfo, FunctionArgs,
339                 SourceLocation());
340 
341   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
342   CXXThisValue = CXXABIThisValue;
343 
344   // Adjust the 'this' pointer if necessary.
345   llvm::Value *AdjustedThisPtr =
346     PerformTypeAdjustment(*this, LoadCXXThis(),
347                           Thunk.This.NonVirtual,
348                           Thunk.This.VCallOffsetOffset,
349                           /*IsReturnAdjustment*/false);
350 
351   CallArgList CallArgs;
352 
353   // Add our adjusted 'this' pointer.
354   CallArgs.add(RValue::get(AdjustedThisPtr), ThisType);
355 
356   // Add the rest of the parameters.
357   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
358        E = MD->param_end(); I != E; ++I) {
359     ParmVarDecl *param = *I;
360     EmitDelegateCallArg(CallArgs, param);
361   }
362 
363   // Get our callee.
364   llvm::Type *Ty =
365     CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration(GD));
366   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
367 
368 #ifndef NDEBUG
369   const CGFunctionInfo &CallFnInfo =
370     CGM.getTypes().arrangeCXXMethodCall(CallArgs, FPT,
371                                        RequiredArgs::forPrototypePlus(FPT, 1));
372   assert(CallFnInfo.getRegParm() == FnInfo.getRegParm() &&
373          CallFnInfo.isNoReturn() == FnInfo.isNoReturn() &&
374          CallFnInfo.getCallingConvention() == FnInfo.getCallingConvention());
375   assert(isa<CXXDestructorDecl>(MD) || // ignore dtor return types
376          similar(CallFnInfo.getReturnInfo(), CallFnInfo.getReturnType(),
377                  FnInfo.getReturnInfo(), FnInfo.getReturnType()));
378   assert(CallFnInfo.arg_size() == FnInfo.arg_size());
379   for (unsigned i = 0, e = FnInfo.arg_size(); i != e; ++i)
380     assert(similar(CallFnInfo.arg_begin()[i].info,
381                    CallFnInfo.arg_begin()[i].type,
382                    FnInfo.arg_begin()[i].info, FnInfo.arg_begin()[i].type));
383 #endif
384 
385   // Determine whether we have a return value slot to use.
386   ReturnValueSlot Slot;
387   if (!ResultType->isVoidType() &&
388       FnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
389       hasAggregateLLVMType(CurFnInfo->getReturnType()))
390     Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
391 
392   // Now emit our call.
393   RValue RV = EmitCall(FnInfo, Callee, Slot, CallArgs, MD);
394 
395   if (!Thunk.Return.isEmpty())
396     RV = PerformReturnAdjustment(*this, ResultType, RV, Thunk);
397 
398   if (!ResultType->isVoidType() && Slot.isNull())
399     CGM.getCXXABI().EmitReturnFromThunk(*this, RV, ResultType);
400 
401   // Disable the final ARC autorelease.
402   AutoreleaseResult = false;
403 
404   FinishFunction();
405 
406   // Set the right linkage.
407   CGM.setFunctionLinkage(MD, Fn);
408 
409   // Set the right visibility.
410   setThunkVisibility(CGM, MD, Thunk, Fn);
411 }
412 
413 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,
414                                bool UseAvailableExternallyLinkage)
415 {
416   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeGlobalDeclaration(GD);
417 
418   // FIXME: re-use FnInfo in this computation.
419   llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
420 
421   // Strip off a bitcast if we got one back.
422   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
423     assert(CE->getOpcode() == llvm::Instruction::BitCast);
424     Entry = CE->getOperand(0);
425   }
426 
427   // There's already a declaration with the same name, check if it has the same
428   // type or if we need to replace it.
429   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() !=
430       CGM.getTypes().GetFunctionTypeForVTable(GD)) {
431     llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
432 
433     // If the types mismatch then we have to rewrite the definition.
434     assert(OldThunkFn->isDeclaration() &&
435            "Shouldn't replace non-declaration");
436 
437     // Remove the name from the old thunk function and get a new thunk.
438     OldThunkFn->setName(StringRef());
439     Entry = CGM.GetAddrOfThunk(GD, Thunk);
440 
441     // If needed, replace the old thunk with a bitcast.
442     if (!OldThunkFn->use_empty()) {
443       llvm::Constant *NewPtrForOldDecl =
444         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
445       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
446     }
447 
448     // Remove the old thunk.
449     OldThunkFn->eraseFromParent();
450   }
451 
452   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
453 
454   if (!ThunkFn->isDeclaration()) {
455     if (UseAvailableExternallyLinkage) {
456       // There is already a thunk emitted for this function, do nothing.
457       return;
458     }
459 
460     // If a function has a body, it should have available_externally linkage.
461     assert(ThunkFn->hasAvailableExternallyLinkage() &&
462            "Function should have available_externally linkage!");
463 
464     // Change the linkage.
465     CGM.setFunctionLinkage(cast<CXXMethodDecl>(GD.getDecl()), ThunkFn);
466     return;
467   }
468 
469   if (ThunkFn->isVarArg()) {
470     // Varargs thunks are special; we can't just generate a call because
471     // we can't copy the varargs.  Our implementation is rather
472     // expensive/sucky at the moment, so don't generate the thunk unless
473     // we have to.
474     // FIXME: Do something better here; GenerateVarArgsThunk is extremely ugly.
475     if (!UseAvailableExternallyLinkage)
476       CodeGenFunction(CGM).GenerateVarArgsThunk(ThunkFn, FnInfo, GD, Thunk);
477   } else {
478     // Normal thunk body generation.
479     CodeGenFunction(CGM).GenerateThunk(ThunkFn, FnInfo, GD, Thunk);
480   }
481 
482   if (UseAvailableExternallyLinkage)
483     ThunkFn->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
484 }
485 
486 void CodeGenVTables::MaybeEmitThunkAvailableExternally(GlobalDecl GD,
487                                                        const ThunkInfo &Thunk) {
488   // We only want to do this when building with optimizations.
489   if (!CGM.getCodeGenOpts().OptimizationLevel)
490     return;
491 
492   // We can't emit thunks for member functions with incomplete types.
493   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
494   if (!CGM.getTypes().isFuncTypeConvertible(
495                                 cast<FunctionType>(MD->getType().getTypePtr())))
496     return;
497 
498   EmitThunk(GD, Thunk, /*UseAvailableExternallyLinkage=*/true);
499 }
500 
501 void CodeGenVTables::EmitThunks(GlobalDecl GD)
502 {
503   const CXXMethodDecl *MD =
504     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
505 
506   // We don't need to generate thunks for the base destructor.
507   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
508     return;
509 
510   const VTableContext::ThunkInfoVectorTy *ThunkInfoVector =
511     VTContext.getThunkInfo(MD);
512   if (!ThunkInfoVector)
513     return;
514 
515   for (unsigned I = 0, E = ThunkInfoVector->size(); I != E; ++I)
516     EmitThunk(GD, (*ThunkInfoVector)[I],
517               /*UseAvailableExternallyLinkage=*/false);
518 }
519 
520 llvm::Constant *
521 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
522                                         const VTableComponent *Components,
523                                         unsigned NumComponents,
524                                 const VTableLayout::VTableThunkTy *VTableThunks,
525                                         unsigned NumVTableThunks) {
526   SmallVector<llvm::Constant *, 64> Inits;
527 
528   llvm::Type *Int8PtrTy = CGM.Int8PtrTy;
529 
530   llvm::Type *PtrDiffTy =
531     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
532 
533   QualType ClassType = CGM.getContext().getTagDeclType(RD);
534   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
535 
536   unsigned NextVTableThunkIndex = 0;
537 
538   llvm::Constant* PureVirtualFn = 0;
539 
540   for (unsigned I = 0; I != NumComponents; ++I) {
541     VTableComponent Component = Components[I];
542 
543     llvm::Constant *Init = 0;
544 
545     switch (Component.getKind()) {
546     case VTableComponent::CK_VCallOffset:
547       Init = llvm::ConstantInt::get(PtrDiffTy,
548                                     Component.getVCallOffset().getQuantity());
549       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
550       break;
551     case VTableComponent::CK_VBaseOffset:
552       Init = llvm::ConstantInt::get(PtrDiffTy,
553                                     Component.getVBaseOffset().getQuantity());
554       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
555       break;
556     case VTableComponent::CK_OffsetToTop:
557       Init = llvm::ConstantInt::get(PtrDiffTy,
558                                     Component.getOffsetToTop().getQuantity());
559       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
560       break;
561     case VTableComponent::CK_RTTI:
562       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
563       break;
564     case VTableComponent::CK_FunctionPointer:
565     case VTableComponent::CK_CompleteDtorPointer:
566     case VTableComponent::CK_DeletingDtorPointer: {
567       GlobalDecl GD;
568 
569       // Get the right global decl.
570       switch (Component.getKind()) {
571       default:
572         llvm_unreachable("Unexpected vtable component kind");
573       case VTableComponent::CK_FunctionPointer:
574         GD = Component.getFunctionDecl();
575         break;
576       case VTableComponent::CK_CompleteDtorPointer:
577         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
578         break;
579       case VTableComponent::CK_DeletingDtorPointer:
580         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
581         break;
582       }
583 
584       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
585         // We have a pure virtual member function.
586         if (!PureVirtualFn) {
587           llvm::FunctionType *Ty =
588             llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
589           StringRef PureCallName = CGM.getCXXABI().GetPureVirtualCallName();
590           PureVirtualFn = CGM.CreateRuntimeFunction(Ty, PureCallName);
591           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn,
592                                                          CGM.Int8PtrTy);
593         }
594         Init = PureVirtualFn;
595       } else {
596         // Check if we should use a thunk.
597         if (NextVTableThunkIndex < NumVTableThunks &&
598             VTableThunks[NextVTableThunkIndex].first == I) {
599           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
600 
601           MaybeEmitThunkAvailableExternally(GD, Thunk);
602           Init = CGM.GetAddrOfThunk(GD, Thunk);
603 
604           NextVTableThunkIndex++;
605         } else {
606           llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(GD);
607 
608           Init = CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=*/true);
609         }
610 
611         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
612       }
613       break;
614     }
615 
616     case VTableComponent::CK_UnusedFunctionPointer:
617       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
618       break;
619     };
620 
621     Inits.push_back(Init);
622   }
623 
624   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
625   return llvm::ConstantArray::get(ArrayType, Inits);
626 }
627 
628 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
629   llvm::GlobalVariable *&VTable = VTables[RD];
630   if (VTable)
631     return VTable;
632 
633   // We may need to generate a definition for this vtable.
634   if (ShouldEmitVTableInThisTU(RD))
635     CGM.DeferredVTables.push_back(RD);
636 
637   SmallString<256> OutName;
638   llvm::raw_svector_ostream Out(OutName);
639   CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
640   Out.flush();
641   StringRef Name = OutName.str();
642 
643   llvm::ArrayType *ArrayType =
644     llvm::ArrayType::get(CGM.Int8PtrTy,
645                         VTContext.getVTableLayout(RD).getNumVTableComponents());
646 
647   VTable =
648     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,
649                                           llvm::GlobalValue::ExternalLinkage);
650   VTable->setUnnamedAddr(true);
651   return VTable;
652 }
653 
654 void
655 CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
656                                      llvm::GlobalVariable::LinkageTypes Linkage,
657                                      const CXXRecordDecl *RD) {
658   const VTableLayout &VTLayout = VTContext.getVTableLayout(RD);
659 
660   // Create and set the initializer.
661   llvm::Constant *Init =
662     CreateVTableInitializer(RD,
663                             VTLayout.vtable_component_begin(),
664                             VTLayout.getNumVTableComponents(),
665                             VTLayout.vtable_thunk_begin(),
666                             VTLayout.getNumVTableThunks());
667   VTable->setInitializer(Init);
668 
669   // Set the correct linkage.
670   VTable->setLinkage(Linkage);
671 
672   // Set the right visibility.
673   CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForVTable);
674 }
675 
676 llvm::GlobalVariable *
677 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD,
678                                       const BaseSubobject &Base,
679                                       bool BaseIsVirtual,
680                                    llvm::GlobalVariable::LinkageTypes Linkage,
681                                       VTableAddressPointsMapTy& AddressPoints) {
682   OwningPtr<VTableLayout> VTLayout(
683     VTContext.createConstructionVTableLayout(Base.getBase(),
684                                              Base.getBaseOffset(),
685                                              BaseIsVirtual, RD));
686 
687   // Add the address points.
688   AddressPoints = VTLayout->getAddressPoints();
689 
690   // Get the mangled construction vtable name.
691   SmallString<256> OutName;
692   llvm::raw_svector_ostream Out(OutName);
693   CGM.getCXXABI().getMangleContext().
694     mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBase(),
695                         Out);
696   Out.flush();
697   StringRef Name = OutName.str();
698 
699   llvm::ArrayType *ArrayType =
700     llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents());
701 
702   // Create the variable that will hold the construction vtable.
703   llvm::GlobalVariable *VTable =
704     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType, Linkage);
705   CGM.setTypeVisibility(VTable, RD, CodeGenModule::TVK_ForConstructionVTable);
706 
707   // V-tables are always unnamed_addr.
708   VTable->setUnnamedAddr(true);
709 
710   // Create and set the initializer.
711   llvm::Constant *Init =
712     CreateVTableInitializer(Base.getBase(),
713                             VTLayout->vtable_component_begin(),
714                             VTLayout->getNumVTableComponents(),
715                             VTLayout->vtable_thunk_begin(),
716                             VTLayout->getNumVTableThunks());
717   VTable->setInitializer(Init);
718 
719   return VTable;
720 }
721 
722 void
723 CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
724                                   const CXXRecordDecl *RD) {
725   llvm::GlobalVariable *VTable = GetAddrOfVTable(RD);
726   if (VTable->hasInitializer())
727     return;
728 
729   EmitVTableDefinition(VTable, Linkage, RD);
730 
731   if (RD->getNumVBases()) {
732     llvm::GlobalVariable *VTT = GetAddrOfVTT(RD);
733     EmitVTTDefinition(VTT, Linkage, RD);
734   }
735 
736   // If this is the magic class __cxxabiv1::__fundamental_type_info,
737   // we will emit the typeinfo for the fundamental types. This is the
738   // same behaviour as GCC.
739   const DeclContext *DC = RD->getDeclContext();
740   if (RD->getIdentifier() &&
741       RD->getIdentifier()->isStr("__fundamental_type_info") &&
742       isa<NamespaceDecl>(DC) &&
743       cast<NamespaceDecl>(DC)->getIdentifier() &&
744       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
745       DC->getParent()->isTranslationUnit())
746     CGM.EmitFundamentalRTTIDescriptors();
747 }
748