CXXInheritance.cpp 25 KB

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