1 //===------ CXXInheritance.cpp - C++ Inheritance ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides routines that help analyzing C++ inheritance hierarchies.
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/CXXInheritance.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "llvm/ADT/SetVector.h"
21 using namespace clang;
23 /// \brief Computes the set of declarations referenced by these base
25 void CXXBasePaths::ComputeDeclsFound() {
26 assert(NumDeclsFound == 0 && !DeclsFound &&
27 "Already computed the set of declarations");
29 llvm::SetVector<NamedDecl *, SmallVector<NamedDecl *, 8> > Decls;
30 for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
31 Decls.insert(Path->Decls.front());
33 NumDeclsFound = Decls.size();
34 DeclsFound = llvm::make_unique<NamedDecl *[]>(NumDeclsFound);
35 std::copy(Decls.begin(), Decls.end(), DeclsFound.get());
38 CXXBasePaths::decl_range CXXBasePaths::found_decls() {
39 if (NumDeclsFound == 0)
42 return decl_range(decl_iterator(DeclsFound.get()),
43 decl_iterator(DeclsFound.get() + NumDeclsFound));
46 /// isAmbiguous - Determines whether the set of paths provided is
47 /// ambiguous, i.e., there are two or more paths that refer to
48 /// different base class subobjects of the same type. BaseType must be
49 /// an unqualified, canonical class type.
50 bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
51 BaseType = BaseType.getUnqualifiedType();
52 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
53 return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
56 /// clear - Clear out all prior path information.
57 void CXXBasePaths::clear() {
59 ClassSubobjects.clear();
61 DetectedVirtual = nullptr;
64 /// @brief Swaps the contents of this CXXBasePaths structure with the
65 /// contents of Other.
66 void CXXBasePaths::swap(CXXBasePaths &Other) {
67 std::swap(Origin, Other.Origin);
68 Paths.swap(Other.Paths);
69 ClassSubobjects.swap(Other.ClassSubobjects);
70 std::swap(FindAmbiguities, Other.FindAmbiguities);
71 std::swap(RecordPaths, Other.RecordPaths);
72 std::swap(DetectVirtual, Other.DetectVirtual);
73 std::swap(DetectedVirtual, Other.DetectedVirtual);
76 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
77 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
78 /*DetectVirtual=*/false);
79 return isDerivedFrom(Base, Paths);
82 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
83 CXXBasePaths &Paths) const {
84 if (getCanonicalDecl() == Base->getCanonicalDecl())
87 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
89 const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
90 // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
92 [this, BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
93 return FindBaseClass(Specifier, Path, BaseDecl);
98 bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const {
102 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
103 /*DetectVirtual=*/false);
105 if (getCanonicalDecl() == Base->getCanonicalDecl())
108 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
110 const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
111 // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
112 return lookupInBases(
113 [this, BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
114 return FindVirtualBaseClass(Specifier, Path, BaseDecl);
119 bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
120 const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl();
121 return forallBases([TargetDecl](const CXXRecordDecl *Base) {
122 return Base->getCanonicalDecl() != TargetDecl;
127 CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const {
128 assert(isDependentContext());
130 for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
131 if (CurContext->Equals(this))
137 bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches,
138 bool AllowShortCircuit) const {
139 SmallVector<const CXXRecordDecl*, 8> Queue;
141 const CXXRecordDecl *Record = this;
142 bool AllMatches = true;
144 for (const auto &I : Record->bases()) {
145 const RecordType *Ty = I.getType()->getAs<RecordType>();
147 if (AllowShortCircuit) return false;
152 CXXRecordDecl *Base =
153 cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
155 (Base->isDependentContext() &&
156 !Base->isCurrentInstantiation(Record))) {
157 if (AllowShortCircuit) return false;
162 Queue.push_back(Base);
163 if (!BaseMatches(Base)) {
164 if (AllowShortCircuit) return false;
172 Record = Queue.pop_back_val(); // not actually a queue.
178 bool CXXBasePaths::lookupInBases(
179 ASTContext &Context, const CXXRecordDecl *Record,
180 CXXRecordDecl::BaseMatchesCallback BaseMatches) {
181 bool FoundPath = false;
183 // The access of the path down to this record.
184 AccessSpecifier AccessToHere = ScratchPath.Access;
185 bool IsFirstStep = ScratchPath.empty();
187 for (const auto &BaseSpec : Record->bases()) {
188 // Find the record of the base class subobjects for this type.
190 Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType();
193 // In the definition of a class template or a member of a class template,
194 // if a base class of the class template depends on a template-parameter,
195 // the base class scope is not examined during unqualified name lookup
196 // either at the point of definition of the class template or member or
197 // during an instantiation of the class tem- plate or member.
198 if (BaseType->isDependentType())
201 // Determine whether we need to visit this base class at all,
202 // updating the count of subobjects appropriately.
203 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
204 bool VisitBase = true;
205 bool SetVirtual = false;
206 if (BaseSpec.isVirtual()) {
207 VisitBase = !Subobjects.first;
208 Subobjects.first = true;
209 if (isDetectingVirtual() && DetectedVirtual == nullptr) {
210 // If this is the first virtual we find, remember it. If it turns out
211 // there is no base path here, we'll reset it later.
212 DetectedVirtual = BaseType->getAs<RecordType>();
218 if (isRecordingPaths()) {
219 // Add this base specifier to the current path.
220 CXXBasePathElement Element;
221 Element.Base = &BaseSpec;
222 Element.Class = Record;
223 if (BaseSpec.isVirtual())
224 Element.SubobjectNumber = 0;
226 Element.SubobjectNumber = Subobjects.second;
227 ScratchPath.push_back(Element);
229 // Calculate the "top-down" access to this base class.
230 // The spec actually describes this bottom-up, but top-down is
231 // equivalent because the definition works out as follows:
232 // 1. Write down the access along each step in the inheritance
233 // chain, followed by the access of the decl itself.
235 // class A { public: int foo; };
236 // class B : protected A {};
237 // class C : public B {};
238 // class D : private C {};
240 // private public protected public
241 // 2. If 'private' appears anywhere except far-left, access is denied.
242 // 3. Otherwise, overall access is determined by the most restrictive
243 // access in the sequence.
245 ScratchPath.Access = BaseSpec.getAccessSpecifier();
247 ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
248 BaseSpec.getAccessSpecifier());
251 // Track whether there's a path involving this specific base.
252 bool FoundPathThroughBase = false;
254 if (BaseMatches(&BaseSpec, ScratchPath)) {
255 // We've found a path that terminates at this base.
256 FoundPath = FoundPathThroughBase = true;
257 if (isRecordingPaths()) {
258 // We have a path. Make a copy of it before moving on.
259 Paths.push_back(ScratchPath);
260 } else if (!isFindingAmbiguities()) {
261 // We found a path and we don't care about ambiguities;
262 // return immediately.
265 } else if (VisitBase) {
266 CXXRecordDecl *BaseRecord
267 = cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>()
269 if (lookupInBases(Context, BaseRecord, BaseMatches)) {
270 // C++ [class.member.lookup]p2:
271 // A member name f in one sub-object B hides a member name f in
272 // a sub-object A if A is a base class sub-object of B. Any
273 // declarations that are so hidden are eliminated from
276 // There is a path to a base class that meets the criteria. If we're
277 // not collecting paths or finding ambiguities, we're done.
278 FoundPath = FoundPathThroughBase = true;
279 if (!isFindingAmbiguities())
284 // Pop this base specifier off the current path (if we're
285 // collecting paths).
286 if (isRecordingPaths()) {
287 ScratchPath.pop_back();
290 // If we set a virtual earlier, and this isn't a path, forget it again.
291 if (SetVirtual && !FoundPathThroughBase) {
292 DetectedVirtual = nullptr;
296 // Reset the scratch path access.
297 ScratchPath.Access = AccessToHere;
302 bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches,
303 CXXBasePaths &Paths) const {
304 // If we didn't find anything, report that.
305 if (!Paths.lookupInBases(getASTContext(), this, BaseMatches))
308 // If we're not recording paths or we won't ever find ambiguities,
310 if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
313 // C++ [class.member.lookup]p6:
314 // When virtual base classes are used, a hidden declaration can be
315 // reached along a path through the sub-object lattice that does
316 // not pass through the hiding declaration. This is not an
317 // ambiguity. The identical use with nonvirtual base classes is an
318 // ambiguity; in that case there is no unique instance of the name
319 // that hides all the others.
321 // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
322 // way to make it any faster.
323 Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) {
324 for (const CXXBasePathElement &PE : Path) {
325 if (!PE.Base->isVirtual())
328 CXXRecordDecl *VBase = nullptr;
329 if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>())
330 VBase = cast<CXXRecordDecl>(Record->getDecl());
334 // The declaration(s) we found along this path were found in a
335 // subobject of a virtual base. Check whether this virtual
336 // base is a subobject of any other path; if so, then the
337 // declaration in this path are hidden by that patch.
338 for (const CXXBasePath &HidingP : Paths) {
339 CXXRecordDecl *HidingClass = nullptr;
340 if (const RecordType *Record =
341 HidingP.back().Base->getType()->getAs<RecordType>())
342 HidingClass = cast<CXXRecordDecl>(Record->getDecl());
346 if (HidingClass->isVirtuallyDerivedFrom(VBase))
356 bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier,
358 const CXXRecordDecl *BaseRecord) {
359 assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
360 "User data for FindBaseClass is not canonical!");
361 return Specifier->getType()->castAs<RecordType>()->getDecl()
362 ->getCanonicalDecl() == BaseRecord;
365 bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
367 const CXXRecordDecl *BaseRecord) {
368 assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
369 "User data for FindBaseClass is not canonical!");
370 return Specifier->isVirtual() &&
371 Specifier->getType()->castAs<RecordType>()->getDecl()
372 ->getCanonicalDecl() == BaseRecord;
375 bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier,
377 DeclarationName Name) {
378 RecordDecl *BaseRecord =
379 Specifier->getType()->castAs<RecordType>()->getDecl();
381 for (Path.Decls = BaseRecord->lookup(Name);
383 Path.Decls = Path.Decls.slice(1)) {
384 if (Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
391 bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
393 DeclarationName Name) {
394 RecordDecl *BaseRecord =
395 Specifier->getType()->castAs<RecordType>()->getDecl();
397 const unsigned IDNS = IDNS_Ordinary | IDNS_Tag | IDNS_Member;
398 for (Path.Decls = BaseRecord->lookup(Name);
400 Path.Decls = Path.Decls.slice(1)) {
401 if (Path.Decls.front()->isInIdentifierNamespace(IDNS))
409 FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
411 DeclarationName Name) {
412 RecordDecl *BaseRecord =
413 Specifier->getType()->castAs<RecordType>()->getDecl();
415 for (Path.Decls = BaseRecord->lookup(Name);
417 Path.Decls = Path.Decls.slice(1)) {
418 // FIXME: Refactor the "is it a nested-name-specifier?" check
419 if (isa<TypedefNameDecl>(Path.Decls.front()) ||
420 Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
427 void OverridingMethods::add(unsigned OverriddenSubobject,
428 UniqueVirtualMethod Overriding) {
429 SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides
430 = Overrides[OverriddenSubobject];
431 if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(),
432 Overriding) == SubobjectOverrides.end())
433 SubobjectOverrides.push_back(Overriding);
436 void OverridingMethods::add(const OverridingMethods &Other) {
437 for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
438 for (overriding_const_iterator M = I->second.begin(),
439 MEnd = I->second.end();
446 void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
447 for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
449 I->second.push_back(Overriding);
455 class FinalOverriderCollector {
456 /// \brief The number of subobjects of a given class type that
457 /// occur within the class hierarchy.
458 llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
460 /// \brief Overriders for each virtual base subobject.
461 llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
463 CXXFinalOverriderMap FinalOverriders;
466 ~FinalOverriderCollector();
468 void Collect(const CXXRecordDecl *RD, bool VirtualBase,
469 const CXXRecordDecl *InVirtualSubobject,
470 CXXFinalOverriderMap &Overriders);
474 void FinalOverriderCollector::Collect(const CXXRecordDecl *RD,
476 const CXXRecordDecl *InVirtualSubobject,
477 CXXFinalOverriderMap &Overriders) {
478 unsigned SubobjectNumber = 0;
481 = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
483 for (const auto &Base : RD->bases()) {
484 if (const RecordType *RT = Base.getType()->getAs<RecordType>()) {
485 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
486 if (!BaseDecl->isPolymorphic())
489 if (Overriders.empty() && !Base.isVirtual()) {
490 // There are no other overriders of virtual member functions,
491 // so let the base class fill in our overriders for us.
492 Collect(BaseDecl, false, InVirtualSubobject, Overriders);
496 // Collect all of the overridders from the base class subobject
497 // and merge them into the set of overridders for this class.
498 // For virtual base classes, populate or use the cached virtual
499 // overrides so that we do not walk the virtual base class (and
500 // its base classes) more than once.
501 CXXFinalOverriderMap ComputedBaseOverriders;
502 CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
503 if (Base.isVirtual()) {
504 CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
505 BaseOverriders = MyVirtualOverriders;
506 if (!MyVirtualOverriders) {
507 MyVirtualOverriders = new CXXFinalOverriderMap;
509 // Collect may cause VirtualOverriders to reallocate, invalidating the
510 // MyVirtualOverriders reference. Set BaseOverriders to the right
512 BaseOverriders = MyVirtualOverriders;
514 Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
517 Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
519 // Merge the overriders from this base class into our own set of
521 for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(),
522 OMEnd = BaseOverriders->end();
525 const CXXMethodDecl *CanonOM
526 = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
527 Overriders[CanonOM].add(OM->second);
532 for (auto *M : RD->methods()) {
533 // We only care about virtual methods.
537 CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
539 if (CanonM->begin_overridden_methods()
540 == CanonM->end_overridden_methods()) {
541 // This is a new virtual function that does not override any
542 // other virtual function. Add it to the map of virtual
543 // functions for which we are tracking overridders.
545 // C++ [class.virtual]p2:
546 // For convenience we say that any virtual function overrides itself.
547 Overriders[CanonM].add(SubobjectNumber,
548 UniqueVirtualMethod(CanonM, SubobjectNumber,
549 InVirtualSubobject));
553 // This virtual method overrides other virtual methods, so it does
554 // not add any new slots into the set of overriders. Instead, we
555 // replace entries in the set of overriders with the new
556 // overrider. To do so, we dig down to the original virtual
557 // functions using data recursion and update all of the methods it
559 typedef llvm::iterator_range<CXXMethodDecl::method_iterator>
561 SmallVector<OverriddenMethods, 4> Stack;
562 Stack.push_back(llvm::make_range(CanonM->begin_overridden_methods(),
563 CanonM->end_overridden_methods()));
564 while (!Stack.empty()) {
565 for (const CXXMethodDecl *OM : Stack.pop_back_val()) {
566 const CXXMethodDecl *CanonOM = OM->getCanonicalDecl();
568 // C++ [class.virtual]p2:
569 // A virtual member function C::vf of a class object S is
570 // a final overrider unless the most derived class (1.8)
571 // of which S is a base class subobject (if any) declares
572 // or inherits another member function that overrides vf.
574 // Treating this object like the most derived class, we
575 // replace any overrides from base classes with this
576 // overriding virtual function.
577 Overriders[CanonOM].replaceAll(
578 UniqueVirtualMethod(CanonM, SubobjectNumber,
579 InVirtualSubobject));
581 if (CanonOM->begin_overridden_methods()
582 == CanonOM->end_overridden_methods())
585 // Continue recursion to the methods that this virtual method
587 Stack.push_back(llvm::make_range(CanonOM->begin_overridden_methods(),
588 CanonOM->end_overridden_methods()));
592 // C++ [class.virtual]p2:
593 // For convenience we say that any virtual function overrides itself.
594 Overriders[CanonM].add(SubobjectNumber,
595 UniqueVirtualMethod(CanonM, SubobjectNumber,
596 InVirtualSubobject));
600 FinalOverriderCollector::~FinalOverriderCollector() {
601 for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
602 VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
609 CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
610 FinalOverriderCollector Collector;
611 Collector.Collect(this, false, nullptr, FinalOverriders);
613 // Weed out any final overriders that come from virtual base class
614 // subobjects that were hidden by other subobjects along any path.
615 // This is the final-overrider variant of C++ [class.member.lookup]p10.
616 for (auto &OM : FinalOverriders) {
617 for (auto &SO : OM.second) {
618 SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second;
619 if (Overriding.size() < 2)
622 auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) {
623 if (!M.InVirtualSubobject)
626 // We have an overriding method in a virtual base class
627 // subobject (or non-virtual base class subobject thereof);
628 // determine whether there exists an other overriding method
629 // in a base class subobject that hides the virtual base class
631 for (const UniqueVirtualMethod &OP : Overriding)
633 OP.Method->getParent()->isVirtuallyDerivedFrom(
634 M.InVirtualSubobject))
640 std::remove_if(Overriding.begin(), Overriding.end(), IsHidden),
647 AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
648 CXXIndirectPrimaryBaseSet& Bases) {
649 // If the record has a virtual primary base class, add it to our set.
650 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
651 if (Layout.isPrimaryBaseVirtual())
652 Bases.insert(Layout.getPrimaryBase());
654 for (const auto &I : RD->bases()) {
655 assert(!I.getType()->isDependentType() &&
656 "Cannot get indirect primary bases for class with dependent bases.");
658 const CXXRecordDecl *BaseDecl =
659 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
661 // Only bases with virtual bases participate in computing the
662 // indirect primary virtual base classes.
663 if (BaseDecl->getNumVBases())
664 AddIndirectPrimaryBases(BaseDecl, Context, Bases);
670 CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
671 ASTContext &Context = getASTContext();
676 for (const auto &I : bases()) {
677 assert(!I.getType()->isDependentType() &&
678 "Cannot get indirect primary bases for class with dependent bases.");
680 const CXXRecordDecl *BaseDecl =
681 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
683 // Only bases with virtual bases participate in computing the
684 // indirect primary virtual base classes.
685 if (BaseDecl->getNumVBases())
686 AddIndirectPrimaryBases(BaseDecl, Context, Bases);