1//===- DeclCXX.h - Classes for representing C++ declarations --*- 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/// \file
10/// Defines the C++ Decl subclasses, other than those for templates
11/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLCXX_H
16#define LLVM_CLANG_AST_DECLCXX_H
17
18#include "clang/AST/ASTUnresolvedSet.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/LambdaCapture.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/Redeclarable.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/Lambda.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/OperatorKinds.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/Specifiers.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/TinyPtrVector.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/TrailingObjects.h"
48#include <cassert>
49#include <cstddef>
50#include <iterator>
51#include <memory>
52#include <vector>
53
54namespace clang {
55
56class ASTContext;
57class ClassTemplateDecl;
58class ConstructorUsingShadowDecl;
59class CXXBasePath;
60class CXXBasePaths;
61class CXXConstructorDecl;
62class CXXDestructorDecl;
63class CXXFinalOverriderMap;
64class CXXIndirectPrimaryBaseSet;
65class CXXMethodDecl;
66class DecompositionDecl;
67class FriendDecl;
68class FunctionTemplateDecl;
69class IdentifierInfo;
70class MemberSpecializationInfo;
71class BaseUsingDecl;
72class TemplateDecl;
73class TemplateParameterList;
74class UsingDecl;
75
76/// Represents an access specifier followed by colon ':'.
77///
78/// An objects of this class represents sugar for the syntactic occurrence
79/// of an access specifier followed by a colon in the list of member
80/// specifiers of a C++ class definition.
81///
82/// Note that they do not represent other uses of access specifiers,
83/// such as those occurring in a list of base specifiers.
84/// Also note that this class has nothing to do with so-called
85/// "access declarations" (C++98 11.3 [class.access.dcl]).
86class AccessSpecDecl : public Decl {
87 /// The location of the ':'.
88 SourceLocation ColonLoc;
89
90 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
91 SourceLocation ASLoc, SourceLocation ColonLoc)
92 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
93 setAccess(AS);
94 }
95
96 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
97
98 virtual void anchor();
99
100public:
101 /// The location of the access specifier.
102 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
103
104 /// Sets the location of the access specifier.
105 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
106
107 /// The location of the colon following the access specifier.
108 SourceLocation getColonLoc() const { return ColonLoc; }
109
110 /// Sets the location of the colon.
111 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
112
113 SourceRange getSourceRange() const override LLVM_READONLY {
114 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
115 }
116
117 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
118 DeclContext *DC, SourceLocation ASLoc,
119 SourceLocation ColonLoc) {
120 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
121 }
122
123 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
124
125 // Implement isa/cast/dyncast/etc.
126 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
127 static bool classofKind(Kind K) { return K == AccessSpec; }
128};
129
130/// Represents a base class of a C++ class.
131///
132/// Each CXXBaseSpecifier represents a single, direct base class (or
133/// struct) of a C++ class (or struct). It specifies the type of that
134/// base class, whether it is a virtual or non-virtual base, and what
135/// level of access (public, protected, private) is used for the
136/// derivation. For example:
137///
138/// \code
139/// class A { };
140/// class B { };
141/// class C : public virtual A, protected B { };
142/// \endcode
143///
144/// In this code, C will have two CXXBaseSpecifiers, one for "public
145/// virtual A" and the other for "protected B".
146class CXXBaseSpecifier {
147 /// The source code range that covers the full base
148 /// specifier, including the "virtual" (if present) and access
149 /// specifier (if present).
150 SourceRange Range;
151
152 /// The source location of the ellipsis, if this is a pack
153 /// expansion.
154 SourceLocation EllipsisLoc;
155
156 /// Whether this is a virtual base class or not.
157 unsigned Virtual : 1;
158
159 /// Whether this is the base of a class (true) or of a struct (false).
160 ///
161 /// This determines the mapping from the access specifier as written in the
162 /// source code to the access specifier used for semantic analysis.
163 unsigned BaseOfClass : 1;
164
165 /// Access specifier as written in the source code (may be AS_none).
166 ///
167 /// The actual type of data stored here is an AccessSpecifier, but we use
168 /// "unsigned" here to work around a VC++ bug.
169 unsigned Access : 2;
170
171 /// Whether the class contains a using declaration
172 /// to inherit the named class's constructors.
173 unsigned InheritConstructors : 1;
174
175 /// The type of the base class.
176 ///
177 /// This will be a class or struct (or a typedef of such). The source code
178 /// range does not include the \c virtual or the access specifier.
179 TypeSourceInfo *BaseTypeInfo;
180
181public:
182 CXXBaseSpecifier() = default;
183 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
184 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
185 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
186 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
187
188 /// Retrieves the source range that contains the entire base specifier.
189 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
190 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
191 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
192
193 /// Get the location at which the base class type was written.
194 SourceLocation getBaseTypeLoc() const LLVM_READONLY {
195 return BaseTypeInfo->getTypeLoc().getBeginLoc();
196 }
197
198 /// Determines whether the base class is a virtual base class (or not).
199 bool isVirtual() const { return Virtual; }
200
201 /// Determine whether this base class is a base of a class declared
202 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
203 bool isBaseOfClass() const { return BaseOfClass; }
204
205 /// Determine whether this base specifier is a pack expansion.
206 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
207
208 /// Determine whether this base class's constructors get inherited.
209 bool getInheritConstructors() const { return InheritConstructors; }
210
211 /// Set that this base class's constructors should be inherited.
212 void setInheritConstructors(bool Inherit = true) {
213 InheritConstructors = Inherit;
214 }
215
216 /// For a pack expansion, determine the location of the ellipsis.
217 SourceLocation getEllipsisLoc() const {
218 return EllipsisLoc;
219 }
220
221 /// Returns the access specifier for this base specifier.
222 ///
223 /// This is the actual base specifier as used for semantic analysis, so
224 /// the result can never be AS_none. To retrieve the access specifier as
225 /// written in the source code, use getAccessSpecifierAsWritten().
226 AccessSpecifier getAccessSpecifier() const {
227 if ((AccessSpecifier)Access == AS_none)
228 return BaseOfClass? AS_private : AS_public;
229 else
230 return (AccessSpecifier)Access;
231 }
232
233 /// Retrieves the access specifier as written in the source code
234 /// (which may mean that no access specifier was explicitly written).
235 ///
236 /// Use getAccessSpecifier() to retrieve the access specifier for use in
237 /// semantic analysis.
238 AccessSpecifier getAccessSpecifierAsWritten() const {
239 return (AccessSpecifier)Access;
240 }
241
242 /// Retrieves the type of the base class.
243 ///
244 /// This type will always be an unqualified class type.
245 QualType getType() const {
246 return BaseTypeInfo->getType().getUnqualifiedType();
247 }
248
249 /// Retrieves the type and source location of the base class.
250 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
251};
252
253/// Represents a C++ struct/union/class.
254class CXXRecordDecl : public RecordDecl {
255 friend class ASTDeclReader;
256 friend class ASTDeclWriter;
257 friend class ASTNodeImporter;
258 friend class ASTReader;
259 friend class ASTRecordWriter;
260 friend class ASTWriter;
261 friend class DeclContext;
262 friend class LambdaExpr;
263 friend class ODRDiagsEmitter;
264
265 friend void FunctionDecl::setPure(bool);
266 friend void TagDecl::startDefinition();
267
268 /// Values used in DefinitionData fields to represent special members.
269 enum SpecialMemberFlags {
270 SMF_DefaultConstructor = 0x1,
271 SMF_CopyConstructor = 0x2,
272 SMF_MoveConstructor = 0x4,
273 SMF_CopyAssignment = 0x8,
274 SMF_MoveAssignment = 0x10,
275 SMF_Destructor = 0x20,
276 SMF_All = 0x3f
277 };
278
279public:
280 enum LambdaDependencyKind {
281 LDK_Unknown = 0,
282 LDK_AlwaysDependent,
283 LDK_NeverDependent,
284 };
285
286private:
287 struct DefinitionData {
288 #define FIELD(Name, Width, Merge) \
289 unsigned Name : Width;
290 #include "CXXRecordDeclDefinitionBits.def"
291
292 /// Whether this class describes a C++ lambda.
293 unsigned IsLambda : 1;
294
295 /// Whether we are currently parsing base specifiers.
296 unsigned IsParsingBaseSpecifiers : 1;
297
298 /// True when visible conversion functions are already computed
299 /// and are available.
300 unsigned ComputedVisibleConversions : 1;
301
302 unsigned HasODRHash : 1;
303
304 /// A hash of parts of the class to help in ODR checking.
305 unsigned ODRHash = 0;
306
307 /// The number of base class specifiers in Bases.
308 unsigned NumBases = 0;
309
310 /// The number of virtual base class specifiers in VBases.
311 unsigned NumVBases = 0;
312
313 /// Base classes of this class.
314 ///
315 /// FIXME: This is wasted space for a union.
316 LazyCXXBaseSpecifiersPtr Bases;
317
318 /// direct and indirect virtual base classes of this class.
319 LazyCXXBaseSpecifiersPtr VBases;
320
321 /// The conversion functions of this C++ class (but not its
322 /// inherited conversion functions).
323 ///
324 /// Each of the entries in this overload set is a CXXConversionDecl.
325 LazyASTUnresolvedSet Conversions;
326
327 /// The conversion functions of this C++ class and all those
328 /// inherited conversion functions that are visible in this class.
329 ///
330 /// Each of the entries in this overload set is a CXXConversionDecl or a
331 /// FunctionTemplateDecl.
332 LazyASTUnresolvedSet VisibleConversions;
333
334 /// The declaration which defines this record.
335 CXXRecordDecl *Definition;
336
337 /// The first friend declaration in this class, or null if there
338 /// aren't any.
339 ///
340 /// This is actually currently stored in reverse order.
341 LazyDeclPtr FirstFriend;
342
343 DefinitionData(CXXRecordDecl *D);
344
345 /// Retrieve the set of direct base classes.
346 CXXBaseSpecifier *getBases() const {
347 if (!Bases.isOffset())
348 return Bases.get(nullptr);
349 return getBasesSlowCase();
350 }
351
352 /// Retrieve the set of virtual base classes.
353 CXXBaseSpecifier *getVBases() const {
354 if (!VBases.isOffset())
355 return VBases.get(nullptr);
356 return getVBasesSlowCase();
357 }
358
359 ArrayRef<CXXBaseSpecifier> bases() const {
360 return llvm::ArrayRef(getBases(), NumBases);
361 }
362
363 ArrayRef<CXXBaseSpecifier> vbases() const {
364 return llvm::ArrayRef(getVBases(), NumVBases);
365 }
366
367 private:
368 CXXBaseSpecifier *getBasesSlowCase() const;
369 CXXBaseSpecifier *getVBasesSlowCase() const;
370 };
371
372 struct DefinitionData *DefinitionData;
373
374 /// Describes a C++ closure type (generated by a lambda expression).
375 struct LambdaDefinitionData : public DefinitionData {
376 using Capture = LambdaCapture;
377
378 /// Whether this lambda is known to be dependent, even if its
379 /// context isn't dependent.
380 ///
381 /// A lambda with a non-dependent context can be dependent if it occurs
382 /// within the default argument of a function template, because the
383 /// lambda will have been created with the enclosing context as its
384 /// declaration context, rather than function. This is an unfortunate
385 /// artifact of having to parse the default arguments before.
386 unsigned DependencyKind : 2;
387
388 /// Whether this lambda is a generic lambda.
389 unsigned IsGenericLambda : 1;
390
391 /// The Default Capture.
392 unsigned CaptureDefault : 2;
393
394 /// The number of captures in this lambda is limited 2^NumCaptures.
395 unsigned NumCaptures : 15;
396
397 /// The number of explicit captures in this lambda.
398 unsigned NumExplicitCaptures : 12;
399
400 /// Has known `internal` linkage.
401 unsigned HasKnownInternalLinkage : 1;
402
403 /// The number used to indicate this lambda expression for name
404 /// mangling in the Itanium C++ ABI.
405 unsigned ManglingNumber : 31;
406
407 /// The index of this lambda within its context declaration. This is not in
408 /// general the same as the mangling number.
409 unsigned IndexInContext;
410
411 /// The declaration that provides context for this lambda, if the
412 /// actual DeclContext does not suffice. This is used for lambdas that
413 /// occur within default arguments of function parameters within the class
414 /// or within a data member initializer.
415 LazyDeclPtr ContextDecl;
416
417 /// The lists of captures, both explicit and implicit, for this
418 /// lambda. One list is provided for each merged copy of the lambda.
419 /// The first list corresponds to the canonical definition.
420 /// The destructor is registered by AddCaptureList when necessary.
421 llvm::TinyPtrVector<Capture*> Captures;
422
423 /// The type of the call method.
424 TypeSourceInfo *MethodTyInfo;
425
426 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, unsigned DK,
427 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
428 : DefinitionData(D), DependencyKind(DK), IsGenericLambda(IsGeneric),
429 CaptureDefault(CaptureDefault), NumCaptures(0),
430 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
431 IndexInContext(0), MethodTyInfo(Info) {
432 IsLambda = true;
433
434 // C++1z [expr.prim.lambda]p4:
435 // This class type is not an aggregate type.
436 Aggregate = false;
437 PlainOldData = false;
438 }
439
440 // Add a list of captures.
441 void AddCaptureList(ASTContext &Ctx, Capture *CaptureList);
442 };
443
444 struct DefinitionData *dataPtr() const {
445 // Complete the redecl chain (if necessary).
446 getMostRecentDecl();
447 return DefinitionData;
448 }
449
450 struct DefinitionData &data() const {
451 auto *DD = dataPtr();
452 assert(DD && "queried property of class with no definition");
453 return *DD;
454 }
455
456 struct LambdaDefinitionData &getLambdaData() const {
457 // No update required: a merged definition cannot change any lambda
458 // properties.
459 auto *DD = DefinitionData;
460 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
461 return static_cast<LambdaDefinitionData&>(*DD);
462 }
463
464 /// The template or declaration that this declaration
465 /// describes or was instantiated from, respectively.
466 ///
467 /// For non-templates, this value will be null. For record
468 /// declarations that describe a class template, this will be a
469 /// pointer to a ClassTemplateDecl. For member
470 /// classes of class template specializations, this will be the
471 /// MemberSpecializationInfo referring to the member class that was
472 /// instantiated or specialized.
473 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
474 TemplateOrInstantiation;
475
476 /// Called from setBases and addedMember to notify the class that a
477 /// direct or virtual base class or a member of class type has been added.
478 void addedClassSubobject(CXXRecordDecl *Base);
479
480 /// Notify the class that member has been added.
481 ///
482 /// This routine helps maintain information about the class based on which
483 /// members have been added. It will be invoked by DeclContext::addDecl()
484 /// whenever a member is added to this record.
485 void addedMember(Decl *D);
486
487 void markedVirtualFunctionPure();
488
489 /// Get the head of our list of friend declarations, possibly
490 /// deserializing the friends from an external AST source.
491 FriendDecl *getFirstFriend() const;
492
493 /// Determine whether this class has an empty base class subobject of type X
494 /// or of one of the types that might be at offset 0 within X (per the C++
495 /// "standard layout" rules).
496 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
497 const CXXRecordDecl *X);
498
499protected:
500 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
501 SourceLocation StartLoc, SourceLocation IdLoc,
502 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
503
504public:
505 /// Iterator that traverses the base classes of a class.
506 using base_class_iterator = CXXBaseSpecifier *;
507
508 /// Iterator that traverses the base classes of a class.
509 using base_class_const_iterator = const CXXBaseSpecifier *;
510
511 CXXRecordDecl *getCanonicalDecl() override {
512 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
513 }
514
515 const CXXRecordDecl *getCanonicalDecl() const {
516 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
517 }
518
519 CXXRecordDecl *getPreviousDecl() {
520 return cast_or_null<CXXRecordDecl>(
521 static_cast<RecordDecl *>(this)->getPreviousDecl());
522 }
523
524 const CXXRecordDecl *getPreviousDecl() const {
525 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
526 }
527
528 CXXRecordDecl *getMostRecentDecl() {
529 return cast<CXXRecordDecl>(
530 static_cast<RecordDecl *>(this)->getMostRecentDecl());
531 }
532
533 const CXXRecordDecl *getMostRecentDecl() const {
534 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
535 }
536
537 CXXRecordDecl *getMostRecentNonInjectedDecl() {
538 CXXRecordDecl *Recent =
539 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
540 while (Recent->isInjectedClassName()) {
541 // FIXME: Does injected class name need to be in the redeclarations chain?
542 assert(Recent->getPreviousDecl());
543 Recent = Recent->getPreviousDecl();
544 }
545 return Recent;
546 }
547
548 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
549 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
550 }
551
552 CXXRecordDecl *getDefinition() const {
553 // We only need an update if we don't already know which
554 // declaration is the definition.
555 auto *DD = DefinitionData ? DefinitionData : dataPtr();
556 return DD ? DD->Definition : nullptr;
557 }
558
559 bool hasDefinition() const { return DefinitionData || dataPtr(); }
560
561 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
562 SourceLocation StartLoc, SourceLocation IdLoc,
563 IdentifierInfo *Id,
564 CXXRecordDecl *PrevDecl = nullptr,
565 bool DelayTypeCreation = false);
566 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
567 TypeSourceInfo *Info, SourceLocation Loc,
568 unsigned DependencyKind, bool IsGeneric,
569 LambdaCaptureDefault CaptureDefault);
570 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
571
572 bool isDynamicClass() const {
573 return data().Polymorphic || data().NumVBases != 0;
574 }
575
576 /// @returns true if class is dynamic or might be dynamic because the
577 /// definition is incomplete of dependent.
578 bool mayBeDynamicClass() const {
579 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
580 }
581
582 /// @returns true if class is non dynamic or might be non dynamic because the
583 /// definition is incomplete of dependent.
584 bool mayBeNonDynamicClass() const {
585 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
586 }
587
588 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
589
590 bool isParsingBaseSpecifiers() const {
591 return data().IsParsingBaseSpecifiers;
592 }
593
594 unsigned getODRHash() const;
595
596 /// Sets the base classes of this struct or class.
597 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
598
599 /// Retrieves the number of base classes of this class.
600 unsigned getNumBases() const { return data().NumBases; }
601
602 using base_class_range = llvm::iterator_range<base_class_iterator>;
603 using base_class_const_range =
604 llvm::iterator_range<base_class_const_iterator>;
605
606 base_class_range bases() {
607 return base_class_range(bases_begin(), bases_end());
608 }
609 base_class_const_range bases() const {
610 return base_class_const_range(bases_begin(), bases_end());
611 }
612
613 base_class_iterator bases_begin() { return data().getBases(); }
614 base_class_const_iterator bases_begin() const { return data().getBases(); }
615 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
616 base_class_const_iterator bases_end() const {
617 return bases_begin() + data().NumBases;
618 }
619
620 /// Retrieves the number of virtual base classes of this class.
621 unsigned getNumVBases() const { return data().NumVBases; }
622
623 base_class_range vbases() {
624 return base_class_range(vbases_begin(), vbases_end());
625 }
626 base_class_const_range vbases() const {
627 return base_class_const_range(vbases_begin(), vbases_end());
628 }
629
630 base_class_iterator vbases_begin() { return data().getVBases(); }
631 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
632 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
633 base_class_const_iterator vbases_end() const {
634 return vbases_begin() + data().NumVBases;
635 }
636
637 /// Determine whether this class has any dependent base classes which
638 /// are not the current instantiation.
639 bool hasAnyDependentBases() const;
640
641 /// Iterator access to method members. The method iterator visits
642 /// all method members of the class, including non-instance methods,
643 /// special methods, etc.
644 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
645 using method_range =
646 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
647
648 method_range methods() const {
649 return method_range(method_begin(), method_end());
650 }
651
652 /// Method begin iterator. Iterates in the order the methods
653 /// were declared.
654 method_iterator method_begin() const {
655 return method_iterator(decls_begin());
656 }
657
658 /// Method past-the-end iterator.
659 method_iterator method_end() const {
660 return method_iterator(decls_end());
661 }
662
663 /// Iterator access to constructor members.
664 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
665 using ctor_range =
666 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
667
668 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
669
670 ctor_iterator ctor_begin() const {
671 return ctor_iterator(decls_begin());
672 }
673
674 ctor_iterator ctor_end() const {
675 return ctor_iterator(decls_end());
676 }
677
678 /// An iterator over friend declarations. All of these are defined
679 /// in DeclFriend.h.
680 class friend_iterator;
681 using friend_range = llvm::iterator_range<friend_iterator>;
682
683 friend_range friends() const;
684 friend_iterator friend_begin() const;
685 friend_iterator friend_end() const;
686 void pushFriendDecl(FriendDecl *FD);
687
688 /// Determines whether this record has any friends.
689 bool hasFriends() const {
690 return data().FirstFriend.isValid();
691 }
692
693 /// \c true if a defaulted copy constructor for this class would be
694 /// deleted.
695 bool defaultedCopyConstructorIsDeleted() const {
696 assert((!needsOverloadResolutionForCopyConstructor() ||
697 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
698 "this property has not yet been computed by Sema");
699 return data().DefaultedCopyConstructorIsDeleted;
700 }
701
702 /// \c true if a defaulted move constructor for this class would be
703 /// deleted.
704 bool defaultedMoveConstructorIsDeleted() const {
705 assert((!needsOverloadResolutionForMoveConstructor() ||
706 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
707 "this property has not yet been computed by Sema");
708 return data().DefaultedMoveConstructorIsDeleted;
709 }
710
711 /// \c true if a defaulted destructor for this class would be deleted.
712 bool defaultedDestructorIsDeleted() const {
713 assert((!needsOverloadResolutionForDestructor() ||
714 (data().DeclaredSpecialMembers & SMF_Destructor)) &&
715 "this property has not yet been computed by Sema");
716 return data().DefaultedDestructorIsDeleted;
717 }
718
719 /// \c true if we know for sure that this class has a single,
720 /// accessible, unambiguous copy constructor that is not deleted.
721 bool hasSimpleCopyConstructor() const {
722 return !hasUserDeclaredCopyConstructor() &&
723 !data().DefaultedCopyConstructorIsDeleted;
724 }
725
726 /// \c true if we know for sure that this class has a single,
727 /// accessible, unambiguous move constructor that is not deleted.
728 bool hasSimpleMoveConstructor() const {
729 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
730 !data().DefaultedMoveConstructorIsDeleted;
731 }
732
733 /// \c true if we know for sure that this class has a single,
734 /// accessible, unambiguous copy assignment operator that is not deleted.
735 bool hasSimpleCopyAssignment() const {
736 return !hasUserDeclaredCopyAssignment() &&
737 !data().DefaultedCopyAssignmentIsDeleted;
738 }
739
740 /// \c true if we know for sure that this class has a single,
741 /// accessible, unambiguous move assignment operator that is not deleted.
742 bool hasSimpleMoveAssignment() const {
743 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
744 !data().DefaultedMoveAssignmentIsDeleted;
745 }
746
747 /// \c true if we know for sure that this class has an accessible
748 /// destructor that is not deleted.
749 bool hasSimpleDestructor() const {
750 return !hasUserDeclaredDestructor() &&
751 !data().DefaultedDestructorIsDeleted;
752 }
753
754 /// Determine whether this class has any default constructors.
755 bool hasDefaultConstructor() const {
756 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
757 needsImplicitDefaultConstructor();
758 }
759
760 /// Determine if we need to declare a default constructor for
761 /// this class.
762 ///
763 /// This value is used for lazy creation of default constructors.
764 bool needsImplicitDefaultConstructor() const {
765 return (!data().UserDeclaredConstructor &&
766 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
767 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable())) ||
768 // FIXME: Proposed fix to core wording issue: if a class inherits
769 // a default constructor and doesn't explicitly declare one, one
770 // is declared implicitly.
771 (data().HasInheritedDefaultConstructor &&
772 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
773 }
774
775 /// Determine whether this class has any user-declared constructors.
776 ///
777 /// When true, a default constructor will not be implicitly declared.
778 bool hasUserDeclaredConstructor() const {
779 return data().UserDeclaredConstructor;
780 }
781
782 /// Whether this class has a user-provided default constructor
783 /// per C++11.
784 bool hasUserProvidedDefaultConstructor() const {
785 return data().UserProvidedDefaultConstructor;
786 }
787
788 /// Determine whether this class has a user-declared copy constructor.
789 ///
790 /// When false, a copy constructor will be implicitly declared.
791 bool hasUserDeclaredCopyConstructor() const {
792 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
793 }
794
795 /// Determine whether this class needs an implicit copy
796 /// constructor to be lazily declared.
797 bool needsImplicitCopyConstructor() const {
798 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
799 }
800
801 /// Determine whether we need to eagerly declare a defaulted copy
802 /// constructor for this class.
803 bool needsOverloadResolutionForCopyConstructor() const {
804 // C++17 [class.copy.ctor]p6:
805 // If the class definition declares a move constructor or move assignment
806 // operator, the implicitly declared copy constructor is defined as
807 // deleted.
808 // In MSVC mode, sometimes a declared move assignment does not delete an
809 // implicit copy constructor, so defer this choice to Sema.
810 if (data().UserDeclaredSpecialMembers &
811 (SMF_MoveConstructor | SMF_MoveAssignment))
812 return true;
813 return data().NeedOverloadResolutionForCopyConstructor;
814 }
815
816 /// Determine whether an implicit copy constructor for this type
817 /// would have a parameter with a const-qualified reference type.
818 bool implicitCopyConstructorHasConstParam() const {
819 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
820 (isAbstract() ||
821 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
822 }
823
824 /// Determine whether this class has a copy constructor with
825 /// a parameter type which is a reference to a const-qualified type.
826 bool hasCopyConstructorWithConstParam() const {
827 return data().HasDeclaredCopyConstructorWithConstParam ||
828 (needsImplicitCopyConstructor() &&
829 implicitCopyConstructorHasConstParam());
830 }
831
832 /// Whether this class has a user-declared move constructor or
833 /// assignment operator.
834 ///
835 /// When false, a move constructor and assignment operator may be
836 /// implicitly declared.
837 bool hasUserDeclaredMoveOperation() const {
838 return data().UserDeclaredSpecialMembers &
839 (SMF_MoveConstructor | SMF_MoveAssignment);
840 }
841
842 /// Determine whether this class has had a move constructor
843 /// declared by the user.
844 bool hasUserDeclaredMoveConstructor() const {
845 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
846 }
847
848 /// Determine whether this class has a move constructor.
849 bool hasMoveConstructor() const {
850 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
851 needsImplicitMoveConstructor();
852 }
853
854 /// Set that we attempted to declare an implicit copy
855 /// constructor, but overload resolution failed so we deleted it.
856 void setImplicitCopyConstructorIsDeleted() {
857 assert((data().DefaultedCopyConstructorIsDeleted ||
858 needsOverloadResolutionForCopyConstructor()) &&
859 "Copy constructor should not be deleted");
860 data().DefaultedCopyConstructorIsDeleted = true;
861 }
862
863 /// Set that we attempted to declare an implicit move
864 /// constructor, but overload resolution failed so we deleted it.
865 void setImplicitMoveConstructorIsDeleted() {
866 assert((data().DefaultedMoveConstructorIsDeleted ||
867 needsOverloadResolutionForMoveConstructor()) &&
868 "move constructor should not be deleted");
869 data().DefaultedMoveConstructorIsDeleted = true;
870 }
871
872 /// Set that we attempted to declare an implicit destructor,
873 /// but overload resolution failed so we deleted it.
874 void setImplicitDestructorIsDeleted() {
875 assert((data().DefaultedDestructorIsDeleted ||
876 needsOverloadResolutionForDestructor()) &&
877 "destructor should not be deleted");
878 data().DefaultedDestructorIsDeleted = true;
879 }
880
881 /// Determine whether this class should get an implicit move
882 /// constructor or if any existing special member function inhibits this.
883 bool needsImplicitMoveConstructor() const {
884 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
885 !hasUserDeclaredCopyConstructor() &&
886 !hasUserDeclaredCopyAssignment() &&
887 !hasUserDeclaredMoveAssignment() &&
888 !hasUserDeclaredDestructor();
889 }
890
891 /// Determine whether we need to eagerly declare a defaulted move
892 /// constructor for this class.
893 bool needsOverloadResolutionForMoveConstructor() const {
894 return data().NeedOverloadResolutionForMoveConstructor;
895 }
896
897 /// Determine whether this class has a user-declared copy assignment
898 /// operator.
899 ///
900 /// When false, a copy assignment operator will be implicitly declared.
901 bool hasUserDeclaredCopyAssignment() const {
902 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
903 }
904
905 /// Set that we attempted to declare an implicit copy assignment
906 /// operator, but overload resolution failed so we deleted it.
907 void setImplicitCopyAssignmentIsDeleted() {
908 assert((data().DefaultedCopyAssignmentIsDeleted ||
909 needsOverloadResolutionForCopyAssignment()) &&
910 "copy assignment should not be deleted");
911 data().DefaultedCopyAssignmentIsDeleted = true;
912 }
913
914 /// Determine whether this class needs an implicit copy
915 /// assignment operator to be lazily declared.
916 bool needsImplicitCopyAssignment() const {
917 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
918 }
919
920 /// Determine whether we need to eagerly declare a defaulted copy
921 /// assignment operator for this class.
922 bool needsOverloadResolutionForCopyAssignment() const {
923 // C++20 [class.copy.assign]p2:
924 // If the class definition declares a move constructor or move assignment
925 // operator, the implicitly declared copy assignment operator is defined
926 // as deleted.
927 // In MSVC mode, sometimes a declared move constructor does not delete an
928 // implicit copy assignment, so defer this choice to Sema.
929 if (data().UserDeclaredSpecialMembers &
930 (SMF_MoveConstructor | SMF_MoveAssignment))
931 return true;
932 return data().NeedOverloadResolutionForCopyAssignment;
933 }
934
935 /// Determine whether an implicit copy assignment operator for this
936 /// type would have a parameter with a const-qualified reference type.
937 bool implicitCopyAssignmentHasConstParam() const {
938 return data().ImplicitCopyAssignmentHasConstParam;
939 }
940
941 /// Determine whether this class has a copy assignment operator with
942 /// a parameter type which is a reference to a const-qualified type or is not
943 /// a reference.
944 bool hasCopyAssignmentWithConstParam() const {
945 return data().HasDeclaredCopyAssignmentWithConstParam ||
946 (needsImplicitCopyAssignment() &&
947 implicitCopyAssignmentHasConstParam());
948 }
949
950 /// Determine whether this class has had a move assignment
951 /// declared by the user.
952 bool hasUserDeclaredMoveAssignment() const {
953 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
954 }
955
956 /// Determine whether this class has a move assignment operator.
957 bool hasMoveAssignment() const {
958 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
959 needsImplicitMoveAssignment();
960 }
961
962 /// Set that we attempted to declare an implicit move assignment
963 /// operator, but overload resolution failed so we deleted it.
964 void setImplicitMoveAssignmentIsDeleted() {
965 assert((data().DefaultedMoveAssignmentIsDeleted ||
966 needsOverloadResolutionForMoveAssignment()) &&
967 "move assignment should not be deleted");
968 data().DefaultedMoveAssignmentIsDeleted = true;
969 }
970
971 /// Determine whether this class should get an implicit move
972 /// assignment operator or if any existing special member function inhibits
973 /// this.
974 bool needsImplicitMoveAssignment() const {
975 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
976 !hasUserDeclaredCopyConstructor() &&
977 !hasUserDeclaredCopyAssignment() &&
978 !hasUserDeclaredMoveConstructor() &&
979 !hasUserDeclaredDestructor() &&
980 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
981 }
982
983 /// Determine whether we need to eagerly declare a move assignment
984 /// operator for this class.
985 bool needsOverloadResolutionForMoveAssignment() const {
986 return data().NeedOverloadResolutionForMoveAssignment;
987 }
988
989 /// Determine whether this class has a user-declared destructor.
990 ///
991 /// When false, a destructor will be implicitly declared.
992 bool hasUserDeclaredDestructor() const {
993 return data().UserDeclaredSpecialMembers & SMF_Destructor;
994 }
995
996 /// Determine whether this class needs an implicit destructor to
997 /// be lazily declared.
998 bool needsImplicitDestructor() const {
999 return !(data().DeclaredSpecialMembers & SMF_Destructor);
1000 }
1001
1002 /// Determine whether we need to eagerly declare a destructor for this
1003 /// class.
1004 bool needsOverloadResolutionForDestructor() const {
1005 return data().NeedOverloadResolutionForDestructor;
1006 }
1007
1008 /// Determine whether this class describes a lambda function object.
1009 bool isLambda() const {
1010 // An update record can't turn a non-lambda into a lambda.
1011 auto *DD = DefinitionData;
1012 return DD && DD->IsLambda;
1013 }
1014
1015 /// Determine whether this class describes a generic
1016 /// lambda function object (i.e. function call operator is
1017 /// a template).
1018 bool isGenericLambda() const;
1019
1020 /// Determine whether this lambda should have an implicit default constructor
1021 /// and copy and move assignment operators.
1022 bool lambdaIsDefaultConstructibleAndAssignable() const;
1023
1024 /// Retrieve the lambda call operator of the closure type
1025 /// if this is a closure type.
1026 CXXMethodDecl *getLambdaCallOperator() const;
1027
1028 /// Retrieve the dependent lambda call operator of the closure type
1029 /// if this is a templated closure type.
1030 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1031
1032 /// Retrieve the lambda static invoker, the address of which
1033 /// is returned by the conversion operator, and the body of which
1034 /// is forwarded to the lambda call operator. The version that does not
1035 /// take a calling convention uses the 'default' calling convention for free
1036 /// functions if the Lambda's calling convention was not modified via
1037 /// attribute. Otherwise, it will return the calling convention specified for
1038 /// the lambda.
1039 CXXMethodDecl *getLambdaStaticInvoker() const;
1040 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1041
1042 /// Retrieve the generic lambda's template parameter list.
1043 /// Returns null if the class does not represent a lambda or a generic
1044 /// lambda.
1045 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1046
1047 /// Retrieve the lambda template parameters that were specified explicitly.
1048 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1049
1050 LambdaCaptureDefault getLambdaCaptureDefault() const {
1051 assert(isLambda());
1052 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1053 }
1054
1055 /// Set the captures for this lambda closure type.
1056 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1057
1058 /// For a closure type, retrieve the mapping from captured
1059 /// variables and \c this to the non-static data members that store the
1060 /// values or references of the captures.
1061 ///
1062 /// \param Captures Will be populated with the mapping from captured
1063 /// variables to the corresponding fields.
1064 ///
1065 /// \param ThisCapture Will be set to the field declaration for the
1066 /// \c this capture.
1067 ///
1068 /// \note No entries will be added for init-captures, as they do not capture
1069 /// variables.
1070 ///
1071 /// \note If multiple versions of the lambda are merged together, they may
1072 /// have different variable declarations corresponding to the same capture.
1073 /// In that case, all of those variable declarations will be added to the
1074 /// Captures list, so it may have more than one variable listed per field.
1075 void
1076 getCaptureFields(llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,
1077 FieldDecl *&ThisCapture) const;
1078
1079 using capture_const_iterator = const LambdaCapture *;
1080 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1081
1082 capture_const_range captures() const {
1083 return capture_const_range(captures_begin(), captures_end());
1084 }
1085
1086 capture_const_iterator captures_begin() const {
1087 if (!isLambda()) return nullptr;
1088 LambdaDefinitionData &LambdaData = getLambdaData();
1089 return LambdaData.Captures.empty() ? nullptr : LambdaData.Captures.front();
1090 }
1091
1092 capture_const_iterator captures_end() const {
1093 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1094 : nullptr;
1095 }
1096
1097 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1098
1099 const LambdaCapture *getCapture(unsigned I) const {
1100 assert(isLambda() && I < capture_size() && "invalid index for capture");
1101 return captures_begin() + I;
1102 }
1103
1104 using conversion_iterator = UnresolvedSetIterator;
1105
1106 conversion_iterator conversion_begin() const {
1107 return data().Conversions.get(getASTContext()).begin();
1108 }
1109
1110 conversion_iterator conversion_end() const {
1111 return data().Conversions.get(getASTContext()).end();
1112 }
1113
1114 /// Removes a conversion function from this class. The conversion
1115 /// function must currently be a member of this class. Furthermore,
1116 /// this class must currently be in the process of being defined.
1117 void removeConversion(const NamedDecl *Old);
1118
1119 /// Get all conversion functions visible in current class,
1120 /// including conversion function templates.
1121 llvm::iterator_range<conversion_iterator>
1122 getVisibleConversionFunctions() const;
1123
1124 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1125 /// which is a class with no user-declared constructors, no private
1126 /// or protected non-static data members, no base classes, and no virtual
1127 /// functions (C++ [dcl.init.aggr]p1).
1128 bool isAggregate() const { return data().Aggregate; }
1129
1130 /// Whether this class has any in-class initializers
1131 /// for non-static data members (including those in anonymous unions or
1132 /// structs).
1133 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1134
1135 /// Whether this class or any of its subobjects has any members of
1136 /// reference type which would make value-initialization ill-formed.
1137 ///
1138 /// Per C++03 [dcl.init]p5:
1139 /// - if T is a non-union class type without a user-declared constructor,
1140 /// then every non-static data member and base-class component of T is
1141 /// value-initialized [...] A program that calls for [...]
1142 /// value-initialization of an entity of reference type is ill-formed.
1143 bool hasUninitializedReferenceMember() const {
1144 return !isUnion() && !hasUserDeclaredConstructor() &&
1145 data().HasUninitializedReferenceMember;
1146 }
1147
1148 /// Whether this class is a POD-type (C++ [class]p4)
1149 ///
1150 /// For purposes of this function a class is POD if it is an aggregate
1151 /// that has no non-static non-POD data members, no reference data
1152 /// members, no user-defined copy assignment operator and no
1153 /// user-defined destructor.
1154 ///
1155 /// Note that this is the C++ TR1 definition of POD.
1156 bool isPOD() const { return data().PlainOldData; }
1157
1158 /// True if this class is C-like, without C++-specific features, e.g.
1159 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1160 bool isCLike() const;
1161
1162 /// Determine whether this is an empty class in the sense of
1163 /// (C++11 [meta.unary.prop]).
1164 ///
1165 /// The CXXRecordDecl is a class type, but not a union type,
1166 /// with no non-static data members other than bit-fields of length 0,
1167 /// no virtual member functions, no virtual base classes,
1168 /// and no base class B for which is_empty<B>::value is false.
1169 ///
1170 /// \note This does NOT include a check for union-ness.
1171 bool isEmpty() const { return data().Empty; }
1172 /// Marks this record as empty. This is used by DWARFASTParserClang
1173 /// when parsing records with empty fields having [[no_unique_address]]
1174 /// attribute
1175 void markEmpty() { data().Empty = true; }
1176
1177 void setInitMethod(bool Val) { data().HasInitMethod = Val; }
1178 bool hasInitMethod() const { return data().HasInitMethod; }
1179
1180 bool hasPrivateFields() const {
1181 return data().HasPrivateFields;
1182 }
1183
1184 bool hasProtectedFields() const {
1185 return data().HasProtectedFields;
1186 }
1187
1188 /// Determine whether this class has direct non-static data members.
1189 bool hasDirectFields() const {
1190 auto &D = data();
1191 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1192 }
1193
1194 /// Whether this class is polymorphic (C++ [class.virtual]),
1195 /// which means that the class contains or inherits a virtual function.
1196 bool isPolymorphic() const { return data().Polymorphic; }
1197
1198 /// Determine whether this class has a pure virtual function.
1199 ///
1200 /// The class is abstract per (C++ [class.abstract]p2) if it declares
1201 /// a pure virtual function or inherits a pure virtual function that is
1202 /// not overridden.
1203 bool isAbstract() const { return data().Abstract; }
1204
1205 /// Determine whether this class is standard-layout per
1206 /// C++ [class]p7.
1207 bool isStandardLayout() const { return data().IsStandardLayout; }
1208
1209 /// Determine whether this class was standard-layout per
1210 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1211 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1212
1213 /// Determine whether this class, or any of its class subobjects,
1214 /// contains a mutable field.
1215 bool hasMutableFields() const { return data().HasMutableFields; }
1216
1217 /// Determine whether this class has any variant members.
1218 bool hasVariantMembers() const { return data().HasVariantMembers; }
1219
1220 /// Determine whether this class has a trivial default constructor
1221 /// (C++11 [class.ctor]p5).
1222 bool hasTrivialDefaultConstructor() const {
1223 return hasDefaultConstructor() &&
1224 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1225 }
1226
1227 /// Determine whether this class has a non-trivial default constructor
1228 /// (C++11 [class.ctor]p5).
1229 bool hasNonTrivialDefaultConstructor() const {
1230 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1231 (needsImplicitDefaultConstructor() &&
1232 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1233 }
1234
1235 /// Determine whether this class has at least one constexpr constructor
1236 /// other than the copy or move constructors.
1237 bool hasConstexprNonCopyMoveConstructor() const {
1238 return data().HasConstexprNonCopyMoveConstructor ||
1239 (needsImplicitDefaultConstructor() &&
1240 defaultedDefaultConstructorIsConstexpr());
1241 }
1242
1243 /// Determine whether a defaulted default constructor for this class
1244 /// would be constexpr.
1245 bool defaultedDefaultConstructorIsConstexpr() const {
1246 return data().DefaultedDefaultConstructorIsConstexpr &&
1247 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1248 getLangOpts().CPlusPlus20);
1249 }
1250
1251 /// Determine whether this class has a constexpr default constructor.
1252 bool hasConstexprDefaultConstructor() const {
1253 return data().HasConstexprDefaultConstructor ||
1254 (needsImplicitDefaultConstructor() &&
1255 defaultedDefaultConstructorIsConstexpr());
1256 }
1257
1258 /// Determine whether this class has a trivial copy constructor
1259 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1260 bool hasTrivialCopyConstructor() const {
1261 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1262 }
1263
1264 bool hasTrivialCopyConstructorForCall() const {
1265 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1266 }
1267
1268 /// Determine whether this class has a non-trivial copy constructor
1269 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1270 bool hasNonTrivialCopyConstructor() const {
1271 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1272 !hasTrivialCopyConstructor();
1273 }
1274
1275 bool hasNonTrivialCopyConstructorForCall() const {
1276 return (data().DeclaredNonTrivialSpecialMembersForCall &
1277 SMF_CopyConstructor) ||
1278 !hasTrivialCopyConstructorForCall();
1279 }
1280
1281 /// Determine whether this class has a trivial move constructor
1282 /// (C++11 [class.copy]p12)
1283 bool hasTrivialMoveConstructor() const {
1284 return hasMoveConstructor() &&
1285 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1286 }
1287
1288 bool hasTrivialMoveConstructorForCall() const {
1289 return hasMoveConstructor() &&
1290 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1291 }
1292
1293 /// Determine whether this class has a non-trivial move constructor
1294 /// (C++11 [class.copy]p12)
1295 bool hasNonTrivialMoveConstructor() const {
1296 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1297 (needsImplicitMoveConstructor() &&
1298 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1299 }
1300
1301 bool hasNonTrivialMoveConstructorForCall() const {
1302 return (data().DeclaredNonTrivialSpecialMembersForCall &
1303 SMF_MoveConstructor) ||
1304 (needsImplicitMoveConstructor() &&
1305 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1306 }
1307
1308 /// Determine whether this class has a trivial copy assignment operator
1309 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1310 bool hasTrivialCopyAssignment() const {
1311 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1312 }
1313
1314 /// Determine whether this class has a non-trivial copy assignment
1315 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1316 bool hasNonTrivialCopyAssignment() const {
1317 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1318 !hasTrivialCopyAssignment();
1319 }
1320
1321 /// Determine whether this class has a trivial move assignment operator
1322 /// (C++11 [class.copy]p25)
1323 bool hasTrivialMoveAssignment() const {
1324 return hasMoveAssignment() &&
1325 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1326 }
1327
1328 /// Determine whether this class has a non-trivial move assignment
1329 /// operator (C++11 [class.copy]p25)
1330 bool hasNonTrivialMoveAssignment() const {
1331 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1332 (needsImplicitMoveAssignment() &&
1333 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1334 }
1335
1336 /// Determine whether a defaulted default constructor for this class
1337 /// would be constexpr.
1338 bool defaultedDestructorIsConstexpr() const {
1339 return data().DefaultedDestructorIsConstexpr &&
1340 getLangOpts().CPlusPlus20;
1341 }
1342
1343 /// Determine whether this class has a constexpr destructor.
1344 bool hasConstexprDestructor() const;
1345
1346 /// Determine whether this class has a trivial destructor
1347 /// (C++ [class.dtor]p3)
1348 bool hasTrivialDestructor() const {
1349 return data().HasTrivialSpecialMembers & SMF_Destructor;
1350 }
1351
1352 bool hasTrivialDestructorForCall() const {
1353 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1354 }
1355
1356 /// Determine whether this class has a non-trivial destructor
1357 /// (C++ [class.dtor]p3)
1358 bool hasNonTrivialDestructor() const {
1359 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1360 }
1361
1362 bool hasNonTrivialDestructorForCall() const {
1363 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1364 }
1365
1366 void setHasTrivialSpecialMemberForCall() {
1367 data().HasTrivialSpecialMembersForCall =
1368 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1369 }
1370
1371 /// Determine whether declaring a const variable with this type is ok
1372 /// per core issue 253.
1373 bool allowConstDefaultInit() const {
1374 return !data().HasUninitializedFields ||
1375 !(data().HasDefaultedDefaultConstructor ||
1376 needsImplicitDefaultConstructor());
1377 }
1378
1379 /// Determine whether this class has a destructor which has no
1380 /// semantic effect.
1381 ///
1382 /// Any such destructor will be trivial, public, defaulted and not deleted,
1383 /// and will call only irrelevant destructors.
1384 bool hasIrrelevantDestructor() const {
1385 return data().HasIrrelevantDestructor;
1386 }
1387
1388 /// Determine whether this class has a non-literal or/ volatile type
1389 /// non-static data member or base class.
1390 bool hasNonLiteralTypeFieldsOrBases() const {
1391 return data().HasNonLiteralTypeFieldsOrBases;
1392 }
1393
1394 /// Determine whether this class has a using-declaration that names
1395 /// a user-declared base class constructor.
1396 bool hasInheritedConstructor() const {
1397 return data().HasInheritedConstructor;
1398 }
1399
1400 /// Determine whether this class has a using-declaration that names
1401 /// a base class assignment operator.
1402 bool hasInheritedAssignment() const {
1403 return data().HasInheritedAssignment;
1404 }
1405
1406 /// Determine whether this class is considered trivially copyable per
1407 /// (C++11 [class]p6).
1408 bool isTriviallyCopyable() const;
1409
1410 /// Determine whether this class is considered trivial.
1411 ///
1412 /// C++11 [class]p6:
1413 /// "A trivial class is a class that has a trivial default constructor and
1414 /// is trivially copyable."
1415 bool isTrivial() const {
1416 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1417 }
1418
1419 /// Determine whether this class is a literal type.
1420 ///
1421 /// C++11 [basic.types]p10:
1422 /// A class type that has all the following properties:
1423 /// - it has a trivial destructor
1424 /// - every constructor call and full-expression in the
1425 /// brace-or-equal-intializers for non-static data members (if any) is
1426 /// a constant expression.
1427 /// - it is an aggregate type or has at least one constexpr constructor
1428 /// or constructor template that is not a copy or move constructor, and
1429 /// - all of its non-static data members and base classes are of literal
1430 /// types
1431 ///
1432 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1433 /// treating types with trivial default constructors as literal types.
1434 ///
1435 /// Only in C++17 and beyond, are lambdas literal types.
1436 bool isLiteral() const {
1437 const LangOptions &LangOpts = getLangOpts();
1438 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1439 : hasTrivialDestructor()) &&
1440 (!isLambda() || LangOpts.CPlusPlus17) &&
1441 !hasNonLiteralTypeFieldsOrBases() &&
1442 (isAggregate() || isLambda() ||
1443 hasConstexprNonCopyMoveConstructor() ||
1444 hasTrivialDefaultConstructor());
1445 }
1446
1447 /// Determine whether this is a structural type.
1448 bool isStructural() const {
1449 return isLiteral() && data().StructuralIfLiteral;
1450 }
1451
1452 /// Notify the class that this destructor is now selected.
1453 ///
1454 /// Important properties of the class depend on destructor properties. Since
1455 /// C++20, it is possible to have multiple destructor declarations in a class
1456 /// out of which one will be selected at the end.
1457 /// This is called separately from addedMember because it has to be deferred
1458 /// to the completion of the class.
1459 void addedSelectedDestructor(CXXDestructorDecl *DD);
1460
1461 /// Notify the class that an eligible SMF has been added.
1462 /// This updates triviality and destructor based properties of the class accordingly.
1463 void addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD, unsigned SMKind);
1464
1465 /// If this record is an instantiation of a member class,
1466 /// retrieves the member class from which it was instantiated.
1467 ///
1468 /// This routine will return non-null for (non-templated) member
1469 /// classes of class templates. For example, given:
1470 ///
1471 /// \code
1472 /// template<typename T>
1473 /// struct X {
1474 /// struct A { };
1475 /// };
1476 /// \endcode
1477 ///
1478 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1479 /// whose parent is the class template specialization X<int>. For
1480 /// this declaration, getInstantiatedFromMemberClass() will return
1481 /// the CXXRecordDecl X<T>::A. When a complete definition of
1482 /// X<int>::A is required, it will be instantiated from the
1483 /// declaration returned by getInstantiatedFromMemberClass().
1484 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1485
1486 /// If this class is an instantiation of a member class of a
1487 /// class template specialization, retrieves the member specialization
1488 /// information.
1489 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1490
1491 /// Specify that this record is an instantiation of the
1492 /// member class \p RD.
1493 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1494 TemplateSpecializationKind TSK);
1495
1496 /// Retrieves the class template that is described by this
1497 /// class declaration.
1498 ///
1499 /// Every class template is represented as a ClassTemplateDecl and a
1500 /// CXXRecordDecl. The former contains template properties (such as
1501 /// the template parameter lists) while the latter contains the
1502 /// actual description of the template's
1503 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1504 /// CXXRecordDecl that from a ClassTemplateDecl, while
1505 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1506 /// a CXXRecordDecl.
1507 ClassTemplateDecl *getDescribedClassTemplate() const;
1508
1509 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1510
1511 /// Determine whether this particular class is a specialization or
1512 /// instantiation of a class template or member class of a class template,
1513 /// and how it was instantiated or specialized.
1514 TemplateSpecializationKind getTemplateSpecializationKind() const;
1515
1516 /// Set the kind of specialization or template instantiation this is.
1517 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1518
1519 /// Retrieve the record declaration from which this record could be
1520 /// instantiated. Returns null if this class is not a template instantiation.
1521 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1522
1523 CXXRecordDecl *getTemplateInstantiationPattern() {
1524 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1525 ->getTemplateInstantiationPattern());
1526 }
1527
1528 /// Returns the destructor decl for this class.
1529 CXXDestructorDecl *getDestructor() const;
1530
1531 /// Returns true if the class destructor, or any implicitly invoked
1532 /// destructors are marked noreturn.
1533 bool isAnyDestructorNoReturn() const { return data().IsAnyDestructorNoReturn; }
1534
1535 /// If the class is a local class [class.local], returns
1536 /// the enclosing function declaration.
1537 const FunctionDecl *isLocalClass() const {
1538 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1539 return RD->isLocalClass();
1540
1541 return dyn_cast<FunctionDecl>(getDeclContext());
1542 }
1543
1544 FunctionDecl *isLocalClass() {
1545 return const_cast<FunctionDecl*>(
1546 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1547 }
1548
1549 /// Determine whether this dependent class is a current instantiation,
1550 /// when viewed from within the given context.
1551 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1552
1553 /// Determine whether this class is derived from the class \p Base.
1554 ///
1555 /// This routine only determines whether this class is derived from \p Base,
1556 /// but does not account for factors that may make a Derived -> Base class
1557 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1558 /// base class subobjects.
1559 ///
1560 /// \param Base the base class we are searching for.
1561 ///
1562 /// \returns true if this class is derived from Base, false otherwise.
1563 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1564
1565 /// Determine whether this class is derived from the type \p Base.
1566 ///
1567 /// This routine only determines whether this class is derived from \p Base,
1568 /// but does not account for factors that may make a Derived -> Base class
1569 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1570 /// base class subobjects.
1571 ///
1572 /// \param Base the base class we are searching for.
1573 ///
1574 /// \param Paths will contain the paths taken from the current class to the
1575 /// given \p Base class.
1576 ///
1577 /// \returns true if this class is derived from \p Base, false otherwise.
1578 ///
1579 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1580 /// tangling input and output in \p Paths
1581 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1582
1583 /// Determine whether this class is virtually derived from
1584 /// the class \p Base.
1585 ///
1586 /// This routine only determines whether this class is virtually
1587 /// derived from \p Base, but does not account for factors that may
1588 /// make a Derived -> Base class ill-formed, such as
1589 /// private/protected inheritance or multiple, ambiguous base class
1590 /// subobjects.
1591 ///
1592 /// \param Base the base class we are searching for.
1593 ///
1594 /// \returns true if this class is virtually derived from Base,
1595 /// false otherwise.
1596 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1597
1598 /// Determine whether this class is provably not derived from
1599 /// the type \p Base.
1600 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1601
1602 /// Function type used by forallBases() as a callback.
1603 ///
1604 /// \param BaseDefinition the definition of the base class
1605 ///
1606 /// \returns true if this base matched the search criteria
1607 using ForallBasesCallback =
1608 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1609
1610 /// Determines if the given callback holds for all the direct
1611 /// or indirect base classes of this type.
1612 ///
1613 /// The class itself does not count as a base class. This routine
1614 /// returns false if the class has non-computable base classes.
1615 ///
1616 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1617 /// class of this type until a call returns false.
1618 bool forallBases(ForallBasesCallback BaseMatches) const;
1619
1620 /// Function type used by lookupInBases() to determine whether a
1621 /// specific base class subobject matches the lookup criteria.
1622 ///
1623 /// \param Specifier the base-class specifier that describes the inheritance
1624 /// from the base class we are trying to match.
1625 ///
1626 /// \param Path the current path, from the most-derived class down to the
1627 /// base named by the \p Specifier.
1628 ///
1629 /// \returns true if this base matched the search criteria, false otherwise.
1630 using BaseMatchesCallback =
1631 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1632 CXXBasePath &Path)>;
1633
1634 /// Look for entities within the base classes of this C++ class,
1635 /// transitively searching all base class subobjects.
1636 ///
1637 /// This routine uses the callback function \p BaseMatches to find base
1638 /// classes meeting some search criteria, walking all base class subobjects
1639 /// and populating the given \p Paths structure with the paths through the
1640 /// inheritance hierarchy that resulted in a match. On a successful search,
1641 /// the \p Paths structure can be queried to retrieve the matching paths and
1642 /// to determine if there were any ambiguities.
1643 ///
1644 /// \param BaseMatches callback function used to determine whether a given
1645 /// base matches the user-defined search criteria.
1646 ///
1647 /// \param Paths used to record the paths from this class to its base class
1648 /// subobjects that match the search criteria.
1649 ///
1650 /// \param LookupInDependent can be set to true to extend the search to
1651 /// dependent base classes.
1652 ///
1653 /// \returns true if there exists any path from this class to a base class
1654 /// subobject that matches the search criteria.
1655 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1656 bool LookupInDependent = false) const;
1657
1658 /// Base-class lookup callback that determines whether the given
1659 /// base class specifier refers to a specific class declaration.
1660 ///
1661 /// This callback can be used with \c lookupInBases() to determine whether
1662 /// a given derived class has is a base class subobject of a particular type.
1663 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1664 /// base class that we are searching for.
1665 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1666 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1667
1668 /// Base-class lookup callback that determines whether the
1669 /// given base class specifier refers to a specific class
1670 /// declaration and describes virtual derivation.
1671 ///
1672 /// This callback can be used with \c lookupInBases() to determine
1673 /// whether a given derived class has is a virtual base class
1674 /// subobject of a particular type. The base record pointer should
1675 /// refer to the canonical CXXRecordDecl of the base class that we
1676 /// are searching for.
1677 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1678 CXXBasePath &Path,
1679 const CXXRecordDecl *BaseRecord);
1680
1681 /// Retrieve the final overriders for each virtual member
1682 /// function in the class hierarchy where this class is the
1683 /// most-derived class in the class hierarchy.
1684 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1685
1686 /// Get the indirect primary bases for this class.
1687 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1688
1689 /// Determine whether this class has a member with the given name, possibly
1690 /// in a non-dependent base class.
1691 ///
1692 /// No check for ambiguity is performed, so this should never be used when
1693 /// implementing language semantics, but it may be appropriate for warnings,
1694 /// static analysis, or similar.
1695 bool hasMemberName(DeclarationName N) const;
1696
1697 /// Performs an imprecise lookup of a dependent name in this class.
1698 ///
1699 /// This function does not follow strict semantic rules and should be used
1700 /// only when lookup rules can be relaxed, e.g. indexing.
1701 std::vector<const NamedDecl *>
1702 lookupDependentName(DeclarationName Name,
1703 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1704
1705 /// Renders and displays an inheritance diagram
1706 /// for this C++ class and all of its base classes (transitively) using
1707 /// GraphViz.
1708 void viewInheritance(ASTContext& Context) const;
1709
1710 /// Calculates the access of a decl that is reached
1711 /// along a path.
1712 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1713 AccessSpecifier DeclAccess) {
1714 assert(DeclAccess != AS_none);
1715 if (DeclAccess == AS_private) return AS_none;
1716 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1717 }
1718
1719 /// Indicates that the declaration of a defaulted or deleted special
1720 /// member function is now complete.
1721 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1722
1723 void setTrivialForCallFlags(CXXMethodDecl *MD);
1724
1725 /// Indicates that the definition of this class is now complete.
1726 void completeDefinition() override;
1727
1728 /// Indicates that the definition of this class is now complete,
1729 /// and provides a final overrider map to help determine
1730 ///
1731 /// \param FinalOverriders The final overrider map for this class, which can
1732 /// be provided as an optimization for abstract-class checking. If NULL,
1733 /// final overriders will be computed if they are needed to complete the
1734 /// definition.
1735 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1736
1737 /// Determine whether this class may end up being abstract, even though
1738 /// it is not yet known to be abstract.
1739 ///
1740 /// \returns true if this class is not known to be abstract but has any
1741 /// base classes that are abstract. In this case, \c completeDefinition()
1742 /// will need to compute final overriders to determine whether the class is
1743 /// actually abstract.
1744 bool mayBeAbstract() const;
1745
1746 /// Determine whether it's impossible for a class to be derived from this
1747 /// class. This is best-effort, and may conservatively return false.
1748 bool isEffectivelyFinal() const;
1749
1750 /// If this is the closure type of a lambda expression, retrieve the
1751 /// number to be used for name mangling in the Itanium C++ ABI.
1752 ///
1753 /// Zero indicates that this closure type has internal linkage, so the
1754 /// mangling number does not matter, while a non-zero value indicates which
1755 /// lambda expression this is in this particular context.
1756 unsigned getLambdaManglingNumber() const {
1757 assert(isLambda() && "Not a lambda closure type!");
1758 return getLambdaData().ManglingNumber;
1759 }
1760
1761 /// The lambda is known to has internal linkage no matter whether it has name
1762 /// mangling number.
1763 bool hasKnownLambdaInternalLinkage() const {
1764 assert(isLambda() && "Not a lambda closure type!");
1765 return getLambdaData().HasKnownInternalLinkage;
1766 }
1767
1768 /// Retrieve the declaration that provides additional context for a
1769 /// lambda, when the normal declaration context is not specific enough.
1770 ///
1771 /// Certain contexts (default arguments of in-class function parameters and
1772 /// the initializers of data members) have separate name mangling rules for
1773 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1774 /// the declaration in which the lambda occurs, e.g., the function parameter
1775 /// or the non-static data member. Otherwise, it returns NULL to imply that
1776 /// the declaration context suffices.
1777 Decl *getLambdaContextDecl() const;
1778
1779 /// Retrieve the index of this lambda within the context declaration returned
1780 /// by getLambdaContextDecl().
1781 unsigned getLambdaIndexInContext() const {
1782 assert(isLambda() && "Not a lambda closure type!");
1783 return getLambdaData().IndexInContext;
1784 }
1785
1786 /// Information about how a lambda is numbered within its context.
1787 struct LambdaNumbering {
1788 Decl *ContextDecl = nullptr;
1789 unsigned IndexInContext = 0;
1790 unsigned ManglingNumber = 0;
1791 unsigned DeviceManglingNumber = 0;
1792 bool HasKnownInternalLinkage = false;
1793 };
1794
1795 /// Set the mangling numbers and context declaration for a lambda class.
1796 void setLambdaNumbering(LambdaNumbering Numbering);
1797
1798 // Get the mangling numbers and context declaration for a lambda class.
1799 LambdaNumbering getLambdaNumbering() const {
1800 return {getLambdaContextDecl(), getLambdaIndexInContext(),
1801 getLambdaManglingNumber(), getDeviceLambdaManglingNumber(),
1802 hasKnownLambdaInternalLinkage()};
1803 }
1804
1805 /// Retrieve the device side mangling number.
1806 unsigned getDeviceLambdaManglingNumber() const;
1807
1808 /// Returns the inheritance model used for this record.
1809 MSInheritanceModel getMSInheritanceModel() const;
1810
1811 /// Calculate what the inheritance model would be for this class.
1812 MSInheritanceModel calculateInheritanceModel() const;
1813
1814 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1815 /// member pointer if we can guarantee that zero is not a valid field offset,
1816 /// or if the member pointer has multiple fields. Polymorphic classes have a
1817 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1818 /// fields, we can use zero even if it is a valid field offset because
1819 /// null-ness testing will check the other fields.
1820 bool nullFieldOffsetIsZero() const;
1821
1822 /// Controls when vtordisps will be emitted if this record is used as a
1823 /// virtual base.
1824 MSVtorDispMode getMSVtorDispMode() const;
1825
1826 /// Determine whether this lambda expression was known to be dependent
1827 /// at the time it was created, even if its context does not appear to be
1828 /// dependent.
1829 ///
1830 /// This flag is a workaround for an issue with parsing, where default
1831 /// arguments are parsed before their enclosing function declarations have
1832 /// been created. This means that any lambda expressions within those
1833 /// default arguments will have as their DeclContext the context enclosing
1834 /// the function declaration, which may be non-dependent even when the
1835 /// function declaration itself is dependent. This flag indicates when we
1836 /// know that the lambda is dependent despite that.
1837 bool isDependentLambda() const {
1838 return isLambda() && getLambdaData().DependencyKind == LDK_AlwaysDependent;
1839 }
1840
1841 bool isNeverDependentLambda() const {
1842 return isLambda() && getLambdaData().DependencyKind == LDK_NeverDependent;
1843 }
1844
1845 unsigned getLambdaDependencyKind() const {
1846 if (!isLambda())
1847 return LDK_Unknown;
1848 return getLambdaData().DependencyKind;
1849 }
1850
1851 TypeSourceInfo *getLambdaTypeInfo() const {
1852 return getLambdaData().MethodTyInfo;
1853 }
1854
1855 void setLambdaTypeInfo(TypeSourceInfo *TS) {
1856 assert(DefinitionData && DefinitionData->IsLambda &&
1857 "setting lambda property of non-lambda class");
1858 auto &DL = static_cast<LambdaDefinitionData &>(*DefinitionData);
1859 DL.MethodTyInfo = TS;
1860 }
1861
1862 void setLambdaIsGeneric(bool IsGeneric) {
1863 assert(DefinitionData && DefinitionData->IsLambda &&
1864 "setting lambda property of non-lambda class");
1865 auto &DL = static_cast<LambdaDefinitionData &>(*DefinitionData);
1866 DL.IsGenericLambda = IsGeneric;
1867 }
1868
1869 // Determine whether this type is an Interface Like type for
1870 // __interface inheritance purposes.
1871 bool isInterfaceLike() const;
1872
1873 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1874 static bool classofKind(Kind K) {
1875 return K >= firstCXXRecord && K <= lastCXXRecord;
1876 }
1877 void markAbstract() { data().Abstract = true; }
1878};
1879
1880/// Store information needed for an explicit specifier.
1881/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1882class ExplicitSpecifier {
1883 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1884 nullptr, ExplicitSpecKind::ResolvedFalse};
1885
1886public:
1887 ExplicitSpecifier() = default;
1888 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1889 : ExplicitSpec(Expression, Kind) {}
1890 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1891 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1892 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1893
1894 /// Determine if the declaration had an explicit specifier of any kind.
1895 bool isSpecified() const {
1896 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1897 ExplicitSpec.getPointer();
1898 }
1899
1900 /// Check for equivalence of explicit specifiers.
1901 /// \return true if the explicit specifier are equivalent, false otherwise.
1902 bool isEquivalent(const ExplicitSpecifier Other) const;
1903 /// Determine whether this specifier is known to correspond to an explicit
1904 /// declaration. Returns false if the specifier is absent or has an
1905 /// expression that is value-dependent or evaluates to false.
1906 bool isExplicit() const {
1907 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1908 }
1909 /// Determine if the explicit specifier is invalid.
1910 /// This state occurs after a substitution failures.
1911 bool isInvalid() const {
1912 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1913 !ExplicitSpec.getPointer();
1914 }
1915 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1916 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1917 // Retrieve the explicit specifier in the given declaration, if any.
1918 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1919 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1920 return getFromDecl(const_cast<FunctionDecl *>(Function));
1921 }
1922 static ExplicitSpecifier Invalid() {
1923 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1924 }
1925};
1926
1927/// Represents a C++ deduction guide declaration.
1928///
1929/// \code
1930/// template<typename T> struct A { A(); A(T); };
1931/// A() -> A<int>;
1932/// \endcode
1933///
1934/// In this example, there will be an explicit deduction guide from the
1935/// second line, and implicit deduction guide templates synthesized from
1936/// the constructors of \c A.
1937class CXXDeductionGuideDecl : public FunctionDecl {
1938 void anchor() override;
1939
1940private:
1941 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1942 ExplicitSpecifier ES,
1943 const DeclarationNameInfo &NameInfo, QualType T,
1944 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1945 CXXConstructorDecl *Ctor, DeductionCandidate Kind)
1946 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1947 SC_None, false, false, ConstexprSpecKind::Unspecified),
1948 Ctor(Ctor), ExplicitSpec(ES) {
1949 if (EndLocation.isValid())
1950 setRangeEnd(EndLocation);
1951 setDeductionCandidateKind(Kind);
1952 }
1953
1954 CXXConstructorDecl *Ctor;
1955 ExplicitSpecifier ExplicitSpec;
1956 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1957
1958public:
1959 friend class ASTDeclReader;
1960 friend class ASTDeclWriter;
1961
1962 static CXXDeductionGuideDecl *
1963 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1964 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1965 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1966 CXXConstructorDecl *Ctor = nullptr,
1967 DeductionCandidate Kind = DeductionCandidate::Normal);
1968
1969 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1970
1971 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1972 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1973
1974 /// Return true if the declaration is already resolved to be explicit.
1975 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1976
1977 /// Get the template for which this guide performs deduction.
1978 TemplateDecl *getDeducedTemplate() const {
1979 return getDeclName().getCXXDeductionGuideTemplate();
1980 }
1981
1982 /// Get the constructor from which this deduction guide was generated, if
1983 /// this is an implicit deduction guide.
1984 CXXConstructorDecl *getCorrespondingConstructor() const { return Ctor; }
1985
1986 void setDeductionCandidateKind(DeductionCandidate K) {
1987 FunctionDeclBits.DeductionCandidateKind = static_cast<unsigned char>(K);
1988 }
1989
1990 DeductionCandidate getDeductionCandidateKind() const {
1991 return static_cast<DeductionCandidate>(
1992 FunctionDeclBits.DeductionCandidateKind);
1993 }
1994
1995 // Implement isa/cast/dyncast/etc.
1996 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1997 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1998};
1999
2000/// \brief Represents the body of a requires-expression.
2001///
2002/// This decl exists merely to serve as the DeclContext for the local
2003/// parameters of the requires expression as well as other declarations inside
2004/// it.
2005///
2006/// \code
2007/// template<typename T> requires requires (T t) { {t++} -> regular; }
2008/// \endcode
2009///
2010/// In this example, a RequiresExpr object will be generated for the expression,
2011/// and a RequiresExprBodyDecl will be created to hold the parameter t and the
2012/// template argument list imposed by the compound requirement.
2013class RequiresExprBodyDecl : public Decl, public DeclContext {
2014 RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
2015 : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
2016
2017public:
2018 friend class ASTDeclReader;
2019 friend class ASTDeclWriter;
2020
2021 static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
2022 SourceLocation StartLoc);
2023
2024 static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2025
2026 // Implement isa/cast/dyncast/etc.
2027 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2028 static bool classofKind(Kind K) { return K == RequiresExprBody; }
2029};
2030
2031/// Represents a static or instance method of a struct/union/class.
2032///
2033/// In the terminology of the C++ Standard, these are the (static and
2034/// non-static) member functions, whether virtual or not.
2035class CXXMethodDecl : public FunctionDecl {
2036 void anchor() override;
2037
2038protected:
2039 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2040 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2041 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
2042 bool UsesFPIntrin, bool isInline,
2043 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2044 Expr *TrailingRequiresClause = nullptr)
2045 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
2046 isInline, ConstexprKind, TrailingRequiresClause) {
2047 if (EndLocation.isValid())
2048 setRangeEnd(EndLocation);
2049 }
2050
2051public:
2052 static CXXMethodDecl *
2053 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2054 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2055 StorageClass SC, bool UsesFPIntrin, bool isInline,
2056 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2057 Expr *TrailingRequiresClause = nullptr);
2058
2059 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2060
2061 bool isStatic() const;
2062 bool isInstance() const { return !isStatic(); }
2063
2064 /// Returns true if the given operator is implicitly static in a record
2065 /// context.
2066 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2067 // [class.free]p1:
2068 // Any allocation function for a class T is a static member
2069 // (even if not explicitly declared static).
2070 // [class.free]p6 Any deallocation function for a class X is a static member
2071 // (even if not explicitly declared static).
2072 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2073 OOK == OO_Array_Delete;
2074 }
2075
2076 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2077 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2078
2079 bool isVirtual() const {
2080 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2081
2082 // Member function is virtual if it is marked explicitly so, or if it is
2083 // declared in __interface -- then it is automatically pure virtual.
2084 if (CD->isVirtualAsWritten() || CD->isPure())
2085 return true;
2086
2087 return CD->size_overridden_methods() != 0;
2088 }
2089
2090 /// If it's possible to devirtualize a call to this method, return the called
2091 /// function. Otherwise, return null.
2092
2093 /// \param Base The object on which this virtual function is called.
2094 /// \param IsAppleKext True if we are compiling for Apple kext.
2095 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2096
2097 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2098 bool IsAppleKext) const {
2099 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2100 Base, IsAppleKext);
2101 }
2102
2103 /// Determine whether this is a usual deallocation function (C++
2104 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2105 /// delete[] operator with a particular signature. Populates \p PreventedBy
2106 /// with the declarations of the functions of the same kind if they were the
2107 /// reason for this function returning false. This is used by
2108 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2109 /// context.
2110 bool isUsualDeallocationFunction(
2111 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2112
2113 /// Determine whether this is a copy-assignment operator, regardless
2114 /// of whether it was declared implicitly or explicitly.
2115 bool isCopyAssignmentOperator() const;
2116
2117 /// Determine whether this is a move assignment operator.
2118 bool isMoveAssignmentOperator() const;
2119
2120 CXXMethodDecl *getCanonicalDecl() override {
2121 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2122 }
2123 const CXXMethodDecl *getCanonicalDecl() const {
2124 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2125 }
2126
2127 CXXMethodDecl *getMostRecentDecl() {
2128 return cast<CXXMethodDecl>(
2129 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2130 }
2131 const CXXMethodDecl *getMostRecentDecl() const {
2132 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2133 }
2134
2135 void addOverriddenMethod(const CXXMethodDecl *MD);
2136
2137 using method_iterator = const CXXMethodDecl *const *;
2138
2139 method_iterator begin_overridden_methods() const;
2140 method_iterator end_overridden_methods() const;
2141 unsigned size_overridden_methods() const;
2142
2143 using overridden_method_range = llvm::iterator_range<
2144 llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2145
2146 overridden_method_range overridden_methods() const;
2147
2148 /// Return the parent of this method declaration, which
2149 /// is the class in which this method is defined.
2150 const CXXRecordDecl *getParent() const {
2151 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2152 }
2153
2154 /// Return the parent of this method declaration, which
2155 /// is the class in which this method is defined.
2156 CXXRecordDecl *getParent() {
2157 return const_cast<CXXRecordDecl *>(
2158 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2159 }
2160
2161 /// Return the type of the \c this pointer.
2162 ///
2163 /// Should only be called for instance (i.e., non-static) methods. Note
2164 /// that for the call operator of a lambda closure type, this returns the
2165 /// desugared 'this' type (a pointer to the closure type), not the captured
2166 /// 'this' type.
2167 QualType getThisType() const;
2168
2169 /// Return the type of the object pointed by \c this.
2170 ///
2171 /// See getThisType() for usage restriction.
2172 QualType getThisObjectType() const;
2173
2174 static QualType getThisType(const FunctionProtoType *FPT,
2175 const CXXRecordDecl *Decl);
2176
2177 static QualType getThisObjectType(const FunctionProtoType *FPT,
2178 const CXXRecordDecl *Decl);
2179
2180 Qualifiers getMethodQualifiers() const {
2181 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2182 }
2183
2184 /// Retrieve the ref-qualifier associated with this method.
2185 ///
2186 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2187 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2188 /// @code
2189 /// struct X {
2190 /// void f() &;
2191 /// void g() &&;
2192 /// void h();
2193 /// };
2194 /// @endcode
2195 RefQualifierKind getRefQualifier() const {
2196 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2197 }
2198
2199 bool hasInlineBody() const;
2200
2201 /// Determine whether this is a lambda closure type's static member
2202 /// function that is used for the result of the lambda's conversion to
2203 /// function pointer (for a lambda with no captures).
2204 ///
2205 /// The function itself, if used, will have a placeholder body that will be
2206 /// supplied by IR generation to either forward to the function call operator
2207 /// or clone the function call operator.
2208 bool isLambdaStaticInvoker() const;
2209
2210 /// Find the method in \p RD that corresponds to this one.
2211 ///
2212 /// Find if \p RD or one of the classes it inherits from override this method.
2213 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2214 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2215 CXXMethodDecl *
2216 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2217 bool MayBeBase = false);
2218
2219 const CXXMethodDecl *
2220 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2221 bool MayBeBase = false) const {
2222 return const_cast<CXXMethodDecl *>(this)
2223 ->getCorrespondingMethodInClass(RD, MayBeBase);
2224 }
2225
2226 /// Find if \p RD declares a function that overrides this function, and if so,
2227 /// return it. Does not search base classes.
2228 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2229 bool MayBeBase = false);
2230 const CXXMethodDecl *
2231 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2232 bool MayBeBase = false) const {
2233 return const_cast<CXXMethodDecl *>(this)
2234 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2235 }
2236
2237 // Implement isa/cast/dyncast/etc.
2238 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2239 static bool classofKind(Kind K) {
2240 return K >= firstCXXMethod && K <= lastCXXMethod;
2241 }
2242};
2243
2244/// Represents a C++ base or member initializer.
2245///
2246/// This is part of a constructor initializer that
2247/// initializes one non-static member variable or one base class. For
2248/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2249/// initializers:
2250///
2251/// \code
2252/// class A { };
2253/// class B : public A {
2254/// float f;
2255/// public:
2256/// B(A& a) : A(a), f(3.14159) { }
2257/// };
2258/// \endcode
2259class CXXCtorInitializer final {
2260 /// Either the base class name/delegating constructor type (stored as
2261 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2262 /// (IndirectFieldDecl*) being initialized.
2263 llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2264 Initializee;
2265
2266 /// The argument used to initialize the base or member, which may
2267 /// end up constructing an object (when multiple arguments are involved).
2268 Stmt *Init;
2269
2270 /// The source location for the field name or, for a base initializer
2271 /// pack expansion, the location of the ellipsis.
2272 ///
2273 /// In the case of a delegating
2274 /// constructor, it will still include the type's source location as the
2275 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2276 SourceLocation MemberOrEllipsisLocation;
2277
2278 /// Location of the left paren of the ctor-initializer.
2279 SourceLocation LParenLoc;
2280
2281 /// Location of the right paren of the ctor-initializer.
2282 SourceLocation RParenLoc;
2283
2284 /// If the initializee is a type, whether that type makes this
2285 /// a delegating initialization.
2286 unsigned IsDelegating : 1;
2287
2288 /// If the initializer is a base initializer, this keeps track
2289 /// of whether the base is virtual or not.
2290 unsigned IsVirtual : 1;
2291
2292 /// Whether or not the initializer is explicitly written
2293 /// in the sources.
2294 unsigned IsWritten : 1;
2295
2296 /// If IsWritten is true, then this number keeps track of the textual order
2297 /// of this initializer in the original sources, counting from 0.
2298 unsigned SourceOrder : 13;
2299
2300public:
2301 /// Creates a new base-class initializer.
2302 explicit
2303 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2304 SourceLocation L, Expr *Init, SourceLocation R,
2305 SourceLocation EllipsisLoc);
2306
2307 /// Creates a new member initializer.
2308 explicit
2309 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2310 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2311 SourceLocation R);
2312
2313 /// Creates a new anonymous field initializer.
2314 explicit
2315 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2316 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2317 SourceLocation R);
2318
2319 /// Creates a new delegating initializer.
2320 explicit
2321 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2322 SourceLocation L, Expr *Init, SourceLocation R);
2323
2324 /// \return Unique reproducible object identifier.
2325 int64_t getID(const ASTContext &Context) const;
2326
2327 /// Determine whether this initializer is initializing a base class.
2328 bool isBaseInitializer() const {
2329 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2330 }
2331
2332 /// Determine whether this initializer is initializing a non-static
2333 /// data member.
2334 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2335
2336 bool isAnyMemberInitializer() const {
2337 return isMemberInitializer() || isIndirectMemberInitializer();
2338 }
2339
2340 bool isIndirectMemberInitializer() const {
2341 return Initializee.is<IndirectFieldDecl*>();
2342 }
2343
2344 /// Determine whether this initializer is an implicit initializer
2345 /// generated for a field with an initializer defined on the member
2346 /// declaration.
2347 ///
2348 /// In-class member initializers (also known as "non-static data member
2349 /// initializations", NSDMIs) were introduced in C++11.
2350 bool isInClassMemberInitializer() const {
2351 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2352 }
2353
2354 /// Determine whether this initializer is creating a delegating
2355 /// constructor.
2356 bool isDelegatingInitializer() const {
2357 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2358 }
2359
2360 /// Determine whether this initializer is a pack expansion.
2361 bool isPackExpansion() const {
2362 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2363 }
2364
2365 // For a pack expansion, returns the location of the ellipsis.
2366 SourceLocation getEllipsisLoc() const {
2367 if (!isPackExpansion())
2368 return {};
2369 return MemberOrEllipsisLocation;
2370 }
2371
2372 /// If this is a base class initializer, returns the type of the
2373 /// base class with location information. Otherwise, returns an NULL
2374 /// type location.
2375 TypeLoc getBaseClassLoc() const;
2376
2377 /// If this is a base class initializer, returns the type of the base class.
2378 /// Otherwise, returns null.
2379 const Type *getBaseClass() const;
2380
2381 /// Returns whether the base is virtual or not.
2382 bool isBaseVirtual() const {
2383 assert(isBaseInitializer() && "Must call this on base initializer!");
2384
2385 return IsVirtual;
2386 }
2387
2388 /// Returns the declarator information for a base class or delegating
2389 /// initializer.
2390 TypeSourceInfo *getTypeSourceInfo() const {
2391 return Initializee.dyn_cast<TypeSourceInfo *>();
2392 }
2393
2394 /// If this is a member initializer, returns the declaration of the
2395 /// non-static data member being initialized. Otherwise, returns null.
2396 FieldDecl *getMember() const {
2397 if (isMemberInitializer())
2398 return Initializee.get<FieldDecl*>();
2399 return nullptr;
2400 }
2401
2402 FieldDecl *getAnyMember() const {
2403 if (isMemberInitializer())
2404 return Initializee.get<FieldDecl*>();
2405 if (isIndirectMemberInitializer())
2406 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2407 return nullptr;
2408 }
2409
2410 IndirectFieldDecl *getIndirectMember() const {
2411 if (isIndirectMemberInitializer())
2412 return Initializee.get<IndirectFieldDecl*>();
2413 return nullptr;
2414 }
2415
2416 SourceLocation getMemberLocation() const {
2417 return MemberOrEllipsisLocation;
2418 }
2419
2420 /// Determine the source location of the initializer.
2421 SourceLocation getSourceLocation() const;
2422
2423 /// Determine the source range covering the entire initializer.
2424 SourceRange getSourceRange() const LLVM_READONLY;
2425
2426 /// Determine whether this initializer is explicitly written
2427 /// in the source code.
2428 bool isWritten() const { return IsWritten; }
2429
2430 /// Return the source position of the initializer, counting from 0.
2431 /// If the initializer was implicit, -1 is returned.
2432 int getSourceOrder() const {
2433 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2434 }
2435
2436 /// Set the source order of this initializer.
2437 ///
2438 /// This can only be called once for each initializer; it cannot be called
2439 /// on an initializer having a positive number of (implicit) array indices.
2440 ///
2441 /// This assumes that the initializer was written in the source code, and
2442 /// ensures that isWritten() returns true.
2443 void setSourceOrder(int Pos) {
2444 assert(!IsWritten &&
2445 "setSourceOrder() used on implicit initializer");
2446 assert(SourceOrder == 0 &&
2447 "calling twice setSourceOrder() on the same initializer");
2448 assert(Pos >= 0 &&
2449 "setSourceOrder() used to make an initializer implicit");
2450 IsWritten = true;
2451 SourceOrder = static_cast<unsigned>(Pos);
2452 }
2453
2454 SourceLocation getLParenLoc() const { return LParenLoc; }
2455 SourceLocation getRParenLoc() const { return RParenLoc; }
2456
2457 /// Get the initializer.
2458 Expr *getInit() const { return static_cast<Expr *>(Init); }
2459};
2460
2461/// Description of a constructor that was inherited from a base class.
2462class InheritedConstructor {
2463 ConstructorUsingShadowDecl *Shadow = nullptr;
2464 CXXConstructorDecl *BaseCtor = nullptr;
2465
2466public:
2467 InheritedConstructor() = default;
2468 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2469 CXXConstructorDecl *BaseCtor)
2470 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2471
2472 explicit operator bool() const { return Shadow; }
2473
2474 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2475 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2476};
2477
2478/// Represents a C++ constructor within a class.
2479///
2480/// For example:
2481///
2482/// \code
2483/// class X {
2484/// public:
2485/// explicit X(int); // represented by a CXXConstructorDecl.
2486/// };
2487/// \endcode
2488class CXXConstructorDecl final
2489 : public CXXMethodDecl,
2490 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2491 ExplicitSpecifier> {
2492 // This class stores some data in DeclContext::CXXConstructorDeclBits
2493 // to save some space. Use the provided accessors to access it.
2494
2495 /// \name Support for base and member initializers.
2496 /// \{
2497 /// The arguments used to initialize the base or member.
2498 LazyCXXCtorInitializersPtr CtorInitializers;
2499
2500 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2501 const DeclarationNameInfo &NameInfo, QualType T,
2502 TypeSourceInfo *TInfo, ExplicitSpecifier ES,
2503 bool UsesFPIntrin, bool isInline,
2504 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2505 InheritedConstructor Inherited,
2506 Expr *TrailingRequiresClause);
2507
2508 void anchor() override;
2509
2510 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2511 return CXXConstructorDeclBits.IsInheritingConstructor;
2512 }
2513 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2514 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2515 }
2516
2517 ExplicitSpecifier getExplicitSpecifierInternal() const {
2518 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2519 return *getTrailingObjects<ExplicitSpecifier>();
2520 return ExplicitSpecifier(
2521 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2522 ? ExplicitSpecKind::ResolvedTrue
2523 : ExplicitSpecKind::ResolvedFalse);
2524 }
2525
2526 enum TrailingAllocKind {
2527 TAKInheritsConstructor = 1,
2528 TAKHasTailExplicit = 1 << 1,
2529 };
2530
2531 uint64_t getTrailingAllocKind() const {
2532 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2533 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2534 }
2535
2536public:
2537 friend class ASTDeclReader;
2538 friend class ASTDeclWriter;
2539 friend TrailingObjects;
2540
2541 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2542 uint64_t AllocKind);
2543 static CXXConstructorDecl *
2544 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2545 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2546 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2547 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2548 InheritedConstructor Inherited = InheritedConstructor(),
2549 Expr *TrailingRequiresClause = nullptr);
2550
2551 void setExplicitSpecifier(ExplicitSpecifier ES) {
2552 assert((!ES.getExpr() ||
2553 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&
2554 "cannot set this explicit specifier. no trail-allocated space for "
2555 "explicit");
2556 if (ES.getExpr())
2557 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2558 else
2559 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2560 }
2561
2562 ExplicitSpecifier getExplicitSpecifier() {
2563 return getCanonicalDecl()->getExplicitSpecifierInternal();
2564 }
2565 const ExplicitSpecifier getExplicitSpecifier() const {
2566 return getCanonicalDecl()->getExplicitSpecifierInternal();
2567 }
2568
2569 /// Return true if the declaration is already resolved to be explicit.
2570 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2571
2572 /// Iterates through the member/base initializer list.
2573 using init_iterator = CXXCtorInitializer **;
2574
2575 /// Iterates through the member/base initializer list.
2576 using init_const_iterator = CXXCtorInitializer *const *;
2577
2578 using init_range = llvm::iterator_range<init_iterator>;
2579 using init_const_range = llvm::iterator_range<init_const_iterator>;
2580
2581 init_range inits() { return init_range(init_begin(), init_end()); }
2582 init_const_range inits() const {
2583 return init_const_range(init_begin(), init_end());
2584 }
2585
2586 /// Retrieve an iterator to the first initializer.
2587 init_iterator init_begin() {
2588 const auto *ConstThis = this;
2589 return const_cast<init_iterator>(ConstThis->init_begin());
2590 }
2591
2592 /// Retrieve an iterator to the first initializer.
2593 init_const_iterator init_begin() const;
2594
2595 /// Retrieve an iterator past the last initializer.
2596 init_iterator init_end() {
2597 return init_begin() + getNumCtorInitializers();
2598 }
2599
2600 /// Retrieve an iterator past the last initializer.
2601 init_const_iterator init_end() const {
2602 return init_begin() + getNumCtorInitializers();
2603 }
2604
2605 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2606 using init_const_reverse_iterator =
2607 std::reverse_iterator<init_const_iterator>;
2608
2609 init_reverse_iterator init_rbegin() {
2610 return init_reverse_iterator(init_end());
2611 }
2612 init_const_reverse_iterator init_rbegin() const {
2613 return init_const_reverse_iterator(init_end());
2614 }
2615
2616 init_reverse_iterator init_rend() {
2617 return init_reverse_iterator(init_begin());
2618 }
2619 init_const_reverse_iterator init_rend() const {
2620 return init_const_reverse_iterator(init_begin());
2621 }
2622
2623 /// Determine the number of arguments used to initialize the member
2624 /// or base.
2625 unsigned getNumCtorInitializers() const {
2626 return CXXConstructorDeclBits.NumCtorInitializers;
2627 }
2628
2629 void setNumCtorInitializers(unsigned numCtorInitializers) {
2630 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2631 // This assert added because NumCtorInitializers is stored
2632 // in CXXConstructorDeclBits as a bitfield and its width has
2633 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2634 assert(CXXConstructorDeclBits.NumCtorInitializers ==
2635 numCtorInitializers && "NumCtorInitializers overflow!");
2636 }
2637
2638 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2639 CtorInitializers = Initializers;
2640 }
2641
2642 /// Determine whether this constructor is a delegating constructor.
2643 bool isDelegatingConstructor() const {
2644 return (getNumCtorInitializers() == 1) &&
2645 init_begin()[0]->isDelegatingInitializer();
2646 }
2647
2648 /// When this constructor delegates to another, retrieve the target.
2649 CXXConstructorDecl *getTargetConstructor() const;
2650
2651 /// Whether this constructor is a default
2652 /// constructor (C++ [class.ctor]p5), which can be used to
2653 /// default-initialize a class of this type.
2654 bool isDefaultConstructor() const;
2655
2656 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2657 /// which can be used to copy the class.
2658 ///
2659 /// \p TypeQuals will be set to the qualifiers on the
2660 /// argument type. For example, \p TypeQuals would be set to \c
2661 /// Qualifiers::Const for the following copy constructor:
2662 ///
2663 /// \code
2664 /// class X {
2665 /// public:
2666 /// X(const X&);
2667 /// };
2668 /// \endcode
2669 bool isCopyConstructor(unsigned &TypeQuals) const;
2670
2671 /// Whether this constructor is a copy
2672 /// constructor (C++ [class.copy]p2, which can be used to copy the
2673 /// class.
2674 bool isCopyConstructor() const {
2675 unsigned TypeQuals = 0;
2676 return isCopyConstructor(TypeQuals);
2677 }
2678
2679 /// Determine whether this constructor is a move constructor
2680 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2681 ///
2682 /// \param TypeQuals If this constructor is a move constructor, will be set
2683 /// to the type qualifiers on the referent of the first parameter's type.
2684 bool isMoveConstructor(unsigned &TypeQuals) const;
2685
2686 /// Determine whether this constructor is a move constructor
2687 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2688 bool isMoveConstructor() const {
2689 unsigned TypeQuals = 0;
2690 return isMoveConstructor(TypeQuals);
2691 }
2692
2693 /// Determine whether this is a copy or move constructor.
2694 ///
2695 /// \param TypeQuals Will be set to the type qualifiers on the reference
2696 /// parameter, if in fact this is a copy or move constructor.
2697 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2698
2699 /// Determine whether this a copy or move constructor.
2700 bool isCopyOrMoveConstructor() const {
2701 unsigned Quals;
2702 return isCopyOrMoveConstructor(Quals);
2703 }
2704
2705 /// Whether this constructor is a
2706 /// converting constructor (C++ [class.conv.ctor]), which can be
2707 /// used for user-defined conversions.
2708 bool isConvertingConstructor(bool AllowExplicit) const;
2709
2710 /// Determine whether this is a member template specialization that
2711 /// would copy the object to itself. Such constructors are never used to copy
2712 /// an object.
2713 bool isSpecializationCopyingObject() const;
2714
2715 /// Determine whether this is an implicit constructor synthesized to
2716 /// model a call to a constructor inherited from a base class.
2717 bool isInheritingConstructor() const {
2718 return CXXConstructorDeclBits.IsInheritingConstructor;
2719 }
2720
2721 /// State that this is an implicit constructor synthesized to
2722 /// model a call to a constructor inherited from a base class.
2723 void setInheritingConstructor(bool isIC = true) {
2724 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2725 }
2726
2727 /// Get the constructor that this inheriting constructor is based on.
2728 InheritedConstructor getInheritedConstructor() const {
2729 return isInheritingConstructor() ?
2730 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2731 }
2732
2733 CXXConstructorDecl *getCanonicalDecl() override {
2734 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2735 }
2736 const CXXConstructorDecl *getCanonicalDecl() const {
2737 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2738 }
2739
2740 // Implement isa/cast/dyncast/etc.
2741 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2742 static bool classofKind(Kind K) { return K == CXXConstructor; }
2743};
2744
2745/// Represents a C++ destructor within a class.
2746///
2747/// For example:
2748///
2749/// \code
2750/// class X {
2751/// public:
2752/// ~X(); // represented by a CXXDestructorDecl.
2753/// };
2754/// \endcode
2755class CXXDestructorDecl : public CXXMethodDecl {
2756 friend class ASTDeclReader;
2757 friend class ASTDeclWriter;
2758
2759 // FIXME: Don't allocate storage for these except in the first declaration
2760 // of a virtual destructor.
2761 FunctionDecl *OperatorDelete = nullptr;
2762 Expr *OperatorDeleteThisArg = nullptr;
2763
2764 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2765 const DeclarationNameInfo &NameInfo, QualType T,
2766 TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline,
2767 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2768 Expr *TrailingRequiresClause = nullptr)
2769 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2770 SC_None, UsesFPIntrin, isInline, ConstexprKind,
2771 SourceLocation(), TrailingRequiresClause) {
2772 setImplicit(isImplicitlyDeclared);
2773 }
2774
2775 void anchor() override;
2776
2777public:
2778 static CXXDestructorDecl *
2779 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2780 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2781 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
2782 ConstexprSpecKind ConstexprKind,
2783 Expr *TrailingRequiresClause = nullptr);
2784 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2785
2786 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2787
2788 const FunctionDecl *getOperatorDelete() const {
2789 return getCanonicalDecl()->OperatorDelete;
2790 }
2791
2792 Expr *getOperatorDeleteThisArg() const {
2793 return getCanonicalDecl()->OperatorDeleteThisArg;
2794 }
2795
2796 CXXDestructorDecl *getCanonicalDecl() override {
2797 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2798 }
2799 const CXXDestructorDecl *getCanonicalDecl() const {
2800 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2801 }
2802
2803 // Implement isa/cast/dyncast/etc.
2804 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2805 static bool classofKind(Kind K) { return K == CXXDestructor; }
2806};
2807
2808/// Represents a C++ conversion function within a class.
2809///
2810/// For example:
2811///
2812/// \code
2813/// class X {
2814/// public:
2815/// operator bool();
2816/// };
2817/// \endcode
2818class CXXConversionDecl : public CXXMethodDecl {
2819 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2820 const DeclarationNameInfo &NameInfo, QualType T,
2821 TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline,
2822 ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2823 SourceLocation EndLocation,
2824 Expr *TrailingRequiresClause = nullptr)
2825 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2826 SC_None, UsesFPIntrin, isInline, ConstexprKind,
2827 EndLocation, TrailingRequiresClause),
2828 ExplicitSpec(ES) {}
2829 void anchor() override;
2830
2831 ExplicitSpecifier ExplicitSpec;
2832
2833public:
2834 friend class ASTDeclReader;
2835 friend class ASTDeclWriter;
2836
2837 static CXXConversionDecl *
2838 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2839 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2840 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
2841 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2842 Expr *TrailingRequiresClause = nullptr);
2843 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2844
2845 ExplicitSpecifier getExplicitSpecifier() {
2846 return getCanonicalDecl()->ExplicitSpec;
2847 }
2848
2849 const ExplicitSpecifier getExplicitSpecifier() const {
2850 return getCanonicalDecl()->ExplicitSpec;
2851 }
2852
2853 /// Return true if the declaration is already resolved to be explicit.
2854 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2855 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2856
2857 /// Returns the type that this conversion function is converting to.
2858 QualType getConversionType() const {
2859 return getType()->castAs<FunctionType>()->getReturnType();
2860 }
2861
2862 /// Determine whether this conversion function is a conversion from
2863 /// a lambda closure type to a block pointer.
2864 bool isLambdaToBlockPointerConversion() const;
2865
2866 CXXConversionDecl *getCanonicalDecl() override {
2867 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2868 }
2869 const CXXConversionDecl *getCanonicalDecl() const {
2870 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2871 }
2872
2873 // Implement isa/cast/dyncast/etc.
2874 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2875 static bool classofKind(Kind K) { return K == CXXConversion; }
2876};
2877
2878/// Represents a linkage specification.
2879///
2880/// For example:
2881/// \code
2882/// extern "C" void foo();
2883/// \endcode
2884class LinkageSpecDecl : public Decl, public DeclContext {
2885 virtual void anchor();
2886 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2887 // some space. Use the provided accessors to access it.
2888public:
2889 /// Represents the language in a linkage specification.
2890 ///
2891 /// The values are part of the serialization ABI for
2892 /// ASTs and cannot be changed without altering that ABI.
2893 enum LanguageIDs { lang_c = 1, lang_cxx = 2 };
2894
2895private:
2896 /// The source location for the extern keyword.
2897 SourceLocation ExternLoc;
2898
2899 /// The source location for the right brace (if valid).
2900 SourceLocation RBraceLoc;
2901
2902 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2903 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2904
2905public:
2906 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2907 SourceLocation ExternLoc,
2908 SourceLocation LangLoc, LanguageIDs Lang,
2909 bool HasBraces);
2910 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2911
2912 /// Return the language specified by this linkage specification.
2913 LanguageIDs getLanguage() const {
2914 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2915 }
2916
2917 /// Set the language specified by this linkage specification.
2918 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2919
2920 /// Determines whether this linkage specification had braces in
2921 /// its syntactic form.
2922 bool hasBraces() const {
2923 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces);
2924 return LinkageSpecDeclBits.HasBraces;
2925 }
2926
2927 SourceLocation getExternLoc() const { return ExternLoc; }
2928 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2929 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2930 void setRBraceLoc(SourceLocation L) {
2931 RBraceLoc = L;
2932 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2933 }
2934
2935 SourceLocation getEndLoc() const LLVM_READONLY {
2936 if (hasBraces())
2937 return getRBraceLoc();
2938 // No braces: get the end location of the (only) declaration in context
2939 // (if present).
2940 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
2941 }
2942
2943 SourceRange getSourceRange() const override LLVM_READONLY {
2944 return SourceRange(ExternLoc, getEndLoc());
2945 }
2946
2947 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2948 static bool classofKind(Kind K) { return K == LinkageSpec; }
2949
2950 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2951 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2952 }
2953
2954 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2955 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2956 }
2957};
2958
2959/// Represents C++ using-directive.
2960///
2961/// For example:
2962/// \code
2963/// using namespace std;
2964/// \endcode
2965///
2966/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2967/// artificial names for all using-directives in order to store
2968/// them in DeclContext effectively.
2969class UsingDirectiveDecl : public NamedDecl {
2970 /// The location of the \c using keyword.
2971 SourceLocation UsingLoc;
2972
2973 /// The location of the \c namespace keyword.
2974 SourceLocation NamespaceLoc;
2975
2976 /// The nested-name-specifier that precedes the namespace.
2977 NestedNameSpecifierLoc QualifierLoc;
2978
2979 /// The namespace nominated by this using-directive.
2980 NamedDecl *NominatedNamespace;
2981
2982 /// Enclosing context containing both using-directive and nominated
2983 /// namespace.
2984 DeclContext *CommonAncestor;
2985
2986 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2987 SourceLocation NamespcLoc,
2988 NestedNameSpecifierLoc QualifierLoc,
2989 SourceLocation IdentLoc,
2990 NamedDecl *Nominated,
2991 DeclContext *CommonAncestor)
2992 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2993 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2994 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2995
2996 /// Returns special DeclarationName used by using-directives.
2997 ///
2998 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2999 /// its lookup structure.
3000 static DeclarationName getName() {
3001 return DeclarationName::getUsingDirectiveName();
3002 }
3003
3004 void anchor() override;
3005
3006public:
3007 friend class ASTDeclReader;
3008
3009 // Friend for getUsingDirectiveName.
3010 friend class DeclContext;
3011
3012 /// Retrieve the nested-name-specifier that qualifies the
3013 /// name of the namespace, with source-location information.
3014 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3015
3016 /// Retrieve the nested-name-specifier that qualifies the
3017 /// name of the namespace.
3018 NestedNameSpecifier *getQualifier() const {
3019 return QualifierLoc.getNestedNameSpecifier();
3020 }
3021
3022 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
3023 const NamedDecl *getNominatedNamespaceAsWritten() const {
3024 return NominatedNamespace;
3025 }
3026
3027 /// Returns the namespace nominated by this using-directive.
3028 NamespaceDecl *getNominatedNamespace();
3029
3030 const NamespaceDecl *getNominatedNamespace() const {
3031 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
3032 }
3033
3034 /// Returns the common ancestor context of this using-directive and
3035 /// its nominated namespace.
3036 DeclContext *getCommonAncestor() { return CommonAncestor; }
3037 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
3038
3039 /// Return the location of the \c using keyword.
3040 SourceLocation getUsingLoc() const { return UsingLoc; }
3041
3042 // FIXME: Could omit 'Key' in name.
3043 /// Returns the location of the \c namespace keyword.
3044 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
3045
3046 /// Returns the location of this using declaration's identifier.
3047 SourceLocation getIdentLocation() const { return getLocation(); }
3048
3049 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
3050 SourceLocation UsingLoc,
3051 SourceLocation NamespaceLoc,
3052 NestedNameSpecifierLoc QualifierLoc,
3053 SourceLocation IdentLoc,
3054 NamedDecl *Nominated,
3055 DeclContext *CommonAncestor);
3056 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3057
3058 SourceRange getSourceRange() const override LLVM_READONLY {
3059 return SourceRange(UsingLoc, getLocation());
3060 }
3061
3062 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3063 static bool classofKind(Kind K) { return K == UsingDirective; }
3064};
3065
3066/// Represents a C++ namespace alias.
3067///
3068/// For example:
3069///
3070/// \code
3071/// namespace Foo = Bar;
3072/// \endcode
3073class NamespaceAliasDecl : public NamedDecl,
3074 public Redeclarable<NamespaceAliasDecl> {
3075 friend class ASTDeclReader;
3076
3077 /// The location of the \c namespace keyword.
3078 SourceLocation NamespaceLoc;
3079
3080 /// The location of the namespace's identifier.
3081 ///
3082 /// This is accessed by TargetNameLoc.
3083 SourceLocation IdentLoc;
3084
3085 /// The nested-name-specifier that precedes the namespace.
3086 NestedNameSpecifierLoc QualifierLoc;
3087
3088 /// The Decl that this alias points to, either a NamespaceDecl or
3089 /// a NamespaceAliasDecl.
3090 NamedDecl *Namespace;
3091
3092 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3093 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3094 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3095 SourceLocation IdentLoc, NamedDecl *Namespace)
3096 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3097 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3098 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3099
3100 void anchor() override;
3101
3102 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3103
3104 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3105 NamespaceAliasDecl *getPreviousDeclImpl() override;
3106 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3107
3108public:
3109 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3110 SourceLocation NamespaceLoc,
3111 SourceLocation AliasLoc,
3112 IdentifierInfo *Alias,
3113 NestedNameSpecifierLoc QualifierLoc,
3114 SourceLocation IdentLoc,
3115 NamedDecl *Namespace);
3116
3117 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3118
3119 using redecl_range = redeclarable_base::redecl_range;
3120 using redecl_iterator = redeclarable_base::redecl_iterator;
3121
3122 using redeclarable_base::redecls_begin;
3123 using redeclarable_base::redecls_end;
3124 using redeclarable_base::redecls;
3125 using redeclarable_base::getPreviousDecl;
3126 using redeclarable_base::getMostRecentDecl;
3127
3128 NamespaceAliasDecl *getCanonicalDecl() override {
3129 return getFirstDecl();
3130 }
3131 const NamespaceAliasDecl *getCanonicalDecl() const {
3132 return getFirstDecl();
3133 }
3134
3135 /// Retrieve the nested-name-specifier that qualifies the
3136 /// name of the namespace, with source-location information.
3137 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3138
3139 /// Retrieve the nested-name-specifier that qualifies the
3140 /// name of the namespace.
3141 NestedNameSpecifier *getQualifier() const {
3142 return QualifierLoc.getNestedNameSpecifier();
3143 }
3144
3145 /// Retrieve the namespace declaration aliased by this directive.
3146 NamespaceDecl *getNamespace() {
3147 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3148 return AD->getNamespace();
3149
3150 return cast<NamespaceDecl>(Namespace);
3151 }
3152
3153 const NamespaceDecl *getNamespace() const {
3154 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3155 }
3156
3157 /// Returns the location of the alias name, i.e. 'foo' in
3158 /// "namespace foo = ns::bar;".
3159 SourceLocation getAliasLoc() const { return getLocation(); }
3160
3161 /// Returns the location of the \c namespace keyword.
3162 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3163
3164 /// Returns the location of the identifier in the named namespace.
3165 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3166
3167 /// Retrieve the namespace that this alias refers to, which
3168 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3169 NamedDecl *getAliasedNamespace() const { return Namespace; }
3170
3171 SourceRange getSourceRange() const override LLVM_READONLY {
3172 return SourceRange(NamespaceLoc, IdentLoc);
3173 }
3174
3175 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3176 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3177};
3178
3179/// Implicit declaration of a temporary that was materialized by
3180/// a MaterializeTemporaryExpr and lifetime-extended by a declaration
3181class LifetimeExtendedTemporaryDecl final
3182 : public Decl,
3183 public Mergeable<LifetimeExtendedTemporaryDecl> {
3184 friend class MaterializeTemporaryExpr;
3185 friend class ASTDeclReader;
3186
3187 Stmt *ExprWithTemporary = nullptr;
3188
3189 /// The declaration which lifetime-extended this reference, if any.
3190 /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3191 ValueDecl *ExtendingDecl = nullptr;
3192 unsigned ManglingNumber;
3193
3194 mutable APValue *Value = nullptr;
3195
3196 virtual void anchor();
3197
3198 LifetimeExtendedTemporaryDecl(Expr *Temp, ValueDecl *EDecl, unsigned Mangling)
3199 : Decl(Decl::LifetimeExtendedTemporary, EDecl->getDeclContext(),
3200 EDecl->getLocation()),
3201 ExprWithTemporary(Temp), ExtendingDecl(EDecl),
3202 ManglingNumber(Mangling) {}
3203
3204 LifetimeExtendedTemporaryDecl(EmptyShell)
3205 : Decl(Decl::LifetimeExtendedTemporary, EmptyShell{}) {}
3206
3207public:
3208 static LifetimeExtendedTemporaryDecl *Create(Expr *Temp, ValueDecl *EDec,
3209 unsigned Mangling) {
3210 return new (EDec->getASTContext(), EDec->getDeclContext())
3211 LifetimeExtendedTemporaryDecl(Temp, EDec, Mangling);
3212 }
3213 static LifetimeExtendedTemporaryDecl *CreateDeserialized(ASTContext &C,
3214 unsigned ID) {
3215 return new (C, ID) LifetimeExtendedTemporaryDecl(EmptyShell{});
3216 }
3217
3218 ValueDecl *getExtendingDecl() { return ExtendingDecl; }
3219 const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3220
3221 /// Retrieve the storage duration for the materialized temporary.
3222 StorageDuration getStorageDuration() const;
3223
3224 /// Retrieve the expression to which the temporary materialization conversion
3225 /// was applied. This isn't necessarily the initializer of the temporary due
3226 /// to the C++98 delayed materialization rules, but
3227 /// skipRValueSubobjectAdjustments can be used to find said initializer within
3228 /// the subexpression.
3229 Expr *getTemporaryExpr() { return cast<Expr>(ExprWithTemporary); }
3230 const Expr *getTemporaryExpr() const { return cast<Expr>(ExprWithTemporary); }
3231
3232 unsigned getManglingNumber() const { return ManglingNumber; }
3233
3234 /// Get the storage for the constant value of a materialized temporary
3235 /// of static storage duration.
3236 APValue *getOrCreateValue(bool MayCreate) const;
3237
3238 APValue *getValue() const { return Value; }
3239
3240 // Iterators
3241 Stmt::child_range childrenExpr() {
3242 return Stmt::child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3243 }
3244
3245 Stmt::const_child_range childrenExpr() const {
3246 return Stmt::const_child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3247 }
3248
3249 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3250 static bool classofKind(Kind K) {
3251 return K == Decl::LifetimeExtendedTemporary;
3252 }
3253};
3254
3255/// Represents a shadow declaration implicitly introduced into a scope by a
3256/// (resolved) using-declaration or using-enum-declaration to achieve
3257/// the desired lookup semantics.
3258///
3259/// For example:
3260/// \code
3261/// namespace A {
3262/// void foo();
3263/// void foo(int);
3264/// struct foo {};
3265/// enum bar { bar1, bar2 };
3266/// }
3267/// namespace B {
3268/// // add a UsingDecl and three UsingShadowDecls (named foo) to B.
3269/// using A::foo;
3270/// // adds UsingEnumDecl and two UsingShadowDecls (named bar1 and bar2) to B.
3271/// using enum A::bar;
3272/// }
3273/// \endcode
3274class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3275 friend class BaseUsingDecl;
3276
3277 /// The referenced declaration.
3278 NamedDecl *Underlying = nullptr;
3279
3280 /// The using declaration which introduced this decl or the next using
3281 /// shadow declaration contained in the aforementioned using declaration.
3282 NamedDecl *UsingOrNextShadow = nullptr;
3283
3284 void anchor() override;
3285
3286 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3287
3288 UsingShadowDecl *getNextRedeclarationImpl() override {
3289 return getNextRedeclaration();
3290 }
3291
3292 UsingShadowDecl *getPreviousDeclImpl() override {
3293 return getPreviousDecl();
3294 }
3295
3296 UsingShadowDecl *getMostRecentDeclImpl() override {
3297 return getMostRecentDecl();
3298 }
3299
3300protected:
3301 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3302 DeclarationName Name, BaseUsingDecl *Introducer,
3303 NamedDecl *Target);
3304 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3305
3306public:
3307 friend class ASTDeclReader;
3308 friend class ASTDeclWriter;
3309
3310 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3311 SourceLocation Loc, DeclarationName Name,
3312 BaseUsingDecl *Introducer, NamedDecl *Target) {
3313 return new (C, DC)
3314 UsingShadowDecl(UsingShadow, C, DC, Loc, Name, Introducer, Target);
3315 }
3316
3317 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3318
3319 using redecl_range = redeclarable_base::redecl_range;
3320 using redecl_iterator = redeclarable_base::redecl_iterator;
3321
3322 using redeclarable_base::redecls_begin;
3323 using redeclarable_base::redecls_end;
3324 using redeclarable_base::redecls;
3325 using redeclarable_base::getPreviousDecl;
3326 using redeclarable_base::getMostRecentDecl;
3327 using redeclarable_base::isFirstDecl;
3328
3329 UsingShadowDecl *getCanonicalDecl() override {
3330 return getFirstDecl();
3331 }
3332 const UsingShadowDecl *getCanonicalDecl() const {
3333 return getFirstDecl();
3334 }
3335
3336 /// Gets the underlying declaration which has been brought into the
3337 /// local scope.
3338 NamedDecl *getTargetDecl() const { return Underlying; }
3339
3340 /// Sets the underlying declaration which has been brought into the
3341 /// local scope.
3342 void setTargetDecl(NamedDecl *ND) {
3343 assert(ND && "Target decl is null!");
3344 Underlying = ND;
3345 // A UsingShadowDecl is never a friend or local extern declaration, even
3346 // if it is a shadow declaration for one.
3347 IdentifierNamespace =
3348 ND->getIdentifierNamespace() &
3349 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3350 }
3351
3352 /// Gets the (written or instantiated) using declaration that introduced this
3353 /// declaration.
3354 BaseUsingDecl *getIntroducer() const;
3355
3356 /// The next using shadow declaration contained in the shadow decl
3357 /// chain of the using declaration which introduced this decl.
3358 UsingShadowDecl *getNextUsingShadowDecl() const {
3359 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3360 }
3361
3362 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3363 static bool classofKind(Kind K) {
3364 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3365 }
3366};
3367
3368/// Represents a C++ declaration that introduces decls from somewhere else. It
3369/// provides a set of the shadow decls so introduced.
3370
3371class BaseUsingDecl : public NamedDecl {
3372 /// The first shadow declaration of the shadow decl chain associated
3373 /// with this using declaration.
3374 ///
3375 /// The bool member of the pair is a bool flag a derived type may use
3376 /// (UsingDecl makes use of it).
3377 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3378
3379protected:
3380 BaseUsingDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
3381 : NamedDecl(DK, DC, L, N), FirstUsingShadow(nullptr, false) {}
3382
3383private:
3384 void anchor() override;
3385
3386protected:
3387 /// A bool flag for use by a derived type
3388 bool getShadowFlag() const { return FirstUsingShadow.getInt(); }
3389
3390 /// A bool flag a derived type may set
3391 void setShadowFlag(bool V) { FirstUsingShadow.setInt(V); }
3392
3393public:
3394 friend class ASTDeclReader;
3395 friend class ASTDeclWriter;
3396
3397 /// Iterates through the using shadow declarations associated with
3398 /// this using declaration.
3399 class shadow_iterator {
3400 /// The current using shadow declaration.
3401 UsingShadowDecl *Current = nullptr;
3402
3403 public:
3404 using value_type = UsingShadowDecl *;
3405 using reference = UsingShadowDecl *;
3406 using pointer = UsingShadowDecl *;
3407 using iterator_category = std::forward_iterator_tag;
3408 using difference_type = std::ptrdiff_t;
3409
3410 shadow_iterator() = default;
3411 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3412
3413 reference operator*() const { return Current; }
3414 pointer operator->() const { return Current; }
3415
3416 shadow_iterator &operator++() {
3417 Current = Current->getNextUsingShadowDecl();
3418 return *this;
3419 }
3420
3421 shadow_iterator operator++(int) {
3422 shadow_iterator tmp(*this);
3423 ++(*this);
3424 return tmp;
3425 }
3426
3427 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3428 return x.Current == y.Current;
3429 }
3430 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3431 return x.Current != y.Current;
3432 }
3433 };
3434
3435 using shadow_range = llvm::iterator_range<shadow_iterator>;
3436
3437 shadow_range shadows() const {
3438 return shadow_range(shadow_begin(), shadow_end());
3439 }
3440
3441 shadow_iterator shadow_begin() const {
3442 return shadow_iterator(FirstUsingShadow.getPointer());
3443 }
3444
3445 shadow_iterator shadow_end() const { return shadow_iterator(); }
3446
3447 /// Return the number of shadowed declarations associated with this
3448 /// using declaration.
3449 unsigned shadow_size() const {
3450 return std::distance(shadow_begin(), shadow_end());
3451 }
3452
3453 void addShadowDecl(UsingShadowDecl *S);
3454 void removeShadowDecl(UsingShadowDecl *S);
3455
3456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3457 static bool classofKind(Kind K) { return K == Using || K == UsingEnum; }
3458};
3459
3460/// Represents a C++ using-declaration.
3461///
3462/// For example:
3463/// \code
3464/// using someNameSpace::someIdentifier;
3465/// \endcode
3466class UsingDecl : public BaseUsingDecl, public Mergeable<UsingDecl> {
3467 /// The source location of the 'using' keyword itself.
3468 SourceLocation UsingLocation;
3469
3470 /// The nested-name-specifier that precedes the name.
3471 NestedNameSpecifierLoc QualifierLoc;
3472
3473 /// Provides source/type location info for the declaration name
3474 /// embedded in the ValueDecl base class.
3475 DeclarationNameLoc DNLoc;
3476
3477 UsingDecl(DeclContext *DC, SourceLocation UL,
3478 NestedNameSpecifierLoc QualifierLoc,
3479 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3480 : BaseUsingDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3481 UsingLocation(UL), QualifierLoc(QualifierLoc),
3482 DNLoc(NameInfo.getInfo()) {
3483 setShadowFlag(HasTypenameKeyword);
3484 }
3485
3486 void anchor() override;
3487
3488public:
3489 friend class ASTDeclReader;
3490 friend class ASTDeclWriter;
3491
3492 /// Return the source location of the 'using' keyword.
3493 SourceLocation getUsingLoc() const { return UsingLocation; }
3494
3495 /// Set the source location of the 'using' keyword.
3496 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3497
3498 /// Retrieve the nested-name-specifier that qualifies the name,
3499 /// with source-location information.
3500 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3501
3502 /// Retrieve the nested-name-specifier that qualifies the name.
3503 NestedNameSpecifier *getQualifier() const {
3504 return QualifierLoc.getNestedNameSpecifier();
3505 }
3506
3507 DeclarationNameInfo getNameInfo() const {
3508 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3509 }
3510
3511 /// Return true if it is a C++03 access declaration (no 'using').
3512 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3513
3514 /// Return true if the using declaration has 'typename'.
3515 bool hasTypename() const { return getShadowFlag(); }
3516
3517 /// Sets whether the using declaration has 'typename'.
3518 void setTypename(bool TN) { setShadowFlag(TN); }
3519
3520 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3521 SourceLocation UsingL,
3522 NestedNameSpecifierLoc QualifierLoc,
3523 const DeclarationNameInfo &NameInfo,
3524 bool HasTypenameKeyword);
3525
3526 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3527
3528 SourceRange getSourceRange() const override LLVM_READONLY;
3529
3530 /// Retrieves the canonical declaration of this declaration.
3531 UsingDecl *getCanonicalDecl() override {
3532 return cast<UsingDecl>(getFirstDecl());
3533 }
3534 const UsingDecl *getCanonicalDecl() const {
3535 return cast<UsingDecl>(getFirstDecl());
3536 }
3537
3538 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3539 static bool classofKind(Kind K) { return K == Using; }
3540};
3541
3542/// Represents a shadow constructor declaration introduced into a
3543/// class by a C++11 using-declaration that names a constructor.
3544///
3545/// For example:
3546/// \code
3547/// struct Base { Base(int); };
3548/// struct Derived {
3549/// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3550/// };
3551/// \endcode
3552class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3553 /// If this constructor using declaration inherted the constructor
3554 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3555 /// in the named direct base class from which the declaration was inherited.
3556 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3557
3558 /// If this constructor using declaration inherted the constructor
3559 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3560 /// that will be used to construct the unique direct or virtual base class
3561 /// that receives the constructor arguments.
3562 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3563
3564 /// \c true if the constructor ultimately named by this using shadow
3565 /// declaration is within a virtual base class subobject of the class that
3566 /// contains this declaration.
3567 unsigned IsVirtual : 1;
3568
3569 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3570 UsingDecl *Using, NamedDecl *Target,
3571 bool TargetInVirtualBase)
3572 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc,
3573 Using->getDeclName(), Using,
3574 Target->getUnderlyingDecl()),
3575 NominatedBaseClassShadowDecl(
3576 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3577 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3578 IsVirtual(TargetInVirtualBase) {
3579 // If we found a constructor that chains to a constructor for a virtual
3580 // base, we should directly call that virtual base constructor instead.
3581 // FIXME: This logic belongs in Sema.
3582 if (NominatedBaseClassShadowDecl &&
3583 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3584 ConstructedBaseClassShadowDecl =
3585 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3586 IsVirtual = true;
3587 }
3588 }
3589
3590 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3591 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3592
3593 void anchor() override;
3594
3595public:
3596 friend class ASTDeclReader;
3597 friend class ASTDeclWriter;
3598
3599 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3600 SourceLocation Loc,
3601 UsingDecl *Using, NamedDecl *Target,
3602 bool IsVirtual);
3603 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3604 unsigned ID);
3605
3606 /// Override the UsingShadowDecl's getIntroducer, returning the UsingDecl that
3607 /// introduced this.
3608 UsingDecl *getIntroducer() const {
3609 return cast<UsingDecl>(UsingShadowDecl::getIntroducer());
3610 }
3611
3612 /// Returns the parent of this using shadow declaration, which
3613 /// is the class in which this is declared.
3614 //@{
3615 const CXXRecordDecl *getParent() const {
3616 return cast<CXXRecordDecl>(getDeclContext());
3617 }
3618 CXXRecordDecl *getParent() {
3619 return cast<CXXRecordDecl>(getDeclContext());
3620 }
3621 //@}
3622
3623 /// Get the inheriting constructor declaration for the direct base
3624 /// class from which this using shadow declaration was inherited, if there is
3625 /// one. This can be different for each redeclaration of the same shadow decl.
3626 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3627 return NominatedBaseClassShadowDecl;
3628 }
3629
3630 /// Get the inheriting constructor declaration for the base class
3631 /// for which we don't have an explicit initializer, if there is one.
3632 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3633 return ConstructedBaseClassShadowDecl;
3634 }
3635
3636 /// Get the base class that was named in the using declaration. This
3637 /// can be different for each redeclaration of this same shadow decl.
3638 CXXRecordDecl *getNominatedBaseClass() const;
3639
3640 /// Get the base class whose constructor or constructor shadow
3641 /// declaration is passed the constructor arguments.
3642 CXXRecordDecl *getConstructedBaseClass() const {
3643 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3644 ? ConstructedBaseClassShadowDecl
3645 : getTargetDecl())
3646 ->getDeclContext());
3647 }
3648
3649 /// Returns \c true if the constructed base class is a virtual base
3650 /// class subobject of this declaration's class.
3651 bool constructsVirtualBase() const {
3652 return IsVirtual;
3653 }
3654
3655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3656 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3657};
3658
3659/// Represents a C++ using-enum-declaration.
3660///
3661/// For example:
3662/// \code
3663/// using enum SomeEnumTag ;
3664/// \endcode
3665
3666class UsingEnumDecl : public BaseUsingDecl, public Mergeable<UsingEnumDecl> {
3667 /// The source location of the 'using' keyword itself.
3668 SourceLocation UsingLocation;
3669 /// The source location of the 'enum' keyword.
3670 SourceLocation EnumLocation;
3671 /// 'qual::SomeEnum' as an EnumType, possibly with Elaborated/Typedef sugar.
3672 TypeSourceInfo *EnumType;
3673
3674 UsingEnumDecl(DeclContext *DC, DeclarationName DN, SourceLocation UL,
3675 SourceLocation EL, SourceLocation NL, TypeSourceInfo *EnumType)
3676 : BaseUsingDecl(UsingEnum, DC, NL, DN), UsingLocation(UL), EnumLocation(EL),
3677 EnumType(EnumType){}
3678
3679 void anchor() override;
3680
3681public:
3682 friend class ASTDeclReader;
3683 friend class ASTDeclWriter;
3684
3685 /// The source location of the 'using' keyword.
3686 SourceLocation getUsingLoc() const { return UsingLocation; }
3687 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3688
3689 /// The source location of the 'enum' keyword.
3690 SourceLocation getEnumLoc() const { return EnumLocation; }
3691 void setEnumLoc(SourceLocation L) { EnumLocation = L; }
3692 NestedNameSpecifier *getQualifier() const {
3693 return getQualifierLoc().getNestedNameSpecifier();
3694 }
3695 NestedNameSpecifierLoc getQualifierLoc() const {
3696 if (auto ETL = EnumType->getTypeLoc().getAs<ElaboratedTypeLoc>())
3697 return ETL.getQualifierLoc();
3698 return NestedNameSpecifierLoc();
3699 }
3700 // Returns the "qualifier::Name" part as a TypeLoc.
3701 TypeLoc getEnumTypeLoc() const {
3702 return EnumType->getTypeLoc();
3703 }
3704 TypeSourceInfo *getEnumType() const {
3705 return EnumType;
3706 }
3707 void setEnumType(TypeSourceInfo *TSI) { EnumType = TSI; }
3708
3709public:
3710 EnumDecl *getEnumDecl() const { return cast<EnumDecl>(EnumType->getType()->getAsTagDecl()); }
3711
3712 static UsingEnumDecl *Create(ASTContext &C, DeclContext *DC,
3713 SourceLocation UsingL, SourceLocation EnumL,
3714 SourceLocation NameL, TypeSourceInfo *EnumType);
3715
3716 static UsingEnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3717
3718 SourceRange getSourceRange() const override LLVM_READONLY;
3719
3720 /// Retrieves the canonical declaration of this declaration.
3721 UsingEnumDecl *getCanonicalDecl() override {
3722 return cast<UsingEnumDecl>(getFirstDecl());
3723 }
3724 const UsingEnumDecl *getCanonicalDecl() const {
3725 return cast<UsingEnumDecl>(getFirstDecl());
3726 }
3727
3728 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3729 static bool classofKind(Kind K) { return K == UsingEnum; }
3730};
3731
3732/// Represents a pack of using declarations that a single
3733/// using-declarator pack-expanded into.
3734///
3735/// \code
3736/// template<typename ...T> struct X : T... {
3737/// using T::operator()...;
3738/// using T::operator T...;
3739/// };
3740/// \endcode
3741///
3742/// In the second case above, the UsingPackDecl will have the name
3743/// 'operator T' (which contains an unexpanded pack), but the individual
3744/// UsingDecls and UsingShadowDecls will have more reasonable names.
3745class UsingPackDecl final
3746 : public NamedDecl, public Mergeable<UsingPackDecl>,
3747 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3748 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3749 /// which this waas instantiated.
3750 NamedDecl *InstantiatedFrom;
3751
3752 /// The number of using-declarations created by this pack expansion.
3753 unsigned NumExpansions;
3754
3755 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3756 ArrayRef<NamedDecl *> UsingDecls)
3757 : NamedDecl(UsingPack, DC,
3758 InstantiatedFrom ? InstantiatedFrom->getLocation()
3759 : SourceLocation(),
3760 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3761 : DeclarationName()),
3762 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3763 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3764 getTrailingObjects<NamedDecl *>());
3765 }
3766
3767 void anchor() override;
3768
3769public:
3770 friend class ASTDeclReader;
3771 friend class ASTDeclWriter;
3772 friend TrailingObjects;
3773
3774 /// Get the using declaration from which this was instantiated. This will
3775 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3776 /// that is a pack expansion.
3777 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3778
3779 /// Get the set of using declarations that this pack expanded into. Note that
3780 /// some of these may still be unresolved.
3781 ArrayRef<NamedDecl *> expansions() const {
3782 return llvm::ArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3783 }
3784
3785 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3786 NamedDecl *InstantiatedFrom,
3787 ArrayRef<NamedDecl *> UsingDecls);
3788
3789 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3790 unsigned NumExpansions);
3791
3792 SourceRange getSourceRange() const override LLVM_READONLY {
3793 return InstantiatedFrom->getSourceRange();
3794 }
3795
3796 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3797 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3798
3799 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3800 static bool classofKind(Kind K) { return K == UsingPack; }
3801};
3802
3803/// Represents a dependent using declaration which was not marked with
3804/// \c typename.
3805///
3806/// Unlike non-dependent using declarations, these *only* bring through
3807/// non-types; otherwise they would break two-phase lookup.
3808///
3809/// \code
3810/// template \<class T> class A : public Base<T> {
3811/// using Base<T>::foo;
3812/// };
3813/// \endcode
3814class UnresolvedUsingValueDecl : public ValueDecl,
3815 public Mergeable<UnresolvedUsingValueDecl> {
3816 /// The source location of the 'using' keyword
3817 SourceLocation UsingLocation;
3818
3819 /// If this is a pack expansion, the location of the '...'.
3820 SourceLocation EllipsisLoc;
3821
3822 /// The nested-name-specifier that precedes the name.
3823 NestedNameSpecifierLoc QualifierLoc;
3824
3825 /// Provides source/type location info for the declaration name
3826 /// embedded in the ValueDecl base class.
3827 DeclarationNameLoc DNLoc;
3828
3829 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3830 SourceLocation UsingLoc,
3831 NestedNameSpecifierLoc QualifierLoc,
3832 const DeclarationNameInfo &NameInfo,
3833 SourceLocation EllipsisLoc)
3834 : ValueDecl(UnresolvedUsingValue, DC,
3835 NameInfo.getLoc(), NameInfo.getName(), Ty),
3836 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3837 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3838
3839 void anchor() override;
3840
3841public:
3842 friend class ASTDeclReader;
3843 friend class ASTDeclWriter;
3844
3845 /// Returns the source location of the 'using' keyword.
3846 SourceLocation getUsingLoc() const { return UsingLocation; }
3847
3848 /// Set the source location of the 'using' keyword.
3849 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3850
3851 /// Return true if it is a C++03 access declaration (no 'using').
3852 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3853
3854 /// Retrieve the nested-name-specifier that qualifies the name,
3855 /// with source-location information.
3856 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3857
3858 /// Retrieve the nested-name-specifier that qualifies the name.
3859 NestedNameSpecifier *getQualifier() const {
3860 return QualifierLoc.getNestedNameSpecifier();
3861 }
3862
3863 DeclarationNameInfo getNameInfo() const {
3864 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3865 }
3866
3867 /// Determine whether this is a pack expansion.
3868 bool isPackExpansion() const {
3869 return EllipsisLoc.isValid();
3870 }
3871
3872 /// Get the location of the ellipsis if this is a pack expansion.
3873 SourceLocation getEllipsisLoc() const {
3874 return EllipsisLoc;
3875 }
3876
3877 static UnresolvedUsingValueDecl *
3878 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3879 NestedNameSpecifierLoc QualifierLoc,
3880 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3881
3882 static UnresolvedUsingValueDecl *
3883 CreateDeserialized(ASTContext &C, unsigned ID);
3884
3885 SourceRange getSourceRange() const override LLVM_READONLY;
3886
3887 /// Retrieves the canonical declaration of this declaration.
3888 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3889 return getFirstDecl();
3890 }
3891 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3892 return getFirstDecl();
3893 }
3894
3895 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3896 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3897};
3898
3899/// Represents a dependent using declaration which was marked with
3900/// \c typename.
3901///
3902/// \code
3903/// template \<class T> class A : public Base<T> {
3904/// using typename Base<T>::foo;
3905/// };
3906/// \endcode
3907///
3908/// The type associated with an unresolved using typename decl is
3909/// currently always a typename type.
3910class UnresolvedUsingTypenameDecl
3911 : public TypeDecl,
3912 public Mergeable<UnresolvedUsingTypenameDecl> {
3913 friend class ASTDeclReader;
3914
3915 /// The source location of the 'typename' keyword
3916 SourceLocation TypenameLocation;
3917
3918 /// If this is a pack expansion, the location of the '...'.
3919 SourceLocation EllipsisLoc;
3920
3921 /// The nested-name-specifier that precedes the name.
3922 NestedNameSpecifierLoc QualifierLoc;
3923
3924 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3925 SourceLocation TypenameLoc,
3926 NestedNameSpecifierLoc QualifierLoc,
3927 SourceLocation TargetNameLoc,
3928 IdentifierInfo *TargetName,
3929 SourceLocation EllipsisLoc)
3930 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3931 UsingLoc),
3932 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3933 QualifierLoc(QualifierLoc) {}
3934
3935 void anchor() override;
3936
3937public:
3938 /// Returns the source location of the 'using' keyword.
3939 SourceLocation getUsingLoc() const { return getBeginLoc(); }
3940
3941 /// Returns the source location of the 'typename' keyword.
3942 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3943
3944 /// Retrieve the nested-name-specifier that qualifies the name,
3945 /// with source-location information.
3946 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3947
3948 /// Retrieve the nested-name-specifier that qualifies the name.
3949 NestedNameSpecifier *getQualifier() const {
3950 return QualifierLoc.getNestedNameSpecifier();
3951 }
3952
3953 DeclarationNameInfo getNameInfo() const {
3954 return DeclarationNameInfo(getDeclName(), getLocation());
3955 }
3956
3957 /// Determine whether this is a pack expansion.
3958 bool isPackExpansion() const {
3959 return EllipsisLoc.isValid();
3960 }
3961
3962 /// Get the location of the ellipsis if this is a pack expansion.
3963 SourceLocation getEllipsisLoc() const {
3964 return EllipsisLoc;
3965 }
3966
3967 static UnresolvedUsingTypenameDecl *
3968 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3969 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3970 SourceLocation TargetNameLoc, DeclarationName TargetName,
3971 SourceLocation EllipsisLoc);
3972
3973 static UnresolvedUsingTypenameDecl *
3974 CreateDeserialized(ASTContext &C, unsigned ID);
3975
3976 /// Retrieves the canonical declaration of this declaration.
3977 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3978 return getFirstDecl();
3979 }
3980 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3981 return getFirstDecl();
3982 }
3983
3984 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3985 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3986};
3987
3988/// This node is generated when a using-declaration that was annotated with
3989/// __attribute__((using_if_exists)) failed to resolve to a known declaration.
3990/// In that case, Sema builds a UsingShadowDecl whose target is an instance of
3991/// this declaration, adding it to the current scope. Referring to this
3992/// declaration in any way is an error.
3993class UnresolvedUsingIfExistsDecl final : public NamedDecl {
3994 UnresolvedUsingIfExistsDecl(DeclContext *DC, SourceLocation Loc,
3995 DeclarationName Name);
3996
3997 void anchor() override;
3998
3999public:
4000 static UnresolvedUsingIfExistsDecl *Create(ASTContext &Ctx, DeclContext *DC,
4001 SourceLocation Loc,
4002 DeclarationName Name);
4003 static UnresolvedUsingIfExistsDecl *CreateDeserialized(ASTContext &Ctx,
4004 unsigned ID);
4005
4006 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4007 static bool classofKind(Kind K) { return K == Decl::UnresolvedUsingIfExists; }
4008};
4009
4010/// Represents a C++11 static_assert declaration.
4011class StaticAssertDecl : public Decl {
4012 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
4013 Expr *Message;
4014 SourceLocation RParenLoc;
4015
4016 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
4017 Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc,
4018 bool Failed)
4019 : Decl(StaticAssert, DC, StaticAssertLoc),
4020 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
4021 RParenLoc(RParenLoc) {}
4022
4023 virtual void anchor();
4024
4025public:
4026 friend class ASTDeclReader;
4027
4028 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
4029 SourceLocation StaticAssertLoc,
4030 Expr *AssertExpr, Expr *Message,
4031 SourceLocation RParenLoc, bool Failed);
4032 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4033
4034 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
4035 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
4036
4037 Expr *getMessage() { return Message; }
4038 const Expr *getMessage() const { return Message; }
4039
4040 bool isFailed() const { return AssertExprAndFailed.getInt(); }
4041
4042 SourceLocation getRParenLoc() const { return RParenLoc; }
4043
4044 SourceRange getSourceRange() const override LLVM_READONLY {
4045 return SourceRange(getLocation(), getRParenLoc());
4046 }
4047
4048 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4049 static bool classofKind(Kind K) { return K == StaticAssert; }
4050};
4051
4052/// A binding in a decomposition declaration. For instance, given:
4053///
4054/// int n[3];
4055/// auto &[a, b, c] = n;
4056///
4057/// a, b, and c are BindingDecls, whose bindings are the expressions
4058/// x[0], x[1], and x[2] respectively, where x is the implicit
4059/// DecompositionDecl of type 'int (&)[3]'.
4060class BindingDecl : public ValueDecl {
4061 /// The declaration that this binding binds to part of.
4062 ValueDecl *Decomp;
4063 /// The binding represented by this declaration. References to this
4064 /// declaration are effectively equivalent to this expression (except
4065 /// that it is only evaluated once at the point of declaration of the
4066 /// binding).
4067 Expr *Binding = nullptr;
4068
4069 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
4070 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
4071
4072 void anchor() override;
4073
4074public:
4075 friend class ASTDeclReader;
4076
4077 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
4078 SourceLocation IdLoc, IdentifierInfo *Id);
4079 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4080
4081 /// Get the expression to which this declaration is bound. This may be null
4082 /// in two different cases: while parsing the initializer for the
4083 /// decomposition declaration, and when the initializer is type-dependent.
4084 Expr *getBinding() const { return Binding; }
4085
4086 /// Get the decomposition declaration that this binding represents a
4087 /// decomposition of.
4088 ValueDecl *getDecomposedDecl() const { return Decomp; }
4089
4090 /// Get the variable (if any) that holds the value of evaluating the binding.
4091 /// Only present for user-defined bindings for tuple-like types.
4092 VarDecl *getHoldingVar() const;
4093
4094 /// Set the binding for this BindingDecl, along with its declared type (which
4095 /// should be a possibly-cv-qualified form of the type of the binding, or a
4096 /// reference to such a type).
4097 void setBinding(QualType DeclaredType, Expr *Binding) {
4098 setType(DeclaredType);
4099 this->Binding = Binding;
4100 }
4101
4102 /// Set the decomposed variable for this BindingDecl.
4103 void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
4104
4105 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4106 static bool classofKind(Kind K) { return K == Decl::Binding; }
4107};
4108
4109/// A decomposition declaration. For instance, given:
4110///
4111/// int n[3];
4112/// auto &[a, b, c] = n;
4113///
4114/// the second line declares a DecompositionDecl of type 'int (&)[3]', and
4115/// three BindingDecls (named a, b, and c). An instance of this class is always
4116/// unnamed, but behaves in almost all other respects like a VarDecl.
4117class DecompositionDecl final
4118 : public VarDecl,
4119 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
4120 /// The number of BindingDecl*s following this object.
4121 unsigned NumBindings;
4122
4123 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4124 SourceLocation LSquareLoc, QualType T,
4125 TypeSourceInfo *TInfo, StorageClass SC,
4126 ArrayRef<BindingDecl *> Bindings)
4127 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
4128 SC),
4129 NumBindings(Bindings.size()) {
4130 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
4131 getTrailingObjects<BindingDecl *>());
4132 for (auto *B : Bindings)
4133 B->setDecomposedDecl(this);
4134 }
4135
4136 void anchor() override;
4137
4138public:
4139 friend class ASTDeclReader;
4140 friend TrailingObjects;
4141
4142 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
4143 SourceLocation StartLoc,
4144 SourceLocation LSquareLoc,
4145 QualType T, TypeSourceInfo *TInfo,
4146 StorageClass S,
4147 ArrayRef<BindingDecl *> Bindings);
4148 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4149 unsigned NumBindings);
4150
4151 ArrayRef<BindingDecl *> bindings() const {
4152 return llvm::ArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
4153 }
4154
4155 void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
4156
4157 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4158 static bool classofKind(Kind K) { return K == Decomposition; }
4159};
4160
4161/// An instance of this class represents the declaration of a property
4162/// member. This is a Microsoft extension to C++, first introduced in
4163/// Visual Studio .NET 2003 as a parallel to similar features in C#
4164/// and Managed C++.
4165///
4166/// A property must always be a non-static class member.
4167///
4168/// A property member superficially resembles a non-static data
4169/// member, except preceded by a property attribute:
4170/// __declspec(property(get=GetX, put=PutX)) int x;
4171/// Either (but not both) of the 'get' and 'put' names may be omitted.
4172///
4173/// A reference to a property is always an lvalue. If the lvalue
4174/// undergoes lvalue-to-rvalue conversion, then a getter name is
4175/// required, and that member is called with no arguments.
4176/// If the lvalue is assigned into, then a setter name is required,
4177/// and that member is called with one argument, the value assigned.
4178/// Both operations are potentially overloaded. Compound assignments
4179/// are permitted, as are the increment and decrement operators.
4180///
4181/// The getter and putter methods are permitted to be overloaded,
4182/// although their return and parameter types are subject to certain
4183/// restrictions according to the type of the property.
4184///
4185/// A property declared using an incomplete array type may
4186/// additionally be subscripted, adding extra parameters to the getter
4187/// and putter methods.
4188class MSPropertyDecl : public DeclaratorDecl {
4189 IdentifierInfo *GetterId, *SetterId;
4190
4191 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
4192 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
4193 IdentifierInfo *Getter, IdentifierInfo *Setter)
4194 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
4195 GetterId(Getter), SetterId(Setter) {}
4196
4197 void anchor() override;
4198public:
4199 friend class ASTDeclReader;
4200
4201 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
4202 SourceLocation L, DeclarationName N, QualType T,
4203 TypeSourceInfo *TInfo, SourceLocation StartL,
4204 IdentifierInfo *Getter, IdentifierInfo *Setter);
4205 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4206
4207 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
4208
4209 bool hasGetter() const { return GetterId != nullptr; }
4210 IdentifierInfo* getGetterId() const { return GetterId; }
4211 bool hasSetter() const { return SetterId != nullptr; }
4212 IdentifierInfo* getSetterId() const { return SetterId; }
4213};
4214
4215/// Parts of a decomposed MSGuidDecl. Factored out to avoid unnecessary
4216/// dependencies on DeclCXX.h.
4217struct MSGuidDeclParts {
4218 /// {01234567-...
4219 uint32_t Part1;
4220 /// ...-89ab-...
4221 uint16_t Part2;
4222 /// ...-cdef-...
4223 uint16_t Part3;
4224 /// ...-0123-456789abcdef}
4225 uint8_t Part4And5[8];
4226
4227 uint64_t getPart4And5AsUint64() const {
4228 uint64_t Val;
4229 memcpy(&Val, &Part4And5, sizeof(Part4And5));
4230 return Val;
4231 }
4232};
4233
4234/// A global _GUID constant. These are implicitly created by UuidAttrs.
4235///
4236/// struct _declspec(uuid("01234567-89ab-cdef-0123-456789abcdef")) X{};
4237///
4238/// X is a CXXRecordDecl that contains a UuidAttr that references the (unique)
4239/// MSGuidDecl for the specified UUID.
4240class MSGuidDecl : public ValueDecl,
4241 public Mergeable<MSGuidDecl>,
4242 public llvm::FoldingSetNode {
4243public:
4244 using Parts = MSGuidDeclParts;
4245
4246private:
4247 /// The decomposed form of the UUID.
4248 Parts PartVal;
4249
4250 /// The resolved value of the UUID as an APValue. Computed on demand and
4251 /// cached.
4252 mutable APValue APVal;
4253
4254 void anchor() override;
4255
4256 MSGuidDecl(DeclContext *DC, QualType T, Parts P);
4257
4258 static MSGuidDecl *Create(const ASTContext &C, QualType T, Parts P);
4259 static MSGuidDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4260
4261 // Only ASTContext::getMSGuidDecl and deserialization create these.
4262 friend class ASTContext;
4263 friend class ASTReader;
4264 friend class ASTDeclReader;
4265
4266public:
4267 /// Print this UUID in a human-readable format.
4268 void printName(llvm::raw_ostream &OS,
4269 const PrintingPolicy &Policy) const override;
4270
4271 /// Get the decomposed parts of this declaration.
4272 Parts getParts() const { return PartVal; }
4273
4274 /// Get the value of this MSGuidDecl as an APValue. This may fail and return
4275 /// an absent APValue if the type of the declaration is not of the expected
4276 /// shape.
4277 APValue &getAsAPValue() const;
4278
4279 static void Profile(llvm::FoldingSetNodeID &ID, Parts P) {
4280 ID.AddInteger(P.Part1);
4281 ID.AddInteger(P.Part2);
4282 ID.AddInteger(P.Part3);
4283 ID.AddInteger(P.getPart4And5AsUint64());
4284 }
4285 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, PartVal); }
4286
4287 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4288 static bool classofKind(Kind K) { return K == Decl::MSGuid; }
4289};
4290
4291/// An artificial decl, representing a global anonymous constant value which is
4292/// uniquified by value within a translation unit.
4293///
4294/// These is currently only used to back the LValue returned by
4295/// __builtin_source_location, but could potentially be used for other similar
4296/// situations in the future.
4297class UnnamedGlobalConstantDecl : public ValueDecl,
4298 public Mergeable<UnnamedGlobalConstantDecl>,
4299 public llvm::FoldingSetNode {
4300
4301 // The constant value of this global.
4302 APValue Value;
4303
4304 void anchor() override;
4305
4306 UnnamedGlobalConstantDecl(const ASTContext &C, DeclContext *DC, QualType T,
4307 const APValue &Val);
4308
4309 static UnnamedGlobalConstantDecl *Create(const ASTContext &C, QualType T,
4310 const APValue &APVal);
4311 static UnnamedGlobalConstantDecl *CreateDeserialized(ASTContext &C,
4312 unsigned ID);
4313
4314 // Only ASTContext::getUnnamedGlobalConstantDecl and deserialization create
4315 // these.
4316 friend class ASTContext;
4317 friend class ASTReader;
4318 friend class ASTDeclReader;
4319
4320public:
4321 /// Print this in a human-readable format.
4322 void printName(llvm::raw_ostream &OS,
4323 const PrintingPolicy &Policy) const override;
4324
4325 const APValue &getValue() const { return Value; }
4326
4327 static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty,
4328 const APValue &APVal) {
4329 Ty.Profile(ID);
4330 APVal.Profile(ID);
4331 }
4332 void Profile(llvm::FoldingSetNodeID &ID) {
4333 Profile(ID, getType(), getValue());
4334 }
4335
4336 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4337 static bool classofKind(Kind K) { return K == Decl::UnnamedGlobalConstant; }
4338};
4339
4340/// Insertion operator for diagnostics. This allows sending an AccessSpecifier
4341/// into a diagnostic with <<.
4342const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
4343 AccessSpecifier AS);
4344
4345} // namespace clang
4346
4347#endif // LLVM_CLANG_AST_DECLCXX_H
4348