xref: /freebsd/contrib/llvm-project/clang/include/clang/Sema/DeclSpec.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===--- DeclSpec.h - Parsed declaration specifiers -------------*- 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 /// This file defines the classes used to store parsed information about
11 /// declaration-specifiers and declarators.
12 ///
13 /// \verbatim
14 ///   static const int volatile x, *y, *(*(*z)[10])(const void *x);
15 ///   ------------------------- -  --  ---------------------------
16 ///     declaration-specifiers  \  |   /
17 ///                            declarators
18 /// \endverbatim
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23 #define LLVM_CLANG_SEMA_DECLSPEC_H
24 
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/DeclObjCCommon.h"
27 #include "clang/AST/NestedNameSpecifier.h"
28 #include "clang/Basic/ExceptionSpecificationType.h"
29 #include "clang/Basic/Lambda.h"
30 #include "clang/Basic/OperatorKinds.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Lex/Token.h"
33 #include "clang/Sema/Ownership.h"
34 #include "clang/Sema/ParsedAttr.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include <optional>
40 
41 namespace clang {
42   class ASTContext;
43   class CXXRecordDecl;
44   class TypeLoc;
45   class LangOptions;
46   class IdentifierInfo;
47   class NamespaceAliasDecl;
48   class NamespaceDecl;
49   class ObjCDeclSpec;
50   class Sema;
51   class Declarator;
52   struct TemplateIdAnnotation;
53 
54 /// Represents a C++ nested-name-specifier or a global scope specifier.
55 ///
56 /// These can be in 3 states:
57 ///   1) Not present, identified by isEmpty()
58 ///   2) Present, identified by isNotEmpty()
59 ///      2.a) Valid, identified by isValid()
60 ///      2.b) Invalid, identified by isInvalid().
61 ///
62 /// isSet() is deprecated because it mostly corresponded to "valid" but was
63 /// often used as if it meant "present".
64 ///
65 /// The actual scope is described by getScopeRep().
66 ///
67 /// If the kind of getScopeRep() is TypeSpec then TemplateParamLists may be empty
68 /// or contain the template parameter lists attached to the current declaration.
69 /// Consider the following example:
70 /// template <class T> void SomeType<T>::some_method() {}
71 /// If CXXScopeSpec refers to SomeType<T> then TemplateParamLists will contain
72 /// a single element referring to template <class T>.
73 
74 class CXXScopeSpec {
75   SourceRange Range;
76   NestedNameSpecifierLocBuilder Builder;
77   ArrayRef<TemplateParameterList *> TemplateParamLists;
78 
79 public:
getRange()80   SourceRange getRange() const { return Range; }
setRange(SourceRange R)81   void setRange(SourceRange R) { Range = R; }
setBeginLoc(SourceLocation Loc)82   void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
setEndLoc(SourceLocation Loc)83   void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
getBeginLoc()84   SourceLocation getBeginLoc() const { return Range.getBegin(); }
getEndLoc()85   SourceLocation getEndLoc() const { return Range.getEnd(); }
86 
setTemplateParamLists(ArrayRef<TemplateParameterList * > L)87   void setTemplateParamLists(ArrayRef<TemplateParameterList *> L) {
88     TemplateParamLists = L;
89   }
getTemplateParamLists()90   ArrayRef<TemplateParameterList *> getTemplateParamLists() const {
91     return TemplateParamLists;
92   }
93 
94   /// Retrieve the representation of the nested-name-specifier.
getScopeRep()95   NestedNameSpecifier *getScopeRep() const {
96     return Builder.getRepresentation();
97   }
98 
99   /// Extend the current nested-name-specifier by another
100   /// nested-name-specifier component of the form 'type::'.
101   ///
102   /// \param Context The AST context in which this nested-name-specifier
103   /// resides.
104   ///
105   /// \param TemplateKWLoc The location of the 'template' keyword, if present.
106   ///
107   /// \param TL The TypeLoc that describes the type preceding the '::'.
108   ///
109   /// \param ColonColonLoc The location of the trailing '::'.
110   void Extend(ASTContext &Context, TypeLoc TL, SourceLocation ColonColonLoc);
111 
112   /// Extend the current nested-name-specifier by another
113   /// nested-name-specifier component of the form 'identifier::'.
114   ///
115   /// \param Context The AST context in which this nested-name-specifier
116   /// resides.
117   ///
118   /// \param Identifier The identifier.
119   ///
120   /// \param IdentifierLoc The location of the identifier.
121   ///
122   /// \param ColonColonLoc The location of the trailing '::'.
123   void Extend(ASTContext &Context, IdentifierInfo *Identifier,
124               SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
125 
126   /// Extend the current nested-name-specifier by another
127   /// nested-name-specifier component of the form 'namespace::'.
128   ///
129   /// \param Context The AST context in which this nested-name-specifier
130   /// resides.
131   ///
132   /// \param Namespace The namespace.
133   ///
134   /// \param NamespaceLoc The location of the namespace name.
135   ///
136   /// \param ColonColonLoc The location of the trailing '::'.
137   void Extend(ASTContext &Context, NamespaceDecl *Namespace,
138               SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
139 
140   /// Extend the current nested-name-specifier by another
141   /// nested-name-specifier component of the form 'namespace-alias::'.
142   ///
143   /// \param Context The AST context in which this nested-name-specifier
144   /// resides.
145   ///
146   /// \param Alias The namespace alias.
147   ///
148   /// \param AliasLoc The location of the namespace alias
149   /// name.
150   ///
151   /// \param ColonColonLoc The location of the trailing '::'.
152   void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
153               SourceLocation AliasLoc, SourceLocation ColonColonLoc);
154 
155   /// Turn this (empty) nested-name-specifier into the global
156   /// nested-name-specifier '::'.
157   void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
158 
159   /// Turns this (empty) nested-name-specifier into '__super'
160   /// nested-name-specifier.
161   ///
162   /// \param Context The AST context in which this nested-name-specifier
163   /// resides.
164   ///
165   /// \param RD The declaration of the class in which nested-name-specifier
166   /// appeared.
167   ///
168   /// \param SuperLoc The location of the '__super' keyword.
169   /// name.
170   ///
171   /// \param ColonColonLoc The location of the trailing '::'.
172   void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
173                  SourceLocation SuperLoc, SourceLocation ColonColonLoc);
174 
175   /// Make a new nested-name-specifier from incomplete source-location
176   /// information.
177   ///
178   /// FIXME: This routine should be used very, very rarely, in cases where we
179   /// need to synthesize a nested-name-specifier. Most code should instead use
180   /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
181   void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
182                    SourceRange R);
183 
184   /// Adopt an existing nested-name-specifier (with source-range
185   /// information).
186   void Adopt(NestedNameSpecifierLoc Other);
187 
188   /// Retrieve a nested-name-specifier with location information, copied
189   /// into the given AST context.
190   ///
191   /// \param Context The context into which this nested-name-specifier will be
192   /// copied.
193   NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
194 
195   /// Retrieve the location of the name in the last qualifier
196   /// in this nested name specifier.
197   ///
198   /// For example, the location of \c bar
199   /// in
200   /// \verbatim
201   ///   \::foo::bar<0>::
202   ///           ^~~
203   /// \endverbatim
204   SourceLocation getLastQualifierNameLoc() const;
205 
206   /// No scope specifier.
isEmpty()207   bool isEmpty() const { return Range.isInvalid() && getScopeRep() == nullptr; }
208   /// A scope specifier is present, but may be valid or invalid.
isNotEmpty()209   bool isNotEmpty() const { return !isEmpty(); }
210 
211   /// An error occurred during parsing of the scope specifier.
isInvalid()212   bool isInvalid() const { return Range.isValid() && getScopeRep() == nullptr; }
213   /// A scope specifier is present, and it refers to a real scope.
isValid()214   bool isValid() const { return getScopeRep() != nullptr; }
215 
216   /// Indicate that this nested-name-specifier is invalid.
SetInvalid(SourceRange R)217   void SetInvalid(SourceRange R) {
218     assert(R.isValid() && "Must have a valid source range");
219     if (Range.getBegin().isInvalid())
220       Range.setBegin(R.getBegin());
221     Range.setEnd(R.getEnd());
222     Builder.Clear();
223   }
224 
225   /// Deprecated.  Some call sites intend isNotEmpty() while others intend
226   /// isValid().
isSet()227   bool isSet() const { return getScopeRep() != nullptr; }
228 
clear()229   void clear() {
230     Range = SourceRange();
231     Builder.Clear();
232   }
233 
234   /// Retrieve the data associated with the source-location information.
location_data()235   char *location_data() const { return Builder.getBuffer().first; }
236 
237   /// Retrieve the size of the data associated with source-location
238   /// information.
location_size()239   unsigned location_size() const { return Builder.getBuffer().second; }
240 };
241 
242 /// Captures information about "declaration specifiers".
243 ///
244 /// "Declaration specifiers" encompasses storage-class-specifiers,
245 /// type-specifiers, type-qualifiers, and function-specifiers.
246 class DeclSpec {
247 public:
248   /// storage-class-specifier
249   /// \note The order of these enumerators is important for diagnostics.
250   enum SCS {
251     SCS_unspecified = 0,
252     SCS_typedef,
253     SCS_extern,
254     SCS_static,
255     SCS_auto,
256     SCS_register,
257     SCS_private_extern,
258     SCS_mutable
259   };
260 
261   // Import thread storage class specifier enumeration and constants.
262   // These can be combined with SCS_extern and SCS_static.
263   typedef ThreadStorageClassSpecifier TSCS;
264   static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
265   static const TSCS TSCS___thread = clang::TSCS___thread;
266   static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
267   static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
268 
269   enum TSC {
270     TSC_unspecified,
271     TSC_imaginary, // Unsupported
272     TSC_complex
273   };
274 
275   // Import type specifier type enumeration and constants.
276   typedef TypeSpecifierType TST;
277   static const TST TST_unspecified = clang::TST_unspecified;
278   static const TST TST_void = clang::TST_void;
279   static const TST TST_char = clang::TST_char;
280   static const TST TST_wchar = clang::TST_wchar;
281   static const TST TST_char8 = clang::TST_char8;
282   static const TST TST_char16 = clang::TST_char16;
283   static const TST TST_char32 = clang::TST_char32;
284   static const TST TST_int = clang::TST_int;
285   static const TST TST_int128 = clang::TST_int128;
286   static const TST TST_bitint = clang::TST_bitint;
287   static const TST TST_half = clang::TST_half;
288   static const TST TST_BFloat16 = clang::TST_BFloat16;
289   static const TST TST_float = clang::TST_float;
290   static const TST TST_double = clang::TST_double;
291   static const TST TST_float16 = clang::TST_Float16;
292   static const TST TST_accum = clang::TST_Accum;
293   static const TST TST_fract = clang::TST_Fract;
294   static const TST TST_float128 = clang::TST_float128;
295   static const TST TST_ibm128 = clang::TST_ibm128;
296   static const TST TST_bool = clang::TST_bool;
297   static const TST TST_decimal32 = clang::TST_decimal32;
298   static const TST TST_decimal64 = clang::TST_decimal64;
299   static const TST TST_decimal128 = clang::TST_decimal128;
300   static const TST TST_enum = clang::TST_enum;
301   static const TST TST_union = clang::TST_union;
302   static const TST TST_struct = clang::TST_struct;
303   static const TST TST_interface = clang::TST_interface;
304   static const TST TST_class = clang::TST_class;
305   static const TST TST_typename = clang::TST_typename;
306   static const TST TST_typeofType = clang::TST_typeofType;
307   static const TST TST_typeofExpr = clang::TST_typeofExpr;
308   static const TST TST_typeof_unqualType = clang::TST_typeof_unqualType;
309   static const TST TST_typeof_unqualExpr = clang::TST_typeof_unqualExpr;
310   static const TST TST_decltype = clang::TST_decltype;
311   static const TST TST_decltype_auto = clang::TST_decltype_auto;
312   static const TST TST_typename_pack_indexing =
313       clang::TST_typename_pack_indexing;
314 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait)                                     \
315   static const TST TST_##Trait = clang::TST_##Trait;
316 #include "clang/Basic/TransformTypeTraits.def"
317   static const TST TST_auto = clang::TST_auto;
318   static const TST TST_auto_type = clang::TST_auto_type;
319   static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
320   static const TST TST_atomic = clang::TST_atomic;
321 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
322   static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
323 #include "clang/Basic/OpenCLImageTypes.def"
324 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId)                            \
325   static const TST TST_##Name = clang::TST_##Name;
326 #include "clang/Basic/HLSLIntangibleTypes.def"
327   static const TST TST_error = clang::TST_error;
328 
329   // type-qualifiers
330   enum TQ {   // NOTE: These flags must be kept in sync with Qualifiers::TQ.
331     TQ_unspecified = 0,
332     TQ_const       = 1,
333     TQ_restrict    = 2,
334     TQ_volatile    = 4,
335     TQ_unaligned   = 8,
336     // This has no corresponding Qualifiers::TQ value, because it's not treated
337     // as a qualifier in our type system.
338     TQ_atomic      = 16
339   };
340 
341   /// ParsedSpecifiers - Flags to query which specifiers were applied.  This is
342   /// returned by getParsedSpecifiers.
343   enum ParsedSpecifiers {
344     PQ_None                  = 0,
345     PQ_StorageClassSpecifier = 1,
346     PQ_TypeSpecifier         = 2,
347     PQ_TypeQualifier         = 4,
348     PQ_FunctionSpecifier     = 8
349     // FIXME: Attributes should be included here.
350   };
351 
352   enum FriendSpecified : bool { No, Yes };
353 
354 private:
355   // storage-class-specifier
356   LLVM_PREFERRED_TYPE(SCS)
357   unsigned StorageClassSpec : 3;
358   LLVM_PREFERRED_TYPE(TSCS)
359   unsigned ThreadStorageClassSpec : 2;
360   LLVM_PREFERRED_TYPE(bool)
361   unsigned SCS_extern_in_linkage_spec : 1;
362 
363   // type-specifier
364   LLVM_PREFERRED_TYPE(TypeSpecifierWidth)
365   unsigned TypeSpecWidth : 2;
366   LLVM_PREFERRED_TYPE(TSC)
367   unsigned TypeSpecComplex : 2;
368   LLVM_PREFERRED_TYPE(TypeSpecifierSign)
369   unsigned TypeSpecSign : 2;
370   LLVM_PREFERRED_TYPE(TST)
371   unsigned TypeSpecType : 7;
372   LLVM_PREFERRED_TYPE(bool)
373   unsigned TypeAltiVecVector : 1;
374   LLVM_PREFERRED_TYPE(bool)
375   unsigned TypeAltiVecPixel : 1;
376   LLVM_PREFERRED_TYPE(bool)
377   unsigned TypeAltiVecBool : 1;
378   LLVM_PREFERRED_TYPE(bool)
379   unsigned TypeSpecOwned : 1;
380   LLVM_PREFERRED_TYPE(bool)
381   unsigned TypeSpecPipe : 1;
382   LLVM_PREFERRED_TYPE(bool)
383   unsigned TypeSpecSat : 1;
384   LLVM_PREFERRED_TYPE(bool)
385   unsigned ConstrainedAuto : 1;
386 
387   // type-qualifiers
388   LLVM_PREFERRED_TYPE(TQ)
389   unsigned TypeQualifiers : 5;  // Bitwise OR of TQ.
390 
391   // function-specifier
392   LLVM_PREFERRED_TYPE(bool)
393   unsigned FS_inline_specified : 1;
394   LLVM_PREFERRED_TYPE(bool)
395   unsigned FS_forceinline_specified: 1;
396   LLVM_PREFERRED_TYPE(bool)
397   unsigned FS_virtual_specified : 1;
398   LLVM_PREFERRED_TYPE(bool)
399   unsigned FS_noreturn_specified : 1;
400 
401   // friend-specifier
402   LLVM_PREFERRED_TYPE(bool)
403   unsigned FriendSpecifiedFirst : 1;
404 
405   // constexpr-specifier
LLVM_PREFERRED_TYPE(ConstexprSpecKind)406   LLVM_PREFERRED_TYPE(ConstexprSpecKind)
407   unsigned ConstexprSpecifier : 2;
408 
409   union {
410     UnionParsedType TypeRep;
411     Decl *DeclRep;
412     Expr *ExprRep;
413     TemplateIdAnnotation *TemplateIdRep;
414   };
415   Expr *PackIndexingExpr = nullptr;
416 
417   /// ExplicitSpecifier - Store information about explicit spicifer.
418   ExplicitSpecifier FS_explicit_specifier;
419 
420   // attributes.
421   ParsedAttributes Attrs;
422 
423   // Scope specifier for the type spec, if applicable.
424   CXXScopeSpec TypeScope;
425 
426   // SourceLocation info.  These are null if the item wasn't specified or if
427   // the setting was synthesized.
428   SourceRange Range;
429 
430   SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
431   SourceRange TSWRange;
432   SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc, EllipsisLoc;
433   /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
434   /// typename, then this is the location of the named type (if present);
435   /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
436   /// TSTNameLoc provides source range info for tag types.
437   SourceLocation TSTNameLoc;
438   SourceRange TypeofParensRange;
439   SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
440       TQ_unalignedLoc;
441   SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
442   SourceLocation FS_explicitCloseParenLoc;
443   SourceLocation FS_forceinlineLoc;
444   SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
445   SourceLocation TQ_pipeLoc;
446 
447   WrittenBuiltinSpecs writtenBS;
448   void SaveWrittenBuiltinSpecs();
449 
450   ObjCDeclSpec *ObjCQualifiers;
451 
isTypeRep(TST T)452   static bool isTypeRep(TST T) {
453     return T == TST_atomic || T == TST_typename || T == TST_typeofType ||
454            T == TST_typeof_unqualType || isTransformTypeTrait(T) ||
455            T == TST_typename_pack_indexing;
456   }
isExprRep(TST T)457   static bool isExprRep(TST T) {
458     return T == TST_typeofExpr || T == TST_typeof_unqualExpr ||
459            T == TST_decltype || T == TST_bitint;
460   }
isTemplateIdRep(TST T)461   static bool isTemplateIdRep(TST T) {
462     return (T == TST_auto || T == TST_decltype_auto);
463   }
464 
465   DeclSpec(const DeclSpec &) = delete;
466   void operator=(const DeclSpec &) = delete;
467 public:
isDeclRep(TST T)468   static bool isDeclRep(TST T) {
469     return (T == TST_enum || T == TST_struct ||
470             T == TST_interface || T == TST_union ||
471             T == TST_class);
472   }
isTransformTypeTrait(TST T)473   static bool isTransformTypeTrait(TST T) {
474     constexpr std::array<TST, 16> Traits = {
475 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait,
476 #include "clang/Basic/TransformTypeTraits.def"
477     };
478 
479     return T >= Traits.front() && T <= Traits.back();
480   }
481 
DeclSpec(AttributeFactory & attrFactory)482   DeclSpec(AttributeFactory &attrFactory)
483       : StorageClassSpec(SCS_unspecified),
484         ThreadStorageClassSpec(TSCS_unspecified),
485         SCS_extern_in_linkage_spec(false),
486         TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)),
487         TypeSpecComplex(TSC_unspecified),
488         TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)),
489         TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
490         TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
491         TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
492         TypeQualifiers(TQ_unspecified), FS_inline_specified(false),
493         FS_forceinline_specified(false), FS_virtual_specified(false),
494         FS_noreturn_specified(false), FriendSpecifiedFirst(false),
495         ConstexprSpecifier(
496             static_cast<unsigned>(ConstexprSpecKind::Unspecified)),
497         Attrs(attrFactory), writtenBS(), ObjCQualifiers(nullptr) {}
498 
499   // storage-class-specifier
getStorageClassSpec()500   SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
getThreadStorageClassSpec()501   TSCS getThreadStorageClassSpec() const {
502     return (TSCS)ThreadStorageClassSpec;
503   }
isExternInLinkageSpec()504   bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
setExternInLinkageSpec(bool Value)505   void setExternInLinkageSpec(bool Value) {
506     SCS_extern_in_linkage_spec = Value;
507   }
508 
getStorageClassSpecLoc()509   SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
getThreadStorageClassSpecLoc()510   SourceLocation getThreadStorageClassSpecLoc() const {
511     return ThreadStorageClassSpecLoc;
512   }
513 
ClearStorageClassSpecs()514   void ClearStorageClassSpecs() {
515     StorageClassSpec           = DeclSpec::SCS_unspecified;
516     ThreadStorageClassSpec     = DeclSpec::TSCS_unspecified;
517     SCS_extern_in_linkage_spec = false;
518     StorageClassSpecLoc        = SourceLocation();
519     ThreadStorageClassSpecLoc  = SourceLocation();
520   }
521 
ClearTypeSpecType()522   void ClearTypeSpecType() {
523     TypeSpecType = DeclSpec::TST_unspecified;
524     TypeSpecOwned = false;
525     TSTLoc = SourceLocation();
526   }
527 
528   // type-specifier
getTypeSpecWidth()529   TypeSpecifierWidth getTypeSpecWidth() const {
530     return static_cast<TypeSpecifierWidth>(TypeSpecWidth);
531   }
getTypeSpecComplex()532   TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
getTypeSpecSign()533   TypeSpecifierSign getTypeSpecSign() const {
534     return static_cast<TypeSpecifierSign>(TypeSpecSign);
535   }
getTypeSpecType()536   TST getTypeSpecType() const { return (TST)TypeSpecType; }
isTypeAltiVecVector()537   bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
isTypeAltiVecPixel()538   bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
isTypeAltiVecBool()539   bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
isTypeSpecOwned()540   bool isTypeSpecOwned() const { return TypeSpecOwned; }
isTypeRep()541   bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
isTypeSpecPipe()542   bool isTypeSpecPipe() const { return TypeSpecPipe; }
isTypeSpecSat()543   bool isTypeSpecSat() const { return TypeSpecSat; }
isConstrainedAuto()544   bool isConstrainedAuto() const { return ConstrainedAuto; }
545 
getRepAsType()546   ParsedType getRepAsType() const {
547     assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
548     return TypeRep;
549   }
getRepAsDecl()550   Decl *getRepAsDecl() const {
551     assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
552     return DeclRep;
553   }
getRepAsExpr()554   Expr *getRepAsExpr() const {
555     assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
556     return ExprRep;
557   }
558 
getPackIndexingExpr()559   Expr *getPackIndexingExpr() const {
560     assert(TypeSpecType == TST_typename_pack_indexing &&
561            "DeclSpec is not a pack indexing expr");
562     return PackIndexingExpr;
563   }
564 
getRepAsTemplateId()565   TemplateIdAnnotation *getRepAsTemplateId() const {
566     assert(isTemplateIdRep((TST) TypeSpecType) &&
567            "DeclSpec does not store a template id");
568     return TemplateIdRep;
569   }
getTypeSpecScope()570   CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
getTypeSpecScope()571   const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
572 
getSourceRange()573   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
getBeginLoc()574   SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
getEndLoc()575   SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
576 
getTypeSpecWidthLoc()577   SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
getTypeSpecWidthRange()578   SourceRange getTypeSpecWidthRange() const { return TSWRange; }
getTypeSpecComplexLoc()579   SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
getTypeSpecSignLoc()580   SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
getTypeSpecTypeLoc()581   SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
getAltiVecLoc()582   SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
getTypeSpecSatLoc()583   SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
584 
getTypeSpecTypeNameLoc()585   SourceLocation getTypeSpecTypeNameLoc() const {
586     assert(isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) ||
587            isExprRep((TST)TypeSpecType));
588     return TSTNameLoc;
589   }
590 
getTypeofParensRange()591   SourceRange getTypeofParensRange() const { return TypeofParensRange; }
setTypeArgumentRange(SourceRange range)592   void setTypeArgumentRange(SourceRange range) { TypeofParensRange = range; }
593 
hasAutoTypeSpec()594   bool hasAutoTypeSpec() const {
595     return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
596             TypeSpecType == TST_decltype_auto);
597   }
598 
599   bool hasTagDefinition() const;
600 
601   /// Turn a type-specifier-type into a string like "_Bool" or "union".
602   static const char *getSpecifierName(DeclSpec::TST T,
603                                       const PrintingPolicy &Policy);
604   static const char *getSpecifierName(DeclSpec::TQ Q);
605   static const char *getSpecifierName(TypeSpecifierSign S);
606   static const char *getSpecifierName(DeclSpec::TSC C);
607   static const char *getSpecifierName(TypeSpecifierWidth W);
608   static const char *getSpecifierName(DeclSpec::SCS S);
609   static const char *getSpecifierName(DeclSpec::TSCS S);
610   static const char *getSpecifierName(ConstexprSpecKind C);
611 
612   // type-qualifiers
613 
614   /// getTypeQualifiers - Return a set of TQs.
getTypeQualifiers()615   unsigned getTypeQualifiers() const { return TypeQualifiers; }
getConstSpecLoc()616   SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
getRestrictSpecLoc()617   SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
getVolatileSpecLoc()618   SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
getAtomicSpecLoc()619   SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
getUnalignedSpecLoc()620   SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
getPipeLoc()621   SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
getEllipsisLoc()622   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
623 
624   /// Clear out all of the type qualifiers.
ClearTypeQualifiers()625   void ClearTypeQualifiers() {
626     TypeQualifiers = 0;
627     TQ_constLoc = SourceLocation();
628     TQ_restrictLoc = SourceLocation();
629     TQ_volatileLoc = SourceLocation();
630     TQ_atomicLoc = SourceLocation();
631     TQ_unalignedLoc = SourceLocation();
632     TQ_pipeLoc = SourceLocation();
633   }
634 
635   // function-specifier
isInlineSpecified()636   bool isInlineSpecified() const {
637     return FS_inline_specified | FS_forceinline_specified;
638   }
getInlineSpecLoc()639   SourceLocation getInlineSpecLoc() const {
640     return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
641   }
642 
getExplicitSpecifier()643   ExplicitSpecifier getExplicitSpecifier() const {
644     return FS_explicit_specifier;
645   }
646 
isVirtualSpecified()647   bool isVirtualSpecified() const { return FS_virtual_specified; }
getVirtualSpecLoc()648   SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
649 
hasExplicitSpecifier()650   bool hasExplicitSpecifier() const {
651     return FS_explicit_specifier.isSpecified();
652   }
getExplicitSpecLoc()653   SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
getExplicitSpecRange()654   SourceRange getExplicitSpecRange() const {
655     return FS_explicit_specifier.getExpr()
656                ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
657                : SourceRange(FS_explicitLoc);
658   }
659 
isNoreturnSpecified()660   bool isNoreturnSpecified() const { return FS_noreturn_specified; }
getNoreturnSpecLoc()661   SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
662 
ClearFunctionSpecs()663   void ClearFunctionSpecs() {
664     FS_inline_specified = false;
665     FS_inlineLoc = SourceLocation();
666     FS_forceinline_specified = false;
667     FS_forceinlineLoc = SourceLocation();
668     FS_virtual_specified = false;
669     FS_virtualLoc = SourceLocation();
670     FS_explicit_specifier = ExplicitSpecifier();
671     FS_explicitLoc = SourceLocation();
672     FS_explicitCloseParenLoc = SourceLocation();
673     FS_noreturn_specified = false;
674     FS_noreturnLoc = SourceLocation();
675   }
676 
677   /// This method calls the passed in handler on each CVRU qual being
678   /// set.
679   /// Handle - a handler to be invoked.
680   void forEachCVRUQualifier(
681       llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
682 
683   /// This method calls the passed in handler on each qual being
684   /// set.
685   /// Handle - a handler to be invoked.
686   void forEachQualifier(
687       llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
688 
689   /// Return true if any type-specifier has been found.
hasTypeSpecifier()690   bool hasTypeSpecifier() const {
691     return getTypeSpecType() != DeclSpec::TST_unspecified ||
692            getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
693            getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
694            getTypeSpecSign() != TypeSpecifierSign::Unspecified;
695   }
696 
697   /// Return a bitmask of which flavors of specifiers this
698   /// DeclSpec includes.
699   unsigned getParsedSpecifiers() const;
700 
701   /// isEmpty - Return true if this declaration specifier is completely empty:
702   /// no tokens were parsed in the production of it.
isEmpty()703   bool isEmpty() const {
704     return getParsedSpecifiers() == DeclSpec::PQ_None;
705   }
706 
SetRangeStart(SourceLocation Loc)707   void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
SetRangeEnd(SourceLocation Loc)708   void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
709 
710   /// These methods set the specified attribute of the DeclSpec and
711   /// return false if there was no error.  If an error occurs (for
712   /// example, if we tried to set "auto" on a spec with "extern"
713   /// already set), they return true and set PrevSpec and DiagID
714   /// such that
715   ///   Diag(Loc, DiagID) << PrevSpec;
716   /// will yield a useful result.
717   ///
718   /// TODO: use a more general approach that still allows these
719   /// diagnostics to be ignored when desired.
720   bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
721                            const char *&PrevSpec, unsigned &DiagID,
722                            const PrintingPolicy &Policy);
723   bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
724                                  const char *&PrevSpec, unsigned &DiagID);
725   bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
726                         const char *&PrevSpec, unsigned &DiagID,
727                         const PrintingPolicy &Policy);
728   bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
729                           unsigned &DiagID);
730   bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
731                        const char *&PrevSpec, unsigned &DiagID);
732   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
733                        unsigned &DiagID, const PrintingPolicy &Policy);
734   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
735                        unsigned &DiagID, ParsedType Rep,
736                        const PrintingPolicy &Policy);
SetTypeSpecType(TST T,SourceLocation Loc,const char * & PrevSpec,unsigned & DiagID,TypeResult Rep,const PrintingPolicy & Policy)737   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
738                        unsigned &DiagID, TypeResult Rep,
739                        const PrintingPolicy &Policy) {
740     if (Rep.isInvalid())
741       return SetTypeSpecError();
742     return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep.get(), Policy);
743   }
744   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
745                        unsigned &DiagID, Decl *Rep, bool Owned,
746                        const PrintingPolicy &Policy);
747   bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
748                        SourceLocation TagNameLoc, const char *&PrevSpec,
749                        unsigned &DiagID, ParsedType Rep,
750                        const PrintingPolicy &Policy);
751   bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
752                        SourceLocation TagNameLoc, const char *&PrevSpec,
753                        unsigned &DiagID, Decl *Rep, bool Owned,
754                        const PrintingPolicy &Policy);
755   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
756                        unsigned &DiagID, TemplateIdAnnotation *Rep,
757                        const PrintingPolicy &Policy);
758 
759   bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
760                        unsigned &DiagID, Expr *Rep,
761                        const PrintingPolicy &policy);
762   bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
763                        const char *&PrevSpec, unsigned &DiagID,
764                        const PrintingPolicy &Policy);
765   bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
766                        const char *&PrevSpec, unsigned &DiagID,
767                        const PrintingPolicy &Policy);
768   bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
769                        const char *&PrevSpec, unsigned &DiagID,
770                        const PrintingPolicy &Policy);
771   bool SetTypePipe(bool isPipe, SourceLocation Loc,
772                        const char *&PrevSpec, unsigned &DiagID,
773                        const PrintingPolicy &Policy);
774   bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth,
775                      const char *&PrevSpec, unsigned &DiagID,
776                      const PrintingPolicy &Policy);
777   bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
778                       unsigned &DiagID);
779 
780   void SetPackIndexingExpr(SourceLocation EllipsisLoc, Expr *Pack);
781 
782   bool SetTypeSpecError();
UpdateDeclRep(Decl * Rep)783   void UpdateDeclRep(Decl *Rep) {
784     assert(isDeclRep((TST) TypeSpecType));
785     DeclRep = Rep;
786   }
UpdateTypeRep(ParsedType Rep)787   void UpdateTypeRep(ParsedType Rep) {
788     assert(isTypeRep((TST) TypeSpecType));
789     TypeRep = Rep;
790   }
UpdateExprRep(Expr * Rep)791   void UpdateExprRep(Expr *Rep) {
792     assert(isExprRep((TST) TypeSpecType));
793     ExprRep = Rep;
794   }
795 
796   bool SetTypeQual(TQ T, SourceLocation Loc);
797 
798   bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
799                    unsigned &DiagID, const LangOptions &Lang);
800 
801   bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
802                              unsigned &DiagID);
803   bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
804                                   unsigned &DiagID);
805   bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
806                               unsigned &DiagID);
807   bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
808                                unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
809                                SourceLocation CloseParenLoc);
810   bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
811                                unsigned &DiagID);
812 
813   bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
814                      unsigned &DiagID);
815   bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
816                             unsigned &DiagID);
817   bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
818                         const char *&PrevSpec, unsigned &DiagID);
819 
isFriendSpecified()820   FriendSpecified isFriendSpecified() const {
821     return static_cast<FriendSpecified>(FriendLoc.isValid());
822   }
823 
isFriendSpecifiedFirst()824   bool isFriendSpecifiedFirst() const { return FriendSpecifiedFirst; }
825 
getFriendSpecLoc()826   SourceLocation getFriendSpecLoc() const { return FriendLoc; }
827 
isModulePrivateSpecified()828   bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
getModulePrivateSpecLoc()829   SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
830 
getConstexprSpecifier()831   ConstexprSpecKind getConstexprSpecifier() const {
832     return ConstexprSpecKind(ConstexprSpecifier);
833   }
834 
getConstexprSpecLoc()835   SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
hasConstexprSpecifier()836   bool hasConstexprSpecifier() const {
837     return getConstexprSpecifier() != ConstexprSpecKind::Unspecified;
838   }
839 
ClearConstexprSpec()840   void ClearConstexprSpec() {
841     ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified);
842     ConstexprLoc = SourceLocation();
843   }
844 
getAttributePool()845   AttributePool &getAttributePool() const {
846     return Attrs.getPool();
847   }
848 
849   /// Concatenates two attribute lists.
850   ///
851   /// The GCC attribute syntax allows for the following:
852   ///
853   /// \code
854   /// short __attribute__(( unused, deprecated ))
855   /// int __attribute__(( may_alias, aligned(16) )) var;
856   /// \endcode
857   ///
858   /// This declares 4 attributes using 2 lists. The following syntax is
859   /// also allowed and equivalent to the previous declaration.
860   ///
861   /// \code
862   /// short __attribute__((unused)) __attribute__((deprecated))
863   /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
864   /// \endcode
865   ///
addAttributes(const ParsedAttributesView & AL)866   void addAttributes(const ParsedAttributesView &AL) {
867     Attrs.addAll(AL.begin(), AL.end());
868   }
869 
hasAttributes()870   bool hasAttributes() const { return !Attrs.empty(); }
871 
getAttributes()872   ParsedAttributes &getAttributes() { return Attrs; }
getAttributes()873   const ParsedAttributes &getAttributes() const { return Attrs; }
874 
takeAttributesFrom(ParsedAttributes & attrs)875   void takeAttributesFrom(ParsedAttributes &attrs) {
876     Attrs.takeAllFrom(attrs);
877   }
878 
879   /// Finish - This does final analysis of the declspec, issuing diagnostics for
880   /// things like "_Complex" (lacking an FP type).  After calling this method,
881   /// DeclSpec is guaranteed self-consistent, even if an error occurred.
882   void Finish(Sema &S, const PrintingPolicy &Policy);
883 
getWrittenBuiltinSpecs()884   const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
885     return writtenBS;
886   }
887 
getObjCQualifiers()888   ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
setObjCQualifiers(ObjCDeclSpec * quals)889   void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
890 
891   /// Checks if this DeclSpec can stand alone, without a Declarator.
892   ///
893   /// Only tag declspecs can stand alone.
894   bool isMissingDeclaratorOk();
895 };
896 
897 /// Captures information about "declaration specifiers" specific to
898 /// Objective-C.
899 class ObjCDeclSpec {
900 public:
901   /// ObjCDeclQualifier - Qualifier used on types in method
902   /// declarations.  Not all combinations are sensible.  Parameters
903   /// can be one of { in, out, inout } with one of { bycopy, byref }.
904   /// Returns can either be { oneway } or not.
905   ///
906   /// This should be kept in sync with Decl::ObjCDeclQualifier.
907   enum ObjCDeclQualifier {
908     DQ_None = 0x0,
909     DQ_In = 0x1,
910     DQ_Inout = 0x2,
911     DQ_Out = 0x4,
912     DQ_Bycopy = 0x8,
913     DQ_Byref = 0x10,
914     DQ_Oneway = 0x20,
915     DQ_CSNullability = 0x40
916   };
917 
ObjCDeclSpec()918   ObjCDeclSpec()
919       : objcDeclQualifier(DQ_None),
920         PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0),
921         GetterName(nullptr), SetterName(nullptr) {}
922 
getObjCDeclQualifier()923   ObjCDeclQualifier getObjCDeclQualifier() const {
924     return (ObjCDeclQualifier)objcDeclQualifier;
925   }
setObjCDeclQualifier(ObjCDeclQualifier DQVal)926   void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
927     objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
928   }
clearObjCDeclQualifier(ObjCDeclQualifier DQVal)929   void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
930     objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
931   }
932 
getPropertyAttributes()933   ObjCPropertyAttribute::Kind getPropertyAttributes() const {
934     return ObjCPropertyAttribute::Kind(PropertyAttributes);
935   }
setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal)936   void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) {
937     PropertyAttributes =
938         (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal);
939   }
940 
getNullability()941   NullabilityKind getNullability() const {
942     assert(
943         ((getObjCDeclQualifier() & DQ_CSNullability) ||
944          (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
945         "Objective-C declspec doesn't have nullability");
946     return static_cast<NullabilityKind>(Nullability);
947   }
948 
getNullabilityLoc()949   SourceLocation getNullabilityLoc() const {
950     assert(
951         ((getObjCDeclQualifier() & DQ_CSNullability) ||
952          (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
953         "Objective-C declspec doesn't have nullability");
954     return NullabilityLoc;
955   }
956 
setNullability(SourceLocation loc,NullabilityKind kind)957   void setNullability(SourceLocation loc, NullabilityKind kind) {
958     assert(
959         ((getObjCDeclQualifier() & DQ_CSNullability) ||
960          (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&
961         "Set the nullability declspec or property attribute first");
962     Nullability = static_cast<unsigned>(kind);
963     NullabilityLoc = loc;
964   }
965 
getGetterName()966   const IdentifierInfo *getGetterName() const { return GetterName; }
getGetterName()967   IdentifierInfo *getGetterName() { return GetterName; }
getGetterNameLoc()968   SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
setGetterName(IdentifierInfo * name,SourceLocation loc)969   void setGetterName(IdentifierInfo *name, SourceLocation loc) {
970     GetterName = name;
971     GetterNameLoc = loc;
972   }
973 
getSetterName()974   const IdentifierInfo *getSetterName() const { return SetterName; }
getSetterName()975   IdentifierInfo *getSetterName() { return SetterName; }
getSetterNameLoc()976   SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
setSetterName(IdentifierInfo * name,SourceLocation loc)977   void setSetterName(IdentifierInfo *name, SourceLocation loc) {
978     SetterName = name;
979     SetterNameLoc = loc;
980   }
981 
982 private:
983   // FIXME: These two are unrelated and mutually exclusive. So perhaps
984   // we can put them in a union to reflect their mutual exclusivity
985   // (space saving is negligible).
986   unsigned objcDeclQualifier : 7;
987 
988   // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind
989   unsigned PropertyAttributes : NumObjCPropertyAttrsBits;
990 
991   unsigned Nullability : 2;
992 
993   SourceLocation NullabilityLoc;
994 
995   IdentifierInfo *GetterName;    // getter name or NULL if no getter
996   IdentifierInfo *SetterName;    // setter name or NULL if no setter
997   SourceLocation GetterNameLoc; // location of the getter attribute's value
998   SourceLocation SetterNameLoc; // location of the setter attribute's value
999 
1000 };
1001 
1002 /// Describes the kind of unqualified-id parsed.
1003 enum class UnqualifiedIdKind {
1004   /// An identifier.
1005   IK_Identifier,
1006   /// An overloaded operator name, e.g., operator+.
1007   IK_OperatorFunctionId,
1008   /// A conversion function name, e.g., operator int.
1009   IK_ConversionFunctionId,
1010   /// A user-defined literal name, e.g., operator "" _i.
1011   IK_LiteralOperatorId,
1012   /// A constructor name.
1013   IK_ConstructorName,
1014   /// A constructor named via a template-id.
1015   IK_ConstructorTemplateId,
1016   /// A destructor name.
1017   IK_DestructorName,
1018   /// A template-id, e.g., f<int>.
1019   IK_TemplateId,
1020   /// An implicit 'self' parameter
1021   IK_ImplicitSelfParam,
1022   /// A deduction-guide name (a template-name)
1023   IK_DeductionGuideName
1024 };
1025 
1026 /// Represents a C++ unqualified-id that has been parsed.
1027 class UnqualifiedId {
1028 private:
1029   UnqualifiedId(const UnqualifiedId &Other) = delete;
1030   const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
1031 
1032   /// Describes the kind of unqualified-id parsed.
1033   UnqualifiedIdKind Kind;
1034 
1035 public:
1036   struct OFI {
1037     /// The kind of overloaded operator.
1038     OverloadedOperatorKind Operator;
1039 
1040     /// The source locations of the individual tokens that name
1041     /// the operator, e.g., the "new", "[", and "]" tokens in
1042     /// operator new [].
1043     ///
1044     /// Different operators have different numbers of tokens in their name,
1045     /// up to three. Any remaining source locations in this array will be
1046     /// set to an invalid value for operators with fewer than three tokens.
1047     SourceLocation SymbolLocations[3];
1048   };
1049 
1050   /// Anonymous union that holds extra data associated with the
1051   /// parsed unqualified-id.
1052   union {
1053     /// When Kind == IK_Identifier, the parsed identifier, or when
1054     /// Kind == IK_UserLiteralId, the identifier suffix.
1055     const IdentifierInfo *Identifier;
1056 
1057     /// When Kind == IK_OperatorFunctionId, the overloaded operator
1058     /// that we parsed.
1059     struct OFI OperatorFunctionId;
1060 
1061     /// When Kind == IK_ConversionFunctionId, the type that the
1062     /// conversion function names.
1063     UnionParsedType ConversionFunctionId;
1064 
1065     /// When Kind == IK_ConstructorName, the class-name of the type
1066     /// whose constructor is being referenced.
1067     UnionParsedType ConstructorName;
1068 
1069     /// When Kind == IK_DestructorName, the type referred to by the
1070     /// class-name.
1071     UnionParsedType DestructorName;
1072 
1073     /// When Kind == IK_DeductionGuideName, the parsed template-name.
1074     UnionParsedTemplateTy TemplateName;
1075 
1076     /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
1077     /// the template-id annotation that contains the template name and
1078     /// template arguments.
1079     TemplateIdAnnotation *TemplateId;
1080   };
1081 
1082   /// The location of the first token that describes this unqualified-id,
1083   /// which will be the location of the identifier, "operator" keyword,
1084   /// tilde (for a destructor), or the template name of a template-id.
1085   SourceLocation StartLocation;
1086 
1087   /// The location of the last token that describes this unqualified-id.
1088   SourceLocation EndLocation;
1089 
UnqualifiedId()1090   UnqualifiedId()
1091       : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1092 
1093   /// Clear out this unqualified-id, setting it to default (invalid)
1094   /// state.
clear()1095   void clear() {
1096     Kind = UnqualifiedIdKind::IK_Identifier;
1097     Identifier = nullptr;
1098     StartLocation = SourceLocation();
1099     EndLocation = SourceLocation();
1100   }
1101 
1102   /// Determine whether this unqualified-id refers to a valid name.
isValid()1103   bool isValid() const { return StartLocation.isValid(); }
1104 
1105   /// Determine whether this unqualified-id refers to an invalid name.
isInvalid()1106   bool isInvalid() const { return !isValid(); }
1107 
1108   /// Determine what kind of name we have.
getKind()1109   UnqualifiedIdKind getKind() const { return Kind; }
1110 
1111   /// Specify that this unqualified-id was parsed as an identifier.
1112   ///
1113   /// \param Id the parsed identifier.
1114   /// \param IdLoc the location of the parsed identifier.
setIdentifier(const IdentifierInfo * Id,SourceLocation IdLoc)1115   void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1116     Kind = UnqualifiedIdKind::IK_Identifier;
1117     Identifier = Id;
1118     StartLocation = EndLocation = IdLoc;
1119   }
1120 
1121   /// Specify that this unqualified-id was parsed as an
1122   /// operator-function-id.
1123   ///
1124   /// \param OperatorLoc the location of the 'operator' keyword.
1125   ///
1126   /// \param Op the overloaded operator.
1127   ///
1128   /// \param SymbolLocations the locations of the individual operator symbols
1129   /// in the operator.
1130   void setOperatorFunctionId(SourceLocation OperatorLoc,
1131                              OverloadedOperatorKind Op,
1132                              SourceLocation SymbolLocations[3]);
1133 
1134   /// Specify that this unqualified-id was parsed as a
1135   /// conversion-function-id.
1136   ///
1137   /// \param OperatorLoc the location of the 'operator' keyword.
1138   ///
1139   /// \param Ty the type to which this conversion function is converting.
1140   ///
1141   /// \param EndLoc the location of the last token that makes up the type name.
setConversionFunctionId(SourceLocation OperatorLoc,ParsedType Ty,SourceLocation EndLoc)1142   void setConversionFunctionId(SourceLocation OperatorLoc,
1143                                ParsedType Ty,
1144                                SourceLocation EndLoc) {
1145     Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1146     StartLocation = OperatorLoc;
1147     EndLocation = EndLoc;
1148     ConversionFunctionId = Ty;
1149   }
1150 
1151   /// Specific that this unqualified-id was parsed as a
1152   /// literal-operator-id.
1153   ///
1154   /// \param Id the parsed identifier.
1155   ///
1156   /// \param OpLoc the location of the 'operator' keyword.
1157   ///
1158   /// \param IdLoc the location of the identifier.
setLiteralOperatorId(const IdentifierInfo * Id,SourceLocation OpLoc,SourceLocation IdLoc)1159   void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1160                             SourceLocation IdLoc) {
1161     Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1162     Identifier = Id;
1163     StartLocation = OpLoc;
1164     EndLocation = IdLoc;
1165   }
1166 
1167   /// Specify that this unqualified-id was parsed as a constructor name.
1168   ///
1169   /// \param ClassType the class type referred to by the constructor name.
1170   ///
1171   /// \param ClassNameLoc the location of the class name.
1172   ///
1173   /// \param EndLoc the location of the last token that makes up the type name.
setConstructorName(ParsedType ClassType,SourceLocation ClassNameLoc,SourceLocation EndLoc)1174   void setConstructorName(ParsedType ClassType,
1175                           SourceLocation ClassNameLoc,
1176                           SourceLocation EndLoc) {
1177     Kind = UnqualifiedIdKind::IK_ConstructorName;
1178     StartLocation = ClassNameLoc;
1179     EndLocation = EndLoc;
1180     ConstructorName = ClassType;
1181   }
1182 
1183   /// Specify that this unqualified-id was parsed as a
1184   /// template-id that names a constructor.
1185   ///
1186   /// \param TemplateId the template-id annotation that describes the parsed
1187   /// template-id. This UnqualifiedId instance will take ownership of the
1188   /// \p TemplateId and will free it on destruction.
1189   void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1190 
1191   /// Specify that this unqualified-id was parsed as a destructor name.
1192   ///
1193   /// \param TildeLoc the location of the '~' that introduces the destructor
1194   /// name.
1195   ///
1196   /// \param ClassType the name of the class referred to by the destructor name.
setDestructorName(SourceLocation TildeLoc,ParsedType ClassType,SourceLocation EndLoc)1197   void setDestructorName(SourceLocation TildeLoc,
1198                          ParsedType ClassType,
1199                          SourceLocation EndLoc) {
1200     Kind = UnqualifiedIdKind::IK_DestructorName;
1201     StartLocation = TildeLoc;
1202     EndLocation = EndLoc;
1203     DestructorName = ClassType;
1204   }
1205 
1206   /// Specify that this unqualified-id was parsed as a template-id.
1207   ///
1208   /// \param TemplateId the template-id annotation that describes the parsed
1209   /// template-id. This UnqualifiedId instance will take ownership of the
1210   /// \p TemplateId and will free it on destruction.
1211   void setTemplateId(TemplateIdAnnotation *TemplateId);
1212 
1213   /// Specify that this unqualified-id was parsed as a template-name for
1214   /// a deduction-guide.
1215   ///
1216   /// \param Template The parsed template-name.
1217   /// \param TemplateLoc The location of the parsed template-name.
setDeductionGuideName(ParsedTemplateTy Template,SourceLocation TemplateLoc)1218   void setDeductionGuideName(ParsedTemplateTy Template,
1219                              SourceLocation TemplateLoc) {
1220     Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1221     TemplateName = Template;
1222     StartLocation = EndLocation = TemplateLoc;
1223   }
1224 
1225   /// Specify that this unqualified-id is an implicit 'self'
1226   /// parameter.
1227   ///
1228   /// \param Id the identifier.
setImplicitSelfParam(const IdentifierInfo * Id)1229   void setImplicitSelfParam(const IdentifierInfo *Id) {
1230     Kind = UnqualifiedIdKind::IK_ImplicitSelfParam;
1231     Identifier = Id;
1232     StartLocation = EndLocation = SourceLocation();
1233   }
1234 
1235   /// Return the source range that covers this unqualified-id.
getSourceRange()1236   SourceRange getSourceRange() const LLVM_READONLY {
1237     return SourceRange(StartLocation, EndLocation);
1238   }
getBeginLoc()1239   SourceLocation getBeginLoc() const LLVM_READONLY { return StartLocation; }
getEndLoc()1240   SourceLocation getEndLoc() const LLVM_READONLY { return EndLocation; }
1241 };
1242 
1243 /// A set of tokens that has been cached for later parsing.
1244 typedef SmallVector<Token, 4> CachedTokens;
1245 
1246 /// One instance of this struct is used for each type in a
1247 /// declarator that is parsed.
1248 ///
1249 /// This is intended to be a small value object.
1250 struct DeclaratorChunk {
DeclaratorChunkDeclaratorChunk1251   DeclaratorChunk() {};
1252 
1253   enum {
1254     Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1255   } Kind;
1256 
1257   /// Loc - The place where this type was defined.
1258   SourceLocation Loc;
1259   /// EndLoc - If valid, the place where this chunck ends.
1260   SourceLocation EndLoc;
1261 
getSourceRangeDeclaratorChunk1262   SourceRange getSourceRange() const {
1263     if (EndLoc.isInvalid())
1264       return SourceRange(Loc, Loc);
1265     return SourceRange(Loc, EndLoc);
1266   }
1267 
1268   ParsedAttributesView AttrList;
1269 
1270   struct PointerTypeInfo {
1271     /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1272     LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1273     unsigned TypeQuals : 5;
1274 
1275     /// The location of the const-qualifier, if any.
1276     SourceLocation ConstQualLoc;
1277 
1278     /// The location of the volatile-qualifier, if any.
1279     SourceLocation VolatileQualLoc;
1280 
1281     /// The location of the restrict-qualifier, if any.
1282     SourceLocation RestrictQualLoc;
1283 
1284     /// The location of the _Atomic-qualifier, if any.
1285     SourceLocation AtomicQualLoc;
1286 
1287     /// The location of the __unaligned-qualifier, if any.
1288     SourceLocation UnalignedQualLoc;
1289 
destroyDeclaratorChunk::PointerTypeInfo1290     void destroy() {
1291     }
1292   };
1293 
1294   struct ReferenceTypeInfo {
1295     /// The type qualifier: restrict. [GNU] C++ extension
1296     bool HasRestrict : 1;
1297     /// True if this is an lvalue reference, false if it's an rvalue reference.
1298     bool LValueRef : 1;
destroyDeclaratorChunk::ReferenceTypeInfo1299     void destroy() {
1300     }
1301   };
1302 
1303   struct ArrayTypeInfo {
1304     /// The type qualifiers for the array:
1305     /// const/volatile/restrict/__unaligned/_Atomic.
1306     LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1307     unsigned TypeQuals : 5;
1308 
1309     /// True if this dimension included the 'static' keyword.
1310     LLVM_PREFERRED_TYPE(bool)
1311     unsigned hasStatic : 1;
1312 
1313     /// True if this dimension was [*].  In this case, NumElts is null.
1314     LLVM_PREFERRED_TYPE(bool)
1315     unsigned isStar : 1;
1316 
1317     /// This is the size of the array, or null if [] or [*] was specified.
1318     /// Since the parser is multi-purpose, and we don't want to impose a root
1319     /// expression class on all clients, NumElts is untyped.
1320     Expr *NumElts;
1321 
destroyDeclaratorChunk::ArrayTypeInfo1322     void destroy() {}
1323   };
1324 
1325   /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1326   /// declarator is parsed.  There are two interesting styles of parameters
1327   /// here:
1328   /// K&R-style identifier lists and parameter type lists.  K&R-style identifier
1329   /// lists will have information about the identifier, but no type information.
1330   /// Parameter type lists will have type info (if the actions module provides
1331   /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1332   struct ParamInfo {
1333     const IdentifierInfo *Ident;
1334     SourceLocation IdentLoc;
1335     Decl *Param;
1336 
1337     /// DefaultArgTokens - When the parameter's default argument
1338     /// cannot be parsed immediately (because it occurs within the
1339     /// declaration of a member function), it will be stored here as a
1340     /// sequence of tokens to be parsed once the class definition is
1341     /// complete. Non-NULL indicates that there is a default argument.
1342     std::unique_ptr<CachedTokens> DefaultArgTokens;
1343 
1344     ParamInfo() = default;
1345     ParamInfo(const IdentifierInfo *ident, SourceLocation iloc, Decl *param,
1346               std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
IdentDeclaratorChunk::ParamInfo1347         : Ident(ident), IdentLoc(iloc), Param(param),
1348           DefaultArgTokens(std::move(DefArgTokens)) {}
1349   };
1350 
1351   struct TypeAndRange {
1352     ParsedType Ty;
1353     SourceRange Range;
1354   };
1355 
1356   struct FunctionTypeInfo {
1357     /// hasPrototype - This is true if the function had at least one typed
1358     /// parameter.  If the function is () or (a,b,c), then it has no prototype,
1359     /// and is treated as a K&R-style function.
1360     LLVM_PREFERRED_TYPE(bool)
1361     unsigned hasPrototype : 1;
1362 
1363     /// isVariadic - If this function has a prototype, and if that
1364     /// proto ends with ',...)', this is true. When true, EllipsisLoc
1365     /// contains the location of the ellipsis.
1366     LLVM_PREFERRED_TYPE(bool)
1367     unsigned isVariadic : 1;
1368 
1369     /// Can this declaration be a constructor-style initializer?
1370     LLVM_PREFERRED_TYPE(bool)
1371     unsigned isAmbiguous : 1;
1372 
1373     /// Whether the ref-qualifier (if any) is an lvalue reference.
1374     /// Otherwise, it's an rvalue reference.
1375     LLVM_PREFERRED_TYPE(bool)
1376     unsigned RefQualifierIsLValueRef : 1;
1377 
1378     /// ExceptionSpecType - An ExceptionSpecificationType value.
1379     LLVM_PREFERRED_TYPE(ExceptionSpecificationType)
1380     unsigned ExceptionSpecType : 4;
1381 
1382     /// DeleteParams - If this is true, we need to delete[] Params.
1383     LLVM_PREFERRED_TYPE(bool)
1384     unsigned DeleteParams : 1;
1385 
1386     /// HasTrailingReturnType - If this is true, a trailing return type was
1387     /// specified.
1388     LLVM_PREFERRED_TYPE(bool)
1389     unsigned HasTrailingReturnType : 1;
1390 
1391     /// The location of the left parenthesis in the source.
1392     SourceLocation LParenLoc;
1393 
1394     /// When isVariadic is true, the location of the ellipsis in the source.
1395     SourceLocation EllipsisLoc;
1396 
1397     /// The location of the right parenthesis in the source.
1398     SourceLocation RParenLoc;
1399 
1400     /// NumParams - This is the number of formal parameters specified by the
1401     /// declarator.
1402     unsigned NumParams;
1403 
1404     /// NumExceptionsOrDecls - This is the number of types in the
1405     /// dynamic-exception-decl, if the function has one. In C, this is the
1406     /// number of declarations in the function prototype.
1407     unsigned NumExceptionsOrDecls;
1408 
1409     /// The location of the ref-qualifier, if any.
1410     ///
1411     /// If this is an invalid location, there is no ref-qualifier.
1412     SourceLocation RefQualifierLoc;
1413 
1414     /// The location of the 'mutable' qualifer in a lambda-declarator, if
1415     /// any.
1416     SourceLocation MutableLoc;
1417 
1418     /// The beginning location of the exception specification, if any.
1419     SourceLocation ExceptionSpecLocBeg;
1420 
1421     /// The end location of the exception specification, if any.
1422     SourceLocation ExceptionSpecLocEnd;
1423 
1424     /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1425     /// describe the parameters specified by this function declarator.  null if
1426     /// there are no parameters specified.
1427     ParamInfo *Params;
1428 
1429     /// DeclSpec for the function with the qualifier related info.
1430     DeclSpec *MethodQualifiers;
1431 
1432     /// AttributeFactory for the MethodQualifiers.
1433     AttributeFactory *QualAttrFactory;
1434 
1435     union {
1436       /// Pointer to a new[]'d array of TypeAndRange objects that
1437       /// contain the types in the function's dynamic exception specification
1438       /// and their locations, if there is one.
1439       TypeAndRange *Exceptions;
1440 
1441       /// Pointer to the expression in the noexcept-specifier of this
1442       /// function, if it has one.
1443       Expr *NoexceptExpr;
1444 
1445       /// Pointer to the cached tokens for an exception-specification
1446       /// that has not yet been parsed.
1447       CachedTokens *ExceptionSpecTokens;
1448 
1449       /// Pointer to a new[]'d array of declarations that need to be available
1450       /// for lookup inside the function body, if one exists. Does not exist in
1451       /// C++.
1452       NamedDecl **DeclsInPrototype;
1453     };
1454 
1455     /// If HasTrailingReturnType is true, this is the trailing return
1456     /// type specified.
1457     UnionParsedType TrailingReturnType;
1458 
1459     /// If HasTrailingReturnType is true, this is the location of the trailing
1460     /// return type.
1461     SourceLocation TrailingReturnTypeLoc;
1462 
1463     /// Reset the parameter list to having zero parameters.
1464     ///
1465     /// This is used in various places for error recovery.
freeParamsDeclaratorChunk::FunctionTypeInfo1466     void freeParams() {
1467       for (unsigned I = 0; I < NumParams; ++I)
1468         Params[I].DefaultArgTokens.reset();
1469       if (DeleteParams) {
1470         delete[] Params;
1471         DeleteParams = false;
1472       }
1473       NumParams = 0;
1474     }
1475 
destroyDeclaratorChunk::FunctionTypeInfo1476     void destroy() {
1477       freeParams();
1478       delete QualAttrFactory;
1479       delete MethodQualifiers;
1480       switch (getExceptionSpecType()) {
1481       default:
1482         break;
1483       case EST_Dynamic:
1484         delete[] Exceptions;
1485         break;
1486       case EST_Unparsed:
1487         delete ExceptionSpecTokens;
1488         break;
1489       case EST_None:
1490         if (NumExceptionsOrDecls != 0)
1491           delete[] DeclsInPrototype;
1492         break;
1493       }
1494     }
1495 
getOrCreateMethodQualifiersDeclaratorChunk::FunctionTypeInfo1496     DeclSpec &getOrCreateMethodQualifiers() {
1497       if (!MethodQualifiers) {
1498         QualAttrFactory = new AttributeFactory();
1499         MethodQualifiers = new DeclSpec(*QualAttrFactory);
1500       }
1501       return *MethodQualifiers;
1502     }
1503 
1504     /// isKNRPrototype - Return true if this is a K&R style identifier list,
1505     /// like "void foo(a,b,c)".  In a function definition, this will be followed
1506     /// by the parameter type definitions.
isKNRPrototypeDeclaratorChunk::FunctionTypeInfo1507     bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1508 
getLParenLocDeclaratorChunk::FunctionTypeInfo1509     SourceLocation getLParenLoc() const { return LParenLoc; }
1510 
getEllipsisLocDeclaratorChunk::FunctionTypeInfo1511     SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1512 
getRParenLocDeclaratorChunk::FunctionTypeInfo1513     SourceLocation getRParenLoc() const { return RParenLoc; }
1514 
getExceptionSpecLocBegDeclaratorChunk::FunctionTypeInfo1515     SourceLocation getExceptionSpecLocBeg() const {
1516       return ExceptionSpecLocBeg;
1517     }
1518 
getExceptionSpecLocEndDeclaratorChunk::FunctionTypeInfo1519     SourceLocation getExceptionSpecLocEnd() const {
1520       return ExceptionSpecLocEnd;
1521     }
1522 
getExceptionSpecRangeDeclaratorChunk::FunctionTypeInfo1523     SourceRange getExceptionSpecRange() const {
1524       return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1525     }
1526 
1527     /// Retrieve the location of the ref-qualifier, if any.
getRefQualifierLocDeclaratorChunk::FunctionTypeInfo1528     SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; }
1529 
1530     /// Retrieve the location of the 'const' qualifier.
getConstQualifierLocDeclaratorChunk::FunctionTypeInfo1531     SourceLocation getConstQualifierLoc() const {
1532       assert(MethodQualifiers);
1533       return MethodQualifiers->getConstSpecLoc();
1534     }
1535 
1536     /// Retrieve the location of the 'volatile' qualifier.
getVolatileQualifierLocDeclaratorChunk::FunctionTypeInfo1537     SourceLocation getVolatileQualifierLoc() const {
1538       assert(MethodQualifiers);
1539       return MethodQualifiers->getVolatileSpecLoc();
1540     }
1541 
1542     /// Retrieve the location of the 'restrict' qualifier.
getRestrictQualifierLocDeclaratorChunk::FunctionTypeInfo1543     SourceLocation getRestrictQualifierLoc() const {
1544       assert(MethodQualifiers);
1545       return MethodQualifiers->getRestrictSpecLoc();
1546     }
1547 
1548     /// Retrieve the location of the 'mutable' qualifier, if any.
getMutableLocDeclaratorChunk::FunctionTypeInfo1549     SourceLocation getMutableLoc() const { return MutableLoc; }
1550 
1551     /// Determine whether this function declaration contains a
1552     /// ref-qualifier.
hasRefQualifierDeclaratorChunk::FunctionTypeInfo1553     bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1554 
1555     /// Determine whether this lambda-declarator contains a 'mutable'
1556     /// qualifier.
hasMutableQualifierDeclaratorChunk::FunctionTypeInfo1557     bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1558 
1559     /// Determine whether this method has qualifiers.
hasMethodTypeQualifiersDeclaratorChunk::FunctionTypeInfo1560     bool hasMethodTypeQualifiers() const {
1561       return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1562                                   MethodQualifiers->getAttributes().size());
1563     }
1564 
1565     /// Get the type of exception specification this function has.
getExceptionSpecTypeDeclaratorChunk::FunctionTypeInfo1566     ExceptionSpecificationType getExceptionSpecType() const {
1567       return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1568     }
1569 
1570     /// Get the number of dynamic exception specifications.
getNumExceptionsDeclaratorChunk::FunctionTypeInfo1571     unsigned getNumExceptions() const {
1572       assert(ExceptionSpecType != EST_None);
1573       return NumExceptionsOrDecls;
1574     }
1575 
1576     /// Get the non-parameter decls defined within this function
1577     /// prototype. Typically these are tag declarations.
getDeclsInPrototypeDeclaratorChunk::FunctionTypeInfo1578     ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1579       assert(ExceptionSpecType == EST_None);
1580       return llvm::ArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1581     }
1582 
1583     /// Determine whether this function declarator had a
1584     /// trailing-return-type.
hasTrailingReturnTypeDeclaratorChunk::FunctionTypeInfo1585     bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1586 
1587     /// Get the trailing-return-type for this function declarator.
getTrailingReturnTypeDeclaratorChunk::FunctionTypeInfo1588     ParsedType getTrailingReturnType() const {
1589       assert(HasTrailingReturnType);
1590       return TrailingReturnType;
1591     }
1592 
1593     /// Get the trailing-return-type location for this function declarator.
getTrailingReturnTypeLocDeclaratorChunk::FunctionTypeInfo1594     SourceLocation getTrailingReturnTypeLoc() const {
1595       assert(HasTrailingReturnType);
1596       return TrailingReturnTypeLoc;
1597     }
1598   };
1599 
1600   struct BlockPointerTypeInfo {
1601     /// For now, sema will catch these as invalid.
1602     /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1603     LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1604     unsigned TypeQuals : 5;
1605 
destroyDeclaratorChunk::BlockPointerTypeInfo1606     void destroy() {
1607     }
1608   };
1609 
1610   struct MemberPointerTypeInfo {
1611     /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1612     LLVM_PREFERRED_TYPE(DeclSpec::TQ)
1613     unsigned TypeQuals : 5;
1614     /// Location of the '*' token.
1615     SourceLocation StarLoc;
1616     // CXXScopeSpec has a constructor, so it can't be a direct member.
1617     // So we need some pointer-aligned storage and a bit of trickery.
1618     alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
ScopeDeclaratorChunk::MemberPointerTypeInfo1619     CXXScopeSpec &Scope() {
1620       return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1621     }
ScopeDeclaratorChunk::MemberPointerTypeInfo1622     const CXXScopeSpec &Scope() const {
1623       return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1624     }
destroyDeclaratorChunk::MemberPointerTypeInfo1625     void destroy() {
1626       Scope().~CXXScopeSpec();
1627     }
1628   };
1629 
1630   struct PipeTypeInfo {
1631     /// The access writes.
1632     unsigned AccessWrites : 3;
1633 
destroyDeclaratorChunk::PipeTypeInfo1634     void destroy() {}
1635   };
1636 
1637   union {
1638     PointerTypeInfo       Ptr;
1639     ReferenceTypeInfo     Ref;
1640     ArrayTypeInfo         Arr;
1641     FunctionTypeInfo      Fun;
1642     BlockPointerTypeInfo  Cls;
1643     MemberPointerTypeInfo Mem;
1644     PipeTypeInfo          PipeInfo;
1645   };
1646 
destroyDeclaratorChunk1647   void destroy() {
1648     switch (Kind) {
1649     case DeclaratorChunk::Function:      return Fun.destroy();
1650     case DeclaratorChunk::Pointer:       return Ptr.destroy();
1651     case DeclaratorChunk::BlockPointer:  return Cls.destroy();
1652     case DeclaratorChunk::Reference:     return Ref.destroy();
1653     case DeclaratorChunk::Array:         return Arr.destroy();
1654     case DeclaratorChunk::MemberPointer: return Mem.destroy();
1655     case DeclaratorChunk::Paren:         return;
1656     case DeclaratorChunk::Pipe:          return PipeInfo.destroy();
1657     }
1658   }
1659 
1660   /// If there are attributes applied to this declaratorchunk, return
1661   /// them.
getAttrsDeclaratorChunk1662   const ParsedAttributesView &getAttrs() const { return AttrList; }
getAttrsDeclaratorChunk1663   ParsedAttributesView &getAttrs() { return AttrList; }
1664 
1665   /// Return a DeclaratorChunk for a pointer.
getPointerDeclaratorChunk1666   static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1667                                     SourceLocation ConstQualLoc,
1668                                     SourceLocation VolatileQualLoc,
1669                                     SourceLocation RestrictQualLoc,
1670                                     SourceLocation AtomicQualLoc,
1671                                     SourceLocation UnalignedQualLoc) {
1672     DeclaratorChunk I;
1673     I.Kind                = Pointer;
1674     I.Loc                 = Loc;
1675     new (&I.Ptr) PointerTypeInfo;
1676     I.Ptr.TypeQuals       = TypeQuals;
1677     I.Ptr.ConstQualLoc    = ConstQualLoc;
1678     I.Ptr.VolatileQualLoc = VolatileQualLoc;
1679     I.Ptr.RestrictQualLoc = RestrictQualLoc;
1680     I.Ptr.AtomicQualLoc   = AtomicQualLoc;
1681     I.Ptr.UnalignedQualLoc = UnalignedQualLoc;
1682     return I;
1683   }
1684 
1685   /// Return a DeclaratorChunk for a reference.
getReferenceDeclaratorChunk1686   static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1687                                       bool lvalue) {
1688     DeclaratorChunk I;
1689     I.Kind            = Reference;
1690     I.Loc             = Loc;
1691     I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1692     I.Ref.LValueRef   = lvalue;
1693     return I;
1694   }
1695 
1696   /// Return a DeclaratorChunk for an array.
getArrayDeclaratorChunk1697   static DeclaratorChunk getArray(unsigned TypeQuals,
1698                                   bool isStatic, bool isStar, Expr *NumElts,
1699                                   SourceLocation LBLoc, SourceLocation RBLoc) {
1700     DeclaratorChunk I;
1701     I.Kind          = Array;
1702     I.Loc           = LBLoc;
1703     I.EndLoc        = RBLoc;
1704     I.Arr.TypeQuals = TypeQuals;
1705     I.Arr.hasStatic = isStatic;
1706     I.Arr.isStar    = isStar;
1707     I.Arr.NumElts   = NumElts;
1708     return I;
1709   }
1710 
1711   /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1712   /// "TheDeclarator" is the declarator that this will be added to.
1713   static DeclaratorChunk getFunction(bool HasProto,
1714                                      bool IsAmbiguous,
1715                                      SourceLocation LParenLoc,
1716                                      ParamInfo *Params, unsigned NumParams,
1717                                      SourceLocation EllipsisLoc,
1718                                      SourceLocation RParenLoc,
1719                                      bool RefQualifierIsLvalueRef,
1720                                      SourceLocation RefQualifierLoc,
1721                                      SourceLocation MutableLoc,
1722                                      ExceptionSpecificationType ESpecType,
1723                                      SourceRange ESpecRange,
1724                                      ParsedType *Exceptions,
1725                                      SourceRange *ExceptionRanges,
1726                                      unsigned NumExceptions,
1727                                      Expr *NoexceptExpr,
1728                                      CachedTokens *ExceptionSpecTokens,
1729                                      ArrayRef<NamedDecl *> DeclsInPrototype,
1730                                      SourceLocation LocalRangeBegin,
1731                                      SourceLocation LocalRangeEnd,
1732                                      Declarator &TheDeclarator,
1733                                      TypeResult TrailingReturnType =
1734                                                     TypeResult(),
1735                                      SourceLocation TrailingReturnTypeLoc =
1736                                                     SourceLocation(),
1737                                      DeclSpec *MethodQualifiers = nullptr);
1738 
1739   /// Return a DeclaratorChunk for a block.
getBlockPointerDeclaratorChunk1740   static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1741                                          SourceLocation Loc) {
1742     DeclaratorChunk I;
1743     I.Kind          = BlockPointer;
1744     I.Loc           = Loc;
1745     I.Cls.TypeQuals = TypeQuals;
1746     return I;
1747   }
1748 
1749   /// Return a DeclaratorChunk for a block.
getPipeDeclaratorChunk1750   static DeclaratorChunk getPipe(unsigned TypeQuals,
1751                                  SourceLocation Loc) {
1752     DeclaratorChunk I;
1753     I.Kind          = Pipe;
1754     I.Loc           = Loc;
1755     I.Cls.TypeQuals = TypeQuals;
1756     return I;
1757   }
1758 
getMemberPointerDeclaratorChunk1759   static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1760                                           unsigned TypeQuals,
1761                                           SourceLocation StarLoc,
1762                                           SourceLocation EndLoc) {
1763     DeclaratorChunk I;
1764     I.Kind          = MemberPointer;
1765     I.Loc           = SS.getBeginLoc();
1766     I.EndLoc = EndLoc;
1767     new (&I.Mem) MemberPointerTypeInfo;
1768     I.Mem.StarLoc = StarLoc;
1769     I.Mem.TypeQuals = TypeQuals;
1770     new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1771     return I;
1772   }
1773 
1774   /// Return a DeclaratorChunk for a paren.
getParenDeclaratorChunk1775   static DeclaratorChunk getParen(SourceLocation LParenLoc,
1776                                   SourceLocation RParenLoc) {
1777     DeclaratorChunk I;
1778     I.Kind          = Paren;
1779     I.Loc           = LParenLoc;
1780     I.EndLoc        = RParenLoc;
1781     return I;
1782   }
1783 
isParenDeclaratorChunk1784   bool isParen() const {
1785     return Kind == Paren;
1786   }
1787 };
1788 
1789 /// A parsed C++17 decomposition declarator of the form
1790 ///   '[' identifier-list ']'
1791 class DecompositionDeclarator {
1792 public:
1793   struct Binding {
1794     IdentifierInfo *Name;
1795     SourceLocation NameLoc;
1796     std::optional<ParsedAttributes> Attrs;
1797     SourceLocation EllipsisLoc;
1798   };
1799 
1800 private:
1801   /// The locations of the '[' and ']' tokens.
1802   SourceLocation LSquareLoc, RSquareLoc;
1803 
1804   /// The bindings.
1805   Binding *Bindings;
1806   unsigned NumBindings : 31;
1807   LLVM_PREFERRED_TYPE(bool)
1808   unsigned DeleteBindings : 1;
1809 
1810   friend class Declarator;
1811 
1812 public:
DecompositionDeclarator()1813   DecompositionDeclarator()
1814       : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1815   DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1816   DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
~DecompositionDeclarator()1817   ~DecompositionDeclarator() { clear(); }
1818 
clear()1819   void clear() {
1820     LSquareLoc = RSquareLoc = SourceLocation();
1821     if (DeleteBindings)
1822       delete[] Bindings;
1823     else
1824       for (Binding &B : llvm::MutableArrayRef(Bindings, NumBindings))
1825         B.Attrs.reset();
1826     Bindings = nullptr;
1827     NumBindings = 0;
1828     DeleteBindings = false;
1829   }
1830 
bindings()1831   ArrayRef<Binding> bindings() const {
1832     return llvm::ArrayRef(Bindings, NumBindings);
1833   }
1834 
isSet()1835   bool isSet() const { return LSquareLoc.isValid(); }
1836 
getLSquareLoc()1837   SourceLocation getLSquareLoc() const { return LSquareLoc; }
getRSquareLoc()1838   SourceLocation getRSquareLoc() const { return RSquareLoc; }
getSourceRange()1839   SourceRange getSourceRange() const {
1840     return SourceRange(LSquareLoc, RSquareLoc);
1841   }
1842 };
1843 
1844 /// Described the kind of function definition (if any) provided for
1845 /// a function.
1846 enum class FunctionDefinitionKind {
1847   Declaration,
1848   Definition,
1849   Defaulted,
1850   Deleted
1851 };
1852 
1853 enum class DeclaratorContext {
1854   File,                // File scope declaration.
1855   Prototype,           // Within a function prototype.
1856   ObjCResult,          // An ObjC method result type.
1857   ObjCParameter,       // An ObjC method parameter type.
1858   KNRTypeList,         // K&R type definition list for formals.
1859   TypeName,            // Abstract declarator for types.
1860   FunctionalCast,      // Type in a C++ functional cast expression.
1861   Member,              // Struct/Union field.
1862   Block,               // Declaration within a block in a function.
1863   ForInit,             // Declaration within first part of a for loop.
1864   SelectionInit,       // Declaration within optional init stmt of if/switch.
1865   Condition,           // Condition declaration in a C++ if/switch/while/for.
1866   TemplateParam,       // Within a template parameter list.
1867   CXXNew,              // C++ new-expression.
1868   CXXCatch,            // C++ catch exception-declaration
1869   ObjCCatch,           // Objective-C catch exception-declaration
1870   BlockLiteral,        // Block literal declarator.
1871   LambdaExpr,          // Lambda-expression declarator.
1872   LambdaExprParameter, // Lambda-expression parameter declarator.
1873   ConversionId,        // C++ conversion-type-id.
1874   TrailingReturn,      // C++11 trailing-type-specifier.
1875   TrailingReturnVar,   // C++11 trailing-type-specifier for variable.
1876   TemplateArg,         // Any template argument (in template argument list).
1877   TemplateTypeArg,     // Template type argument (in default argument).
1878   AliasDecl,           // C++11 alias-declaration.
1879   AliasTemplate,       // C++11 alias-declaration template.
1880   RequiresExpr,        // C++2a requires-expression.
1881   Association          // C11 _Generic selection expression association.
1882 };
1883 
1884 // Describes whether the current context is a context where an implicit
1885 // typename is allowed (C++2a [temp.res]p5]).
1886 enum class ImplicitTypenameContext {
1887   No,
1888   Yes,
1889 };
1890 
1891 /// Information about one declarator, including the parsed type
1892 /// information and the identifier.
1893 ///
1894 /// When the declarator is fully formed, this is turned into the appropriate
1895 /// Decl object.
1896 ///
1897 /// Declarators come in two types: normal declarators and abstract declarators.
1898 /// Abstract declarators are used when parsing types, and don't have an
1899 /// identifier.  Normal declarators do have ID's.
1900 ///
1901 /// Instances of this class should be a transient object that lives on the
1902 /// stack, not objects that are allocated in large quantities on the heap.
1903 class Declarator {
1904 
1905 private:
1906   const DeclSpec &DS;
1907   CXXScopeSpec SS;
1908   UnqualifiedId Name;
1909   SourceRange Range;
1910 
1911   /// Where we are parsing this declarator.
1912   DeclaratorContext Context;
1913 
1914   /// The C++17 structured binding, if any. This is an alternative to a Name.
1915   DecompositionDeclarator BindingGroup;
1916 
1917   /// DeclTypeInfo - This holds each type that the declarator includes as it is
1918   /// parsed.  This is pushed from the identifier out, which means that element
1919   /// #0 will be the most closely bound to the identifier, and
1920   /// DeclTypeInfo.back() will be the least closely bound.
1921   SmallVector<DeclaratorChunk, 4> DeclTypeInfo;
1922 
1923   /// InvalidType - Set by Sema::GetTypeForDeclarator().
1924   LLVM_PREFERRED_TYPE(bool)
1925   unsigned InvalidType : 1;
1926 
1927   /// GroupingParens - Set by Parser::ParseParenDeclarator().
1928   LLVM_PREFERRED_TYPE(bool)
1929   unsigned GroupingParens : 1;
1930 
1931   /// FunctionDefinition - Is this Declarator for a function or member
1932   /// definition and, if so, what kind?
1933   ///
1934   /// Actually a FunctionDefinitionKind.
1935   LLVM_PREFERRED_TYPE(FunctionDefinitionKind)
1936   unsigned FunctionDefinition : 2;
1937 
1938   /// Is this Declarator a redeclaration?
1939   LLVM_PREFERRED_TYPE(bool)
1940   unsigned Redeclaration : 1;
1941 
1942   /// true if the declaration is preceded by \c __extension__.
1943   LLVM_PREFERRED_TYPE(bool)
1944   unsigned Extension : 1;
1945 
1946   /// Indicates whether this is an Objective-C instance variable.
1947   LLVM_PREFERRED_TYPE(bool)
1948   unsigned ObjCIvar : 1;
1949 
1950   /// Indicates whether this is an Objective-C 'weak' property.
1951   LLVM_PREFERRED_TYPE(bool)
1952   unsigned ObjCWeakProperty : 1;
1953 
1954   /// Indicates whether the InlineParams / InlineBindings storage has been used.
1955   LLVM_PREFERRED_TYPE(bool)
1956   unsigned InlineStorageUsed : 1;
1957 
1958   /// Indicates whether this declarator has an initializer.
1959   LLVM_PREFERRED_TYPE(bool)
1960   unsigned HasInitializer : 1;
1961 
1962   /// Attributes attached to the declarator.
1963   ParsedAttributes Attrs;
1964 
1965   /// Attributes attached to the declaration. See also documentation for the
1966   /// corresponding constructor parameter.
1967   const ParsedAttributesView &DeclarationAttrs;
1968 
1969   /// The asm label, if specified.
1970   Expr *AsmLabel;
1971 
1972   /// \brief The constraint-expression specified by the trailing
1973   /// requires-clause, or null if no such clause was specified.
1974   Expr *TrailingRequiresClause;
1975 
1976   /// If this declarator declares a template, its template parameter lists.
1977   ArrayRef<TemplateParameterList *> TemplateParameterLists;
1978 
1979   /// If the declarator declares an abbreviated function template, the innermost
1980   /// template parameter list containing the invented and explicit template
1981   /// parameters (if any).
1982   TemplateParameterList *InventedTemplateParameterList;
1983 
1984 #ifndef _MSC_VER
1985   union {
1986 #endif
1987     /// InlineParams - This is a local array used for the first function decl
1988     /// chunk to avoid going to the heap for the common case when we have one
1989     /// function chunk in the declarator.
1990     DeclaratorChunk::ParamInfo InlineParams[16];
1991     DecompositionDeclarator::Binding InlineBindings[16];
1992 #ifndef _MSC_VER
1993   };
1994 #endif
1995 
1996   /// If this is the second or subsequent declarator in this declaration,
1997   /// the location of the comma before this declarator.
1998   SourceLocation CommaLoc;
1999 
2000   /// If provided, the source location of the ellipsis used to describe
2001   /// this declarator as a parameter pack.
2002   SourceLocation EllipsisLoc;
2003 
2004   Expr *PackIndexingExpr;
2005 
2006   friend struct DeclaratorChunk;
2007 
2008 public:
2009   /// `DS` and `DeclarationAttrs` must outlive the `Declarator`. In particular,
2010   /// take care not to pass temporary objects for these parameters.
2011   ///
2012   /// `DeclarationAttrs` contains [[]] attributes from the
2013   /// attribute-specifier-seq at the beginning of a declaration, which appertain
2014   /// to the declared entity itself. Attributes with other syntax (e.g. GNU)
2015   /// should not be placed in this attribute list; if they occur at the
2016   /// beginning of a declaration, they apply to the `DeclSpec` and should be
2017   /// attached to that instead.
2018   ///
2019   /// Here is an example of an attribute associated with a declaration:
2020   ///
2021   ///  [[deprecated]] int x, y;
2022   ///
2023   /// This attribute appertains to all of the entities declared in the
2024   /// declaration, i.e. `x` and `y` in this case.
Declarator(const DeclSpec & DS,const ParsedAttributesView & DeclarationAttrs,DeclaratorContext C)2025   Declarator(const DeclSpec &DS, const ParsedAttributesView &DeclarationAttrs,
2026              DeclaratorContext C)
2027       : DS(DS), Range(DS.getSourceRange()), Context(C),
2028         InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
2029         GroupingParens(false), FunctionDefinition(static_cast<unsigned>(
2030                                    FunctionDefinitionKind::Declaration)),
2031         Redeclaration(false), Extension(false), ObjCIvar(false),
2032         ObjCWeakProperty(false), InlineStorageUsed(false),
2033         HasInitializer(false), Attrs(DS.getAttributePool().getFactory()),
2034         DeclarationAttrs(DeclarationAttrs), AsmLabel(nullptr),
2035         TrailingRequiresClause(nullptr),
2036         InventedTemplateParameterList(nullptr) {
2037     assert(llvm::all_of(DeclarationAttrs,
2038                         [](const ParsedAttr &AL) {
2039                           return (AL.isStandardAttributeSyntax() ||
2040                                   AL.isRegularKeywordAttribute());
2041                         }) &&
2042            "DeclarationAttrs may only contain [[]] and keyword attributes");
2043   }
2044 
~Declarator()2045   ~Declarator() {
2046     clear();
2047   }
2048   /// getDeclSpec - Return the declaration-specifier that this declarator was
2049   /// declared with.
getDeclSpec()2050   const DeclSpec &getDeclSpec() const { return DS; }
2051 
2052   /// getMutableDeclSpec - Return a non-const version of the DeclSpec.  This
2053   /// should be used with extreme care: declspecs can often be shared between
2054   /// multiple declarators, so mutating the DeclSpec affects all of the
2055   /// Declarators.  This should only be done when the declspec is known to not
2056   /// be shared or when in error recovery etc.
getMutableDeclSpec()2057   DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
2058 
getAttributePool()2059   AttributePool &getAttributePool() const {
2060     return Attrs.getPool();
2061   }
2062 
2063   /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
2064   /// nested-name-specifier) that is part of the declarator-id.
getCXXScopeSpec()2065   const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
getCXXScopeSpec()2066   CXXScopeSpec &getCXXScopeSpec() { return SS; }
2067 
2068   /// Retrieve the name specified by this declarator.
getName()2069   UnqualifiedId &getName() { return Name; }
2070 
getDecompositionDeclarator()2071   const DecompositionDeclarator &getDecompositionDeclarator() const {
2072     return BindingGroup;
2073   }
2074 
getContext()2075   DeclaratorContext getContext() const { return Context; }
2076 
isPrototypeContext()2077   bool isPrototypeContext() const {
2078     return (Context == DeclaratorContext::Prototype ||
2079             Context == DeclaratorContext::ObjCParameter ||
2080             Context == DeclaratorContext::ObjCResult ||
2081             Context == DeclaratorContext::LambdaExprParameter);
2082   }
2083 
2084   /// Get the source range that spans this declarator.
getSourceRange()2085   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
getBeginLoc()2086   SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
getEndLoc()2087   SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2088 
SetSourceRange(SourceRange R)2089   void SetSourceRange(SourceRange R) { Range = R; }
2090   /// SetRangeBegin - Set the start of the source range to Loc, unless it's
2091   /// invalid.
SetRangeBegin(SourceLocation Loc)2092   void SetRangeBegin(SourceLocation Loc) {
2093     if (!Loc.isInvalid())
2094       Range.setBegin(Loc);
2095   }
2096   /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
SetRangeEnd(SourceLocation Loc)2097   void SetRangeEnd(SourceLocation Loc) {
2098     if (!Loc.isInvalid())
2099       Range.setEnd(Loc);
2100   }
2101   /// ExtendWithDeclSpec - Extend the declarator source range to include the
2102   /// given declspec, unless its location is invalid. Adopts the range start if
2103   /// the current range start is invalid.
ExtendWithDeclSpec(const DeclSpec & DS)2104   void ExtendWithDeclSpec(const DeclSpec &DS) {
2105     SourceRange SR = DS.getSourceRange();
2106     if (Range.getBegin().isInvalid())
2107       Range.setBegin(SR.getBegin());
2108     if (!SR.getEnd().isInvalid())
2109       Range.setEnd(SR.getEnd());
2110   }
2111 
2112   /// Reset the contents of this Declarator.
clear()2113   void clear() {
2114     SS.clear();
2115     Name.clear();
2116     Range = DS.getSourceRange();
2117     BindingGroup.clear();
2118 
2119     for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
2120       DeclTypeInfo[i].destroy();
2121     DeclTypeInfo.clear();
2122     Attrs.clear();
2123     AsmLabel = nullptr;
2124     InlineStorageUsed = false;
2125     HasInitializer = false;
2126     ObjCIvar = false;
2127     ObjCWeakProperty = false;
2128     CommaLoc = SourceLocation();
2129     EllipsisLoc = SourceLocation();
2130     PackIndexingExpr = nullptr;
2131   }
2132 
2133   /// mayOmitIdentifier - Return true if the identifier is either optional or
2134   /// not allowed.  This is true for typenames, prototypes, and template
2135   /// parameter lists.
mayOmitIdentifier()2136   bool mayOmitIdentifier() const {
2137     switch (Context) {
2138     case DeclaratorContext::File:
2139     case DeclaratorContext::KNRTypeList:
2140     case DeclaratorContext::Member:
2141     case DeclaratorContext::Block:
2142     case DeclaratorContext::ForInit:
2143     case DeclaratorContext::SelectionInit:
2144     case DeclaratorContext::Condition:
2145       return false;
2146 
2147     case DeclaratorContext::TypeName:
2148     case DeclaratorContext::FunctionalCast:
2149     case DeclaratorContext::AliasDecl:
2150     case DeclaratorContext::AliasTemplate:
2151     case DeclaratorContext::Prototype:
2152     case DeclaratorContext::LambdaExprParameter:
2153     case DeclaratorContext::ObjCParameter:
2154     case DeclaratorContext::ObjCResult:
2155     case DeclaratorContext::TemplateParam:
2156     case DeclaratorContext::CXXNew:
2157     case DeclaratorContext::CXXCatch:
2158     case DeclaratorContext::ObjCCatch:
2159     case DeclaratorContext::BlockLiteral:
2160     case DeclaratorContext::LambdaExpr:
2161     case DeclaratorContext::ConversionId:
2162     case DeclaratorContext::TemplateArg:
2163     case DeclaratorContext::TemplateTypeArg:
2164     case DeclaratorContext::TrailingReturn:
2165     case DeclaratorContext::TrailingReturnVar:
2166     case DeclaratorContext::RequiresExpr:
2167     case DeclaratorContext::Association:
2168       return true;
2169     }
2170     llvm_unreachable("unknown context kind!");
2171   }
2172 
2173   /// mayHaveIdentifier - Return true if the identifier is either optional or
2174   /// required.  This is true for normal declarators and prototypes, but not
2175   /// typenames.
mayHaveIdentifier()2176   bool mayHaveIdentifier() const {
2177     switch (Context) {
2178     case DeclaratorContext::File:
2179     case DeclaratorContext::KNRTypeList:
2180     case DeclaratorContext::Member:
2181     case DeclaratorContext::Block:
2182     case DeclaratorContext::ForInit:
2183     case DeclaratorContext::SelectionInit:
2184     case DeclaratorContext::Condition:
2185     case DeclaratorContext::Prototype:
2186     case DeclaratorContext::LambdaExprParameter:
2187     case DeclaratorContext::TemplateParam:
2188     case DeclaratorContext::CXXCatch:
2189     case DeclaratorContext::ObjCCatch:
2190     case DeclaratorContext::RequiresExpr:
2191       return true;
2192 
2193     case DeclaratorContext::TypeName:
2194     case DeclaratorContext::FunctionalCast:
2195     case DeclaratorContext::CXXNew:
2196     case DeclaratorContext::AliasDecl:
2197     case DeclaratorContext::AliasTemplate:
2198     case DeclaratorContext::ObjCParameter:
2199     case DeclaratorContext::ObjCResult:
2200     case DeclaratorContext::BlockLiteral:
2201     case DeclaratorContext::LambdaExpr:
2202     case DeclaratorContext::ConversionId:
2203     case DeclaratorContext::TemplateArg:
2204     case DeclaratorContext::TemplateTypeArg:
2205     case DeclaratorContext::TrailingReturn:
2206     case DeclaratorContext::TrailingReturnVar:
2207     case DeclaratorContext::Association:
2208       return false;
2209     }
2210     llvm_unreachable("unknown context kind!");
2211   }
2212 
2213   /// Return true if the context permits a C++17 decomposition declarator.
mayHaveDecompositionDeclarator()2214   bool mayHaveDecompositionDeclarator() const {
2215     switch (Context) {
2216     case DeclaratorContext::File:
2217       // FIXME: It's not clear that the proposal meant to allow file-scope
2218       // structured bindings, but it does.
2219     case DeclaratorContext::Block:
2220     case DeclaratorContext::ForInit:
2221     case DeclaratorContext::SelectionInit:
2222     case DeclaratorContext::Condition:
2223       return true;
2224 
2225     case DeclaratorContext::Member:
2226     case DeclaratorContext::Prototype:
2227     case DeclaratorContext::TemplateParam:
2228     case DeclaratorContext::RequiresExpr:
2229       // Maybe one day...
2230       return false;
2231 
2232     // These contexts don't allow any kind of non-abstract declarator.
2233     case DeclaratorContext::KNRTypeList:
2234     case DeclaratorContext::TypeName:
2235     case DeclaratorContext::FunctionalCast:
2236     case DeclaratorContext::AliasDecl:
2237     case DeclaratorContext::AliasTemplate:
2238     case DeclaratorContext::LambdaExprParameter:
2239     case DeclaratorContext::ObjCParameter:
2240     case DeclaratorContext::ObjCResult:
2241     case DeclaratorContext::CXXNew:
2242     case DeclaratorContext::CXXCatch:
2243     case DeclaratorContext::ObjCCatch:
2244     case DeclaratorContext::BlockLiteral:
2245     case DeclaratorContext::LambdaExpr:
2246     case DeclaratorContext::ConversionId:
2247     case DeclaratorContext::TemplateArg:
2248     case DeclaratorContext::TemplateTypeArg:
2249     case DeclaratorContext::TrailingReturn:
2250     case DeclaratorContext::TrailingReturnVar:
2251     case DeclaratorContext::Association:
2252       return false;
2253     }
2254     llvm_unreachable("unknown context kind!");
2255   }
2256 
2257   /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2258   /// followed by a C++ direct initializer, e.g. "int x(1);".
mayBeFollowedByCXXDirectInit()2259   bool mayBeFollowedByCXXDirectInit() const {
2260     if (hasGroupingParens()) return false;
2261 
2262     if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2263       return false;
2264 
2265     if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2266         Context != DeclaratorContext::File)
2267       return false;
2268 
2269     // Special names can't have direct initializers.
2270     if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2271       return false;
2272 
2273     switch (Context) {
2274     case DeclaratorContext::File:
2275     case DeclaratorContext::Block:
2276     case DeclaratorContext::ForInit:
2277     case DeclaratorContext::SelectionInit:
2278     case DeclaratorContext::TrailingReturnVar:
2279       return true;
2280 
2281     case DeclaratorContext::Condition:
2282       // This may not be followed by a direct initializer, but it can't be a
2283       // function declaration either, and we'd prefer to perform a tentative
2284       // parse in order to produce the right diagnostic.
2285       return true;
2286 
2287     case DeclaratorContext::KNRTypeList:
2288     case DeclaratorContext::Member:
2289     case DeclaratorContext::Prototype:
2290     case DeclaratorContext::LambdaExprParameter:
2291     case DeclaratorContext::ObjCParameter:
2292     case DeclaratorContext::ObjCResult:
2293     case DeclaratorContext::TemplateParam:
2294     case DeclaratorContext::CXXCatch:
2295     case DeclaratorContext::ObjCCatch:
2296     case DeclaratorContext::TypeName:
2297     case DeclaratorContext::FunctionalCast: // FIXME
2298     case DeclaratorContext::CXXNew:
2299     case DeclaratorContext::AliasDecl:
2300     case DeclaratorContext::AliasTemplate:
2301     case DeclaratorContext::BlockLiteral:
2302     case DeclaratorContext::LambdaExpr:
2303     case DeclaratorContext::ConversionId:
2304     case DeclaratorContext::TemplateArg:
2305     case DeclaratorContext::TemplateTypeArg:
2306     case DeclaratorContext::TrailingReturn:
2307     case DeclaratorContext::RequiresExpr:
2308     case DeclaratorContext::Association:
2309       return false;
2310     }
2311     llvm_unreachable("unknown context kind!");
2312   }
2313 
2314   /// isPastIdentifier - Return true if we have parsed beyond the point where
2315   /// the name would appear. (This may happen even if we haven't actually parsed
2316   /// a name, perhaps because this context doesn't require one.)
isPastIdentifier()2317   bool isPastIdentifier() const { return Name.isValid(); }
2318 
2319   /// hasName - Whether this declarator has a name, which might be an
2320   /// identifier (accessible via getIdentifier()) or some kind of
2321   /// special C++ name (constructor, destructor, etc.), or a structured
2322   /// binding (which is not exactly a name, but occupies the same position).
hasName()2323   bool hasName() const {
2324     return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2325            Name.Identifier || isDecompositionDeclarator();
2326   }
2327 
2328   /// Return whether this declarator is a decomposition declarator.
isDecompositionDeclarator()2329   bool isDecompositionDeclarator() const {
2330     return BindingGroup.isSet();
2331   }
2332 
getIdentifier()2333   const IdentifierInfo *getIdentifier() const {
2334     if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2335       return Name.Identifier;
2336 
2337     return nullptr;
2338   }
getIdentifierLoc()2339   SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2340 
2341   /// Set the name of this declarator to be the given identifier.
SetIdentifier(const IdentifierInfo * Id,SourceLocation IdLoc)2342   void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
2343     Name.setIdentifier(Id, IdLoc);
2344   }
2345 
2346   /// Set the decomposition bindings for this declarator.
2347   void setDecompositionBindings(
2348       SourceLocation LSquareLoc,
2349       MutableArrayRef<DecompositionDeclarator::Binding> Bindings,
2350       SourceLocation RSquareLoc);
2351 
2352   /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2353   /// EndLoc, which should be the last token of the chunk.
2354   /// This function takes attrs by R-Value reference because it takes ownership
2355   /// of those attributes from the parameter.
AddTypeInfo(const DeclaratorChunk & TI,ParsedAttributes && attrs,SourceLocation EndLoc)2356   void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2357                    SourceLocation EndLoc) {
2358     DeclTypeInfo.push_back(TI);
2359     DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2360     getAttributePool().takeAllFrom(attrs.getPool());
2361 
2362     if (!EndLoc.isInvalid())
2363       SetRangeEnd(EndLoc);
2364   }
2365 
2366   /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2367   /// EndLoc, which should be the last token of the chunk. This overload is for
2368   /// copying a 'chunk' from another declarator, so it takes the pool that the
2369   /// other Declarator owns so that it can 'take' the attributes from it.
AddTypeInfo(const DeclaratorChunk & TI,AttributePool & OtherPool,SourceLocation EndLoc)2370   void AddTypeInfo(const DeclaratorChunk &TI, AttributePool &OtherPool,
2371                    SourceLocation EndLoc) {
2372     DeclTypeInfo.push_back(TI);
2373     getAttributePool().takeFrom(DeclTypeInfo.back().getAttrs(), OtherPool);
2374 
2375     if (!EndLoc.isInvalid())
2376       SetRangeEnd(EndLoc);
2377   }
2378 
2379   /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2380   /// EndLoc, which should be the last token of the chunk.
AddTypeInfo(const DeclaratorChunk & TI,SourceLocation EndLoc)2381   void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2382     DeclTypeInfo.push_back(TI);
2383 
2384     assert(TI.AttrList.empty() &&
2385            "Cannot add a declarator chunk with attributes with this overload");
2386 
2387     if (!EndLoc.isInvalid())
2388       SetRangeEnd(EndLoc);
2389   }
2390 
2391   /// Add a new innermost chunk to this declarator.
AddInnermostTypeInfo(const DeclaratorChunk & TI)2392   void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2393     DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2394   }
2395 
2396   /// Return the number of types applied to this declarator.
getNumTypeObjects()2397   unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2398 
2399   /// Return the specified TypeInfo from this declarator.  TypeInfo #0 is
2400   /// closest to the identifier.
getTypeObject(unsigned i)2401   const DeclaratorChunk &getTypeObject(unsigned i) const {
2402     assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2403     return DeclTypeInfo[i];
2404   }
getTypeObject(unsigned i)2405   DeclaratorChunk &getTypeObject(unsigned i) {
2406     assert(i < DeclTypeInfo.size() && "Invalid type chunk");
2407     return DeclTypeInfo[i];
2408   }
2409 
2410   typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2411   typedef llvm::iterator_range<type_object_iterator> type_object_range;
2412 
2413   /// Returns the range of type objects, from the identifier outwards.
type_objects()2414   type_object_range type_objects() const {
2415     return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2416   }
2417 
DropFirstTypeObject()2418   void DropFirstTypeObject() {
2419     assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
2420     DeclTypeInfo.front().destroy();
2421     DeclTypeInfo.erase(DeclTypeInfo.begin());
2422   }
2423 
2424   /// Return the innermost (closest to the declarator) chunk of this
2425   /// declarator that is not a parens chunk, or null if there are no
2426   /// non-parens chunks.
getInnermostNonParenChunk()2427   const DeclaratorChunk *getInnermostNonParenChunk() const {
2428     for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2429       if (!DeclTypeInfo[i].isParen())
2430         return &DeclTypeInfo[i];
2431     }
2432     return nullptr;
2433   }
2434 
2435   /// Return the outermost (furthest from the declarator) chunk of
2436   /// this declarator that is not a parens chunk, or null if there are
2437   /// no non-parens chunks.
getOutermostNonParenChunk()2438   const DeclaratorChunk *getOutermostNonParenChunk() const {
2439     for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2440       if (!DeclTypeInfo[i-1].isParen())
2441         return &DeclTypeInfo[i-1];
2442     }
2443     return nullptr;
2444   }
2445 
2446   /// isArrayOfUnknownBound - This method returns true if the declarator
2447   /// is a declarator for an array of unknown bound (looking through
2448   /// parentheses).
isArrayOfUnknownBound()2449   bool isArrayOfUnknownBound() const {
2450     const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2451     return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2452             !chunk->Arr.NumElts);
2453   }
2454 
2455   /// isFunctionDeclarator - This method returns true if the declarator
2456   /// is a function declarator (looking through parentheses).
2457   /// If true is returned, then the reference type parameter idx is
2458   /// assigned with the index of the declaration chunk.
isFunctionDeclarator(unsigned & idx)2459   bool isFunctionDeclarator(unsigned& idx) const {
2460     for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2461       switch (DeclTypeInfo[i].Kind) {
2462       case DeclaratorChunk::Function:
2463         idx = i;
2464         return true;
2465       case DeclaratorChunk::Paren:
2466         continue;
2467       case DeclaratorChunk::Pointer:
2468       case DeclaratorChunk::Reference:
2469       case DeclaratorChunk::Array:
2470       case DeclaratorChunk::BlockPointer:
2471       case DeclaratorChunk::MemberPointer:
2472       case DeclaratorChunk::Pipe:
2473         return false;
2474       }
2475       llvm_unreachable("Invalid type chunk");
2476     }
2477     return false;
2478   }
2479 
2480   /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2481   /// this method returns true if the identifier is a function declarator
2482   /// (looking through parentheses).
isFunctionDeclarator()2483   bool isFunctionDeclarator() const {
2484     unsigned index;
2485     return isFunctionDeclarator(index);
2486   }
2487 
2488   /// getFunctionTypeInfo - Retrieves the function type info object
2489   /// (looking through parentheses).
getFunctionTypeInfo()2490   DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2491     assert(isFunctionDeclarator() && "Not a function declarator!");
2492     unsigned index = 0;
2493     isFunctionDeclarator(index);
2494     return DeclTypeInfo[index].Fun;
2495   }
2496 
2497   /// getFunctionTypeInfo - Retrieves the function type info object
2498   /// (looking through parentheses).
getFunctionTypeInfo()2499   const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2500     return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2501   }
2502 
2503   /// Determine whether the declaration that will be produced from
2504   /// this declaration will be a function.
2505   ///
2506   /// A declaration can declare a function even if the declarator itself
2507   /// isn't a function declarator, if the type specifier refers to a function
2508   /// type. This routine checks for both cases.
2509   bool isDeclarationOfFunction() const;
2510 
2511   /// Return true if this declaration appears in a context where a
2512   /// function declarator would be a function declaration.
isFunctionDeclarationContext()2513   bool isFunctionDeclarationContext() const {
2514     if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2515       return false;
2516 
2517     switch (Context) {
2518     case DeclaratorContext::File:
2519     case DeclaratorContext::Member:
2520     case DeclaratorContext::Block:
2521     case DeclaratorContext::ForInit:
2522     case DeclaratorContext::SelectionInit:
2523       return true;
2524 
2525     case DeclaratorContext::Condition:
2526     case DeclaratorContext::KNRTypeList:
2527     case DeclaratorContext::TypeName:
2528     case DeclaratorContext::FunctionalCast:
2529     case DeclaratorContext::AliasDecl:
2530     case DeclaratorContext::AliasTemplate:
2531     case DeclaratorContext::Prototype:
2532     case DeclaratorContext::LambdaExprParameter:
2533     case DeclaratorContext::ObjCParameter:
2534     case DeclaratorContext::ObjCResult:
2535     case DeclaratorContext::TemplateParam:
2536     case DeclaratorContext::CXXNew:
2537     case DeclaratorContext::CXXCatch:
2538     case DeclaratorContext::ObjCCatch:
2539     case DeclaratorContext::BlockLiteral:
2540     case DeclaratorContext::LambdaExpr:
2541     case DeclaratorContext::ConversionId:
2542     case DeclaratorContext::TemplateArg:
2543     case DeclaratorContext::TemplateTypeArg:
2544     case DeclaratorContext::TrailingReturn:
2545     case DeclaratorContext::TrailingReturnVar:
2546     case DeclaratorContext::RequiresExpr:
2547     case DeclaratorContext::Association:
2548       return false;
2549     }
2550     llvm_unreachable("unknown context kind!");
2551   }
2552 
2553   /// Determine whether this declaration appears in a context where an
2554   /// expression could appear.
isExpressionContext()2555   bool isExpressionContext() const {
2556     switch (Context) {
2557     case DeclaratorContext::File:
2558     case DeclaratorContext::KNRTypeList:
2559     case DeclaratorContext::Member:
2560 
2561     // FIXME: sizeof(...) permits an expression.
2562     case DeclaratorContext::TypeName:
2563 
2564     case DeclaratorContext::FunctionalCast:
2565     case DeclaratorContext::AliasDecl:
2566     case DeclaratorContext::AliasTemplate:
2567     case DeclaratorContext::Prototype:
2568     case DeclaratorContext::LambdaExprParameter:
2569     case DeclaratorContext::ObjCParameter:
2570     case DeclaratorContext::ObjCResult:
2571     case DeclaratorContext::TemplateParam:
2572     case DeclaratorContext::CXXNew:
2573     case DeclaratorContext::CXXCatch:
2574     case DeclaratorContext::ObjCCatch:
2575     case DeclaratorContext::BlockLiteral:
2576     case DeclaratorContext::LambdaExpr:
2577     case DeclaratorContext::ConversionId:
2578     case DeclaratorContext::TrailingReturn:
2579     case DeclaratorContext::TrailingReturnVar:
2580     case DeclaratorContext::TemplateTypeArg:
2581     case DeclaratorContext::RequiresExpr:
2582     case DeclaratorContext::Association:
2583       return false;
2584 
2585     case DeclaratorContext::Block:
2586     case DeclaratorContext::ForInit:
2587     case DeclaratorContext::SelectionInit:
2588     case DeclaratorContext::Condition:
2589     case DeclaratorContext::TemplateArg:
2590       return true;
2591     }
2592 
2593     llvm_unreachable("unknown context kind!");
2594   }
2595 
2596   /// Return true if a function declarator at this position would be a
2597   /// function declaration.
isFunctionDeclaratorAFunctionDeclaration()2598   bool isFunctionDeclaratorAFunctionDeclaration() const {
2599     if (!isFunctionDeclarationContext())
2600       return false;
2601 
2602     for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2603       if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2604         return false;
2605 
2606     return true;
2607   }
2608 
2609   /// Determine whether a trailing return type was written (at any
2610   /// level) within this declarator.
hasTrailingReturnType()2611   bool hasTrailingReturnType() const {
2612     for (const auto &Chunk : type_objects())
2613       if (Chunk.Kind == DeclaratorChunk::Function &&
2614           Chunk.Fun.hasTrailingReturnType())
2615         return true;
2616     return false;
2617   }
2618   /// Get the trailing return type appearing (at any level) within this
2619   /// declarator.
getTrailingReturnType()2620   ParsedType getTrailingReturnType() const {
2621     for (const auto &Chunk : type_objects())
2622       if (Chunk.Kind == DeclaratorChunk::Function &&
2623           Chunk.Fun.hasTrailingReturnType())
2624         return Chunk.Fun.getTrailingReturnType();
2625     return ParsedType();
2626   }
2627 
2628   /// \brief Sets a trailing requires clause for this declarator.
setTrailingRequiresClause(Expr * TRC)2629   void setTrailingRequiresClause(Expr *TRC) {
2630     TrailingRequiresClause = TRC;
2631 
2632     SetRangeEnd(TRC->getEndLoc());
2633   }
2634 
2635   /// \brief Sets a trailing requires clause for this declarator.
getTrailingRequiresClause()2636   Expr *getTrailingRequiresClause() {
2637     return TrailingRequiresClause;
2638   }
2639 
2640   /// \brief Determine whether a trailing requires clause was written in this
2641   /// declarator.
hasTrailingRequiresClause()2642   bool hasTrailingRequiresClause() const {
2643     return TrailingRequiresClause != nullptr;
2644   }
2645 
2646   /// Sets the template parameter lists that preceded the declarator.
setTemplateParameterLists(ArrayRef<TemplateParameterList * > TPLs)2647   void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) {
2648     TemplateParameterLists = TPLs;
2649   }
2650 
2651   /// The template parameter lists that preceded the declarator.
getTemplateParameterLists()2652   ArrayRef<TemplateParameterList *> getTemplateParameterLists() const {
2653     return TemplateParameterLists;
2654   }
2655 
2656   /// Sets the template parameter list generated from the explicit template
2657   /// parameters along with any invented template parameters from
2658   /// placeholder-typed parameters.
setInventedTemplateParameterList(TemplateParameterList * Invented)2659   void setInventedTemplateParameterList(TemplateParameterList *Invented) {
2660     InventedTemplateParameterList = Invented;
2661   }
2662 
2663   /// The template parameter list generated from the explicit template
2664   /// parameters along with any invented template parameters from
2665   /// placeholder-typed parameters, if there were any such parameters.
getInventedTemplateParameterList()2666   TemplateParameterList * getInventedTemplateParameterList() const {
2667     return InventedTemplateParameterList;
2668   }
2669 
2670   /// takeAttributes - Takes attributes from the given parsed-attributes
2671   /// set and add them to this declarator.
2672   ///
2673   /// These examples both add 3 attributes to "var":
2674   ///  short int var __attribute__((aligned(16),common,deprecated));
2675   ///  short int x, __attribute__((aligned(16)) var
2676   ///                                 __attribute__((common,deprecated));
2677   ///
2678   /// Also extends the range of the declarator.
takeAttributes(ParsedAttributes & attrs)2679   void takeAttributes(ParsedAttributes &attrs) {
2680     Attrs.takeAllFrom(attrs);
2681 
2682     if (attrs.Range.getEnd().isValid())
2683       SetRangeEnd(attrs.Range.getEnd());
2684   }
2685 
getAttributes()2686   const ParsedAttributes &getAttributes() const { return Attrs; }
getAttributes()2687   ParsedAttributes &getAttributes() { return Attrs; }
2688 
getDeclarationAttributes()2689   const ParsedAttributesView &getDeclarationAttributes() const {
2690     return DeclarationAttrs;
2691   }
2692 
2693   /// hasAttributes - do we contain any attributes?
hasAttributes()2694   bool hasAttributes() const {
2695     if (!getAttributes().empty() || !getDeclarationAttributes().empty() ||
2696         getDeclSpec().hasAttributes())
2697       return true;
2698     for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2699       if (!getTypeObject(i).getAttrs().empty())
2700         return true;
2701     return false;
2702   }
2703 
setAsmLabel(Expr * E)2704   void setAsmLabel(Expr *E) { AsmLabel = E; }
getAsmLabel()2705   Expr *getAsmLabel() const { return AsmLabel; }
2706 
2707   void setExtension(bool Val = true) { Extension = Val; }
getExtension()2708   bool getExtension() const { return Extension; }
2709 
2710   void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
isObjCIvar()2711   bool isObjCIvar() const { return ObjCIvar; }
2712 
2713   void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
isObjCWeakProperty()2714   bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2715 
2716   void setInvalidType(bool Val = true) { InvalidType = Val; }
isInvalidType()2717   bool isInvalidType() const {
2718     return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2719   }
2720 
setGroupingParens(bool flag)2721   void setGroupingParens(bool flag) { GroupingParens = flag; }
hasGroupingParens()2722   bool hasGroupingParens() const { return GroupingParens; }
2723 
isFirstDeclarator()2724   bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
getCommaLoc()2725   SourceLocation getCommaLoc() const { return CommaLoc; }
setCommaLoc(SourceLocation CL)2726   void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2727 
hasEllipsis()2728   bool hasEllipsis() const { return EllipsisLoc.isValid(); }
getEllipsisLoc()2729   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
setEllipsisLoc(SourceLocation EL)2730   void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2731 
hasPackIndexing()2732   bool hasPackIndexing() const { return PackIndexingExpr != nullptr; }
getPackIndexingExpr()2733   Expr *getPackIndexingExpr() const { return PackIndexingExpr; }
setPackIndexingExpr(Expr * PI)2734   void setPackIndexingExpr(Expr *PI) { PackIndexingExpr = PI; }
2735 
setFunctionDefinitionKind(FunctionDefinitionKind Val)2736   void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2737     FunctionDefinition = static_cast<unsigned>(Val);
2738   }
2739 
isFunctionDefinition()2740   bool isFunctionDefinition() const {
2741     return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration;
2742   }
2743 
getFunctionDefinitionKind()2744   FunctionDefinitionKind getFunctionDefinitionKind() const {
2745     return (FunctionDefinitionKind)FunctionDefinition;
2746   }
2747 
2748   void setHasInitializer(bool Val = true) { HasInitializer = Val; }
hasInitializer()2749   bool hasInitializer() const { return HasInitializer; }
2750 
2751   /// Returns true if this declares a real member and not a friend.
isFirstDeclarationOfMember()2752   bool isFirstDeclarationOfMember() {
2753     return getContext() == DeclaratorContext::Member &&
2754            !getDeclSpec().isFriendSpecified();
2755   }
2756 
2757   /// Returns true if this declares a static member.  This cannot be called on a
2758   /// declarator outside of a MemberContext because we won't know until
2759   /// redeclaration time if the decl is static.
2760   bool isStaticMember();
2761 
2762   bool isExplicitObjectMemberFunction();
2763 
2764   /// Returns true if this declares a constructor or a destructor.
2765   bool isCtorOrDtor();
2766 
setRedeclaration(bool Val)2767   void setRedeclaration(bool Val) { Redeclaration = Val; }
isRedeclaration()2768   bool isRedeclaration() const { return Redeclaration; }
2769 };
2770 
2771 /// This little struct is used to capture information about
2772 /// structure field declarators, which is basically just a bitfield size.
2773 struct FieldDeclarator {
2774   Declarator D;
2775   Expr *BitfieldSize;
FieldDeclaratorFieldDeclarator2776   explicit FieldDeclarator(const DeclSpec &DS,
2777                            const ParsedAttributes &DeclarationAttrs)
2778       : D(DS, DeclarationAttrs, DeclaratorContext::Member),
2779         BitfieldSize(nullptr) {}
2780 };
2781 
2782 /// Represents a C++11 virt-specifier-seq.
2783 class VirtSpecifiers {
2784 public:
2785   enum Specifier {
2786     VS_None = 0,
2787     VS_Override = 1,
2788     VS_Final = 2,
2789     VS_Sealed = 4,
2790     // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2791     VS_GNU_Final = 8,
2792     VS_Abstract = 16
2793   };
2794 
2795   VirtSpecifiers() = default;
2796 
2797   bool SetSpecifier(Specifier VS, SourceLocation Loc,
2798                     const char *&PrevSpec);
2799 
isUnset()2800   bool isUnset() const { return Specifiers == 0; }
2801 
isOverrideSpecified()2802   bool isOverrideSpecified() const { return Specifiers & VS_Override; }
getOverrideLoc()2803   SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2804 
isFinalSpecified()2805   bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
isFinalSpelledSealed()2806   bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
getFinalLoc()2807   SourceLocation getFinalLoc() const { return VS_finalLoc; }
getAbstractLoc()2808   SourceLocation getAbstractLoc() const { return VS_abstractLoc; }
2809 
clear()2810   void clear() { Specifiers = 0; }
2811 
2812   static const char *getSpecifierName(Specifier VS);
2813 
getFirstLocation()2814   SourceLocation getFirstLocation() const { return FirstLocation; }
getLastLocation()2815   SourceLocation getLastLocation() const { return LastLocation; }
getLastSpecifier()2816   Specifier getLastSpecifier() const { return LastSpecifier; }
2817 
2818 private:
2819   unsigned Specifiers = 0;
2820   Specifier LastSpecifier = VS_None;
2821 
2822   SourceLocation VS_overrideLoc, VS_finalLoc, VS_abstractLoc;
2823   SourceLocation FirstLocation;
2824   SourceLocation LastLocation;
2825 };
2826 
2827 enum class LambdaCaptureInitKind {
2828   NoInit,     //!< [a]
2829   CopyInit,   //!< [a = b], [a = {b}]
2830   DirectInit, //!< [a(b)]
2831   ListInit    //!< [a{b}]
2832 };
2833 
2834 /// Represents a complete lambda introducer.
2835 struct LambdaIntroducer {
2836   /// An individual capture in a lambda introducer.
2837   struct LambdaCapture {
2838     LambdaCaptureKind Kind;
2839     SourceLocation Loc;
2840     IdentifierInfo *Id;
2841     SourceLocation EllipsisLoc;
2842     LambdaCaptureInitKind InitKind;
2843     ExprResult Init;
2844     ParsedType InitCaptureType;
2845     SourceRange ExplicitRange;
2846 
LambdaCaptureLambdaIntroducer::LambdaCapture2847     LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2848                   IdentifierInfo *Id, SourceLocation EllipsisLoc,
2849                   LambdaCaptureInitKind InitKind, ExprResult Init,
2850                   ParsedType InitCaptureType,
2851                   SourceRange ExplicitRange)
2852         : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2853           InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2854           ExplicitRange(ExplicitRange) {}
2855   };
2856 
2857   SourceRange Range;
2858   SourceLocation DefaultLoc;
2859   LambdaCaptureDefault Default = LCD_None;
2860   SmallVector<LambdaCapture, 4> Captures;
2861 
2862   LambdaIntroducer() = default;
2863 
hasLambdaCaptureLambdaIntroducer2864   bool hasLambdaCapture() const {
2865     return Captures.size() > 0 || Default != LCD_None;
2866   }
2867 
2868   /// Append a capture in a lambda introducer.
addCaptureLambdaIntroducer2869   void addCapture(LambdaCaptureKind Kind,
2870                   SourceLocation Loc,
2871                   IdentifierInfo* Id,
2872                   SourceLocation EllipsisLoc,
2873                   LambdaCaptureInitKind InitKind,
2874                   ExprResult Init,
2875                   ParsedType InitCaptureType,
2876                   SourceRange ExplicitRange) {
2877     Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2878                                      InitCaptureType, ExplicitRange));
2879   }
2880 };
2881 
2882 struct InventedTemplateParameterInfo {
2883   /// The number of parameters in the template parameter list that were
2884   /// explicitly specified by the user, as opposed to being invented by use
2885   /// of an auto parameter.
2886   unsigned NumExplicitTemplateParams = 0;
2887 
2888   /// If this is a generic lambda or abbreviated function template, use this
2889   /// as the depth of each 'auto' parameter, during initial AST construction.
2890   unsigned AutoTemplateParameterDepth = 0;
2891 
2892   /// Store the list of the template parameters for a generic lambda or an
2893   /// abbreviated function template.
2894   /// If this is a generic lambda or abbreviated function template, this holds
2895   /// the explicit template parameters followed by the auto parameters
2896   /// converted into TemplateTypeParmDecls.
2897   /// It can be used to construct the generic lambda or abbreviated template's
2898   /// template parameter list during initial AST construction.
2899   SmallVector<NamedDecl*, 4> TemplateParams;
2900 };
2901 
2902 } // end namespace clang
2903 
2904 #endif // LLVM_CLANG_SEMA_DECLSPEC_H
2905