CXXInheritance.cpp 25 KB

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