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