1 //===- CXXInheritance.cpp - C++ Inheritance -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides routines that help analyzing C++ inheritance hierarchies. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/CXXInheritance.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/Decl.h" 16 #include "clang/AST/DeclBase.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/RecordLayout.h" 20 #include "clang/AST/TemplateName.h" 21 #include "clang/AST/Type.h" 22 #include "clang/Basic/LLVM.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SetVector.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/iterator_range.h" 28 #include "llvm/Support/Casting.h" 29 #include <algorithm> 30 #include <utility> 31 #include <cassert> 32 #include <vector> 33 34 using namespace clang; 35 36 /// Computes the set of declarations referenced by these base 37 /// paths. 38 void CXXBasePaths::ComputeDeclsFound() { 39 assert(NumDeclsFound == 0 && !DeclsFound && 40 "Already computed the set of declarations"); 41 42 llvm::SmallSetVector<NamedDecl *, 8> Decls; 43 for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path) 44 Decls.insert(Path->Decls.front()); 45 46 NumDeclsFound = Decls.size(); 47 DeclsFound = std::make_unique<NamedDecl *[]>(NumDeclsFound); 48 std::copy(Decls.begin(), Decls.end(), DeclsFound.get()); 49 } 50 51 CXXBasePaths::decl_range CXXBasePaths::found_decls() { 52 if (NumDeclsFound == 0) 53 ComputeDeclsFound(); 54 55 return decl_range(decl_iterator(DeclsFound.get()), 56 decl_iterator(DeclsFound.get() + NumDeclsFound)); 57 } 58 59 /// isAmbiguous - Determines whether the set of paths provided is 60 /// ambiguous, i.e., there are two or more paths that refer to 61 /// different base class subobjects of the same type. BaseType must be 62 /// an unqualified, canonical class type. 63 bool CXXBasePaths::isAmbiguous(CanQualType BaseType) { 64 BaseType = BaseType.getUnqualifiedType(); 65 IsVirtBaseAndNumberNonVirtBases Subobjects = ClassSubobjects[BaseType]; 66 return Subobjects.NumberOfNonVirtBases + (Subobjects.IsVirtBase ? 1 : 0) > 1; 67 } 68 69 /// clear - Clear out all prior path information. 70 void CXXBasePaths::clear() { 71 Paths.clear(); 72 ClassSubobjects.clear(); 73 VisitedDependentRecords.clear(); 74 ScratchPath.clear(); 75 DetectedVirtual = nullptr; 76 } 77 78 /// Swaps the contents of this CXXBasePaths structure with the 79 /// contents of Other. 80 void CXXBasePaths::swap(CXXBasePaths &Other) { 81 std::swap(Origin, Other.Origin); 82 Paths.swap(Other.Paths); 83 ClassSubobjects.swap(Other.ClassSubobjects); 84 VisitedDependentRecords.swap(Other.VisitedDependentRecords); 85 std::swap(FindAmbiguities, Other.FindAmbiguities); 86 std::swap(RecordPaths, Other.RecordPaths); 87 std::swap(DetectVirtual, Other.DetectVirtual); 88 std::swap(DetectedVirtual, Other.DetectedVirtual); 89 } 90 91 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const { 92 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false, 93 /*DetectVirtual=*/false); 94 return isDerivedFrom(Base, Paths); 95 } 96 97 bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base, 98 CXXBasePaths &Paths) const { 99 if (getCanonicalDecl() == Base->getCanonicalDecl()) 100 return false; 101 102 Paths.setOrigin(const_cast<CXXRecordDecl*>(this)); 103 104 const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); 105 return lookupInBases( 106 [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 107 return FindBaseClass(Specifier, Path, BaseDecl); 108 }, 109 Paths); 110 } 111 112 bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const { 113 if (!getNumVBases()) 114 return false; 115 116 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false, 117 /*DetectVirtual=*/false); 118 119 if (getCanonicalDecl() == Base->getCanonicalDecl()) 120 return false; 121 122 Paths.setOrigin(const_cast<CXXRecordDecl*>(this)); 123 124 const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); 125 return lookupInBases( 126 [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 127 return FindVirtualBaseClass(Specifier, Path, BaseDecl); 128 }, 129 Paths); 130 } 131 132 bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const { 133 const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl(); 134 return forallBases([TargetDecl](const CXXRecordDecl *Base) { 135 return Base->getCanonicalDecl() != TargetDecl; 136 }); 137 } 138 139 bool 140 CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const { 141 assert(isDependentContext()); 142 143 for (; !CurContext->isFileContext(); CurContext = CurContext->getParent()) 144 if (CurContext->Equals(this)) 145 return true; 146 147 return false; 148 } 149 150 bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches) const { 151 SmallVector<const CXXRecordDecl*, 8> Queue; 152 153 const CXXRecordDecl *Record = this; 154 while (true) { 155 for (const auto &I : Record->bases()) { 156 const RecordType *Ty = I.getType()->getAs<RecordType>(); 157 if (!Ty) 158 return false; 159 160 CXXRecordDecl *Base = 161 cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition()); 162 if (!Base || 163 (Base->isDependentContext() && 164 !Base->isCurrentInstantiation(Record))) { 165 return false; 166 } 167 168 Queue.push_back(Base); 169 if (!BaseMatches(Base)) 170 return false; 171 } 172 173 if (Queue.empty()) 174 break; 175 Record = Queue.pop_back_val(); // not actually a queue. 176 } 177 178 return true; 179 } 180 181 bool CXXBasePaths::lookupInBases(ASTContext &Context, 182 const CXXRecordDecl *Record, 183 CXXRecordDecl::BaseMatchesCallback BaseMatches, 184 bool LookupInDependent) { 185 bool FoundPath = false; 186 187 // The access of the path down to this record. 188 AccessSpecifier AccessToHere = ScratchPath.Access; 189 bool IsFirstStep = ScratchPath.empty(); 190 191 for (const auto &BaseSpec : Record->bases()) { 192 // Find the record of the base class subobjects for this type. 193 QualType BaseType = 194 Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); 195 196 // C++ [temp.dep]p3: 197 // In the definition of a class template or a member of a class template, 198 // if a base class of the class template depends on a template-parameter, 199 // the base class scope is not examined during unqualified name lookup 200 // either at the point of definition of the class template or member or 201 // during an instantiation of the class tem- plate or member. 202 if (!LookupInDependent && BaseType->isDependentType()) 203 continue; 204 205 // Determine whether we need to visit this base class at all, 206 // updating the count of subobjects appropriately. 207 IsVirtBaseAndNumberNonVirtBases &Subobjects = ClassSubobjects[BaseType]; 208 bool VisitBase = true; 209 bool SetVirtual = false; 210 if (BaseSpec.isVirtual()) { 211 VisitBase = !Subobjects.IsVirtBase; 212 Subobjects.IsVirtBase = true; 213 if (isDetectingVirtual() && DetectedVirtual == nullptr) { 214 // If this is the first virtual we find, remember it. If it turns out 215 // there is no base path here, we'll reset it later. 216 DetectedVirtual = BaseType->getAs<RecordType>(); 217 SetVirtual = true; 218 } 219 } else { 220 ++Subobjects.NumberOfNonVirtBases; 221 } 222 if (isRecordingPaths()) { 223 // Add this base specifier to the current path. 224 CXXBasePathElement Element; 225 Element.Base = &BaseSpec; 226 Element.Class = Record; 227 if (BaseSpec.isVirtual()) 228 Element.SubobjectNumber = 0; 229 else 230 Element.SubobjectNumber = Subobjects.NumberOfNonVirtBases; 231 ScratchPath.push_back(Element); 232 233 // Calculate the "top-down" access to this base class. 234 // The spec actually describes this bottom-up, but top-down is 235 // equivalent because the definition works out as follows: 236 // 1. Write down the access along each step in the inheritance 237 // chain, followed by the access of the decl itself. 238 // For example, in 239 // class A { public: int foo; }; 240 // class B : protected A {}; 241 // class C : public B {}; 242 // class D : private C {}; 243 // we would write: 244 // private public protected public 245 // 2. If 'private' appears anywhere except far-left, access is denied. 246 // 3. Otherwise, overall access is determined by the most restrictive 247 // access in the sequence. 248 if (IsFirstStep) 249 ScratchPath.Access = BaseSpec.getAccessSpecifier(); 250 else 251 ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, 252 BaseSpec.getAccessSpecifier()); 253 } 254 255 // Track whether there's a path involving this specific base. 256 bool FoundPathThroughBase = false; 257 258 if (BaseMatches(&BaseSpec, ScratchPath)) { 259 // We've found a path that terminates at this base. 260 FoundPath = FoundPathThroughBase = true; 261 if (isRecordingPaths()) { 262 // We have a path. Make a copy of it before moving on. 263 Paths.push_back(ScratchPath); 264 } else if (!isFindingAmbiguities()) { 265 // We found a path and we don't care about ambiguities; 266 // return immediately. 267 return FoundPath; 268 } 269 } else if (VisitBase) { 270 CXXRecordDecl *BaseRecord; 271 if (LookupInDependent) { 272 BaseRecord = nullptr; 273 const TemplateSpecializationType *TST = 274 BaseSpec.getType()->getAs<TemplateSpecializationType>(); 275 if (!TST) { 276 if (auto *RT = BaseSpec.getType()->getAs<RecordType>()) 277 BaseRecord = cast<CXXRecordDecl>(RT->getDecl()); 278 } else { 279 TemplateName TN = TST->getTemplateName(); 280 if (auto *TD = 281 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) 282 BaseRecord = TD->getTemplatedDecl(); 283 } 284 if (BaseRecord) { 285 if (!BaseRecord->hasDefinition() || 286 VisitedDependentRecords.count(BaseRecord)) { 287 BaseRecord = nullptr; 288 } else { 289 VisitedDependentRecords.insert(BaseRecord); 290 } 291 } 292 } else { 293 BaseRecord = cast<CXXRecordDecl>( 294 BaseSpec.getType()->castAs<RecordType>()->getDecl()); 295 } 296 if (BaseRecord && 297 lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) { 298 // C++ [class.member.lookup]p2: 299 // A member name f in one sub-object B hides a member name f in 300 // a sub-object A if A is a base class sub-object of B. Any 301 // declarations that are so hidden are eliminated from 302 // consideration. 303 304 // There is a path to a base class that meets the criteria. If we're 305 // not collecting paths or finding ambiguities, we're done. 306 FoundPath = FoundPathThroughBase = true; 307 if (!isFindingAmbiguities()) 308 return FoundPath; 309 } 310 } 311 312 // Pop this base specifier off the current path (if we're 313 // collecting paths). 314 if (isRecordingPaths()) { 315 ScratchPath.pop_back(); 316 } 317 318 // If we set a virtual earlier, and this isn't a path, forget it again. 319 if (SetVirtual && !FoundPathThroughBase) { 320 DetectedVirtual = nullptr; 321 } 322 } 323 324 // Reset the scratch path access. 325 ScratchPath.Access = AccessToHere; 326 327 return FoundPath; 328 } 329 330 bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches, 331 CXXBasePaths &Paths, 332 bool LookupInDependent) const { 333 // If we didn't find anything, report that. 334 if (!Paths.lookupInBases(getASTContext(), this, BaseMatches, 335 LookupInDependent)) 336 return false; 337 338 // If we're not recording paths or we won't ever find ambiguities, 339 // we're done. 340 if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities()) 341 return true; 342 343 // C++ [class.member.lookup]p6: 344 // When virtual base classes are used, a hidden declaration can be 345 // reached along a path through the sub-object lattice that does 346 // not pass through the hiding declaration. This is not an 347 // ambiguity. The identical use with nonvirtual base classes is an 348 // ambiguity; in that case there is no unique instance of the name 349 // that hides all the others. 350 // 351 // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy 352 // way to make it any faster. 353 Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) { 354 for (const CXXBasePathElement &PE : Path) { 355 if (!PE.Base->isVirtual()) 356 continue; 357 358 CXXRecordDecl *VBase = nullptr; 359 if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>()) 360 VBase = cast<CXXRecordDecl>(Record->getDecl()); 361 if (!VBase) 362 break; 363 364 // The declaration(s) we found along this path were found in a 365 // subobject of a virtual base. Check whether this virtual 366 // base is a subobject of any other path; if so, then the 367 // declaration in this path are hidden by that patch. 368 for (const CXXBasePath &HidingP : Paths) { 369 CXXRecordDecl *HidingClass = nullptr; 370 if (const RecordType *Record = 371 HidingP.back().Base->getType()->getAs<RecordType>()) 372 HidingClass = cast<CXXRecordDecl>(Record->getDecl()); 373 if (!HidingClass) 374 break; 375 376 if (HidingClass->isVirtuallyDerivedFrom(VBase)) 377 return true; 378 } 379 } 380 return false; 381 }); 382 383 return true; 384 } 385 386 bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, 387 CXXBasePath &Path, 388 const CXXRecordDecl *BaseRecord) { 389 assert(BaseRecord->getCanonicalDecl() == BaseRecord && 390 "User data for FindBaseClass is not canonical!"); 391 return Specifier->getType()->castAs<RecordType>()->getDecl() 392 ->getCanonicalDecl() == BaseRecord; 393 } 394 395 bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, 396 CXXBasePath &Path, 397 const CXXRecordDecl *BaseRecord) { 398 assert(BaseRecord->getCanonicalDecl() == BaseRecord && 399 "User data for FindBaseClass is not canonical!"); 400 return Specifier->isVirtual() && 401 Specifier->getType()->castAs<RecordType>()->getDecl() 402 ->getCanonicalDecl() == BaseRecord; 403 } 404 405 static bool isOrdinaryMember(const NamedDecl *ND) { 406 return ND->isInIdentifierNamespace(Decl::IDNS_Ordinary | Decl::IDNS_Tag | 407 Decl::IDNS_Member); 408 } 409 410 static bool findOrdinaryMember(const CXXRecordDecl *RD, CXXBasePath &Path, 411 DeclarationName Name) { 412 Path.Decls = RD->lookup(Name); 413 for (NamedDecl *ND : Path.Decls) 414 if (isOrdinaryMember(ND)) 415 return true; 416 417 return false; 418 } 419 420 bool CXXRecordDecl::hasMemberName(DeclarationName Name) const { 421 CXXBasePath P; 422 if (findOrdinaryMember(this, P, Name)) 423 return true; 424 425 CXXBasePaths Paths(false, false, false); 426 return lookupInBases( 427 [Name](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 428 return findOrdinaryMember(Specifier->getType()->getAsCXXRecordDecl(), 429 Path, Name); 430 }, 431 Paths); 432 } 433 434 static bool 435 findOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, 436 CXXBasePath &Path, DeclarationName Name) { 437 const TemplateSpecializationType *TST = 438 Specifier->getType()->getAs<TemplateSpecializationType>(); 439 if (!TST) { 440 auto *RT = Specifier->getType()->getAs<RecordType>(); 441 if (!RT) 442 return false; 443 return findOrdinaryMember(cast<CXXRecordDecl>(RT->getDecl()), Path, Name); 444 } 445 TemplateName TN = TST->getTemplateName(); 446 const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); 447 if (!TD) 448 return false; 449 CXXRecordDecl *RD = TD->getTemplatedDecl(); 450 if (!RD) 451 return false; 452 return findOrdinaryMember(RD, Path, Name); 453 } 454 455 std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName( 456 DeclarationName Name, 457 llvm::function_ref<bool(const NamedDecl *ND)> Filter) { 458 std::vector<const NamedDecl *> Results; 459 // Lookup in the class. 460 bool AnyOrdinaryMembers = false; 461 for (const NamedDecl *ND : lookup(Name)) { 462 if (isOrdinaryMember(ND)) 463 AnyOrdinaryMembers = true; 464 if (Filter(ND)) 465 Results.push_back(ND); 466 } 467 if (AnyOrdinaryMembers) 468 return Results; 469 470 // Perform lookup into our base classes. 471 CXXBasePaths Paths; 472 Paths.setOrigin(this); 473 if (!lookupInBases( 474 [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 475 return findOrdinaryMemberInDependentClasses(Specifier, Path, Name); 476 }, 477 Paths, /*LookupInDependent=*/true)) 478 return Results; 479 for (const NamedDecl *ND : Paths.front().Decls) { 480 if (isOrdinaryMember(ND) && Filter(ND)) 481 Results.push_back(ND); 482 } 483 return Results; 484 } 485 486 void OverridingMethods::add(unsigned OverriddenSubobject, 487 UniqueVirtualMethod Overriding) { 488 SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides 489 = Overrides[OverriddenSubobject]; 490 if (llvm::find(SubobjectOverrides, Overriding) == SubobjectOverrides.end()) 491 SubobjectOverrides.push_back(Overriding); 492 } 493 494 void OverridingMethods::add(const OverridingMethods &Other) { 495 for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) { 496 for (overriding_const_iterator M = I->second.begin(), 497 MEnd = I->second.end(); 498 M != MEnd; 499 ++M) 500 add(I->first, *M); 501 } 502 } 503 504 void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) { 505 for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) { 506 I->second.clear(); 507 I->second.push_back(Overriding); 508 } 509 } 510 511 namespace { 512 513 class FinalOverriderCollector { 514 /// The number of subobjects of a given class type that 515 /// occur within the class hierarchy. 516 llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount; 517 518 /// Overriders for each virtual base subobject. 519 llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders; 520 521 CXXFinalOverriderMap FinalOverriders; 522 523 public: 524 ~FinalOverriderCollector(); 525 526 void Collect(const CXXRecordDecl *RD, bool VirtualBase, 527 const CXXRecordDecl *InVirtualSubobject, 528 CXXFinalOverriderMap &Overriders); 529 }; 530 531 } // namespace 532 533 void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, 534 bool VirtualBase, 535 const CXXRecordDecl *InVirtualSubobject, 536 CXXFinalOverriderMap &Overriders) { 537 unsigned SubobjectNumber = 0; 538 if (!VirtualBase) 539 SubobjectNumber 540 = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())]; 541 542 for (const auto &Base : RD->bases()) { 543 if (const RecordType *RT = Base.getType()->getAs<RecordType>()) { 544 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 545 if (!BaseDecl->isPolymorphic()) 546 continue; 547 548 if (Overriders.empty() && !Base.isVirtual()) { 549 // There are no other overriders of virtual member functions, 550 // so let the base class fill in our overriders for us. 551 Collect(BaseDecl, false, InVirtualSubobject, Overriders); 552 continue; 553 } 554 555 // Collect all of the overridders from the base class subobject 556 // and merge them into the set of overridders for this class. 557 // For virtual base classes, populate or use the cached virtual 558 // overrides so that we do not walk the virtual base class (and 559 // its base classes) more than once. 560 CXXFinalOverriderMap ComputedBaseOverriders; 561 CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders; 562 if (Base.isVirtual()) { 563 CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl]; 564 BaseOverriders = MyVirtualOverriders; 565 if (!MyVirtualOverriders) { 566 MyVirtualOverriders = new CXXFinalOverriderMap; 567 568 // Collect may cause VirtualOverriders to reallocate, invalidating the 569 // MyVirtualOverriders reference. Set BaseOverriders to the right 570 // value now. 571 BaseOverriders = MyVirtualOverriders; 572 573 Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders); 574 } 575 } else 576 Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders); 577 578 // Merge the overriders from this base class into our own set of 579 // overriders. 580 for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), 581 OMEnd = BaseOverriders->end(); 582 OM != OMEnd; 583 ++OM) { 584 const CXXMethodDecl *CanonOM = OM->first->getCanonicalDecl(); 585 Overriders[CanonOM].add(OM->second); 586 } 587 } 588 } 589 590 for (auto *M : RD->methods()) { 591 // We only care about virtual methods. 592 if (!M->isVirtual()) 593 continue; 594 595 CXXMethodDecl *CanonM = M->getCanonicalDecl(); 596 using OverriddenMethodsRange = 597 llvm::iterator_range<CXXMethodDecl::method_iterator>; 598 OverriddenMethodsRange OverriddenMethods = CanonM->overridden_methods(); 599 600 if (OverriddenMethods.begin() == OverriddenMethods.end()) { 601 // This is a new virtual function that does not override any 602 // other virtual function. Add it to the map of virtual 603 // functions for which we are tracking overridders. 604 605 // C++ [class.virtual]p2: 606 // For convenience we say that any virtual function overrides itself. 607 Overriders[CanonM].add(SubobjectNumber, 608 UniqueVirtualMethod(CanonM, SubobjectNumber, 609 InVirtualSubobject)); 610 continue; 611 } 612 613 // This virtual method overrides other virtual methods, so it does 614 // not add any new slots into the set of overriders. Instead, we 615 // replace entries in the set of overriders with the new 616 // overrider. To do so, we dig down to the original virtual 617 // functions using data recursion and update all of the methods it 618 // overrides. 619 SmallVector<OverriddenMethodsRange, 4> Stack(1, OverriddenMethods); 620 while (!Stack.empty()) { 621 for (const CXXMethodDecl *OM : Stack.pop_back_val()) { 622 const CXXMethodDecl *CanonOM = OM->getCanonicalDecl(); 623 624 // C++ [class.virtual]p2: 625 // A virtual member function C::vf of a class object S is 626 // a final overrider unless the most derived class (1.8) 627 // of which S is a base class subobject (if any) declares 628 // or inherits another member function that overrides vf. 629 // 630 // Treating this object like the most derived class, we 631 // replace any overrides from base classes with this 632 // overriding virtual function. 633 Overriders[CanonOM].replaceAll( 634 UniqueVirtualMethod(CanonM, SubobjectNumber, 635 InVirtualSubobject)); 636 637 auto OverriddenMethods = CanonOM->overridden_methods(); 638 if (OverriddenMethods.begin() == OverriddenMethods.end()) 639 continue; 640 641 // Continue recursion to the methods that this virtual method 642 // overrides. 643 Stack.push_back(OverriddenMethods); 644 } 645 } 646 647 // C++ [class.virtual]p2: 648 // For convenience we say that any virtual function overrides itself. 649 Overriders[CanonM].add(SubobjectNumber, 650 UniqueVirtualMethod(CanonM, SubobjectNumber, 651 InVirtualSubobject)); 652 } 653 } 654 655 FinalOverriderCollector::~FinalOverriderCollector() { 656 for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator 657 VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end(); 658 VO != VOEnd; 659 ++VO) 660 delete VO->second; 661 } 662 663 void 664 CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const { 665 FinalOverriderCollector Collector; 666 Collector.Collect(this, false, nullptr, FinalOverriders); 667 668 // Weed out any final overriders that come from virtual base class 669 // subobjects that were hidden by other subobjects along any path. 670 // This is the final-overrider variant of C++ [class.member.lookup]p10. 671 for (auto &OM : FinalOverriders) { 672 for (auto &SO : OM.second) { 673 SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second; 674 if (Overriding.size() < 2) 675 continue; 676 677 auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) { 678 if (!M.InVirtualSubobject) 679 return false; 680 681 // We have an overriding method in a virtual base class 682 // subobject (or non-virtual base class subobject thereof); 683 // determine whether there exists an other overriding method 684 // in a base class subobject that hides the virtual base class 685 // subobject. 686 for (const UniqueVirtualMethod &OP : Overriding) 687 if (&M != &OP && 688 OP.Method->getParent()->isVirtuallyDerivedFrom( 689 M.InVirtualSubobject)) 690 return true; 691 return false; 692 }; 693 694 // FIXME: IsHidden reads from Overriding from the middle of a remove_if 695 // over the same sequence! Is this guaranteed to work? 696 Overriding.erase( 697 std::remove_if(Overriding.begin(), Overriding.end(), IsHidden), 698 Overriding.end()); 699 } 700 } 701 } 702 703 static void 704 AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, 705 CXXIndirectPrimaryBaseSet& Bases) { 706 // If the record has a virtual primary base class, add it to our set. 707 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 708 if (Layout.isPrimaryBaseVirtual()) 709 Bases.insert(Layout.getPrimaryBase()); 710 711 for (const auto &I : RD->bases()) { 712 assert(!I.getType()->isDependentType() && 713 "Cannot get indirect primary bases for class with dependent bases."); 714 715 const CXXRecordDecl *BaseDecl = 716 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 717 718 // Only bases with virtual bases participate in computing the 719 // indirect primary virtual base classes. 720 if (BaseDecl->getNumVBases()) 721 AddIndirectPrimaryBases(BaseDecl, Context, Bases); 722 } 723 724 } 725 726 void 727 CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const { 728 ASTContext &Context = getASTContext(); 729 730 if (!getNumVBases()) 731 return; 732 733 for (const auto &I : bases()) { 734 assert(!I.getType()->isDependentType() && 735 "Cannot get indirect primary bases for class with dependent bases."); 736 737 const CXXRecordDecl *BaseDecl = 738 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 739 740 // Only bases with virtual bases participate in computing the 741 // indirect primary virtual base classes. 742 if (BaseDecl->getNumVBases()) 743 AddIndirectPrimaryBases(BaseDecl, Context, Bases); 744 } 745 } 746