clang API Documentation

CGVtable.cpp

Go to the documentation of this file.
00001 //===--- CGVtable.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   if (PrimaryBase) {
00986     uint64_t PrimaryBaseOffset;
00987     
00988     // Get the base offset of the primary base.
00989     if (Layout.getPrimaryBaseWasVirtual()) {
00990       assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
00991              "Primary vbase should have a zero offset!");
00992       
00993       const ASTRecordLayout &MostDerivedClassLayout =
00994         Context.getASTRecordLayout(MostDerivedClass);
00995       
00996       PrimaryBaseOffset = 
00997         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
00998     } else {
00999       assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
01000              "Primary base should have a zero offset!");
01001 
01002       PrimaryBaseOffset = Base.getBaseOffset();
01003     }
01004     
01005     AddVCallOffsets(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
01006                     VBaseOffset);
01007   }
01008 
01009   // Add the vcall offsets.
01010   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
01011        E = RD->method_end(); I != E; ++I) {
01012     const CXXMethodDecl *MD = *I;
01013     
01014     if (!MD->isVirtual())
01015       continue;
01016 
01017     int64_t OffsetOffset = getCurrentOffsetOffset();
01018     
01019     // Don't add a vcall offset if we already have one for this member function
01020     // signature.
01021     if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
01022       continue;
01023 
01024     int64_t Offset = 0;
01025 
01026     if (Overriders) {
01027       // Get the final overrider.
01028       FinalOverriders::OverriderInfo Overrider = 
01029         Overriders->getOverrider(Base, MD);
01030       
01031       /// The vcall offset is the offset from the virtual base to the object 
01032       /// where the function was overridden.
01033       // FIXME: We should not use / 8 here.
01034       Offset = (int64_t)(Overrider.Offset - VBaseOffset) / 8;
01035     }
01036     
01037     Components.push_back(VtableComponent::MakeVCallOffset(Offset));
01038   }
01039 
01040   // And iterate over all non-virtual bases (ignoring the primary base).
01041   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01042        E = RD->bases_end(); I != E; ++I) {
01043   
01044     if (I->isVirtual())
01045       continue;
01046 
01047     const CXXRecordDecl *BaseDecl =
01048       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01049     if (BaseDecl == PrimaryBase)
01050       continue;
01051 
01052     // Get the base offset of this base.
01053     uint64_t BaseOffset = Base.getBaseOffset() + 
01054       Layout.getBaseClassOffset(BaseDecl);
01055     
01056     AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset), VBaseOffset);
01057   }
01058 }
01059 
01060 void VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
01061                                                  uint64_t OffsetInLayoutClass) {
01062   const ASTRecordLayout &LayoutClassLayout = 
01063     Context.getASTRecordLayout(LayoutClass);
01064 
01065   // Add vbase offsets.
01066   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01067        E = RD->bases_end(); I != E; ++I) {
01068     const CXXRecordDecl *BaseDecl =
01069       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01070 
01071     // Check if this is a virtual base that we haven't visited before.
01072     if (I->isVirtual() && VisitedVirtualBases.insert(BaseDecl)) {
01073       // FIXME: We shouldn't use / 8 here.
01074       int64_t Offset = 
01075         (int64_t)(LayoutClassLayout.getVBaseClassOffset(BaseDecl) - 
01076                   OffsetInLayoutClass) / 8;
01077 
01078       // Add the vbase offset offset.
01079       assert(!VBaseOffsetOffsets.count(BaseDecl) &&
01080              "vbase offset offset already exists!");
01081 
01082       int64_t VBaseOffsetOffset = getCurrentOffsetOffset();
01083       VBaseOffsetOffsets.insert(std::make_pair(BaseDecl, VBaseOffsetOffset));
01084 
01085       Components.push_back(VtableComponent::MakeVBaseOffset(Offset));
01086     }
01087 
01088     // Check the base class looking for more vbase offsets.
01089     AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
01090   }
01091 }
01092 
01093 /// VtableBuilder - Class for building vtable layout information.
01094 class VtableBuilder {
01095 public:
01096   /// PrimaryBasesSetVectorTy - A set vector of direct and indirect 
01097   /// primary bases.
01098   typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> 
01099     PrimaryBasesSetVectorTy;
01100   
01101   typedef llvm::DenseMap<const CXXRecordDecl *, int64_t> 
01102     VBaseOffsetOffsetsMapTy;
01103   
01104   typedef llvm::DenseMap<BaseSubobject, uint64_t> 
01105     AddressPointsMapTy;
01106 
01107 private:
01108   /// VTables - Global vtable information.
01109   CodeGenVTables &VTables;
01110   
01111   /// MostDerivedClass - The most derived class for which we're building this
01112   /// vtable.
01113   const CXXRecordDecl *MostDerivedClass;
01114 
01115   /// MostDerivedClassOffset - If we're building a construction vtable, this
01116   /// holds the offset from the layout class to the most derived class.
01117   const uint64_t MostDerivedClassOffset;
01118   
01119   /// MostDerivedClassIsVirtual - Whether the most derived class is a virtual 
01120   /// base. (This only makes sense when building a construction vtable).
01121   bool MostDerivedClassIsVirtual;
01122   
01123   /// LayoutClass - The class we're using for layout information. Will be 
01124   /// different than the most derived class if we're building a construction
01125   /// vtable.
01126   const CXXRecordDecl *LayoutClass;
01127   
01128   /// Context - The ASTContext which we will use for layout information.
01129   ASTContext &Context;
01130   
01131   /// FinalOverriders - The final overriders of the most derived class.
01132   const FinalOverriders Overriders;
01133 
01134   /// VCallOffsetsForVBases - Keeps track of vcall offsets for the virtual
01135   /// bases in this vtable.
01136   llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
01137 
01138   /// VBaseOffsetOffsets - Contains the offsets of the virtual base offsets for
01139   /// the most derived class.
01140   VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
01141   
01142   /// Components - The components of the vtable being built.
01143   llvm::SmallVector<VtableComponent, 64> Components;
01144 
01145   /// AddressPoints - Address points for the vtable being built.
01146   AddressPointsMapTy AddressPoints;
01147 
01148   /// MethodInfo - Contains information about a method in a vtable.
01149   /// (Used for computing 'this' pointer adjustment thunks.
01150   struct MethodInfo {
01151     /// BaseOffset - The base offset of this method.
01152     const uint64_t BaseOffset;
01153     
01154     /// BaseOffsetInLayoutClass - The base offset in the layout class of this
01155     /// method.
01156     const uint64_t BaseOffsetInLayoutClass;
01157     
01158     /// VtableIndex - The index in the vtable that this method has.
01159     /// (For destructors, this is the index of the complete destructor).
01160     const uint64_t VtableIndex;
01161     
01162     MethodInfo(uint64_t BaseOffset, uint64_t BaseOffsetInLayoutClass, 
01163                uint64_t VtableIndex)
01164       : BaseOffset(BaseOffset), 
01165       BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
01166       VtableIndex(VtableIndex) { }
01167     
01168     MethodInfo() : BaseOffset(0), BaseOffsetInLayoutClass(0), VtableIndex(0) { }
01169   };
01170   
01171   typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
01172   
01173   /// MethodInfoMap - The information for all methods in the vtable we're
01174   /// currently building.
01175   MethodInfoMapTy MethodInfoMap;
01176   
01177   typedef llvm::DenseMap<uint64_t, ThunkInfo> VtableThunksMapTy;
01178   
01179   /// VTableThunks - The thunks by vtable index in the vtable currently being 
01180   /// built.
01181   VtableThunksMapTy VTableThunks;
01182 
01183   typedef llvm::SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
01184   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
01185   
01186   /// Thunks - A map that contains all the thunks needed for all methods in the
01187   /// most derived class for which the vtable is currently being built.
01188   ThunksMapTy Thunks;
01189   
01190   /// AddThunk - Add a thunk for the given method.
01191   void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
01192   
01193   /// ComputeThisAdjustments - Compute the 'this' pointer adjustments for the
01194   /// part of the vtable we're currently building.
01195   void ComputeThisAdjustments();
01196   
01197   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
01198 
01199   /// PrimaryVirtualBases - All known virtual bases who are a primary base of
01200   /// some other base.
01201   VisitedVirtualBasesSetTy PrimaryVirtualBases;
01202 
01203   /// ComputeReturnAdjustment - Compute the return adjustment given a return
01204   /// adjustment base offset.
01205   ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
01206   
01207   /// ComputeThisAdjustmentBaseOffset - Compute the base offset for adjusting
01208   /// the 'this' pointer from the base subobject to the derived subobject.
01209   BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
01210                                              BaseSubobject Derived) const;
01211 
01212   /// ComputeThisAdjustment - Compute the 'this' pointer adjustment for the
01213   /// given virtual member function, its offset in the layout class and its
01214   /// final overrider.
01215   ThisAdjustment 
01216   ComputeThisAdjustment(const CXXMethodDecl *MD, 
01217                         uint64_t BaseOffsetInLayoutClass,
01218                         FinalOverriders::OverriderInfo Overrider);
01219 
01220   /// AddMethod - Add a single virtual member function to the vtable
01221   /// components vector.
01222   void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
01223 
01224   /// IsOverriderUsed - Returns whether the overrider will ever be used in this
01225   /// part of the vtable. 
01226   ///
01227   /// Itanium C++ ABI 2.5.2:
01228   ///
01229   ///   struct A { virtual void f(); };
01230   ///   struct B : virtual public A { int i; };
01231   ///   struct C : virtual public A { int j; };
01232   ///   struct D : public B, public C {};
01233   ///
01234   ///   When B and C are declared, A is a primary base in each case, so although
01235   ///   vcall offsets are allocated in the A-in-B and A-in-C vtables, no this
01236   ///   adjustment is required and no thunk is generated. However, inside D
01237   ///   objects, A is no longer a primary base of C, so if we allowed calls to
01238   ///   C::f() to use the copy of A's vtable in the C subobject, we would need
01239   ///   to adjust this from C* to B::A*, which would require a third-party 
01240   ///   thunk. Since we require that a call to C::f() first convert to A*, 
01241   ///   C-in-D's copy of A's vtable is never referenced, so this is not 
01242   ///   necessary.
01243   bool IsOverriderUsed(const CXXMethodDecl *Overrider,
01244                        uint64_t BaseOffsetInLayoutClass,
01245                        const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01246                        uint64_t FirstBaseOffsetInLayoutClass) const;
01247 
01248   
01249   /// AddMethods - Add the methods of this base subobject and all its
01250   /// primary bases to the vtable components vector.
01251   void AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,                  
01252                   const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01253                   uint64_t FirstBaseOffsetInLayoutClass,
01254                   PrimaryBasesSetVectorTy &PrimaryBases);
01255 
01256   // LayoutVtable - Layout the vtable for the given base class, including its
01257   // secondary vtables and any vtables for virtual bases.
01258   void LayoutVtable();
01259 
01260   /// LayoutPrimaryAndSecondaryVtables - Layout the primary vtable for the
01261   /// given base subobject, as well as all its secondary vtables.
01262   void LayoutPrimaryAndSecondaryVtables(BaseSubobject Base,
01263                                         bool BaseIsVirtual,
01264                                         uint64_t OffsetInLayoutClass);
01265   
01266   /// LayoutSecondaryVtables - Layout the secondary vtables for the given base
01267   /// subobject.
01268   ///
01269   /// \param BaseIsMorallyVirtual whether the base subobject is a virtual base
01270   /// or a direct or indirect base of a virtual base.
01271   void LayoutSecondaryVtables(BaseSubobject Base, bool BaseIsMorallyVirtual,
01272                               uint64_t OffsetInLayoutClass);
01273 
01274   /// DeterminePrimaryVirtualBases - Determine the primary virtual bases in this
01275   /// class hierarchy.
01276   void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD, 
01277                                     uint64_t OffsetInLayoutClass,
01278                                     VisitedVirtualBasesSetTy &VBases);
01279 
01280   /// LayoutVtablesForVirtualBases - Layout vtables for all virtual bases of the
01281   /// given base (excluding any primary bases).
01282   void LayoutVtablesForVirtualBases(const CXXRecordDecl *RD, 
01283                                     VisitedVirtualBasesSetTy &VBases);
01284 
01285   /// isBuildingConstructionVtable - Return whether this vtable builder is
01286   /// building a construction vtable.
01287   bool isBuildingConstructorVtable() const { 
01288     return MostDerivedClass != LayoutClass;
01289   }
01290 
01291 public:
01292   VtableBuilder(CodeGenVTables &VTables, const CXXRecordDecl *MostDerivedClass,
01293                 uint64_t MostDerivedClassOffset, bool MostDerivedClassIsVirtual,
01294                 const CXXRecordDecl *LayoutClass)
01295     : VTables(VTables), MostDerivedClass(MostDerivedClass),
01296     MostDerivedClassOffset(MostDerivedClassOffset), 
01297     MostDerivedClassIsVirtual(MostDerivedClassIsVirtual), 
01298     LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()), 
01299     Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
01300 
01301     LayoutVtable();
01302   }
01303 
01304   ThunksMapTy::const_iterator thunks_begin() const {
01305     return Thunks.begin();
01306   }
01307 
01308   ThunksMapTy::const_iterator thunks_end() const {
01309     return Thunks.end();
01310   }
01311 
01312   const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
01313     return VBaseOffsetOffsets;
01314   }
01315 
01316   /// getNumVTableComponents - Return the number of components in the vtable
01317   /// currently built.
01318   uint64_t getNumVTableComponents() const {
01319     return Components.size();
01320   }
01321 
01322   const uint64_t *vtable_components_data_begin() const {
01323     return reinterpret_cast<const uint64_t *>(Components.begin());
01324   }
01325   
01326   const uint64_t *vtable_components_data_end() const {
01327     return reinterpret_cast<const uint64_t *>(Components.end());
01328   }
01329   
01330   AddressPointsMapTy::const_iterator address_points_begin() const {
01331     return AddressPoints.begin();
01332   }
01333 
01334   AddressPointsMapTy::const_iterator address_points_end() const {
01335     return AddressPoints.end();
01336   }
01337 
01338   VtableThunksMapTy::const_iterator vtable_thunks_begin() const {
01339     return VTableThunks.begin();
01340   }
01341 
01342   VtableThunksMapTy::const_iterator vtable_thunks_end() const {
01343     return VTableThunks.end();
01344   }
01345 
01346   /// dumpLayout - Dump the vtable layout.
01347   void dumpLayout(llvm::raw_ostream&);
01348 };
01349 
01350 void VtableBuilder::AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
01351   assert(!isBuildingConstructorVtable() && 
01352          "Can't add thunks for construction vtable");
01353 
01354   llvm::SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
01355   
01356   // Check if we have this thunk already.
01357   if (std::find(ThunksVector.begin(), ThunksVector.end(), Thunk) != 
01358       ThunksVector.end())
01359     return;
01360   
01361   ThunksVector.push_back(Thunk);
01362 }
01363 
01364 /// OverridesMethodInBases - Checks whether whether this virtual member 
01365 /// function overrides a member function in any of the given bases.
01366 /// Returns the overridden member function, or null if none was found.
01367 static const CXXMethodDecl * 
01368 OverridesMethodInBases(const CXXMethodDecl *MD,
01369                        VtableBuilder::PrimaryBasesSetVectorTy &Bases) {
01370   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
01371        E = MD->end_overridden_methods(); I != E; ++I) {
01372     const CXXMethodDecl *OverriddenMD = *I;
01373     const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
01374     assert(OverriddenMD->isCanonicalDecl() &&
01375            "Should have the canonical decl of the overridden RD!");
01376     
01377     if (Bases.count(OverriddenRD))
01378       return OverriddenMD;
01379   }
01380       
01381   return 0;
01382 }
01383 
01384 void VtableBuilder::ComputeThisAdjustments() {
01385   // Now go through the method info map and see if any of the methods need
01386   // 'this' pointer adjustments.
01387   for (MethodInfoMapTy::const_iterator I = MethodInfoMap.begin(),
01388        E = MethodInfoMap.end(); I != E; ++I) {
01389     const CXXMethodDecl *MD = I->first;
01390     const MethodInfo &MethodInfo = I->second;
01391 
01392     // Ignore adjustments for unused function pointers.
01393     uint64_t VtableIndex = MethodInfo.VtableIndex;
01394     if (Components[VtableIndex].getKind() == 
01395         VtableComponent::CK_UnusedFunctionPointer)
01396       continue;
01397     
01398     // Get the final overrider for this method.
01399     FinalOverriders::OverriderInfo Overrider =
01400       Overriders.getOverrider(BaseSubobject(MD->getParent(), 
01401                                             MethodInfo.BaseOffset), MD);
01402     
01403     // Check if we need an adjustment at all.
01404     if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
01405       // When a return thunk is needed by a derived class that overrides a
01406       // virtual base, gcc uses a virtual 'this' adjustment as well. 
01407       // While the thunk itself might be needed by vtables in subclasses or
01408       // in construction vtables, there doesn't seem to be a reason for using
01409       // the thunk in this vtable. Still, we do so to match gcc.
01410       if (VTableThunks.lookup(VtableIndex).Return.isEmpty())
01411         continue;
01412     }
01413 
01414     ThisAdjustment ThisAdjustment =
01415       ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
01416 
01417     if (ThisAdjustment.isEmpty())
01418       continue;
01419 
01420     // Add it.
01421     VTableThunks[VtableIndex].This = ThisAdjustment;
01422 
01423     if (isa<CXXDestructorDecl>(MD)) {
01424       // Add an adjustment for the deleting destructor as well.
01425       VTableThunks[VtableIndex + 1].This = ThisAdjustment;
01426     }
01427   }
01428 
01429   /// Clear the method info map.
01430   MethodInfoMap.clear();
01431   
01432   if (isBuildingConstructorVtable()) {
01433     // We don't need to store thunk information for construction vtables.
01434     return;
01435   }
01436 
01437   for (VtableThunksMapTy::const_iterator I = VTableThunks.begin(),
01438        E = VTableThunks.end(); I != E; ++I) {
01439     const VtableComponent &Component = Components[I->first];
01440     const ThunkInfo &Thunk = I->second;
01441     const CXXMethodDecl *MD;
01442     
01443     switch (Component.getKind()) {
01444     default:
01445       llvm_unreachable("Unexpected vtable component kind!");
01446     case VtableComponent::CK_FunctionPointer:
01447       MD = Component.getFunctionDecl();
01448       break;
01449     case VtableComponent::CK_CompleteDtorPointer:
01450       MD = Component.getDestructorDecl();
01451       break;
01452     case VtableComponent::CK_DeletingDtorPointer:
01453       // We've already added the thunk when we saw the complete dtor pointer.
01454       continue;
01455     }
01456 
01457     if (MD->getParent() == MostDerivedClass)
01458       AddThunk(MD, Thunk);
01459   }
01460 }
01461 
01462 ReturnAdjustment VtableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
01463   ReturnAdjustment Adjustment;
01464   
01465   if (!Offset.isEmpty()) {
01466     if (Offset.VirtualBase) {
01467       // Get the virtual base offset offset.
01468       if (Offset.DerivedClass == MostDerivedClass) {
01469         // We can get the offset offset directly from our map.
01470         Adjustment.VBaseOffsetOffset = 
01471           VBaseOffsetOffsets.lookup(Offset.VirtualBase);
01472       } else {
01473         Adjustment.VBaseOffsetOffset = 
01474           VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
01475                                              Offset.VirtualBase);
01476       }
01477 
01478       // FIXME: Once the assert in getVirtualBaseOffsetOffset is back again,
01479       // we can get rid of this assert.
01480       assert(Adjustment.VBaseOffsetOffset != 0 && 
01481              "Invalid vbase offset offset!");
01482     }
01483 
01484     Adjustment.NonVirtual = Offset.NonVirtualOffset;
01485   }
01486   
01487   return Adjustment;
01488 }
01489 
01490 BaseOffset
01491 VtableBuilder::ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
01492                                                BaseSubobject Derived) const {
01493   const CXXRecordDecl *BaseRD = Base.getBase();
01494   const CXXRecordDecl *DerivedRD = Derived.getBase();
01495   
01496   CXXBasePaths Paths(/*FindAmbiguities=*/true,
01497                      /*RecordPaths=*/true, /*DetectVirtual=*/true);
01498 
01499   if (!const_cast<CXXRecordDecl *>(DerivedRD)->
01500       isDerivedFrom(const_cast<CXXRecordDecl *>(BaseRD), Paths)) {
01501     assert(false && "Class must be derived from the passed in base class!");
01502     return BaseOffset();
01503   }
01504 
01505   // We have to go through all the paths, and see which one leads us to the
01506   // right base subobject.
01507   for (CXXBasePaths::const_paths_iterator I = Paths.begin(), E = Paths.end();
01508        I != E; ++I) {
01509     BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, *I);
01510     
01511     // FIXME: Should not use * 8 here.
01512     uint64_t OffsetToBaseSubobject = Offset.NonVirtualOffset * 8;
01513     
01514     if (Offset.VirtualBase) {
01515       // If we have a virtual base class, the non-virtual offset is relative
01516       // to the virtual base class offset.
01517       const ASTRecordLayout &LayoutClassLayout =
01518         Context.getASTRecordLayout(LayoutClass);
01519       
01520       /// Get the virtual base offset, relative to the most derived class 
01521       /// layout.
01522       OffsetToBaseSubobject += 
01523         LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
01524     } else {
01525       // Otherwise, the non-virtual offset is relative to the derived class 
01526       // offset.
01527       OffsetToBaseSubobject += Derived.getBaseOffset();
01528     }
01529     
01530     // Check if this path gives us the right base subobject.
01531     if (OffsetToBaseSubobject == Base.getBaseOffset()) {
01532       // Since we're going from the base class _to_ the derived class, we'll
01533       // invert the non-virtual offset here.
01534       Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
01535       return Offset;
01536     }      
01537   }
01538   
01539   return BaseOffset();
01540 }
01541   
01542 ThisAdjustment 
01543 VtableBuilder::ComputeThisAdjustment(const CXXMethodDecl *MD, 
01544                                      uint64_t BaseOffsetInLayoutClass,
01545                                      FinalOverriders::OverriderInfo Overrider) {
01546   // Ignore adjustments for pure virtual member functions.
01547   if (Overrider.Method->isPure())
01548     return ThisAdjustment();
01549   
01550   BaseSubobject OverriddenBaseSubobject(MD->getParent(),
01551                                         BaseOffsetInLayoutClass);
01552   
01553   BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
01554                                        Overrider.Offset);
01555   
01556   // Compute the adjustment offset.
01557   BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
01558                                                       OverriderBaseSubobject);
01559   if (Offset.isEmpty())
01560     return ThisAdjustment();
01561 
01562   ThisAdjustment Adjustment;
01563   
01564   if (Offset.VirtualBase) {
01565     // Get the vcall offset map for this virtual base.
01566     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
01567 
01568     if (VCallOffsets.empty()) {
01569       // We don't have vcall offsets for this virtual base, go ahead and
01570       // build them.
01571       VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, MostDerivedClass,
01572                                          /*FinalOverriders=*/0,
01573                                          BaseSubobject(Offset.VirtualBase, 0),                                           
01574                                          /*BaseIsVirtual=*/true,
01575                                          /*OffsetInLayoutClass=*/0);
01576         
01577       VCallOffsets = Builder.getVCallOffsets();
01578     }
01579       
01580     Adjustment.VCallOffsetOffset = VCallOffsets.getVCallOffsetOffset(MD);
01581   }
01582 
01583   // Set the non-virtual part of the adjustment.
01584   Adjustment.NonVirtual = Offset.NonVirtualOffset;
01585   
01586   return Adjustment;
01587 }
01588   
01589 void 
01590 VtableBuilder::AddMethod(const CXXMethodDecl *MD,
01591                          ReturnAdjustment ReturnAdjustment) {
01592   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
01593     assert(ReturnAdjustment.isEmpty() && 
01594            "Destructor can't have return adjustment!");
01595 
01596     // Add both the complete destructor and the deleting destructor.
01597     Components.push_back(VtableComponent::MakeCompleteDtor(DD));
01598     Components.push_back(VtableComponent::MakeDeletingDtor(DD));
01599   } else {
01600     // Add the return adjustment if necessary.
01601     if (!ReturnAdjustment.isEmpty())
01602       VTableThunks[Components.size()].Return = ReturnAdjustment;
01603 
01604     // Add the function.
01605     Components.push_back(VtableComponent::MakeFunction(MD));
01606   }
01607 }
01608 
01609 /// OverridesIndirectMethodInBase - Return whether the given member function
01610 /// overrides any methods in the set of given bases. 
01611 /// Unlike OverridesMethodInBase, this checks "overriders of overriders".
01612 /// For example, if we have:
01613 ///
01614 /// struct A { virtual void f(); }
01615 /// struct B : A { virtual void f(); }
01616 /// struct C : B { virtual void f(); }
01617 ///
01618 /// OverridesIndirectMethodInBase will return true if given C::f as the method 
01619 /// and { A } as the set of  bases.
01620 static bool
01621 OverridesIndirectMethodInBases(const CXXMethodDecl *MD,
01622                                VtableBuilder::PrimaryBasesSetVectorTy &Bases) {
01623   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
01624        E = MD->end_overridden_methods(); I != E; ++I) {
01625     const CXXMethodDecl *OverriddenMD = *I;
01626     const CXXRecordDecl *OverriddenRD = OverriddenMD->getParent();
01627     assert(OverriddenMD->isCanonicalDecl() &&
01628            "Should have the canonical decl of the overridden RD!");
01629     
01630     if (Bases.count(OverriddenRD))
01631       return true;
01632     
01633     // Check "indirect overriders".
01634     if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
01635       return true;
01636   }
01637    
01638   return false;
01639 }
01640 
01641 bool 
01642 VtableBuilder::IsOverriderUsed(const CXXMethodDecl *Overrider,
01643                                uint64_t BaseOffsetInLayoutClass,
01644                                const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01645                                uint64_t FirstBaseOffsetInLayoutClass) const {
01646   // If the base and the first base in the primary base chain have the same
01647   // offsets, then this overrider will be used.
01648   if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
01649    return true;
01650 
01651   // We know now that Base (or a direct or indirect base of it) is a primary
01652   // base in part of the class hierarchy, but not a primary base in the most 
01653   // derived class.
01654   
01655   // If the overrider is the first base in the primary base chain, we know
01656   // that the overrider will be used.
01657   if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
01658     return true;
01659   
01660   VtableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
01661 
01662   const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
01663   PrimaryBases.insert(RD);
01664 
01665   // Now traverse the base chain, starting with the first base, until we find
01666   // the base that is no longer a primary base.
01667   while (true) {
01668     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01669     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
01670     
01671     if (!PrimaryBase)
01672       break;
01673     
01674     if (Layout.getPrimaryBaseWasVirtual()) {
01675       assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 && 
01676              "Primary base should always be at offset 0!");
01677 
01678       const ASTRecordLayout &LayoutClassLayout =
01679         Context.getASTRecordLayout(LayoutClass);
01680 
01681       // Now check if this is the primary base that is not a primary base in the
01682       // most derived class.
01683       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
01684           FirstBaseOffsetInLayoutClass) {
01685         // We found it, stop walking the chain.
01686         break;
01687       }
01688     } else {
01689       assert(Layout.getBaseClassOffset(PrimaryBase) == 0 && 
01690              "Primary base should always be at offset 0!");
01691     }
01692     
01693     if (!PrimaryBases.insert(PrimaryBase))
01694       assert(false && "Found a duplicate primary base!");
01695 
01696     RD = PrimaryBase;
01697   }
01698   
01699   // If the final overrider is an override of one of the primary bases,
01700   // then we know that it will be used.
01701   return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
01702 }
01703 
01704 /// FindNearestOverriddenMethod - Given a method, returns the overridden method
01705 /// from the nearest base. Returns null if no method was found.
01706 static const CXXMethodDecl * 
01707 FindNearestOverriddenMethod(const CXXMethodDecl *MD,
01708                             VtableBuilder::PrimaryBasesSetVectorTy &Bases) {
01709   for (int I = Bases.size(), E = 0; I != E; --I) {
01710     const CXXRecordDecl *PrimaryBase = Bases[I - 1];
01711 
01712     // Now check the overriden methods.
01713     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
01714          E = MD->end_overridden_methods(); I != E; ++I) {
01715       const CXXMethodDecl *OverriddenMD = *I;
01716 
01717       // We found our overridden method.
01718       if (OverriddenMD->getParent() == PrimaryBase)
01719         return OverriddenMD;
01720     }
01721   }
01722   
01723   return 0;
01724 }  
01725 
01726 void
01727 VtableBuilder::AddMethods(BaseSubobject Base, uint64_t BaseOffsetInLayoutClass,                  
01728                           const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
01729                           uint64_t FirstBaseOffsetInLayoutClass,
01730                           PrimaryBasesSetVectorTy &PrimaryBases) {
01731   const CXXRecordDecl *RD = Base.getBase();
01732   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01733 
01734   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
01735     uint64_t PrimaryBaseOffset;
01736     uint64_t PrimaryBaseOffsetInLayoutClass;
01737     if (Layout.getPrimaryBaseWasVirtual()) {
01738       assert(Layout.getVBaseClassOffset(PrimaryBase) == 0 &&
01739              "Primary vbase should have a zero offset!");
01740       
01741       const ASTRecordLayout &MostDerivedClassLayout =
01742         Context.getASTRecordLayout(MostDerivedClass);
01743       
01744       PrimaryBaseOffset = 
01745         MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
01746       
01747       const ASTRecordLayout &LayoutClassLayout =
01748         Context.getASTRecordLayout(LayoutClass);
01749 
01750       PrimaryBaseOffsetInLayoutClass =
01751         LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
01752     } else {
01753       assert(Layout.getBaseClassOffset(PrimaryBase) == 0 &&
01754              "Primary base should have a zero offset!");
01755 
01756       PrimaryBaseOffset = Base.getBaseOffset();
01757       PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
01758     }
01759 
01760     AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
01761                PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain, 
01762                FirstBaseOffsetInLayoutClass, PrimaryBases);
01763     
01764     if (!PrimaryBases.insert(PrimaryBase))
01765       assert(false && "Found a duplicate primary base!");
01766   }
01767 
01768   // Now go through all virtual member functions and add them.
01769   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
01770        E = RD->method_end(); I != E; ++I) {
01771     const CXXMethodDecl *MD = *I;
01772   
01773     if (!MD->isVirtual())
01774       continue;
01775 
01776     // Get the final overrider.
01777     FinalOverriders::OverriderInfo Overrider = 
01778       Overriders.getOverrider(Base, MD);
01779 
01780     // Check if this virtual member function overrides a method in a primary
01781     // base. If this is the case, and the return type doesn't require adjustment
01782     // then we can just use the member function from the primary base.
01783     if (const CXXMethodDecl *OverriddenMD = 
01784           FindNearestOverriddenMethod(MD, PrimaryBases)) {
01785       if (ComputeReturnAdjustmentBaseOffset(Context, MD, 
01786                                             OverriddenMD).isEmpty()) {
01787         // Replace the method info of the overridden method with our own
01788         // method.
01789         assert(MethodInfoMap.count(OverriddenMD) && 
01790                "Did not find the overridden method!");
01791         MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
01792         
01793         MethodInfo MethodInfo(Base.getBaseOffset(), 
01794                               BaseOffsetInLayoutClass,
01795                               OverriddenMethodInfo.VtableIndex);
01796 
01797         assert(!MethodInfoMap.count(MD) &&
01798                "Should not have method info for this method yet!");
01799         
01800         MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
01801         MethodInfoMap.erase(OverriddenMD);
01802         
01803         // If the overridden method exists in a virtual base class or a direct
01804         // or indirect base class of a virtual base class, we need to emit a
01805         // thunk if we ever have a class hierarchy where the base class is not
01806         // a primary base in the complete object.
01807         if (!isBuildingConstructorVtable() && OverriddenMD != MD) {
01808           // Compute the this adjustment.
01809           ThisAdjustment ThisAdjustment =
01810             ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
01811                                   Overrider);
01812 
01813           if (ThisAdjustment.VCallOffsetOffset &&
01814               Overrider.Method->getParent() == MostDerivedClass) {
01815             // This is a virtual thunk for the most derived class, add it.
01816             AddThunk(Overrider.Method, 
01817                      ThunkInfo(ThisAdjustment, ReturnAdjustment()));
01818           }
01819         }
01820 
01821         continue;
01822       }
01823     }
01824 
01825     // Insert the method info for this method.
01826     MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
01827                           Components.size());
01828 
01829     assert(!MethodInfoMap.count(MD) &&
01830            "Should not have method info for this method yet!");
01831     MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
01832 
01833     // Check if this overrider is going to be used.
01834     const CXXMethodDecl *OverriderMD = Overrider.Method;
01835     if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
01836                          FirstBaseInPrimaryBaseChain, 
01837                          FirstBaseOffsetInLayoutClass)) {
01838       Components.push_back(VtableComponent::MakeUnusedFunction(OverriderMD));
01839       continue;
01840     }
01841     
01842     // Check if this overrider needs a return adjustment.
01843     BaseOffset ReturnAdjustmentOffset = 
01844       Overriders.getReturnAdjustmentOffset(Base, MD);
01845 
01846     ReturnAdjustment ReturnAdjustment = 
01847       ComputeReturnAdjustment(ReturnAdjustmentOffset);
01848     
01849     AddMethod(Overrider.Method, ReturnAdjustment);
01850   }
01851 }
01852 
01853 void VtableBuilder::LayoutVtable() {
01854   LayoutPrimaryAndSecondaryVtables(BaseSubobject(MostDerivedClass, 0),
01855                                    MostDerivedClassIsVirtual,
01856                                    MostDerivedClassOffset);
01857   
01858   VisitedVirtualBasesSetTy VBases;
01859   
01860   // Determine the primary virtual bases.
01861   DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
01862                                VBases);
01863   VBases.clear();
01864   
01865   LayoutVtablesForVirtualBases(MostDerivedClass, VBases);
01866 }
01867   
01868 void
01869 VtableBuilder::LayoutPrimaryAndSecondaryVtables(BaseSubobject Base,
01870                                                 bool BaseIsVirtual,
01871                                                 uint64_t OffsetInLayoutClass) {
01872   assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
01873 
01874   // Add vcall and vbase offsets for this vtable.
01875   VCallAndVBaseOffsetBuilder Builder(MostDerivedClass, LayoutClass, &Overriders,
01876                                      Base, BaseIsVirtual, OffsetInLayoutClass);
01877   Components.append(Builder.components_begin(), Builder.components_end());
01878   
01879   // Check if we need to add these vcall offsets.
01880   if (BaseIsVirtual && !Builder.getVCallOffsets().empty()) {
01881     VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
01882     
01883     if (VCallOffsets.empty())
01884       VCallOffsets = Builder.getVCallOffsets();
01885   }
01886 
01887   // If we're laying out the most derived class we want to keep track of the
01888   // virtual base class offset offsets.
01889   if (Base.getBase() == MostDerivedClass)
01890     VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
01891 
01892   // Add the offset to top.
01893   // FIXME: We should not use / 8 here.
01894   int64_t OffsetToTop = -(int64_t)(OffsetInLayoutClass -
01895                                    MostDerivedClassOffset) / 8;
01896   Components.push_back(VtableComponent::MakeOffsetToTop(OffsetToTop));
01897   
01898   // Next, add the RTTI.
01899   Components.push_back(VtableComponent::MakeRTTI(MostDerivedClass));
01900   
01901   uint64_t AddressPoint = Components.size();
01902 
01903   // Now go through all virtual member functions and add them.
01904   PrimaryBasesSetVectorTy PrimaryBases;
01905   AddMethods(Base, OffsetInLayoutClass, Base.getBase(), OffsetInLayoutClass, 
01906              PrimaryBases);
01907 
01908   // Compute 'this' pointer adjustments.
01909   ComputeThisAdjustments();
01910 
01911   // Add all address points.
01912   const CXXRecordDecl *RD = Base.getBase();
01913   while (true) {
01914     AddressPoints.insert(std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
01915                                         AddressPoint));
01916 
01917     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01918     const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
01919     
01920     if (!PrimaryBase)
01921       break;
01922     
01923     if (Layout.getPrimaryBaseWasVirtual()) {
01924       // Check if this virtual primary base is a primary base in the layout
01925       // class. If it's not, we don't want to add it.
01926       const ASTRecordLayout &LayoutClassLayout =
01927         Context.getASTRecordLayout(LayoutClass);
01928 
01929       if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
01930           OffsetInLayoutClass) {
01931         // We don't want to add this class (or any of its primary bases).
01932         break;
01933       }
01934     }
01935 
01936     RD = PrimaryBase;
01937   }
01938 
01939   bool BaseIsMorallyVirtual = BaseIsVirtual;
01940   if (isBuildingConstructorVtable() && Base.getBase() == MostDerivedClass)
01941     BaseIsMorallyVirtual = false;
01942   
01943   // Layout secondary vtables.
01944   LayoutSecondaryVtables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
01945 }
01946 
01947 void VtableBuilder::LayoutSecondaryVtables(BaseSubobject Base,
01948                                            bool BaseIsMorallyVirtual,
01949                                            uint64_t OffsetInLayoutClass) {
01950   // Itanium C++ ABI 2.5.2:
01951   //   Following the primary virtual table of a derived class are secondary 
01952   //   virtual tables for each of its proper base classes, except any primary
01953   //   base(s) with which it shares its primary virtual table.
01954 
01955   const CXXRecordDecl *RD = Base.getBase();
01956   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
01957   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
01958   
01959   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
01960        E = RD->bases_end(); I != E; ++I) {
01961     // Ignore virtual bases, we'll emit them later.
01962     if (I->isVirtual())
01963       continue;
01964     
01965     const CXXRecordDecl *BaseDecl = 
01966       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
01967 
01968     // Ignore bases that don't have a vtable.
01969     if (!BaseDecl->isDynamicClass())
01970       continue;
01971 
01972     if (isBuildingConstructorVtable()) {
01973       // Itanium C++ ABI 2.6.4:
01974       //   Some of the base class subobjects may not need construction virtual
01975       //   tables, which will therefore not be present in the construction
01976       //   virtual table group, even though the subobject virtual tables are
01977       //   present in the main virtual table group for the complete object.
01978       if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
01979         continue;
01980     }
01981 
01982     // Get the base offset of this base.
01983     uint64_t RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
01984     uint64_t BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
01985     
01986     uint64_t BaseOffsetInLayoutClass = OffsetInLayoutClass + RelativeBaseOffset;
01987     
01988     // Don't emit a secondary vtable for a primary base. We might however want 
01989     // to emit secondary vtables for other bases of this base.
01990     if (BaseDecl == PrimaryBase) {
01991       LayoutSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
01992                              BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
01993       continue;
01994     }
01995 
01996     // Layout the primary vtable (and any secondary vtables) for this base.
01997     LayoutPrimaryAndSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
01998                                      /*BaseIsVirtual=*/false,
01999                                      BaseOffsetInLayoutClass);
02000   }
02001 }
02002 
02003 void
02004 VtableBuilder::DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
02005                                             uint64_t OffsetInLayoutClass,
02006                                             VisitedVirtualBasesSetTy &VBases) {
02007   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
02008   
02009   // Check if this base has a primary base.
02010   if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
02011 
02012     // Check if it's virtual.
02013     if (Layout.getPrimaryBaseWasVirtual()) {
02014       bool IsPrimaryVirtualBase = true;
02015 
02016       if (isBuildingConstructorVtable()) {
02017         // Check if the base is actually a primary base in the class we use for
02018         // layout.
02019         const ASTRecordLayout &LayoutClassLayout =
02020           Context.getASTRecordLayout(LayoutClass);
02021 
02022         uint64_t PrimaryBaseOffsetInLayoutClass =
02023           LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
02024         
02025         // We know that the base is not a primary base in the layout class if 
02026         // the base offsets are different.
02027         if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
02028           IsPrimaryVirtualBase = false;
02029       }
02030         
02031       if (IsPrimaryVirtualBase)
02032         PrimaryVirtualBases.insert(PrimaryBase);
02033     }
02034   }
02035 
02036   // Traverse bases, looking for more primary virtual bases.
02037   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
02038        E = RD->bases_end(); I != E; ++I) {
02039     const CXXRecordDecl *BaseDecl = 
02040       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
02041 
02042     uint64_t BaseOffsetInLayoutClass;
02043     
02044     if (I->isVirtual()) {
02045       if (!VBases.insert(BaseDecl))
02046         continue;
02047       
02048       const ASTRecordLayout &LayoutClassLayout =
02049         Context.getASTRecordLayout(LayoutClass);
02050 
02051       BaseOffsetInLayoutClass = LayoutClassLayout.getVBaseClassOffset(BaseDecl);
02052     } else {
02053       BaseOffsetInLayoutClass = 
02054         OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
02055     }
02056 
02057     DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
02058   }
02059 }
02060 
02061 void
02062 VtableBuilder::LayoutVtablesForVirtualBases(const CXXRecordDecl *RD, 
02063                                             VisitedVirtualBasesSetTy &VBases) {
02064   // Itanium C++ ABI 2.5.2:
02065   //   Then come the virtual base virtual tables, also in inheritance graph
02066   //   order, and again excluding primary bases (which share virtual tables with
02067   //   the classes for which they are primary).
02068   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
02069        E = RD->bases_end(); I != E; ++I) {
02070     const CXXRecordDecl *BaseDecl = 
02071       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
02072 
02073     // Check if this base needs a vtable. (If it's virtual, not a primary base
02074     // of some other class, and we haven't visited it before).
02075     if (I->isVirtual() && BaseDecl->isDynamicClass() && 
02076         !PrimaryVirtualBases.count(BaseDecl) && VBases.insert(BaseDecl)) {
02077       const ASTRecordLayout &MostDerivedClassLayout =
02078         Context.getASTRecordLayout(MostDerivedClass);
02079       uint64_t BaseOffset = 
02080         MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
02081       
02082       const ASTRecordLayout &LayoutClassLayout =
02083         Context.getASTRecordLayout(LayoutClass);
02084       uint64_t BaseOffsetInLayoutClass = 
02085         LayoutClassLayout.getVBaseClassOffset(BaseDecl);
02086 
02087       LayoutPrimaryAndSecondaryVtables(BaseSubobject(BaseDecl, BaseOffset),
02088                                        /*BaseIsVirtual=*/true,
02089                                        BaseOffsetInLayoutClass);
02090     }
02091     
02092     // We only need to check the base for virtual base vtables if it actually
02093     // has virtual bases.
02094     if (BaseDecl->getNumVBases())
02095       LayoutVtablesForVirtualBases(BaseDecl, VBases);
02096   }
02097 }
02098 
02099 /// dumpLayout - Dump the vtable layout.
02100 void VtableBuilder::dumpLayout(llvm::raw_ostream& Out) {
02101 
02102   if (isBuildingConstructorVtable()) {
02103     Out << "Construction vtable for ('";
02104     Out << MostDerivedClass->getQualifiedNameAsString() << "', ";
02105     // FIXME: Don't use / 8 .
02106     Out << MostDerivedClassOffset / 8 << ") in '";
02107     Out << LayoutClass->getQualifiedNameAsString();
02108   } else {
02109     Out << "Vtable for '";
02110     Out << MostDerivedClass->getQualifiedNameAsString();
02111   }
02112   Out << "' (" << Components.size() << " entries).\n";
02113 
02114   // Iterate through the address points and insert them into a new map where
02115   // they are keyed by the index and not the base object.
02116   // Since an address point can be shared by multiple subobjects, we use an
02117   // STL multimap.
02118   std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
02119   for (AddressPointsMapTy::const_iterator I = AddressPoints.begin(), 
02120        E = AddressPoints.end(); I != E; ++I) {
02121     const BaseSubobject& Base = I->first;
02122     uint64_t Index = I->second;
02123     
02124     AddressPointsByIndex.insert(std::make_pair(Index, Base));
02125   }
02126   
02127   for (unsigned I = 0, E = Components.size(); I != E; ++I) {
02128     uint64_t Index = I;
02129 
02130     Out << llvm::format("%4d | ", I);
02131 
02132     const VtableComponent &Component = Components[I];
02133 
02134     // Dump the component.
02135     switch (Component.getKind()) {
02136 
02137     case VtableComponent::CK_VCallOffset:
02138       Out << "vcall_offset (" << Component.getVCallOffset() << ")";
02139       break;
02140 
02141     case VtableComponent::CK_VBaseOffset:
02142       Out << "vbase_offset (" << Component.getVBaseOffset() << ")";
02143       break;
02144 
02145     case VtableComponent::CK_OffsetToTop:
02146       Out << "offset_to_top (" << Component.getOffsetToTop() << ")";
02147       break;
02148     
02149     case VtableComponent::CK_RTTI:
02150       Out << Component.getRTTIDecl()->getQualifiedNameAsString() << " RTTI";
02151       break;
02152     
02153     case VtableComponent::CK_FunctionPointer: {
02154       const CXXMethodDecl *MD = Component.getFunctionDecl();
02155 
02156       std::string Str = 
02157         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 
02158                                     MD);
02159       Out << Str;
02160       if (MD->isPure())
02161         Out << " [pure]";
02162 
02163       ThunkInfo Thunk = VTableThunks.lookup(I);
02164       if (!Thunk.isEmpty()) {
02165         // If this function pointer has a return adjustment, dump it.
02166         if (!Thunk.Return.isEmpty()) {
02167           Out << "\n       [return adjustment: ";
02168           Out << Thunk.Return.NonVirtual << " non-virtual";
02169           
02170           if (Thunk.Return.VBaseOffsetOffset) {
02171             Out << ", " << Thunk.Return.VBaseOffsetOffset;
02172             Out << " vbase offset offset";
02173           }
02174 
02175           Out << ']';
02176         }
02177 
02178         // If this function pointer has a 'this' pointer adjustment, dump it.
02179         if (!Thunk.This.isEmpty()) {
02180           Out << "\n       [this adjustment: ";
02181           Out << Thunk.This.NonVirtual << " non-virtual";
02182           
02183           if (Thunk.This.VCallOffsetOffset) {
02184             Out << ", " << Thunk.This.VCallOffsetOffset;
02185             Out << " vcall offset offset";
02186           }
02187 
02188           Out << ']';
02189         }          
02190       }
02191 
02192       break;
02193     }
02194 
02195     case VtableComponent::CK_CompleteDtorPointer: 
02196     case VtableComponent::CK_DeletingDtorPointer: {
02197       bool IsComplete = 
02198         Component.getKind() == VtableComponent::CK_CompleteDtorPointer;
02199       
02200       const CXXDestructorDecl *DD = Component.getDestructorDecl();
02201       
02202       Out << DD->getQualifiedNameAsString();
02203       if (IsComplete)
02204         Out << "() [complete]";
02205       else
02206         Out << "() [deleting]";
02207 
02208       if (DD->isPure())
02209         Out << " [pure]";
02210 
02211       ThunkInfo Thunk = VTableThunks.lookup(I);
02212       if (!Thunk.isEmpty()) {
02213         // If this destructor has a 'this' pointer adjustment, dump it.
02214         if (!Thunk.This.isEmpty()) {
02215           Out << "\n       [this adjustment: ";
02216           Out << Thunk.This.NonVirtual << " non-virtual";
02217           
02218           if (Thunk.This.VCallOffsetOffset) {
02219             Out << ", " << Thunk.This.VCallOffsetOffset;
02220             Out << " vcall offset offset";
02221           }
02222           
02223           Out << ']';
02224         }          
02225       }        
02226 
02227       break;
02228     }
02229 
02230     case VtableComponent::CK_UnusedFunctionPointer: {
02231       const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
02232 
02233       std::string Str = 
02234         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual, 
02235                                     MD);
02236       Out << "[unused] " << Str;
02237       if (MD->isPure())
02238         Out << " [pure]";
02239     }
02240 
02241     }
02242 
02243     Out << '\n';
02244     
02245     // Dump the next address point.
02246     uint64_t NextIndex = Index + 1;
02247     if (AddressPointsByIndex.count(NextIndex)) {
02248       if (AddressPointsByIndex.count(NextIndex) == 1) {
02249         const BaseSubobject &Base = 
02250           AddressPointsByIndex.find(NextIndex)->second;
02251         
02252         // FIXME: Instead of dividing by 8, we should be using CharUnits.
02253         Out << "       -- (" << Base.getBase()->getQualifiedNameAsString();
02254         Out << ", " << Base.getBaseOffset() / 8 << ") vtable address --\n";
02255       } else {
02256         uint64_t BaseOffset = 
02257           AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
02258         
02259         // We store the class names in a set to get a stable order.
02260         std::set<std::string> ClassNames;
02261         for (std::multimap<uint64_t, BaseSubobject>::const_iterator I =
02262              AddressPointsByIndex.lower_bound(NextIndex), E =
02263              AddressPointsByIndex.upper_bound(NextIndex); I != E; ++I) {
02264           assert(I->second.getBaseOffset() == BaseOffset &&
02265                  "Invalid base offset!");
02266           const CXXRecordDecl *RD = I->second.getBase();
02267           ClassNames.insert(RD->getQualifiedNameAsString());
02268         }
02269         
02270         for (std::set<std::string>::const_iterator I = ClassNames.begin(),
02271              E = ClassNames.end(); I != E; ++I) {
02272           // FIXME: Instead of dividing by 8, we should be using CharUnits.
02273           Out << "       -- (" << *I;
02274           Out << ", " << BaseOffset / 8 << ") vtable address --\n";
02275         }
02276       }
02277     }
02278   }
02279 
02280   Out << '\n';
02281   
02282   if (isBuildingConstructorVtable())
02283     return;
02284   
02285   if (MostDerivedClass->getNumVBases()) {
02286     // We store the virtual base class names and their offsets in a map to get
02287     // a stable order.
02288 
02289     std::map<std::string, int64_t> ClassNamesAndOffsets;
02290     for (VBaseOffsetOffsetsMapTy::const_iterator I = VBaseOffsetOffsets.begin(),
02291          E = VBaseOffsetOffsets.end(); I != E; ++I) {
02292       std::string ClassName = I->first->getQualifiedNameAsString();
02293       int64_t OffsetOffset = I->second;
02294       ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
02295     }
02296     
02297     Out << "Virtual base offset offsets for '";
02298     Out << MostDerivedClass->getQualifiedNameAsString() << "' (";
02299     Out << ClassNamesAndOffsets.size();
02300     Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
02301 
02302     for (std::map<std::string, int64_t>::const_iterator I =
02303          ClassNamesAndOffsets.begin(), E = ClassNamesAndOffsets.end(); 
02304          I != E; ++I)
02305       Out << "   " << I->first << " | " << I->second << '\n';
02306 
02307     Out << "\n";
02308   }
02309   
02310   if (!Thunks.empty()) {
02311     // We store the method names in a map to get a stable order.
02312     std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
02313     
02314     for (ThunksMapTy::const_iterator I = Thunks.begin(), E = Thunks.end();
02315          I != E; ++I) {
02316       const CXXMethodDecl *MD = I->first;
02317       std::string MethodName = 
02318         PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
02319                                     MD);
02320       
02321       MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
02322     }
02323 
02324     for (std::map<std::string, const CXXMethodDecl *>::const_iterator I =
02325          MethodNamesAndDecls.begin(), E = MethodNamesAndDecls.end(); 
02326          I != E; ++I) {
02327       const std::string &MethodName = I->first;
02328       const CXXMethodDecl *MD = I->second;
02329 
02330       ThunkInfoVectorTy ThunksVector = Thunks[MD];
02331       std::sort(ThunksVector.begin(), ThunksVector.end());
02332 
02333       Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
02334       Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
02335       
02336       for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
02337         const ThunkInfo &Thunk = ThunksVector[I];
02338 
02339         Out << llvm::format("%4d | ", I);
02340         
02341         // If this function pointer has a return pointer adjustment, dump it.
02342         if (!Thunk.Return.isEmpty()) {
02343           Out << "return adjustment: " << Thunk.This.NonVirtual;
02344           Out << " non-virtual";
02345           if (Thunk.Return.VBaseOffsetOffset) {
02346             Out << ", " << Thunk.Return.VBaseOffsetOffset;
02347             Out << " vbase offset offset";
02348           }
02349 
02350           if (!Thunk.This.isEmpty())
02351             Out << "\n       ";
02352         }
02353 
02354         // If this function pointer has a 'this' pointer adjustment, dump it.
02355         if (!Thunk.This.isEmpty()) {
02356           Out << "this adjustment: ";
02357           Out << Thunk.This.NonVirtual << " non-virtual";
02358           
02359           if (Thunk.This.VCallOffsetOffset) {
02360             Out << ", " << Thunk.This.VCallOffsetOffset;
02361             Out << " vcall offset offset";
02362           }
02363         }
02364         
02365         Out << '\n';
02366       }
02367       
02368       Out << '\n';
02369 
02370     }
02371   }
02372 }
02373   
02374 }
02375 
02376 void CodeGenVTables::ComputeMethodVtableIndices(const CXXRecordDecl *RD) {
02377   
02378   // Itanium C++ ABI 2.5.2:
02379   //   The order of the virtual function pointers in a virtual table is the 
02380   //   order of declaration of the corresponding member functions in the class.
02381   //
02382   //   There is an entry for any virtual function declared in a class, 
02383   //   whether it is a new function or overrides a base class function, 
02384   //   unless it overrides a function from the primary base, and conversion
02385   //   between their return types does not require an adjustment. 
02386 
02387   int64_t CurrentIndex = 0;
02388   
02389   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
02390   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
02391   
02392   if (PrimaryBase) {
02393     assert(PrimaryBase->isDefinition() && 
02394            "Should have the definition decl of the primary base!");
02395 
02396     // Since the record decl shares its vtable pointer with the primary base
02397     // we need to start counting at the end of the primary base's vtable.
02398     CurrentIndex = getNumVirtualFunctionPointers(PrimaryBase);
02399   }
02400 
02401   // Collect all the primary bases, so we can check whether methods override
02402   // a method from the base.
02403   VtableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
02404   for (ASTRecordLayout::primary_base_info_iterator
02405        I = Layout.primary_base_begin(), E = Layout.primary_base_end();
02406        I != E; ++I)
02407     PrimaryBases.insert((*I).getBase());
02408 
02409   const CXXDestructorDecl *ImplicitVirtualDtor = 0;
02410   
02411   for (CXXRecordDecl::method_iterator i = RD->method_begin(),
02412        e = RD->method_end(); i != e; ++i) {
02413     const CXXMethodDecl *MD = *i;
02414 
02415     // We only want virtual methods.
02416     if (!MD->isVirtual())
02417       continue;
02418 
02419     // Check if this method overrides a method in the primary base.
02420     if (const CXXMethodDecl *OverriddenMD = 
02421           OverridesMethodInBases(MD, PrimaryBases)) {
02422       // Check if converting from the return type of the method to the 
02423       // return type of the overridden method requires conversion.
02424       if (ComputeReturnAdjustmentBaseOffset(CGM.getContext(), MD, 
02425                                             OverriddenMD).isEmpty()) {
02426         // This index is shared between the index in the vtable of the primary
02427         // base class.
02428         if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
02429           const CXXDestructorDecl *OverriddenDD = 
02430             cast<CXXDestructorDecl>(OverriddenMD);
02431           
02432           // Add both the complete and deleting entries.
02433           MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = 
02434             getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Complete));
02435           MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = 
02436             getMethodVtableIndex(GlobalDecl(OverriddenDD, Dtor_Deleting));
02437         } else {
02438           MethodVtableIndices[MD] = getMethodVtableIndex(OverriddenMD);
02439         }
02440         
02441         // We don't need to add an entry for this method.
02442         continue;
02443       }
02444     }
02445     
02446     if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
02447       if (MD->isImplicit()) {
02448         assert(!ImplicitVirtualDtor && 
02449                "Did already see an implicit virtual dtor!");
02450         ImplicitVirtualDtor = DD;
02451         continue;
02452       } 
02453 
02454       // Add the complete dtor.
02455       MethodVtableIndices[GlobalDecl(DD, Dtor_Complete)] = CurrentIndex++;
02456       
02457       // Add the deleting dtor.
02458       MethodVtableIndices[GlobalDecl(DD, Dtor_Deleting)] = CurrentIndex++;
02459     } else {
02460       // Add the entry.
02461       MethodVtableIndices[MD] = CurrentIndex++;
02462     }
02463   }
02464 
02465   if (ImplicitVirtualDtor) {
02466     // Itanium C++ ABI 2.5.2:
02467     //   If a class has an implicitly-defined virtual destructor, 
02468     //   its entries come after the declared virtual function pointers.
02469 
02470     // Add the complete dtor.
02471     MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Complete)] = 
02472       CurrentIndex++;
02473     
02474     // Add the deleting dtor.
02475     MethodVtableIndices[GlobalDecl(ImplicitVirtualDtor, Dtor_Deleting)] = 
02476       CurrentIndex++;
02477   }
02478   
02479   NumVirtualFunctionPointers[RD] = CurrentIndex;
02480 }
02481 
02482 uint64_t CodeGenVTables::getNumVirtualFunctionPointers(const CXXRecordDecl *RD) {
02483   llvm::DenseMap<const CXXRecordDecl *, uint64_t>::iterator I = 
02484     NumVirtualFunctionPointers.find(RD);
02485   if (I != NumVirtualFunctionPointers.end())
02486     return I->second;
02487 
02488   ComputeMethodVtableIndices(RD);
02489 
02490   I = NumVirtualFunctionPointers.find(RD);
02491   assert(I != NumVirtualFunctionPointers.end() && "Did not find entry!");
02492   return I->second;
02493 }
02494       
02495 uint64_t CodeGenVTables::getMethodVtableIndex(GlobalDecl GD) {
02496   MethodVtableIndicesTy::iterator I = MethodVtableIndices.find(GD);
02497   if (I != MethodVtableIndices.end())
02498     return I->second;
02499   
02500   const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
02501 
02502   ComputeMethodVtableIndices(RD);
02503 
02504   I = MethodVtableIndices.find(GD);
02505   assert(I != MethodVtableIndices.end() && "Did not find index!");
02506   return I->second;
02507 }
02508 
02509 int64_t CodeGenVTables::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, 
02510                                                    const CXXRecordDecl *VBase) {
02511   ClassPairTy ClassPair(RD, VBase);
02512   
02513   VirtualBaseClassOffsetOffsetsMapTy::iterator I = 
02514     VirtualBaseClassOffsetOffsets.find(ClassPair);
02515   if (I != VirtualBaseClassOffsetOffsets.end())
02516     return I->second;
02517   
02518   VCallAndVBaseOffsetBuilder Builder(RD, RD, /*FinalOverriders=*/0,
02519                                      BaseSubobject(RD, 0),                                           
02520                                      /*BaseIsVirtual=*/false,
02521                                      /*OffsetInLayoutClass=*/0);
02522 
02523   for (VCallAndVBaseOffsetBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
02524        Builder.getVBaseOffsetOffsets().begin(), 
02525        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
02526     // Insert all types.
02527     ClassPairTy ClassPair(RD, I->first);
02528     
02529     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
02530   }
02531   
02532   I = VirtualBaseClassOffsetOffsets.find(ClassPair);
02533   
02534   // FIXME: The assertion below assertion currently fails with the old vtable 
02535   /// layout code if there is a non-virtual thunk adjustment in a vtable.
02536   // Once the new layout is in place, this return should be removed.
02537   if (I == VirtualBaseClassOffsetOffsets.end())
02538     return 0;
02539   
02540   assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
02541   
02542   return I->second;
02543 }
02544 
02545 uint64_t
02546 CodeGenVTables::getAddressPoint(BaseSubobject Base, const CXXRecordDecl *RD) {
02547   uint64_t AddressPoint = AddressPoints.lookup(std::make_pair(RD, Base));
02548   assert(AddressPoint && "Address point must not be zero!");
02549 
02550   return AddressPoint;
02551 }
02552 
02553 llvm::Constant *CodeGenModule::GetAddrOfThunk(GlobalDecl GD, 
02554                                               const ThunkInfo &Thunk) {
02555   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02556 
02557   // Compute the mangled name.
02558   llvm::SmallString<256> Name;
02559   if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD))
02560     getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), Thunk.This,
02561                                           Name);
02562   else
02563     getMangleContext().mangleThunk(MD, Thunk, Name);
02564   
02565   const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD);
02566   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
02567 }
02568 
02569 static llvm::Value *PerformTypeAdjustment(CodeGenFunction &CGF,
02570                                           llvm::Value *Ptr,
02571                                           int64_t NonVirtualAdjustment,
02572                                           int64_t VirtualAdjustment) {
02573   if (!NonVirtualAdjustment && !VirtualAdjustment)
02574     return Ptr;
02575 
02576   const llvm::Type *Int8PtrTy = 
02577     llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
02578   
02579   llvm::Value *V = CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
02580 
02581   if (NonVirtualAdjustment) {
02582     // Do the non-virtual adjustment.
02583     V = CGF.Builder.CreateConstInBoundsGEP1_64(V, NonVirtualAdjustment);
02584   }
02585 
02586   if (VirtualAdjustment) {
02587     const llvm::Type *PtrDiffTy = 
02588       CGF.ConvertType(CGF.getContext().getPointerDiffType());
02589 
02590     // Do the virtual adjustment.
02591     llvm::Value *VTablePtrPtr = 
02592       CGF.Builder.CreateBitCast(V, Int8PtrTy->getPointerTo());
02593     
02594     llvm::Value *VTablePtr = CGF.Builder.CreateLoad(VTablePtrPtr);
02595   
02596     llvm::Value *OffsetPtr =
02597       CGF.Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment);
02598     
02599     OffsetPtr = CGF.Builder.CreateBitCast(OffsetPtr, PtrDiffTy->getPointerTo());
02600     
02601     // Load the adjustment offset from the vtable.
02602     llvm::Value *Offset = CGF.Builder.CreateLoad(OffsetPtr);
02603     
02604     // Adjust our pointer.
02605     V = CGF.Builder.CreateInBoundsGEP(V, Offset);
02606   }
02607 
02608   // Cast back to the original type.
02609   return CGF.Builder.CreateBitCast(V, Ptr->getType());
02610 }
02611 
02612 void CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD,
02613                                     const ThunkInfo &Thunk) {
02614   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02615   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
02616   QualType ResultType = FPT->getResultType();
02617   QualType ThisType = MD->getThisType(getContext());
02618 
02619   FunctionArgList FunctionArgs;
02620 
02621   // FIXME: It would be nice if more of this code could be shared with 
02622   // CodeGenFunction::GenerateCode.
02623 
02624   // Create the implicit 'this' parameter declaration.
02625   CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
02626                                           MD->getLocation(),
02627                                           &getContext().Idents.get("this"),
02628                                           ThisType);
02629 
02630   // Add the 'this' parameter.
02631   FunctionArgs.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
02632 
02633   // Add the rest of the parameters.
02634   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
02635        E = MD->param_end(); I != E; ++I) {
02636     ParmVarDecl *Param = *I;
02637     
02638     FunctionArgs.push_back(std::make_pair(Param, Param->getType()));
02639   }
02640   
02641   StartFunction(GlobalDecl(), ResultType, Fn, FunctionArgs, SourceLocation());
02642 
02643   // Adjust the 'this' pointer if necessary.
02644   llvm::Value *AdjustedThisPtr = 
02645     PerformTypeAdjustment(*this, LoadCXXThis(), 
02646                           Thunk.This.NonVirtual, 
02647                           Thunk.This.VCallOffsetOffset);
02648   
02649   CallArgList CallArgs;
02650   
02651   // Add our adjusted 'this' pointer.
02652   CallArgs.push_back(std::make_pair(RValue::get(AdjustedThisPtr), ThisType));
02653 
02654   // Add the rest of the parameters.
02655   for (FunctionDecl::param_const_iterator I = MD->param_begin(),
02656        E = MD->param_end(); I != E; ++I) {
02657     ParmVarDecl *Param = *I;
02658     QualType ArgType = Param->getType();
02659     
02660     // FIXME: Declaring a DeclRefExpr on the stack is kinda icky.
02661     DeclRefExpr ArgExpr(Param, ArgType.getNonReferenceType(), SourceLocation());
02662     CallArgs.push_back(std::make_pair(EmitCallArg(&ArgExpr, ArgType), ArgType));
02663   }
02664 
02665   // Get our callee.
02666   const llvm::Type *Ty =
02667     CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
02668                                    FPT->isVariadic());
02669   llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
02670 
02671   const CGFunctionInfo &FnInfo = 
02672     CGM.getTypes().getFunctionInfo(ResultType, CallArgs,
02673                                    FPT->getExtInfo());
02674   
02675   // Now emit our call.
02676   RValue RV = EmitCall(FnInfo, Callee, ReturnValueSlot(), CallArgs, MD);
02677   
02678   if (!Thunk.Return.isEmpty()) {
02679     // Emit the return adjustment.
02680     bool NullCheckValue = !ResultType->isReferenceType();
02681     
02682     llvm::BasicBlock *AdjustNull = 0;
02683     llvm::BasicBlock *AdjustNotNull = 0;
02684     llvm::BasicBlock *AdjustEnd = 0;
02685     
02686     llvm::Value *ReturnValue = RV.getScalarVal();
02687 
02688     if (NullCheckValue) {
02689       AdjustNull = createBasicBlock("adjust.null");
02690       AdjustNotNull = createBasicBlock("adjust.notnull");
02691       AdjustEnd = createBasicBlock("adjust.end");
02692     
02693       llvm::Value *IsNull = Builder.CreateIsNull(ReturnValue);
02694       Builder.CreateCondBr(IsNull, AdjustNull, AdjustNotNull);
02695       EmitBlock(AdjustNotNull);
02696     }
02697     
02698     ReturnValue = PerformTypeAdjustment(*this, ReturnValue, 
02699                                         Thunk.Return.NonVirtual, 
02700                                         Thunk.Return.VBaseOffsetOffset);
02701     
02702     if (NullCheckValue) {
02703       Builder.CreateBr(AdjustEnd);
02704       EmitBlock(AdjustNull);
02705       Builder.CreateBr(AdjustEnd);
02706       EmitBlock(AdjustEnd);
02707     
02708       llvm::PHINode *PHI = Builder.CreatePHI(ReturnValue->getType());
02709       PHI->reserveOperandSpace(2);
02710       PHI->addIncoming(ReturnValue, AdjustNotNull);
02711       PHI->addIncoming(llvm::Constant::getNullValue(ReturnValue->getType()), 
02712                        AdjustNull);
02713       ReturnValue = PHI;
02714     }
02715     
02716     RV = RValue::get(ReturnValue);
02717   }
02718 
02719   if (!ResultType->isVoidType())
02720     EmitReturnOfRValue(RV, ResultType);
02721 
02722   FinishFunction();
02723 
02724   // Destroy the 'this' declaration.
02725   CXXThisDecl->Destroy(getContext());
02726   
02727   // Set the right linkage.
02728   Fn->setLinkage(CGM.getFunctionLinkage(MD));
02729   
02730   // Set the right visibility.
02731   CGM.setGlobalVisibility(Fn, MD);
02732 }
02733 
02734 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk)
02735 {
02736   llvm::Constant *Entry = CGM.GetAddrOfThunk(GD, Thunk);
02737   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02738   
02739   // Strip off a bitcast if we got one back.
02740   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
02741     assert(CE->getOpcode() == llvm::Instruction::BitCast);
02742     Entry = CE->getOperand(0);
02743   }
02744   
02745   // There's already a declaration with the same name, check if it has the same
02746   // type or if we need to replace it.
02747   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != 
02748       CGM.getTypes().GetFunctionTypeForVtable(MD)) {
02749     llvm::GlobalValue *OldThunkFn = cast<llvm::GlobalValue>(Entry);
02750     
02751     // If the types mismatch then we have to rewrite the definition.
02752     assert(OldThunkFn->isDeclaration() &&
02753            "Shouldn't replace non-declaration");
02754 
02755     // Remove the name from the old thunk function and get a new thunk.
02756     OldThunkFn->setName(llvm::StringRef());
02757     Entry = CGM.GetAddrOfThunk(GD, Thunk);
02758     
02759     // If needed, replace the old thunk with a bitcast.
02760     if (!OldThunkFn->use_empty()) {
02761       llvm::Constant *NewPtrForOldDecl =
02762         llvm::ConstantExpr::getBitCast(Entry, OldThunkFn->getType());
02763       OldThunkFn->replaceAllUsesWith(NewPtrForOldDecl);
02764     }
02765     
02766     // Remove the old thunk.
02767     OldThunkFn->eraseFromParent();
02768   }
02769 
02770   // Actually generate the thunk body.
02771   llvm::Function *ThunkFn = cast<llvm::Function>(Entry);
02772   CodeGenFunction(CGM).GenerateThunk(ThunkFn, GD, Thunk);
02773 }
02774 
02775 void CodeGenVTables::EmitThunks(GlobalDecl GD)
02776 {
02777   const CXXMethodDecl *MD = 
02778     cast<CXXMethodDecl>(GD.getDecl())->getCanonicalDecl();
02779 
02780   // We don't need to generate thunks for the base destructor.
02781   if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
02782     return;
02783 
02784   const CXXRecordDecl *RD = MD->getParent();
02785   
02786   // Compute VTable related info for this class.
02787   ComputeVTableRelatedInformation(RD);
02788   
02789   ThunksMapTy::const_iterator I = Thunks.find(MD);
02790   if (I == Thunks.end()) {
02791     // We did not find a thunk for this method.
02792     return;
02793   }
02794 
02795   const ThunkInfoVectorTy &ThunkInfoVector = I->second;
02796   for (unsigned I = 0, E = ThunkInfoVector.size(); I != E; ++I)
02797     EmitThunk(GD, ThunkInfoVector[I]);
02798 }
02799 
02800 void CodeGenVTables::ComputeVTableRelatedInformation(const CXXRecordDecl *RD) {
02801   uint64_t *&LayoutData = VTableLayoutMap[RD];
02802   
02803   // Check if we've computed this information before.
02804   if (LayoutData)
02805     return;
02806       
02807   VtableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
02808 
02809   // Add the VTable layout.
02810   uint64_t NumVTableComponents = Builder.getNumVTableComponents();
02811   LayoutData = new uint64_t[NumVTableComponents + 1];
02812 
02813   // Store the number of components.
02814   LayoutData[0] = NumVTableComponents;
02815 
02816   // Store the components.
02817   std::copy(Builder.vtable_components_data_begin(),
02818             Builder.vtable_components_data_end(),
02819             &LayoutData[1]);
02820 
02821   // Add the known thunks.
02822   Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
02823   
02824   // Add the thunks needed in this vtable.
02825   assert(!VTableThunksMap.count(RD) && 
02826          "Thunks already exists for this vtable!");
02827 
02828   VTableThunksTy &VTableThunks = VTableThunksMap[RD];
02829   VTableThunks.append(Builder.vtable_thunks_begin(),
02830                       Builder.vtable_thunks_end());
02831   
02832   // Sort them.
02833   std::sort(VTableThunks.begin(), VTableThunks.end());
02834   
02835   // Add the address points.
02836   for (VtableBuilder::AddressPointsMapTy::const_iterator I =
02837        Builder.address_points_begin(), E = Builder.address_points_end();
02838        I != E; ++I) {
02839     
02840     uint64_t &AddressPoint = AddressPoints[std::make_pair(RD, I->first)];
02841     
02842     // Check if we already have the address points for this base.
02843     assert(!AddressPoint && "Address point already exists for this base!");
02844     
02845     AddressPoint = I->second;
02846   }
02847   
02848   // If we don't have the vbase information for this class, insert it.
02849   // getVirtualBaseOffsetOffset will compute it separately without computing
02850   // the rest of the vtable related information.
02851   if (!RD->getNumVBases())
02852     return;
02853   
02854   const RecordType *VBaseRT = 
02855     RD->vbases_begin()->getType()->getAs<RecordType>();
02856   const CXXRecordDecl *VBase = cast<CXXRecordDecl>(VBaseRT->getDecl());
02857   
02858   if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
02859     return;
02860   
02861   for (VtableBuilder::VBaseOffsetOffsetsMapTy::const_iterator I =
02862        Builder.getVBaseOffsetOffsets().begin(), 
02863        E = Builder.getVBaseOffsetOffsets().end(); I != E; ++I) {
02864     // Insert all types.
02865     ClassPairTy ClassPair(RD, I->first);
02866     
02867     VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I->second));
02868   }
02869 }
02870 
02871 llvm::Constant *
02872 CodeGenVTables::CreateVTableInitializer(const CXXRecordDecl *RD,
02873                                         const uint64_t *Components, 
02874                                         unsigned NumComponents,
02875                                         const VTableThunksTy &VTableThunks) {
02876   llvm::SmallVector<llvm::Constant *, 64> Inits;
02877 
02878   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
02879   
02880   const llvm::Type *PtrDiffTy = 
02881     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
02882 
02883   QualType ClassType = CGM.getContext().getTagDeclType(RD);
02884   llvm::Constant *RTTI = CGM.GetAddrOfRTTIDescriptor(ClassType);
02885   
02886   unsigned NextVTableThunkIndex = 0;
02887   
02888   llvm::Constant* PureVirtualFn = 0;
02889 
02890   for (unsigned I = 0; I != NumComponents; ++I) {
02891     VtableComponent Component = 
02892       VtableComponent::getFromOpaqueInteger(Components[I]);
02893 
02894     llvm::Constant *Init = 0;
02895 
02896     switch (Component.getKind()) {
02897     case VtableComponent::CK_VCallOffset:
02898       Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVCallOffset());
02899       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
02900       break;
02901     case VtableComponent::CK_VBaseOffset:
02902       Init = llvm::ConstantInt::get(PtrDiffTy, Component.getVBaseOffset());
02903       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
02904       break;
02905     case VtableComponent::CK_OffsetToTop:
02906       Init = llvm::ConstantInt::get(PtrDiffTy, Component.getOffsetToTop());
02907       Init = llvm::ConstantExpr::getIntToPtr(Init, Int8PtrTy);
02908       break;
02909     case VtableComponent::CK_RTTI:
02910       Init = llvm::ConstantExpr::getBitCast(RTTI, Int8PtrTy);
02911       break;
02912     case VtableComponent::CK_FunctionPointer:
02913     case VtableComponent::CK_CompleteDtorPointer:
02914     case VtableComponent::CK_DeletingDtorPointer: {
02915       GlobalDecl GD;
02916       
02917       // Get the right global decl.
02918       switch (Component.getKind()) {
02919       default:
02920         llvm_unreachable("Unexpected vtable component kind");
02921       case VtableComponent::CK_FunctionPointer:
02922         GD = Component.getFunctionDecl();
02923         break;
02924       case VtableComponent::CK_CompleteDtorPointer:
02925         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Complete);
02926         break;
02927       case VtableComponent::CK_DeletingDtorPointer:
02928         GD = GlobalDecl(Component.getDestructorDecl(), Dtor_Deleting);
02929         break;
02930       }
02931 
02932       if (cast<CXXMethodDecl>(GD.getDecl())->isPure()) {
02933         // We have a pure virtual member function.
02934         if (!PureVirtualFn) {
02935           const llvm::FunctionType *Ty = 
02936             llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), 
02937                                     /*isVarArg=*/false);
02938           PureVirtualFn = 
02939             CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
02940           PureVirtualFn = llvm::ConstantExpr::getBitCast(PureVirtualFn, 
02941                                                          Int8PtrTy);
02942         }
02943         
02944         Init = PureVirtualFn;
02945       } else {
02946         // Check if we should use a thunk.
02947         if (NextVTableThunkIndex < VTableThunks.size() &&
02948             VTableThunks[NextVTableThunkIndex].first == I) {
02949           const ThunkInfo &Thunk = VTableThunks[NextVTableThunkIndex].second;
02950         
02951           Init = CGM.GetAddrOfThunk(GD, Thunk);
02952         
02953           NextVTableThunkIndex++;
02954         } else {
02955           const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
02956           const llvm::Type *Ty = CGM.getTypes().GetFunctionTypeForVtable(MD);
02957         
02958           Init = CGM.GetAddrOfFunction(GD, Ty);
02959         }
02960 
02961         Init = llvm::ConstantExpr::getBitCast(Init, Int8PtrTy);
02962       }
02963       break;
02964     }
02965 
02966     case VtableComponent::CK_UnusedFunctionPointer:
02967       Init = llvm::ConstantExpr::getNullValue(Int8PtrTy);
02968       break;
02969     };
02970     
02971     Inits.push_back(Init);
02972   }
02973   
02974   llvm::ArrayType *ArrayType = llvm::ArrayType::get(Int8PtrTy, NumComponents);
02975   return llvm::ConstantArray::get(ArrayType, Inits.data(), Inits.size());
02976 }
02977 
02978 /// GetGlobalVariable - Will return a global variable of the given type. 
02979 /// If a variable with a different type already exists then a new variable
02980 /// with the right type will be created.
02981 /// FIXME: We should move this to CodeGenModule and rename it to something 
02982 /// better and then use it in CGVTT and CGRTTI. 
02983 static llvm::GlobalVariable *
02984 GetGlobalVariable(llvm::Module &Module, llvm::StringRef Name,
02985                   const llvm::Type *Ty,
02986                   llvm::GlobalValue::LinkageTypes Linkage) {
02987 
02988   llvm::GlobalVariable *GV = Module.getNamedGlobal(Name);
02989   llvm::GlobalVariable *OldGV = 0;
02990   
02991   if (GV) {
02992     // Check if the variable has the right type.
02993     if (GV->getType()->getElementType() == Ty)
02994       return GV;
02995 
02996     assert(GV->isDeclaration() && "Declaration has wrong type!");
02997     
02998     OldGV = GV;
02999   }
03000   
03001   // Create a new variable.
03002   GV = new llvm::GlobalVariable(Module, Ty, /*isConstant=*/true,
03003                                 Linkage, 0, Name);
03004   
03005   if (OldGV) {
03006     // Replace occurrences of the old variable if needed.
03007     GV->takeName(OldGV);
03008    
03009     if (!OldGV->use_empty()) {
03010       llvm::Constant *NewPtrForOldDecl =
03011         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
03012       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
03013     }
03014 
03015     OldGV->eraseFromParent();
03016   }
03017   
03018   return GV;
03019 }
03020 
03021 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTable(const CXXRecordDecl *RD) {
03022   llvm::SmallString<256> OutName;
03023   CGM.getMangleContext().mangleCXXVtable(RD, OutName);
03024   llvm::StringRef Name = OutName.str();
03025 
03026   ComputeVTableRelatedInformation(RD);
03027   
03028   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
03029   llvm::ArrayType *ArrayType = 
03030     llvm::ArrayType::get(Int8PtrTy, getNumVTableComponents(RD));
03031 
03032   return GetGlobalVariable(CGM.getModule(), Name, ArrayType, 
03033                            llvm::GlobalValue::ExternalLinkage);
03034 }
03035 
03036 void
03037 CodeGenVTables::EmitVTableDefinition(llvm::GlobalVariable *VTable,
03038                                      llvm::GlobalVariable::LinkageTypes Linkage,
03039                                      const CXXRecordDecl *RD) {
03040   // Dump the vtable layout if necessary.
03041   if (CGM.getLangOptions().DumpVtableLayouts) {
03042     VtableBuilder Builder(*this, RD, 0, /*MostDerivedClassIsVirtual=*/0, RD);
03043 
03044     Builder.dumpLayout(llvm::errs());
03045   }
03046 
03047   assert(VTableThunksMap.count(RD) && 
03048          "No thunk status for this record decl!");
03049   
03050   const VTableThunksTy& Thunks = VTableThunksMap[RD];
03051   
03052   // Create and set the initializer.
03053   llvm::Constant *Init = 
03054     CreateVTableInitializer(RD, getVTableComponentsData(RD),
03055                             getNumVTableComponents(RD), Thunks);
03056   VTable->setInitializer(Init);
03057   
03058   // Set the correct linkage.
03059   VTable->setLinkage(Linkage);
03060 }
03061 
03062 llvm::GlobalVariable *
03063 CodeGenVTables::GenerateConstructionVTable(const CXXRecordDecl *RD, 
03064                                       const BaseSubobject &Base, 
03065                                       bool BaseIsVirtual, 
03066                                       VTableAddressPointsMapTy& AddressPoints) {
03067   VtableBuilder Builder(*this, Base.getBase(), Base.getBaseOffset(), 
03068                         /*MostDerivedClassIsVirtual=*/BaseIsVirtual, RD);
03069 
03070   // Dump the vtable layout if necessary.
03071   if (CGM.getLangOptions().DumpVtableLayouts)
03072     Builder.dumpLayout(llvm::errs());
03073 
03074   // Add the address points.
03075   AddressPoints.insert(Builder.address_points_begin(),
03076                        Builder.address_points_end());
03077 
03078   // Get the mangled construction vtable name.
03079   llvm::SmallString<256> OutName;
03080   CGM.getMangleContext().mangleCXXCtorVtable(RD, Base.getBaseOffset() / 8, 
03081                                              Base.getBase(), OutName);
03082   llvm::StringRef Name = OutName.str();
03083 
03084   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
03085   llvm::ArrayType *ArrayType = 
03086     llvm::ArrayType::get(Int8PtrTy, Builder.getNumVTableComponents());
03087 
03088   // Create the variable that will hold the construction vtable.
03089   llvm::GlobalVariable *VTable = 
03090     GetGlobalVariable(CGM.getModule(), Name, ArrayType, 
03091                       llvm::GlobalValue::InternalLinkage);
03092 
03093   // Add the thunks.
03094   VTableThunksTy VTableThunks;
03095   VTableThunks.append(Builder.vtable_thunks_begin(),
03096                       Builder.vtable_thunks_end());
03097 
03098   // Sort them.
03099   std::sort(VTableThunks.begin(), VTableThunks.end());
03100 
03101   // Create and set the initializer.
03102   llvm::Constant *Init = 
03103     CreateVTableInitializer(Base.getBase(), 
03104                             Builder.vtable_components_data_begin(), 
03105                             Builder.getNumVTableComponents(), VTableThunks);
03106   VTable->setInitializer(Init);
03107   
03108   return VTable;
03109 }
03110 
03111 void 
03112 CodeGenVTables::GenerateClassData(llvm::GlobalVariable::LinkageTypes Linkage,
03113                                   const CXXRecordDecl *RD) {
03114   llvm::GlobalVariable *&VTable = Vtables[RD];
03115   if (VTable) {
03116     assert(VTable->getInitializer() && "Vtable doesn't have a definition!");
03117     return;
03118   }
03119 
03120   VTable = GetAddrOfVTable(RD);
03121   EmitVTableDefinition(VTable, Linkage, RD);
03122 
03123   GenerateVTT(Linkage, /*GenerateDefinition=*/true, RD);
03124 }
03125 
03126 void CodeGenVTables::EmitVTableRelatedData(GlobalDecl GD) {
03127   const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
03128   const CXXRecordDecl *RD = MD->getParent();
03129 
03130   // If the class doesn't have a vtable we don't need to emit one.
03131   if (!RD->isDynamicClass())
03132     return;
03133   
03134   // Check if we need to emit thunks for this function.
03135   if (MD->isVirtual())
03136     EmitThunks(GD);
03137 
03138   // Get the key function.
03139   const CXXMethodDecl *KeyFunction = CGM.getContext().getKeyFunction(RD);
03140   
03141   TemplateSpecializationKind RDKind = RD->getTemplateSpecializationKind();
03142   TemplateSpecializationKind MDKind = MD->getTemplateSpecializationKind();
03143 
03144   if (KeyFunction) {
03145     // We don't have the right key function.
03146     if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
03147       return;
03148   } else {
03149     // If we have no key funcion and this is a explicit instantiation declaration,
03150     // we will produce a vtable at the explicit instantiation. We don't need one
03151     // here.
03152     if (RDKind == clang::TSK_ExplicitInstantiationDeclaration)
03153       return;
03154 
03155     // If this is an explicit instantiation of a method, we don't need a vtable.
03156     // Since we have no key function, we will emit the vtable when we see
03157     // a use, and just defining a function is not an use.
03158     if (RDKind == TSK_ImplicitInstantiation &&
03159         MDKind == TSK_ExplicitInstantiationDefinition)
03160       return;
03161   }
03162 
03163   if (Vtables.count(RD))
03164     return;
03165 
03166   if (RDKind == TSK_ImplicitInstantiation)
03167     CGM.DeferredVtables.push_back(RD);
03168   else
03169     GenerateClassData(CGM.getVtableLinkage(RD), RD);
03170 }