clang API Documentation

CGVTables.cpp

Go to the documentation of this file.
00001 //===--- CGVTables.cpp - Emit LLVM Code for C++ vtables -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code dealing with C++ code generation of virtual tables.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenModule.h"
00015 #include "CodeGenFunction.h"
00016 #include "clang/AST/CXXInheritance.h"
00017 #include "clang/AST/RecordLayout.h"
00018 #include "llvm/ADT/DenseSet.h"
00019 #include "llvm/ADT/SetVector.h"
00020 #include "llvm/Support/Compiler.h"
00021 #include "llvm/Support/Format.h"
00022 #include <algorithm>
00023 #include <cstdio>
00024 
00025 using namespace clang;
00026 using namespace CodeGen;
00027 
00028 namespace {
00029 
00030 /// BaseOffset - Represents an offset from a derived class to a direct or
00031 /// indirect base class.
00032 struct BaseOffset {
00033   /// DerivedClass - The derived class.
00034   const CXXRecordDecl *DerivedClass;
00035   
00036   /// VirtualBase - If the path from the derived class to the base class
00037   /// involves a virtual base class, this holds its declaration.
00038   const CXXRecordDecl *VirtualBase;
00039 
00040   /// NonVirtualOffset - The offset from the derived class to the base class.
00041   /// (Or the offset from the virtual base class to the base class, if the 
00042   /// path from the derived class to the base class involves a virtual base
00043   /// class.
00044   int64_t NonVirtualOffset;
00045   
00046   BaseOffset() : DerivedClass(0), VirtualBase(0), NonVirtualOffset(0) { }
00047   BaseOffset(const CXXRecordDecl *DerivedClass,
00048              const CXXRecordDecl *VirtualBase, int64_t NonVirtualOffset)
00049     : DerivedClass(DerivedClass), VirtualBase(VirtualBase), 
00050     NonVirtualOffset(NonVirtualOffset) { }
00051 
00052   bool isEmpty() const { return !NonVirtualOffset && !VirtualBase; }
00053 };
00054 
00055 /// FinalOverriders - Contains the final overrider member functions for all
00056 /// member functions in the base subobjects of a class.
00057 class FinalOverriders {
00058 public:
00059   /// OverriderInfo - Information about a final overrider.
00060   struct OverriderInfo {
00061     /// Method - The method decl of the overrider.
00062     const CXXMethodDecl *Method;
00063 
00064     /// Offset - the base offset of the overrider in the layout class.
00065     uint64_t Offset;
00066     
00067     OverriderInfo() : Method(0), Offset(0) { }
00068   };
00069 
00070 private:
00071   /// MostDerivedClass - The most derived class for which the final overriders
00072   /// are stored.
00073   const CXXRecordDecl *MostDerivedClass;
00074   
00075   /// MostDerivedClassOffset - If we're building final overriders for a 
00076   /// construction vtable, this holds the offset from the layout class to the
00077   /// most derived class.
00078   const uint64_t MostDerivedClassOffset;
00079 
00080   /// LayoutClass - The class we're using for layout information. Will be 
00081   /// different than the most derived class if the final overriders are for a
00082   /// construction vtable.  
00083   const CXXRecordDecl *LayoutClass;  
00084 
00085   ASTContext &Context;
00086   
00087   /// MostDerivedClassLayout - the AST record layout of the most derived class.
00088   const ASTRecordLayout &MostDerivedClassLayout;
00089 
00090   /// BaseSubobjectMethodPairTy - Uniquely identifies a member function
00091   /// in a base subobject.
00092   typedef std::pair<BaseSubobject, const CXXMethodDecl *>
00093     BaseSubobjectMethodPairTy;
00094   
00095   typedef llvm::DenseMap<BaseSubobjectMethodPairTy,
00096                          OverriderInfo> OverridersMapTy;
00097   
00098   /// OverridersMap - The final overriders for all virtual member functions of 
00099   /// all the base subobjects of the most derived class.
00100   OverridersMapTy OverridersMap;
00101   
00102   /// VisitedVirtualBases - A set of all the visited virtual bases, used to
00103   /// avoid visiting virtual bases more than once.
00104   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
00105 
00106   typedef llvm::DenseMap<BaseSubobjectMethodPairTy, BaseOffset>
00107     AdjustmentOffsetsMapTy;
00108 
00109   /// ReturnAdjustments - Holds return adjustments for all the overriders that 
00110   /// need to perform return value adjustments.
00111   AdjustmentOffsetsMapTy ReturnAdjustments;
00112 
00113   // FIXME: We might be able to get away with making this a SmallSet.
00114   typedef llvm::SmallSetVector<uint64_t, 2> OffsetSetVectorTy;
00115   
00116   /// SubobjectOffsetsMapTy - This map is used for keeping track of all the
00117   /// base subobject offsets that a single class declaration might refer to.
00118   ///
00119   /// For example, in:
00120   ///
00121   /// struct A { virtual void f(); };
00122   /// struct B1 : A { };
00123   /// struct B2 : A { };
00124   /// struct C : B1, B2 { virtual void f(); };
00125   ///
00126   /// when we determine that C::f() overrides A::f(), we need to update the
00127   /// overriders map for both A-in-B1 and A-in-B2 and the subobject offsets map
00128   /// will have the subobject offsets for both A copies.
00129   typedef llvm::DenseMap<const CXXRecordDecl *, OffsetSetVectorTy>
00130     SubobjectOffsetsMapTy;
00131   
00132   /// ComputeFinalOverriders - Compute the final overriders for a given base
00133   /// subobject (and all its direct and indirect bases).
00134   void ComputeFinalOverriders(BaseSubobject Base,
00135                               bool BaseSubobjectIsVisitedVBase,
00136                               uint64_t OffsetInLayoutClass,
00137                               SubobjectOffsetsMapTy &Offsets);
00138   
00139   /// AddOverriders - Add the final overriders for this base subobject to the
00140   /// map of final overriders.  
00141   void AddOverriders(BaseSubobject Base, uint64_t OffsetInLayoutClass,
00142                      SubobjectOffsetsMapTy &Offsets);
00143 
00144   /// PropagateOverrider - Propagate the NewMD overrider to all the functions 
00145   /// that OldMD overrides. For example, if we have:
00146   ///
00147   /// struct A { virtual void f(); };
00148   /// struct B : A { virtual void f(); };
00149   /// struct C : B { virtual void f(); };
00150   ///
00151   /// and we want to override B::f with C::f, we also need to override A::f with
00152   /// C::f.
00153   void PropagateOverrider(const CXXMethodDecl *OldMD,
00154                           BaseSubobject NewBase,
00155                           uint64_t OverriderOffsetInLayoutClass,
00156                           const CXXMethodDecl *NewMD,
00157                           SubobjectOffsetsMapTy &Offsets);
00158   
00159   static void MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
00160                                     SubobjectOffsetsMapTy &Offsets);
00161 
00162 public:
00163   FinalOverriders(const CXXRecordDecl *MostDerivedClass,
00164                   uint64_t MostDerivedClassOffset,
00165                   const CXXRecordDecl *LayoutClass);
00166 
00167   /// getOverrider - Get the final overrider for the given method declaration in
00168   /// the given base subobject.
00169   OverriderInfo getOverrider(BaseSubobject Base,
00170                              const CXXMethodDecl *MD) const {
00171     assert(OverridersMap.count(std::make_pair(Base, MD)) && 
00172            "Did not find overrider!");
00173     
00174     return OverridersMap.lookup(std::make_pair(Base, MD));
00175   }
00176   
00177   /// getReturnAdjustmentOffset - Get the return adjustment offset for the
00178   /// method decl in the given base subobject. Returns an empty base offset if
00179   /// no adjustment is needed.
00180   BaseOffset getReturnAdjustmentOffset(BaseSubobject Base,
00181                                        const CXXMethodDecl *MD) const {
00182     return ReturnAdjustments.lookup(std::make_pair(Base, MD));
00183   }
00184 
00185   /// dump - dump the final overriders.
00186   void dump() {
00187     assert(VisitedVirtualBases.empty() &&
00188            "Visited virtual bases aren't empty!");
00189     dump(llvm::errs(), BaseSubobject(MostDerivedClass, 0)); 
00190     VisitedVirtualBases.clear();
00191   }
00192   
00193   /// dump - dump the final overriders for a base subobject, and all its direct
00194   /// and indirect base subobjects.
00195   void dump(llvm::raw_ostream &Out, BaseSubobject Base);
00196 };
00197 
00198 #define DUMP_OVERRIDERS 0
00199 
00200 FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
00201                                  uint64_t MostDerivedClassOffset,
00202                                  const CXXRecordDecl *LayoutClass)
00203   : MostDerivedClass(MostDerivedClass), 
00204   MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
00205   Context(MostDerivedClass->getASTContext()),
00206   MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
00207     
00208   // Compute the final overriders.
00209   SubobjectOffsetsMapTy Offsets;
00210   ComputeFinalOverriders(BaseSubobject(MostDerivedClass, 0), 
00211                          /*BaseSubobjectIsVisitedVBase=*/false, 
00212                          MostDerivedClassOffset, Offsets);
00213   VisitedVirtualBases.clear();
00214 
00215 #if DUMP_OVERRIDERS
00216   // And dump them (for now).
00217   dump();
00218     
00219   // Also dump the base offsets (for now).
00220   for (SubobjectOffsetsMapTy::const_iterator I = Offsets.begin(),
00221        E = Offsets.end(); I != E; ++I) {
00222     const OffsetSetVectorTy& OffsetSetVector = I->second;
00223 
00224     llvm::errs() << "Base offsets for ";
00225     llvm::errs() << I->first->getQualifiedNameAsString() << '\n';
00226 
00227     for (unsigned I = 0, E = OffsetSetVector.size(); I != E; ++I)
00228       llvm::errs() << "  " << I << " - " << OffsetSetVector[I] / 8 << '\n';
00229   }
00230 #endif
00231 }
00232 
00233 void FinalOverriders::AddOverriders(BaseSubobject Base,
00234                                     uint64_t OffsetInLayoutClass,
00235                                     SubobjectOffsetsMapTy &Offsets) {
00236   const CXXRecordDecl *RD = Base.getBase();
00237 
00238   for (CXXRecordDecl::method_iterator I = RD->method_begin(), 
00239        E = RD->method_end(); I != E; ++I) {
00240     const CXXMethodDecl *MD = *I;
00241     
00242     if (!MD->isVirtual())
00243       continue;
00244 
00245     // First, propagate the overrider.
00246     PropagateOverrider(MD, Base, OffsetInLayoutClass, MD, Offsets);
00247 
00248     // Add the overrider as the final overrider of itself.
00249     OverriderInfo& Overrider = OverridersMap[std::make_pair(Base, MD)];
00250     assert(!Overrider.Method && "Overrider should not exist yet!");
00251 
00252     Overrider.Offset = OffsetInLayoutClass;
00253     Overrider.Method = MD;
00254   }
00255 }
00256 
00257 static BaseOffset ComputeBaseOffset(ASTContext &Context, 
00258                                     const CXXRecordDecl *DerivedRD,
00259                                     const CXXBasePath &Path) {
00260   int64_t NonVirtualOffset = 0;
00261 
00262   unsigned NonVirtualStart = 0;
00263   const CXXRecordDecl *VirtualBase = 0;
00264   
00265   // First, look for the virtual base class.
00266   for (unsigned I = 0, E = Path.size(); I != E; ++I) {
00267     const CXXBasePathElement &Element = Path[I];
00268     
00269     if (Element.Base->isVirtual()) {
00270       // FIXME: Can we break when we find the first virtual base?
00271       // (If we can't, can't we just iterate over the path in reverse order?)
00272       NonVirtualStart = I + 1;
00273       QualType VBaseType = Element.Base->getType();
00274       VirtualBase = 
00275         cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
00276     }
00277   }
00278   
00279   // Now compute the non-virtual offset.
00280   for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
00281     const CXXBasePathElement &Element = Path[I];
00282     
00283     // Check the base class offset.
00284     const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
00285 
00286     const RecordType *BaseType = Element.Base->getType()->getAs<RecordType>();
00287     const CXXRecordDecl *Base = cast<CXXRecordDecl>(BaseType->getDecl());
00288 
00289     NonVirtualOffset += Layout.getBaseClassOffset(Base);
00290   }
00291   
00292   // FIXME: This should probably use CharUnits or something. Maybe we should
00293   // even change the base offsets in ASTRecordLayout to be specified in 
00294   // CharUnits.
00295   return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset / 8);
00296   
00297 }
00298 
00299 static BaseOffset ComputeBaseOffset(ASTContext &Context, 
00300                                     const CXXRecordDecl *BaseRD,
00301                                     const CXXRecordDecl *DerivedRD) {
00302   CXXBasePaths Paths(/*FindAmbiguities=*/false,
00303                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
00304   
00305   if (!const_cast<CXXRecordDecl *>(DerivedRD)->
00306       isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
00307     assert(false && "Class must be derived from the passed in base class!");
00308     return BaseOffset();
00309   }
00310 
00311   return ComputeBaseOffset(Context, DerivedRD, Paths.front());
00312 }
00313 
00314 static BaseOffset
00315 ComputeReturnAdjustmentBaseOffset(ASTContext &Context, 
00316                                   const CXXMethodDecl *DerivedMD,
00317                                   const CXXMethodDecl *BaseMD) {
00318   const FunctionType *BaseFT = BaseMD->getType()->getAs<FunctionType>();
00319   const FunctionType *DerivedFT = DerivedMD->getType()->getAs<FunctionType>();
00320   
00321   // Canonicalize the return types.
00322   CanQualType CanDerivedReturnType = 
00323     Context.getCanonicalType(DerivedFT->getResultType());
00324   CanQualType CanBaseReturnType = 
00325     Context.getCanonicalType(BaseFT->getResultType());
00326   
00327   assert(CanDerivedReturnType->getTypeClass() == 
00328          CanBaseReturnType->getTypeClass() && 
00329          "Types must have same type class!");
00330   
00331   if (CanDerivedReturnType == CanBaseReturnType) {
00332     // No adjustment needed.
00333     return BaseOffset();
00334   }
00335   
00336   if (isa<ReferenceType>(CanDerivedReturnType)) {
00337     CanDerivedReturnType = 
00338       CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
00339     CanBaseReturnType = 
00340       CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
00341   } else if (isa<PointerType>(CanDerivedReturnType)) {
00342     CanDerivedReturnType = 
00343       CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
00344     CanBaseReturnType = 
00345       CanBaseReturnType->getAs<PointerType>()->getPointeeType();
00346   } else {
00347     assert(false && "Unexpected return type!");
00348   }
00349   
00350   // We need to compare unqualified types here; consider
00351   //   const T *Base::foo();
00352   //   T *Derived::foo();
00353   if (CanDerivedReturnType.getUnqualifiedType() == 
00354       CanBaseReturnType.getUnqualifiedType()) {
00355     // No adjustment needed.
00356     return BaseOffset();
00357   }
00358   
00359   const CXXRecordDecl *DerivedRD = 
00360     cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
00361   
00362   const CXXRecordDecl *BaseRD = 
00363     cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
00364 
00365   return ComputeBaseOffset(Context, BaseRD, DerivedRD);
00366 }
00367 
00368 void FinalOverriders::PropagateOverrider(const CXXMethodDecl *OldMD,
00369                                          BaseSubobject NewBase,
00370                                          uint64_t OverriderOffsetInLayoutClass,
00371                                          const CXXMethodDecl *NewMD,
00372                                          SubobjectOffsetsMapTy &Offsets) {
00373   for (CXXMethodDecl::method_iterator I = OldMD->begin_overridden_methods(),
00374        E = OldMD->end_overridden_methods(); I != E; ++I) {
00375     const CXXMethodDecl *OverriddenMD = *I;
00376     const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
00377 
00378     // We want to override OverriddenMD in all subobjects, for example:
00379     //
00380     /// struct A { virtual void f(); };
00381     /// struct B1 : A { };
00382     /// struct B2 : A { };
00383     /// struct C : B1, B2 { virtual void f(); };
00384     ///
00385     /// When overriding A::f with C::f we need to do so in both A subobjects.
00386     const OffsetSetVectorTy &OffsetVector = Offsets[OverriddenRD];
00387     
00388     // Go through all the subobjects.
00389     for (unsigned I = 0, E = OffsetVector.size(); I != E; ++I) {
00390       uint64_t Offset = OffsetVector[I];
00391 
00392       BaseSubobject OverriddenSubobject = BaseSubobject(OverriddenRD, Offset);
00393       BaseSubobjectMethodPairTy SubobjectAndMethod =
00394         std::make_pair(OverriddenSubobject, OverriddenMD);
00395       
00396       OverriderInfo &Overrider = OverridersMap[SubobjectAndMethod];
00397 
00398       assert(Overrider.Method && "Did not find existing overrider!");
00399 
00400       // Check if we need return adjustments or base adjustments.
00401       // (We don't want to do this for pure virtual member functions).
00402       if (!NewMD->isPure()) {
00403         // Get the return adjustment base offset.
00404         BaseOffset ReturnBaseOffset =
00405           ComputeReturnAdjustmentBaseOffset(Context, NewMD, OverriddenMD);
00406 
00407         if (!ReturnBaseOffset.isEmpty()) {
00408           // Store the return adjustment base offset.
00409           ReturnAdjustments[SubobjectAndMethod] = ReturnBaseOffset;
00410         }
00411       }
00412 
00413       // Set the new overrider.
00414       Overrider.Offset = OverriderOffsetInLayoutClass;
00415       Overrider.Method = NewMD;
00416       
00417       // And propagate it further.
00418       PropagateOverrider(OverriddenMD, NewBase, OverriderOffsetInLayoutClass,
00419                          NewMD, Offsets);
00420     }
00421   }
00422 }
00423 
00424 void 
00425 FinalOverriders::MergeSubobjectOffsets(const SubobjectOffsetsMapTy &NewOffsets,
00426                                        SubobjectOffsetsMapTy &Offsets) {
00427   // Iterate over the new offsets.
00428   for (SubobjectOffsetsMapTy::const_iterator I = NewOffsets.begin(),
00429        E = NewOffsets.end(); I != E; ++I) {
00430     const CXXRecordDecl *NewRD = I->first;
00431     const OffsetSetVectorTy& NewOffsetVector = I->second;
00432     
00433     OffsetSetVectorTy &OffsetVector = Offsets[NewRD];
00434     
00435     // Merge the new offsets set vector into the old.
00436     OffsetVector.insert(NewOffsetVector.begin(), NewOffsetVector.end());
00437   }
00438 }
00439 
00440 void FinalOverriders::ComputeFinalOverriders(BaseSubobject Base,
00441                                              bool BaseSubobjectIsVisitedVBase,
00442                                              uint64_t OffsetInLayoutClass,
00443                                              SubobjectOffsetsMapTy &Offsets) {
00444   const CXXRecordDecl *RD = Base.getBase();
00445   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00446   
00447   SubobjectOffsetsMapTy NewOffsets;
00448   
00449   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00450        E = RD->bases_end(); I != E; ++I) {
00451     const CXXRecordDecl *BaseDecl = 
00452       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00453     
00454     // Ignore bases that don't have any virtual member functions.
00455     if (!BaseDecl->isPolymorphic())
00456       continue;
00457     
00458     bool IsVisitedVirtualBase = BaseSubobjectIsVisitedVBase;
00459     uint64_t BaseOffset;
00460     uint64_t BaseOffsetInLayoutClass;
00461     if (I->isVirtual()) {
00462       if (!VisitedVirtualBases.insert(BaseDecl))
00463         IsVisitedVirtualBase = true;
00464       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
00465       
00466       const ASTRecordLayout &LayoutClassLayout =
00467         Context.getASTRecordLayout(LayoutClass);
00468       BaseOffsetInLayoutClass = 
00469         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
00470     } else {
00471       BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
00472       BaseOffsetInLayoutClass = Layout.getBaseClassOffset(BaseDecl) +
00473         OffsetInLayoutClass;
00474     }
00475     
00476     // Compute the final overriders for this base.
00477     // We always want to compute the final overriders, even if the base is a
00478     // visited virtual base. Consider:
00479     //
00480     // struct A {
00481     //   virtual void f();
00482     //   virtual void g();
00483     // };
00484     //  
00485     // struct B : virtual A {
00486     //   void f();
00487     // };
00488     //
00489     // struct C : virtual A {
00490     //   void g ();
00491     // };
00492     //
00493     // struct D : B, C { };
00494     //
00495     // Here, we still want to compute the overriders for A as a base of C, 
00496     // because otherwise we'll miss that C::g overrides A::f.
00497     ComputeFinalOverriders(BaseSubobject(BaseDecl, BaseOffset), 
00498                            IsVisitedVirtualBase, BaseOffsetInLayoutClass, 
00499                            NewOffsets);
00500   }
00501 
00502   /// Now add the overriders for this particular subobject.
00503   /// (We don't want to do this more than once for a virtual base).
00504   if (!BaseSubobjectIsVisitedVBase)
00505     AddOverriders(Base, OffsetInLayoutClass, NewOffsets);
00506   
00507   // And merge the newly discovered subobject offsets.
00508   MergeSubobjectOffsets(NewOffsets, Offsets);
00509 
00510   /// Finally, add the offset for our own subobject.
00511   Offsets[RD].insert(Base.getBaseOffset());
00512 }
00513 
00514 void FinalOverriders::dump(llvm::raw_ostream &Out, BaseSubobject Base) {
00515   const CXXRecordDecl *RD = Base.getBase();
00516   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00517 
00518   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
00519        E = RD->bases_end(); I != E; ++I) {
00520     const CXXRecordDecl *BaseDecl = 
00521       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
00522     
00523     // Ignore bases that don't have any virtual member functions.
00524     if (!BaseDecl->isPolymorphic())
00525       continue;
00526 
00527     uint64_t BaseOffset;
00528     if (I->isVirtual()) {
00529       if (!VisitedVirtualBases.insert(BaseDecl)) {
00530         // We've visited this base before.
00531         continue;
00532       }
00533       
00534       BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
00535     } else {
00536       BaseOffset = Layout.getBaseClassOffset(BaseDecl) + 
00537         Base.getBaseOffset();
00538     }
00539 
00540     dump(Out, BaseSubobject(BaseDecl, BaseOffset));
00541   }
00542 
00543   Out << "Final overriders for (" << RD->getQualifiedNameAsString() << ", ";
00544   Out << Base.getBaseOffset() / 8 << ")\n";
00545 
00546   // Now dump the overriders for this base subobject.
00547   for (CXXRecordDecl::method_iterator I = RD->method_begin(), 
00548        E = RD->method_end(); I != E; ++I) {
00549     const CXXMethodDecl *MD = *I;
00550 
00551     if (!MD->isVirtual())
00552       continue;
00553   
00554     OverriderInfo Overrider = getOverrider(Base, MD);
00555 
00556     Out << "  " << MD->getQualifiedNameAsString() << " - (";
00557     Out << Overrider.Method->getQualifiedNameAsString();
00558     Out << ", " << ", " << Overrider.Offset / 8 << ')';
00559 
00560     AdjustmentOffsetsMapTy::const_iterator AI =
00561       ReturnAdjustments.find(std::make_pair(Base, MD));
00562     if (AI != ReturnAdjustments.end()) {
00563       const BaseOffset &Offset = AI->second;
00564 
00565       Out << " [ret-adj: ";
00566       if (Offset.VirtualBase)
00567         Out << Offset.VirtualBase->getQualifiedNameAsString() << " vbase, ";
00568              
00569       Out << Offset.NonVirtualOffset << " nv]";
00570     }
00571     
00572     Out << "\n";
00573   }  
00574 }
00575 
00576 /// VTableComponent - Represents a single component in a vtable.
00577 class VTableComponent {
00578 public:
00579   enum Kind {
00580     CK_VCallOffset,
00581     CK_VBaseOffset,
00582     CK_OffsetToTop,
00583     CK_RTTI,
00584     CK_FunctionPointer,
00585     
00586     /// CK_CompleteDtorPointer - A pointer to the complete destructor.
00587     CK_CompleteDtorPointer,
00588     
00589     /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
00590     CK_DeletingDtorPointer,
00591     
00592     /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
00593     /// will end up never being called. Such vtable function pointers are
00594     /// represented as a CK_UnusedFunctionPointer. 
00595     CK_UnusedFunctionPointer
00596   };
00597 
00598   static VTableComponent MakeVCallOffset(int64_t Offset) {
00599     return VTableComponent(CK_VCallOffset, Offset);
00600   }
00601 
00602   static VTableComponent MakeVBaseOffset(int64_t Offset) {
00603     return VTableComponent(CK_VBaseOffset, Offset);
00604   }
00605 
00606   static VTableComponent MakeOffsetToTop(int64_t Offset) {
00607     return VTableComponent(CK_OffsetToTop, Offset);
00608   }
00609   
00610   static VTableComponent MakeRTTI(const CXXRecordDecl *RD) {
00611     return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
00612   }
00613 
00614   static VTableComponent MakeFunction(const CXXMethodDecl *MD) {
00615     assert(!isa<CXXDestructorDecl>(MD) && 
00616            "Don't use MakeFunction with destructors!");
00617 
00618     return VTableComponent(CK_FunctionPointer, 
00619                            reinterpret_cast<uintptr_t>(MD));
00620   }
00621   
00622   static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
00623     return VTableComponent(CK_CompleteDtorPointer,
00624                            reinterpret_cast<uintptr_t>(DD));
00625   }
00626 
00627   static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
00628     return VTableComponent(CK_DeletingDtorPointer, 
00629                            reinterpret_cast<uintptr_t>(DD));
00630   }
00631 
00632   static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
00633     assert(!isa<CXXDestructorDecl>(MD) && 
00634            "Don't use MakeUnusedFunction with destructors!");
00635     return VTableComponent(CK_UnusedFunctionPointer,
00636                            reinterpret_cast<uintptr_t>(MD));                           
00637   }
00638 
00639   static VTableComponent getFromOpaqueInteger(uint64_t I) {
00640     return VTableComponent(I);
00641   }
00642 
00643   /// getKind - Get the kind of this vtable component.
00644   Kind getKind() const {
00645     return (Kind)(Value & 0x7);
00646   }
00647 
00648   int64_t getVCallOffset() const {
00649     assert(getKind() == CK_VCallOffset && "Invalid component kind!");
00650     
00651     return getOffset();
00652   }
00653 
00654   int64_t getVBaseOffset() const {
00655     assert(getKind() == CK_VBaseOffset && "Invalid component kind!");
00656     
00657     return getOffset();
00658   }
00659 
00660   int64_t getOffsetToTop() const {
00661     assert(getKind() == CK_OffsetToTop && "Invalid component kind!");
00662     
00663     return getOffset();
00664   }
00665   
00666   const CXXRecordDecl *getRTTIDecl() const {
00667     assert(getKind() == CK_RTTI && "Invalid component kind!");
00668     
00669     return reinterpret_cast<CXXRecordDecl *>(getPointer());
00670   }
00671   
00672   const CXXMethodDecl *getFunctionDecl() const {
00673     assert(getKind() == CK_FunctionPointer);
00674     
00675     return reinterpret_cast<CXXMethodDecl *>(getPointer());
00676   }
00677 
00678   const CXXDestructorDecl *getDestructorDecl() const {
00679     assert((getKind() == CK_CompleteDtorPointer ||
00680             getKind() == CK_DeletingDtorPointer) && "Invalid component kind!");
00681     
00682     return reinterpret_cast<CXXDestructorDecl *>(getPointer());
00683   }
00684 
00685   const CXXMethodDecl *getUnusedFunctionDecl() const {
00686     assert(getKind() == CK_UnusedFunctionPointer);
00687     
00688     return reinterpret_cast<CXXMethodDecl *>(getPointer());
00689   }
00690   
00691 private:
00692   VTableComponent(Kind ComponentKind, int64_t Offset) {
00693     assert((ComponentKind == CK_VCallOffset || 
00694             ComponentKind == CK_VBaseOffset ||
00695             ComponentKind == CK_OffsetToTop) && "Invalid component kind!");
00696     assert(Offset <= ((1LL << 56) - 1) && "Offset is too big!");
00697     
00698     Value = ((Offset << 3) | ComponentKind);
00699   }
00700 
00701   VTableComponent(Kind ComponentKind, uintptr_t Ptr) {
00702     assert((ComponentKind == CK_RTTI || 
00703             ComponentKind == CK_FunctionPointer ||
00704             ComponentKind == CK_CompleteDtorPointer ||
00705             ComponentKind == CK_DeletingDtorPointer ||
00706             ComponentKind == CK_UnusedFunctionPointer) &&
00707             "Invalid component kind!");
00708     
00709     assert((Ptr & 7) == 0 && "Pointer not sufficiently aligned!");
00710     
00711     Value = Ptr | ComponentKind;
00712   }
00713   
00714   int64_t getOffset() const {
00715     assert((getKind() == CK_VCallOffset || getKind() == CK_VBaseOffset ||
00716             getKind() == CK_OffsetToTop) && "Invalid component kind!");
00717     
00718     return Value >> 3;
00719   }
00720 
00721   uintptr_t getPointer() const {
00722     assert((getKind() == CK_RTTI || 
00723             getKind() == CK_FunctionPointer ||
00724             getKind() == CK_CompleteDtorPointer ||
00725             getKind() == CK_DeletingDtorPointer ||
00726             getKind() == CK_UnusedFunctionPointer) &&
00727            "Invalid component kind!");
00728     
00729     return static_cast<uintptr_t>(Value & ~7ULL);
00730   }
00731   
00732   explicit VTableComponent(uint64_t Value)
00733     : Value(Value) { }
00734 
00735   /// The kind is stored in the lower 3 bits of the value. For offsets, we
00736   /// make use of the facts that classes can't be larger than 2^55 bytes,
00737   /// so we store the offset in the lower part of the 61 bytes that remain.
00738   /// (The reason that we're not simply using a PointerIntPair here is that we
00739   /// need the offsets to be 64-bit, even when on a 32-bit machine).
00740   int64_t Value;
00741 };
00742 
00743 /// VCallOffsetMap - Keeps track of vcall offsets when building a vtable.
00744 struct VCallOffsetMap {
00745   
00746   typedef std::pair<const CXXMethodDecl *, int64_t> MethodAndOffsetPairTy;
00747   
00748   /// Offsets - Keeps track of methods and their offsets.
00749   // FIXME: This should be a real map and not a vector.
00750   llvm::SmallVector<MethodAndOffsetPairTy, 16> Offsets;
00751 
00752   /// MethodsCanShareVCallOffset - Returns whether two virtual member functions
00753   /// can share the same vcall offset.
00754   static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
00755                                          const CXXMethodDecl *RHS);
00756 
00757 public:
00758   /// AddVCallOffset - Adds a vcall offset to the map. Returns true if the
00759   /// add was successful, or false if there was already a member function with
00760   /// the same signature in the map.
00761   bool AddVCallOffset(const CXXMethodDecl *MD, int64_t OffsetOffset);
00762   
00763   /// getVCallOffsetOffset - Returns the vcall offset offset (relative to the
00764   /// vtable address point) for the given virtual member function.
00765   int64_t getVCallOffsetOffset(const CXXMethodDecl *MD);
00766   
00767   // empty - Return whether the offset map is empty or not.
00768   bool empty() const { return Offsets.empty(); }
00769 };
00770 
00771 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
00772                                     const CXXMethodDecl *RHS) {
00773   ASTContext &C = LHS->getASTContext(); // TODO: thread this down
00774   CanQual<FunctionProtoType>
00775     LT = C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
00776     RT = C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
00777 
00778   // Fast-path matches in the canonical types.
00779   if (LT == RT) return true;
00780 
00781   // Force the signatures to match.  We can't rely on the overrides
00782   // list here because there isn't necessarily an inheritance
00783   // relationship between the two methods.
00784   if (LT.getQualifiers() != RT.getQualifiers() ||
00785       LT->getNumArgs() != RT->getNumArgs())
00786     return false;
00787   for (unsigned I = 0, E = LT->getNumArgs(); I != E; ++I)
00788     if (LT->getArgType(I) != RT->getArgType(I))
00789       return false;
00790   return true;
00791 }
00792 
00793 bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
00794                                                 const CXXMethodDecl *RHS) {
00795   assert(LHS->isVirtual() && "LHS must be virtual!");
00796   assert(RHS->isVirtual() && "LHS must be virtual!");
00797   
00798   // A destructor can share a vcall offset with another destructor.
00799   if (isa<CXXDestructorDecl>(LHS))
00800     return isa<CXXDestructorDecl>(RHS);
00801 
00802   // FIXME: We need to check more things here.
00803   
00804   // The methods must have the same name.
00805   DeclarationName LHSName = LHS->getDeclName();
00806   DeclarationName RHSName = RHS->getDeclName();
00807   if (LHSName != RHSName)
00808     return false;
00809 
00810   // And the same signatures.
00811   return HasSameVirtualSignature(LHS, RHS);
00812 }
00813 
00814 bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD, 
00815                                     int64_t OffsetOffset) {
00816   // Check if we can reuse an offset.
00817   for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
00818     if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
00819       return false;
00820   }
00821   
00822   // Add the offset.
00823   Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
00824   return true;
00825 }
00826 
00827 int64_t VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
00828   // Look for an offset.
00829   for (unsigned I = 0, E = Offsets.size(); I != E; ++I) {
00830     if (MethodsCanShareVCallOffset(Offsets[I].first, MD))
00831       return Offsets[I].second;
00832   }
00833   
00834   assert(false && "Should always find a vcall offset offset!");
00835   return 0;
00836 }
00837 
00838 /// VCallAndVBaseOffsetBuilder - Class for building vcall and vbase offsets.
00839 class VCallAndVBaseOffsetBuilder {
00840 public:
00841   typedef llvm::DenseMap<const CXXRecordDecl *, int64_t> 
00842     VBaseOffsetOffsetsMapTy;
00843 
00844 private:
00845   /// MostDerivedClass - The most derived class for which we're building vcall
00846   /// and vbase offsets.
00847   const CXXRecordDecl *MostDerivedClass;
00848   
00849   /// LayoutClass - The class we're using for layout information. Will be 
00850   /// different than the most derived class if we're building a construction
00851   /// vtable.
00852   const CXXRecordDecl *LayoutClass;
00853   
00854   /// Context - The ASTContext which we will use for layout information.
00855   ASTContext &Context;
00856 
00857   /// Components - vcall and vbase offset components
00858   typedef llvm::SmallVector<VTableComponent, 64> VTableComponentVectorTy;
00859   VTableComponentVectorTy Components;
00860   
00861   /// VisitedVirtualBases - Visited virtual bases.
00862   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
00863   
00864   /// VCallOffsets - Keeps track of vcall offsets.
00865   VCallOffsetMap VCallOffsets;
00866 
00867 
00868   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets,
00869   /// relative to the address point.
00870   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
00871   
00872   /// FinalOverriders - The final overriders of the most derived class.
00873   /// (Can be null when we're not building a vtable of the most derived class).
00874   const FinalOverriders *Overriders;
00875 
00876   /// AddVCallAndVBaseOffsets - Add vcall offsets and vbase offsets for the
00877   /// given base subobject.
00878   void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
00879                                uint64_t RealBaseOffset);
00880   
00881   /// AddVCallOffsets - Add vcall offsets for the given base subobject.
00882   void AddVCallOffsets(BaseSubobject Base, uint64_t VBaseOffset);
00883   
00884   /// AddVBaseOffsets - Add vbase offsets for the given class.
00885   void AddVBaseOffsets(const CXXRecordDecl *Base, uint64_t OffsetInLayoutClass);
00886   
00887   /// getCurrentOffsetOffset - Get the current vcall or vbase offset offset in
00888   /// bytes, relative to the vtable address point.
00889   int64_t getCurrentOffsetOffset() const;
00890   
00891 public:
00892   VCallAndVBaseOffsetBuilder(const CXXRecordDecl *MostDerivedClass,
00893                              const CXXRecordDecl *LayoutClass,
00894                              const FinalOverriders *Overriders,
00895                              BaseSubobject Base, bool BaseIsVirtual,
00896                              uint64_t OffsetInLayoutClass)
00897     : MostDerivedClass(MostDerivedClass), LayoutClass(LayoutClass), 
00898     Context(MostDerivedClass->getASTContext()), Overriders(Overriders) {
00899       
00900     // Add vcall and vbase offsets.
00901     AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
00902   }
00903   
00904   /// Methods for iterating over the components.
00905   typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
00906   const_iterator components_begin() const { return Components.rbegin(); }
00907   const_iterator components_end() const { return Components.rend(); }
00908   
00909   const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
00910   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
00911     return VBaseOffsetOffsets;
00912   }
00913 };
00914   
00915 void 
00916 VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
00917                                                     bool BaseIsVirtual,
00918                                                     uint64_t RealBaseOffset) {
00919   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
00920   
00921   // Itanium C++ ABI 2.5.2:
00922   //   ..in classes sharing a virtual table with a primary base class, the vcall
00923   //   and vbase offsets added by the derived class all come before the vcall
00924   //   and vbase offsets required by the base class, so that the latter may be
00925   //   laid out as required by the base class without regard to additions from
00926   //   the derived class(es).
00927 
00928   // (Since we're emitting the vcall and vbase offsets in reverse order, we'll
00929   // emit them for the primary base first).
00930   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
00931     bool PrimaryBaseIsVirtual = Layout.getPrimaryBaseWasVirtual();
00932 
00933     uint64_t PrimaryBaseOffset;
00934     
00935     // Get the base offset of the primary base.
00936     if (PrimaryBaseIsVirtual) {
00937       assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
00938              "Primary vbase should have a zero offset!");
00939       
00940       const ASTRecordLayout &MostDerivedClassLayout =
00941         Context.getASTRecordLayout(MostDerivedClass);
00942       
00943       PrimaryBaseOffset = 
00944         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
00945     } else {
00946       assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
00947              "Primary base should have a zero offset!");
00948 
00949       PrimaryBaseOffset = Base.getBaseOffset();
00950     }
00951 
00952     AddVCallAndVBaseOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
00953                             PrimaryBaseIsVirtual, RealBaseOffset);
00954   }
00955 
00956   AddVBaseOffsets(Base.getBase(), RealBaseOffset);
00957 
00958   // We only want to add vcall offsets for virtual bases.
00959   if (BaseIsVirtual)
00960     AddVCallOffsets(Base, RealBaseOffset);
00961 }
00962 
00963 int64_t VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
00964   // OffsetIndex is the index of this vcall or vbase offset, relative to the 
00965   // vtable address point. (We subtract 3 to account for the information just
00966   // above the address point, the RTTI info, the offset to top, and the
00967   // vcall offset itself).
00968   int64_t OffsetIndex = -(int64_t)(3 + Components.size());
00969     
00970   // FIXME: We shouldn't use / 8 here.
00971   int64_t OffsetOffset = OffsetIndex * 
00972     (int64_t)Context.Target.getPointerWidth(0) / 8;
00973 
00974   return OffsetOffset;
00975 }
00976 
00977 void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base, 
00978                                                  uint64_t VBaseOffset) {
00979   const CXXRecordDecl *RD = Base.getBase();
00980   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00981 
00982   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
00983 
00984   // Handle the primary base first.
00985   // We only want to add vcall offsets if the base is non-virtual; a virtual
00986   // primary base will have its vcall and vbase offsets emitted already.
00987   if (PrimaryBase && !Layout.getPrimaryBaseWasVirtual()) {
00988     // Get the base offset of the primary base.
00989     assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
00990            "Primary base should have a zero offset!");
00991 
00992     AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
00993                     VBaseOffset);
00994   }
00995   
00996   // Add the vcall offsets.
00997   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
00998        E = RD->method_end(); I != E; ++I) {
00999     const CXXMethodDecl *MD = *I;
01000     
01001     if (!MD->isVirtual())
01002       continue;
01003 
01004     int64_t OffsetOffset = getCurrentOffsetOffset();
01005     
01006     // Don't add a vcall offset if we already have one for this member function
01007     // signature.
01008     if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
01009       continue;
01010 
01011     int64_t Offset = 0;
01012 
01013     if (Overriders) {
01014       // Get the final overrider.
01015       FinalOverriders::OverriderInfo Overrider = 
01016         Overriders->getOverrider(Base, MD);
01017       
01018       /// The vcall offset is the offset from the virtual base to the object 
01019       /// where the function was overridden.
01020       // FIXME: We should not use / 8 here.
01021       Offset = (int64_t)(Overrider.Offset - VBaseOffset) / 8;
01022     }
01023     
01024     Components.push_back(VTableComponent::MakeVCallOffset(Offset));
01025   }
01026 
01027   // And iterate over all non-virtual bases (ignoring the primary base).
01028   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01029        E = RD->bases_end(); I != E; ++I) {
01030   
01031     if (I->isVirtual())
01032       continue;
01033 
01034     const CXXRecordDecl *BaseDecl =
01035       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01036     if (BaseDecl == PrimaryBase)
01037       continue;
01038 
01039     // Get the base offset of this base.
01040     uint64_t BaseOffset = Base.getBaseOffset() + 
01041       Layout.getBaseClassOffset(BaseDecl);
01042     
01043     AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset);
01044   }
01045 }
01046 
01047 void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
01048                                                  uint64_t OffsetInLayoutClass) {
01049   const ASTRecordLayout &LayoutClassLayout = 
01050     Context.getASTRecordLayout(LayoutClass);
01051 
01052   // Add vbase offsets.
01053   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01054        E = RD->bases_end(); I != E; ++I) {
01055     const CXXRecordDecl *BaseDecl =
01056       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01057 
01058     // Check if this is a virtual base that we haven't visited before.
01059     if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
01060       // FIXME: We shouldn't use / 8 here.
01061       int64_t Offset = 
01062         (int64_t)(LayoutClassLayout.getVBaseClassOffset(BaseDecl) - 
01063                   OffsetInLayoutClass) / 8;
01064 
01065       // Add the vbase offset offset.
01066       assert(!VBaseOffsetOffsets.count(BaseDecl) &&
01067              "vbase offset offset already exists!");
01068 
01069       int64_t VBaseOffsetOffset = getCurrentOffsetOffset();
01070       VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset));
01071 
01072       Components.push_back(VTableComponent::MakeVBaseOffset(Offset));
01073     }
01074 
01075     // Check the base class looking for more vbase offsets.
01076     AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
01077   }
01078 }
01079 
01080 /// VTableBuilder - Class for building vtable layout information.
01081 class VTableBuilder {
01082 public:
01083   /// PrimaryBasesSetVectorTy - A set vector of direct and indirect 
01084   /// primary bases.
01085   typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> 
01086     PrimaryBasesSetVectorTy;
01087   
01088   typedef llvm::DenseMap<const CXXRecordDecl *, int64_t> 
01089     VBaseOffsetOffsetsMapTy;
01090   
01091   typedef llvm::DenseMap<BaseSubobject, uint64_t> 
01092     AddressPointsMapTy;
01093 
01094 private:
01095   /// VTables - Global vtable information.
01096   CodeGenVTables &VTables;
01097   
01098   /// MostDerivedClass - The most derived class for which we're building this
01099   /// vtable.
01100   const CXXRecordDecl *MostDerivedClass;
01101 
01102   /// MostDerivedClassOffset - If we're building a construction vtable, this
01103   /// holds the offset from the layout class to the most derived class.
01104   const uint64_t MostDerivedClassOffset;
01105   
01106   /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual 
01107   /// base. (This only makes sense when building a construction vtable).
01108   bool MostDerivedClassIsVirtual;
01109   
01110   /// LayoutClass - The class we're using for layout information. Will be 
01111   /// different than the most derived class if we're building a construction
01112   /// vtable.
01113   const CXXRecordDecl *LayoutClass;
01114   
01115   /// Context - The ASTContext which we will use for layout information.
01116   ASTContext &Context;
01117   
01118   /// FinalOverriders - The final overriders of the most derived class.
01119   const FinalOverriders Overriders;
01120 
01121   /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
01122   /// bases in this vtable.
01123   llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
01124 
01125   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
01126   /// the most derived class.
01127   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
01128   
01129   /// Components - The components of the vtable being built.
01130   llvm::SmallVector<VTableComponent, 64> Components;
01131 
01132   /// AddressPoints - Address points for the vtable being built.
01133   AddressPointsMapTy AddressPoints;
01134 
01135   /// MethodInfo - Contains information about a method in a vtable.
01136   /// (Used for computing 'this' pointer adjustment thunks.
01137   struct MethodInfo {
01138     /// BaseOffset - The base offset of this method.
01139     const uint64_t BaseOffset;
01140     
01141     /// BaseOffsetInLayoutClass - The base offset in the layout class of this
01142     /// method.
01143     const uint64_t BaseOffsetInLayoutClass;
01144     
01145     /// VTableIndex - The index in the vtable that this method has.
01146     /// (For destructors, this is the index of the complete destructor).
01147     const uint64_t VTableIndex;
01148     
01149     MethodInfo(uint64_t BaseOffset, uint64_t BaseOffsetInLayoutClass, 
01150                uint64_t VTableIndex)
01151       : BaseOffset(BaseOffset), 
01152       BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
01153       VTableIndex(VTableIndex) { }
01154     
01155     MethodInfo() : BaseOffset(0), BaseOffsetInLayoutClass(0), VTableIndex(0) { }
01156   };
01157   
01158   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
01159   
01160   /// MethodInfoMap - The information for all methods in the vtable we're
01161   /// currently building.
01162   MethodInfoMapTy MethodInfoMap;
01163   
01164   typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
01165   
01166   /// VTableThunks - The thunks by vtable index in the vtable currently being 
01167   /// built.
01168   VTableThunksMapTy VTableThunks;
01169 
01170   typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
01171   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
01172   
01173   /// Thunks - A map that contains all the thunks needed for all methods in the
01174   /// most derived class for which the vtable is currently being built.
01175   ThunksMapTy Thunks;
01176   
01177   /// AddThunk - Add a thunk for the given method.
01178   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
01179   
01180   /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
01181   /// part of the vtable we're currently building.
01182   void ComputeThisAdjustments();
01183   
01184   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
01185 
01186   /// PrimaryVirtualBases - All known virtual bases who are a primary base of
01187   /// some other base.
01188   VisitedVirtualBasesSetTy PrimaryVirtualBases;
01189 
01190   /// ComputeReturnAdjustment - Compute the return adjustment given a return
01191   /// adjustment base offset.
01192   ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
01193   
01194   /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
01195   /// the 'this' pointer from the base subobject to the derived subobject.
01196   BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
01197                                              BaseSubobject Derived) const;
01198 
01199   /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
01200   /// given virtual member function, its offset in the layout class and its
01201   /// final overrider.
01202   ThisAdjustment 
01203   ComputeThisAdjustment(const CXXMethodDecl *MD, 
01204                         uint64_t BaseOffsetInLayoutClass,
01205                         FinalOverriders::OverriderInfo Overrider);
01206 
01207   /// AddMethod - Add a single virtual member function to the vtable
01208   /// components vector.
01209   void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
01210 
01211   /// IsOverriderUsed - Returns whether the overrider will ever be used in this
01212   /// part of the vtable. 
01213   ///
01214   /// Itanium C++ ABI 2.5.2:
01215   ///
01216   ///   struct A { virtual void f(); };
01217   ///   struct B : virtual public A { int i; };
01218   ///   struct C : virtual public A { int j; };
01219   ///   struct D : public B, public C {};
01220   ///
01221   ///   When B and C are declared, A is a primary base in each case, so although
01222   ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
01223   ///   adjustment is required and no thunk is generated. However, inside D
01224   ///   objects, A is no longer a primary base of C, so if we allowed calls to
01225   ///   C::f() to use the copy of A's vtable in the C subobject, we would need
01226   ///   to adjust this from C* to B::A*, which would require a third-party 
01227   ///   thunk. Since we require that a call to C::f() first convert to A*, 
01228   ///   C-in-D's copy of A's vtable is never referenced, so this is not 
01229   ///   necessary.
01230   bool IsOverriderUsed(const CXXMethodDecl *Overrider,
01231                        uint64_t BaseOffsetInLayoutClass,
01232                        const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01233                        uint64_t FirstBaseOffsetInLayoutClass) const;
01234 
01235   
01236   /// AddMethods - Add the methods of this base subobject and all its
01237   /// primary bases to the vtable components vector.
01238   void AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,                  
01239                   const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01240                   uint64_t FirstBaseOffsetInLayoutClass,
01241                   PrimaryBasesSetVectorTy &PrimaryBases);
01242 
01243   // LayoutVTable - Layout the vtable for the given base class, including its
01244   // secondary vtables and any vtables for virtual bases.
01245   void LayoutVTable();
01246 
01247   /// LayoutPrimaryAndSecondaryVTables - Layout the primary vtable for the
01248   /// given base subobject, as well as all its secondary vtables.
01249   ///
01250   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
01251   /// or a direct or indirect base of a virtual base.
01252   ///
01253   /// \param BaseIsVirtualInLayoutClass - Whether the base subobject is virtual
01254   /// in the layout class. 
01255   void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
01256                                         bool BaseIsMorallyVirtual,
01257                                         bool BaseIsVirtualInLayoutClass,
01258                                         uint64_t OffsetInLayoutClass);
01259   
01260   /// LayoutSecondaryVTables - Layout the secondary vtables for the given base
01261   /// subobject.
01262   ///
01263   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
01264   /// or a direct or indirect base of a virtual base.
01265   void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
01266                               uint64_t OffsetInLayoutClass);
01267 
01268   /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
01269   /// class hierarchy.
01270   void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, 
01271                                     uint64_t OffsetInLayoutClass,
01272                                     VisitedVirtualBasesSetTy &VBases);
01273 
01274   /// LayoutVTablesForVirtualBases - Layout vtables for all virtual bases of the
01275   /// given base (excluding any primary bases).
01276   void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, 
01277                                     VisitedVirtualBasesSetTy &VBases);
01278 
01279   /// isBuildingConstructionVTable - Return whether this vtable builder is
01280   /// building a construction vtable.
01281   bool isBuildingConstructorVTable() const { 
01282     return MostDerivedClass != LayoutClass;
01283   }
01284 
01285 public:
01286   VTableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass,
01287                 uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual,
01288                 const CXXRecordDecl *LayoutClass)
01289     : VTables(VTables), MostDerivedClass(MostDerivedClass),
01290     MostDerivedClassOffset(MostDerivedClassOffset), 
01291     MostDerivedClassIsVirtual(MostDerivedClassIsVirtual), 
01292     LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), 
01293     Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
01294 
01295     LayoutVTable();
01296   }
01297 
01298   ThunksMapTy::const_iterator thunks_begin() const {
01299     return Thunks.begin();
01300   }
01301 
01302   ThunksMapTy::const_iterator thunks_end() const {
01303     return Thunks.end();
01304   }
01305 
01306   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
01307     return VBaseOffsetOffsets;
01308   }
01309 
01310   /// getNumVTableComponents - Return the number of components in the vtable
01311   /// currently built.
01312   uint64_t getNumVTableComponents() const {
01313     return Components.size();
01314   }
01315 
01316   const uint64_t *vtable_components_data_begin() const {
01317     return reinterpret_cast<const uint64_t *>(Components.begin());
01318   }
01319   
01320   const uint64_t *vtable_components_data_end() const {
01321     return reinterpret_cast<const uint64_t *>(Components.end());
01322   }
01323   
01324   AddressPointsMapTy::const_iterator address_points_begin() const {
01325     return AddressPoints.begin();
01326   }
01327 
01328   AddressPointsMapTy::const_iterator address_points_end() const {
01329     return AddressPoints.end();
01330   }
01331 
01332   VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
01333     return VTableThunks.begin();
01334   }
01335 
01336   VTableThunksMapTy::const_iterator vtable_thunks_end() const {
01337     return VTableThunks.end();
01338   }
01339 
01340   /// dumpLayout - Dump the vtable layout.
01341   void dumpLayout(llvm::raw_ostream&);
01342 };
01343 
01344 void VTableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
01345   assert(!isBuildingConstructorVTable() && 
01346          "Can't add thunks for construction vtable");
01347 
01348   llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
01349   
01350   // Check if we have this thunk already.
01351   if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != 
01352       ThunksVector.end())
01353     return;
01354   
01355   ThunksVector.push_back(Thunk);
01356 }
01357 
01358 typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
01359 
01360 /// ComputeAllOverriddenMethods - Given a method decl, will return a set of all
01361 /// the overridden methods that the function decl overrides.
01362 static void 
01363 ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
01364                             OverriddenMethodsSetTy& OverriddenMethods) {
01365   assert(MD->isVirtual() && "Method is not virtual!");
01366 
01367   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
01368        E = MD->end_overridden_methods(); I != E; ++I) {
01369     const CXXMethodDecl *OverriddenMD = *I;
01370     
01371     OverriddenMethods.insert(OverriddenMD);
01372     
01373     ComputeAllOverriddenMethods(OverriddenMD, OverriddenMethods);
01374   }
01375 }
01376 
01377 void VTableBuilder::ComputeThisAdjustments() {
01378   // Now go through the method info map and see if any of the methods need
01379   // 'this' pointer adjustments.
01380   for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
01381        E = MethodInfoMap.end(); I != E; ++I) {
01382     const CXXMethodDecl *MD = I->first;
01383     const MethodInfo &MethodInfo = I->second;
01384 
01385     // Ignore adjustments for unused function pointers.
01386     uint64_t VTableIndex = MethodInfo.VTableIndex;
01387     if (Components[VTableIndex].getKind() == 
01388         VTableComponent::CK_UnusedFunctionPointer)
01389       continue;
01390     
01391     // Get the final overrider for this method.
01392     FinalOverriders::OverriderInfo Overrider =
01393       Overriders.getOverrider(BaseSubobject(MD->getParent(), 
01394                                             MethodInfo.BaseOffset), MD);
01395     
01396     // Check if we need an adjustment at all.
01397     if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
01398       // When a return thunk is needed by a derived class that overrides a
01399       // virtual base, gcc uses a virtual 'this' adjustment as well. 
01400       // While the thunk itself might be needed by vtables in subclasses or
01401       // in construction vtables, there doesn't seem to be a reason for using
01402       // the thunk in this vtable. Still, we do so to match gcc.
01403       if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
01404         continue;
01405     }
01406 
01407     ThisAdjustment ThisAdjustment =
01408       ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
01409 
01410     if (ThisAdjustment.isEmpty())
01411       continue;
01412 
01413     // Add it.
01414     VTableThunks[VTableIndex].This = ThisAdjustment;
01415 
01416     if (isa<CXXDestructorDecl>(MD)) {
01417       // Add an adjustment for the deleting destructor as well.
01418       VTableThunks[VTableIndex + 1].This = ThisAdjustment;
01419     }
01420   }
01421 
01422   /// Clear the method info map.
01423   MethodInfoMap.clear();
01424   
01425   if (isBuildingConstructorVTable()) {
01426     // We don't need to store thunk information for construction vtables.
01427     return;
01428   }
01429 
01430   for (VTableThunksMapTy::const_iterator I = VTableThunks.begin(),
01431        E = VTableThunks.end(); I != E; ++I) {
01432     const VTableComponent &Component = Components[I->first];
01433     const ThunkInfo &Thunk = I->second;
01434     const CXXMethodDecl *MD;
01435     
01436     switch (Component.getKind()) {
01437     default:
01438       llvm_unreachable("Unexpected vtable component kind!");
01439     case VTableComponent::CK_FunctionPointer:
01440       MD = Component.getFunctionDecl();
01441       break;
01442     case VTableComponent::CK_CompleteDtorPointer:
01443       MD = Component.getDestructorDecl();
01444       break;
01445     case VTableComponent::CK_DeletingDtorPointer:
01446       // We've already added the thunk when we saw the complete dtor pointer.
01447       continue;
01448     }
01449 
01450     if (MD->getParent() == MostDerivedClass)
01451       AddThunk(MD, Thunk);
01452   }
01453 }
01454 
01455 ReturnAdjustment VTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
01456   ReturnAdjustment Adjustment;
01457   
01458   if (!Offset.isEmpty()) {
01459     if (Offset.VirtualBase) {
01460       // Get the virtual base offset offset.
01461       if (Offset.DerivedClass == MostDerivedClass) {
01462         // We can get the offset offset directly from our map.
01463         Adjustment.VBaseOffsetOffset = 
01464           VBaseOffsetOffsets.lookup(Offset.VirtualBase);
01465       } else {
01466         Adjustment.VBaseOffsetOffset = 
01467           VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
01468                                              Offset.VirtualBase);
01469       }
01470     }
01471 
01472     Adjustment.NonVirtual = Offset.NonVirtualOffset;
01473   }
01474   
01475   return Adjustment;
01476 }
01477 
01478 BaseOffset
01479 VTableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
01480                                                BaseSubobject Derived) const {
01481   const CXXRecordDecl *BaseRD = Base.getBase();
01482   const CXXRecordDecl *DerivedRD = Derived.getBase();
01483   
01484   CXXBasePaths Paths(/*FindAmbiguities=*/true,
01485                      /*RecordPaths=*/true, /*DetectVirtual=*/true);
01486 
01487   if (!const_cast<CXXRecordDecl *>(DerivedRD)->
01488       isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
01489     assert(false && "Class must be derived from the passed in base class!");
01490     return BaseOffset();
01491   }
01492 
01493   // We have to go through all the paths, and see which one leads us to the
01494   // right base subobject.
01495   for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
01496        I != E; ++I) {
01497     BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
01498     
01499     // FIXME: Should not use * 8 here.
01500     uint64_t OffsetToBaseSubobject = Offset.NonVirtualOffset * 8;
01501     
01502     if (Offset.VirtualBase) {
01503       // If we have a virtual base class, the non-virtual offset is relative
01504       // to the virtual base class offset.
01505       const ASTRecordLayout &LayoutClassLayout =
01506         Context.getASTRecordLayout(LayoutClass);
01507       
01508       /// Get the virtual base offset, relative to the most derived class 
01509       /// layout.
01510       OffsetToBaseSubobject += 
01511         LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
01512     } else {
01513       // Otherwise, the non-virtual offset is relative to the derived class 
01514       // offset.
01515       OffsetToBaseSubobject += Derived.getBaseOffset();
01516     }
01517     
01518     // Check if this path gives us the right base subobject.
01519     if (OffsetToBaseSubobject == Base.getBaseOffset()) {
01520       // Since we're going from the base class _to_ the derived class, we'll
01521       // invert the non-virtual offset here.
01522       Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
01523       return Offset;
01524     }      
01525   }
01526   
01527   return BaseOffset();
01528 }
01529   
01530 ThisAdjustment 
01531 VTableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD, 
01532                                      uint64_t BaseOffsetInLayoutClass,
01533                                      FinalOverriders::OverriderInfo Overrider) {
01534   // Ignore adjustments for pure virtual member functions.
01535   if (Overrider.Method->isPure())
01536     return ThisAdjustment();
01537   
01538   BaseSubobject OverriddenBaseSubobject(MD->getParent(),
01539                                         BaseOffsetInLayoutClass);
01540   
01541   BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
01542                                        Overrider.Offset);
01543   
01544   // Compute the adjustment offset.
01545   BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
01546                                                       OverriderBaseSubobject);
01547   if (Offset.isEmpty())
01548     return ThisAdjustment();
01549 
01550   ThisAdjustment Adjustment;
01551   
01552   if (Offset.VirtualBase) {
01553     // Get the vcall offset map for this virtual base.
01554     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
01555 
01556     if (VCallOffsets.empty()) {
01557       // We don't have vcall offsets for this virtual base, go ahead and
01558       // build them.
01559       VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
01560                                          /*FinalOverriders=*/0,
01561                                          BaseSubobject(Offset.VirtualBase, 0),                                           
01562                                          /*BaseIsVirtual=*/true,
01563                                          /*OffsetInLayoutClass=*/0);
01564         
01565       VCallOffsets = Builder.getVCallOffsets();
01566     }
01567       
01568     Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
01569   }
01570 
01571   // Set the non-virtual part of the adjustment.
01572   Adjustment.NonVirtual = Offset.NonVirtualOffset;
01573   
01574   return Adjustment;
01575 }
01576   
01577 void 
01578 VTableBuilder::AddMethod(const CXXMethodDecl *MD,
01579                          ReturnAdjustment ReturnAdjustment) {
01580   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
01581     assert(ReturnAdjustment.isEmpty() && 
01582            "Destructor can't have return adjustment!");
01583 
01584     // Add both the complete destructor and the deleting destructor.
01585     Components.push_back(VTableComponent::MakeCompleteDtor(DD));
01586     Components.push_back(VTableComponent::MakeDeletingDtor(DD));
01587   } else {
01588     // Add the return adjustment if necessary.
01589     if (!ReturnAdjustment.isEmpty())
01590       VTableThunks[Components.size()].Return = ReturnAdjustment;
01591 
01592     // Add the function.
01593     Components.push_back(VTableComponent::MakeFunction(MD));
01594   }
01595 }
01596 
01597 /// OverridesIndirectMethodInBase - Return whether the given member function
01598 /// overrides any methods in the set of given bases. 
01599 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
01600 /// For example, if we have:
01601 ///
01602 /// struct A { virtual void f(); }
01603 /// struct B : A { virtual void f(); }
01604 /// struct C : B { virtual void f(); }
01605 ///
01606 /// OverridesIndirectMethodInBase will return true if given C::f as the method 
01607 /// and { A } as the set of bases.
01608 static bool
01609 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
01610                                VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
01611   if (Bases.count(MD->getParent()))
01612     return true;
01613   
01614   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
01615        E = MD->end_overridden_methods(); I != E; ++I) {
01616     const CXXMethodDecl *OverriddenMD = *I;
01617     
01618     // Check "indirect overriders".
01619     if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
01620       return true;
01621   }
01622    
01623   return false;
01624 }
01625 
01626 bool 
01627 VTableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
01628                                uint64_t BaseOffsetInLayoutClass,
01629                                const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01630                                uint64_t FirstBaseOffsetInLayoutClass) const {
01631   // If the base and the first base in the primary base chain have the same
01632   // offsets, then this overrider will be used.
01633   if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
01634    return true;
01635 
01636   // We know now that Base (or a direct or indirect base of it) is a primary
01637   // base in part of the class hierarchy, but not a primary base in the most 
01638   // derived class.
01639   
01640   // If the overrider is the first base in the primary base chain, we know
01641   // that the overrider will be used.
01642   if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
01643     return true;
01644   
01645   VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
01646 
01647   const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
01648   PrimaryBases.insert(RD);
01649 
01650   // Now traverse the base chain, starting with the first base, until we find
01651   // the base that is no longer a primary base.
01652   while (true) {
01653     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01654     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
01655     
01656     if (!PrimaryBase)
01657       break;
01658     
01659     if (Layout.getPrimaryBaseWasVirtual()) {
01660       assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 && 
01661              "Primary base should always be at offset 0!");
01662 
01663       const ASTRecordLayout &LayoutClassLayout =
01664         Context.getASTRecordLayout(LayoutClass);
01665 
01666       // Now check if this is the primary base that is not a primary base in the
01667       // most derived class.
01668       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
01669           FirstBaseOffsetInLayoutClass) {
01670         // We found it, stop walking the chain.
01671         break;
01672       }
01673     } else {
01674       assert(Layout.getBaseClassOffset(PrimaryBase) == 0 && 
01675              "Primary base should always be at offset 0!");
01676     }
01677     
01678     if (!PrimaryBases.insert(PrimaryBase))
01679       assert(false && "Found a duplicate primary base!");
01680 
01681     RD = PrimaryBase;
01682   }
01683   
01684   // If the final overrider is an override of one of the primary bases,
01685   // then we know that it will be used.
01686   return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
01687 }
01688 
01689 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
01690 /// from the nearest base. Returns null if no method was found.
01691 static const CXXMethodDecl * 
01692 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
01693                             VTableBuilder::PrimaryBasesSetVectorTy &Bases) {
01694   OverriddenMethodsSetTy OverriddenMethods;
01695   ComputeAllOverriddenMethods(MD, OverriddenMethods);
01696   
01697   for (int I = Bases.size(), E = 0; I != E; --I) {
01698     const CXXRecordDecl *PrimaryBase = Bases[I - 1];
01699 
01700     // Now check the overriden methods.
01701     for (OverriddenMethodsSetTy::const_iterator I = OverriddenMethods.begin(),
01702          E = OverriddenMethods.end(); I != E; ++I) {
01703       const CXXMethodDecl *OverriddenMD = *I;
01704       
01705       // We found our overridden method.
01706       if (OverriddenMD->getParent() == PrimaryBase)
01707         return OverriddenMD;
01708     }
01709   }
01710   
01711   return 0;
01712 }  
01713 
01714 void
01715 VTableBuilder::AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,                  
01716                           const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01717                           uint64_t FirstBaseOffsetInLayoutClass,
01718                           PrimaryBasesSetVectorTy &PrimaryBases) {
01719   const CXXRecordDecl *RD = Base.getBase();
01720   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01721 
01722   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
01723     uint64_t PrimaryBaseOffset;
01724     uint64_t PrimaryBaseOffsetInLayoutClass;
01725     if (Layout.getPrimaryBaseWasVirtual()) {
01726       assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
01727              "Primary vbase should have a zero offset!");
01728       
01729       const ASTRecordLayout &MostDerivedClassLayout =
01730         Context.getASTRecordLayout(MostDerivedClass);
01731       
01732       PrimaryBaseOffset = 
01733         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
01734       
01735       const ASTRecordLayout &LayoutClassLayout =
01736         Context.getASTRecordLayout(LayoutClass);
01737 
01738       PrimaryBaseOffsetInLayoutClass =
01739         LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
01740     } else {
01741       assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
01742              "Primary base should have a zero offset!");
01743 
01744       PrimaryBaseOffset = Base.getBaseOffset();
01745       PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
01746     }
01747 
01748     AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
01749                PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, 
01750                FirstBaseOffsetInLayoutClass, PrimaryBases);
01751     
01752     if (!PrimaryBases.insert(PrimaryBase))
01753       assert(false && "Found a duplicate primary base!");
01754   }
01755 
01756   // Now go through all virtual member functions and add them.
01757   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
01758        E = RD->method_end(); I != E; ++I) {
01759     const CXXMethodDecl *MD = *I;
01760   
01761     if (!MD->isVirtual())
01762       continue;
01763 
01764     // Get the final overrider.
01765     FinalOverriders::OverriderInfo Overrider = 
01766       Overriders.getOverrider(Base, MD);
01767 
01768     // Check if this virtual member function overrides a method in a primary
01769     // base. If this is the case, and the return type doesn't require adjustment
01770     // then we can just use the member function from the primary base.
01771     if (const CXXMethodDecl *OverriddenMD = 
01772           FindNearestOverriddenMethod(MD, PrimaryBases)) {
01773       if (ComputeReturnAdjustmentBaseOffset(Context, MD, 
01774                                             OverriddenMD).isEmpty()) {
01775         // Replace the method info of the overridden method with our own
01776         // method.
01777         assert(MethodInfoMap.count(OverriddenMD) && 
01778                "Did not find the overridden method!");
01779         MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
01780         
01781         MethodInfo MethodInfo(Base.getBaseOffset(), 
01782                               BaseOffsetInLayoutClass,
01783                               OverriddenMethodInfo.VTableIndex);
01784 
01785         assert(!MethodInfoMap.count(MD) &&
01786                "Should not have method info for this method yet!");
01787         
01788         MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
01789         MethodInfoMap.erase(OverriddenMD);
01790         
01791         // If the overridden method exists in a virtual base class or a direct
01792         // or indirect base class of a virtual base class, we need to emit a
01793         // thunk if we ever have a class hierarchy where the base class is not
01794         // a primary base in the complete object.
01795         if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
01796           // Compute the this adjustment.
01797           ThisAdjustment ThisAdjustment =
01798             ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
01799                                   Overrider);
01800 
01801           if (ThisAdjustment.VCallOffsetOffset &&
01802               Overrider.Method->getParent() == MostDerivedClass) {
01803             // This is a virtual thunk for the most derived class, add it.
01804             AddThunk(Overrider.Method, 
01805                      ThunkInfo(ThisAdjustment, ReturnAdjustment()));
01806           }
01807         }
01808 
01809         continue;
01810       }
01811     }
01812 
01813     // Insert the method info for this method.
01814     MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
01815                           Components.size());
01816 
01817     assert(!MethodInfoMap.count(MD) &&
01818            "Should not have method info for this method yet!");
01819     MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
01820 
01821     // Check if this overrider is going to be used.
01822     const CXXMethodDecl *OverriderMD = Overrider.Method;
01823     if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
01824                          FirstBaseInPrimaryBaseChain, 
01825                          FirstBaseOffsetInLayoutClass)) {
01826       Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
01827       continue;
01828     }
01829     
01830     // Check if this overrider needs a return adjustment.
01831     BaseOffset ReturnAdjustmentOffset = 
01832       Overriders.getReturnAdjustmentOffset(Base, MD);
01833 
01834     ReturnAdjustment ReturnAdjustment = 
01835       ComputeReturnAdjustment(ReturnAdjustmentOffset);
01836     
01837     AddMethod(Overrider.Method, ReturnAdjustment);
01838   }
01839 }
01840 
01841 void VTableBuilder::LayoutVTable() {
01842   LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass, 0),
01843                                    /*BaseIsMorallyVirtual=*/false,
01844                                    MostDerivedClassIsVirtual,
01845                                    MostDerivedClassOffset);
01846   
01847   VisitedVirtualBasesSetTy VBases;
01848   
01849   // Determine the primary virtual bases.
01850   DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
01851                                VBases);
01852   VBases.clear();
01853   
01854   LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
01855 }
01856   
01857 void
01858 VTableBuilder::LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
01859                                                 bool BaseIsMorallyVirtual,
01860                                                 bool BaseIsVirtualInLayoutClass,
01861                                                 uint64_t OffsetInLayoutClass) {
01862   assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
01863 
01864   // Add vcall and vbase offsets for this vtable.
01865   VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
01866                                      Base, BaseIsVirtualInLayoutClass, 
01867                                      OffsetInLayoutClass);
01868   Components.append(Builder.components_begin(), Builder.components_end());
01869   
01870   // Check if we need to add these vcall offsets.
01871   if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
01872     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
01873     
01874     if (VCallOffsets.empty())
01875       VCallOffsets = Builder.getVCallOffsets();
01876   }
01877 
01878   // If we're laying out the most derived class we want to keep track of the
01879   // virtual base class offset offsets.
01880   if (Base.getBase() == MostDerivedClass)
01881     VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
01882 
01883   // Add the offset to top.
01884   // FIXME: We should not use / 8 here.
01885   int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
01886                                    MostDerivedClassOffset) / 8;
01887   Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
01888   
01889   // Next, add the RTTI.
01890   Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
01891   
01892   uint64_t AddressPoint = Components.size();
01893 
01894   // Now go through all virtual member functions and add them.
01895   PrimaryBasesSetVectorTy PrimaryBases;
01896   AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass, 
01897              PrimaryBases);
01898 
01899   // Compute 'this' pointer adjustments.
01900   ComputeThisAdjustments();
01901 
01902   // Add all address points.
01903   const CXXRecordDecl *RD = Base.getBase();
01904   while (true) {
01905     AddressPoints.insert(std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
01906                                         AddressPoint));
01907 
01908     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01909     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
01910     
01911     if (!PrimaryBase)
01912       break;
01913     
01914     if (Layout.getPrimaryBaseWasVirtual()) {
01915       // Check if this virtual primary base is a primary base in the layout
01916       // class. If it's not, we don't want to add it.
01917       const ASTRecordLayout &LayoutClassLayout =
01918         Context.getASTRecordLayout(LayoutClass);
01919 
01920       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
01921           OffsetInLayoutClass) {
01922         // We don't want to add this class (or any of its primary bases).
01923         break;
01924       }
01925     }
01926 
01927     RD = PrimaryBase;
01928   }
01929 
01930   // Layout secondary vtables.
01931   LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
01932 }
01933 
01934 void VTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
01935                                            bool BaseIsMorallyVirtual,
01936                                            uint64_t OffsetInLayoutClass) {
01937   // Itanium C++ ABI 2.5.2:
01938   //   Following the primary virtual table of a derived class are secondary 
01939   //   virtual tables for each of its proper base classes, except any primary
01940   //   base(s) with which it shares its primary virtual table.
01941 
01942   const CXXRecordDecl *RD = Base.getBase();
01943   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01944   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
01945   
01946   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01947        E = RD->bases_end(); I != E; ++I) {
01948     // Ignore virtual bases, we'll emit them later.
01949     if (I->isVirtual())
01950       continue;
01951     
01952     const CXXRecordDecl *BaseDecl = 
01953       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01954 
01955     // Ignore bases that don't have a vtable.
01956     if (!BaseDecl->isDynamicClass())
01957       continue;
01958 
01959     if (isBuildingConstructorVTable()) {
01960       // Itanium C++ ABI 2.6.4:
01961       //   Some of the base class subobjects may not need construction virtual
01962       //   tables, which will therefore not be present in the construction
01963       //   virtual table group, even though the subobject virtual tables are
01964       //   present in the main virtual table group for the complete object.
01965       if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
01966         continue;
01967     }
01968 
01969     // Get the base offset of this base.
01970     uint64_t RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
01971     uint64_t BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
01972     
01973     uint64_t BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset;
01974     
01975     // Don't emit a secondary vtable for a primary base. We might however want 
01976     // to emit secondary vtables for other bases of this base.
01977     if (BaseDecl == PrimaryBase) {
01978       LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
01979                              BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
01980       continue;
01981     }
01982 
01983     // Layout the primary vtable (and any secondary vtables) for this base.
01984     LayoutPrimaryAndSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
01985                                      BaseIsMorallyVirtual,
01986                                      /*BaseIsVirtualInLayoutClass=*/false,
01987                                      BaseOffsetInLayoutClass);
01988   }
01989 }
01990 
01991 void
01992 VTableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
01993                                             uint64_t OffsetInLayoutClass,
01994                                             VisitedVirtualBasesSetTy &VBases) {
01995   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01996   
01997   // Check if this base has a primary base.
01998   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
01999 
02000     // Check if it's virtual.
02001     if (Layout.getPrimaryBaseWasVirtual()) {
02002       bool IsPrimaryVirtualBase = true;
02003 
02004       if (isBuildingConstructorVTable()) {
02005         // Check if the base is actually a primary base in the class we use for
02006         // layout.
02007         const ASTRecordLayout &LayoutClassLayout =
02008           Context.getASTRecordLayout(LayoutClass);
02009 
02010         uint64_t PrimaryBaseOffsetInLayoutClass =
02011           LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
02012         
02013         // We know that the base is not a primary base in the layout class if 
02014         // the base offsets are different.
02015         if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
02016           IsPrimaryVirtualBase = false;
02017       }
02018         
02019       if (IsPrimaryVirtualBase)
02020         PrimaryVirtualBases.insert(PrimaryBase);
02021     }
02022   }
02023 
02024   // Traverse bases, looking for more primary virtual bases.
02025   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
02026        E = RD->bases_end(); I != E; ++I) {
02027     const CXXRecordDecl *BaseDecl = 
02028       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
02029 
02030     uint64_t BaseOffsetInLayoutClass;
02031     
02032     if (I->isVirtual()) {
02033       if (!VBases.insert(BaseDecl))
02034         continue;
02035       
02036       const ASTRecordLayout &LayoutClassLayout =
02037         Context.getASTRecordLayout(LayoutClass);
02038 
02039       BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl);
02040     } else {
02041       BaseOffsetInLayoutClass = 
02042         OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
02043     }
02044 
02045     DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
02046   }
02047 }
02048 
02049 void
02050 VTableBuilder::LayoutVTablesForVirtualBases(const CXXRecordDecl *RD, 
02051                                             VisitedVirtualBasesSetTy &VBases) {
02052   // Itanium C++ ABI 2.5.2:
02053   //   Then come the virtual base virtual tables, also in inheritance graph
02054   //   order, and again excluding primary bases (which share virtual tables with
02055   //   the classes for which they are primary).
02056   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
02057        E = RD->bases_end(); I != E; ++I) {
02058     const CXXRecordDecl *BaseDecl = 
02059       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
02060 
02061     // Check if this base needs a vtable. (If it's virtual, not a primary base
02062     // of some other class, and we haven't visited it before).
02063     if (I->isVirtual() && BaseDecl->isDynamicClass() && 
02064         !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
02065       const ASTRecordLayout &MostDerivedClassLayout =
02066         Context.getASTRecordLayout(MostDerivedClass);
02067       uint64_t BaseOffset = 
02068         MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
02069       
02070       const ASTRecordLayout &LayoutClassLayout =
02071         Context.getASTRecordLayout(LayoutClass);
02072       uint64_t BaseOffsetInLayoutClass = 
02073         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
02074 
02075       LayoutPrimaryAndSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
02076                                        /*BaseIsMorallyVirtual=*/true,
02077                                        /*BaseIsVirtualInLayoutClass=*/true,
02078                                        BaseOffsetInLayoutClass);
02079     }
02080     
02081     // We only need to check the base for virtual base vtables if it actually
02082     // has virtual bases.
02083     if (BaseDecl->getNumVBases())
02084       LayoutVTablesForVirtualBases(BaseDecl, VBases);
02085   }
02086 }
02087 
02088 /// dumpLayout - Dump the vtable layout.
02089 void VTableBuilder::dumpLayout(llvm::raw_ostream& Out) {
02090 
02091   if (isBuildingConstructorVTable()) {
02092     Out << "Construction vtable for ('";
02093     Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
02094     // FIXME: Don't use / 8 .
02095     Out << MostDerivedClassOffset / 8 << ") in '";
02096     Out << LayoutClass->getQualifiedNameAsString();
02097   } else {
02098     Out << "Vtable for '";
02099     Out << MostDerivedClass->getQualifiedNameAsString();
02100   }
02101   Out << "' (" << Components.size() << " entries).\n";
02102 
02103   // Iterate through the address points and insert them into a new map where
02104   // they are keyed by the index and not the base object.
02105   // Since an address point can be shared by multiple subobjects, we use an
02106   // STL multimap.
02107   std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
02108   for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(), 
02109        E = AddressPoints.end(); I != E; ++I) {
02110     const BaseSubobject& Base = I->first;
02111     uint64_t Index = I->second;
02112     
02113     AddressPointsByIndex.insert(std::make_pair(Index, Base));
02114   }
02115   
02116   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
02117     uint64_t Index = I;
02118 
02119     Out << llvm::format("%4d | ", I);
02120 
02121     const VTableComponent &Component = Components[I];
02122 
02123     // Dump the component.
02124     switch (Component.getKind()) {
02125 
02126     case VTableComponent::CK_VCallOffset:
02127       Out << "vcall_offset (" << Component.getVCallOffset() << ")";
02128       break;
02129 
02130     case VTableComponent::CK_VBaseOffset:
02131       Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
02132       break;
02133 
02134     case VTableComponent::CK_OffsetToTop:
02135       Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
02136       break;
02137     
02138     case VTableComponent::CK_RTTI:
02139       Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
02140       break;
02141     
02142     case VTableComponent::CK_FunctionPointer: {
02143       const CXXMethodDecl *MD = Component.getFunctionDecl();
02144 
02145       std::string Str = 
02146         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 
02147                                     MD);
02148       Out << Str;
02149       if (MD->isPure())
02150         Out << " [pure]";
02151 
02152       ThunkInfo Thunk = VTableThunks.lookup(I);
02153       if (!Thunk.isEmpty()) {
02154         // If this function pointer has a return adjustment, dump it.
02155         if (!Thunk.Return.isEmpty()) {
02156           Out << "\n       [return adjustment: ";
02157           Out << Thunk.Return.NonVirtual << " non-virtual";
02158           
02159           if (Thunk.Return.VBaseOffsetOffset) {
02160             Out << ", " << Thunk.Return.VBaseOffsetOffset;
02161             Out << " vbase offset offset";
02162           }
02163 
02164           Out << ']';
02165         }
02166 
02167         // If this function pointer has a 'this' pointer adjustment, dump it.
02168         if (!Thunk.This.isEmpty()) {
02169           Out << "\n       [this adjustment: ";
02170           Out << Thunk.This.NonVirtual << " non-virtual";
02171           
02172           if (Thunk.This.VCallOffsetOffset) {
02173             Out << ", " << Thunk.This.VCallOffsetOffset;
02174             Out << " vcall offset offset";
02175           }
02176 
02177           Out << ']';
02178         }          
02179       }
02180 
02181       break;
02182     }
02183 
02184     case VTableComponent::CK_CompleteDtorPointer: 
02185     case VTableComponent::CK_DeletingDtorPointer: {
02186       bool IsComplete = 
02187         Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
02188       
02189       const CXXDestructorDecl *DD = Component.getDestructorDecl();
02190       
02191       Out << DD->getQualifiedNameAsString();
02192       if (IsComplete)
02193         Out << "() [complete]";
02194       else
02195         Out << "() [deleting]";
02196 
02197       if (DD->isPure())
02198         Out << " [pure]";
02199 
02200       ThunkInfo Thunk = VTableThunks.lookup(I);
02201       if (!Thunk.isEmpty()) {
02202         // If this destructor has a 'this' pointer adjustment, dump it.
02203         if (!Thunk.This.isEmpty()) {
02204           Out << "\n       [this adjustment: ";
02205           Out << Thunk.This.NonVirtual << " non-virtual";
02206           
02207           if (Thunk.This.VCallOffsetOffset) {
02208             Out << ", " << Thunk.This.VCallOffsetOffset;
02209             Out << " vcall offset offset";
02210           }
02211           
02212           Out << ']';
02213         }          
02214       }        
02215 
02216       break;
02217     }
02218 
02219     case VTableComponent::CK_UnusedFunctionPointer: {
02220       const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
02221 
02222       std::string Str = 
02223         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 
02224                                     MD);
02225       Out << "[unused] " << Str;
02226       if (MD->isPure())
02227         Out << " [pure]";
02228     }
02229 
02230     }
02231 
02232     Out << '\n';
02233     
02234     // Dump the next address point.
02235     uint64_t NextIndex = Index + 1;
02236     if (AddressPointsByIndex.count(NextIndex)) {
02237       if (AddressPointsByIndex.count(NextIndex) == 1) {
02238         const BaseSubobject &Base = 
02239           AddressPointsByIndex.find(NextIndex)->second;
02240         
02241         // FIXME: Instead of dividing by 8, we should be using CharUnits.
02242         Out << "       -- (" << Base.getBase()->getQualifiedNameAsString();
02243         Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
02244       } else {
02245         uint64_t BaseOffset = 
02246           AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
02247         
02248         // We store the class names in a set to get a stable order.
02249         std::set<std::string> ClassNames;
02250         for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
02251              AddressPointsByIndex.lower_bound(NextIndex), E =
02252              AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
02253           assert(I->second.getBaseOffset() == BaseOffset &&
02254                  "Invalid base offset!");
02255           const CXXRecordDecl *RD = I->second.getBase();
02256           ClassNames.insert(RD->getQualifiedNameAsString());
02257         }
02258         
02259         for (std::set<std::string>::const_iterator I = ClassNames.begin(),
02260              E = ClassNames.end(); I != E; ++I) {
02261           // FIXME: Instead of dividing by 8, we should be using CharUnits.
02262           Out << "       -- (" << *I;
02263           Out << ", " << BaseOffset / 8 << ") vtable address --\n";
02264         }
02265       }
02266     }
02267   }
02268 
02269   Out << '\n';
02270   
02271   if (isBuildingConstructorVTable())
02272     return;
02273   
02274   if (MostDerivedClass->getNumVBases()) {
02275     // We store the virtual base class names and their offsets in a map to get
02276     // a stable order.
02277 
02278     std::map<std::string, int64_t> ClassNamesAndOffsets;
02279     for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
02280          E = VBaseOffsetOffsets.end(); I != E; ++I) {
02281       std::string ClassName = I->first->getQualifiedNameAsString();
02282       int64_t OffsetOffset = I->second;
02283       ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
02284     }
02285     
02286     Out << "Virtual base offset offsets for '";
02287     Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
02288     Out << ClassNamesAndOffsets.size();
02289     Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
02290 
02291     for (std::map<std::string, int64_t>::const_iterator I =
02292          ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end(); 
02293          I != E; ++I)
02294       Out << "   " << I->first << " | " << I->second << '\n';
02295 
02296     Out << "\n";
02297   }
02298   
02299   if (!Thunks.empty()) {
02300     // We store the method names in a map to get a stable order.
02301     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
02302     
02303     for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
02304          I != E; ++I) {
02305       const CXXMethodDecl *MD = I->first;
02306       std::string MethodName = 
02307         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
02308                                     MD);
02309       
02310       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
02311     }
02312 
02313     for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
02314          MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end(); 
02315          I != E; ++I) {
02316       const std::string &MethodName = I->first;
02317       const CXXMethodDecl *MD = I->second;
02318 
02319       ThunkInfoVectorTy ThunksVector = Thunks[MD];
02320       std::sort(ThunksVector.begin(), ThunksVector.end());
02321 
02322       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
02323       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
02324       
02325       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
02326         const ThunkInfo &Thunk = ThunksVector[I];
02327 
02328         Out << llvm::format("%4d | ", I);
02329         
02330         // If this function pointer has a return pointer adjustment, dump it.
02331         if (!Thunk.Return.isEmpty()) {
02332           Out << "return adjustment: " << Thunk.This.NonVirtual;
02333           Out << " non-virtual";
02334           if (Thunk.Return.VBaseOffsetOffset) {
02335             Out << ", " << Thunk.Return.VBaseOffsetOffset;
02336             Out << " vbase offset offset";
02337           }
02338 
02339           if (!Thunk.This.isEmpty())
02340             Out << "\n       ";
02341         }
02342 
02343         // If this function pointer has a 'this' pointer adjustment, dump it.
02344         if (!Thunk.This.isEmpty()) {
02345           Out << "this adjustment: ";
02346           Out << Thunk.This.NonVirtual << " non-virtual";
02347           
02348           if (Thunk.This.VCallOffsetOffset) {
02349             Out << ", " << Thunk.This.VCallOffsetOffset;
02350             Out << " vcall offset offset";
02351           }
02352         }
02353         
02354         Out << '\n';
02355       }
02356       
02357       Out << '\n';
02358 
02359     }
02360   }
02361 }
02362   
02363 }
02364 
02365 void CodeGenVTables::ComputeMethodVTableIndices(const CXXRecordDecl *RD) {
02366   
02367   // Itanium C++ ABI 2.5.2:
02368   //   The order of the virtual function pointers in a virtual table is the 
02369   //   order of declaration of the corresponding member functions in the class.
02370   //
02371   //   There is an entry for any virtual function declared in a class, 
02372   //   whether it is a new function or overrides a base class function, 
02373   //   unless it overrides a function from the primary base, and conversion
02374   //   between their return types does not require an adjustment. 
02375 
02376   int64_t CurrentIndex = 0;
02377   
02378   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
02379   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
02380   
02381   if (PrimaryBase) {
02382     assert(PrimaryBase->isDefinition() && 
02383            "Should have the definition decl of the primary base!");
02384 
02385     // Since the record decl shares its vtable pointer with the primary base
02386     // we need to start counting at the end of the primary base's vtable.
02387     CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
02388   }
02389 
02390   // Collect all the primary bases, so we can check whether methods override
02391   // a method from the base.
02392   VTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
02393   for (ASTRecordLayout::primary_base_info_iterator
02394        I = Layout.primary_base_begin(), E = Layout.primary_base_end();
02395        I != E; ++I)
02396     PrimaryBases.insert((*I).getBase());
02397 
02398   const CXXDestructorDecl *ImplicitVirtualDtor = 0;
02399   
02400   for (CXXRecordDecl::method_iterator i = RD->method_begin(),
02401        e = RD->method_end(); i != e; ++i) {
02402     const CXXMethodDecl *MD = *i;
02403 
02404     // We only want virtual methods.
02405     if (!MD->isVirtual())
02406       continue;
02407 
02408     // Check if this method overrides a method in the primary base.
02409     if (const CXXMethodDecl *OverriddenMD = 
02410           FindNearestOverriddenMethod(MD, PrimaryBases)) {
02411       // Check if converting from the return type of the method to the 
02412       // return type of the overridden method requires conversion.
02413       if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD, 
02414                                             OverriddenMD).isEmpty()) {
02415         // This index is shared between the index in the vtable of the primary
02416         // base class.
02417         if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
02418           const CXXDestructorDecl *OverriddenDD = 
02419             cast<CXXDestructorDecl>(OverriddenMD);
02420           
02421           // Add both the complete and deleting entries.
02422           MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = 
02423             getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
02424           MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = 
02425             getMethodVTableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
02426         } else {
02427           MethodVTableIndices[MD] = getMethodVTableIndex(OverriddenMD);
02428         }
02429         
02430         // We don't need to add an entry for this method.
02431         continue;
02432       }
02433     }
02434     
02435     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
02436       if (MD->isImplicit()) {
02437         assert(!ImplicitVirtualDtor && 
02438                "Did already see an implicit virtual dtor!");
02439         ImplicitVirtualDtor = DD;
02440         continue;
02441       } 
02442 
02443       // Add the complete dtor.
02444       MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
02445       
02446       // Add the deleting dtor.
02447       MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
02448     } else {
02449       // Add the entry.
02450       MethodVTableIndices[MD] = CurrentIndex++;
02451     }
02452   }
02453 
02454   if (ImplicitVirtualDtor) {
02455     // Itanium C++ ABI 2.5.2:
02456     //   If a class has an implicitly-defined virtual destructor, 
02457     //   its entries come after the declared virtual function pointers.
02458 
02459     // Add the complete dtor.
02460     MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] = 
02461       CurrentIndex++;
02462     
02463     // Add the deleting dtor.
02464     MethodVTableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] = 
02465       CurrentIndex++;
02466   }
02467   
02468   NumVirtualFunctionPointers[RD] = CurrentIndex;
02469 }
02470 
02471 uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
02472   llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I = 
02473     NumVirtualFunctionPointers.find(RD);
02474   if (I != NumVirtualFunctionPointers.end())
02475     return I->second;
02476 
02477   ComputeMethodVTableIndices(RD);
02478 
02479   I = NumVirtualFunctionPointers.find(RD);
02480   assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
02481   return I->second;
02482 }
02483       
02484 uint64_t CodeGenVTables::getMethodVTableIndex(GlobalDecl GD) {
02485   MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
02486   if (I != MethodVTableIndices.end())
02487     return I->second;
02488   
02489   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
02490 
02491   ComputeMethodVTableIndices(RD);
02492 
02493   I = MethodVTableIndices.find(GD);
02494   assert(I != MethodVTableIndices.end() && "Did not find index!");
02495   return I->second;
02496 }
02497 
02498 int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, 
02499                                                    const CXXRecordDecl *VBase) {
02500   ClassPairTy ClassPair(RD, VBase);
02501   
02502   VirtualBaseClassOffsetOffsetsMapTy::iterator I = 
02503     VirtualBaseClassOffsetOffsets.find(ClassPair);
02504   if (I != VirtualBaseClassOffsetOffsets.end())
02505     return I->second;
02506   
02507   VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
02508                                      BaseSubobject(RD, 0),                                           
02509                                      /*BaseIsVirtual=*/false,
02510                                      /*OffsetInLayoutClass=*/0);
02511 
02512   for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
02513        Builder.getVBaseOffsetOffsets().begin(), 
02514        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
02515     // Insert all types.
02516     ClassPairTy ClassPair(RD, I->first);
02517     
02518     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
02519   }
02520   
02521   I = VirtualBaseClassOffsetOffsets.find(ClassPair);
02522   assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
02523   
02524   return I->second;
02525 }
02526 
02527 uint64_t
02528 CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
02529   assert(AddressPoints.count(std::make_pair(RD, Base)) &&
02530          "Did not find address point!");
02531 
02532   uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
02533   assert(AddressPoint && "Address point must not be zero!");
02534 
02535   return AddressPoint;
02536 }
02537 
02538 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD, 
02539                                               const ThunkInfo &Thunk) {
02540   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02541 
02542   // Compute the mangled name.
02543   llvm::SmallString<256> Name;
02544   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
02545     getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), Thunk.This,
02546                                           Name);
02547   else
02548     getMangleContext().mangleThunk(MD, Thunk, Name);
02549   
02550   const llvm::Type *Ty = getTypes().GetFunctionTypeForVTable(MD);
02551   return GetOrCreateLLVMFunction(Name, Ty, GD);
02552 }
02553 
02554 static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
02555                                           llvm::Value *Ptr,
02556                                           int64_t NonVirtualAdjustment,
02557                                           int64_t VirtualAdjustment) {
02558   if (!NonVirtualAdjustment && !VirtualAdjustment)
02559     return Ptr;
02560 
02561   const llvm::Type *Int8PtrTy = 
02562     llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
02563   
02564   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
02565 
02566   if (NonVirtualAdjustment) {
02567     // Do the non-virtual adjustment.
02568     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
02569   }
02570 
02571   if (VirtualAdjustment) {
02572     const llvm::Type *PtrDiffTy = 
02573       CGF.ConvertType(CGF.getContext().getPointerDiffType());
02574 
02575     // Do the virtual adjustment.
02576     llvm::Value *VTablePtrPtr = 
02577       CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
02578     
02579     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
02580   
02581     llvm::Value *OffsetPtr =
02582       CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
02583     
02584     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
02585     
02586     // Load the adjustment offset from the vtable.
02587     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
02588     
02589     // Adjust our pointer.
02590     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
02591   }
02592 
02593   // Cast back to the original type.
02594   return CGF.Builder.CreateBitCast(V, Ptr->getType());
02595 }
02596 
02597 void CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
02598                                     const ThunkInfo &Thunk) {
02599   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02600   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
02601   QualType ResultType = FPT->getResultType();
02602   QualType ThisType = MD->getThisType(getContext());
02603 
02604   FunctionArgList FunctionArgs;
02605 
02606   // FIXME: It would be nice if more of this code could be shared with 
02607   // CodeGenFunction::GenerateCode.
02608 
02609   // Create the implicit 'this' parameter declaration.
02610   CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
02611                                           MD->getLocation(),
02612                                           &getContext().Idents.get("this"),
02613                                           ThisType);
02614 
02615   // Add the 'this' parameter.
02616   FunctionArgs.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
02617 
02618   // Add the rest of the parameters.
02619   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
02620        E = MD->param_end(); I != E; ++I) {
02621     ParmVarDecl *Param = *I;
02622     
02623     FunctionArgs.push_back(std::make_pair(Param, Param->getType()));
02624   }
02625   
02626   StartFunction(GlobalDecl(), ResultType, Fn, FunctionArgs, SourceLocation());
02627 
02628   // Adjust the 'this' pointer if necessary.
02629   llvm::Value *AdjustedThisPtr = 
02630     PerformTypeAdjustment(*this, LoadCXXThis(), 
02631                           Thunk.This.NonVirtual, 
02632                           Thunk.This.VCallOffsetOffset);
02633   
02634   CallArgList CallArgs;
02635   
02636   // Add our adjusted 'this' pointer.
02637   CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
02638 
02639   // Add the rest of the parameters.
02640   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
02641        E = MD->param_end(); I != E; ++I) {
02642     ParmVarDecl *Param = *I;
02643     QualType ArgType = Param->getType();
02644     
02645     // FIXME: Declaring a DeclRefExpr on the stack is kinda icky.
02646     DeclRefExpr ArgExpr(Param, ArgType.getNonReferenceType(), SourceLocation());
02647     CallArgs.push_back(std::make_pair(EmitCallArg(&ArgExpr, ArgType), ArgType));
02648   }
02649 
02650   // Get our callee.
02651   const llvm::Type *Ty =
02652     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
02653                                    FPT->isVariadic());
02654   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
02655 
02656   const CGFunctionInfo &FnInfo = 
02657     CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
02658                                    FPT->getExtInfo());
02659   
02660   // Now emit our call.
02661   RValue RV = EmitCall(FnInfo, Callee, ReturnValueSlot(), CallArgs, MD);
02662   
02663   if (!Thunk.Return.isEmpty()) {
02664     // Emit the return adjustment.
02665     bool NullCheckValue = !ResultType->isReferenceType();
02666     
02667     llvm::BasicBlock *AdjustNull = 0;
02668     llvm::BasicBlock *AdjustNotNull = 0;
02669     llvm::BasicBlock *AdjustEnd = 0;
02670     
02671     llvm::Value *ReturnValue = RV.getScalarVal();
02672 
02673     if (NullCheckValue) {
02674       AdjustNull = createBasicBlock("adjust.null");
02675       AdjustNotNull = createBasicBlock("adjust.notnull");
02676       AdjustEnd = createBasicBlock("adjust.end");
02677     
02678       llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
02679       Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
02680       EmitBlock(AdjustNotNull);
02681     }
02682     
02683     ReturnValue = PerformTypeAdjustment(*this, ReturnValue, 
02684                                         Thunk.Return.NonVirtual, 
02685                                         Thunk.Return.VBaseOffsetOffset);
02686     
02687     if (NullCheckValue) {
02688       Builder.CreateBr(AdjustEnd);
02689       EmitBlock(AdjustNull);
02690       Builder.CreateBr(AdjustEnd);
02691       EmitBlock(AdjustEnd);
02692     
02693       llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType());
02694       PHI->reserveOperandSpace(2);
02695       PHI->addIncoming(ReturnValue, AdjustNotNull);
02696       PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()), 
02697                        AdjustNull);
02698       ReturnValue = PHI;
02699     }
02700     
02701     RV = RValue::get(ReturnValue);
02702   }
02703 
02704   if (!ResultType->isVoidType())
02705     EmitReturnOfRValue(RV, ResultType);
02706 
02707   FinishFunction();
02708 
02709   // Destroy the 'this' declaration.
02710   CXXThisDecl->Destroy(getContext());
02711   
02712   // Set the right linkage.
02713   Fn->setLinkage(CGM.getFunctionLinkage(MD));
02714   
02715   // Set the right visibility.
02716   CGM.setGlobalVisibility(Fn, MD);
02717 }
02718 
02719 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk)
02720 {
02721   llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
02722   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02723   
02724   // Strip off a bitcast if we got one back.
02725   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
02726     assert(CE->getOpcode() == llvm::Instruction::BitCast);
02727     Entry = CE->getOperand(0);
02728   }
02729   
02730   // There's already a declaration with the same name, check if it has the same
02731   // type or if we need to replace it.
02732   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != 
02733       CGM.getTypes().GetFunctionTypeForVTable(MD)) {
02734     llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
02735     
02736     // If the types mismatch then we have to rewrite the definition.
02737     assert(OldThunkFn->isDeclaration() &&
02738            "Shouldn't replace non-declaration");
02739 
02740     // Remove the name from the old thunk function and get a new thunk.
02741     OldThunkFn->setName(llvm::StringRef());
02742     Entry = CGM.GetAddrOfThunk(GD, Thunk);
02743     
02744     // If needed, replace the old thunk with a bitcast.
02745     if (!OldThunkFn->use_empty()) {
02746       llvm::Constant *NewPtrForOldDecl =
02747         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
02748       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
02749     }
02750     
02751     // Remove the old thunk.
02752     OldThunkFn->eraseFromParent();
02753   }
02754 
02755   // Actually generate the thunk body.
02756   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
02757   CodeGenFunction(CGM).GenerateThunk(ThunkFn, GD, Thunk);
02758 }
02759 
02760 void CodeGenVTables::EmitThunks(GlobalDecl GD)
02761 {
02762   const CXXMethodDecl *MD = 
02763     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
02764 
02765   // We don't need to generate thunks for the base destructor.
02766   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
02767     return;
02768 
02769   const CXXRecordDecl *RD = MD->getParent();
02770   
02771   // Compute VTable related info for this class.
02772   ComputeVTableRelatedInformation(RD);
02773   
02774   ThunksMapTy::const_iterator I = Thunks.find(MD);
02775   if (I == Thunks.end()) {
02776     // We did not find a thunk for this method.
02777     return;
02778   }
02779 
02780   const ThunkInfoVectorTy &ThunkInfoVector = I->second;
02781   for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
02782     EmitThunk(GD, ThunkInfoVector[I]);
02783 }
02784 
02785 void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
02786   uint64_t *&LayoutData = VTableLayoutMap[RD];
02787   
02788   // Check if we've computed this information before.
02789   if (LayoutData)
02790     return;
02791       
02792   VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
02793 
02794   // Add the VTable layout.
02795   uint64_t NumVTableComponents = Builder.getNumVTableComponents();
02796   LayoutData = new uint64_t[NumVTableComponents + 1];
02797 
02798   // Store the number of components.
02799   LayoutData[0] = NumVTableComponents;
02800 
02801   // Store the components.
02802   std::copy(Builder.vtable_components_data_begin(),
02803             Builder.vtable_components_data_end(),
02804             &LayoutData[1]);
02805 
02806   // Add the known thunks.
02807   Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
02808   
02809   // Add the thunks needed in this vtable.
02810   assert(!VTableThunksMap.count(RD) && 
02811          "Thunks already exists for this vtable!");
02812 
02813   VTableThunksTy &VTableThunks = VTableThunksMap[RD];
02814   VTableThunks.append(Builder.vtable_thunks_begin(),
02815                       Builder.vtable_thunks_end());
02816   
02817   // Sort them.
02818   std::sort(VTableThunks.begin(), VTableThunks.end());
02819   
02820   // Add the address points.
02821   for (VTableBuilder::AddressPointsMapTy::const_iterator I =
02822        Builder.address_points_begin(), E = Builder.address_points_end();
02823        I != E; ++I) {
02824     
02825     uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
02826     
02827     // Check if we already have the address points for this base.
02828     assert(!AddressPoint && "Address point already exists for this base!");
02829     
02830     AddressPoint = I->second;
02831   }
02832   
02833   // If we don't have the vbase information for this class, insert it.
02834   // getVirtualBaseOffsetOffset will compute it separately without computing
02835   // the rest of the vtable related information.
02836   if (!RD->getNumVBases())
02837     return;
02838   
02839   const RecordType *VBaseRT = 
02840     RD->vbases_begin()->getType()->getAs<RecordType>();
02841   const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
02842   
02843   if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
02844     return;
02845   
02846   for (VTableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
02847        Builder.getVBaseOffsetOffsets().begin(), 
02848        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
02849     // Insert all types.
02850     ClassPairTy ClassPair(RD, I->first);
02851     
02852     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
02853   }
02854 }
02855 
02856 llvm::Constant *
02857 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
02858                                         const uint64_t *Components, 
02859                                         unsigned NumComponents,
02860                                         const VTableThunksTy &VTableThunks) {
02861   llvm::SmallVector<llvm::Constant *, 64> Inits;
02862 
02863   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
02864   
02865   const llvm::Type *PtrDiffTy = 
02866     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
02867 
02868   QualType ClassType = CGM.getContext().getTagDeclType(RD);
02869   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
02870   
02871   unsigned NextVTableThunkIndex = 0;
02872   
02873   llvm::Constant* PureVirtualFn = 0;
02874 
02875   for (unsigned I = 0; I != NumComponents; ++I) {
02876     VTableComponent Component = 
02877       VTableComponent::getFromOpaqueInteger(Components[I]);
02878 
02879     llvm::Constant *Init = 0;
02880 
02881     switch (Component.getKind()) {
02882     case VTableComponent::CK_VCallOffset:
02883       Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
02884       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
02885       break;
02886     case VTableComponent::CK_VBaseOffset:
02887       Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
02888       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
02889       break;
02890     case VTableComponent::CK_OffsetToTop:
02891       Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
02892       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
02893       break;
02894     case VTableComponent::CK_RTTI:
02895       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
02896       break;
02897     case VTableComponent::CK_FunctionPointer:
02898     case VTableComponent::CK_CompleteDtorPointer:
02899     case VTableComponent::CK_DeletingDtorPointer: {
02900       GlobalDecl GD;
02901       
02902       // Get the right global decl.
02903       switch (Component.getKind()) {
02904       default:
02905         llvm_unreachable("Unexpected vtable component kind");
02906       case VTableComponent::CK_FunctionPointer:
02907         GD = Component.getFunctionDecl();
02908         break;
02909       case VTableComponent::CK_CompleteDtorPointer:
02910         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
02911         break;
02912       case VTableComponent::CK_DeletingDtorPointer:
02913         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
02914         break;
02915       }
02916 
02917       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
02918         // We have a pure virtual member function.
02919         if (!PureVirtualFn) {
02920           const llvm::FunctionType *Ty = 
02921             llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 
02922                                     /*isVarArg=*/false);
02923           PureVirtualFn = 
02924             CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
02925           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn, 
02926                                                          Int8PtrTy);
02927         }
02928         
02929         Init = PureVirtualFn;
02930       } else {
02931         // Check if we should use a thunk.
02932         if (NextVTableThunkIndex < VTableThunks.size() &&
02933             VTableThunks[NextVTableThunkIndex].first == I) {
02934           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
02935         
02936           Init = CGM.GetAddrOfThunk(GD, Thunk);
02937         
02938           NextVTableThunkIndex++;
02939         } else {
02940           const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02941           const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVTable(MD);
02942         
02943           Init = CGM.GetAddrOfFunction(GD, Ty);
02944         }
02945 
02946         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
02947       }
02948       break;
02949     }
02950 
02951     case VTableComponent::CK_UnusedFunctionPointer:
02952       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
02953       break;
02954     };
02955     
02956     Inits.push_back(Init);
02957   }
02958   
02959   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
02960   return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
02961 }
02962 
02963 /// GetGlobalVariable - Will return a global variable of the given type. 
02964 /// If a variable with a different type already exists then a new variable
02965 /// with the right type will be created.
02966 /// FIXME: We should move this to CodeGenModule and rename it to something 
02967 /// better and then use it in CGVTT and CGRTTI. 
02968 static llvm::GlobalVariable *
02969 GetGlobalVariable(llvm::Module &Module, llvm::StringRef Name,
02970                   const llvm::Type *Ty,
02971                   llvm::GlobalValue::LinkageTypes Linkage) {
02972 
02973   llvm::GlobalVariable *GV = Module.getNamedGlobal(Name);
02974   llvm::GlobalVariable *OldGV = 0;
02975   
02976   if (GV) {
02977     // Check if the variable has the right type.
02978     if (GV->getType()->getElementType() == Ty)
02979       return GV;
02980 
02981     assert(GV->isDeclaration() && "Declaration has wrong type!");
02982     
02983     OldGV = GV;
02984   }
02985   
02986   // Create a new variable.
02987   GV = new llvm::GlobalVariable(Module, Ty, /*isConstant=*/true,
02988                                 Linkage, 0, Name);
02989   
02990   if (OldGV) {
02991     // Replace occurrences of the old variable if needed.
02992     GV->takeName(OldGV);
02993    
02994     if (!OldGV->use_empty()) {
02995       llvm::Constant *NewPtrForOldDecl =
02996         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
02997       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
02998     }
02999 
03000     OldGV->eraseFromParent();
03001   }
03002   
03003   return GV;
03004 }
03005 
03006 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
03007   llvm::SmallString<256> OutName;
03008   CGM.getMangleContext().mangleCXXVTable(RD, OutName);
03009   llvm::StringRef Name = OutName.str();
03010 
03011   ComputeVTableRelatedInformation(RD);
03012   
03013   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
03014   llvm::ArrayType *ArrayType = 
03015     llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
03016 
03017   return GetGlobalVariable(CGM.getModule(), Name, ArrayType, 
03018                            llvm::GlobalValue::ExternalLinkage);
03019 }
03020 
03021 void
03022 CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
03023                                      llvm::GlobalVariable::LinkageTypes Linkage,
03024                                      const CXXRecordDecl *RD) {
03025   // Dump the vtable layout if necessary.
03026   if (CGM.getLangOptions().DumpVTableLayouts) {
03027     VTableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
03028 
03029     Builder.dumpLayout(llvm::errs());
03030   }
03031 
03032   assert(VTableThunksMap.count(RD) && 
03033          "No thunk status for this record decl!");
03034   
03035   const VTableThunksTy& Thunks = VTableThunksMap[RD];
03036   
03037   // Create and set the initializer.
03038   llvm::Constant *Init = 
03039     CreateVTableInitializer(RD, getVTableComponentsData(RD),
03040                             getNumVTableComponents(RD), Thunks);
03041   VTable->setInitializer(Init);
03042   
03043   // Set the correct linkage.
03044   VTable->setLinkage(Linkage);
03045 }
03046 
03047 llvm::GlobalVariable *
03048 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD, 
03049                                       const BaseSubobject &Base, 
03050                                       bool BaseIsVirtual, 
03051                                       VTableAddressPointsMapTy& AddressPoints) {
03052   VTableBuilder Builder(*this, Base.getBase(), Base.getBaseOffset(), 
03053                         /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
03054 
03055   // Dump the vtable layout if necessary.
03056   if (CGM.getLangOptions().DumpVTableLayouts)
03057     Builder.dumpLayout(llvm::errs());
03058 
03059   // Add the address points.
03060   AddressPoints.insert(Builder.address_points_begin(),
03061                        Builder.address_points_end());
03062 
03063   // Get the mangled construction vtable name.
03064   llvm::SmallString<256> OutName;
03065   CGM.getMangleContext().mangleCXXCtorVTable(RD, Base.getBaseOffset() / 8, 
03066                                              Base.getBase(), OutName);
03067   llvm::StringRef Name = OutName.str();
03068 
03069   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
03070   llvm::ArrayType *ArrayType = 
03071     llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
03072 
03073   // Create the variable that will hold the construction vtable.
03074   llvm::GlobalVariable *VTable = 
03075     GetGlobalVariable(CGM.getModule(), Name, ArrayType, 
03076                       llvm::GlobalValue::InternalLinkage);
03077 
03078   // Add the thunks.
03079   VTableThunksTy VTableThunks;
03080   VTableThunks.append(Builder.vtable_thunks_begin(),
03081                       Builder.vtable_thunks_end());
03082 
03083   // Sort them.
03084   std::sort(VTableThunks.begin(), VTableThunks.end());
03085 
03086   // Create and set the initializer.
03087   llvm::Constant *Init = 
03088     CreateVTableInitializer(Base.getBase(), 
03089                             Builder.vtable_components_data_begin(), 
03090                             Builder.getNumVTableComponents(), VTableThunks);
03091   VTable->setInitializer(Init);
03092   
03093   return VTable;
03094 }
03095 
03096 void 
03097 CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
03098                                   const CXXRecordDecl *RD) {
03099   llvm::GlobalVariable *&VTable = VTables[RD];
03100   if (VTable) {
03101     assert(VTable->getInitializer() && "VTable doesn't have a definition!");
03102     return;
03103   }
03104 
03105   VTable = GetAddrOfVTable(RD);
03106   EmitVTableDefinition(VTable, Linkage, RD);
03107 
03108   GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
03109 
03110   // If this is the magic class __cxxabiv1::__fundamental_type_info,
03111   // we will emit the typeinfo for the fundamental types. This is the
03112   // same behaviour as GCC.
03113   const DeclContext *DC = RD->getDeclContext();
03114   if (RD->getIdentifier() &&
03115       RD->getIdentifier()->isStr("__fundamental_type_info") &&
03116       isa<NamespaceDecl>(DC) &&
03117       cast<NamespaceDecl>(DC)->getIdentifier() &&
03118       cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__cxxabiv1") &&
03119       DC->getParent()->isTranslationUnit())
03120     CGM.EmitFundamentalRTTIDescriptors();
03121 }
03122 
03123 void CodeGenVTables::EmitVTableRelatedData(GlobalDecl GD) {
03124   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
03125   const CXXRecordDecl *RD = MD->getParent();
03126 
03127   // If the class doesn't have a vtable we don't need to emit one.
03128   if (!RD->isDynamicClass())
03129     return;
03130   
03131   // Check if we need to emit thunks for this function.
03132   if (MD->isVirtual())
03133     EmitThunks(GD);
03134 
03135   // Get the key function.
03136   const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
03137   
03138   TemplateSpecializationKind RDKind = RD->getTemplateSpecializationKind();
03139   TemplateSpecializationKind MDKind = MD->getTemplateSpecializationKind();
03140 
03141   if (KeyFunction) {
03142     // We don't have the right key function.
03143     if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
03144       return;
03145   } else {
03146     // If we have no key funcion and this is a explicit instantiation declaration,
03147     // we will produce a vtable at the explicit instantiation. We don't need one
03148     // here.
03149     if (RDKind == clang::TSK_ExplicitInstantiationDeclaration)
03150       return;
03151 
03152     // If this is an explicit instantiation of a method, we don't need a vtable.
03153     // Since we have no key function, we will emit the vtable when we see
03154     // a use, and just defining a function is not an use.
03155     if (RDKind == TSK_ImplicitInstantiation &&
03156         MDKind == TSK_ExplicitInstantiationDefinition)
03157       return;
03158   }
03159 
03160   if (VTables.count(RD))
03161     return;
03162 
03163   if (RDKind == TSK_ImplicitInstantiation)
03164     CGM.DeferredVTables.push_back(RD);
03165   else
03166     GenerateClassData(CGM.getVTableLinkage(RD), RD);
03167 }