CXXInheritance.cpp 26 KB

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