blob: f9aa9127d21e9d7a621fae6a5fc249d703bdb198 [file] [log] [blame]
Douglas Gregora8f32e02009-10-06 17:59:45 +00001//===------ 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"
Benjamin Kramerd4f51982012-07-04 18:45:14 +000014#include "clang/AST/ASTContext.h"
Anders Carlsson46170f92010-11-24 22:50:27 +000015#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/DeclCXX.h"
17#include <algorithm>
18#include <set>
19
20using namespace clang;
21
22/// \brief Computes the set of declarations referenced by these base
23/// paths.
24void CXXBasePaths::ComputeDeclsFound() {
25 assert(NumDeclsFound == 0 && !DeclsFound &&
26 "Already computed the set of declarations");
Benjamin Kramerd0e49e52012-02-23 15:18:31 +000027
28 SmallVector<NamedDecl *, 8> Decls;
29 for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
30 Decls.push_back(*Path->Decls.first);
31
32 // Eliminate duplicated decls.
33 llvm::array_pod_sort(Decls.begin(), Decls.end());
Benjamin Kramereb2f2202012-02-23 18:35:56 +000034 Decls.erase(std::unique(Decls.begin(), Decls.end()), Decls.end());
Benjamin Kramerd0e49e52012-02-23 15:18:31 +000035
Douglas Gregora8f32e02009-10-06 17:59:45 +000036 NumDeclsFound = Decls.size();
37 DeclsFound = new NamedDecl * [NumDeclsFound];
38 std::copy(Decls.begin(), Decls.end(), DeclsFound);
39}
40
41CXXBasePaths::decl_iterator CXXBasePaths::found_decls_begin() {
42 if (NumDeclsFound == 0)
43 ComputeDeclsFound();
44 return DeclsFound;
45}
46
47CXXBasePaths::decl_iterator CXXBasePaths::found_decls_end() {
48 if (NumDeclsFound == 0)
49 ComputeDeclsFound();
50 return DeclsFound + NumDeclsFound;
51}
52
53/// isAmbiguous - Determines whether the set of paths provided is
54/// ambiguous, i.e., there are two or more paths that refer to
55/// different base class subobjects of the same type. BaseType must be
56/// an unqualified, canonical class type.
Douglas Gregore0d5fe22010-05-21 20:29:55 +000057bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
58 BaseType = BaseType.getUnqualifiedType();
Douglas Gregora8f32e02009-10-06 17:59:45 +000059 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
60 return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
61}
62
63/// clear - Clear out all prior path information.
64void CXXBasePaths::clear() {
65 Paths.clear();
66 ClassSubobjects.clear();
67 ScratchPath.clear();
68 DetectedVirtual = 0;
69}
70
71/// @brief Swaps the contents of this CXXBasePaths structure with the
72/// contents of Other.
73void CXXBasePaths::swap(CXXBasePaths &Other) {
74 std::swap(Origin, Other.Origin);
75 Paths.swap(Other.Paths);
76 ClassSubobjects.swap(Other.ClassSubobjects);
77 std::swap(FindAmbiguities, Other.FindAmbiguities);
78 std::swap(RecordPaths, Other.RecordPaths);
79 std::swap(DetectVirtual, Other.DetectVirtual);
80 std::swap(DetectedVirtual, Other.DetectedVirtual);
81}
82
John McCalld89d30f2011-01-28 22:02:36 +000083bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
Douglas Gregora8f32e02009-10-06 17:59:45 +000084 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
85 /*DetectVirtual=*/false);
86 return isDerivedFrom(Base, Paths);
87}
88
John McCalld89d30f2011-01-28 22:02:36 +000089bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
90 CXXBasePaths &Paths) const {
Douglas Gregora8f32e02009-10-06 17:59:45 +000091 if (getCanonicalDecl() == Base->getCanonicalDecl())
92 return false;
93
John McCallaf8e6ed2009-11-12 03:15:40 +000094 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
John McCalld89d30f2011-01-28 22:02:36 +000095 return lookupInBases(&FindBaseClass,
96 const_cast<CXXRecordDecl*>(Base->getCanonicalDecl()),
97 Paths);
Douglas Gregora8f32e02009-10-06 17:59:45 +000098}
99
Douglas Gregor4e6ba4b2010-03-03 04:38:46 +0000100bool CXXRecordDecl::isVirtuallyDerivedFrom(CXXRecordDecl *Base) const {
Anders Carlsson1c4c3972010-06-04 01:40:08 +0000101 if (!getNumVBases())
102 return false;
103
Douglas Gregor4e6ba4b2010-03-03 04:38:46 +0000104 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
105 /*DetectVirtual=*/false);
106
107 if (getCanonicalDecl() == Base->getCanonicalDecl())
108 return false;
109
110 Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
111 return lookupInBases(&FindVirtualBaseClass, Base->getCanonicalDecl(), Paths);
112}
113
John McCalle8174bc2009-12-08 07:42:38 +0000114static bool BaseIsNot(const CXXRecordDecl *Base, void *OpaqueTarget) {
115 // OpaqueTarget is a CXXRecordDecl*.
116 return Base->getCanonicalDecl() != (const CXXRecordDecl*) OpaqueTarget;
117}
118
119bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
120 return forallBases(BaseIsNot, (void*) Base->getCanonicalDecl());
121}
122
123bool CXXRecordDecl::forallBases(ForallBasesCallback *BaseMatches,
124 void *OpaqueData,
125 bool AllowShortCircuit) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000126 SmallVector<const CXXRecordDecl*, 8> Queue;
John McCalle8174bc2009-12-08 07:42:38 +0000127
128 const CXXRecordDecl *Record = this;
129 bool AllMatches = true;
130 while (true) {
131 for (CXXRecordDecl::base_class_const_iterator
132 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
133 const RecordType *Ty = I->getType()->getAs<RecordType>();
134 if (!Ty) {
135 if (AllowShortCircuit) return false;
136 AllMatches = false;
137 continue;
138 }
139
Anders Carlssonca910e82009-12-09 04:26:02 +0000140 CXXRecordDecl *Base =
Douglas Gregor952b0172010-02-11 01:04:33 +0000141 cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
John McCalle8174bc2009-12-08 07:42:38 +0000142 if (!Base) {
143 if (AllowShortCircuit) return false;
144 AllMatches = false;
145 continue;
146 }
147
Anders Carlssonca910e82009-12-09 04:26:02 +0000148 Queue.push_back(Base);
149 if (!BaseMatches(Base, OpaqueData)) {
John McCalle8174bc2009-12-08 07:42:38 +0000150 if (AllowShortCircuit) return false;
151 AllMatches = false;
152 continue;
153 }
154 }
155
156 if (Queue.empty()) break;
157 Record = Queue.back(); // not actually a queue.
158 Queue.pop_back();
159 }
160
161 return AllMatches;
162}
163
Douglas Gregor89b77022010-03-03 02:18:00 +0000164bool CXXBasePaths::lookupInBases(ASTContext &Context,
165 const CXXRecordDecl *Record,
166 CXXRecordDecl::BaseMatchesCallback *BaseMatches,
167 void *UserData) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000168 bool FoundPath = false;
John McCall46460a62010-01-20 21:53:11 +0000169
John McCall92f88312010-01-23 00:46:32 +0000170 // The access of the path down to this record.
Douglas Gregor89b77022010-03-03 02:18:00 +0000171 AccessSpecifier AccessToHere = ScratchPath.Access;
172 bool IsFirstStep = ScratchPath.empty();
John McCall92f88312010-01-23 00:46:32 +0000173
Douglas Gregor89b77022010-03-03 02:18:00 +0000174 for (CXXRecordDecl::base_class_const_iterator BaseSpec = Record->bases_begin(),
175 BaseSpecEnd = Record->bases_end();
176 BaseSpec != BaseSpecEnd;
177 ++BaseSpec) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000178 // Find the record of the base class subobjects for this type.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000179 QualType BaseType = Context.getCanonicalType(BaseSpec->getType())
180 .getUnqualifiedType();
Douglas Gregora8f32e02009-10-06 17:59:45 +0000181
182 // C++ [temp.dep]p3:
183 // In the definition of a class template or a member of a class template,
184 // if a base class of the class template depends on a template-parameter,
185 // the base class scope is not examined during unqualified name lookup
186 // either at the point of definition of the class template or member or
187 // during an instantiation of the class tem- plate or member.
188 if (BaseType->isDependentType())
189 continue;
190
191 // Determine whether we need to visit this base class at all,
192 // updating the count of subobjects appropriately.
Douglas Gregor89b77022010-03-03 02:18:00 +0000193 std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
Douglas Gregora8f32e02009-10-06 17:59:45 +0000194 bool VisitBase = true;
195 bool SetVirtual = false;
196 if (BaseSpec->isVirtual()) {
197 VisitBase = !Subobjects.first;
198 Subobjects.first = true;
Douglas Gregor89b77022010-03-03 02:18:00 +0000199 if (isDetectingVirtual() && DetectedVirtual == 0) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000200 // If this is the first virtual we find, remember it. If it turns out
201 // there is no base path here, we'll reset it later.
Douglas Gregor89b77022010-03-03 02:18:00 +0000202 DetectedVirtual = BaseType->getAs<RecordType>();
Douglas Gregora8f32e02009-10-06 17:59:45 +0000203 SetVirtual = true;
204 }
205 } else
206 ++Subobjects.second;
207
Douglas Gregor89b77022010-03-03 02:18:00 +0000208 if (isRecordingPaths()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000209 // Add this base specifier to the current path.
210 CXXBasePathElement Element;
211 Element.Base = &*BaseSpec;
Douglas Gregor89b77022010-03-03 02:18:00 +0000212 Element.Class = Record;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000213 if (BaseSpec->isVirtual())
214 Element.SubobjectNumber = 0;
215 else
216 Element.SubobjectNumber = Subobjects.second;
Douglas Gregor89b77022010-03-03 02:18:00 +0000217 ScratchPath.push_back(Element);
John McCall46460a62010-01-20 21:53:11 +0000218
John McCall92f88312010-01-23 00:46:32 +0000219 // Calculate the "top-down" access to this base class.
220 // The spec actually describes this bottom-up, but top-down is
221 // equivalent because the definition works out as follows:
222 // 1. Write down the access along each step in the inheritance
223 // chain, followed by the access of the decl itself.
224 // For example, in
225 // class A { public: int foo; };
226 // class B : protected A {};
227 // class C : public B {};
228 // class D : private C {};
229 // we would write:
230 // private public protected public
231 // 2. If 'private' appears anywhere except far-left, access is denied.
232 // 3. Otherwise, overall access is determined by the most restrictive
233 // access in the sequence.
234 if (IsFirstStep)
Douglas Gregor89b77022010-03-03 02:18:00 +0000235 ScratchPath.Access = BaseSpec->getAccessSpecifier();
John McCall92f88312010-01-23 00:46:32 +0000236 else
Douglas Gregor89b77022010-03-03 02:18:00 +0000237 ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
238 BaseSpec->getAccessSpecifier());
Douglas Gregora8f32e02009-10-06 17:59:45 +0000239 }
John McCalled814cc2010-02-09 00:57:12 +0000240
241 // Track whether there's a path involving this specific base.
242 bool FoundPathThroughBase = false;
243
Douglas Gregor89b77022010-03-03 02:18:00 +0000244 if (BaseMatches(BaseSpec, ScratchPath, UserData)) {
John McCall92f88312010-01-23 00:46:32 +0000245 // We've found a path that terminates at this base.
John McCalled814cc2010-02-09 00:57:12 +0000246 FoundPath = FoundPathThroughBase = true;
Douglas Gregor89b77022010-03-03 02:18:00 +0000247 if (isRecordingPaths()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000248 // We have a path. Make a copy of it before moving on.
Douglas Gregor89b77022010-03-03 02:18:00 +0000249 Paths.push_back(ScratchPath);
250 } else if (!isFindingAmbiguities()) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000251 // We found a path and we don't care about ambiguities;
252 // return immediately.
253 return FoundPath;
254 }
255 } else if (VisitBase) {
256 CXXRecordDecl *BaseRecord
257 = cast<CXXRecordDecl>(BaseSpec->getType()->getAs<RecordType>()
258 ->getDecl());
Douglas Gregor89b77022010-03-03 02:18:00 +0000259 if (lookupInBases(Context, BaseRecord, BaseMatches, UserData)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000260 // C++ [class.member.lookup]p2:
261 // A member name f in one sub-object B hides a member name f in
262 // a sub-object A if A is a base class sub-object of B. Any
263 // declarations that are so hidden are eliminated from
264 // consideration.
265
266 // There is a path to a base class that meets the criteria. If we're
267 // not collecting paths or finding ambiguities, we're done.
John McCalled814cc2010-02-09 00:57:12 +0000268 FoundPath = FoundPathThroughBase = true;
Douglas Gregor89b77022010-03-03 02:18:00 +0000269 if (!isFindingAmbiguities())
Douglas Gregora8f32e02009-10-06 17:59:45 +0000270 return FoundPath;
271 }
272 }
273
274 // Pop this base specifier off the current path (if we're
275 // collecting paths).
Douglas Gregor89b77022010-03-03 02:18:00 +0000276 if (isRecordingPaths()) {
277 ScratchPath.pop_back();
John McCall46460a62010-01-20 21:53:11 +0000278 }
279
Douglas Gregora8f32e02009-10-06 17:59:45 +0000280 // If we set a virtual earlier, and this isn't a path, forget it again.
John McCalled814cc2010-02-09 00:57:12 +0000281 if (SetVirtual && !FoundPathThroughBase) {
Douglas Gregor89b77022010-03-03 02:18:00 +0000282 DetectedVirtual = 0;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000283 }
284 }
John McCall92f88312010-01-23 00:46:32 +0000285
286 // Reset the scratch path access.
Douglas Gregor89b77022010-03-03 02:18:00 +0000287 ScratchPath.Access = AccessToHere;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000288
289 return FoundPath;
290}
291
Douglas Gregor89b77022010-03-03 02:18:00 +0000292bool CXXRecordDecl::lookupInBases(BaseMatchesCallback *BaseMatches,
293 void *UserData,
294 CXXBasePaths &Paths) const {
Douglas Gregor4e6ba4b2010-03-03 04:38:46 +0000295 // If we didn't find anything, report that.
296 if (!Paths.lookupInBases(getASTContext(), this, BaseMatches, UserData))
297 return false;
298
299 // If we're not recording paths or we won't ever find ambiguities,
300 // we're done.
301 if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
302 return true;
303
304 // C++ [class.member.lookup]p6:
305 // When virtual base classes are used, a hidden declaration can be
306 // reached along a path through the sub-object lattice that does
307 // not pass through the hiding declaration. This is not an
308 // ambiguity. The identical use with nonvirtual base classes is an
309 // ambiguity; in that case there is no unique instance of the name
310 // that hides all the others.
311 //
312 // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
313 // way to make it any faster.
314 for (CXXBasePaths::paths_iterator P = Paths.begin(), PEnd = Paths.end();
315 P != PEnd; /* increment in loop */) {
316 bool Hidden = false;
317
318 for (CXXBasePath::iterator PE = P->begin(), PEEnd = P->end();
319 PE != PEEnd && !Hidden; ++PE) {
320 if (PE->Base->isVirtual()) {
321 CXXRecordDecl *VBase = 0;
322 if (const RecordType *Record = PE->Base->getType()->getAs<RecordType>())
323 VBase = cast<CXXRecordDecl>(Record->getDecl());
324 if (!VBase)
325 break;
326
327 // The declaration(s) we found along this path were found in a
328 // subobject of a virtual base. Check whether this virtual
329 // base is a subobject of any other path; if so, then the
330 // declaration in this path are hidden by that patch.
331 for (CXXBasePaths::paths_iterator HidingP = Paths.begin(),
332 HidingPEnd = Paths.end();
333 HidingP != HidingPEnd;
334 ++HidingP) {
335 CXXRecordDecl *HidingClass = 0;
336 if (const RecordType *Record
337 = HidingP->back().Base->getType()->getAs<RecordType>())
338 HidingClass = cast<CXXRecordDecl>(Record->getDecl());
339 if (!HidingClass)
340 break;
341
342 if (HidingClass->isVirtuallyDerivedFrom(VBase)) {
343 Hidden = true;
344 break;
345 }
346 }
347 }
348 }
349
350 if (Hidden)
351 P = Paths.Paths.erase(P);
352 else
353 ++P;
354 }
355
356 return true;
Douglas Gregor89b77022010-03-03 02:18:00 +0000357}
358
John McCallaf8e6ed2009-11-12 03:15:40 +0000359bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000360 CXXBasePath &Path,
361 void *BaseRecord) {
362 assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
363 "User data for FindBaseClass is not canonical!");
364 return Specifier->getType()->getAs<RecordType>()->getDecl()
365 ->getCanonicalDecl() == BaseRecord;
366}
367
Douglas Gregor4e6ba4b2010-03-03 04:38:46 +0000368bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
369 CXXBasePath &Path,
370 void *BaseRecord) {
371 assert(((Decl *)BaseRecord)->getCanonicalDecl() == BaseRecord &&
372 "User data for FindBaseClass is not canonical!");
373 return Specifier->isVirtual() &&
374 Specifier->getType()->getAs<RecordType>()->getDecl()
375 ->getCanonicalDecl() == BaseRecord;
376}
377
John McCallaf8e6ed2009-11-12 03:15:40 +0000378bool CXXRecordDecl::FindTagMember(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000379 CXXBasePath &Path,
380 void *Name) {
381 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
382
383 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
384 for (Path.Decls = BaseRecord->lookup(N);
385 Path.Decls.first != Path.Decls.second;
386 ++Path.Decls.first) {
387 if ((*Path.Decls.first)->isInIdentifierNamespace(IDNS_Tag))
388 return true;
389 }
390
391 return false;
392}
393
John McCallaf8e6ed2009-11-12 03:15:40 +0000394bool CXXRecordDecl::FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000395 CXXBasePath &Path,
396 void *Name) {
397 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
398
399 const unsigned IDNS = IDNS_Ordinary | IDNS_Tag | IDNS_Member;
400 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
401 for (Path.Decls = BaseRecord->lookup(N);
402 Path.Decls.first != Path.Decls.second;
403 ++Path.Decls.first) {
404 if ((*Path.Decls.first)->isInIdentifierNamespace(IDNS))
405 return true;
406 }
407
408 return false;
409}
410
John McCallaf8e6ed2009-11-12 03:15:40 +0000411bool CXXRecordDecl::
412FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
413 CXXBasePath &Path,
414 void *Name) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000415 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
416
417 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
418 for (Path.Decls = BaseRecord->lookup(N);
419 Path.Decls.first != Path.Decls.second;
420 ++Path.Decls.first) {
421 // FIXME: Refactor the "is it a nested-name-specifier?" check
Richard Smith162e1c12011-04-15 14:24:37 +0000422 if (isa<TypedefNameDecl>(*Path.Decls.first) ||
Douglas Gregora8f32e02009-10-06 17:59:45 +0000423 (*Path.Decls.first)->isInIdentifierNamespace(IDNS_Tag))
424 return true;
425 }
426
427 return false;
Mike Stump82109bd2009-10-06 23:38:59 +0000428}
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000429
430void OverridingMethods::add(unsigned OverriddenSubobject,
431 UniqueVirtualMethod Overriding) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000432 SmallVector<UniqueVirtualMethod, 4> &SubobjectOverrides
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000433 = Overrides[OverriddenSubobject];
434 if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(),
435 Overriding) == SubobjectOverrides.end())
436 SubobjectOverrides.push_back(Overriding);
437}
438
439void OverridingMethods::add(const OverridingMethods &Other) {
440 for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
441 for (overriding_const_iterator M = I->second.begin(),
442 MEnd = I->second.end();
443 M != MEnd;
444 ++M)
445 add(I->first, *M);
446 }
447}
448
449void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
450 for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
451 I->second.clear();
452 I->second.push_back(Overriding);
453 }
454}
455
456
457namespace {
458 class FinalOverriderCollector {
459 /// \brief The number of subobjects of a given class type that
460 /// occur within the class hierarchy.
461 llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
462
463 /// \brief Overriders for each virtual base subobject.
464 llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
465
466 CXXFinalOverriderMap FinalOverriders;
467
468 public:
469 ~FinalOverriderCollector();
470
471 void Collect(const CXXRecordDecl *RD, bool VirtualBase,
472 const CXXRecordDecl *InVirtualSubobject,
473 CXXFinalOverriderMap &Overriders);
474 };
475}
476
477void FinalOverriderCollector::Collect(const CXXRecordDecl *RD,
478 bool VirtualBase,
479 const CXXRecordDecl *InVirtualSubobject,
480 CXXFinalOverriderMap &Overriders) {
481 unsigned SubobjectNumber = 0;
482 if (!VirtualBase)
483 SubobjectNumber
484 = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
485
486 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
487 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
488 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
489 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
490 if (!BaseDecl->isPolymorphic())
491 continue;
492
493 if (Overriders.empty() && !Base->isVirtual()) {
494 // There are no other overriders of virtual member functions,
495 // so let the base class fill in our overriders for us.
496 Collect(BaseDecl, false, InVirtualSubobject, Overriders);
497 continue;
498 }
499
500 // Collect all of the overridders from the base class subobject
501 // and merge them into the set of overridders for this class.
502 // For virtual base classes, populate or use the cached virtual
503 // overrides so that we do not walk the virtual base class (and
504 // its base classes) more than once.
505 CXXFinalOverriderMap ComputedBaseOverriders;
506 CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
507 if (Base->isVirtual()) {
508 CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
Benjamin Kramere0cf31d2012-05-27 22:41:08 +0000509 BaseOverriders = MyVirtualOverriders;
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000510 if (!MyVirtualOverriders) {
511 MyVirtualOverriders = new CXXFinalOverriderMap;
Benjamin Kramere0cf31d2012-05-27 22:41:08 +0000512
513 // Collect may cause VirtualOverriders to reallocate, invalidating the
514 // MyVirtualOverriders reference. Set BaseOverriders to the right
515 // value now.
516 BaseOverriders = MyVirtualOverriders;
517
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000518 Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
519 }
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000520 } else
521 Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
522
523 // Merge the overriders from this base class into our own set of
524 // overriders.
525 for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(),
526 OMEnd = BaseOverriders->end();
527 OM != OMEnd;
528 ++OM) {
529 const CXXMethodDecl *CanonOM
530 = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
531 Overriders[CanonOM].add(OM->second);
532 }
533 }
534 }
535
536 for (CXXRecordDecl::method_iterator M = RD->method_begin(),
537 MEnd = RD->method_end();
538 M != MEnd;
539 ++M) {
540 // We only care about virtual methods.
541 if (!M->isVirtual())
542 continue;
543
544 CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
545
546 if (CanonM->begin_overridden_methods()
547 == CanonM->end_overridden_methods()) {
548 // This is a new virtual function that does not override any
549 // other virtual function. Add it to the map of virtual
550 // functions for which we are tracking overridders.
551
552 // C++ [class.virtual]p2:
553 // For convenience we say that any virtual function overrides itself.
554 Overriders[CanonM].add(SubobjectNumber,
555 UniqueVirtualMethod(CanonM, SubobjectNumber,
556 InVirtualSubobject));
557 continue;
558 }
559
560 // This virtual method overrides other virtual methods, so it does
561 // not add any new slots into the set of overriders. Instead, we
562 // replace entries in the set of overriders with the new
563 // overrider. To do so, we dig down to the original virtual
564 // functions using data recursion and update all of the methods it
565 // overrides.
566 typedef std::pair<CXXMethodDecl::method_iterator,
567 CXXMethodDecl::method_iterator> OverriddenMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 SmallVector<OverriddenMethods, 4> Stack;
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000569 Stack.push_back(std::make_pair(CanonM->begin_overridden_methods(),
570 CanonM->end_overridden_methods()));
571 while (!Stack.empty()) {
572 OverriddenMethods OverMethods = Stack.back();
573 Stack.pop_back();
574
575 for (; OverMethods.first != OverMethods.second; ++OverMethods.first) {
576 const CXXMethodDecl *CanonOM
577 = cast<CXXMethodDecl>((*OverMethods.first)->getCanonicalDecl());
Anders Carlssonffdb2d22010-06-03 01:00:02 +0000578
579 // C++ [class.virtual]p2:
580 // A virtual member function C::vf of a class object S is
581 // a final overrider unless the most derived class (1.8)
582 // of which S is a base class subobject (if any) declares
583 // or inherits another member function that overrides vf.
584 //
585 // Treating this object like the most derived class, we
586 // replace any overrides from base classes with this
587 // overriding virtual function.
588 Overriders[CanonOM].replaceAll(
589 UniqueVirtualMethod(CanonM, SubobjectNumber,
590 InVirtualSubobject));
591
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000592 if (CanonOM->begin_overridden_methods()
Anders Carlssonffdb2d22010-06-03 01:00:02 +0000593 == CanonOM->end_overridden_methods())
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000594 continue;
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000595
596 // Continue recursion to the methods that this virtual method
597 // overrides.
598 Stack.push_back(std::make_pair(CanonOM->begin_overridden_methods(),
599 CanonOM->end_overridden_methods()));
600 }
601 }
Anders Carlssonffdb2d22010-06-03 01:00:02 +0000602
603 // C++ [class.virtual]p2:
604 // For convenience we say that any virtual function overrides itself.
605 Overriders[CanonM].add(SubobjectNumber,
606 UniqueVirtualMethod(CanonM, SubobjectNumber,
607 InVirtualSubobject));
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000608 }
609}
610
611FinalOverriderCollector::~FinalOverriderCollector() {
612 for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
613 VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
614 VO != VOEnd;
615 ++VO)
616 delete VO->second;
617}
618
619void
620CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
621 FinalOverriderCollector Collector;
622 Collector.Collect(this, false, 0, FinalOverriders);
623
624 // Weed out any final overriders that come from virtual base class
625 // subobjects that were hidden by other subobjects along any path.
626 // This is the final-overrider variant of C++ [class.member.lookup]p10.
627 for (CXXFinalOverriderMap::iterator OM = FinalOverriders.begin(),
628 OMEnd = FinalOverriders.end();
629 OM != OMEnd;
630 ++OM) {
631 for (OverridingMethods::iterator SO = OM->second.begin(),
632 SOEnd = OM->second.end();
633 SO != SOEnd;
634 ++SO) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000635 SmallVector<UniqueVirtualMethod, 4> &Overriding = SO->second;
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000636 if (Overriding.size() < 2)
637 continue;
638
Chris Lattner5f9e2722011-07-23 10:55:15 +0000639 for (SmallVector<UniqueVirtualMethod, 4>::iterator
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000640 Pos = Overriding.begin(), PosEnd = Overriding.end();
641 Pos != PosEnd;
642 /* increment in loop */) {
643 if (!Pos->InVirtualSubobject) {
644 ++Pos;
645 continue;
646 }
647
648 // We have an overriding method in a virtual base class
649 // subobject (or non-virtual base class subobject thereof);
650 // determine whether there exists an other overriding method
651 // in a base class subobject that hides the virtual base class
652 // subobject.
653 bool Hidden = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000654 for (SmallVector<UniqueVirtualMethod, 4>::iterator
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +0000655 OP = Overriding.begin(), OPEnd = Overriding.end();
656 OP != OPEnd && !Hidden;
657 ++OP) {
658 if (Pos == OP)
659 continue;
660
661 if (OP->Method->getParent()->isVirtuallyDerivedFrom(
662 const_cast<CXXRecordDecl *>(Pos->InVirtualSubobject)))
663 Hidden = true;
664 }
665
666 if (Hidden) {
667 // The current overriding function is hidden by another
668 // overriding function; remove this one.
669 Pos = Overriding.erase(Pos);
670 PosEnd = Overriding.end();
671 } else {
672 ++Pos;
673 }
674 }
675 }
676 }
677}
Anders Carlsson46170f92010-11-24 22:50:27 +0000678
679static void
680AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
681 CXXIndirectPrimaryBaseSet& Bases) {
682 // If the record has a virtual primary base class, add it to our set.
683 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonc9e814b2010-11-24 23:12:57 +0000684 if (Layout.isPrimaryBaseVirtual())
Anders Carlsson46170f92010-11-24 22:50:27 +0000685 Bases.insert(Layout.getPrimaryBase());
686
687 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
688 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson3a037652010-11-24 22:55:29 +0000689 assert(!I->getType()->isDependentType() &&
Anders Carlsson46170f92010-11-24 22:50:27 +0000690 "Cannot get indirect primary bases for class with dependent bases.");
691
692 const CXXRecordDecl *BaseDecl =
693 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
694
695 // Only bases with virtual bases participate in computing the
696 // indirect primary virtual base classes.
697 if (BaseDecl->getNumVBases())
698 AddIndirectPrimaryBases(BaseDecl, Context, Bases);
699 }
700
701}
702
703void
704CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
705 ASTContext &Context = getASTContext();
706
707 if (!getNumVBases())
708 return;
709
710 for (CXXRecordDecl::base_class_const_iterator I = bases_begin(),
711 E = bases_end(); I != E; ++I) {
Anders Carlsson3a037652010-11-24 22:55:29 +0000712 assert(!I->getType()->isDependentType() &&
Anders Carlsson46170f92010-11-24 22:50:27 +0000713 "Cannot get indirect primary bases for class with dependent bases.");
714
715 const CXXRecordDecl *BaseDecl =
716 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
717
718 // Only bases with virtual bases participate in computing the
719 // indirect primary virtual base classes.
720 if (BaseDecl->getNumVBases())
721 AddIndirectPrimaryBases(BaseDecl, Context, Bases);
722 }
723}
724