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