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