clang API Documentation

CXXInheritance.cpp
Go to the documentation of this file.
00001 //===------ CXXInheritance.cpp - C++ Inheritance ----------------*- C++ -*-===//
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 file provides routines that help analyzing C++ inheritance hierarchies.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #include "clang/AST/CXXInheritance.h"
00014 #include "clang/AST/ASTContext.h"
00015 #include "clang/AST/DeclCXX.h"
00016 #include "clang/AST/RecordLayout.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include <algorithm>
00019 #include <set>
00020 
00021 using namespace clang;
00022 
00023 /// \brief Computes the set of declarations referenced by these base
00024 /// paths.
00025 void CXXBasePaths::ComputeDeclsFound() {
00026   assert(NumDeclsFound == 0 && !DeclsFound &&
00027          "Already computed the set of declarations");
00028 
00029   llvm::SetVector<NamedDecl *, SmallVector<NamedDecl *, 8> > Decls;
00030   for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
00031     Decls.insert(Path->Decls.front());
00032 
00033   NumDeclsFound = Decls.size();
00034   DeclsFound = new NamedDecl * [NumDeclsFound];
00035   std::copy(Decls.begin(), Decls.end(), DeclsFound);
00036 }
00037 
00038 CXXBasePaths::decl_range CXXBasePaths::found_decls() {
00039   if (NumDeclsFound == 0)
00040     ComputeDeclsFound();
00041 
00042   return decl_range(decl_iterator(DeclsFound),
00043                     decl_iterator(DeclsFound + NumDeclsFound));
00044 }
00045 
00046 /// isAmbiguous - Determines whether the set of paths provided is
00047 /// ambiguous, i.e., there are two or more paths that refer to
00048 /// different base class subobjects of the same type. BaseType must be
00049 /// an unqualified, canonical class type.
00050 bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
00051   BaseType = BaseType.getUnqualifiedType();
00052   std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
00053   return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
00054 }
00055 
00056 /// clear - Clear out all prior path information.
00057 void CXXBasePaths::clear() {
00058   Paths.clear();
00059   ClassSubobjects.clear();
00060   ScratchPath.clear();
00061   DetectedVirtual = nullptr;
00062 }
00063 
00064 /// @brief Swaps the contents of this CXXBasePaths structure with the
00065 /// contents of Other.
00066 void CXXBasePaths::swap(CXXBasePaths &Other) {
00067   std::swap(Origin, Other.Origin);
00068   Paths.swap(Other.Paths);
00069   ClassSubobjects.swap(Other.ClassSubobjects);
00070   std::swap(FindAmbiguities, Other.FindAmbiguities);
00071   std::swap(RecordPaths, Other.RecordPaths);
00072   std::swap(DetectVirtual, Other.DetectVirtual);
00073   std::swap(DetectedVirtual, Other.DetectedVirtual);
00074 }
00075 
00076 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
00077   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
00078                      /*DetectVirtual=*/false);
00079   return isDerivedFrom(Base, Paths);
00080 }
00081 
00082 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
00083                                   CXXBasePaths &Paths) const {
00084   if (getCanonicalDecl() == Base->getCanonicalDecl())
00085     return false;
00086   
00087   Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
00088   return lookupInBases(&FindBaseClass,
00089                        const_cast<CXXRecordDecl*>(Base->getCanonicalDecl()),
00090                        Paths);
00091 }
00092 
00093 bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const {
00094   if (!getNumVBases())
00095     return false;
00096 
00097   CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
00098                      /*DetectVirtual=*/false);
00099 
00100   if (getCanonicalDecl() == Base->getCanonicalDecl())
00101     return false;
00102   
00103   Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
00104 
00105   const void *BasePtr = static_cast<const void*>(Base->getCanonicalDecl());
00106   return lookupInBases(&FindVirtualBaseClass,
00107                        const_cast<void *>(BasePtr),
00108                        Paths);
00109 }
00110 
00111 static bool BaseIsNot(const CXXRecordDecl *Base, void *OpaqueTarget) {
00112   // OpaqueTarget is a CXXRecordDecl*.
00113   return Base->getCanonicalDecl() != (const CXXRecordDecl*) OpaqueTarget;
00114 }
00115 
00116 bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
00117   return forallBases(BaseIsNot,
00118                      const_cast<CXXRecordDecl *>(Base->getCanonicalDecl()));
00119 }
00120 
00121 bool
00122 CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const {
00123   assert(isDependentContext());
00124 
00125   for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
00126     if (CurContext->Equals(this))
00127       return true;
00128 
00129   return false;
00130 }
00131 
00132 bool CXXRecordDecl::forallBases(ForallBasesCallback *BaseMatches,
00133                                 void *OpaqueData,
00134                                 bool AllowShortCircuit) const {
00135   SmallVector<const CXXRecordDecl*, 8> Queue;
00136 
00137   const CXXRecordDecl *Record = this;
00138   bool AllMatches = true;
00139   while (true) {
00140     for (const auto &I : Record->bases()) {
00141       const RecordType *Ty = I.getType()->getAs<RecordType>();
00142       if (!Ty) {
00143         if (AllowShortCircuit) return false;
00144         AllMatches = false;
00145         continue;
00146       }
00147 
00148       CXXRecordDecl *Base = 
00149             cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
00150       if (!Base ||
00151           (Base->isDependentContext() &&
00152            !Base->isCurrentInstantiation(Record))) {
00153         if (AllowShortCircuit) return false;
00154         AllMatches = false;
00155         continue;
00156       }
00157       
00158       Queue.push_back(Base);
00159       if (!BaseMatches(Base, OpaqueData)) {
00160         if (AllowShortCircuit) return false;
00161         AllMatches = false;
00162         continue;
00163       }
00164     }
00165 
00166     if (Queue.empty())
00167       break;
00168     Record = Queue.pop_back_val(); // not actually a queue.
00169   }
00170 
00171   return AllMatches;
00172 }
00173 
00174 bool CXXBasePaths::lookupInBases(ASTContext &Context,
00175                                  const CXXRecordDecl *Record,
00176                                CXXRecordDecl::BaseMatchesCallback *BaseMatches, 
00177                                  void *UserData) {
00178   bool FoundPath = false;
00179 
00180   // The access of the path down to this record.
00181   AccessSpecifier AccessToHere = ScratchPath.Access;
00182   bool IsFirstStep = ScratchPath.empty();
00183 
00184   for (const auto &BaseSpec : Record->bases()) {
00185     // Find the record of the base class subobjects for this type.
00186     QualType BaseType =
00187         Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType();
00188 
00189     // C++ [temp.dep]p3:
00190     //   In the definition of a class template or a member of a class template,
00191     //   if a base class of the class template depends on a template-parameter,
00192     //   the base class scope is not examined during unqualified name lookup 
00193     //   either at the point of definition of the class template or member or 
00194     //   during an instantiation of the class tem- plate or member.
00195     if (BaseType->isDependentType())
00196       continue;
00197     
00198     // Determine whether we need to visit this base class at all,
00199     // updating the count of subobjects appropriately.
00200     std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
00201     bool VisitBase = true;
00202     bool SetVirtual = false;
00203     if (BaseSpec.isVirtual()) {
00204       VisitBase = !Subobjects.first;
00205       Subobjects.first = true;
00206       if (isDetectingVirtual() && DetectedVirtual == nullptr) {
00207         // If this is the first virtual we find, remember it. If it turns out
00208         // there is no base path here, we'll reset it later.
00209         DetectedVirtual = BaseType->getAs<RecordType>();
00210         SetVirtual = true;
00211       }
00212     } else
00213       ++Subobjects.second;
00214     
00215     if (isRecordingPaths()) {
00216       // Add this base specifier to the current path.
00217       CXXBasePathElement Element;
00218       Element.Base = &BaseSpec;
00219       Element.Class = Record;
00220       if (BaseSpec.isVirtual())
00221         Element.SubobjectNumber = 0;
00222       else
00223         Element.SubobjectNumber = Subobjects.second;
00224       ScratchPath.push_back(Element);
00225 
00226       // Calculate the "top-down" access to this base class.
00227       // The spec actually describes this bottom-up, but top-down is
00228       // equivalent because the definition works out as follows:
00229       // 1. Write down the access along each step in the inheritance
00230       //    chain, followed by the access of the decl itself.
00231       //    For example, in
00232       //      class A { public: int foo; };
00233       //      class B : protected A {};
00234       //      class C : public B {};
00235       //      class D : private C {};
00236       //    we would write:
00237       //      private public protected public
00238       // 2. If 'private' appears anywhere except far-left, access is denied.
00239       // 3. Otherwise, overall access is determined by the most restrictive
00240       //    access in the sequence.
00241       if (IsFirstStep)
00242         ScratchPath.Access = BaseSpec.getAccessSpecifier();
00243       else
00244         ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, 
00245                                                  BaseSpec.getAccessSpecifier());
00246     }
00247     
00248     // Track whether there's a path involving this specific base.
00249     bool FoundPathThroughBase = false;
00250     
00251     if (BaseMatches(&BaseSpec, ScratchPath, UserData)) {
00252       // We've found a path that terminates at this base.
00253       FoundPath = FoundPathThroughBase = true;
00254       if (isRecordingPaths()) {
00255         // We have a path. Make a copy of it before moving on.
00256         Paths.push_back(ScratchPath);
00257       } else if (!isFindingAmbiguities()) {
00258         // We found a path and we don't care about ambiguities;
00259         // return immediately.
00260         return FoundPath;
00261       }
00262     } else if (VisitBase) {
00263       CXXRecordDecl *BaseRecord
00264         = cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>()
00265                                 ->getDecl());
00266       if (lookupInBases(Context, BaseRecord, BaseMatches, UserData)) {
00267         // C++ [class.member.lookup]p2:
00268         //   A member name f in one sub-object B hides a member name f in
00269         //   a sub-object A if A is a base class sub-object of B. Any
00270         //   declarations that are so hidden are eliminated from
00271         //   consideration.
00272         
00273         // There is a path to a base class that meets the criteria. If we're 
00274         // not collecting paths or finding ambiguities, we're done.
00275         FoundPath = FoundPathThroughBase = true;
00276         if (!isFindingAmbiguities())
00277           return FoundPath;
00278       }
00279     }
00280     
00281     // Pop this base specifier off the current path (if we're
00282     // collecting paths).
00283     if (isRecordingPaths()) {
00284       ScratchPath.pop_back();
00285     }
00286 
00287     // If we set a virtual earlier, and this isn't a path, forget it again.
00288     if (SetVirtual && !FoundPathThroughBase) {
00289       DetectedVirtual = nullptr;
00290     }
00291   }
00292 
00293   // Reset the scratch path access.
00294   ScratchPath.Access = AccessToHere;
00295   
00296   return FoundPath;
00297 }
00298 
00299 bool CXXRecordDecl::lookupInBases(BaseMatchesCallback *BaseMatches,
00300                                   void *UserData,
00301                                   CXXBasePaths &Paths) const {
00302   // If we didn't find anything, report that.
00303   if (!Paths.lookupInBases(getASTContext(), this, BaseMatches, UserData))
00304     return false;
00305 
00306   // If we're not recording paths or we won't ever find ambiguities,
00307   // we're done.
00308   if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
00309     return true;
00310   
00311   // C++ [class.member.lookup]p6:
00312   //   When virtual base classes are used, a hidden declaration can be
00313   //   reached along a path through the sub-object lattice that does
00314   //   not pass through the hiding declaration. This is not an
00315   //   ambiguity. The identical use with nonvirtual base classes is an
00316   //   ambiguity; in that case there is no unique instance of the name
00317   //   that hides all the others.
00318   //
00319   // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
00320   // way to make it any faster.
00321   for (CXXBasePaths::paths_iterator P = Paths.begin(), PEnd = Paths.end();
00322        P != PEnd; /* increment in loop */) {
00323     bool Hidden = false;
00324 
00325     for (CXXBasePath::iterator PE = P->begin(), PEEnd = P->end();
00326          PE != PEEnd && !Hidden; ++PE) {
00327       if (PE->Base->isVirtual()) {
00328         CXXRecordDecl *VBase = nullptr;
00329         if (const RecordType *Record = PE->Base->getType()->getAs<RecordType>())
00330           VBase = cast<CXXRecordDecl>(Record->getDecl());
00331         if (!VBase)
00332           break;
00333 
00334         // The declaration(s) we found along this path were found in a
00335         // subobject of a virtual base. Check whether this virtual
00336         // base is a subobject of any other path; if so, then the
00337         // declaration in this path are hidden by that patch.
00338         for (CXXBasePaths::paths_iterator HidingP = Paths.begin(),
00339                                        HidingPEnd = Paths.end();
00340              HidingP != HidingPEnd;
00341              ++HidingP) {
00342           CXXRecordDecl *HidingClass = nullptr;
00343           if (const RecordType *Record
00344                        = HidingP->back().Base->getType()->getAs<RecordType>())
00345             HidingClass = cast<CXXRecordDecl>(Record->getDecl());
00346           if (!HidingClass)
00347             break;
00348 
00349           if (HidingClass->isVirtuallyDerivedFrom(VBase)) {
00350             Hidden = true;
00351             break;
00352           }
00353         }
00354       }
00355     }
00356 
00357     if (Hidden)
00358       P = Paths.Paths.erase(P);
00359     else
00360       ++P;
00361   }
00362   
00363   return true;
00364 }
00365 
00366 bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, 
00367                                   CXXBasePath &Path,
00368                                   void *BaseRecord) {
00369   assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
00370          "User data for FindBaseClass is not canonical!");
00371   return Specifier->getType()->castAs<RecordType>()->getDecl()
00372             ->getCanonicalDecl() == BaseRecord;
00373 }
00374 
00375 bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, 
00376                                          CXXBasePath &Path,
00377                                          void *BaseRecord) {
00378   assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
00379          "User data for FindBaseClass is not canonical!");
00380   return Specifier->isVirtual() &&
00381          Specifier->getType()->castAs<RecordType>()->getDecl()
00382             ->getCanonicalDecl() == BaseRecord;
00383 }
00384 
00385 bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier, 
00386                                   CXXBasePath &Path,
00387                                   void *Name) {
00388   RecordDecl *BaseRecord =
00389     Specifier->getType()->castAs<RecordType>()->getDecl();
00390 
00391   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
00392   for (Path.Decls = BaseRecord->lookup(N);
00393        !Path.Decls.empty();
00394        Path.Decls = Path.Decls.slice(1)) {
00395     if (Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
00396       return true;
00397   }
00398 
00399   return false;
00400 }
00401 
00402 bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier, 
00403                                        CXXBasePath &Path,
00404                                        void *Name) {
00405   RecordDecl *BaseRecord =
00406     Specifier->getType()->castAs<RecordType>()->getDecl();
00407   
00408   const unsigned IDNS = IDNS_Ordinary | IDNS_Tag | IDNS_Member;
00409   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
00410   for (Path.Decls = BaseRecord->lookup(N);
00411        !Path.Decls.empty();
00412        Path.Decls = Path.Decls.slice(1)) {
00413     if (Path.Decls.front()->isInIdentifierNamespace(IDNS))
00414       return true;
00415   }
00416   
00417   return false;
00418 }
00419 
00420 bool CXXRecordDecl::
00421 FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, 
00422                               CXXBasePath &Path,
00423                               void *Name) {
00424   RecordDecl *BaseRecord =
00425     Specifier->getType()->castAs<RecordType>()->getDecl();
00426   
00427   DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
00428   for (Path.Decls = BaseRecord->lookup(N);
00429        !Path.Decls.empty();
00430        Path.Decls = Path.Decls.slice(1)) {
00431     // FIXME: Refactor the "is it a nested-name-specifier?" check
00432     if (isa<TypedefNameDecl>(Path.Decls.front()) ||
00433         Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
00434       return true;
00435   }
00436   
00437   return false;
00438 }
00439 
00440 void OverridingMethods::add(unsigned OverriddenSubobject, 
00441                             UniqueVirtualMethod Overriding) {
00442   SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides
00443     = Overrides[OverriddenSubobject];
00444   if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(), 
00445                 Overriding) == SubobjectOverrides.end())
00446     SubobjectOverrides.push_back(Overriding);
00447 }
00448 
00449 void OverridingMethods::add(const OverridingMethods &Other) {
00450   for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
00451     for (overriding_const_iterator M = I->second.begin(), 
00452                                 MEnd = I->second.end();
00453          M != MEnd; 
00454          ++M)
00455       add(I->first, *M);
00456   }
00457 }
00458 
00459 void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
00460   for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
00461     I->second.clear();
00462     I->second.push_back(Overriding);
00463   }
00464 }
00465 
00466 
00467 namespace {
00468   class FinalOverriderCollector {
00469     /// \brief The number of subobjects of a given class type that
00470     /// occur within the class hierarchy.
00471     llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
00472 
00473     /// \brief Overriders for each virtual base subobject.
00474     llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
00475 
00476     CXXFinalOverriderMap FinalOverriders;
00477 
00478   public:
00479     ~FinalOverriderCollector();
00480 
00481     void Collect(const CXXRecordDecl *RD, bool VirtualBase,
00482                  const CXXRecordDecl *InVirtualSubobject,
00483                  CXXFinalOverriderMap &Overriders);
00484   };
00485 }
00486 
00487 void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, 
00488                                       bool VirtualBase,
00489                                       const CXXRecordDecl *InVirtualSubobject,
00490                                       CXXFinalOverriderMap &Overriders) {
00491   unsigned SubobjectNumber = 0;
00492   if (!VirtualBase)
00493     SubobjectNumber
00494       = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
00495 
00496   for (const auto &Base : RD->bases()) {
00497     if (const RecordType *RT = Base.getType()->getAs<RecordType>()) {
00498       const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
00499       if (!BaseDecl->isPolymorphic())
00500         continue;
00501 
00502       if (Overriders.empty() && !Base.isVirtual()) {
00503         // There are no other overriders of virtual member functions,
00504         // so let the base class fill in our overriders for us.
00505         Collect(BaseDecl, false, InVirtualSubobject, Overriders);
00506         continue;
00507       }
00508 
00509       // Collect all of the overridders from the base class subobject
00510       // and merge them into the set of overridders for this class.
00511       // For virtual base classes, populate or use the cached virtual
00512       // overrides so that we do not walk the virtual base class (and
00513       // its base classes) more than once.
00514       CXXFinalOverriderMap ComputedBaseOverriders;
00515       CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
00516       if (Base.isVirtual()) {
00517         CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
00518         BaseOverriders = MyVirtualOverriders;
00519         if (!MyVirtualOverriders) {
00520           MyVirtualOverriders = new CXXFinalOverriderMap;
00521 
00522           // Collect may cause VirtualOverriders to reallocate, invalidating the
00523           // MyVirtualOverriders reference. Set BaseOverriders to the right
00524           // value now.
00525           BaseOverriders = MyVirtualOverriders;
00526 
00527           Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
00528         }
00529       } else
00530         Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
00531 
00532       // Merge the overriders from this base class into our own set of
00533       // overriders.
00534       for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), 
00535                                OMEnd = BaseOverriders->end();
00536            OM != OMEnd;
00537            ++OM) {
00538         const CXXMethodDecl *CanonOM
00539           = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
00540         Overriders[CanonOM].add(OM->second);
00541       }
00542     }
00543   }
00544 
00545   for (auto *M : RD->methods()) {
00546     // We only care about virtual methods.
00547     if (!M->isVirtual())
00548       continue;
00549 
00550     CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
00551 
00552     if (CanonM->begin_overridden_methods()
00553                                        == CanonM->end_overridden_methods()) {
00554       // This is a new virtual function that does not override any
00555       // other virtual function. Add it to the map of virtual
00556       // functions for which we are tracking overridders. 
00557 
00558       // C++ [class.virtual]p2:
00559       //   For convenience we say that any virtual function overrides itself.
00560       Overriders[CanonM].add(SubobjectNumber,
00561                              UniqueVirtualMethod(CanonM, SubobjectNumber,
00562                                                  InVirtualSubobject));
00563       continue;
00564     }
00565 
00566     // This virtual method overrides other virtual methods, so it does
00567     // not add any new slots into the set of overriders. Instead, we
00568     // replace entries in the set of overriders with the new
00569     // overrider. To do so, we dig down to the original virtual
00570     // functions using data recursion and update all of the methods it
00571     // overrides.
00572     typedef std::pair<CXXMethodDecl::method_iterator, 
00573                       CXXMethodDecl::method_iterator> OverriddenMethods;
00574     SmallVector<OverriddenMethods, 4> Stack;
00575     Stack.push_back(std::make_pair(CanonM->begin_overridden_methods(),
00576                                    CanonM->end_overridden_methods()));
00577     while (!Stack.empty()) {
00578       OverriddenMethods OverMethods = Stack.back();
00579       Stack.pop_back();
00580 
00581       for (; OverMethods.first != OverMethods.second; ++OverMethods.first) {
00582         const CXXMethodDecl *CanonOM
00583           = cast<CXXMethodDecl>((*OverMethods.first)->getCanonicalDecl());
00584 
00585         // C++ [class.virtual]p2:
00586         //   A virtual member function C::vf of a class object S is
00587         //   a final overrider unless the most derived class (1.8)
00588         //   of which S is a base class subobject (if any) declares
00589         //   or inherits another member function that overrides vf.
00590         //
00591         // Treating this object like the most derived class, we
00592         // replace any overrides from base classes with this
00593         // overriding virtual function.
00594         Overriders[CanonOM].replaceAll(
00595                                UniqueVirtualMethod(CanonM, SubobjectNumber,
00596                                                    InVirtualSubobject));
00597 
00598         if (CanonOM->begin_overridden_methods()
00599                                        == CanonOM->end_overridden_methods())
00600           continue;
00601 
00602         // Continue recursion to the methods that this virtual method
00603         // overrides.
00604         Stack.push_back(std::make_pair(CanonOM->begin_overridden_methods(),
00605                                        CanonOM->end_overridden_methods()));
00606       }
00607     }
00608 
00609     // C++ [class.virtual]p2:
00610     //   For convenience we say that any virtual function overrides itself.
00611     Overriders[CanonM].add(SubobjectNumber,
00612                            UniqueVirtualMethod(CanonM, SubobjectNumber,
00613                                                InVirtualSubobject));
00614   }
00615 }
00616 
00617 FinalOverriderCollector::~FinalOverriderCollector() {
00618   for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
00619          VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
00620        VO != VOEnd; 
00621        ++VO)
00622     delete VO->second;
00623 }
00624 
00625 void 
00626 CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
00627   FinalOverriderCollector Collector;
00628   Collector.Collect(this, false, nullptr, FinalOverriders);
00629 
00630   // Weed out any final overriders that come from virtual base class
00631   // subobjects that were hidden by other subobjects along any path.
00632   // This is the final-overrider variant of C++ [class.member.lookup]p10.
00633   for (CXXFinalOverriderMap::iterator OM = FinalOverriders.begin(), 
00634                            OMEnd = FinalOverriders.end();
00635        OM != OMEnd;
00636        ++OM) {
00637     for (OverridingMethods::iterator SO = OM->second.begin(), 
00638                                   SOEnd = OM->second.end();
00639          SO != SOEnd; 
00640          ++SO) {
00641       SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO->second;
00642       if (Overriding.size() < 2)
00643         continue;
00644 
00645       for (SmallVectorImpl<UniqueVirtualMethod>::iterator
00646              Pos = Overriding.begin(), PosEnd = Overriding.end();
00647            Pos != PosEnd;
00648            /* increment in loop */) {
00649         if (!Pos->InVirtualSubobject) {
00650           ++Pos;
00651           continue;
00652         }
00653 
00654         // We have an overriding method in a virtual base class
00655         // subobject (or non-virtual base class subobject thereof);
00656         // determine whether there exists an other overriding method
00657         // in a base class subobject that hides the virtual base class
00658         // subobject.
00659         bool Hidden = false;
00660         for (SmallVectorImpl<UniqueVirtualMethod>::iterator
00661                OP = Overriding.begin(), OPEnd = Overriding.end();
00662              OP != OPEnd && !Hidden; 
00663              ++OP) {
00664           if (Pos == OP)
00665             continue;
00666 
00667           if (OP->Method->getParent()->isVirtuallyDerivedFrom(
00668                          const_cast<CXXRecordDecl *>(Pos->InVirtualSubobject)))
00669             Hidden = true;
00670         }
00671 
00672         if (Hidden) {
00673           // The current overriding function is hidden by another
00674           // overriding function; remove this one.
00675           Pos = Overriding.erase(Pos);
00676           PosEnd = Overriding.end();
00677         } else {
00678           ++Pos;
00679         }
00680       }
00681     }
00682   }
00683 }
00684 
00685 static void 
00686 AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
00687                         CXXIndirectPrimaryBaseSet& Bases) {
00688   // If the record has a virtual primary base class, add it to our set.
00689   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
00690   if (Layout.isPrimaryBaseVirtual())
00691     Bases.insert(Layout.getPrimaryBase());
00692 
00693   for (const auto &I : RD->bases()) {
00694     assert(!I.getType()->isDependentType() &&
00695            "Cannot get indirect primary bases for class with dependent bases.");
00696 
00697     const CXXRecordDecl *BaseDecl =
00698       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
00699 
00700     // Only bases with virtual bases participate in computing the
00701     // indirect primary virtual base classes.
00702     if (BaseDecl->getNumVBases())
00703       AddIndirectPrimaryBases(BaseDecl, Context, Bases);
00704   }
00705 
00706 }
00707 
00708 void 
00709 CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
00710   ASTContext &Context = getASTContext();
00711 
00712   if (!getNumVBases())
00713     return;
00714 
00715   for (const auto &I : bases()) {
00716     assert(!I.getType()->isDependentType() &&
00717            "Cannot get indirect primary bases for class with dependent bases.");
00718 
00719     const CXXRecordDecl *BaseDecl =
00720       cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
00721 
00722     // Only bases with virtual bases participate in computing the
00723     // indirect primary virtual base classes.
00724     if (BaseDecl->getNumVBases())
00725       AddIndirectPrimaryBases(BaseDecl, Context, Bases);
00726   }
00727 }