clang  5.0.0
CXXInheritance.cpp
Go to the documentation of this file.
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 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "llvm/ADT/SetVector.h"
19 #include <algorithm>
20 
21 using namespace clang;
22 
23 /// \brief Computes the set of declarations referenced by these base
24 /// paths.
25 void CXXBasePaths::ComputeDeclsFound() {
26  assert(NumDeclsFound == 0 && !DeclsFound &&
27  "Already computed the set of declarations");
28 
29  llvm::SetVector<NamedDecl *, SmallVector<NamedDecl *, 8> > Decls;
30  for (paths_iterator Path = begin(), PathEnd = end(); Path != PathEnd; ++Path)
31  Decls.insert(Path->Decls.front());
32 
33  NumDeclsFound = Decls.size();
34  DeclsFound = llvm::make_unique<NamedDecl *[]>(NumDeclsFound);
35  std::copy(Decls.begin(), Decls.end(), DeclsFound.get());
36 }
37 
39  if (NumDeclsFound == 0)
40  ComputeDeclsFound();
41 
42  return decl_range(decl_iterator(DeclsFound.get()),
43  decl_iterator(DeclsFound.get() + NumDeclsFound));
44 }
45 
46 /// isAmbiguous - Determines whether the set of paths provided is
47 /// ambiguous, i.e., there are two or more paths that refer to
48 /// different base class subobjects of the same type. BaseType must be
49 /// an unqualified, canonical class type.
51  BaseType = BaseType.getUnqualifiedType();
52  std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
53  return Subobjects.second + (Subobjects.first? 1 : 0) > 1;
54 }
55 
56 /// clear - Clear out all prior path information.
58  Paths.clear();
59  ClassSubobjects.clear();
60  VisitedDependentRecords.clear();
61  ScratchPath.clear();
62  DetectedVirtual = nullptr;
63 }
64 
65 /// @brief Swaps the contents of this CXXBasePaths structure with the
66 /// contents of Other.
68  std::swap(Origin, Other.Origin);
69  Paths.swap(Other.Paths);
70  ClassSubobjects.swap(Other.ClassSubobjects);
71  VisitedDependentRecords.swap(Other.VisitedDependentRecords);
72  std::swap(FindAmbiguities, Other.FindAmbiguities);
73  std::swap(RecordPaths, Other.RecordPaths);
74  std::swap(DetectVirtual, Other.DetectVirtual);
75  std::swap(DetectedVirtual, Other.DetectedVirtual);
76 }
77 
79  CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
80  /*DetectVirtual=*/false);
81  return isDerivedFrom(Base, Paths);
82 }
83 
85  CXXBasePaths &Paths) const {
86  if (getCanonicalDecl() == Base->getCanonicalDecl())
87  return false;
88 
89  Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
90 
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  [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
95  return FindBaseClass(Specifier, Path, BaseDecl);
96  },
97  Paths);
98 }
99 
101  if (!getNumVBases())
102  return false;
103 
104  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 
112  const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
113  // FIXME: Capturing 'this' is a workaround for name lookup bugs in GCC 4.7.
114  return lookupInBases(
115  [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
116  return FindVirtualBaseClass(Specifier, Path, BaseDecl);
117  },
118  Paths);
119 }
120 
122  const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl();
123  return forallBases([TargetDecl](const CXXRecordDecl *Base) {
124  return Base->getCanonicalDecl() != TargetDecl;
125  });
126 }
127 
128 bool
130  assert(isDependentContext());
131 
132  for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
133  if (CurContext->Equals(this))
134  return true;
135 
136  return false;
137 }
138 
140  bool AllowShortCircuit) const {
142 
143  const CXXRecordDecl *Record = this;
144  bool AllMatches = true;
145  while (true) {
146  for (const auto &I : Record->bases()) {
147  const RecordType *Ty = I.getType()->getAs<RecordType>();
148  if (!Ty) {
149  if (AllowShortCircuit) return false;
150  AllMatches = false;
151  continue;
152  }
153 
154  CXXRecordDecl *Base =
155  cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
156  if (!Base ||
157  (Base->isDependentContext() &&
158  !Base->isCurrentInstantiation(Record))) {
159  if (AllowShortCircuit) return false;
160  AllMatches = false;
161  continue;
162  }
163 
164  Queue.push_back(Base);
165  if (!BaseMatches(Base)) {
166  if (AllowShortCircuit) return false;
167  AllMatches = false;
168  continue;
169  }
170  }
171 
172  if (Queue.empty())
173  break;
174  Record = Queue.pop_back_val(); // not actually a queue.
175  }
176 
177  return AllMatches;
178 }
179 
180 bool CXXBasePaths::lookupInBases(ASTContext &Context,
181  const CXXRecordDecl *Record,
183  bool LookupInDependent) {
184  bool FoundPath = false;
185 
186  // The access of the path down to this record.
187  AccessSpecifier AccessToHere = ScratchPath.Access;
188  bool IsFirstStep = ScratchPath.empty();
189 
190  for (const auto &BaseSpec : Record->bases()) {
191  // Find the record of the base class subobjects for this type.
192  QualType BaseType =
193  Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType();
194 
195  // C++ [temp.dep]p3:
196  // In the definition of a class template or a member of a class template,
197  // if a base class of the class template depends on a template-parameter,
198  // the base class scope is not examined during unqualified name lookup
199  // either at the point of definition of the class template or member or
200  // during an instantiation of the class tem- plate or member.
201  if (!LookupInDependent && BaseType->isDependentType())
202  continue;
203 
204  // Determine whether we need to visit this base class at all,
205  // updating the count of subobjects appropriately.
206  std::pair<bool, unsigned>& Subobjects = ClassSubobjects[BaseType];
207  bool VisitBase = true;
208  bool SetVirtual = false;
209  if (BaseSpec.isVirtual()) {
210  VisitBase = !Subobjects.first;
211  Subobjects.first = true;
212  if (isDetectingVirtual() && DetectedVirtual == nullptr) {
213  // If this is the first virtual we find, remember it. If it turns out
214  // there is no base path here, we'll reset it later.
215  DetectedVirtual = BaseType->getAs<RecordType>();
216  SetVirtual = true;
217  }
218  } else
219  ++Subobjects.second;
220 
221  if (isRecordingPaths()) {
222  // Add this base specifier to the current path.
223  CXXBasePathElement Element;
224  Element.Base = &BaseSpec;
225  Element.Class = Record;
226  if (BaseSpec.isVirtual())
227  Element.SubobjectNumber = 0;
228  else
229  Element.SubobjectNumber = Subobjects.second;
230  ScratchPath.push_back(Element);
231 
232  // Calculate the "top-down" access to this base class.
233  // The spec actually describes this bottom-up, but top-down is
234  // equivalent because the definition works out as follows:
235  // 1. Write down the access along each step in the inheritance
236  // chain, followed by the access of the decl itself.
237  // For example, in
238  // class A { public: int foo; };
239  // class B : protected A {};
240  // class C : public B {};
241  // class D : private C {};
242  // we would write:
243  // private public protected public
244  // 2. If 'private' appears anywhere except far-left, access is denied.
245  // 3. Otherwise, overall access is determined by the most restrictive
246  // access in the sequence.
247  if (IsFirstStep)
248  ScratchPath.Access = BaseSpec.getAccessSpecifier();
249  else
250  ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
251  BaseSpec.getAccessSpecifier());
252  }
253 
254  // Track whether there's a path involving this specific base.
255  bool FoundPathThroughBase = false;
256 
257  if (BaseMatches(&BaseSpec, ScratchPath)) {
258  // We've found a path that terminates at this base.
259  FoundPath = FoundPathThroughBase = true;
260  if (isRecordingPaths()) {
261  // We have a path. Make a copy of it before moving on.
262  Paths.push_back(ScratchPath);
263  } else if (!isFindingAmbiguities()) {
264  // We found a path and we don't care about ambiguities;
265  // return immediately.
266  return FoundPath;
267  }
268  } else if (VisitBase) {
269  CXXRecordDecl *BaseRecord;
270  if (LookupInDependent) {
271  BaseRecord = nullptr;
272  const TemplateSpecializationType *TST =
273  BaseSpec.getType()->getAs<TemplateSpecializationType>();
274  if (!TST) {
275  if (auto *RT = BaseSpec.getType()->getAs<RecordType>())
276  BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
277  } else {
278  TemplateName TN = TST->getTemplateName();
279  if (auto *TD =
280  dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()))
281  BaseRecord = TD->getTemplatedDecl();
282  }
283  if (BaseRecord) {
284  if (!BaseRecord->hasDefinition() ||
285  VisitedDependentRecords.count(BaseRecord)) {
286  BaseRecord = nullptr;
287  } else {
288  VisitedDependentRecords.insert(BaseRecord);
289  }
290  }
291  } else {
292  BaseRecord = cast<CXXRecordDecl>(
293  BaseSpec.getType()->castAs<RecordType>()->getDecl());
294  }
295  if (BaseRecord &&
296  lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) {
297  // C++ [class.member.lookup]p2:
298  // A member name f in one sub-object B hides a member name f in
299  // a sub-object A if A is a base class sub-object of B. Any
300  // declarations that are so hidden are eliminated from
301  // consideration.
302 
303  // There is a path to a base class that meets the criteria. If we're
304  // not collecting paths or finding ambiguities, we're done.
305  FoundPath = FoundPathThroughBase = true;
306  if (!isFindingAmbiguities())
307  return FoundPath;
308  }
309  }
310 
311  // Pop this base specifier off the current path (if we're
312  // collecting paths).
313  if (isRecordingPaths()) {
314  ScratchPath.pop_back();
315  }
316 
317  // If we set a virtual earlier, and this isn't a path, forget it again.
318  if (SetVirtual && !FoundPathThroughBase) {
319  DetectedVirtual = nullptr;
320  }
321  }
322 
323  // Reset the scratch path access.
324  ScratchPath.Access = AccessToHere;
325 
326  return FoundPath;
327 }
328 
330  CXXBasePaths &Paths,
331  bool LookupInDependent) const {
332  // If we didn't find anything, report that.
333  if (!Paths.lookupInBases(getASTContext(), this, BaseMatches,
334  LookupInDependent))
335  return false;
336 
337  // If we're not recording paths or we won't ever find ambiguities,
338  // we're done.
339  if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
340  return true;
341 
342  // C++ [class.member.lookup]p6:
343  // When virtual base classes are used, a hidden declaration can be
344  // reached along a path through the sub-object lattice that does
345  // not pass through the hiding declaration. This is not an
346  // ambiguity. The identical use with nonvirtual base classes is an
347  // ambiguity; in that case there is no unique instance of the name
348  // that hides all the others.
349  //
350  // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy
351  // way to make it any faster.
352  Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) {
353  for (const CXXBasePathElement &PE : Path) {
354  if (!PE.Base->isVirtual())
355  continue;
356 
357  CXXRecordDecl *VBase = nullptr;
358  if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>())
359  VBase = cast<CXXRecordDecl>(Record->getDecl());
360  if (!VBase)
361  break;
362 
363  // The declaration(s) we found along this path were found in a
364  // subobject of a virtual base. Check whether this virtual
365  // base is a subobject of any other path; if so, then the
366  // declaration in this path are hidden by that patch.
367  for (const CXXBasePath &HidingP : Paths) {
368  CXXRecordDecl *HidingClass = nullptr;
369  if (const RecordType *Record =
370  HidingP.back().Base->getType()->getAs<RecordType>())
371  HidingClass = cast<CXXRecordDecl>(Record->getDecl());
372  if (!HidingClass)
373  break;
374 
375  if (HidingClass->isVirtuallyDerivedFrom(VBase))
376  return true;
377  }
378  }
379  return false;
380  });
381 
382  return true;
383 }
384 
386  CXXBasePath &Path,
387  const CXXRecordDecl *BaseRecord) {
388  assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
389  "User data for FindBaseClass is not canonical!");
390  return Specifier->getType()->castAs<RecordType>()->getDecl()
391  ->getCanonicalDecl() == BaseRecord;
392 }
393 
395  CXXBasePath &Path,
396  const CXXRecordDecl *BaseRecord) {
397  assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
398  "User data for FindBaseClass is not canonical!");
399  return Specifier->isVirtual() &&
400  Specifier->getType()->castAs<RecordType>()->getDecl()
401  ->getCanonicalDecl() == BaseRecord;
402 }
403 
405  CXXBasePath &Path,
407  RecordDecl *BaseRecord =
408  Specifier->getType()->castAs<RecordType>()->getDecl();
409 
410  for (Path.Decls = BaseRecord->lookup(Name);
411  !Path.Decls.empty();
412  Path.Decls = Path.Decls.slice(1)) {
413  if (Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
414  return true;
415  }
416 
417  return false;
418 }
419 
420 static bool findOrdinaryMember(RecordDecl *BaseRecord, CXXBasePath &Path,
422  const unsigned IDNS = clang::Decl::IDNS_Ordinary | clang::Decl::IDNS_Tag |
424  for (Path.Decls = BaseRecord->lookup(Name);
425  !Path.Decls.empty();
426  Path.Decls = Path.Decls.slice(1)) {
427  if (Path.Decls.front()->isInIdentifierNamespace(IDNS))
428  return true;
429  }
430 
431  return false;
432 }
433 
435  CXXBasePath &Path,
437  RecordDecl *BaseRecord =
438  Specifier->getType()->castAs<RecordType>()->getDecl();
439  return findOrdinaryMember(BaseRecord, Path, Name);
440 }
441 
443  const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
445  const TemplateSpecializationType *TST =
446  Specifier->getType()->getAs<TemplateSpecializationType>();
447  if (!TST) {
448  auto *RT = Specifier->getType()->getAs<RecordType>();
449  if (!RT)
450  return false;
451  return findOrdinaryMember(RT->getDecl(), Path, Name);
452  }
453  TemplateName TN = TST->getTemplateName();
454  const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
455  if (!TD)
456  return false;
457  CXXRecordDecl *RD = TD->getTemplatedDecl();
458  if (!RD)
459  return false;
460  return findOrdinaryMember(RD, Path, Name);
461 }
462 
464  CXXBasePath &Path,
466  RecordDecl *BaseRecord =
467  Specifier->getType()->castAs<RecordType>()->getDecl();
468 
469  for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
470  Path.Decls = Path.Decls.slice(1)) {
471  if (Path.Decls.front()->isInIdentifierNamespace(IDNS_OMPReduction))
472  return true;
473  }
474 
475  return false;
476 }
477 
478 bool CXXRecordDecl::
480  CXXBasePath &Path,
482  RecordDecl *BaseRecord =
483  Specifier->getType()->castAs<RecordType>()->getDecl();
484 
485  for (Path.Decls = BaseRecord->lookup(Name);
486  !Path.Decls.empty();
487  Path.Decls = Path.Decls.slice(1)) {
488  // FIXME: Refactor the "is it a nested-name-specifier?" check
489  if (isa<TypedefNameDecl>(Path.Decls.front()) ||
490  Path.Decls.front()->isInIdentifierNamespace(IDNS_Tag))
491  return true;
492  }
493 
494  return false;
495 }
496 
497 std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName(
498  const DeclarationName &Name,
499  llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
500  std::vector<const NamedDecl *> Results;
501  // Lookup in the class.
502  DeclContext::lookup_result DirectResult = lookup(Name);
503  if (!DirectResult.empty()) {
504  for (const NamedDecl *ND : DirectResult) {
505  if (Filter(ND))
506  Results.push_back(ND);
507  }
508  return Results;
509  }
510  // Perform lookup into our base classes.
511  CXXBasePaths Paths;
512  Paths.setOrigin(this);
513  if (!lookupInBases(
514  [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
516  Specifier, Path, Name);
517  },
518  Paths, /*LookupInDependent=*/true))
519  return Results;
520  for (const NamedDecl *ND : Paths.front().Decls) {
521  if (Filter(ND))
522  Results.push_back(ND);
523  }
524  return Results;
525 }
526 
527 void OverridingMethods::add(unsigned OverriddenSubobject,
528  UniqueVirtualMethod Overriding) {
529  SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides
530  = Overrides[OverriddenSubobject];
531  if (std::find(SubobjectOverrides.begin(), SubobjectOverrides.end(),
532  Overriding) == SubobjectOverrides.end())
533  SubobjectOverrides.push_back(Overriding);
534 }
535 
537  for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
538  for (overriding_const_iterator M = I->second.begin(),
539  MEnd = I->second.end();
540  M != MEnd;
541  ++M)
542  add(I->first, *M);
543  }
544 }
545 
547  for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
548  I->second.clear();
549  I->second.push_back(Overriding);
550  }
551 }
552 
553 
554 namespace {
555  class FinalOverriderCollector {
556  /// \brief The number of subobjects of a given class type that
557  /// occur within the class hierarchy.
558  llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
559 
560  /// \brief Overriders for each virtual base subobject.
561  llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
562 
563  CXXFinalOverriderMap FinalOverriders;
564 
565  public:
566  ~FinalOverriderCollector();
567 
568  void Collect(const CXXRecordDecl *RD, bool VirtualBase,
569  const CXXRecordDecl *InVirtualSubobject,
570  CXXFinalOverriderMap &Overriders);
571  };
572 }
573 
574 void FinalOverriderCollector::Collect(const CXXRecordDecl *RD,
575  bool VirtualBase,
576  const CXXRecordDecl *InVirtualSubobject,
577  CXXFinalOverriderMap &Overriders) {
578  unsigned SubobjectNumber = 0;
579  if (!VirtualBase)
580  SubobjectNumber
581  = ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
582 
583  for (const auto &Base : RD->bases()) {
584  if (const RecordType *RT = Base.getType()->getAs<RecordType>()) {
585  const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
586  if (!BaseDecl->isPolymorphic())
587  continue;
588 
589  if (Overriders.empty() && !Base.isVirtual()) {
590  // There are no other overriders of virtual member functions,
591  // so let the base class fill in our overriders for us.
592  Collect(BaseDecl, false, InVirtualSubobject, Overriders);
593  continue;
594  }
595 
596  // Collect all of the overridders from the base class subobject
597  // and merge them into the set of overridders for this class.
598  // For virtual base classes, populate or use the cached virtual
599  // overrides so that we do not walk the virtual base class (and
600  // its base classes) more than once.
601  CXXFinalOverriderMap ComputedBaseOverriders;
602  CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
603  if (Base.isVirtual()) {
604  CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
605  BaseOverriders = MyVirtualOverriders;
606  if (!MyVirtualOverriders) {
607  MyVirtualOverriders = new CXXFinalOverriderMap;
608 
609  // Collect may cause VirtualOverriders to reallocate, invalidating the
610  // MyVirtualOverriders reference. Set BaseOverriders to the right
611  // value now.
612  BaseOverriders = MyVirtualOverriders;
613 
614  Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
615  }
616  } else
617  Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
618 
619  // Merge the overriders from this base class into our own set of
620  // overriders.
621  for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(),
622  OMEnd = BaseOverriders->end();
623  OM != OMEnd;
624  ++OM) {
625  const CXXMethodDecl *CanonOM
626  = cast<CXXMethodDecl>(OM->first->getCanonicalDecl());
627  Overriders[CanonOM].add(OM->second);
628  }
629  }
630  }
631 
632  for (auto *M : RD->methods()) {
633  // We only care about virtual methods.
634  if (!M->isVirtual())
635  continue;
636 
637  CXXMethodDecl *CanonM = cast<CXXMethodDecl>(M->getCanonicalDecl());
638 
639  if (CanonM->begin_overridden_methods()
640  == CanonM->end_overridden_methods()) {
641  // This is a new virtual function that does not override any
642  // other virtual function. Add it to the map of virtual
643  // functions for which we are tracking overridders.
644 
645  // C++ [class.virtual]p2:
646  // For convenience we say that any virtual function overrides itself.
647  Overriders[CanonM].add(SubobjectNumber,
648  UniqueVirtualMethod(CanonM, SubobjectNumber,
649  InVirtualSubobject));
650  continue;
651  }
652 
653  // This virtual method overrides other virtual methods, so it does
654  // not add any new slots into the set of overriders. Instead, we
655  // replace entries in the set of overriders with the new
656  // overrider. To do so, we dig down to the original virtual
657  // functions using data recursion and update all of the methods it
658  // overrides.
659  typedef llvm::iterator_range<CXXMethodDecl::method_iterator>
662  Stack.push_back(llvm::make_range(CanonM->begin_overridden_methods(),
663  CanonM->end_overridden_methods()));
664  while (!Stack.empty()) {
665  for (const CXXMethodDecl *OM : Stack.pop_back_val()) {
666  const CXXMethodDecl *CanonOM = OM->getCanonicalDecl();
667 
668  // C++ [class.virtual]p2:
669  // A virtual member function C::vf of a class object S is
670  // a final overrider unless the most derived class (1.8)
671  // of which S is a base class subobject (if any) declares
672  // or inherits another member function that overrides vf.
673  //
674  // Treating this object like the most derived class, we
675  // replace any overrides from base classes with this
676  // overriding virtual function.
677  Overriders[CanonOM].replaceAll(
678  UniqueVirtualMethod(CanonM, SubobjectNumber,
679  InVirtualSubobject));
680 
681  if (CanonOM->begin_overridden_methods()
682  == CanonOM->end_overridden_methods())
683  continue;
684 
685  // Continue recursion to the methods that this virtual method
686  // overrides.
687  Stack.push_back(llvm::make_range(CanonOM->begin_overridden_methods(),
688  CanonOM->end_overridden_methods()));
689  }
690  }
691 
692  // C++ [class.virtual]p2:
693  // For convenience we say that any virtual function overrides itself.
694  Overriders[CanonM].add(SubobjectNumber,
695  UniqueVirtualMethod(CanonM, SubobjectNumber,
696  InVirtualSubobject));
697  }
698 }
699 
700 FinalOverriderCollector::~FinalOverriderCollector() {
701  for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
702  VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
703  VO != VOEnd;
704  ++VO)
705  delete VO->second;
706 }
707 
708 void
710  FinalOverriderCollector Collector;
711  Collector.Collect(this, false, nullptr, FinalOverriders);
712 
713  // Weed out any final overriders that come from virtual base class
714  // subobjects that were hidden by other subobjects along any path.
715  // This is the final-overrider variant of C++ [class.member.lookup]p10.
716  for (auto &OM : FinalOverriders) {
717  for (auto &SO : OM.second) {
718  SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second;
719  if (Overriding.size() < 2)
720  continue;
721 
722  auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) {
723  if (!M.InVirtualSubobject)
724  return false;
725 
726  // We have an overriding method in a virtual base class
727  // subobject (or non-virtual base class subobject thereof);
728  // determine whether there exists an other overriding method
729  // in a base class subobject that hides the virtual base class
730  // subobject.
731  for (const UniqueVirtualMethod &OP : Overriding)
732  if (&M != &OP &&
733  OP.Method->getParent()->isVirtuallyDerivedFrom(
734  M.InVirtualSubobject))
735  return true;
736  return false;
737  };
738 
739  Overriding.erase(
740  std::remove_if(Overriding.begin(), Overriding.end(), IsHidden),
741  Overriding.end());
742  }
743  }
744 }
745 
746 static void
748  CXXIndirectPrimaryBaseSet& Bases) {
749  // If the record has a virtual primary base class, add it to our set.
750  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
751  if (Layout.isPrimaryBaseVirtual())
752  Bases.insert(Layout.getPrimaryBase());
753 
754  for (const auto &I : RD->bases()) {
755  assert(!I.getType()->isDependentType() &&
756  "Cannot get indirect primary bases for class with dependent bases.");
757 
758  const CXXRecordDecl *BaseDecl =
759  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
760 
761  // Only bases with virtual bases participate in computing the
762  // indirect primary virtual base classes.
763  if (BaseDecl->getNumVBases())
764  AddIndirectPrimaryBases(BaseDecl, Context, Bases);
765  }
766 
767 }
768 
769 void
771  ASTContext &Context = getASTContext();
772 
773  if (!getNumVBases())
774  return;
775 
776  for (const auto &I : bases()) {
777  assert(!I.getType()->isDependentType() &&
778  "Cannot get indirect primary bases for class with dependent bases.");
779 
780  const CXXRecordDecl *BaseDecl =
781  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
782 
783  // Only bases with virtual bases participate in computing the
784  // indirect primary virtual base classes.
785  if (BaseDecl->getNumVBases())
786  AddIndirectPrimaryBases(BaseDecl, Context, Bases);
787  }
788 }
Defines the clang::ASTContext interface.
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
void setOrigin(CXXRecordDecl *Rec)
A (possibly-)qualified type.
Definition: Type.h:616
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:212
base_class_range bases()
Definition: DeclCXX.h:737
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:258
method_range methods() const
Definition: DeclCXX.h:779
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
Defines the C++ template declaration subclasses.
void swap(CXXBasePaths &Other)
Swap this data structure's contents with another CXXBasePaths object.
bool hasDefinition() const
Definition: DeclCXX.h:702
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1009
MapType::iterator iterator
bool forallBases(ForallBasesCallback BaseMatches, bool AllowShortCircuit=true) const
Determines if the given callback holds for all the direct or indirect base classes of this type...
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not...
Definition: RecordLayout.h:212
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:94
const NestedNameSpecifier * Specifier
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
DeclContext::lookup_result Decls
The set of declarations found inside this base class subobject.
static bool FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name)
Base-class lookup callback that determines whether there exists a member with the given name...
void clear()
Clear the base-paths results.
MapType::const_iterator const_iterator
static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name)
Base-class lookup callback that determines whether there exists an OpenMP declare reduction member wi...
std::vector< const NamedDecl * > lookupDependentName(const DeclarationName &Name, llvm::function_ref< bool(const NamedDecl *ND)> Filter)
Performs an imprecise lookup of a dependent name in this class.
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3354
bool isFindingAmbiguities() const
Whether we are finding multiple paths to detect ambiguities.
method_iterator end_overridden_methods() const
Definition: DeclCXX.cpp:1828
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1146
bool isRecordingPaths() const
Whether we are recording paths.
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:1984
std::vector< const CXXMethodDecl * > OverriddenMethods
void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet &Bases) const
Get the indirect primary bases for this class.
void add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding)
The set of methods that override a given virtual method in each subobject where it occurs...
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:4382
RecordDecl * getDecl() const
Definition: Type.h:3793
llvm::function_ref< bool(const CXXBaseSpecifier *Specifier, CXXBasePath &Path)> BaseMatchesCallback
Function type used by lookupInBases() to determine whether a specific base class subobject matches th...
Definition: DeclCXX.h:1618
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:671
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
static bool findOrdinaryMember(RecordDecl *BaseRecord, CXXBasePath &Path, DeclarationName Name)
detail::InMemoryDirectory::const_iterator I
Ordinary names.
Definition: DeclBase.h:139
bool isDetectingVirtual() const
Whether we are detecting virtual bases.
ASTContext * Context
std::vector< bool > & Stack
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
NamedDecl ** decl_iterator
int SubobjectNumber
Identifies which base class subobject (of type Base->getType()) this base path element refers to...
This declaration is an OpenMP user defined reduction construction.
Definition: DeclBase.h:173
static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name)
Base-class lookup callback that determines whether there exists a member with the given name that can...
llvm::function_ref< bool(const CXXRecordDecl *BaseDefinition)> ForallBasesCallback
Function type used by forallBases() as a callback.
Definition: DeclCXX.h:1589
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1797
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1294
static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name)
Base-class lookup callback that determines whether there exists a member with the given name...
Uniquely identifies a virtual method within a class hierarchy by the method itself and a class subobj...
DeclContextLookupResult slice(size_t N) const
Definition: DeclBase.h:1193
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3473
decl_range found_decls()
const CXXBaseSpecifier * Base
The base specifier that states the link from a derived class to a base class, which will be followed ...
SmallVectorImpl< UniqueVirtualMethod >::const_iterator overriding_const_iterator
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:131
method_iterator begin_overridden_methods() const
Definition: DeclCXX.cpp:1823
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:204
A set of all the primary bases for a class.
reference front() const
Definition: DeclBase.h:1188
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:346
static bool FindBaseClass(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, const CXXRecordDecl *BaseRecord)
Base-class lookup callback that determines whether the given base class specifier refers to a specifi...
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
paths_iterator begin()
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6105
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1507
bool isFileContext() const
Definition: DeclBase.h:1360
bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is virtually derived from the class Base.
Represents an element in a path from a derived class to a base class.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1215
StringRef Name
Definition: USRFinder.cpp:123
static void AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, CXXIndirectPrimaryBaseSet &Bases)
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
DeclarationName - The name of a declaration.
A mapping from each virtual member function to its set of final overriders.
bool isAmbiguous(CanQualType BaseType)
Determine whether the path from the most-derived type to the given base type is ambiguous (i...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2087
bool isCurrentInstantiation(const DeclContext *CurContext) const
Determine whether this dependent class is a current instantiation, when viewed from within the given ...
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:120
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, AccessSpecifier DeclAccess)
Calculates the access of a decl that is reached along a path.
Definition: DeclCXX.h:1734
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3784
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
llvm::iterator_range< decl_iterator > decl_range
CXXBasePath & front()
static bool FindTagMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name)
Base-class lookup callback that determines whether there exists a tag with the given name...
Represents a base class of a C++ class.
Definition: DeclCXX.h:158
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Represents a C++ struct/union/class.
Definition: DeclCXX.h:267
AccessSpecifier Access
The access along this inheritance path.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1414
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4297
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is provably not derived from the type Base.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
void replaceAll(UniqueVirtualMethod Overriding)
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:752
paths_iterator end()
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const
Retrieve the final overriders for each virtual member function in the class hierarchy where this clas...
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1235
const CXXRecordDecl * Class
The record decl of the class that the base is a base of.
static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, const CXXRecordDecl *BaseRecord)
Base-class lookup callback that determines whether the given base class specifier refers to a specifi...
std::list< CXXBasePath >::iterator paths_iterator