CXXInheritance.cpp 25 KB

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