1 //===- CXXInheritance.h - C++ Inheritance -----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides routines that help analyzing C++ inheritance hierarchies.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_CLANG_AST_CXXINHERITANCE_H
14 #define LLVM_CLANG_AST_CXXINHERITANCE_H
15
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/AST/Type.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include <list>
29 #include <memory>
30 #include <utility>
31
32 namespace clang {
33
34 class ASTContext;
35 class NamedDecl;
36
37 /// Represents an element in a path from a derived class to a
38 /// base class.
39 ///
40 /// Each step in the path references the link from a
41 /// derived class to one of its direct base classes, along with a
42 /// base "number" that identifies which base subobject of the
43 /// original derived class we are referencing.
44 struct CXXBasePathElement {
45 /// The base specifier that states the link from a derived
46 /// class to a base class, which will be followed by this base
47 /// path element.
48 const CXXBaseSpecifier *Base;
49
50 /// The record decl of the class that the base is a base of.
51 const CXXRecordDecl *Class;
52
53 /// Identifies which base class subobject (of type
54 /// \c Base->getType()) this base path element refers to.
55 ///
56 /// This value is only valid if \c !Base->isVirtual(), because there
57 /// is no base numbering for the zero or one virtual bases of a
58 /// given type.
59 int SubobjectNumber;
60 };
61
62 /// Represents a path from a specific derived class
63 /// (which is not represented as part of the path) to a particular
64 /// (direct or indirect) base class subobject.
65 ///
66 /// Individual elements in the path are described by the \c CXXBasePathElement
67 /// structure, which captures both the link from a derived class to one of its
68 /// direct bases and identification describing which base class
69 /// subobject is being used.
70 class CXXBasePath : public SmallVector<CXXBasePathElement, 4> {
71 public:
72 /// The access along this inheritance path. This is only
73 /// calculated when recording paths. AS_none is a special value
74 /// used to indicate a path which permits no legal access.
75 AccessSpecifier Access = AS_public;
76
77 CXXBasePath() = default;
78
79 /// The set of declarations found inside this base class
80 /// subobject.
81 DeclContext::lookup_result Decls;
82
clear()83 void clear() {
84 SmallVectorImpl<CXXBasePathElement>::clear();
85 Access = AS_public;
86 }
87 };
88
89 /// BasePaths - Represents the set of paths from a derived class to
90 /// one of its (direct or indirect) bases. For example, given the
91 /// following class hierarchy:
92 ///
93 /// @code
94 /// class A { };
95 /// class B : public A { };
96 /// class C : public A { };
97 /// class D : public B, public C{ };
98 /// @endcode
99 ///
100 /// There are two potential BasePaths to represent paths from D to a
101 /// base subobject of type A. One path is (D,0) -> (B,0) -> (A,0)
102 /// and another is (D,0)->(C,0)->(A,1). These two paths actually
103 /// refer to two different base class subobjects of the same type,
104 /// so the BasePaths object refers to an ambiguous path. On the
105 /// other hand, consider the following class hierarchy:
106 ///
107 /// @code
108 /// class A { };
109 /// class B : public virtual A { };
110 /// class C : public virtual A { };
111 /// class D : public B, public C{ };
112 /// @endcode
113 ///
114 /// Here, there are two potential BasePaths again, (D, 0) -> (B, 0)
115 /// -> (A,v) and (D, 0) -> (C, 0) -> (A, v), but since both of them
116 /// refer to the same base class subobject of type A (the virtual
117 /// one), there is no ambiguity.
118 class CXXBasePaths {
119 friend class CXXRecordDecl;
120
121 /// The type from which this search originated.
122 const CXXRecordDecl *Origin = nullptr;
123
124 /// Paths - The actual set of paths that can be taken from the
125 /// derived class to the same base class.
126 std::list<CXXBasePath> Paths;
127
128 /// ClassSubobjects - Records the class subobjects for each class
129 /// type that we've seen. The first element IsVirtBase says
130 /// whether we found a path to a virtual base for that class type,
131 /// while NumberOfNonVirtBases contains the number of non-virtual base
132 /// class subobjects for that class type. The key of the map is
133 /// the cv-unqualified canonical type of the base class subobject.
134 struct IsVirtBaseAndNumberNonVirtBases {
135 unsigned IsVirtBase : 1;
136 unsigned NumberOfNonVirtBases : 31;
137 };
138 llvm::SmallDenseMap<QualType, IsVirtBaseAndNumberNonVirtBases, 8>
139 ClassSubobjects;
140
141 /// VisitedDependentRecords - Records the dependent records that have been
142 /// already visited.
143 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedDependentRecords;
144
145 /// DetectedVirtual - The base class that is virtual.
146 const RecordType *DetectedVirtual = nullptr;
147
148 /// ScratchPath - A BasePath that is used by Sema::lookupInBases
149 /// to help build the set of paths.
150 CXXBasePath ScratchPath;
151
152 /// FindAmbiguities - Whether Sema::IsDerivedFrom should try find
153 /// ambiguous paths while it is looking for a path from a derived
154 /// type to a base type.
155 bool FindAmbiguities;
156
157 /// RecordPaths - Whether Sema::IsDerivedFrom should record paths
158 /// while it is determining whether there are paths from a derived
159 /// type to a base type.
160 bool RecordPaths;
161
162 /// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search
163 /// if it finds a path that goes across a virtual base. The virtual class
164 /// is also recorded.
165 bool DetectVirtual;
166
167 bool lookupInBases(ASTContext &Context, const CXXRecordDecl *Record,
168 CXXRecordDecl::BaseMatchesCallback BaseMatches,
169 bool LookupInDependent = false);
170
171 public:
172 using paths_iterator = std::list<CXXBasePath>::iterator;
173 using const_paths_iterator = std::list<CXXBasePath>::const_iterator;
174 using decl_iterator = NamedDecl **;
175
176 /// BasePaths - Construct a new BasePaths structure to record the
177 /// paths for a derived-to-base search.
178 explicit CXXBasePaths(bool FindAmbiguities = true, bool RecordPaths = true,
179 bool DetectVirtual = true)
FindAmbiguities(FindAmbiguities)180 : FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths),
181 DetectVirtual(DetectVirtual) {}
182
begin()183 paths_iterator begin() { return Paths.begin(); }
end()184 paths_iterator end() { return Paths.end(); }
begin()185 const_paths_iterator begin() const { return Paths.begin(); }
end()186 const_paths_iterator end() const { return Paths.end(); }
187
front()188 CXXBasePath& front() { return Paths.front(); }
front()189 const CXXBasePath& front() const { return Paths.front(); }
190
191 using decl_range = llvm::iterator_range<decl_iterator>;
192
193 /// Determine whether the path from the most-derived type to the
194 /// given base type is ambiguous (i.e., it refers to multiple subobjects of
195 /// the same base type).
196 bool isAmbiguous(CanQualType BaseType);
197
198 /// Whether we are finding multiple paths to detect ambiguities.
isFindingAmbiguities()199 bool isFindingAmbiguities() const { return FindAmbiguities; }
200
201 /// Whether we are recording paths.
isRecordingPaths()202 bool isRecordingPaths() const { return RecordPaths; }
203
204 /// Specify whether we should be recording paths or not.
setRecordingPaths(bool RP)205 void setRecordingPaths(bool RP) { RecordPaths = RP; }
206
207 /// Whether we are detecting virtual bases.
isDetectingVirtual()208 bool isDetectingVirtual() const { return DetectVirtual; }
209
210 /// The virtual base discovered on the path (if we are merely
211 /// detecting virtuals).
getDetectedVirtual()212 const RecordType* getDetectedVirtual() const {
213 return DetectedVirtual;
214 }
215
216 /// Retrieve the type from which this base-paths search
217 /// began
getOrigin()218 const CXXRecordDecl *getOrigin() const { return Origin; }
setOrigin(const CXXRecordDecl * Rec)219 void setOrigin(const CXXRecordDecl *Rec) { Origin = Rec; }
220
221 /// Clear the base-paths results.
222 void clear();
223
224 /// Swap this data structure's contents with another CXXBasePaths
225 /// object.
226 void swap(CXXBasePaths &Other);
227 };
228
229 /// Uniquely identifies a virtual method within a class
230 /// hierarchy by the method itself and a class subobject number.
231 struct UniqueVirtualMethod {
232 /// The overriding virtual method.
233 CXXMethodDecl *Method = nullptr;
234
235 /// The subobject in which the overriding virtual method
236 /// resides.
237 unsigned Subobject = 0;
238
239 /// The virtual base class subobject of which this overridden
240 /// virtual method is a part. Note that this records the closest
241 /// derived virtual base class subobject.
242 const CXXRecordDecl *InVirtualSubobject = nullptr;
243
244 UniqueVirtualMethod() = default;
245
UniqueVirtualMethodUniqueVirtualMethod246 UniqueVirtualMethod(CXXMethodDecl *Method, unsigned Subobject,
247 const CXXRecordDecl *InVirtualSubobject)
248 : Method(Method), Subobject(Subobject),
249 InVirtualSubobject(InVirtualSubobject) {}
250
251 friend bool operator==(const UniqueVirtualMethod &X,
252 const UniqueVirtualMethod &Y) {
253 return X.Method == Y.Method && X.Subobject == Y.Subobject &&
254 X.InVirtualSubobject == Y.InVirtualSubobject;
255 }
256
257 friend bool operator!=(const UniqueVirtualMethod &X,
258 const UniqueVirtualMethod &Y) {
259 return !(X == Y);
260 }
261 };
262
263 /// The set of methods that override a given virtual method in
264 /// each subobject where it occurs.
265 ///
266 /// The first part of the pair is the subobject in which the
267 /// overridden virtual function occurs, while the second part of the
268 /// pair is the virtual method that overrides it (including the
269 /// subobject in which that virtual function occurs).
270 class OverridingMethods {
271 using ValuesT = SmallVector<UniqueVirtualMethod, 4>;
272 using MapType = llvm::MapVector<unsigned, ValuesT>;
273
274 MapType Overrides;
275
276 public:
277 // Iterate over the set of subobjects that have overriding methods.
278 using iterator = MapType::iterator;
279 using const_iterator = MapType::const_iterator;
280
begin()281 iterator begin() { return Overrides.begin(); }
begin()282 const_iterator begin() const { return Overrides.begin(); }
end()283 iterator end() { return Overrides.end(); }
end()284 const_iterator end() const { return Overrides.end(); }
size()285 unsigned size() const { return Overrides.size(); }
286
287 // Iterate over the set of overriding virtual methods in a given
288 // subobject.
289 using overriding_iterator =
290 SmallVectorImpl<UniqueVirtualMethod>::iterator;
291 using overriding_const_iterator =
292 SmallVectorImpl<UniqueVirtualMethod>::const_iterator;
293
294 // Add a new overriding method for a particular subobject.
295 void add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding);
296
297 // Add all of the overriding methods from "other" into overrides for
298 // this method. Used when merging the overrides from multiple base
299 // class subobjects.
300 void add(const OverridingMethods &Other);
301
302 // Replace all overriding virtual methods in all subobjects with the
303 // given virtual method.
304 void replaceAll(UniqueVirtualMethod Overriding);
305 };
306
307 /// A mapping from each virtual member function to its set of
308 /// final overriders.
309 ///
310 /// Within a class hierarchy for a given derived class, each virtual
311 /// member function in that hierarchy has one or more "final
312 /// overriders" (C++ [class.virtual]p2). A final overrider for a
313 /// virtual function "f" is the virtual function that will actually be
314 /// invoked when dispatching a call to "f" through the
315 /// vtable. Well-formed classes have a single final overrider for each
316 /// virtual function; in abstract classes, the final overrider for at
317 /// least one virtual function is a pure virtual function. Due to
318 /// multiple, virtual inheritance, it is possible for a class to have
319 /// more than one final overrider. Athough this is an error (per C++
320 /// [class.virtual]p2), it is not considered an error here: the final
321 /// overrider map can represent multiple final overriders for a
322 /// method, and it is up to the client to determine whether they are
323 /// problem. For example, the following class \c D has two final
324 /// overriders for the virtual function \c A::f(), one in \c C and one
325 /// in \c D:
326 ///
327 /// \code
328 /// struct A { virtual void f(); };
329 /// struct B : virtual A { virtual void f(); };
330 /// struct C : virtual A { virtual void f(); };
331 /// struct D : B, C { };
332 /// \endcode
333 ///
334 /// This data structure contains a mapping from every virtual
335 /// function *that does not override an existing virtual function* and
336 /// in every subobject where that virtual function occurs to the set
337 /// of virtual functions that override it. Thus, the same virtual
338 /// function \c A::f can actually occur in multiple subobjects of type
339 /// \c A due to multiple inheritance, and may be overridden by
340 /// different virtual functions in each, as in the following example:
341 ///
342 /// \code
343 /// struct A { virtual void f(); };
344 /// struct B : A { virtual void f(); };
345 /// struct C : A { virtual void f(); };
346 /// struct D : B, C { };
347 /// \endcode
348 ///
349 /// Unlike in the previous example, where the virtual functions \c
350 /// B::f and \c C::f both overrode \c A::f in the same subobject of
351 /// type \c A, in this example the two virtual functions both override
352 /// \c A::f but in *different* subobjects of type A. This is
353 /// represented by numbering the subobjects in which the overridden
354 /// and the overriding virtual member functions are located. Subobject
355 /// 0 represents the virtual base class subobject of that type, while
356 /// subobject numbers greater than 0 refer to non-virtual base class
357 /// subobjects of that type.
358 class CXXFinalOverriderMap
359 : public llvm::MapVector<const CXXMethodDecl *, OverridingMethods> {};
360
361 /// A set of all the primary bases for a class.
362 class CXXIndirectPrimaryBaseSet
363 : public llvm::SmallSet<const CXXRecordDecl*, 32> {};
364
365 inline bool
inheritanceModelHasVBPtrOffsetField(MSInheritanceModel Inheritance)366 inheritanceModelHasVBPtrOffsetField(MSInheritanceModel Inheritance) {
367 return Inheritance == MSInheritanceModel::Unspecified;
368 }
369
370 // Only member pointers to functions need a this adjustment, since it can be
371 // combined with the field offset for data pointers.
inheritanceModelHasNVOffsetField(bool IsMemberFunction,MSInheritanceModel Inheritance)372 inline bool inheritanceModelHasNVOffsetField(bool IsMemberFunction,
373 MSInheritanceModel Inheritance) {
374 return IsMemberFunction && Inheritance >= MSInheritanceModel::Multiple;
375 }
376
377 inline bool
inheritanceModelHasVBTableOffsetField(MSInheritanceModel Inheritance)378 inheritanceModelHasVBTableOffsetField(MSInheritanceModel Inheritance) {
379 return Inheritance >= MSInheritanceModel::Virtual;
380 }
381
inheritanceModelHasOnlyOneField(bool IsMemberFunction,MSInheritanceModel Inheritance)382 inline bool inheritanceModelHasOnlyOneField(bool IsMemberFunction,
383 MSInheritanceModel Inheritance) {
384 if (IsMemberFunction)
385 return Inheritance <= MSInheritanceModel::Single;
386 return Inheritance <= MSInheritanceModel::Multiple;
387 }
388
389 } // namespace clang
390
391 #endif // LLVM_CLANG_AST_CXXINHERITANCE_H
392