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