]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Parse/ParseDecl.cpp
Merge ^/vendor/lvm-project/master up to its last change (upstream commit
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Parse / ParseDecl.cpp
1 //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements the Declaration portions of the Parser interfaces.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/Parse/Parser.h"
14 #include "clang/Parse/RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/PrettyDeclStackTrace.h"
18 #include "clang/Basic/AddressSpaces.h"
19 #include "clang/Basic/Attributes.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Parse/ParseDiagnostic.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/ParsedTemplate.h"
25 #include "clang/Sema/Scope.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringSwitch.h"
30
31 using namespace clang;
32
33 //===----------------------------------------------------------------------===//
34 // C99 6.7: Declarations.
35 //===----------------------------------------------------------------------===//
36
37 /// ParseTypeName
38 ///       type-name: [C99 6.7.6]
39 ///         specifier-qualifier-list abstract-declarator[opt]
40 ///
41 /// Called type-id in C++.
42 TypeResult Parser::ParseTypeName(SourceRange *Range,
43                                  DeclaratorContext Context,
44                                  AccessSpecifier AS,
45                                  Decl **OwnedType,
46                                  ParsedAttributes *Attrs) {
47   DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
48   if (DSC == DeclSpecContext::DSC_normal)
49     DSC = DeclSpecContext::DSC_type_specifier;
50
51   // Parse the common declaration-specifiers piece.
52   DeclSpec DS(AttrFactory);
53   if (Attrs)
54     DS.addAttributes(*Attrs);
55   ParseSpecifierQualifierList(DS, AS, DSC);
56   if (OwnedType)
57     *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
58
59   // Parse the abstract-declarator, if present.
60   Declarator DeclaratorInfo(DS, Context);
61   ParseDeclarator(DeclaratorInfo);
62   if (Range)
63     *Range = DeclaratorInfo.getSourceRange();
64
65   if (DeclaratorInfo.isInvalidType())
66     return true;
67
68   return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
69 }
70
71 /// Normalizes an attribute name by dropping prefixed and suffixed __.
72 static StringRef normalizeAttrName(StringRef Name) {
73   if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
74     return Name.drop_front(2).drop_back(2);
75   return Name;
76 }
77
78 /// isAttributeLateParsed - Return true if the attribute has arguments that
79 /// require late parsing.
80 static bool isAttributeLateParsed(const IdentifierInfo &II) {
81 #define CLANG_ATTR_LATE_PARSED_LIST
82     return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
83 #include "clang/Parse/AttrParserStringSwitches.inc"
84         .Default(false);
85 #undef CLANG_ATTR_LATE_PARSED_LIST
86 }
87
88 /// Check if the a start and end source location expand to the same macro.
89 static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
90                                      SourceLocation EndLoc) {
91   if (!StartLoc.isMacroID() || !EndLoc.isMacroID())
92     return false;
93
94   SourceManager &SM = PP.getSourceManager();
95   if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
96     return false;
97
98   bool AttrStartIsInMacro =
99       Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
100   bool AttrEndIsInMacro =
101       Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
102   return AttrStartIsInMacro && AttrEndIsInMacro;
103 }
104
105 /// ParseGNUAttributes - Parse a non-empty attributes list.
106 ///
107 /// [GNU] attributes:
108 ///         attribute
109 ///         attributes attribute
110 ///
111 /// [GNU]  attribute:
112 ///          '__attribute__' '(' '(' attribute-list ')' ')'
113 ///
114 /// [GNU]  attribute-list:
115 ///          attrib
116 ///          attribute_list ',' attrib
117 ///
118 /// [GNU]  attrib:
119 ///          empty
120 ///          attrib-name
121 ///          attrib-name '(' identifier ')'
122 ///          attrib-name '(' identifier ',' nonempty-expr-list ')'
123 ///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
124 ///
125 /// [GNU]  attrib-name:
126 ///          identifier
127 ///          typespec
128 ///          typequal
129 ///          storageclass
130 ///
131 /// Whether an attribute takes an 'identifier' is determined by the
132 /// attrib-name. GCC's behavior here is not worth imitating:
133 ///
134 ///  * In C mode, if the attribute argument list starts with an identifier
135 ///    followed by a ',' or an ')', and the identifier doesn't resolve to
136 ///    a type, it is parsed as an identifier. If the attribute actually
137 ///    wanted an expression, it's out of luck (but it turns out that no
138 ///    attributes work that way, because C constant expressions are very
139 ///    limited).
140 ///  * In C++ mode, if the attribute argument list starts with an identifier,
141 ///    and the attribute *wants* an identifier, it is parsed as an identifier.
142 ///    At block scope, any additional tokens between the identifier and the
143 ///    ',' or ')' are ignored, otherwise they produce a parse error.
144 ///
145 /// We follow the C++ model, but don't allow junk after the identifier.
146 void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
147                                 SourceLocation *endLoc,
148                                 LateParsedAttrList *LateAttrs,
149                                 Declarator *D) {
150   assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
151
152   while (Tok.is(tok::kw___attribute)) {
153     SourceLocation AttrTokLoc = ConsumeToken();
154     unsigned OldNumAttrs = attrs.size();
155     unsigned OldNumLateAttrs = LateAttrs ? LateAttrs->size() : 0;
156
157     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
158                          "attribute")) {
159       SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
160       return;
161     }
162     if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
163       SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
164       return;
165     }
166     // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
167     do {
168       // Eat preceeding commas to allow __attribute__((,,,foo))
169       while (TryConsumeToken(tok::comma))
170         ;
171
172       // Expect an identifier or declaration specifier (const, int, etc.)
173       if (Tok.isAnnotation())
174         break;
175       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
176       if (!AttrName)
177         break;
178
179       SourceLocation AttrNameLoc = ConsumeToken();
180
181       if (Tok.isNot(tok::l_paren)) {
182         attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
183                      ParsedAttr::AS_GNU);
184         continue;
185       }
186
187       // Handle "parameterized" attributes
188       if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
189         ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
190                               SourceLocation(), ParsedAttr::AS_GNU, D);
191         continue;
192       }
193
194       // Handle attributes with arguments that require late parsing.
195       LateParsedAttribute *LA =
196           new LateParsedAttribute(this, *AttrName, AttrNameLoc);
197       LateAttrs->push_back(LA);
198
199       // Attributes in a class are parsed at the end of the class, along
200       // with other late-parsed declarations.
201       if (!ClassStack.empty() && !LateAttrs->parseSoon())
202         getCurrentClass().LateParsedDeclarations.push_back(LA);
203
204       // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
205       // recursively consumes balanced parens.
206       LA->Toks.push_back(Tok);
207       ConsumeParen();
208       // Consume everything up to and including the matching right parens.
209       ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
210
211       Token Eof;
212       Eof.startToken();
213       Eof.setLocation(Tok.getLocation());
214       LA->Toks.push_back(Eof);
215     } while (Tok.is(tok::comma));
216
217     if (ExpectAndConsume(tok::r_paren))
218       SkipUntil(tok::r_paren, StopAtSemi);
219     SourceLocation Loc = Tok.getLocation();
220     if (ExpectAndConsume(tok::r_paren))
221       SkipUntil(tok::r_paren, StopAtSemi);
222     if (endLoc)
223       *endLoc = Loc;
224
225     // If this was declared in a macro, attach the macro IdentifierInfo to the
226     // parsed attribute.
227     auto &SM = PP.getSourceManager();
228     if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
229         FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)) {
230       CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
231       StringRef FoundName =
232           Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
233       IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
234
235       for (unsigned i = OldNumAttrs; i < attrs.size(); ++i)
236         attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
237
238       if (LateAttrs) {
239         for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); ++i)
240           (*LateAttrs)[i]->MacroII = MacroII;
241       }
242     }
243   }
244 }
245
246 /// Determine whether the given attribute has an identifier argument.
247 static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
248 #define CLANG_ATTR_IDENTIFIER_ARG_LIST
249   return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
250 #include "clang/Parse/AttrParserStringSwitches.inc"
251            .Default(false);
252 #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
253 }
254
255 /// Determine whether the given attribute has a variadic identifier argument.
256 static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
257 #define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
258   return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
259 #include "clang/Parse/AttrParserStringSwitches.inc"
260            .Default(false);
261 #undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
262 }
263
264 /// Determine whether the given attribute treats kw_this as an identifier.
265 static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
266 #define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
267   return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
268 #include "clang/Parse/AttrParserStringSwitches.inc"
269            .Default(false);
270 #undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
271 }
272
273 /// Determine whether the given attribute parses a type argument.
274 static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
275 #define CLANG_ATTR_TYPE_ARG_LIST
276   return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
277 #include "clang/Parse/AttrParserStringSwitches.inc"
278            .Default(false);
279 #undef CLANG_ATTR_TYPE_ARG_LIST
280 }
281
282 /// Determine whether the given attribute requires parsing its arguments
283 /// in an unevaluated context or not.
284 static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
285 #define CLANG_ATTR_ARG_CONTEXT_LIST
286   return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
287 #include "clang/Parse/AttrParserStringSwitches.inc"
288            .Default(false);
289 #undef CLANG_ATTR_ARG_CONTEXT_LIST
290 }
291
292 IdentifierLoc *Parser::ParseIdentifierLoc() {
293   assert(Tok.is(tok::identifier) && "expected an identifier");
294   IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
295                                             Tok.getLocation(),
296                                             Tok.getIdentifierInfo());
297   ConsumeToken();
298   return IL;
299 }
300
301 void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
302                                        SourceLocation AttrNameLoc,
303                                        ParsedAttributes &Attrs,
304                                        SourceLocation *EndLoc,
305                                        IdentifierInfo *ScopeName,
306                                        SourceLocation ScopeLoc,
307                                        ParsedAttr::Syntax Syntax) {
308   BalancedDelimiterTracker Parens(*this, tok::l_paren);
309   Parens.consumeOpen();
310
311   TypeResult T;
312   if (Tok.isNot(tok::r_paren))
313     T = ParseTypeName();
314
315   if (Parens.consumeClose())
316     return;
317
318   if (T.isInvalid())
319     return;
320
321   if (T.isUsable())
322     Attrs.addNewTypeAttr(&AttrName,
323                          SourceRange(AttrNameLoc, Parens.getCloseLocation()),
324                          ScopeName, ScopeLoc, T.get(), Syntax);
325   else
326     Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
327                  ScopeName, ScopeLoc, nullptr, 0, Syntax);
328 }
329
330 unsigned Parser::ParseAttributeArgsCommon(
331     IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
332     ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
333     SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
334   // Ignore the left paren location for now.
335   ConsumeParen();
336
337   bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
338   bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
339
340   // Interpret "kw_this" as an identifier if the attributed requests it.
341   if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
342     Tok.setKind(tok::identifier);
343
344   ArgsVector ArgExprs;
345   if (Tok.is(tok::identifier)) {
346     // If this attribute wants an 'identifier' argument, make it so.
347     bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
348                            attributeHasVariadicIdentifierArg(*AttrName);
349     ParsedAttr::Kind AttrKind =
350         ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
351
352     // If we don't know how to parse this attribute, but this is the only
353     // token in this argument, assume it's meant to be an identifier.
354     if (AttrKind == ParsedAttr::UnknownAttribute ||
355         AttrKind == ParsedAttr::IgnoredAttribute) {
356       const Token &Next = NextToken();
357       IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
358     }
359
360     if (IsIdentifierArg)
361       ArgExprs.push_back(ParseIdentifierLoc());
362   }
363
364   ParsedType TheParsedType;
365   if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
366     // Eat the comma.
367     if (!ArgExprs.empty())
368       ConsumeToken();
369
370     // Parse the non-empty comma-separated list of expressions.
371     do {
372       // Interpret "kw_this" as an identifier if the attributed requests it.
373       if (ChangeKWThisToIdent && Tok.is(tok::kw_this))
374         Tok.setKind(tok::identifier);
375
376       ExprResult ArgExpr;
377       if (AttributeIsTypeArgAttr) {
378         TypeResult T = ParseTypeName();
379         if (T.isInvalid()) {
380           SkipUntil(tok::r_paren, StopAtSemi);
381           return 0;
382         }
383         if (T.isUsable())
384           TheParsedType = T.get();
385         break; // FIXME: Multiple type arguments are not implemented.
386       } else if (Tok.is(tok::identifier) &&
387                  attributeHasVariadicIdentifierArg(*AttrName)) {
388         ArgExprs.push_back(ParseIdentifierLoc());
389       } else {
390         bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
391         EnterExpressionEvaluationContext Unevaluated(
392             Actions,
393             Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
394                    : Sema::ExpressionEvaluationContext::ConstantEvaluated);
395
396         ExprResult ArgExpr(
397             Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
398         if (ArgExpr.isInvalid()) {
399           SkipUntil(tok::r_paren, StopAtSemi);
400           return 0;
401         }
402         ArgExprs.push_back(ArgExpr.get());
403       }
404       // Eat the comma, move to the next argument
405     } while (TryConsumeToken(tok::comma));
406   }
407
408   SourceLocation RParen = Tok.getLocation();
409   if (!ExpectAndConsume(tok::r_paren)) {
410     SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
411
412     if (AttributeIsTypeArgAttr && !TheParsedType.get().isNull()) {
413       Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
414                            ScopeName, ScopeLoc, TheParsedType, Syntax);
415     } else {
416       Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
417                    ArgExprs.data(), ArgExprs.size(), Syntax);
418     }
419   }
420
421   if (EndLoc)
422     *EndLoc = RParen;
423
424   return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
425 }
426
427 /// Parse the arguments to a parameterized GNU attribute or
428 /// a C++11 attribute in "gnu" namespace.
429 void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
430                                    SourceLocation AttrNameLoc,
431                                    ParsedAttributes &Attrs,
432                                    SourceLocation *EndLoc,
433                                    IdentifierInfo *ScopeName,
434                                    SourceLocation ScopeLoc,
435                                    ParsedAttr::Syntax Syntax,
436                                    Declarator *D) {
437
438   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
439
440   ParsedAttr::Kind AttrKind =
441       ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
442
443   if (AttrKind == ParsedAttr::AT_Availability) {
444     ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
445                                ScopeLoc, Syntax);
446     return;
447   } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
448     ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
449                                        ScopeName, ScopeLoc, Syntax);
450     return;
451   } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
452     ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
453                                     ScopeName, ScopeLoc, Syntax);
454     return;
455   } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
456     ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
457                                      ScopeName, ScopeLoc, Syntax);
458     return;
459   } else if (attributeIsTypeArgAttr(*AttrName)) {
460     ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
461                               ScopeLoc, Syntax);
462     return;
463   }
464
465   // These may refer to the function arguments, but need to be parsed early to
466   // participate in determining whether it's a redeclaration.
467   llvm::Optional<ParseScope> PrototypeScope;
468   if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
469       D && D->isFunctionDeclarator()) {
470     DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
471     PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
472                                      Scope::FunctionDeclarationScope |
473                                      Scope::DeclScope);
474     for (unsigned i = 0; i != FTI.NumParams; ++i) {
475       ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
476       Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
477     }
478   }
479
480   ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
481                            ScopeLoc, Syntax);
482 }
483
484 unsigned Parser::ParseClangAttributeArgs(
485     IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
486     ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
487     SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
488   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
489
490   ParsedAttr::Kind AttrKind =
491       ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
492
493   switch (AttrKind) {
494   default:
495     return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
496                                     ScopeName, ScopeLoc, Syntax);
497   case ParsedAttr::AT_ExternalSourceSymbol:
498     ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
499                                        ScopeName, ScopeLoc, Syntax);
500     break;
501   case ParsedAttr::AT_Availability:
502     ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
503                                ScopeLoc, Syntax);
504     break;
505   case ParsedAttr::AT_ObjCBridgeRelated:
506     ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
507                                     ScopeName, ScopeLoc, Syntax);
508     break;
509   case ParsedAttr::AT_TypeTagForDatatype:
510     ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
511                                      ScopeName, ScopeLoc, Syntax);
512     break;
513   }
514   return !Attrs.empty() ? Attrs.begin()->getNumArgs() : 0;
515 }
516
517 bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
518                                         SourceLocation AttrNameLoc,
519                                         ParsedAttributes &Attrs) {
520   // If the attribute isn't known, we will not attempt to parse any
521   // arguments.
522   if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
523                     getTargetInfo(), getLangOpts())) {
524     // Eat the left paren, then skip to the ending right paren.
525     ConsumeParen();
526     SkipUntil(tok::r_paren);
527     return false;
528   }
529
530   SourceLocation OpenParenLoc = Tok.getLocation();
531
532   if (AttrName->getName() == "property") {
533     // The property declspec is more complex in that it can take one or two
534     // assignment expressions as a parameter, but the lhs of the assignment
535     // must be named get or put.
536
537     BalancedDelimiterTracker T(*this, tok::l_paren);
538     T.expectAndConsume(diag::err_expected_lparen_after,
539                        AttrName->getNameStart(), tok::r_paren);
540
541     enum AccessorKind {
542       AK_Invalid = -1,
543       AK_Put = 0,
544       AK_Get = 1 // indices into AccessorNames
545     };
546     IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
547     bool HasInvalidAccessor = false;
548
549     // Parse the accessor specifications.
550     while (true) {
551       // Stop if this doesn't look like an accessor spec.
552       if (!Tok.is(tok::identifier)) {
553         // If the user wrote a completely empty list, use a special diagnostic.
554         if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
555             AccessorNames[AK_Put] == nullptr &&
556             AccessorNames[AK_Get] == nullptr) {
557           Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
558           break;
559         }
560
561         Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
562         break;
563       }
564
565       AccessorKind Kind;
566       SourceLocation KindLoc = Tok.getLocation();
567       StringRef KindStr = Tok.getIdentifierInfo()->getName();
568       if (KindStr == "get") {
569         Kind = AK_Get;
570       } else if (KindStr == "put") {
571         Kind = AK_Put;
572
573         // Recover from the common mistake of using 'set' instead of 'put'.
574       } else if (KindStr == "set") {
575         Diag(KindLoc, diag::err_ms_property_has_set_accessor)
576             << FixItHint::CreateReplacement(KindLoc, "put");
577         Kind = AK_Put;
578
579         // Handle the mistake of forgetting the accessor kind by skipping
580         // this accessor.
581       } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
582         Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
583         ConsumeToken();
584         HasInvalidAccessor = true;
585         goto next_property_accessor;
586
587         // Otherwise, complain about the unknown accessor kind.
588       } else {
589         Diag(KindLoc, diag::err_ms_property_unknown_accessor);
590         HasInvalidAccessor = true;
591         Kind = AK_Invalid;
592
593         // Try to keep parsing unless it doesn't look like an accessor spec.
594         if (!NextToken().is(tok::equal))
595           break;
596       }
597
598       // Consume the identifier.
599       ConsumeToken();
600
601       // Consume the '='.
602       if (!TryConsumeToken(tok::equal)) {
603         Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
604             << KindStr;
605         break;
606       }
607
608       // Expect the method name.
609       if (!Tok.is(tok::identifier)) {
610         Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
611         break;
612       }
613
614       if (Kind == AK_Invalid) {
615         // Just drop invalid accessors.
616       } else if (AccessorNames[Kind] != nullptr) {
617         // Complain about the repeated accessor, ignore it, and keep parsing.
618         Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
619       } else {
620         AccessorNames[Kind] = Tok.getIdentifierInfo();
621       }
622       ConsumeToken();
623
624     next_property_accessor:
625       // Keep processing accessors until we run out.
626       if (TryConsumeToken(tok::comma))
627         continue;
628
629       // If we run into the ')', stop without consuming it.
630       if (Tok.is(tok::r_paren))
631         break;
632
633       Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
634       break;
635     }
636
637     // Only add the property attribute if it was well-formed.
638     if (!HasInvalidAccessor)
639       Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
640                                AccessorNames[AK_Get], AccessorNames[AK_Put],
641                                ParsedAttr::AS_Declspec);
642     T.skipToEnd();
643     return !HasInvalidAccessor;
644   }
645
646   unsigned NumArgs =
647       ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
648                                SourceLocation(), ParsedAttr::AS_Declspec);
649
650   // If this attribute's args were parsed, and it was expected to have
651   // arguments but none were provided, emit a diagnostic.
652   if (!Attrs.empty() && Attrs.begin()->getMaxArgs() && !NumArgs) {
653     Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
654     return false;
655   }
656   return true;
657 }
658
659 /// [MS] decl-specifier:
660 ///             __declspec ( extended-decl-modifier-seq )
661 ///
662 /// [MS] extended-decl-modifier-seq:
663 ///             extended-decl-modifier[opt]
664 ///             extended-decl-modifier extended-decl-modifier-seq
665 void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
666                                      SourceLocation *End) {
667   assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
668   assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
669
670   while (Tok.is(tok::kw___declspec)) {
671     ConsumeToken();
672     BalancedDelimiterTracker T(*this, tok::l_paren);
673     if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
674                            tok::r_paren))
675       return;
676
677     // An empty declspec is perfectly legal and should not warn.  Additionally,
678     // you can specify multiple attributes per declspec.
679     while (Tok.isNot(tok::r_paren)) {
680       // Attribute not present.
681       if (TryConsumeToken(tok::comma))
682         continue;
683
684       // We expect either a well-known identifier or a generic string.  Anything
685       // else is a malformed declspec.
686       bool IsString = Tok.getKind() == tok::string_literal;
687       if (!IsString && Tok.getKind() != tok::identifier &&
688           Tok.getKind() != tok::kw_restrict) {
689         Diag(Tok, diag::err_ms_declspec_type);
690         T.skipToEnd();
691         return;
692       }
693
694       IdentifierInfo *AttrName;
695       SourceLocation AttrNameLoc;
696       if (IsString) {
697         SmallString<8> StrBuffer;
698         bool Invalid = false;
699         StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
700         if (Invalid) {
701           T.skipToEnd();
702           return;
703         }
704         AttrName = PP.getIdentifierInfo(Str);
705         AttrNameLoc = ConsumeStringToken();
706       } else {
707         AttrName = Tok.getIdentifierInfo();
708         AttrNameLoc = ConsumeToken();
709       }
710
711       bool AttrHandled = false;
712
713       // Parse attribute arguments.
714       if (Tok.is(tok::l_paren))
715         AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
716       else if (AttrName->getName() == "property")
717         // The property attribute must have an argument list.
718         Diag(Tok.getLocation(), diag::err_expected_lparen_after)
719             << AttrName->getName();
720
721       if (!AttrHandled)
722         Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
723                      ParsedAttr::AS_Declspec);
724     }
725     T.consumeClose();
726     if (End)
727       *End = T.getCloseLocation();
728   }
729 }
730
731 void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
732   // Treat these like attributes
733   while (true) {
734     switch (Tok.getKind()) {
735     case tok::kw___fastcall:
736     case tok::kw___stdcall:
737     case tok::kw___thiscall:
738     case tok::kw___regcall:
739     case tok::kw___cdecl:
740     case tok::kw___vectorcall:
741     case tok::kw___ptr64:
742     case tok::kw___w64:
743     case tok::kw___ptr32:
744     case tok::kw___sptr:
745     case tok::kw___uptr: {
746       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
747       SourceLocation AttrNameLoc = ConsumeToken();
748       attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
749                    ParsedAttr::AS_Keyword);
750       break;
751     }
752     default:
753       return;
754     }
755   }
756 }
757
758 void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
759   SourceLocation StartLoc = Tok.getLocation();
760   SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
761
762   if (EndLoc.isValid()) {
763     SourceRange Range(StartLoc, EndLoc);
764     Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
765   }
766 }
767
768 SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
769   SourceLocation EndLoc;
770
771   while (true) {
772     switch (Tok.getKind()) {
773     case tok::kw_const:
774     case tok::kw_volatile:
775     case tok::kw___fastcall:
776     case tok::kw___stdcall:
777     case tok::kw___thiscall:
778     case tok::kw___cdecl:
779     case tok::kw___vectorcall:
780     case tok::kw___ptr32:
781     case tok::kw___ptr64:
782     case tok::kw___w64:
783     case tok::kw___unaligned:
784     case tok::kw___sptr:
785     case tok::kw___uptr:
786       EndLoc = ConsumeToken();
787       break;
788     default:
789       return EndLoc;
790     }
791   }
792 }
793
794 void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
795   // Treat these like attributes
796   while (Tok.is(tok::kw___pascal)) {
797     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
798     SourceLocation AttrNameLoc = ConsumeToken();
799     attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
800                  ParsedAttr::AS_Keyword);
801   }
802 }
803
804 void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
805   // Treat these like attributes
806   while (Tok.is(tok::kw___kernel)) {
807     IdentifierInfo *AttrName = Tok.getIdentifierInfo();
808     SourceLocation AttrNameLoc = ConsumeToken();
809     attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
810                  ParsedAttr::AS_Keyword);
811   }
812 }
813
814 void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
815   IdentifierInfo *AttrName = Tok.getIdentifierInfo();
816   SourceLocation AttrNameLoc = Tok.getLocation();
817   Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
818                ParsedAttr::AS_Keyword);
819 }
820
821 void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
822   // Treat these like attributes, even though they're type specifiers.
823   while (true) {
824     switch (Tok.getKind()) {
825     case tok::kw__Nonnull:
826     case tok::kw__Nullable:
827     case tok::kw__Null_unspecified: {
828       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
829       SourceLocation AttrNameLoc = ConsumeToken();
830       if (!getLangOpts().ObjC)
831         Diag(AttrNameLoc, diag::ext_nullability)
832           << AttrName;
833       attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
834                    ParsedAttr::AS_Keyword);
835       break;
836     }
837     default:
838       return;
839     }
840   }
841 }
842
843 static bool VersionNumberSeparator(const char Separator) {
844   return (Separator == '.' || Separator == '_');
845 }
846
847 /// Parse a version number.
848 ///
849 /// version:
850 ///   simple-integer
851 ///   simple-integer '.' simple-integer
852 ///   simple-integer '_' simple-integer
853 ///   simple-integer '.' simple-integer '.' simple-integer
854 ///   simple-integer '_' simple-integer '_' simple-integer
855 VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
856   Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
857
858   if (!Tok.is(tok::numeric_constant)) {
859     Diag(Tok, diag::err_expected_version);
860     SkipUntil(tok::comma, tok::r_paren,
861               StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
862     return VersionTuple();
863   }
864
865   // Parse the major (and possibly minor and subminor) versions, which
866   // are stored in the numeric constant. We utilize a quirk of the
867   // lexer, which is that it handles something like 1.2.3 as a single
868   // numeric constant, rather than two separate tokens.
869   SmallString<512> Buffer;
870   Buffer.resize(Tok.getLength()+1);
871   const char *ThisTokBegin = &Buffer[0];
872
873   // Get the spelling of the token, which eliminates trigraphs, etc.
874   bool Invalid = false;
875   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
876   if (Invalid)
877     return VersionTuple();
878
879   // Parse the major version.
880   unsigned AfterMajor = 0;
881   unsigned Major = 0;
882   while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
883     Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
884     ++AfterMajor;
885   }
886
887   if (AfterMajor == 0) {
888     Diag(Tok, diag::err_expected_version);
889     SkipUntil(tok::comma, tok::r_paren,
890               StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
891     return VersionTuple();
892   }
893
894   if (AfterMajor == ActualLength) {
895     ConsumeToken();
896
897     // We only had a single version component.
898     if (Major == 0) {
899       Diag(Tok, diag::err_zero_version);
900       return VersionTuple();
901     }
902
903     return VersionTuple(Major);
904   }
905
906   const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
907   if (!VersionNumberSeparator(AfterMajorSeparator)
908       || (AfterMajor + 1 == ActualLength)) {
909     Diag(Tok, diag::err_expected_version);
910     SkipUntil(tok::comma, tok::r_paren,
911               StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
912     return VersionTuple();
913   }
914
915   // Parse the minor version.
916   unsigned AfterMinor = AfterMajor + 1;
917   unsigned Minor = 0;
918   while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
919     Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
920     ++AfterMinor;
921   }
922
923   if (AfterMinor == ActualLength) {
924     ConsumeToken();
925
926     // We had major.minor.
927     if (Major == 0 && Minor == 0) {
928       Diag(Tok, diag::err_zero_version);
929       return VersionTuple();
930     }
931
932     return VersionTuple(Major, Minor);
933   }
934
935   const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
936   // If what follows is not a '.' or '_', we have a problem.
937   if (!VersionNumberSeparator(AfterMinorSeparator)) {
938     Diag(Tok, diag::err_expected_version);
939     SkipUntil(tok::comma, tok::r_paren,
940               StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
941     return VersionTuple();
942   }
943
944   // Warn if separators, be it '.' or '_', do not match.
945   if (AfterMajorSeparator != AfterMinorSeparator)
946     Diag(Tok, diag::warn_expected_consistent_version_separator);
947
948   // Parse the subminor version.
949   unsigned AfterSubminor = AfterMinor + 1;
950   unsigned Subminor = 0;
951   while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
952     Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
953     ++AfterSubminor;
954   }
955
956   if (AfterSubminor != ActualLength) {
957     Diag(Tok, diag::err_expected_version);
958     SkipUntil(tok::comma, tok::r_paren,
959               StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
960     return VersionTuple();
961   }
962   ConsumeToken();
963   return VersionTuple(Major, Minor, Subminor);
964 }
965
966 /// Parse the contents of the "availability" attribute.
967 ///
968 /// availability-attribute:
969 ///   'availability' '(' platform ',' opt-strict version-arg-list,
970 ///                      opt-replacement, opt-message')'
971 ///
972 /// platform:
973 ///   identifier
974 ///
975 /// opt-strict:
976 ///   'strict' ','
977 ///
978 /// version-arg-list:
979 ///   version-arg
980 ///   version-arg ',' version-arg-list
981 ///
982 /// version-arg:
983 ///   'introduced' '=' version
984 ///   'deprecated' '=' version
985 ///   'obsoleted' = version
986 ///   'unavailable'
987 /// opt-replacement:
988 ///   'replacement' '=' <string>
989 /// opt-message:
990 ///   'message' '=' <string>
991 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
992                                         SourceLocation AvailabilityLoc,
993                                         ParsedAttributes &attrs,
994                                         SourceLocation *endLoc,
995                                         IdentifierInfo *ScopeName,
996                                         SourceLocation ScopeLoc,
997                                         ParsedAttr::Syntax Syntax) {
998   enum { Introduced, Deprecated, Obsoleted, Unknown };
999   AvailabilityChange Changes[Unknown];
1000   ExprResult MessageExpr, ReplacementExpr;
1001
1002   // Opening '('.
1003   BalancedDelimiterTracker T(*this, tok::l_paren);
1004   if (T.consumeOpen()) {
1005     Diag(Tok, diag::err_expected) << tok::l_paren;
1006     return;
1007   }
1008
1009   // Parse the platform name.
1010   if (Tok.isNot(tok::identifier)) {
1011     Diag(Tok, diag::err_availability_expected_platform);
1012     SkipUntil(tok::r_paren, StopAtSemi);
1013     return;
1014   }
1015   IdentifierLoc *Platform = ParseIdentifierLoc();
1016   if (const IdentifierInfo *const Ident = Platform->Ident) {
1017     // Canonicalize platform name from "macosx" to "macos".
1018     if (Ident->getName() == "macosx")
1019       Platform->Ident = PP.getIdentifierInfo("macos");
1020     // Canonicalize platform name from "macosx_app_extension" to
1021     // "macos_app_extension".
1022     else if (Ident->getName() == "macosx_app_extension")
1023       Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1024     else
1025       Platform->Ident = PP.getIdentifierInfo(
1026           AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1027   }
1028
1029   // Parse the ',' following the platform name.
1030   if (ExpectAndConsume(tok::comma)) {
1031     SkipUntil(tok::r_paren, StopAtSemi);
1032     return;
1033   }
1034
1035   // If we haven't grabbed the pointers for the identifiers
1036   // "introduced", "deprecated", and "obsoleted", do so now.
1037   if (!Ident_introduced) {
1038     Ident_introduced = PP.getIdentifierInfo("introduced");
1039     Ident_deprecated = PP.getIdentifierInfo("deprecated");
1040     Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1041     Ident_unavailable = PP.getIdentifierInfo("unavailable");
1042     Ident_message = PP.getIdentifierInfo("message");
1043     Ident_strict = PP.getIdentifierInfo("strict");
1044     Ident_replacement = PP.getIdentifierInfo("replacement");
1045   }
1046
1047   // Parse the optional "strict", the optional "replacement" and the set of
1048   // introductions/deprecations/removals.
1049   SourceLocation UnavailableLoc, StrictLoc;
1050   do {
1051     if (Tok.isNot(tok::identifier)) {
1052       Diag(Tok, diag::err_availability_expected_change);
1053       SkipUntil(tok::r_paren, StopAtSemi);
1054       return;
1055     }
1056     IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1057     SourceLocation KeywordLoc = ConsumeToken();
1058
1059     if (Keyword == Ident_strict) {
1060       if (StrictLoc.isValid()) {
1061         Diag(KeywordLoc, diag::err_availability_redundant)
1062           << Keyword << SourceRange(StrictLoc);
1063       }
1064       StrictLoc = KeywordLoc;
1065       continue;
1066     }
1067
1068     if (Keyword == Ident_unavailable) {
1069       if (UnavailableLoc.isValid()) {
1070         Diag(KeywordLoc, diag::err_availability_redundant)
1071           << Keyword << SourceRange(UnavailableLoc);
1072       }
1073       UnavailableLoc = KeywordLoc;
1074       continue;
1075     }
1076
1077     if (Keyword == Ident_deprecated && Platform->Ident &&
1078         Platform->Ident->isStr("swift")) {
1079       // For swift, we deprecate for all versions.
1080       if (Changes[Deprecated].KeywordLoc.isValid()) {
1081         Diag(KeywordLoc, diag::err_availability_redundant)
1082           << Keyword
1083           << SourceRange(Changes[Deprecated].KeywordLoc);
1084       }
1085
1086       Changes[Deprecated].KeywordLoc = KeywordLoc;
1087       // Use a fake version here.
1088       Changes[Deprecated].Version = VersionTuple(1);
1089       continue;
1090     }
1091
1092     if (Tok.isNot(tok::equal)) {
1093       Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1094       SkipUntil(tok::r_paren, StopAtSemi);
1095       return;
1096     }
1097     ConsumeToken();
1098     if (Keyword == Ident_message || Keyword == Ident_replacement) {
1099       if (Tok.isNot(tok::string_literal)) {
1100         Diag(Tok, diag::err_expected_string_literal)
1101           << /*Source='availability attribute'*/2;
1102         SkipUntil(tok::r_paren, StopAtSemi);
1103         return;
1104       }
1105       if (Keyword == Ident_message)
1106         MessageExpr = ParseStringLiteralExpression();
1107       else
1108         ReplacementExpr = ParseStringLiteralExpression();
1109       // Also reject wide string literals.
1110       if (StringLiteral *MessageStringLiteral =
1111               cast_or_null<StringLiteral>(MessageExpr.get())) {
1112         if (MessageStringLiteral->getCharByteWidth() != 1) {
1113           Diag(MessageStringLiteral->getSourceRange().getBegin(),
1114                diag::err_expected_string_literal)
1115             << /*Source='availability attribute'*/ 2;
1116           SkipUntil(tok::r_paren, StopAtSemi);
1117           return;
1118         }
1119       }
1120       if (Keyword == Ident_message)
1121         break;
1122       else
1123         continue;
1124     }
1125
1126     // Special handling of 'NA' only when applied to introduced or
1127     // deprecated.
1128     if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
1129         Tok.is(tok::identifier)) {
1130       IdentifierInfo *NA = Tok.getIdentifierInfo();
1131       if (NA->getName() == "NA") {
1132         ConsumeToken();
1133         if (Keyword == Ident_introduced)
1134           UnavailableLoc = KeywordLoc;
1135         continue;
1136       }
1137     }
1138
1139     SourceRange VersionRange;
1140     VersionTuple Version = ParseVersionTuple(VersionRange);
1141
1142     if (Version.empty()) {
1143       SkipUntil(tok::r_paren, StopAtSemi);
1144       return;
1145     }
1146
1147     unsigned Index;
1148     if (Keyword == Ident_introduced)
1149       Index = Introduced;
1150     else if (Keyword == Ident_deprecated)
1151       Index = Deprecated;
1152     else if (Keyword == Ident_obsoleted)
1153       Index = Obsoleted;
1154     else
1155       Index = Unknown;
1156
1157     if (Index < Unknown) {
1158       if (!Changes[Index].KeywordLoc.isInvalid()) {
1159         Diag(KeywordLoc, diag::err_availability_redundant)
1160           << Keyword
1161           << SourceRange(Changes[Index].KeywordLoc,
1162                          Changes[Index].VersionRange.getEnd());
1163       }
1164
1165       Changes[Index].KeywordLoc = KeywordLoc;
1166       Changes[Index].Version = Version;
1167       Changes[Index].VersionRange = VersionRange;
1168     } else {
1169       Diag(KeywordLoc, diag::err_availability_unknown_change)
1170         << Keyword << VersionRange;
1171     }
1172
1173   } while (TryConsumeToken(tok::comma));
1174
1175   // Closing ')'.
1176   if (T.consumeClose())
1177     return;
1178
1179   if (endLoc)
1180     *endLoc = T.getCloseLocation();
1181
1182   // The 'unavailable' availability cannot be combined with any other
1183   // availability changes. Make sure that hasn't happened.
1184   if (UnavailableLoc.isValid()) {
1185     bool Complained = false;
1186     for (unsigned Index = Introduced; Index != Unknown; ++Index) {
1187       if (Changes[Index].KeywordLoc.isValid()) {
1188         if (!Complained) {
1189           Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1190             << SourceRange(Changes[Index].KeywordLoc,
1191                            Changes[Index].VersionRange.getEnd());
1192           Complained = true;
1193         }
1194
1195         // Clear out the availability.
1196         Changes[Index] = AvailabilityChange();
1197       }
1198     }
1199   }
1200
1201   // Record this attribute
1202   attrs.addNew(&Availability,
1203                SourceRange(AvailabilityLoc, T.getCloseLocation()),
1204                ScopeName, ScopeLoc,
1205                Platform,
1206                Changes[Introduced],
1207                Changes[Deprecated],
1208                Changes[Obsoleted],
1209                UnavailableLoc, MessageExpr.get(),
1210                Syntax, StrictLoc, ReplacementExpr.get());
1211 }
1212
1213 /// Parse the contents of the "external_source_symbol" attribute.
1214 ///
1215 /// external-source-symbol-attribute:
1216 ///   'external_source_symbol' '(' keyword-arg-list ')'
1217 ///
1218 /// keyword-arg-list:
1219 ///   keyword-arg
1220 ///   keyword-arg ',' keyword-arg-list
1221 ///
1222 /// keyword-arg:
1223 ///   'language' '=' <string>
1224 ///   'defined_in' '=' <string>
1225 ///   'generated_declaration'
1226 void Parser::ParseExternalSourceSymbolAttribute(
1227     IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1228     ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1229     SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1230   // Opening '('.
1231   BalancedDelimiterTracker T(*this, tok::l_paren);
1232   if (T.expectAndConsume())
1233     return;
1234
1235   // Initialize the pointers for the keyword identifiers when required.
1236   if (!Ident_language) {
1237     Ident_language = PP.getIdentifierInfo("language");
1238     Ident_defined_in = PP.getIdentifierInfo("defined_in");
1239     Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1240   }
1241
1242   ExprResult Language;
1243   bool HasLanguage = false;
1244   ExprResult DefinedInExpr;
1245   bool HasDefinedIn = false;
1246   IdentifierLoc *GeneratedDeclaration = nullptr;
1247
1248   // Parse the language/defined_in/generated_declaration keywords
1249   do {
1250     if (Tok.isNot(tok::identifier)) {
1251       Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1252       SkipUntil(tok::r_paren, StopAtSemi);
1253       return;
1254     }
1255
1256     SourceLocation KeywordLoc = Tok.getLocation();
1257     IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1258     if (Keyword == Ident_generated_declaration) {
1259       if (GeneratedDeclaration) {
1260         Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1261         SkipUntil(tok::r_paren, StopAtSemi);
1262         return;
1263       }
1264       GeneratedDeclaration = ParseIdentifierLoc();
1265       continue;
1266     }
1267
1268     if (Keyword != Ident_language && Keyword != Ident_defined_in) {
1269       Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1270       SkipUntil(tok::r_paren, StopAtSemi);
1271       return;
1272     }
1273
1274     ConsumeToken();
1275     if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1276                          Keyword->getName())) {
1277       SkipUntil(tok::r_paren, StopAtSemi);
1278       return;
1279     }
1280
1281     bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1282     if (Keyword == Ident_language)
1283       HasLanguage = true;
1284     else
1285       HasDefinedIn = true;
1286
1287     if (Tok.isNot(tok::string_literal)) {
1288       Diag(Tok, diag::err_expected_string_literal)
1289           << /*Source='external_source_symbol attribute'*/ 3
1290           << /*language | source container*/ (Keyword != Ident_language);
1291       SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1292       continue;
1293     }
1294     if (Keyword == Ident_language) {
1295       if (HadLanguage) {
1296         Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1297             << Keyword;
1298         ParseStringLiteralExpression();
1299         continue;
1300       }
1301       Language = ParseStringLiteralExpression();
1302     } else {
1303       assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1304       if (HadDefinedIn) {
1305         Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1306             << Keyword;
1307         ParseStringLiteralExpression();
1308         continue;
1309       }
1310       DefinedInExpr = ParseStringLiteralExpression();
1311     }
1312   } while (TryConsumeToken(tok::comma));
1313
1314   // Closing ')'.
1315   if (T.consumeClose())
1316     return;
1317   if (EndLoc)
1318     *EndLoc = T.getCloseLocation();
1319
1320   ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1321                       GeneratedDeclaration};
1322   Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1323                ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1324 }
1325
1326 /// Parse the contents of the "objc_bridge_related" attribute.
1327 /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1328 /// related_class:
1329 ///     Identifier
1330 ///
1331 /// opt-class_method:
1332 ///     Identifier: | <empty>
1333 ///
1334 /// opt-instance_method:
1335 ///     Identifier | <empty>
1336 ///
1337 void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1338                                 SourceLocation ObjCBridgeRelatedLoc,
1339                                 ParsedAttributes &attrs,
1340                                 SourceLocation *endLoc,
1341                                 IdentifierInfo *ScopeName,
1342                                 SourceLocation ScopeLoc,
1343                                 ParsedAttr::Syntax Syntax) {
1344   // Opening '('.
1345   BalancedDelimiterTracker T(*this, tok::l_paren);
1346   if (T.consumeOpen()) {
1347     Diag(Tok, diag::err_expected) << tok::l_paren;
1348     return;
1349   }
1350
1351   // Parse the related class name.
1352   if (Tok.isNot(tok::identifier)) {
1353     Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1354     SkipUntil(tok::r_paren, StopAtSemi);
1355     return;
1356   }
1357   IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1358   if (ExpectAndConsume(tok::comma)) {
1359     SkipUntil(tok::r_paren, StopAtSemi);
1360     return;
1361   }
1362
1363   // Parse class method name.  It's non-optional in the sense that a trailing
1364   // comma is required, but it can be the empty string, and then we record a
1365   // nullptr.
1366   IdentifierLoc *ClassMethod = nullptr;
1367   if (Tok.is(tok::identifier)) {
1368     ClassMethod = ParseIdentifierLoc();
1369     if (!TryConsumeToken(tok::colon)) {
1370       Diag(Tok, diag::err_objcbridge_related_selector_name);
1371       SkipUntil(tok::r_paren, StopAtSemi);
1372       return;
1373     }
1374   }
1375   if (!TryConsumeToken(tok::comma)) {
1376     if (Tok.is(tok::colon))
1377       Diag(Tok, diag::err_objcbridge_related_selector_name);
1378     else
1379       Diag(Tok, diag::err_expected) << tok::comma;
1380     SkipUntil(tok::r_paren, StopAtSemi);
1381     return;
1382   }
1383
1384   // Parse instance method name.  Also non-optional but empty string is
1385   // permitted.
1386   IdentifierLoc *InstanceMethod = nullptr;
1387   if (Tok.is(tok::identifier))
1388     InstanceMethod = ParseIdentifierLoc();
1389   else if (Tok.isNot(tok::r_paren)) {
1390     Diag(Tok, diag::err_expected) << tok::r_paren;
1391     SkipUntil(tok::r_paren, StopAtSemi);
1392     return;
1393   }
1394
1395   // Closing ')'.
1396   if (T.consumeClose())
1397     return;
1398
1399   if (endLoc)
1400     *endLoc = T.getCloseLocation();
1401
1402   // Record this attribute
1403   attrs.addNew(&ObjCBridgeRelated,
1404                SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1405                ScopeName, ScopeLoc,
1406                RelatedClass,
1407                ClassMethod,
1408                InstanceMethod,
1409                Syntax);
1410 }
1411
1412 // Late Parsed Attributes:
1413 // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
1414
1415 void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
1416
1417 void Parser::LateParsedClass::ParseLexedAttributes() {
1418   Self->ParseLexedAttributes(*Class);
1419 }
1420
1421 void Parser::LateParsedAttribute::ParseLexedAttributes() {
1422   Self->ParseLexedAttribute(*this, true, false);
1423 }
1424
1425 /// Wrapper class which calls ParseLexedAttribute, after setting up the
1426 /// scope appropriately.
1427 void Parser::ParseLexedAttributes(ParsingClass &Class) {
1428   // Deal with templates
1429   // FIXME: Test cases to make sure this does the right thing for templates.
1430   bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
1431   ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
1432                                 HasTemplateScope);
1433   if (HasTemplateScope)
1434     Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
1435
1436   // Set or update the scope flags.
1437   bool AlreadyHasClassScope = Class.TopLevelClass;
1438   unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
1439   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
1440   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
1441
1442   // Enter the scope of nested classes
1443   if (!AlreadyHasClassScope)
1444     Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
1445                                                 Class.TagOrTemplate);
1446   if (!Class.LateParsedDeclarations.empty()) {
1447     for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
1448       Class.LateParsedDeclarations[i]->ParseLexedAttributes();
1449     }
1450   }
1451
1452   if (!AlreadyHasClassScope)
1453     Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
1454                                                  Class.TagOrTemplate);
1455 }
1456
1457 /// Parse all attributes in LAs, and attach them to Decl D.
1458 void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
1459                                      bool EnterScope, bool OnDefinition) {
1460   assert(LAs.parseSoon() &&
1461          "Attribute list should be marked for immediate parsing.");
1462   for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
1463     if (D)
1464       LAs[i]->addDecl(D);
1465     ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
1466     delete LAs[i];
1467   }
1468   LAs.clear();
1469 }
1470
1471 /// Finish parsing an attribute for which parsing was delayed.
1472 /// This will be called at the end of parsing a class declaration
1473 /// for each LateParsedAttribute. We consume the saved tokens and
1474 /// create an attribute with the arguments filled in. We add this
1475 /// to the Attribute list for the decl.
1476 void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
1477                                  bool EnterScope, bool OnDefinition) {
1478   // Create a fake EOF so that attribute parsing won't go off the end of the
1479   // attribute.
1480   Token AttrEnd;
1481   AttrEnd.startToken();
1482   AttrEnd.setKind(tok::eof);
1483   AttrEnd.setLocation(Tok.getLocation());
1484   AttrEnd.setEofData(LA.Toks.data());
1485   LA.Toks.push_back(AttrEnd);
1486
1487   // Append the current token at the end of the new token stream so that it
1488   // doesn't get lost.
1489   LA.Toks.push_back(Tok);
1490   PP.EnterTokenStream(LA.Toks, true, /*IsReinject=*/true);
1491   // Consume the previously pushed token.
1492   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1493
1494   ParsedAttributes Attrs(AttrFactory);
1495   SourceLocation endLoc;
1496
1497   if (LA.Decls.size() > 0) {
1498     Decl *D = LA.Decls[0];
1499     NamedDecl *ND  = dyn_cast<NamedDecl>(D);
1500     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
1501
1502     // Allow 'this' within late-parsed attributes.
1503     Sema::CXXThisScopeRAII ThisScope(Actions, RD, Qualifiers(),
1504                                      ND && ND->isCXXInstanceMember());
1505
1506     if (LA.Decls.size() == 1) {
1507       // If the Decl is templatized, add template parameters to scope.
1508       bool HasTemplateScope = EnterScope && D->isTemplateDecl();
1509       ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
1510       if (HasTemplateScope)
1511         Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
1512
1513       // If the Decl is on a function, add function parameters to the scope.
1514       bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
1515       ParseScope FnScope(
1516           this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
1517           HasFunScope);
1518       if (HasFunScope)
1519         Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
1520
1521       ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1522                             nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1523                             nullptr);
1524
1525       if (HasFunScope) {
1526         Actions.ActOnExitFunctionContext();
1527         FnScope.Exit();  // Pop scope, and remove Decls from IdResolver
1528       }
1529       if (HasTemplateScope) {
1530         TempScope.Exit();
1531       }
1532     } else {
1533       // If there are multiple decls, then the decl cannot be within the
1534       // function scope.
1535       ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
1536                             nullptr, SourceLocation(), ParsedAttr::AS_GNU,
1537                             nullptr);
1538     }
1539   } else {
1540     Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
1541   }
1542
1543   if (OnDefinition && !Attrs.empty() && !Attrs.begin()->isCXX11Attribute() &&
1544       Attrs.begin()->isKnownToGCC())
1545     Diag(Tok, diag::warn_attribute_on_function_definition)
1546       << &LA.AttrName;
1547
1548   for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
1549     Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
1550
1551   // Due to a parsing error, we either went over the cached tokens or
1552   // there are still cached tokens left, so we skip the leftover tokens.
1553   while (Tok.isNot(tok::eof))
1554     ConsumeAnyToken();
1555
1556   if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
1557     ConsumeAnyToken();
1558 }
1559
1560 void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1561                                               SourceLocation AttrNameLoc,
1562                                               ParsedAttributes &Attrs,
1563                                               SourceLocation *EndLoc,
1564                                               IdentifierInfo *ScopeName,
1565                                               SourceLocation ScopeLoc,
1566                                               ParsedAttr::Syntax Syntax) {
1567   assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1568
1569   BalancedDelimiterTracker T(*this, tok::l_paren);
1570   T.consumeOpen();
1571
1572   if (Tok.isNot(tok::identifier)) {
1573     Diag(Tok, diag::err_expected) << tok::identifier;
1574     T.skipToEnd();
1575     return;
1576   }
1577   IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1578
1579   if (ExpectAndConsume(tok::comma)) {
1580     T.skipToEnd();
1581     return;
1582   }
1583
1584   SourceRange MatchingCTypeRange;
1585   TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1586   if (MatchingCType.isInvalid()) {
1587     T.skipToEnd();
1588     return;
1589   }
1590
1591   bool LayoutCompatible = false;
1592   bool MustBeNull = false;
1593   while (TryConsumeToken(tok::comma)) {
1594     if (Tok.isNot(tok::identifier)) {
1595       Diag(Tok, diag::err_expected) << tok::identifier;
1596       T.skipToEnd();
1597       return;
1598     }
1599     IdentifierInfo *Flag = Tok.getIdentifierInfo();
1600     if (Flag->isStr("layout_compatible"))
1601       LayoutCompatible = true;
1602     else if (Flag->isStr("must_be_null"))
1603       MustBeNull = true;
1604     else {
1605       Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1606       T.skipToEnd();
1607       return;
1608     }
1609     ConsumeToken(); // consume flag
1610   }
1611
1612   if (!T.consumeClose()) {
1613     Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1614                                    ArgumentKind, MatchingCType.get(),
1615                                    LayoutCompatible, MustBeNull, Syntax);
1616   }
1617
1618   if (EndLoc)
1619     *EndLoc = T.getCloseLocation();
1620 }
1621
1622 /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1623 /// of a C++11 attribute-specifier in a location where an attribute is not
1624 /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1625 /// situation.
1626 ///
1627 /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1628 /// this doesn't appear to actually be an attribute-specifier, and the caller
1629 /// should try to parse it.
1630 bool Parser::DiagnoseProhibitedCXX11Attribute() {
1631   assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1632
1633   switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1634   case CAK_NotAttributeSpecifier:
1635     // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1636     return false;
1637
1638   case CAK_InvalidAttributeSpecifier:
1639     Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1640     return false;
1641
1642   case CAK_AttributeSpecifier:
1643     // Parse and discard the attributes.
1644     SourceLocation BeginLoc = ConsumeBracket();
1645     ConsumeBracket();
1646     SkipUntil(tok::r_square);
1647     assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1648     SourceLocation EndLoc = ConsumeBracket();
1649     Diag(BeginLoc, diag::err_attributes_not_allowed)
1650       << SourceRange(BeginLoc, EndLoc);
1651     return true;
1652   }
1653   llvm_unreachable("All cases handled above.");
1654 }
1655
1656 /// We have found the opening square brackets of a C++11
1657 /// attribute-specifier in a location where an attribute is not permitted, but
1658 /// we know where the attributes ought to be written. Parse them anyway, and
1659 /// provide a fixit moving them to the right place.
1660 void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1661                                              SourceLocation CorrectLocation) {
1662   assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1663          Tok.is(tok::kw_alignas));
1664
1665   // Consume the attributes.
1666   SourceLocation Loc = Tok.getLocation();
1667   ParseCXX11Attributes(Attrs);
1668   CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1669   // FIXME: use err_attributes_misplaced
1670   Diag(Loc, diag::err_attributes_not_allowed)
1671     << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1672     << FixItHint::CreateRemoval(AttrRange);
1673 }
1674
1675 void Parser::DiagnoseProhibitedAttributes(
1676     const SourceRange &Range, const SourceLocation CorrectLocation) {
1677   if (CorrectLocation.isValid()) {
1678     CharSourceRange AttrRange(Range, true);
1679     Diag(CorrectLocation, diag::err_attributes_misplaced)
1680         << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1681         << FixItHint::CreateRemoval(AttrRange);
1682   } else
1683     Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1684 }
1685
1686 void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1687                                      unsigned DiagID) {
1688   for (const ParsedAttr &AL : Attrs) {
1689     if (!AL.isCXX11Attribute() && !AL.isC2xAttribute())
1690       continue;
1691     if (AL.getKind() == ParsedAttr::UnknownAttribute)
1692       Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
1693     else {
1694       Diag(AL.getLoc(), DiagID) << AL;
1695       AL.setInvalid();
1696     }
1697   }
1698 }
1699
1700 // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1701 // applies to var, not the type Foo.
1702 // As an exception to the rule, __declspec(align(...)) before the
1703 // class-key affects the type instead of the variable.
1704 // Also, Microsoft-style [attributes] seem to affect the type instead of the
1705 // variable.
1706 // This function moves attributes that should apply to the type off DS to Attrs.
1707 void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1708                                             DeclSpec &DS,
1709                                             Sema::TagUseKind TUK) {
1710   if (TUK == Sema::TUK_Reference)
1711     return;
1712
1713   llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1714
1715   for (ParsedAttr &AL : DS.getAttributes()) {
1716     if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1717          AL.isDeclspecAttribute()) ||
1718         AL.isMicrosoftAttribute())
1719       ToBeMoved.push_back(&AL);
1720   }
1721
1722   for (ParsedAttr *AL : ToBeMoved) {
1723     DS.getAttributes().remove(AL);
1724     Attrs.addAtEnd(AL);
1725   }
1726 }
1727
1728 /// ParseDeclaration - Parse a full 'declaration', which consists of
1729 /// declaration-specifiers, some number of declarators, and a semicolon.
1730 /// 'Context' should be a DeclaratorContext value.  This returns the
1731 /// location of the semicolon in DeclEnd.
1732 ///
1733 ///       declaration: [C99 6.7]
1734 ///         block-declaration ->
1735 ///           simple-declaration
1736 ///           others                   [FIXME]
1737 /// [C++]   template-declaration
1738 /// [C++]   namespace-definition
1739 /// [C++]   using-directive
1740 /// [C++]   using-declaration
1741 /// [C++11/C11] static_assert-declaration
1742 ///         others... [FIXME]
1743 ///
1744 Parser::DeclGroupPtrTy
1745 Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1746                          ParsedAttributesWithRange &attrs,
1747                          SourceLocation *DeclSpecStart) {
1748   ParenBraceBracketBalancer BalancerRAIIObj(*this);
1749   // Must temporarily exit the objective-c container scope for
1750   // parsing c none objective-c decls.
1751   ObjCDeclContextSwitch ObjCDC(*this);
1752
1753   Decl *SingleDecl = nullptr;
1754   switch (Tok.getKind()) {
1755   case tok::kw_template:
1756   case tok::kw_export:
1757     ProhibitAttributes(attrs);
1758     SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1759     break;
1760   case tok::kw_inline:
1761     // Could be the start of an inline namespace. Allowed as an ext in C++03.
1762     if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1763       ProhibitAttributes(attrs);
1764       SourceLocation InlineLoc = ConsumeToken();
1765       return ParseNamespace(Context, DeclEnd, InlineLoc);
1766     }
1767     return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1768                                   DeclSpecStart);
1769   case tok::kw_namespace:
1770     ProhibitAttributes(attrs);
1771     return ParseNamespace(Context, DeclEnd);
1772   case tok::kw_using:
1773     return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1774                                             DeclEnd, attrs);
1775   case tok::kw_static_assert:
1776   case tok::kw__Static_assert:
1777     ProhibitAttributes(attrs);
1778     SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1779     break;
1780   default:
1781     return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1782                                   DeclSpecStart);
1783   }
1784
1785   // This routine returns a DeclGroup, if the thing we parsed only contains a
1786   // single decl, convert it now.
1787   return Actions.ConvertDeclToDeclGroup(SingleDecl);
1788 }
1789
1790 ///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1791 ///         declaration-specifiers init-declarator-list[opt] ';'
1792 /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1793 ///             init-declarator-list ';'
1794 ///[C90/C++]init-declarator-list ';'                             [TODO]
1795 /// [OMP]   threadprivate-directive
1796 /// [OMP]   allocate-directive                                   [TODO]
1797 ///
1798 ///       for-range-declaration: [C++11 6.5p1: stmt.ranged]
1799 ///         attribute-specifier-seq[opt] type-specifier-seq declarator
1800 ///
1801 /// If RequireSemi is false, this does not check for a ';' at the end of the
1802 /// declaration.  If it is true, it checks for and eats it.
1803 ///
1804 /// If FRI is non-null, we might be parsing a for-range-declaration instead
1805 /// of a simple-declaration. If we find that we are, we also parse the
1806 /// for-range-initializer, and place it here.
1807 ///
1808 /// DeclSpecStart is used when decl-specifiers are parsed before parsing
1809 /// the Declaration. The SourceLocation for this Decl is set to
1810 /// DeclSpecStart if DeclSpecStart is non-null.
1811 Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1812     DeclaratorContext Context, SourceLocation &DeclEnd,
1813     ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1814     SourceLocation *DeclSpecStart) {
1815   // Parse the common declaration-specifiers piece.
1816   ParsingDeclSpec DS(*this);
1817
1818   DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1819   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1820
1821   // If we had a free-standing type definition with a missing semicolon, we
1822   // may get this far before the problem becomes obvious.
1823   if (DS.hasTagDefinition() &&
1824       DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
1825     return nullptr;
1826
1827   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1828   // declaration-specifiers init-declarator-list[opt] ';'
1829   if (Tok.is(tok::semi)) {
1830     ProhibitAttributes(Attrs);
1831     DeclEnd = Tok.getLocation();
1832     if (RequireSemi) ConsumeToken();
1833     RecordDecl *AnonRecord = nullptr;
1834     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1835                                                        DS, AnonRecord);
1836     DS.complete(TheDecl);
1837     if (AnonRecord) {
1838       Decl* decls[] = {AnonRecord, TheDecl};
1839       return Actions.BuildDeclaratorGroup(decls);
1840     }
1841     return Actions.ConvertDeclToDeclGroup(TheDecl);
1842   }
1843
1844   if (DeclSpecStart)
1845     DS.SetRangeStart(*DeclSpecStart);
1846
1847   DS.takeAttributesFrom(Attrs);
1848   return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1849 }
1850
1851 /// Returns true if this might be the start of a declarator, or a common typo
1852 /// for a declarator.
1853 bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1854   switch (Tok.getKind()) {
1855   case tok::annot_cxxscope:
1856   case tok::annot_template_id:
1857   case tok::caret:
1858   case tok::code_completion:
1859   case tok::coloncolon:
1860   case tok::ellipsis:
1861   case tok::kw___attribute:
1862   case tok::kw_operator:
1863   case tok::l_paren:
1864   case tok::star:
1865     return true;
1866
1867   case tok::amp:
1868   case tok::ampamp:
1869     return getLangOpts().CPlusPlus;
1870
1871   case tok::l_square: // Might be an attribute on an unnamed bit-field.
1872     return Context == DeclaratorContext::MemberContext &&
1873            getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square);
1874
1875   case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1876     return Context == DeclaratorContext::MemberContext ||
1877            getLangOpts().CPlusPlus;
1878
1879   case tok::identifier:
1880     switch (NextToken().getKind()) {
1881     case tok::code_completion:
1882     case tok::coloncolon:
1883     case tok::comma:
1884     case tok::equal:
1885     case tok::equalequal: // Might be a typo for '='.
1886     case tok::kw_alignas:
1887     case tok::kw_asm:
1888     case tok::kw___attribute:
1889     case tok::l_brace:
1890     case tok::l_paren:
1891     case tok::l_square:
1892     case tok::less:
1893     case tok::r_brace:
1894     case tok::r_paren:
1895     case tok::r_square:
1896     case tok::semi:
1897       return true;
1898
1899     case tok::colon:
1900       // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1901       // and in block scope it's probably a label. Inside a class definition,
1902       // this is a bit-field.
1903       return Context == DeclaratorContext::MemberContext ||
1904              (getLangOpts().CPlusPlus &&
1905               Context == DeclaratorContext::FileContext);
1906
1907     case tok::identifier: // Possible virt-specifier.
1908       return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
1909
1910     default:
1911       return false;
1912     }
1913
1914   default:
1915     return false;
1916   }
1917 }
1918
1919 /// Skip until we reach something which seems like a sensible place to pick
1920 /// up parsing after a malformed declaration. This will sometimes stop sooner
1921 /// than SkipUntil(tok::r_brace) would, but will never stop later.
1922 void Parser::SkipMalformedDecl() {
1923   while (true) {
1924     switch (Tok.getKind()) {
1925     case tok::l_brace:
1926       // Skip until matching }, then stop. We've probably skipped over
1927       // a malformed class or function definition or similar.
1928       ConsumeBrace();
1929       SkipUntil(tok::r_brace);
1930       if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1931         // This declaration isn't over yet. Keep skipping.
1932         continue;
1933       }
1934       TryConsumeToken(tok::semi);
1935       return;
1936
1937     case tok::l_square:
1938       ConsumeBracket();
1939       SkipUntil(tok::r_square);
1940       continue;
1941
1942     case tok::l_paren:
1943       ConsumeParen();
1944       SkipUntil(tok::r_paren);
1945       continue;
1946
1947     case tok::r_brace:
1948       return;
1949
1950     case tok::semi:
1951       ConsumeToken();
1952       return;
1953
1954     case tok::kw_inline:
1955       // 'inline namespace' at the start of a line is almost certainly
1956       // a good place to pick back up parsing, except in an Objective-C
1957       // @interface context.
1958       if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
1959           (!ParsingInObjCContainer || CurParsedObjCImpl))
1960         return;
1961       break;
1962
1963     case tok::kw_namespace:
1964       // 'namespace' at the start of a line is almost certainly a good
1965       // place to pick back up parsing, except in an Objective-C
1966       // @interface context.
1967       if (Tok.isAtStartOfLine() &&
1968           (!ParsingInObjCContainer || CurParsedObjCImpl))
1969         return;
1970       break;
1971
1972     case tok::at:
1973       // @end is very much like } in Objective-C contexts.
1974       if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1975           ParsingInObjCContainer)
1976         return;
1977       break;
1978
1979     case tok::minus:
1980     case tok::plus:
1981       // - and + probably start new method declarations in Objective-C contexts.
1982       if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
1983         return;
1984       break;
1985
1986     case tok::eof:
1987     case tok::annot_module_begin:
1988     case tok::annot_module_end:
1989     case tok::annot_module_include:
1990       return;
1991
1992     default:
1993       break;
1994     }
1995
1996     ConsumeAnyToken();
1997   }
1998 }
1999
2000 /// ParseDeclGroup - Having concluded that this is either a function
2001 /// definition or a group of object declarations, actually parse the
2002 /// result.
2003 Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
2004                                               DeclaratorContext Context,
2005                                               SourceLocation *DeclEnd,
2006                                               ForRangeInit *FRI) {
2007   // Parse the first declarator.
2008   ParsingDeclarator D(*this, DS, Context);
2009   ParseDeclarator(D);
2010
2011   // Bail out if the first declarator didn't seem well-formed.
2012   if (!D.hasName() && !D.mayOmitIdentifier()) {
2013     SkipMalformedDecl();
2014     return nullptr;
2015   }
2016
2017   if (Tok.is(tok::kw_requires))
2018     ParseTrailingRequiresClause(D);
2019
2020   // Save late-parsed attributes for now; they need to be parsed in the
2021   // appropriate function scope after the function Decl has been constructed.
2022   // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2023   LateParsedAttrList LateParsedAttrs(true);
2024   if (D.isFunctionDeclarator()) {
2025     MaybeParseGNUAttributes(D, &LateParsedAttrs);
2026
2027     // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2028     // attribute. If we find the keyword here, tell the user to put it
2029     // at the start instead.
2030     if (Tok.is(tok::kw__Noreturn)) {
2031       SourceLocation Loc = ConsumeToken();
2032       const char *PrevSpec;
2033       unsigned DiagID;
2034
2035       // We can offer a fixit if it's valid to mark this function as _Noreturn
2036       // and we don't have any other declarators in this declaration.
2037       bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2038       MaybeParseGNUAttributes(D, &LateParsedAttrs);
2039       Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2040
2041       Diag(Loc, diag::err_c11_noreturn_misplaced)
2042           << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2043           << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2044                     : FixItHint());
2045     }
2046   }
2047
2048   // Check to see if we have a function *definition* which must have a body.
2049   if (D.isFunctionDeclarator() &&
2050       // Look at the next token to make sure that this isn't a function
2051       // declaration.  We have to check this because __attribute__ might be the
2052       // start of a function definition in GCC-extended K&R C.
2053       !isDeclarationAfterDeclarator()) {
2054
2055     // Function definitions are only allowed at file scope and in C++ classes.
2056     // The C++ inline method definition case is handled elsewhere, so we only
2057     // need to handle the file scope definition case.
2058     if (Context == DeclaratorContext::FileContext) {
2059       if (isStartOfFunctionDefinition(D)) {
2060         if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2061           Diag(Tok, diag::err_function_declared_typedef);
2062
2063           // Recover by treating the 'typedef' as spurious.
2064           DS.ClearStorageClassSpecs();
2065         }
2066
2067         Decl *TheDecl =
2068           ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2069         return Actions.ConvertDeclToDeclGroup(TheDecl);
2070       }
2071
2072       if (isDeclarationSpecifier()) {
2073         // If there is an invalid declaration specifier right after the
2074         // function prototype, then we must be in a missing semicolon case
2075         // where this isn't actually a body.  Just fall through into the code
2076         // that handles it as a prototype, and let the top-level code handle
2077         // the erroneous declspec where it would otherwise expect a comma or
2078         // semicolon.
2079       } else {
2080         Diag(Tok, diag::err_expected_fn_body);
2081         SkipUntil(tok::semi);
2082         return nullptr;
2083       }
2084     } else {
2085       if (Tok.is(tok::l_brace)) {
2086         Diag(Tok, diag::err_function_definition_not_allowed);
2087         SkipMalformedDecl();
2088         return nullptr;
2089       }
2090     }
2091   }
2092
2093   if (ParseAsmAttributesAfterDeclarator(D))
2094     return nullptr;
2095
2096   // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2097   // must parse and analyze the for-range-initializer before the declaration is
2098   // analyzed.
2099   //
2100   // Handle the Objective-C for-in loop variable similarly, although we
2101   // don't need to parse the container in advance.
2102   if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2103     bool IsForRangeLoop = false;
2104     if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2105       IsForRangeLoop = true;
2106       if (getLangOpts().OpenMP)
2107         Actions.startOpenMPCXXRangeFor();
2108       if (Tok.is(tok::l_brace))
2109         FRI->RangeExpr = ParseBraceInitializer();
2110       else
2111         FRI->RangeExpr = ParseExpression();
2112     }
2113
2114     Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2115     if (IsForRangeLoop) {
2116       Actions.ActOnCXXForRangeDecl(ThisDecl);
2117     } else {
2118       // Obj-C for loop
2119       if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2120         VD->setObjCForDecl(true);
2121     }
2122     Actions.FinalizeDeclaration(ThisDecl);
2123     D.complete(ThisDecl);
2124     return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2125   }
2126
2127   SmallVector<Decl *, 8> DeclsInGroup;
2128   Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2129       D, ParsedTemplateInfo(), FRI);
2130   if (LateParsedAttrs.size() > 0)
2131     ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2132   D.complete(FirstDecl);
2133   if (FirstDecl)
2134     DeclsInGroup.push_back(FirstDecl);
2135
2136   bool ExpectSemi = Context != DeclaratorContext::ForContext;
2137
2138   // If we don't have a comma, it is either the end of the list (a ';') or an
2139   // error, bail out.
2140   SourceLocation CommaLoc;
2141   while (TryConsumeToken(tok::comma, CommaLoc)) {
2142     if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2143       // This comma was followed by a line-break and something which can't be
2144       // the start of a declarator. The comma was probably a typo for a
2145       // semicolon.
2146       Diag(CommaLoc, diag::err_expected_semi_declaration)
2147         << FixItHint::CreateReplacement(CommaLoc, ";");
2148       ExpectSemi = false;
2149       break;
2150     }
2151
2152     // Parse the next declarator.
2153     D.clear();
2154     D.setCommaLoc(CommaLoc);
2155
2156     // Accept attributes in an init-declarator.  In the first declarator in a
2157     // declaration, these would be part of the declspec.  In subsequent
2158     // declarators, they become part of the declarator itself, so that they
2159     // don't apply to declarators after *this* one.  Examples:
2160     //    short __attribute__((common)) var;    -> declspec
2161     //    short var __attribute__((common));    -> declarator
2162     //    short x, __attribute__((common)) var;    -> declarator
2163     MaybeParseGNUAttributes(D);
2164
2165     // MSVC parses but ignores qualifiers after the comma as an extension.
2166     if (getLangOpts().MicrosoftExt)
2167       DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2168
2169     ParseDeclarator(D);
2170     if (!D.isInvalidType()) {
2171       // C++2a [dcl.decl]p1
2172       //    init-declarator:
2173       //              declarator initializer[opt]
2174       //        declarator requires-clause
2175       if (Tok.is(tok::kw_requires))
2176         ParseTrailingRequiresClause(D);
2177       Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2178       D.complete(ThisDecl);
2179       if (ThisDecl)
2180         DeclsInGroup.push_back(ThisDecl);
2181     }
2182   }
2183
2184   if (DeclEnd)
2185     *DeclEnd = Tok.getLocation();
2186
2187   if (ExpectSemi &&
2188       ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2189                            ? diag::err_invalid_token_after_toplevel_declarator
2190                            : diag::err_expected_semi_declaration)) {
2191     // Okay, there was no semicolon and one was expected.  If we see a
2192     // declaration specifier, just assume it was missing and continue parsing.
2193     // Otherwise things are very confused and we skip to recover.
2194     if (!isDeclarationSpecifier()) {
2195       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2196       TryConsumeToken(tok::semi);
2197     }
2198   }
2199
2200   return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2201 }
2202
2203 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2204 /// declarator. Returns true on an error.
2205 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2206   // If a simple-asm-expr is present, parse it.
2207   if (Tok.is(tok::kw_asm)) {
2208     SourceLocation Loc;
2209     ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2210     if (AsmLabel.isInvalid()) {
2211       SkipUntil(tok::semi, StopBeforeMatch);
2212       return true;
2213     }
2214
2215     D.setAsmLabel(AsmLabel.get());
2216     D.SetRangeEnd(Loc);
2217   }
2218
2219   MaybeParseGNUAttributes(D);
2220   return false;
2221 }
2222
2223 /// Parse 'declaration' after parsing 'declaration-specifiers
2224 /// declarator'. This method parses the remainder of the declaration
2225 /// (including any attributes or initializer, among other things) and
2226 /// finalizes the declaration.
2227 ///
2228 ///       init-declarator: [C99 6.7]
2229 ///         declarator
2230 ///         declarator '=' initializer
2231 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
2232 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2233 /// [C++]   declarator initializer[opt]
2234 ///
2235 /// [C++] initializer:
2236 /// [C++]   '=' initializer-clause
2237 /// [C++]   '(' expression-list ')'
2238 /// [C++0x] '=' 'default'                                                [TODO]
2239 /// [C++0x] '=' 'delete'
2240 /// [C++0x] braced-init-list
2241 ///
2242 /// According to the standard grammar, =default and =delete are function
2243 /// definitions, but that definitely doesn't fit with the parser here.
2244 ///
2245 Decl *Parser::ParseDeclarationAfterDeclarator(
2246     Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2247   if (ParseAsmAttributesAfterDeclarator(D))
2248     return nullptr;
2249
2250   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2251 }
2252
2253 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2254     Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2255   // RAII type used to track whether we're inside an initializer.
2256   struct InitializerScopeRAII {
2257     Parser &P;
2258     Declarator &D;
2259     Decl *ThisDecl;
2260
2261     InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2262         : P(P), D(D), ThisDecl(ThisDecl) {
2263       if (ThisDecl && P.getLangOpts().CPlusPlus) {
2264         Scope *S = nullptr;
2265         if (D.getCXXScopeSpec().isSet()) {
2266           P.EnterScope(0);
2267           S = P.getCurScope();
2268         }
2269         P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2270       }
2271     }
2272     ~InitializerScopeRAII() { pop(); }
2273     void pop() {
2274       if (ThisDecl && P.getLangOpts().CPlusPlus) {
2275         Scope *S = nullptr;
2276         if (D.getCXXScopeSpec().isSet())
2277           S = P.getCurScope();
2278         P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2279         if (S)
2280           P.ExitScope();
2281       }
2282       ThisDecl = nullptr;
2283     }
2284   };
2285
2286   // Inform the current actions module that we just parsed this declarator.
2287   Decl *ThisDecl = nullptr;
2288   switch (TemplateInfo.Kind) {
2289   case ParsedTemplateInfo::NonTemplate:
2290     ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2291     break;
2292
2293   case ParsedTemplateInfo::Template:
2294   case ParsedTemplateInfo::ExplicitSpecialization: {
2295     ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2296                                                *TemplateInfo.TemplateParams,
2297                                                D);
2298     if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2299       // Re-direct this decl to refer to the templated decl so that we can
2300       // initialize it.
2301       ThisDecl = VT->getTemplatedDecl();
2302     break;
2303   }
2304   case ParsedTemplateInfo::ExplicitInstantiation: {
2305     if (Tok.is(tok::semi)) {
2306       DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2307           getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2308       if (ThisRes.isInvalid()) {
2309         SkipUntil(tok::semi, StopBeforeMatch);
2310         return nullptr;
2311       }
2312       ThisDecl = ThisRes.get();
2313     } else {
2314       // FIXME: This check should be for a variable template instantiation only.
2315
2316       // Check that this is a valid instantiation
2317       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2318         // If the declarator-id is not a template-id, issue a diagnostic and
2319         // recover by ignoring the 'template' keyword.
2320         Diag(Tok, diag::err_template_defn_explicit_instantiation)
2321             << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2322         ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2323       } else {
2324         SourceLocation LAngleLoc =
2325             PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2326         Diag(D.getIdentifierLoc(),
2327              diag::err_explicit_instantiation_with_definition)
2328             << SourceRange(TemplateInfo.TemplateLoc)
2329             << FixItHint::CreateInsertion(LAngleLoc, "<>");
2330
2331         // Recover as if it were an explicit specialization.
2332         TemplateParameterLists FakedParamLists;
2333         FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2334             0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2335             LAngleLoc, nullptr));
2336
2337         ThisDecl =
2338             Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2339       }
2340     }
2341     break;
2342     }
2343   }
2344
2345   // Parse declarator '=' initializer.
2346   // If a '==' or '+=' is found, suggest a fixit to '='.
2347   if (isTokenEqualOrEqualTypo()) {
2348     SourceLocation EqualLoc = ConsumeToken();
2349
2350     if (Tok.is(tok::kw_delete)) {
2351       if (D.isFunctionDeclarator())
2352         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2353           << 1 /* delete */;
2354       else
2355         Diag(ConsumeToken(), diag::err_deleted_non_function);
2356     } else if (Tok.is(tok::kw_default)) {
2357       if (D.isFunctionDeclarator())
2358         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2359           << 0 /* default */;
2360       else
2361         Diag(ConsumeToken(), diag::err_default_special_members)
2362             << getLangOpts().CPlusPlus2a;
2363     } else {
2364       InitializerScopeRAII InitScope(*this, D, ThisDecl);
2365
2366       if (Tok.is(tok::code_completion)) {
2367         Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2368         Actions.FinalizeDeclaration(ThisDecl);
2369         cutOffParsing();
2370         return nullptr;
2371       }
2372
2373       PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2374       ExprResult Init = ParseInitializer();
2375
2376       // If this is the only decl in (possibly) range based for statement,
2377       // our best guess is that the user meant ':' instead of '='.
2378       if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2379         Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2380             << FixItHint::CreateReplacement(EqualLoc, ":");
2381         // We are trying to stop parser from looking for ';' in this for
2382         // statement, therefore preventing spurious errors to be issued.
2383         FRI->ColonLoc = EqualLoc;
2384         Init = ExprError();
2385         FRI->RangeExpr = Init;
2386       }
2387
2388       InitScope.pop();
2389
2390       if (Init.isInvalid()) {
2391         SmallVector<tok::TokenKind, 2> StopTokens;
2392         StopTokens.push_back(tok::comma);
2393         if (D.getContext() == DeclaratorContext::ForContext ||
2394             D.getContext() == DeclaratorContext::InitStmtContext)
2395           StopTokens.push_back(tok::r_paren);
2396         SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2397         Actions.ActOnInitializerError(ThisDecl);
2398       } else
2399         Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2400                                      /*DirectInit=*/false);
2401     }
2402   } else if (Tok.is(tok::l_paren)) {
2403     // Parse C++ direct initializer: '(' expression-list ')'
2404     BalancedDelimiterTracker T(*this, tok::l_paren);
2405     T.consumeOpen();
2406
2407     ExprVector Exprs;
2408     CommaLocsTy CommaLocs;
2409
2410     InitializerScopeRAII InitScope(*this, D, ThisDecl);
2411
2412     auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2413     auto RunSignatureHelp = [&]() {
2414       QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2415           getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2416           ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2417       CalledSignatureHelp = true;
2418       return PreferredType;
2419     };
2420     auto SetPreferredType = [&] {
2421       PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2422     };
2423
2424     llvm::function_ref<void()> ExpressionStarts;
2425     if (ThisVarDecl) {
2426       // ParseExpressionList can sometimes succeed even when ThisDecl is not
2427       // VarDecl. This is an error and it is reported in a call to
2428       // Actions.ActOnInitializerError(). However, we call
2429       // ProduceConstructorSignatureHelp only on VarDecls.
2430       ExpressionStarts = SetPreferredType;
2431     }
2432     if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2433       if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2434         Actions.ProduceConstructorSignatureHelp(
2435             getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2436             ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2437         CalledSignatureHelp = true;
2438       }
2439       Actions.ActOnInitializerError(ThisDecl);
2440       SkipUntil(tok::r_paren, StopAtSemi);
2441     } else {
2442       // Match the ')'.
2443       T.consumeClose();
2444
2445       assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2446              "Unexpected number of commas!");
2447
2448       InitScope.pop();
2449
2450       ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2451                                                           T.getCloseLocation(),
2452                                                           Exprs);
2453       Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2454                                    /*DirectInit=*/true);
2455     }
2456   } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2457              (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2458     // Parse C++0x braced-init-list.
2459     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2460
2461     InitializerScopeRAII InitScope(*this, D, ThisDecl);
2462
2463     ExprResult Init(ParseBraceInitializer());
2464
2465     InitScope.pop();
2466
2467     if (Init.isInvalid()) {
2468       Actions.ActOnInitializerError(ThisDecl);
2469     } else
2470       Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2471
2472   } else {
2473     Actions.ActOnUninitializedDecl(ThisDecl);
2474   }
2475
2476   Actions.FinalizeDeclaration(ThisDecl);
2477
2478   return ThisDecl;
2479 }
2480
2481 /// ParseSpecifierQualifierList
2482 ///        specifier-qualifier-list:
2483 ///          type-specifier specifier-qualifier-list[opt]
2484 ///          type-qualifier specifier-qualifier-list[opt]
2485 /// [GNU]    attributes     specifier-qualifier-list[opt]
2486 ///
2487 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2488                                          DeclSpecContext DSC) {
2489   /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
2490   /// parse declaration-specifiers and complain about extra stuff.
2491   /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2492   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2493
2494   // Validate declspec for type-name.
2495   unsigned Specs = DS.getParsedSpecifiers();
2496   if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2497     Diag(Tok, diag::err_expected_type);
2498     DS.SetTypeSpecError();
2499   } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2500     Diag(Tok, diag::err_typename_requires_specqual);
2501     if (!DS.hasTypeSpecifier())
2502       DS.SetTypeSpecError();
2503   }
2504
2505   // Issue diagnostic and remove storage class if present.
2506   if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2507     if (DS.getStorageClassSpecLoc().isValid())
2508       Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2509     else
2510       Diag(DS.getThreadStorageClassSpecLoc(),
2511            diag::err_typename_invalid_storageclass);
2512     DS.ClearStorageClassSpecs();
2513   }
2514
2515   // Issue diagnostic and remove function specifier if present.
2516   if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2517     if (DS.isInlineSpecified())
2518       Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2519     if (DS.isVirtualSpecified())
2520       Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2521     if (DS.hasExplicitSpecifier())
2522       Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2523     DS.ClearFunctionSpecs();
2524   }
2525
2526   // Issue diagnostic and remove constexpr specifier if present.
2527   if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2528     Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2529         << DS.getConstexprSpecifier();
2530     DS.ClearConstexprSpec();
2531   }
2532 }
2533
2534 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2535 /// specified token is valid after the identifier in a declarator which
2536 /// immediately follows the declspec.  For example, these things are valid:
2537 ///
2538 ///      int x   [             4];         // direct-declarator
2539 ///      int x   (             int y);     // direct-declarator
2540 ///  int(int x   )                         // direct-declarator
2541 ///      int x   ;                         // simple-declaration
2542 ///      int x   =             17;         // init-declarator-list
2543 ///      int x   ,             y;          // init-declarator-list
2544 ///      int x   __asm__       ("foo");    // init-declarator-list
2545 ///      int x   :             4;          // struct-declarator
2546 ///      int x   {             5};         // C++'0x unified initializers
2547 ///
2548 /// This is not, because 'x' does not immediately follow the declspec (though
2549 /// ')' happens to be valid anyway).
2550 ///    int (x)
2551 ///
2552 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2553   return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2554                    tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2555                    tok::colon);
2556 }
2557
2558 /// ParseImplicitInt - This method is called when we have an non-typename
2559 /// identifier in a declspec (which normally terminates the decl spec) when
2560 /// the declspec has no type specifier.  In this case, the declspec is either
2561 /// malformed or is "implicit int" (in K&R and C89).
2562 ///
2563 /// This method handles diagnosing this prettily and returns false if the
2564 /// declspec is done being processed.  If it recovers and thinks there may be
2565 /// other pieces of declspec after it, it returns true.
2566 ///
2567 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2568                               const ParsedTemplateInfo &TemplateInfo,
2569                               AccessSpecifier AS, DeclSpecContext DSC,
2570                               ParsedAttributesWithRange &Attrs) {
2571   assert(Tok.is(tok::identifier) && "should have identifier");
2572
2573   SourceLocation Loc = Tok.getLocation();
2574   // If we see an identifier that is not a type name, we normally would
2575   // parse it as the identifier being declared.  However, when a typename
2576   // is typo'd or the definition is not included, this will incorrectly
2577   // parse the typename as the identifier name and fall over misparsing
2578   // later parts of the diagnostic.
2579   //
2580   // As such, we try to do some look-ahead in cases where this would
2581   // otherwise be an "implicit-int" case to see if this is invalid.  For
2582   // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2583   // an identifier with implicit int, we'd get a parse error because the
2584   // next token is obviously invalid for a type.  Parse these as a case
2585   // with an invalid type specifier.
2586   assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2587
2588   // Since we know that this either implicit int (which is rare) or an
2589   // error, do lookahead to try to do better recovery. This never applies
2590   // within a type specifier. Outside of C++, we allow this even if the
2591   // language doesn't "officially" support implicit int -- we support
2592   // implicit int as an extension in C99 and C11.
2593   if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2594       isValidAfterIdentifierInDeclarator(NextToken())) {
2595     // If this token is valid for implicit int, e.g. "static x = 4", then
2596     // we just avoid eating the identifier, so it will be parsed as the
2597     // identifier in the declarator.
2598     return false;
2599   }
2600
2601   // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2602   // for incomplete declarations such as `pipe p`.
2603   if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2604     return false;
2605
2606   if (getLangOpts().CPlusPlus &&
2607       DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2608     // Don't require a type specifier if we have the 'auto' storage class
2609     // specifier in C++98 -- we'll promote it to a type specifier.
2610     if (SS)
2611       AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2612     return false;
2613   }
2614
2615   if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2616       getLangOpts().MSVCCompat) {
2617     // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2618     // Give Sema a chance to recover if we are in a template with dependent base
2619     // classes.
2620     if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2621             *Tok.getIdentifierInfo(), Tok.getLocation(),
2622             DSC == DeclSpecContext::DSC_template_type_arg)) {
2623       const char *PrevSpec;
2624       unsigned DiagID;
2625       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2626                          Actions.getASTContext().getPrintingPolicy());
2627       DS.SetRangeEnd(Tok.getLocation());
2628       ConsumeToken();
2629       return false;
2630     }
2631   }
2632
2633   // Otherwise, if we don't consume this token, we are going to emit an
2634   // error anyway.  Try to recover from various common problems.  Check
2635   // to see if this was a reference to a tag name without a tag specified.
2636   // This is a common problem in C (saying 'foo' instead of 'struct foo').
2637   //
2638   // C++ doesn't need this, and isTagName doesn't take SS.
2639   if (SS == nullptr) {
2640     const char *TagName = nullptr, *FixitTagName = nullptr;
2641     tok::TokenKind TagKind = tok::unknown;
2642
2643     switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2644       default: break;
2645       case DeclSpec::TST_enum:
2646         TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2647       case DeclSpec::TST_union:
2648         TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2649       case DeclSpec::TST_struct:
2650         TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2651       case DeclSpec::TST_interface:
2652         TagName="__interface"; FixitTagName = "__interface ";
2653         TagKind=tok::kw___interface;break;
2654       case DeclSpec::TST_class:
2655         TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2656     }
2657
2658     if (TagName) {
2659       IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2660       LookupResult R(Actions, TokenName, SourceLocation(),
2661                      Sema::LookupOrdinaryName);
2662
2663       Diag(Loc, diag::err_use_of_tag_name_without_tag)
2664         << TokenName << TagName << getLangOpts().CPlusPlus
2665         << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2666
2667       if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2668         for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2669              I != IEnd; ++I)
2670           Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2671             << TokenName << TagName;
2672       }
2673
2674       // Parse this as a tag as if the missing tag were present.
2675       if (TagKind == tok::kw_enum)
2676         ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2677                            DeclSpecContext::DSC_normal);
2678       else
2679         ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2680                             /*EnteringContext*/ false,
2681                             DeclSpecContext::DSC_normal, Attrs);
2682       return true;
2683     }
2684   }
2685
2686   // Determine whether this identifier could plausibly be the name of something
2687   // being declared (with a missing type).
2688   if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2689                                 DSC == DeclSpecContext::DSC_class)) {
2690     // Look ahead to the next token to try to figure out what this declaration
2691     // was supposed to be.
2692     switch (NextToken().getKind()) {
2693     case tok::l_paren: {
2694       // static x(4); // 'x' is not a type
2695       // x(int n);    // 'x' is not a type
2696       // x (*p)[];    // 'x' is a type
2697       //
2698       // Since we're in an error case, we can afford to perform a tentative
2699       // parse to determine which case we're in.
2700       TentativeParsingAction PA(*this);
2701       ConsumeToken();
2702       TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2703       PA.Revert();
2704
2705       if (TPR != TPResult::False) {
2706         // The identifier is followed by a parenthesized declarator.
2707         // It's supposed to be a type.
2708         break;
2709       }
2710
2711       // If we're in a context where we could be declaring a constructor,
2712       // check whether this is a constructor declaration with a bogus name.
2713       if (DSC == DeclSpecContext::DSC_class ||
2714           (DSC == DeclSpecContext::DSC_top_level && SS)) {
2715         IdentifierInfo *II = Tok.getIdentifierInfo();
2716         if (Actions.isCurrentClassNameTypo(II, SS)) {
2717           Diag(Loc, diag::err_constructor_bad_name)
2718             << Tok.getIdentifierInfo() << II
2719             << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2720           Tok.setIdentifierInfo(II);
2721         }
2722       }
2723       // Fall through.
2724       LLVM_FALLTHROUGH;
2725     }
2726     case tok::comma:
2727     case tok::equal:
2728     case tok::kw_asm:
2729     case tok::l_brace:
2730     case tok::l_square:
2731     case tok::semi:
2732       // This looks like a variable or function declaration. The type is
2733       // probably missing. We're done parsing decl-specifiers.
2734       // But only if we are not in a function prototype scope.
2735       if (getCurScope()->isFunctionPrototypeScope())
2736         break;
2737       if (SS)
2738         AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2739       return false;
2740
2741     default:
2742       // This is probably supposed to be a type. This includes cases like:
2743       //   int f(itn);
2744       //   struct S { unsinged : 4; };
2745       break;
2746     }
2747   }
2748
2749   // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2750   // and attempt to recover.
2751   ParsedType T;
2752   IdentifierInfo *II = Tok.getIdentifierInfo();
2753   bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2754   Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2755                                   IsTemplateName);
2756   if (T) {
2757     // The action has suggested that the type T could be used. Set that as
2758     // the type in the declaration specifiers, consume the would-be type
2759     // name token, and we're done.
2760     const char *PrevSpec;
2761     unsigned DiagID;
2762     DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2763                        Actions.getASTContext().getPrintingPolicy());
2764     DS.SetRangeEnd(Tok.getLocation());
2765     ConsumeToken();
2766     // There may be other declaration specifiers after this.
2767     return true;
2768   } else if (II != Tok.getIdentifierInfo()) {
2769     // If no type was suggested, the correction is to a keyword
2770     Tok.setKind(II->getTokenID());
2771     // There may be other declaration specifiers after this.
2772     return true;
2773   }
2774
2775   // Otherwise, the action had no suggestion for us.  Mark this as an error.
2776   DS.SetTypeSpecError();
2777   DS.SetRangeEnd(Tok.getLocation());
2778   ConsumeToken();
2779
2780   // Eat any following template arguments.
2781   if (IsTemplateName) {
2782     SourceLocation LAngle, RAngle;
2783     TemplateArgList Args;
2784     ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2785   }
2786
2787   // TODO: Could inject an invalid typedef decl in an enclosing scope to
2788   // avoid rippling error messages on subsequent uses of the same type,
2789   // could be useful if #include was forgotten.
2790   return true;
2791 }
2792
2793 /// Determine the declaration specifier context from the declarator
2794 /// context.
2795 ///
2796 /// \param Context the declarator context, which is one of the
2797 /// DeclaratorContext enumerator values.
2798 Parser::DeclSpecContext
2799 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2800   if (Context == DeclaratorContext::MemberContext)
2801     return DeclSpecContext::DSC_class;
2802   if (Context == DeclaratorContext::FileContext)
2803     return DeclSpecContext::DSC_top_level;
2804   if (Context == DeclaratorContext::TemplateParamContext)
2805     return DeclSpecContext::DSC_template_param;
2806   if (Context == DeclaratorContext::TemplateArgContext ||
2807       Context == DeclaratorContext::TemplateTypeArgContext)
2808     return DeclSpecContext::DSC_template_type_arg;
2809   if (Context == DeclaratorContext::TrailingReturnContext ||
2810       Context == DeclaratorContext::TrailingReturnVarContext)
2811     return DeclSpecContext::DSC_trailing;
2812   if (Context == DeclaratorContext::AliasDeclContext ||
2813       Context == DeclaratorContext::AliasTemplateContext)
2814     return DeclSpecContext::DSC_alias_declaration;
2815   return DeclSpecContext::DSC_normal;
2816 }
2817
2818 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2819 ///
2820 /// FIXME: Simply returns an alignof() expression if the argument is a
2821 /// type. Ideally, the type should be propagated directly into Sema.
2822 ///
2823 /// [C11]   type-id
2824 /// [C11]   constant-expression
2825 /// [C++0x] type-id ...[opt]
2826 /// [C++0x] assignment-expression ...[opt]
2827 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2828                                       SourceLocation &EllipsisLoc) {
2829   ExprResult ER;
2830   if (isTypeIdInParens()) {
2831     SourceLocation TypeLoc = Tok.getLocation();
2832     ParsedType Ty = ParseTypeName().get();
2833     SourceRange TypeRange(Start, Tok.getLocation());
2834     ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2835                                                Ty.getAsOpaquePtr(), TypeRange);
2836   } else
2837     ER = ParseConstantExpression();
2838
2839   if (getLangOpts().CPlusPlus11)
2840     TryConsumeToken(tok::ellipsis, EllipsisLoc);
2841
2842   return ER;
2843 }
2844
2845 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2846 /// attribute to Attrs.
2847 ///
2848 /// alignment-specifier:
2849 /// [C11]   '_Alignas' '(' type-id ')'
2850 /// [C11]   '_Alignas' '(' constant-expression ')'
2851 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2852 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2853 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2854                                      SourceLocation *EndLoc) {
2855   assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2856          "Not an alignment-specifier!");
2857
2858   IdentifierInfo *KWName = Tok.getIdentifierInfo();
2859   SourceLocation KWLoc = ConsumeToken();
2860
2861   BalancedDelimiterTracker T(*this, tok::l_paren);
2862   if (T.expectAndConsume())
2863     return;
2864
2865   SourceLocation EllipsisLoc;
2866   ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2867   if (ArgExpr.isInvalid()) {
2868     T.skipToEnd();
2869     return;
2870   }
2871
2872   T.consumeClose();
2873   if (EndLoc)
2874     *EndLoc = T.getCloseLocation();
2875
2876   ArgsVector ArgExprs;
2877   ArgExprs.push_back(ArgExpr.get());
2878   Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2879                ParsedAttr::AS_Keyword, EllipsisLoc);
2880 }
2881
2882 /// Determine whether we're looking at something that might be a declarator
2883 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2884 /// diagnose a missing semicolon after a prior tag definition in the decl
2885 /// specifier.
2886 ///
2887 /// \return \c true if an error occurred and this can't be any kind of
2888 /// declaration.
2889 bool
2890 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2891                                               DeclSpecContext DSContext,
2892                                               LateParsedAttrList *LateAttrs) {
2893   assert(DS.hasTagDefinition() && "shouldn't call this");
2894
2895   bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2896                           DSContext == DeclSpecContext::DSC_top_level);
2897
2898   if (getLangOpts().CPlusPlus &&
2899       Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2900                   tok::annot_template_id) &&
2901       TryAnnotateCXXScopeToken(EnteringContext)) {
2902     SkipMalformedDecl();
2903     return true;
2904   }
2905
2906   bool HasScope = Tok.is(tok::annot_cxxscope);
2907   // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2908   Token AfterScope = HasScope ? NextToken() : Tok;
2909
2910   // Determine whether the following tokens could possibly be a
2911   // declarator.
2912   bool MightBeDeclarator = true;
2913   if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2914     // A declarator-id can't start with 'typename'.
2915     MightBeDeclarator = false;
2916   } else if (AfterScope.is(tok::annot_template_id)) {
2917     // If we have a type expressed as a template-id, this cannot be a
2918     // declarator-id (such a type cannot be redeclared in a simple-declaration).
2919     TemplateIdAnnotation *Annot =
2920         static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2921     if (Annot->Kind == TNK_Type_template)
2922       MightBeDeclarator = false;
2923   } else if (AfterScope.is(tok::identifier)) {
2924     const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2925
2926     // These tokens cannot come after the declarator-id in a
2927     // simple-declaration, and are likely to come after a type-specifier.
2928     if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2929                      tok::annot_cxxscope, tok::coloncolon)) {
2930       // Missing a semicolon.
2931       MightBeDeclarator = false;
2932     } else if (HasScope) {
2933       // If the declarator-id has a scope specifier, it must redeclare a
2934       // previously-declared entity. If that's a type (and this is not a
2935       // typedef), that's an error.
2936       CXXScopeSpec SS;
2937       Actions.RestoreNestedNameSpecifierAnnotation(
2938           Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2939       IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2940       Sema::NameClassification Classification = Actions.ClassifyName(
2941           getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2942           /*CCC=*/nullptr);
2943       switch (Classification.getKind()) {
2944       case Sema::NC_Error:
2945         SkipMalformedDecl();
2946         return true;
2947
2948       case Sema::NC_Keyword:
2949         llvm_unreachable("typo correction is not possible here");
2950
2951       case Sema::NC_Type:
2952       case Sema::NC_TypeTemplate:
2953       case Sema::NC_UndeclaredNonType:
2954       case Sema::NC_UndeclaredTemplate:
2955         // Not a previously-declared non-type entity.
2956         MightBeDeclarator = false;
2957         break;
2958
2959       case Sema::NC_Unknown:
2960       case Sema::NC_NonType:
2961       case Sema::NC_DependentNonType:
2962       case Sema::NC_ContextIndependentExpr:
2963       case Sema::NC_VarTemplate:
2964       case Sema::NC_FunctionTemplate:
2965         // Might be a redeclaration of a prior entity.
2966         break;
2967       }
2968     }
2969   }
2970
2971   if (MightBeDeclarator)
2972     return false;
2973
2974   const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2975   Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2976        diag::err_expected_after)
2977       << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2978
2979   // Try to recover from the typo, by dropping the tag definition and parsing
2980   // the problematic tokens as a type.
2981   //
2982   // FIXME: Split the DeclSpec into pieces for the standalone
2983   // declaration and pieces for the following declaration, instead
2984   // of assuming that all the other pieces attach to new declaration,
2985   // and call ParsedFreeStandingDeclSpec as appropriate.
2986   DS.ClearTypeSpecType();
2987   ParsedTemplateInfo NotATemplate;
2988   ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2989   return false;
2990 }
2991
2992 // Choose the apprpriate diagnostic error for why fixed point types are
2993 // disabled, set the previous specifier, and mark as invalid.
2994 static void SetupFixedPointError(const LangOptions &LangOpts,
2995                                  const char *&PrevSpec, unsigned &DiagID,
2996                                  bool &isInvalid) {
2997   assert(!LangOpts.FixedPoint);
2998   DiagID = diag::err_fixed_point_not_enabled;
2999   PrevSpec = "";  // Not used by diagnostic
3000   isInvalid = true;
3001 }
3002
3003 /// ParseDeclarationSpecifiers
3004 ///       declaration-specifiers: [C99 6.7]
3005 ///         storage-class-specifier declaration-specifiers[opt]
3006 ///         type-specifier declaration-specifiers[opt]
3007 /// [C99]   function-specifier declaration-specifiers[opt]
3008 /// [C11]   alignment-specifier declaration-specifiers[opt]
3009 /// [GNU]   attributes declaration-specifiers[opt]
3010 /// [Clang] '__module_private__' declaration-specifiers[opt]
3011 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3012 ///
3013 ///       storage-class-specifier: [C99 6.7.1]
3014 ///         'typedef'
3015 ///         'extern'
3016 ///         'static'
3017 ///         'auto'
3018 ///         'register'
3019 /// [C++]   'mutable'
3020 /// [C++11] 'thread_local'
3021 /// [C11]   '_Thread_local'
3022 /// [GNU]   '__thread'
3023 ///       function-specifier: [C99 6.7.4]
3024 /// [C99]   'inline'
3025 /// [C++]   'virtual'
3026 /// [C++]   'explicit'
3027 /// [OpenCL] '__kernel'
3028 ///       'friend': [C++ dcl.friend]
3029 ///       'constexpr': [C++0x dcl.constexpr]
3030 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3031                                         const ParsedTemplateInfo &TemplateInfo,
3032                                         AccessSpecifier AS,
3033                                         DeclSpecContext DSContext,
3034                                         LateParsedAttrList *LateAttrs) {
3035   if (DS.getSourceRange().isInvalid()) {
3036     // Start the range at the current token but make the end of the range
3037     // invalid.  This will make the entire range invalid unless we successfully
3038     // consume a token.
3039     DS.SetRangeStart(Tok.getLocation());
3040     DS.SetRangeEnd(SourceLocation());
3041   }
3042
3043   bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3044                           DSContext == DeclSpecContext::DSC_top_level);
3045   bool AttrsLastTime = false;
3046   ParsedAttributesWithRange attrs(AttrFactory);
3047   // We use Sema's policy to get bool macros right.
3048   PrintingPolicy Policy = Actions.getPrintingPolicy();
3049   while (1) {
3050     bool isInvalid = false;
3051     bool isStorageClass = false;
3052     const char *PrevSpec = nullptr;
3053     unsigned DiagID = 0;
3054
3055     // This value needs to be set to the location of the last token if the last
3056     // token of the specifier is already consumed.
3057     SourceLocation ConsumedEnd;
3058
3059     // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3060     // implementation for VS2013 uses _Atomic as an identifier for one of the
3061     // classes in <atomic>.
3062     //
3063     // A typedef declaration containing _Atomic<...> is among the places where
3064     // the class is used.  If we are currently parsing such a declaration, treat
3065     // the token as an identifier.
3066     if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3067         DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3068         !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3069       Tok.setKind(tok::identifier);
3070
3071     SourceLocation Loc = Tok.getLocation();
3072
3073     switch (Tok.getKind()) {
3074     default:
3075     DoneWithDeclSpec:
3076       if (!AttrsLastTime)
3077         ProhibitAttributes(attrs);
3078       else {
3079         // Reject C++11 attributes that appertain to decl specifiers as
3080         // we don't support any C++11 attributes that appertain to decl
3081         // specifiers. This also conforms to what g++ 4.8 is doing.
3082         ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3083
3084         DS.takeAttributesFrom(attrs);
3085       }
3086
3087       // If this is not a declaration specifier token, we're done reading decl
3088       // specifiers.  First verify that DeclSpec's are consistent.
3089       DS.Finish(Actions, Policy);
3090       return;
3091
3092     case tok::l_square:
3093     case tok::kw_alignas:
3094       if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3095         goto DoneWithDeclSpec;
3096
3097       ProhibitAttributes(attrs);
3098       // FIXME: It would be good to recover by accepting the attributes,
3099       //        but attempting to do that now would cause serious
3100       //        madness in terms of diagnostics.
3101       attrs.clear();
3102       attrs.Range = SourceRange();
3103
3104       ParseCXX11Attributes(attrs);
3105       AttrsLastTime = true;
3106       continue;
3107
3108     case tok::code_completion: {
3109       Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3110       if (DS.hasTypeSpecifier()) {
3111         bool AllowNonIdentifiers
3112           = (getCurScope()->getFlags() & (Scope::ControlScope |
3113                                           Scope::BlockScope |
3114                                           Scope::TemplateParamScope |
3115                                           Scope::FunctionPrototypeScope |
3116                                           Scope::AtCatchScope)) == 0;
3117         bool AllowNestedNameSpecifiers
3118           = DSContext == DeclSpecContext::DSC_top_level ||
3119             (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3120
3121         Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3122                                      AllowNonIdentifiers,
3123                                      AllowNestedNameSpecifiers);
3124         return cutOffParsing();
3125       }
3126
3127       if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3128         CCC = Sema::PCC_LocalDeclarationSpecifiers;
3129       else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3130         CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3131                                                       : Sema::PCC_Template;
3132       else if (DSContext == DeclSpecContext::DSC_class)
3133         CCC = Sema::PCC_Class;
3134       else if (CurParsedObjCImpl)
3135         CCC = Sema::PCC_ObjCImplementation;
3136
3137       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3138       return cutOffParsing();
3139     }
3140
3141     case tok::coloncolon: // ::foo::bar
3142       // C++ scope specifier.  Annotate and loop, or bail out on error.
3143       if (TryAnnotateCXXScopeToken(EnteringContext)) {
3144         if (!DS.hasTypeSpecifier())
3145           DS.SetTypeSpecError();
3146         goto DoneWithDeclSpec;
3147       }
3148       if (Tok.is(tok::coloncolon)) // ::new or ::delete
3149         goto DoneWithDeclSpec;
3150       continue;
3151
3152     case tok::annot_cxxscope: {
3153       if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3154         goto DoneWithDeclSpec;
3155
3156       CXXScopeSpec SS;
3157       Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3158                                                    Tok.getAnnotationRange(),
3159                                                    SS);
3160
3161       // We are looking for a qualified typename.
3162       Token Next = NextToken();
3163       if (Next.is(tok::annot_template_id) &&
3164           static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3165             ->Kind == TNK_Type_template) {
3166         // We have a qualified template-id, e.g., N::A<int>
3167
3168         // If this would be a valid constructor declaration with template
3169         // arguments, we will reject the attempt to form an invalid type-id
3170         // referring to the injected-class-name when we annotate the token,
3171         // per C++ [class.qual]p2.
3172         //
3173         // To improve diagnostics for this case, parse the declaration as a
3174         // constructor (and reject the extra template arguments later).
3175         TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3176         if ((DSContext == DeclSpecContext::DSC_top_level ||
3177              DSContext == DeclSpecContext::DSC_class) &&
3178             TemplateId->Name &&
3179             Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3180             isConstructorDeclarator(/*Unqualified*/ false)) {
3181           // The user meant this to be an out-of-line constructor
3182           // definition, but template arguments are not allowed
3183           // there.  Just allow this as a constructor; we'll
3184           // complain about it later.
3185           goto DoneWithDeclSpec;
3186         }
3187
3188         DS.getTypeSpecScope() = SS;
3189         ConsumeAnnotationToken(); // The C++ scope.
3190         assert(Tok.is(tok::annot_template_id) &&
3191                "ParseOptionalCXXScopeSpecifier not working");
3192         AnnotateTemplateIdTokenAsType();
3193         continue;
3194       }
3195
3196       if (Next.is(tok::annot_typename)) {
3197         DS.getTypeSpecScope() = SS;
3198         ConsumeAnnotationToken(); // The C++ scope.
3199         if (Tok.getAnnotationValue()) {
3200           ParsedType T = getTypeAnnotation(Tok);
3201           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3202                                          Tok.getAnnotationEndLoc(),
3203                                          PrevSpec, DiagID, T, Policy);
3204           if (isInvalid)
3205             break;
3206         }
3207         else
3208           DS.SetTypeSpecError();
3209         DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3210         ConsumeAnnotationToken(); // The typename
3211       }
3212
3213       if (Next.isNot(tok::identifier))
3214         goto DoneWithDeclSpec;
3215
3216       // Check whether this is a constructor declaration. If we're in a
3217       // context where the identifier could be a class name, and it has the
3218       // shape of a constructor declaration, process it as one.
3219       if ((DSContext == DeclSpecContext::DSC_top_level ||
3220            DSContext == DeclSpecContext::DSC_class) &&
3221           Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3222                                      &SS) &&
3223           isConstructorDeclarator(/*Unqualified*/ false))
3224         goto DoneWithDeclSpec;
3225
3226       ParsedType TypeRep =
3227           Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3228                               getCurScope(), &SS, false, false, nullptr,
3229                               /*IsCtorOrDtorName=*/false,
3230                               /*WantNontrivialTypeSourceInfo=*/true,
3231                               isClassTemplateDeductionContext(DSContext));
3232
3233       // If the referenced identifier is not a type, then this declspec is
3234       // erroneous: We already checked about that it has no type specifier, and
3235       // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3236       // typename.
3237       if (!TypeRep) {
3238         // Eat the scope spec so the identifier is current.
3239         ConsumeAnnotationToken();
3240         ParsedAttributesWithRange Attrs(AttrFactory);
3241         if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3242           if (!Attrs.empty()) {
3243             AttrsLastTime = true;
3244             attrs.takeAllFrom(Attrs);
3245           }
3246           continue;
3247         }
3248         goto DoneWithDeclSpec;
3249       }
3250
3251       DS.getTypeSpecScope() = SS;
3252       ConsumeAnnotationToken(); // The C++ scope.
3253
3254       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3255                                      DiagID, TypeRep, Policy);
3256       if (isInvalid)
3257         break;
3258
3259       DS.SetRangeEnd(Tok.getLocation());
3260       ConsumeToken(); // The typename.
3261
3262       continue;
3263     }
3264
3265     case tok::annot_typename: {
3266       // If we've previously seen a tag definition, we were almost surely
3267       // missing a semicolon after it.
3268       if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3269         goto DoneWithDeclSpec;
3270
3271       if (Tok.getAnnotationValue()) {
3272         ParsedType T = getTypeAnnotation(Tok);
3273         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3274                                        DiagID, T, Policy);
3275       } else
3276         DS.SetTypeSpecError();
3277
3278       if (isInvalid)
3279         break;
3280
3281       DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3282       ConsumeAnnotationToken(); // The typename
3283
3284       continue;
3285     }
3286
3287     case tok::kw___is_signed:
3288       // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3289       // typically treats it as a trait. If we see __is_signed as it appears
3290       // in libstdc++, e.g.,
3291       //
3292       //   static const bool __is_signed;
3293       //
3294       // then treat __is_signed as an identifier rather than as a keyword.
3295       if (DS.getTypeSpecType() == TST_bool &&
3296           DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3297           DS.getStorageClassSpec() == DeclSpec::SCS_static)
3298         TryKeywordIdentFallback(true);
3299
3300       // We're done with the declaration-specifiers.
3301       goto DoneWithDeclSpec;
3302
3303       // typedef-name
3304     case tok::kw___super:
3305     case tok::kw_decltype:
3306     case tok::identifier: {
3307       // This identifier can only be a typedef name if we haven't already seen
3308       // a type-specifier.  Without this check we misparse:
3309       //  typedef int X; struct Y { short X; };  as 'short int'.
3310       if (DS.hasTypeSpecifier())
3311         goto DoneWithDeclSpec;
3312
3313       // If the token is an identifier named "__declspec" and Microsoft
3314       // extensions are not enabled, it is likely that there will be cascading
3315       // parse errors if this really is a __declspec attribute. Attempt to
3316       // recognize that scenario and recover gracefully.
3317       if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3318           Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3319         Diag(Loc, diag::err_ms_attributes_not_enabled);
3320
3321         // The next token should be an open paren. If it is, eat the entire
3322         // attribute declaration and continue.
3323         if (NextToken().is(tok::l_paren)) {
3324           // Consume the __declspec identifier.
3325           ConsumeToken();
3326
3327           // Eat the parens and everything between them.
3328           BalancedDelimiterTracker T(*this, tok::l_paren);
3329           if (T.consumeOpen()) {
3330             assert(false && "Not a left paren?");
3331             return;
3332           }
3333           T.skipToEnd();
3334           continue;
3335         }
3336       }
3337
3338       // In C++, check to see if this is a scope specifier like foo::bar::, if
3339       // so handle it as such.  This is important for ctor parsing.
3340       if (getLangOpts().CPlusPlus) {
3341         if (TryAnnotateCXXScopeToken(EnteringContext)) {
3342           DS.SetTypeSpecError();
3343           goto DoneWithDeclSpec;
3344         }
3345         if (!Tok.is(tok::identifier))
3346           continue;
3347       }
3348
3349       // Check for need to substitute AltiVec keyword tokens.
3350       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3351         break;
3352
3353       // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3354       //                allow the use of a typedef name as a type specifier.
3355       if (DS.isTypeAltiVecVector())
3356         goto DoneWithDeclSpec;
3357
3358       if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3359           isObjCInstancetype()) {
3360         ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3361         assert(TypeRep);
3362         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3363                                        DiagID, TypeRep, Policy);
3364         if (isInvalid)
3365           break;
3366
3367         DS.SetRangeEnd(Loc);
3368         ConsumeToken();
3369         continue;
3370       }
3371
3372       // If we're in a context where the identifier could be a class name,
3373       // check whether this is a constructor declaration.
3374       if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3375           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3376           isConstructorDeclarator(/*Unqualified*/true))
3377         goto DoneWithDeclSpec;
3378
3379       ParsedType TypeRep = Actions.getTypeName(
3380           *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3381           false, false, nullptr, false, false,
3382           isClassTemplateDeductionContext(DSContext));
3383
3384       // If this is not a typedef name, don't parse it as part of the declspec,
3385       // it must be an implicit int or an error.
3386       if (!TypeRep) {
3387         ParsedAttributesWithRange Attrs(AttrFactory);
3388         if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3389           if (!Attrs.empty()) {
3390             AttrsLastTime = true;
3391             attrs.takeAllFrom(Attrs);
3392           }
3393           continue;
3394         }
3395         goto DoneWithDeclSpec;
3396       }
3397
3398       // Likewise, if this is a context where the identifier could be a template
3399       // name, check whether this is a deduction guide declaration.
3400       if (getLangOpts().CPlusPlus17 &&
3401           (DSContext == DeclSpecContext::DSC_class ||
3402            DSContext == DeclSpecContext::DSC_top_level) &&
3403           Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3404                                        Tok.getLocation()) &&
3405           isConstructorDeclarator(/*Unqualified*/ true,
3406                                   /*DeductionGuide*/ true))
3407         goto DoneWithDeclSpec;
3408
3409       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3410                                      DiagID, TypeRep, Policy);
3411       if (isInvalid)
3412         break;
3413
3414       DS.SetRangeEnd(Tok.getLocation());
3415       ConsumeToken(); // The identifier
3416
3417       // Objective-C supports type arguments and protocol references
3418       // following an Objective-C object or object pointer
3419       // type. Handle either one of them.
3420       if (Tok.is(tok::less) && getLangOpts().ObjC) {
3421         SourceLocation NewEndLoc;
3422         TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3423                                   Loc, TypeRep, /*consumeLastToken=*/true,
3424                                   NewEndLoc);
3425         if (NewTypeRep.isUsable()) {
3426           DS.UpdateTypeRep(NewTypeRep.get());
3427           DS.SetRangeEnd(NewEndLoc);
3428         }
3429       }
3430
3431       // Need to support trailing type qualifiers (e.g. "id<p> const").
3432       // If a type specifier follows, it will be diagnosed elsewhere.
3433       continue;
3434     }
3435
3436       // type-name
3437     case tok::annot_template_id: {
3438       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3439       if (TemplateId->Kind != TNK_Type_template &&
3440           TemplateId->Kind != TNK_Undeclared_template) {
3441         // This template-id does not refer to a type name, so we're
3442         // done with the type-specifiers.
3443         goto DoneWithDeclSpec;
3444       }
3445
3446       // If we're in a context where the template-id could be a
3447       // constructor name or specialization, check whether this is a
3448       // constructor declaration.
3449       if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3450           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3451           isConstructorDeclarator(TemplateId->SS.isEmpty()))
3452         goto DoneWithDeclSpec;
3453
3454       // Turn the template-id annotation token into a type annotation
3455       // token, then try again to parse it as a type-specifier.
3456       AnnotateTemplateIdTokenAsType();
3457       continue;
3458     }
3459
3460     // GNU attributes support.
3461     case tok::kw___attribute:
3462       ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3463       continue;
3464
3465     // Microsoft declspec support.
3466     case tok::kw___declspec:
3467       ParseMicrosoftDeclSpecs(DS.getAttributes());
3468       continue;
3469
3470     // Microsoft single token adornments.
3471     case tok::kw___forceinline: {
3472       isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3473       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3474       SourceLocation AttrNameLoc = Tok.getLocation();
3475       DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3476                                 nullptr, 0, ParsedAttr::AS_Keyword);
3477       break;
3478     }
3479
3480     case tok::kw___unaligned:
3481       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3482                                  getLangOpts());
3483       break;
3484
3485     case tok::kw___sptr:
3486     case tok::kw___uptr:
3487     case tok::kw___ptr64:
3488     case tok::kw___ptr32:
3489     case tok::kw___w64:
3490     case tok::kw___cdecl:
3491     case tok::kw___stdcall:
3492     case tok::kw___fastcall:
3493     case tok::kw___thiscall:
3494     case tok::kw___regcall:
3495     case tok::kw___vectorcall:
3496       ParseMicrosoftTypeAttributes(DS.getAttributes());
3497       continue;
3498
3499     // Borland single token adornments.
3500     case tok::kw___pascal:
3501       ParseBorlandTypeAttributes(DS.getAttributes());
3502       continue;
3503
3504     // OpenCL single token adornments.
3505     case tok::kw___kernel:
3506       ParseOpenCLKernelAttributes(DS.getAttributes());
3507       continue;
3508
3509     // Nullability type specifiers.
3510     case tok::kw__Nonnull:
3511     case tok::kw__Nullable:
3512     case tok::kw__Null_unspecified:
3513       ParseNullabilityTypeSpecifiers(DS.getAttributes());
3514       continue;
3515
3516     // Objective-C 'kindof' types.
3517     case tok::kw___kindof:
3518       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3519                                 nullptr, 0, ParsedAttr::AS_Keyword);
3520       (void)ConsumeToken();
3521       continue;
3522
3523     // storage-class-specifier
3524     case tok::kw_typedef:
3525       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3526                                          PrevSpec, DiagID, Policy);
3527       isStorageClass = true;
3528       break;
3529     case tok::kw_extern:
3530       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3531         Diag(Tok, diag::ext_thread_before) << "extern";
3532       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3533                                          PrevSpec, DiagID, Policy);
3534       isStorageClass = true;
3535       break;
3536     case tok::kw___private_extern__:
3537       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3538                                          Loc, PrevSpec, DiagID, Policy);
3539       isStorageClass = true;
3540       break;
3541     case tok::kw_static:
3542       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3543         Diag(Tok, diag::ext_thread_before) << "static";
3544       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3545                                          PrevSpec, DiagID, Policy);
3546       isStorageClass = true;
3547       break;
3548     case tok::kw_auto:
3549       if (getLangOpts().CPlusPlus11) {
3550         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3551           isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3552                                              PrevSpec, DiagID, Policy);
3553           if (!isInvalid)
3554             Diag(Tok, diag::ext_auto_storage_class)
3555               << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3556         } else
3557           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3558                                          DiagID, Policy);
3559       } else
3560         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3561                                            PrevSpec, DiagID, Policy);
3562       isStorageClass = true;
3563       break;
3564     case tok::kw___auto_type:
3565       Diag(Tok, diag::ext_auto_type);
3566       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3567                                      DiagID, Policy);
3568       break;
3569     case tok::kw_register:
3570       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3571                                          PrevSpec, DiagID, Policy);
3572       isStorageClass = true;
3573       break;
3574     case tok::kw_mutable:
3575       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3576                                          PrevSpec, DiagID, Policy);
3577       isStorageClass = true;
3578       break;
3579     case tok::kw___thread:
3580       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3581                                                PrevSpec, DiagID);
3582       isStorageClass = true;
3583       break;
3584     case tok::kw_thread_local:
3585       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3586                                                PrevSpec, DiagID);
3587       isStorageClass = true;
3588       break;
3589     case tok::kw__Thread_local:
3590       if (!getLangOpts().C11)
3591         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3592       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3593                                                Loc, PrevSpec, DiagID);
3594       isStorageClass = true;
3595       break;
3596
3597     // function-specifier
3598     case tok::kw_inline:
3599       isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3600       break;
3601     case tok::kw_virtual:
3602       // C++ for OpenCL does not allow virtual function qualifier, to avoid
3603       // function pointers restricted in OpenCL v2.0 s6.9.a.
3604       if (getLangOpts().OpenCLCPlusPlus) {
3605         DiagID = diag::err_openclcxx_virtual_function;
3606         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3607         isInvalid = true;
3608       }
3609       else {
3610         isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3611       }
3612       break;
3613     case tok::kw_explicit: {
3614       SourceLocation ExplicitLoc = Loc;
3615       SourceLocation CloseParenLoc;
3616       ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3617       ConsumedEnd = ExplicitLoc;
3618       ConsumeToken(); // kw_explicit
3619       if (Tok.is(tok::l_paren)) {
3620         if (getLangOpts().CPlusPlus2a) {
3621           ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3622           BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3623           Tracker.consumeOpen();
3624           ExplicitExpr = ParseConstantExpression();
3625           ConsumedEnd = Tok.getLocation();
3626           if (ExplicitExpr.isUsable()) {
3627             CloseParenLoc = Tok.getLocation();
3628             Tracker.consumeClose();
3629             ExplicitSpec =
3630                 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3631           } else
3632             Tracker.skipToEnd();
3633         } else
3634           Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3635       }
3636       isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3637                                              ExplicitSpec, CloseParenLoc);
3638       break;
3639     }
3640     case tok::kw__Noreturn:
3641       if (!getLangOpts().C11)
3642         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3643       isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3644       break;
3645
3646     // alignment-specifier
3647     case tok::kw__Alignas:
3648       if (!getLangOpts().C11)
3649         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3650       ParseAlignmentSpecifier(DS.getAttributes());
3651       continue;
3652
3653     // friend
3654     case tok::kw_friend:
3655       if (DSContext == DeclSpecContext::DSC_class)
3656         isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3657       else {
3658         PrevSpec = ""; // not actually used by the diagnostic
3659         DiagID = diag::err_friend_invalid_in_context;
3660         isInvalid = true;
3661       }
3662       break;
3663
3664     // Modules
3665     case tok::kw___module_private__:
3666       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3667       break;
3668
3669     // constexpr, consteval, constinit specifiers
3670     case tok::kw_constexpr:
3671       isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3672       break;
3673     case tok::kw_consteval:
3674       isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3675       break;
3676     case tok::kw_constinit:
3677       isInvalid = DS.SetConstexprSpec(CSK_constinit, Loc, PrevSpec, DiagID);
3678       break;
3679
3680     // type-specifier
3681     case tok::kw_short:
3682       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3683                                       DiagID, Policy);
3684       break;
3685     case tok::kw_long:
3686       if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3687         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3688                                         DiagID, Policy);
3689       else
3690         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3691                                         DiagID, Policy);
3692       break;
3693     case tok::kw___int64:
3694         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3695                                         DiagID, Policy);
3696       break;
3697     case tok::kw_signed:
3698       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3699                                      DiagID);
3700       break;
3701     case tok::kw_unsigned:
3702       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3703                                      DiagID);
3704       break;
3705     case tok::kw__Complex:
3706       if (!getLangOpts().C99)
3707         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3708       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3709                                         DiagID);
3710       break;
3711     case tok::kw__Imaginary:
3712       if (!getLangOpts().C99)
3713         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3714       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3715                                         DiagID);
3716       break;
3717     case tok::kw_void:
3718       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3719                                      DiagID, Policy);
3720       break;
3721     case tok::kw_char:
3722       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3723                                      DiagID, Policy);
3724       break;
3725     case tok::kw_int:
3726       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3727                                      DiagID, Policy);
3728       break;
3729     case tok::kw___int128:
3730       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3731                                      DiagID, Policy);
3732       break;
3733     case tok::kw_half:
3734       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3735                                      DiagID, Policy);
3736       break;
3737     case tok::kw_float:
3738       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3739                                      DiagID, Policy);
3740       break;
3741     case tok::kw_double:
3742       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3743                                      DiagID, Policy);
3744       break;
3745     case tok::kw__Float16:
3746       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3747                                      DiagID, Policy);
3748       break;
3749     case tok::kw__Accum:
3750       if (!getLangOpts().FixedPoint) {
3751         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3752       } else {
3753         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3754                                        DiagID, Policy);
3755       }
3756       break;
3757     case tok::kw__Fract:
3758       if (!getLangOpts().FixedPoint) {
3759         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3760       } else {
3761         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3762                                        DiagID, Policy);
3763       }
3764       break;
3765     case tok::kw__Sat:
3766       if (!getLangOpts().FixedPoint) {
3767         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3768       } else {
3769         isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3770       }
3771       break;
3772     case tok::kw___float128:
3773       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3774                                      DiagID, Policy);
3775       break;
3776     case tok::kw_wchar_t:
3777       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3778                                      DiagID, Policy);
3779       break;
3780     case tok::kw_char8_t:
3781       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3782                                      DiagID, Policy);
3783       break;
3784     case tok::kw_char16_t:
3785       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3786                                      DiagID, Policy);
3787       break;
3788     case tok::kw_char32_t:
3789       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3790                                      DiagID, Policy);
3791       break;
3792     case tok::kw_bool:
3793     case tok::kw__Bool:
3794       if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3795         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3796
3797       if (Tok.is(tok::kw_bool) &&
3798           DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3799           DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3800         PrevSpec = ""; // Not used by the diagnostic.
3801         DiagID = diag::err_bool_redeclaration;
3802         // For better error recovery.
3803         Tok.setKind(tok::identifier);
3804         isInvalid = true;
3805       } else {
3806         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3807                                        DiagID, Policy);
3808       }
3809       break;
3810     case tok::kw__Decimal32:
3811       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3812                                      DiagID, Policy);
3813       break;
3814     case tok::kw__Decimal64:
3815       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3816                                      DiagID, Policy);
3817       break;
3818     case tok::kw__Decimal128:
3819       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3820                                      DiagID, Policy);
3821       break;
3822     case tok::kw___vector:
3823       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3824       break;
3825     case tok::kw___pixel:
3826       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3827       break;
3828     case tok::kw___bool:
3829       isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3830       break;
3831     case tok::kw_pipe:
3832       if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3833                                     !getLangOpts().OpenCLCPlusPlus)) {
3834         // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3835         // support the "pipe" word as identifier.
3836         Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3837         goto DoneWithDeclSpec;
3838       }
3839       isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3840       break;
3841 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3842   case tok::kw_##ImgType##_t: \
3843     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3844                                    DiagID, Policy); \
3845     break;
3846 #include "clang/Basic/OpenCLImageTypes.def"
3847     case tok::kw___unknown_anytype:
3848       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3849                                      PrevSpec, DiagID, Policy);
3850       break;
3851
3852     // class-specifier:
3853     case tok::kw_class:
3854     case tok::kw_struct:
3855     case tok::kw___interface:
3856     case tok::kw_union: {
3857       tok::TokenKind Kind = Tok.getKind();
3858       ConsumeToken();
3859
3860       // These are attributes following class specifiers.
3861       // To produce better diagnostic, we parse them when
3862       // parsing class specifier.
3863       ParsedAttributesWithRange Attributes(AttrFactory);
3864       ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3865                           EnteringContext, DSContext, Attributes);
3866
3867       // If there are attributes following class specifier,
3868       // take them over and handle them here.
3869       if (!Attributes.empty()) {
3870         AttrsLastTime = true;
3871         attrs.takeAllFrom(Attributes);
3872       }
3873       continue;
3874     }
3875
3876     // enum-specifier:
3877     case tok::kw_enum:
3878       ConsumeToken();
3879       ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3880       continue;
3881
3882     // cv-qualifier:
3883     case tok::kw_const:
3884       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3885                                  getLangOpts());
3886       break;
3887     case tok::kw_volatile:
3888       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3889                                  getLangOpts());
3890       break;
3891     case tok::kw_restrict:
3892       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3893                                  getLangOpts());
3894       break;
3895
3896     // C++ typename-specifier:
3897     case tok::kw_typename:
3898       if (TryAnnotateTypeOrScopeToken()) {
3899         DS.SetTypeSpecError();
3900         goto DoneWithDeclSpec;
3901       }
3902       if (!Tok.is(tok::kw_typename))
3903         continue;
3904       break;
3905
3906     // GNU typeof support.
3907     case tok::kw_typeof:
3908       ParseTypeofSpecifier(DS);
3909       continue;
3910
3911     case tok::annot_decltype:
3912       ParseDecltypeSpecifier(DS);
3913       continue;
3914
3915     case tok::annot_pragma_pack:
3916       HandlePragmaPack();
3917       continue;
3918
3919     case tok::annot_pragma_ms_pragma:
3920       HandlePragmaMSPragma();
3921       continue;
3922
3923     case tok::annot_pragma_ms_vtordisp:
3924       HandlePragmaMSVtorDisp();
3925       continue;
3926
3927     case tok::annot_pragma_ms_pointers_to_members:
3928       HandlePragmaMSPointersToMembers();
3929       continue;
3930
3931     case tok::kw___underlying_type:
3932       ParseUnderlyingTypeSpecifier(DS);
3933       continue;
3934
3935     case tok::kw__Atomic:
3936       // C11 6.7.2.4/4:
3937       //   If the _Atomic keyword is immediately followed by a left parenthesis,
3938       //   it is interpreted as a type specifier (with a type name), not as a
3939       //   type qualifier.
3940       if (!getLangOpts().C11)
3941         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3942
3943       if (NextToken().is(tok::l_paren)) {
3944         ParseAtomicSpecifier(DS);
3945         continue;
3946       }
3947       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3948                                  getLangOpts());
3949       break;
3950
3951     // OpenCL address space qualifiers:
3952     case tok::kw___generic:
3953       // generic address space is introduced only in OpenCL v2.0
3954       // see OpenCL C Spec v2.0 s6.5.5
3955       if (Actions.getLangOpts().OpenCLVersion < 200 &&
3956           !Actions.getLangOpts().OpenCLCPlusPlus) {
3957         DiagID = diag::err_opencl_unknown_type_specifier;
3958         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3959         isInvalid = true;
3960         break;
3961       }
3962       LLVM_FALLTHROUGH;
3963     case tok::kw_private:
3964       // It's fine (but redundant) to check this for __generic on the
3965       // fallthrough path; we only form the __generic token in OpenCL mode.
3966       if (!getLangOpts().OpenCL)
3967         goto DoneWithDeclSpec;
3968       LLVM_FALLTHROUGH;
3969     case tok::kw___private:
3970     case tok::kw___global:
3971     case tok::kw___local:
3972     case tok::kw___constant:
3973     // OpenCL access qualifiers:
3974     case tok::kw___read_only:
3975     case tok::kw___write_only:
3976     case tok::kw___read_write:
3977       ParseOpenCLQualifiers(DS.getAttributes());
3978       break;
3979
3980     case tok::less:
3981       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3982       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
3983       // but we support it.
3984       if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
3985         goto DoneWithDeclSpec;
3986
3987       SourceLocation StartLoc = Tok.getLocation();
3988       SourceLocation EndLoc;
3989       TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3990       if (Type.isUsable()) {
3991         if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3992                                PrevSpec, DiagID, Type.get(),
3993                                Actions.getASTContext().getPrintingPolicy()))
3994           Diag(StartLoc, DiagID) << PrevSpec;
3995
3996         DS.SetRangeEnd(EndLoc);
3997       } else {
3998         DS.SetTypeSpecError();
3999       }
4000
4001       // Need to support trailing type qualifiers (e.g. "id<p> const").
4002       // If a type specifier follows, it will be diagnosed elsewhere.
4003       continue;
4004     }
4005
4006     DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
4007
4008     // If the specifier wasn't legal, issue a diagnostic.
4009     if (isInvalid) {
4010       assert(PrevSpec && "Method did not return previous specifier!");
4011       assert(DiagID);
4012
4013       if (DiagID == diag::ext_duplicate_declspec ||
4014           DiagID == diag::ext_warn_duplicate_declspec ||
4015           DiagID == diag::err_duplicate_declspec)
4016         Diag(Loc, DiagID) << PrevSpec
4017                           << FixItHint::CreateRemoval(
4018                                  SourceRange(Loc, DS.getEndLoc()));
4019       else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4020         Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4021                           << getLangOpts().getOpenCLVersionTuple().getAsString()
4022                           << PrevSpec << isStorageClass;
4023       } else
4024         Diag(Loc, DiagID) << PrevSpec;
4025     }
4026
4027     if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4028       // After an error the next token can be an annotation token.
4029       ConsumeAnyToken();
4030
4031     AttrsLastTime = false;
4032   }
4033 }
4034
4035 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4036 /// semicolon.
4037 ///
4038 /// Note that a struct declaration refers to a declaration in a struct,
4039 /// not to the declaration of a struct.
4040 ///
4041 ///       struct-declaration:
4042 /// [C2x]   attributes-specifier-seq[opt]
4043 ///           specifier-qualifier-list struct-declarator-list
4044 /// [GNU]   __extension__ struct-declaration
4045 /// [GNU]   specifier-qualifier-list
4046 ///       struct-declarator-list:
4047 ///         struct-declarator
4048 ///         struct-declarator-list ',' struct-declarator
4049 /// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
4050 ///       struct-declarator:
4051 ///         declarator
4052 /// [GNU]   declarator attributes[opt]
4053 ///         declarator[opt] ':' constant-expression
4054 /// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
4055 ///
4056 void Parser::ParseStructDeclaration(
4057     ParsingDeclSpec &DS,
4058     llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4059
4060   if (Tok.is(tok::kw___extension__)) {
4061     // __extension__ silences extension warnings in the subexpression.
4062     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
4063     ConsumeToken();
4064     return ParseStructDeclaration(DS, FieldsCallback);
4065   }
4066
4067   // Parse leading attributes.
4068   ParsedAttributesWithRange Attrs(AttrFactory);
4069   MaybeParseCXX11Attributes(Attrs);
4070   DS.takeAttributesFrom(Attrs);
4071
4072   // Parse the common specifier-qualifiers-list piece.
4073   ParseSpecifierQualifierList(DS);
4074
4075   // If there are no declarators, this is a free-standing declaration
4076   // specifier. Let the actions module cope with it.
4077   if (Tok.is(tok::semi)) {
4078     RecordDecl *AnonRecord = nullptr;
4079     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4080                                                        DS, AnonRecord);
4081     assert(!AnonRecord && "Did not expect anonymous struct or union here");
4082     DS.complete(TheDecl);
4083     return;
4084   }
4085
4086   // Read struct-declarators until we find the semicolon.
4087   bool FirstDeclarator = true;
4088   SourceLocation CommaLoc;
4089   while (1) {
4090     ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4091     DeclaratorInfo.D.setCommaLoc(CommaLoc);
4092
4093     // Attributes are only allowed here on successive declarators.
4094     if (!FirstDeclarator)
4095       MaybeParseGNUAttributes(DeclaratorInfo.D);
4096
4097     /// struct-declarator: declarator
4098     /// struct-declarator: declarator[opt] ':' constant-expression
4099     if (Tok.isNot(tok::colon)) {
4100       // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4101       ColonProtectionRAIIObject X(*this);
4102       ParseDeclarator(DeclaratorInfo.D);
4103     } else
4104       DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4105
4106     if (TryConsumeToken(tok::colon)) {
4107       ExprResult Res(ParseConstantExpression());
4108       if (Res.isInvalid())
4109         SkipUntil(tok::semi, StopBeforeMatch);
4110       else
4111         DeclaratorInfo.BitfieldSize = Res.get();
4112     }
4113
4114     // If attributes exist after the declarator, parse them.
4115     MaybeParseGNUAttributes(DeclaratorInfo.D);
4116
4117     // We're done with this declarator;  invoke the callback.
4118     FieldsCallback(DeclaratorInfo);
4119
4120     // If we don't have a comma, it is either the end of the list (a ';')
4121     // or an error, bail out.
4122     if (!TryConsumeToken(tok::comma, CommaLoc))
4123       return;
4124
4125     FirstDeclarator = false;
4126   }
4127 }
4128
4129 /// ParseStructUnionBody
4130 ///       struct-contents:
4131 ///         struct-declaration-list
4132 /// [EXT]   empty
4133 /// [GNU]   "struct-declaration-list" without terminatoring ';'
4134 ///       struct-declaration-list:
4135 ///         struct-declaration
4136 ///         struct-declaration-list struct-declaration
4137 /// [OBC]   '@' 'defs' '(' class-name ')'
4138 ///
4139 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4140                                   DeclSpec::TST TagType, Decl *TagDecl) {
4141   PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4142                                       "parsing struct/union body");
4143   assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4144
4145   BalancedDelimiterTracker T(*this, tok::l_brace);
4146   if (T.consumeOpen())
4147     return;
4148
4149   ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4150   Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4151
4152   SmallVector<Decl *, 32> FieldDecls;
4153
4154   // While we still have something to read, read the declarations in the struct.
4155   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4156          Tok.isNot(tok::eof)) {
4157     // Each iteration of this loop reads one struct-declaration.
4158
4159     // Check for extraneous top-level semicolon.
4160     if (Tok.is(tok::semi)) {
4161       ConsumeExtraSemi(InsideStruct, TagType);
4162       continue;
4163     }
4164
4165     // Parse _Static_assert declaration.
4166     if (Tok.is(tok::kw__Static_assert)) {
4167       SourceLocation DeclEnd;
4168       ParseStaticAssertDeclaration(DeclEnd);
4169       continue;
4170     }
4171
4172     if (Tok.is(tok::annot_pragma_pack)) {
4173       HandlePragmaPack();
4174       continue;
4175     }
4176
4177     if (Tok.is(tok::annot_pragma_align)) {
4178       HandlePragmaAlign();
4179       continue;
4180     }
4181
4182     if (Tok.is(tok::annot_pragma_openmp)) {
4183       // Result can be ignored, because it must be always empty.
4184       AccessSpecifier AS = AS_none;
4185       ParsedAttributesWithRange Attrs(AttrFactory);
4186       (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4187       continue;
4188     }
4189
4190     if (tok::isPragmaAnnotation(Tok.getKind())) {
4191       Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4192           << DeclSpec::getSpecifierName(
4193                  TagType, Actions.getASTContext().getPrintingPolicy());
4194       ConsumeAnnotationToken();
4195       continue;
4196     }
4197
4198     if (!Tok.is(tok::at)) {
4199       auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4200         // Install the declarator into the current TagDecl.
4201         Decl *Field =
4202             Actions.ActOnField(getCurScope(), TagDecl,
4203                                FD.D.getDeclSpec().getSourceRange().getBegin(),
4204                                FD.D, FD.BitfieldSize);
4205         FieldDecls.push_back(Field);
4206         FD.complete(Field);
4207       };
4208
4209       // Parse all the comma separated declarators.
4210       ParsingDeclSpec DS(*this);
4211       ParseStructDeclaration(DS, CFieldCallback);
4212     } else { // Handle @defs
4213       ConsumeToken();
4214       if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4215         Diag(Tok, diag::err_unexpected_at);
4216         SkipUntil(tok::semi);
4217         continue;
4218       }
4219       ConsumeToken();
4220       ExpectAndConsume(tok::l_paren);
4221       if (!Tok.is(tok::identifier)) {
4222         Diag(Tok, diag::err_expected) << tok::identifier;
4223         SkipUntil(tok::semi);
4224         continue;
4225       }
4226       SmallVector<Decl *, 16> Fields;
4227       Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4228                         Tok.getIdentifierInfo(), Fields);
4229       FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4230       ConsumeToken();
4231       ExpectAndConsume(tok::r_paren);
4232     }
4233
4234     if (TryConsumeToken(tok::semi))
4235       continue;
4236
4237     if (Tok.is(tok::r_brace)) {
4238       ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4239       break;
4240     }
4241
4242     ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4243     // Skip to end of block or statement to avoid ext-warning on extra ';'.
4244     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4245     // If we stopped at a ';', eat it.
4246     TryConsumeToken(tok::semi);
4247   }
4248
4249   T.consumeClose();
4250
4251   ParsedAttributes attrs(AttrFactory);
4252   // If attributes exist after struct contents, parse them.
4253   MaybeParseGNUAttributes(attrs);
4254
4255   Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4256                       T.getOpenLocation(), T.getCloseLocation(), attrs);
4257   StructScope.Exit();
4258   Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4259 }
4260
4261 /// ParseEnumSpecifier
4262 ///       enum-specifier: [C99 6.7.2.2]
4263 ///         'enum' identifier[opt] '{' enumerator-list '}'
4264 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4265 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4266 ///                                                 '}' attributes[opt]
4267 /// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4268 ///                                                 '}'
4269 ///         'enum' identifier
4270 /// [GNU]   'enum' attributes[opt] identifier
4271 ///
4272 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4273 /// [C++11] enum-head '{' enumerator-list ','  '}'
4274 ///
4275 ///       enum-head: [C++11]
4276 ///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4277 ///         enum-key attribute-specifier-seq[opt] nested-name-specifier
4278 ///             identifier enum-base[opt]
4279 ///
4280 ///       enum-key: [C++11]
4281 ///         'enum'
4282 ///         'enum' 'class'
4283 ///         'enum' 'struct'
4284 ///
4285 ///       enum-base: [C++11]
4286 ///         ':' type-specifier-seq
4287 ///
4288 /// [C++] elaborated-type-specifier:
4289 /// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
4290 ///
4291 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4292                                 const ParsedTemplateInfo &TemplateInfo,
4293                                 AccessSpecifier AS, DeclSpecContext DSC) {
4294   // Parse the tag portion of this.
4295   if (Tok.is(tok::code_completion)) {
4296     // Code completion for an enum name.
4297     Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4298     return cutOffParsing();
4299   }
4300
4301   // If attributes exist after tag, parse them.
4302   ParsedAttributesWithRange attrs(AttrFactory);
4303   MaybeParseGNUAttributes(attrs);
4304   MaybeParseCXX11Attributes(attrs);
4305   MaybeParseMicrosoftDeclSpecs(attrs);
4306
4307   SourceLocation ScopedEnumKWLoc;
4308   bool IsScopedUsingClassTag = false;
4309
4310   // In C++11, recognize 'enum class' and 'enum struct'.
4311   if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4312     Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4313                                         : diag::ext_scoped_enum);
4314     IsScopedUsingClassTag = Tok.is(tok::kw_class);
4315     ScopedEnumKWLoc = ConsumeToken();
4316
4317     // Attributes are not allowed between these keywords.  Diagnose,
4318     // but then just treat them like they appeared in the right place.
4319     ProhibitAttributes(attrs);
4320
4321     // They are allowed afterwards, though.
4322     MaybeParseGNUAttributes(attrs);
4323     MaybeParseCXX11Attributes(attrs);
4324     MaybeParseMicrosoftDeclSpecs(attrs);
4325   }
4326
4327   // C++11 [temp.explicit]p12:
4328   //   The usual access controls do not apply to names used to specify
4329   //   explicit instantiations.
4330   // We extend this to also cover explicit specializations.  Note that
4331   // we don't suppress if this turns out to be an elaborated type
4332   // specifier.
4333   bool shouldDelayDiagsInTag =
4334     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4335      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4336   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4337
4338   // Enum definitions should not be parsed in a trailing-return-type.
4339   bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4340
4341   CXXScopeSpec &SS = DS.getTypeSpecScope();
4342   if (getLangOpts().CPlusPlus) {
4343     // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4344     // if a fixed underlying type is allowed.
4345     ColonProtectionRAIIObject X(*this, AllowDeclaration);
4346
4347     CXXScopeSpec Spec;
4348     if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4349                                        /*EnteringContext=*/true))
4350       return;
4351
4352     if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4353       Diag(Tok, diag::err_expected) << tok::identifier;
4354       if (Tok.isNot(tok::l_brace)) {
4355         // Has no name and is not a definition.
4356         // Skip the rest of this declarator, up until the comma or semicolon.
4357         SkipUntil(tok::comma, StopAtSemi);
4358         return;
4359       }
4360     }
4361
4362     SS = Spec;
4363   }
4364
4365   // Must have either 'enum name' or 'enum {...}'.
4366   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4367       !(AllowDeclaration && Tok.is(tok::colon))) {
4368     Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4369
4370     // Skip the rest of this declarator, up until the comma or semicolon.
4371     SkipUntil(tok::comma, StopAtSemi);
4372     return;
4373   }
4374
4375   // If an identifier is present, consume and remember it.
4376   IdentifierInfo *Name = nullptr;
4377   SourceLocation NameLoc;
4378   if (Tok.is(tok::identifier)) {
4379     Name = Tok.getIdentifierInfo();
4380     NameLoc = ConsumeToken();
4381   }
4382
4383   if (!Name && ScopedEnumKWLoc.isValid()) {
4384     // C++0x 7.2p2: The optional identifier shall not be omitted in the
4385     // declaration of a scoped enumeration.
4386     Diag(Tok, diag::err_scoped_enum_missing_identifier);
4387     ScopedEnumKWLoc = SourceLocation();
4388     IsScopedUsingClassTag = false;
4389   }
4390
4391   // Okay, end the suppression area.  We'll decide whether to emit the
4392   // diagnostics in a second.
4393   if (shouldDelayDiagsInTag)
4394     diagsFromTag.done();
4395
4396   TypeResult BaseType;
4397
4398   // Parse the fixed underlying type.
4399   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4400   if (AllowDeclaration && Tok.is(tok::colon)) {
4401     bool PossibleBitfield = false;
4402     if (CanBeBitfield) {
4403       // If we're in class scope, this can either be an enum declaration with
4404       // an underlying type, or a declaration of a bitfield member. We try to
4405       // use a simple disambiguation scheme first to catch the common cases
4406       // (integer literal, sizeof); if it's still ambiguous, we then consider
4407       // anything that's a simple-type-specifier followed by '(' as an
4408       // expression. This suffices because function types are not valid
4409       // underlying types anyway.
4410       EnterExpressionEvaluationContext Unevaluated(
4411           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4412       TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4413       // If the next token starts an expression, we know we're parsing a
4414       // bit-field. This is the common case.
4415       if (TPR == TPResult::True)
4416         PossibleBitfield = true;
4417       // If the next token starts a type-specifier-seq, it may be either a
4418       // a fixed underlying type or the start of a function-style cast in C++;
4419       // lookahead one more token to see if it's obvious that we have a
4420       // fixed underlying type.
4421       else if (TPR == TPResult::False &&
4422                GetLookAheadToken(2).getKind() == tok::semi) {
4423         // Consume the ':'.
4424         ConsumeToken();
4425       } else {
4426         // We have the start of a type-specifier-seq, so we have to perform
4427         // tentative parsing to determine whether we have an expression or a
4428         // type.
4429         TentativeParsingAction TPA(*this);
4430
4431         // Consume the ':'.
4432         ConsumeToken();
4433
4434         // If we see a type specifier followed by an open-brace, we have an
4435         // ambiguity between an underlying type and a C++11 braced
4436         // function-style cast. Resolve this by always treating it as an
4437         // underlying type.
4438         // FIXME: The standard is not entirely clear on how to disambiguate in
4439         // this case.
4440         if ((getLangOpts().CPlusPlus &&
4441              isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4442             (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4443           // We'll parse this as a bitfield later.
4444           PossibleBitfield = true;
4445           TPA.Revert();
4446         } else {
4447           // We have a type-specifier-seq.
4448           TPA.Commit();
4449         }
4450       }
4451     } else {
4452       // Consume the ':'.
4453       ConsumeToken();
4454     }
4455
4456     if (!PossibleBitfield) {
4457       SourceRange Range;
4458       BaseType = ParseTypeName(&Range);
4459
4460       if (!getLangOpts().ObjC) {
4461         if (getLangOpts().CPlusPlus11)
4462           Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4463         else if (getLangOpts().CPlusPlus)
4464           Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4465         else if (getLangOpts().MicrosoftExt)
4466           Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4467         else
4468           Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4469       }
4470     }
4471   }
4472
4473   // There are four options here.  If we have 'friend enum foo;' then this is a
4474   // friend declaration, and cannot have an accompanying definition. If we have
4475   // 'enum foo;', then this is a forward declaration.  If we have
4476   // 'enum foo {...' then this is a definition. Otherwise we have something
4477   // like 'enum foo xyz', a reference.
4478   //
4479   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4480   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4481   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4482   //
4483   Sema::TagUseKind TUK;
4484   if (!AllowDeclaration) {
4485     TUK = Sema::TUK_Reference;
4486   } else if (Tok.is(tok::l_brace)) {
4487     if (DS.isFriendSpecified()) {
4488       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4489         << SourceRange(DS.getFriendSpecLoc());
4490       ConsumeBrace();
4491       SkipUntil(tok::r_brace, StopAtSemi);
4492       TUK = Sema::TUK_Friend;
4493     } else {
4494       TUK = Sema::TUK_Definition;
4495     }
4496   } else if (!isTypeSpecifier(DSC) &&
4497              (Tok.is(tok::semi) ||
4498               (Tok.isAtStartOfLine() &&
4499                !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4500     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4501     if (Tok.isNot(tok::semi)) {
4502       // A semicolon was missing after this declaration. Diagnose and recover.
4503       ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4504       PP.EnterToken(Tok, /*IsReinject=*/true);
4505       Tok.setKind(tok::semi);
4506     }
4507   } else {
4508     TUK = Sema::TUK_Reference;
4509   }
4510
4511   // If this is an elaborated type specifier, and we delayed
4512   // diagnostics before, just merge them into the current pool.
4513   if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4514     diagsFromTag.redelay();
4515   }
4516
4517   MultiTemplateParamsArg TParams;
4518   if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4519       TUK != Sema::TUK_Reference) {
4520     if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4521       // Skip the rest of this declarator, up until the comma or semicolon.
4522       Diag(Tok, diag::err_enum_template);
4523       SkipUntil(tok::comma, StopAtSemi);
4524       return;
4525     }
4526
4527     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4528       // Enumerations can't be explicitly instantiated.
4529       DS.SetTypeSpecError();
4530       Diag(StartLoc, diag::err_explicit_instantiation_enum);
4531       return;
4532     }
4533
4534     assert(TemplateInfo.TemplateParams && "no template parameters");
4535     TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4536                                      TemplateInfo.TemplateParams->size());
4537   }
4538
4539   if (TUK == Sema::TUK_Reference)
4540     ProhibitAttributes(attrs);
4541
4542   if (!Name && TUK != Sema::TUK_Definition) {
4543     Diag(Tok, diag::err_enumerator_unnamed_no_def);
4544
4545     // Skip the rest of this declarator, up until the comma or semicolon.
4546     SkipUntil(tok::comma, StopAtSemi);
4547     return;
4548   }
4549
4550   stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4551
4552   Sema::SkipBodyInfo SkipBody;
4553   if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4554       NextToken().is(tok::identifier))
4555     SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4556                                               NextToken().getIdentifierInfo(),
4557                                               NextToken().getLocation());
4558
4559   bool Owned = false;
4560   bool IsDependent = false;
4561   const char *PrevSpec = nullptr;
4562   unsigned DiagID;
4563   Decl *TagDecl = Actions.ActOnTag(
4564       getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4565       attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4566       ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4567       DSC == DeclSpecContext::DSC_type_specifier,
4568       DSC == DeclSpecContext::DSC_template_param ||
4569           DSC == DeclSpecContext::DSC_template_type_arg,
4570       &SkipBody);
4571
4572   if (SkipBody.ShouldSkip) {
4573     assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4574
4575     BalancedDelimiterTracker T(*this, tok::l_brace);
4576     T.consumeOpen();
4577     T.skipToEnd();
4578
4579     if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4580                            NameLoc.isValid() ? NameLoc : StartLoc,
4581                            PrevSpec, DiagID, TagDecl, Owned,
4582                            Actions.getASTContext().getPrintingPolicy()))
4583       Diag(StartLoc, DiagID) << PrevSpec;
4584     return;
4585   }
4586
4587   if (IsDependent) {
4588     // This enum has a dependent nested-name-specifier. Handle it as a
4589     // dependent tag.
4590     if (!Name) {
4591       DS.SetTypeSpecError();
4592       Diag(Tok, diag::err_expected_type_name_after_typename);
4593       return;
4594     }
4595
4596     TypeResult Type = Actions.ActOnDependentTag(
4597         getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4598     if (Type.isInvalid()) {
4599       DS.SetTypeSpecError();
4600       return;
4601     }
4602
4603     if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4604                            NameLoc.isValid() ? NameLoc : StartLoc,
4605                            PrevSpec, DiagID, Type.get(),
4606                            Actions.getASTContext().getPrintingPolicy()))
4607       Diag(StartLoc, DiagID) << PrevSpec;
4608
4609     return;
4610   }
4611
4612   if (!TagDecl) {
4613     // The action failed to produce an enumeration tag. If this is a
4614     // definition, consume the entire definition.
4615     if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4616       ConsumeBrace();
4617       SkipUntil(tok::r_brace, StopAtSemi);
4618     }
4619
4620     DS.SetTypeSpecError();
4621     return;
4622   }
4623
4624   if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4625     Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4626     ParseEnumBody(StartLoc, D);
4627     if (SkipBody.CheckSameAsPrevious &&
4628         !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4629       DS.SetTypeSpecError();
4630       return;
4631     }
4632   }
4633
4634   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4635                          NameLoc.isValid() ? NameLoc : StartLoc,
4636                          PrevSpec, DiagID, TagDecl, Owned,
4637                          Actions.getASTContext().getPrintingPolicy()))
4638     Diag(StartLoc, DiagID) << PrevSpec;
4639 }
4640
4641 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4642 ///       enumerator-list:
4643 ///         enumerator
4644 ///         enumerator-list ',' enumerator
4645 ///       enumerator:
4646 ///         enumeration-constant attributes[opt]
4647 ///         enumeration-constant attributes[opt] '=' constant-expression
4648 ///       enumeration-constant:
4649 ///         identifier
4650 ///
4651 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4652   // Enter the scope of the enum body and start the definition.
4653   ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4654   Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4655
4656   BalancedDelimiterTracker T(*this, tok::l_brace);
4657   T.consumeOpen();
4658
4659   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4660   if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4661     Diag(Tok, diag::err_empty_enum);
4662
4663   SmallVector<Decl *, 32> EnumConstantDecls;
4664   SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4665
4666   Decl *LastEnumConstDecl = nullptr;
4667
4668   // Parse the enumerator-list.
4669   while (Tok.isNot(tok::r_brace)) {
4670     // Parse enumerator. If failed, try skipping till the start of the next
4671     // enumerator definition.
4672     if (Tok.isNot(tok::identifier)) {
4673       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4674       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4675           TryConsumeToken(tok::comma))
4676         continue;
4677       break;
4678     }
4679     IdentifierInfo *Ident = Tok.getIdentifierInfo();
4680     SourceLocation IdentLoc = ConsumeToken();
4681
4682     // If attributes exist after the enumerator, parse them.
4683     ParsedAttributesWithRange attrs(AttrFactory);
4684     MaybeParseGNUAttributes(attrs);
4685     ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4686     if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4687       if (getLangOpts().CPlusPlus)
4688         Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4689                                     ? diag::warn_cxx14_compat_ns_enum_attribute
4690                                     : diag::ext_ns_enum_attribute)
4691             << 1 /*enumerator*/;
4692       ParseCXX11Attributes(attrs);
4693     }
4694
4695     SourceLocation EqualLoc;
4696     ExprResult AssignedVal;
4697     EnumAvailabilityDiags.emplace_back(*this);
4698
4699     EnterExpressionEvaluationContext ConstantEvaluated(
4700         Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4701     if (TryConsumeToken(tok::equal, EqualLoc)) {
4702       AssignedVal = ParseConstantExpressionInExprEvalContext();
4703       if (AssignedVal.isInvalid())
4704         SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4705     }
4706
4707     // Install the enumerator constant into EnumDecl.
4708     Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4709         getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4710         EqualLoc, AssignedVal.get());
4711     EnumAvailabilityDiags.back().done();
4712
4713     EnumConstantDecls.push_back(EnumConstDecl);
4714     LastEnumConstDecl = EnumConstDecl;
4715
4716     if (Tok.is(tok::identifier)) {
4717       // We're missing a comma between enumerators.
4718       SourceLocation Loc = getEndOfPreviousToken();
4719       Diag(Loc, diag::err_enumerator_list_missing_comma)
4720         << FixItHint::CreateInsertion(Loc, ", ");
4721       continue;
4722     }
4723
4724     // Emumerator definition must be finished, only comma or r_brace are
4725     // allowed here.
4726     SourceLocation CommaLoc;
4727     if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4728       if (EqualLoc.isValid())
4729         Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4730                                                            << tok::comma;
4731       else
4732         Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4733       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4734         if (TryConsumeToken(tok::comma, CommaLoc))
4735           continue;
4736       } else {
4737         break;
4738       }
4739     }
4740
4741     // If comma is followed by r_brace, emit appropriate warning.
4742     if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4743       if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4744         Diag(CommaLoc, getLangOpts().CPlusPlus ?
4745                diag::ext_enumerator_list_comma_cxx :
4746                diag::ext_enumerator_list_comma_c)
4747           << FixItHint::CreateRemoval(CommaLoc);
4748       else if (getLangOpts().CPlusPlus11)
4749         Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4750           << FixItHint::CreateRemoval(CommaLoc);
4751       break;
4752     }
4753   }
4754
4755   // Eat the }.
4756   T.consumeClose();
4757
4758   // If attributes exist after the identifier list, parse them.
4759   ParsedAttributes attrs(AttrFactory);
4760   MaybeParseGNUAttributes(attrs);
4761
4762   Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4763                         getCurScope(), attrs);
4764
4765   // Now handle enum constant availability diagnostics.
4766   assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4767   for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4768     ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4769     EnumAvailabilityDiags[i].redelay();
4770     PD.complete(EnumConstantDecls[i]);
4771   }
4772
4773   EnumScope.Exit();
4774   Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4775
4776   // The next token must be valid after an enum definition. If not, a ';'
4777   // was probably forgotten.
4778   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4779   if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4780     ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4781     // Push this token back into the preprocessor and change our current token
4782     // to ';' so that the rest of the code recovers as though there were an
4783     // ';' after the definition.
4784     PP.EnterToken(Tok, /*IsReinject=*/true);
4785     Tok.setKind(tok::semi);
4786   }
4787 }
4788
4789 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4790 /// is definitely a type-specifier.  Return false if it isn't part of a type
4791 /// specifier or if we're not sure.
4792 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4793   switch (Tok.getKind()) {
4794   default: return false;
4795     // type-specifiers
4796   case tok::kw_short:
4797   case tok::kw_long:
4798   case tok::kw___int64:
4799   case tok::kw___int128:
4800   case tok::kw_signed:
4801   case tok::kw_unsigned:
4802   case tok::kw__Complex:
4803   case tok::kw__Imaginary:
4804   case tok::kw_void:
4805   case tok::kw_char:
4806   case tok::kw_wchar_t:
4807   case tok::kw_char8_t:
4808   case tok::kw_char16_t:
4809   case tok::kw_char32_t:
4810   case tok::kw_int:
4811   case tok::kw_half:
4812   case tok::kw_float:
4813   case tok::kw_double:
4814   case tok::kw__Accum:
4815   case tok::kw__Fract:
4816   case tok::kw__Float16:
4817   case tok::kw___float128:
4818   case tok::kw_bool:
4819   case tok::kw__Bool:
4820   case tok::kw__Decimal32:
4821   case tok::kw__Decimal64:
4822   case tok::kw__Decimal128:
4823   case tok::kw___vector:
4824 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4825 #include "clang/Basic/OpenCLImageTypes.def"
4826
4827     // struct-or-union-specifier (C99) or class-specifier (C++)
4828   case tok::kw_class:
4829   case tok::kw_struct:
4830   case tok::kw___interface:
4831   case tok::kw_union:
4832     // enum-specifier
4833   case tok::kw_enum:
4834
4835     // typedef-name
4836   case tok::annot_typename:
4837     return true;
4838   }
4839 }
4840
4841 /// isTypeSpecifierQualifier - Return true if the current token could be the
4842 /// start of a specifier-qualifier-list.
4843 bool Parser::isTypeSpecifierQualifier() {
4844   switch (Tok.getKind()) {
4845   default: return false;
4846
4847   case tok::identifier:   // foo::bar
4848     if (TryAltiVecVectorToken())
4849       return true;
4850     LLVM_FALLTHROUGH;
4851   case tok::kw_typename:  // typename T::type
4852     // Annotate typenames and C++ scope specifiers.  If we get one, just
4853     // recurse to handle whatever we get.
4854     if (TryAnnotateTypeOrScopeToken())
4855       return true;
4856     if (Tok.is(tok::identifier))
4857       return false;
4858     return isTypeSpecifierQualifier();
4859
4860   case tok::coloncolon:   // ::foo::bar
4861     if (NextToken().is(tok::kw_new) ||    // ::new
4862         NextToken().is(tok::kw_delete))   // ::delete
4863       return false;
4864
4865     if (TryAnnotateTypeOrScopeToken())
4866       return true;
4867     return isTypeSpecifierQualifier();
4868
4869     // GNU attributes support.
4870   case tok::kw___attribute:
4871     // GNU typeof support.
4872   case tok::kw_typeof:
4873
4874     // type-specifiers
4875   case tok::kw_short:
4876   case tok::kw_long:
4877   case tok::kw___int64:
4878   case tok::kw___int128:
4879   case tok::kw_signed:
4880   case tok::kw_unsigned:
4881   case tok::kw__Complex:
4882   case tok::kw__Imaginary:
4883   case tok::kw_void:
4884   case tok::kw_char:
4885   case tok::kw_wchar_t:
4886   case tok::kw_char8_t:
4887   case tok::kw_char16_t:
4888   case tok::kw_char32_t:
4889   case tok::kw_int:
4890   case tok::kw_half:
4891   case tok::kw_float:
4892   case tok::kw_double:
4893   case tok::kw__Accum:
4894   case tok::kw__Fract:
4895   case tok::kw__Float16:
4896   case tok::kw___float128:
4897   case tok::kw_bool:
4898   case tok::kw__Bool:
4899   case tok::kw__Decimal32:
4900   case tok::kw__Decimal64:
4901   case tok::kw__Decimal128:
4902   case tok::kw___vector:
4903 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4904 #include "clang/Basic/OpenCLImageTypes.def"
4905
4906     // struct-or-union-specifier (C99) or class-specifier (C++)
4907   case tok::kw_class:
4908   case tok::kw_struct:
4909   case tok::kw___interface:
4910   case tok::kw_union:
4911     // enum-specifier
4912   case tok::kw_enum:
4913
4914     // type-qualifier
4915   case tok::kw_const:
4916   case tok::kw_volatile:
4917   case tok::kw_restrict:
4918   case tok::kw__Sat:
4919
4920     // Debugger support.
4921   case tok::kw___unknown_anytype:
4922
4923     // typedef-name
4924   case tok::annot_typename:
4925     return true;
4926
4927     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4928   case tok::less:
4929     return getLangOpts().ObjC;
4930
4931   case tok::kw___cdecl:
4932   case tok::kw___stdcall:
4933   case tok::kw___fastcall:
4934   case tok::kw___thiscall:
4935   case tok::kw___regcall:
4936   case tok::kw___vectorcall:
4937   case tok::kw___w64:
4938   case tok::kw___ptr64:
4939   case tok::kw___ptr32:
4940   case tok::kw___pascal:
4941   case tok::kw___unaligned:
4942
4943   case tok::kw__Nonnull:
4944   case tok::kw__Nullable:
4945   case tok::kw__Null_unspecified:
4946
4947   case tok::kw___kindof:
4948
4949   case tok::kw___private:
4950   case tok::kw___local:
4951   case tok::kw___global:
4952   case tok::kw___constant:
4953   case tok::kw___generic:
4954   case tok::kw___read_only:
4955   case tok::kw___read_write:
4956   case tok::kw___write_only:
4957     return true;
4958
4959   case tok::kw_private:
4960     return getLangOpts().OpenCL;
4961
4962   // C11 _Atomic
4963   case tok::kw__Atomic:
4964     return true;
4965   }
4966 }
4967
4968 /// isDeclarationSpecifier() - Return true if the current token is part of a
4969 /// declaration specifier.
4970 ///
4971 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4972 /// this check is to disambiguate between an expression and a declaration.
4973 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4974   switch (Tok.getKind()) {
4975   default: return false;
4976
4977   case tok::kw_pipe:
4978     return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
4979            getLangOpts().OpenCLCPlusPlus;
4980
4981   case tok::identifier:   // foo::bar
4982     // Unfortunate hack to support "Class.factoryMethod" notation.
4983     if (getLangOpts().ObjC && NextToken().is(tok::period))
4984       return false;
4985     if (TryAltiVecVectorToken())
4986       return true;
4987     LLVM_FALLTHROUGH;
4988   case tok::kw_decltype: // decltype(T())::type
4989   case tok::kw_typename: // typename T::type
4990     // Annotate typenames and C++ scope specifiers.  If we get one, just
4991     // recurse to handle whatever we get.
4992     if (TryAnnotateTypeOrScopeToken())
4993       return true;
4994     if (Tok.is(tok::identifier))
4995       return false;
4996
4997     // If we're in Objective-C and we have an Objective-C class type followed
4998     // by an identifier and then either ':' or ']', in a place where an
4999     // expression is permitted, then this is probably a class message send
5000     // missing the initial '['. In this case, we won't consider this to be
5001     // the start of a declaration.
5002     if (DisambiguatingWithExpression &&
5003         isStartOfObjCClassMessageMissingOpenBracket())
5004       return false;
5005
5006     return isDeclarationSpecifier();
5007
5008   case tok::coloncolon:   // ::foo::bar
5009     if (NextToken().is(tok::kw_new) ||    // ::new
5010         NextToken().is(tok::kw_delete))   // ::delete
5011       return false;
5012
5013     // Annotate typenames and C++ scope specifiers.  If we get one, just
5014     // recurse to handle whatever we get.
5015     if (TryAnnotateTypeOrScopeToken())
5016       return true;
5017     return isDeclarationSpecifier();
5018
5019     // storage-class-specifier
5020   case tok::kw_typedef:
5021   case tok::kw_extern:
5022   case tok::kw___private_extern__:
5023   case tok::kw_static:
5024   case tok::kw_auto:
5025   case tok::kw___auto_type:
5026   case tok::kw_register:
5027   case tok::kw___thread:
5028   case tok::kw_thread_local:
5029   case tok::kw__Thread_local:
5030
5031     // Modules
5032   case tok::kw___module_private__:
5033
5034     // Debugger support
5035   case tok::kw___unknown_anytype:
5036
5037     // type-specifiers
5038   case tok::kw_short:
5039   case tok::kw_long:
5040   case tok::kw___int64:
5041   case tok::kw___int128:
5042   case tok::kw_signed:
5043   case tok::kw_unsigned:
5044   case tok::kw__Complex:
5045   case tok::kw__Imaginary:
5046   case tok::kw_void:
5047   case tok::kw_char:
5048   case tok::kw_wchar_t:
5049   case tok::kw_char8_t:
5050   case tok::kw_char16_t:
5051   case tok::kw_char32_t:
5052
5053   case tok::kw_int:
5054   case tok::kw_half:
5055   case tok::kw_float:
5056   case tok::kw_double:
5057   case tok::kw__Accum:
5058   case tok::kw__Fract:
5059   case tok::kw__Float16:
5060   case tok::kw___float128:
5061   case tok::kw_bool:
5062   case tok::kw__Bool:
5063   case tok::kw__Decimal32:
5064   case tok::kw__Decimal64:
5065   case tok::kw__Decimal128:
5066   case tok::kw___vector:
5067
5068     // struct-or-union-specifier (C99) or class-specifier (C++)
5069   case tok::kw_class:
5070   case tok::kw_struct:
5071   case tok::kw_union:
5072   case tok::kw___interface:
5073     // enum-specifier
5074   case tok::kw_enum:
5075
5076     // type-qualifier
5077   case tok::kw_const:
5078   case tok::kw_volatile:
5079   case tok::kw_restrict:
5080   case tok::kw__Sat:
5081
5082     // function-specifier
5083   case tok::kw_inline:
5084   case tok::kw_virtual:
5085   case tok::kw_explicit:
5086   case tok::kw__Noreturn:
5087
5088     // alignment-specifier
5089   case tok::kw__Alignas:
5090
5091     // friend keyword.
5092   case tok::kw_friend:
5093
5094     // static_assert-declaration
5095   case tok::kw__Static_assert:
5096
5097     // GNU typeof support.
5098   case tok::kw_typeof:
5099
5100     // GNU attributes.
5101   case tok::kw___attribute:
5102
5103     // C++11 decltype and constexpr.
5104   case tok::annot_decltype:
5105   case tok::kw_constexpr:
5106
5107     // C++20 consteval and constinit.
5108   case tok::kw_consteval:
5109   case tok::kw_constinit:
5110
5111     // C11 _Atomic
5112   case tok::kw__Atomic:
5113     return true;
5114
5115     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5116   case tok::less:
5117     return getLangOpts().ObjC;
5118
5119     // typedef-name
5120   case tok::annot_typename:
5121     return !DisambiguatingWithExpression ||
5122            !isStartOfObjCClassMessageMissingOpenBracket();
5123
5124     // placeholder-type-specifier
5125   case tok::annot_template_id: {
5126     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
5127     return TemplateId->Kind == TNK_Concept_template &&
5128         (NextToken().is(tok::kw_auto) || NextToken().is(tok::kw_decltype));
5129   }
5130
5131   case tok::kw___declspec:
5132   case tok::kw___cdecl:
5133   case tok::kw___stdcall:
5134   case tok::kw___fastcall:
5135   case tok::kw___thiscall:
5136   case tok::kw___regcall:
5137   case tok::kw___vectorcall:
5138   case tok::kw___w64:
5139   case tok::kw___sptr:
5140   case tok::kw___uptr:
5141   case tok::kw___ptr64:
5142   case tok::kw___ptr32:
5143   case tok::kw___forceinline:
5144   case tok::kw___pascal:
5145   case tok::kw___unaligned:
5146
5147   case tok::kw__Nonnull:
5148   case tok::kw__Nullable:
5149   case tok::kw__Null_unspecified:
5150
5151   case tok::kw___kindof:
5152
5153   case tok::kw___private:
5154   case tok::kw___local:
5155   case tok::kw___global:
5156   case tok::kw___constant:
5157   case tok::kw___generic:
5158   case tok::kw___read_only:
5159   case tok::kw___read_write:
5160   case tok::kw___write_only:
5161 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5162 #include "clang/Basic/OpenCLImageTypes.def"
5163
5164     return true;
5165
5166   case tok::kw_private:
5167     return getLangOpts().OpenCL;
5168   }
5169 }
5170
5171 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5172   TentativeParsingAction TPA(*this);
5173
5174   // Parse the C++ scope specifier.
5175   CXXScopeSpec SS;
5176   if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
5177                                      /*EnteringContext=*/true)) {
5178     TPA.Revert();
5179     return false;
5180   }
5181
5182   // Parse the constructor name.
5183   if (Tok.is(tok::identifier)) {
5184     // We already know that we have a constructor name; just consume
5185     // the token.
5186     ConsumeToken();
5187   } else if (Tok.is(tok::annot_template_id)) {
5188     ConsumeAnnotationToken();
5189   } else {
5190     TPA.Revert();
5191     return false;
5192   }
5193
5194   // There may be attributes here, appertaining to the constructor name or type
5195   // we just stepped past.
5196   SkipCXX11Attributes();
5197
5198   // Current class name must be followed by a left parenthesis.
5199   if (Tok.isNot(tok::l_paren)) {
5200     TPA.Revert();
5201     return false;
5202   }
5203   ConsumeParen();
5204
5205   // A right parenthesis, or ellipsis followed by a right parenthesis signals
5206   // that we have a constructor.
5207   if (Tok.is(tok::r_paren) ||
5208       (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5209     TPA.Revert();
5210     return true;
5211   }
5212
5213   // A C++11 attribute here signals that we have a constructor, and is an
5214   // attribute on the first constructor parameter.
5215   if (getLangOpts().CPlusPlus11 &&
5216       isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5217                                 /*OuterMightBeMessageSend*/ true)) {
5218     TPA.Revert();
5219     return true;
5220   }
5221
5222   // If we need to, enter the specified scope.
5223   DeclaratorScopeObj DeclScopeObj(*this, SS);
5224   if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5225     DeclScopeObj.EnterDeclaratorScope();
5226
5227   // Optionally skip Microsoft attributes.
5228   ParsedAttributes Attrs(AttrFactory);
5229   MaybeParseMicrosoftAttributes(Attrs);
5230
5231   // Check whether the next token(s) are part of a declaration
5232   // specifier, in which case we have the start of a parameter and,
5233   // therefore, we know that this is a constructor.
5234   bool IsConstructor = false;
5235   if (isDeclarationSpecifier())
5236     IsConstructor = true;
5237   else if (Tok.is(tok::identifier) ||
5238            (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5239     // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5240     // This might be a parenthesized member name, but is more likely to
5241     // be a constructor declaration with an invalid argument type. Keep
5242     // looking.
5243     if (Tok.is(tok::annot_cxxscope))
5244       ConsumeAnnotationToken();
5245     ConsumeToken();
5246
5247     // If this is not a constructor, we must be parsing a declarator,
5248     // which must have one of the following syntactic forms (see the
5249     // grammar extract at the start of ParseDirectDeclarator):
5250     switch (Tok.getKind()) {
5251     case tok::l_paren:
5252       // C(X   (   int));
5253     case tok::l_square:
5254       // C(X   [   5]);
5255       // C(X   [   [attribute]]);
5256     case tok::coloncolon:
5257       // C(X   ::   Y);
5258       // C(X   ::   *p);
5259       // Assume this isn't a constructor, rather than assuming it's a
5260       // constructor with an unnamed parameter of an ill-formed type.
5261       break;
5262
5263     case tok::r_paren:
5264       // C(X   )
5265
5266       // Skip past the right-paren and any following attributes to get to
5267       // the function body or trailing-return-type.
5268       ConsumeParen();
5269       SkipCXX11Attributes();
5270
5271       if (DeductionGuide) {
5272         // C(X) -> ... is a deduction guide.
5273         IsConstructor = Tok.is(tok::arrow);
5274         break;
5275       }
5276       if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5277         // Assume these were meant to be constructors:
5278         //   C(X)   :    (the name of a bit-field cannot be parenthesized).
5279         //   C(X)   try  (this is otherwise ill-formed).
5280         IsConstructor = true;
5281       }
5282       if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5283         // If we have a constructor name within the class definition,
5284         // assume these were meant to be constructors:
5285         //   C(X)   {
5286         //   C(X)   ;
5287         // ... because otherwise we would be declaring a non-static data
5288         // member that is ill-formed because it's of the same type as its
5289         // surrounding class.
5290         //
5291         // FIXME: We can actually do this whether or not the name is qualified,
5292         // because if it is qualified in this context it must be being used as
5293         // a constructor name.
5294         // currently, so we're somewhat conservative here.
5295         IsConstructor = IsUnqualified;
5296       }
5297       break;
5298
5299     default:
5300       IsConstructor = true;
5301       break;
5302     }
5303   }
5304
5305   TPA.Revert();
5306   return IsConstructor;
5307 }
5308
5309 /// ParseTypeQualifierListOpt
5310 ///          type-qualifier-list: [C99 6.7.5]
5311 ///            type-qualifier
5312 /// [vendor]   attributes
5313 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
5314 ///            type-qualifier-list type-qualifier
5315 /// [vendor]   type-qualifier-list attributes
5316 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
5317 /// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
5318 ///              [ only if AttReqs & AR_CXX11AttributesParsed ]
5319 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5320 /// AttrRequirements bitmask values.
5321 void Parser::ParseTypeQualifierListOpt(
5322     DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5323     bool IdentifierRequired,
5324     Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5325   if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5326       isCXX11AttributeSpecifier()) {
5327     ParsedAttributesWithRange attrs(AttrFactory);
5328     ParseCXX11Attributes(attrs);
5329     DS.takeAttributesFrom(attrs);
5330   }
5331
5332   SourceLocation EndLoc;
5333
5334   while (1) {
5335     bool isInvalid = false;
5336     const char *PrevSpec = nullptr;
5337     unsigned DiagID = 0;
5338     SourceLocation Loc = Tok.getLocation();
5339
5340     switch (Tok.getKind()) {
5341     case tok::code_completion:
5342       if (CodeCompletionHandler)
5343         (*CodeCompletionHandler)();
5344       else
5345         Actions.CodeCompleteTypeQualifiers(DS);
5346       return cutOffParsing();
5347
5348     case tok::kw_const:
5349       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
5350                                  getLangOpts());
5351       break;
5352     case tok::kw_volatile:
5353       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5354                                  getLangOpts());
5355       break;
5356     case tok::kw_restrict:
5357       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5358                                  getLangOpts());
5359       break;
5360     case tok::kw__Atomic:
5361       if (!AtomicAllowed)
5362         goto DoneWithTypeQuals;
5363       if (!getLangOpts().C11)
5364         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5365       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5366                                  getLangOpts());
5367       break;
5368
5369     // OpenCL qualifiers:
5370     case tok::kw_private:
5371       if (!getLangOpts().OpenCL)
5372         goto DoneWithTypeQuals;
5373       LLVM_FALLTHROUGH;
5374     case tok::kw___private:
5375     case tok::kw___global:
5376     case tok::kw___local:
5377     case tok::kw___constant:
5378     case tok::kw___generic:
5379     case tok::kw___read_only:
5380     case tok::kw___write_only:
5381     case tok::kw___read_write:
5382       ParseOpenCLQualifiers(DS.getAttributes());
5383       break;
5384
5385     case tok::kw___unaligned:
5386       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5387                                  getLangOpts());
5388       break;
5389     case tok::kw___uptr:
5390       // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5391       // with the MS modifier keyword.
5392       if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5393           IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5394         if (TryKeywordIdentFallback(false))
5395           continue;
5396       }
5397       LLVM_FALLTHROUGH;
5398     case tok::kw___sptr:
5399     case tok::kw___w64:
5400     case tok::kw___ptr64:
5401     case tok::kw___ptr32:
5402     case tok::kw___cdecl:
5403     case tok::kw___stdcall:
5404     case tok::kw___fastcall:
5405     case tok::kw___thiscall:
5406     case tok::kw___regcall:
5407     case tok::kw___vectorcall:
5408       if (AttrReqs & AR_DeclspecAttributesParsed) {
5409         ParseMicrosoftTypeAttributes(DS.getAttributes());
5410         continue;
5411       }
5412       goto DoneWithTypeQuals;
5413     case tok::kw___pascal:
5414       if (AttrReqs & AR_VendorAttributesParsed) {
5415         ParseBorlandTypeAttributes(DS.getAttributes());
5416         continue;
5417       }
5418       goto DoneWithTypeQuals;
5419
5420     // Nullability type specifiers.
5421     case tok::kw__Nonnull:
5422     case tok::kw__Nullable:
5423     case tok::kw__Null_unspecified:
5424       ParseNullabilityTypeSpecifiers(DS.getAttributes());
5425       continue;
5426
5427     // Objective-C 'kindof' types.
5428     case tok::kw___kindof:
5429       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5430                                 nullptr, 0, ParsedAttr::AS_Keyword);
5431       (void)ConsumeToken();
5432       continue;
5433
5434     case tok::kw___attribute:
5435       if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5436         // When GNU attributes are expressly forbidden, diagnose their usage.
5437         Diag(Tok, diag::err_attributes_not_allowed);
5438
5439       // Parse the attributes even if they are rejected to ensure that error
5440       // recovery is graceful.
5441       if (AttrReqs & AR_GNUAttributesParsed ||
5442           AttrReqs & AR_GNUAttributesParsedAndRejected) {
5443         ParseGNUAttributes(DS.getAttributes());
5444         continue; // do *not* consume the next token!
5445       }
5446       // otherwise, FALL THROUGH!
5447       LLVM_FALLTHROUGH;
5448     default:
5449       DoneWithTypeQuals:
5450       // If this is not a type-qualifier token, we're done reading type
5451       // qualifiers.  First verify that DeclSpec's are consistent.
5452       DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5453       if (EndLoc.isValid())
5454         DS.SetRangeEnd(EndLoc);
5455       return;
5456     }
5457
5458     // If the specifier combination wasn't legal, issue a diagnostic.
5459     if (isInvalid) {
5460       assert(PrevSpec && "Method did not return previous specifier!");
5461       Diag(Tok, DiagID) << PrevSpec;
5462     }
5463     EndLoc = ConsumeToken();
5464   }
5465 }
5466
5467 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5468 ///
5469 void Parser::ParseDeclarator(Declarator &D) {
5470   /// This implements the 'declarator' production in the C grammar, then checks
5471   /// for well-formedness and issues diagnostics.
5472   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5473 }
5474
5475 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5476                                DeclaratorContext TheContext) {
5477   if (Kind == tok::star || Kind == tok::caret)
5478     return true;
5479
5480   if (Kind == tok::kw_pipe &&
5481       ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5482     return true;
5483
5484   if (!Lang.CPlusPlus)
5485     return false;
5486
5487   if (Kind == tok::amp)
5488     return true;
5489
5490   // We parse rvalue refs in C++03, because otherwise the errors are scary.
5491   // But we must not parse them in conversion-type-ids and new-type-ids, since
5492   // those can be legitimately followed by a && operator.
5493   // (The same thing can in theory happen after a trailing-return-type, but
5494   // since those are a C++11 feature, there is no rejects-valid issue there.)
5495   if (Kind == tok::ampamp)
5496     return Lang.CPlusPlus11 ||
5497            (TheContext != DeclaratorContext::ConversionIdContext &&
5498             TheContext != DeclaratorContext::CXXNewContext);
5499
5500   return false;
5501 }
5502
5503 // Indicates whether the given declarator is a pipe declarator.
5504 static bool isPipeDeclerator(const Declarator &D) {
5505   const unsigned NumTypes = D.getNumTypeObjects();
5506
5507   for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5508     if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5509       return true;
5510
5511   return false;
5512 }
5513
5514 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5515 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5516 /// isn't parsed at all, making this function effectively parse the C++
5517 /// ptr-operator production.
5518 ///
5519 /// If the grammar of this construct is extended, matching changes must also be
5520 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5521 /// isConstructorDeclarator.
5522 ///
5523 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5524 /// [C]     pointer[opt] direct-declarator
5525 /// [C++]   direct-declarator
5526 /// [C++]   ptr-operator declarator
5527 ///
5528 ///       pointer: [C99 6.7.5]
5529 ///         '*' type-qualifier-list[opt]
5530 ///         '*' type-qualifier-list[opt] pointer
5531 ///
5532 ///       ptr-operator:
5533 ///         '*' cv-qualifier-seq[opt]
5534 ///         '&'
5535 /// [C++0x] '&&'
5536 /// [GNU]   '&' restrict[opt] attributes[opt]
5537 /// [GNU?]  '&&' restrict[opt] attributes[opt]
5538 ///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5539 void Parser::ParseDeclaratorInternal(Declarator &D,
5540                                      DirectDeclParseFunction DirectDeclParser) {
5541   if (Diags.hasAllExtensionsSilenced())
5542     D.setExtension();
5543
5544   // C++ member pointers start with a '::' or a nested-name.
5545   // Member pointers get special handling, since there's no place for the
5546   // scope spec in the generic path below.
5547   if (getLangOpts().CPlusPlus &&
5548       (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5549        (Tok.is(tok::identifier) &&
5550         (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5551        Tok.is(tok::annot_cxxscope))) {
5552     bool EnteringContext =
5553         D.getContext() == DeclaratorContext::FileContext ||
5554         D.getContext() == DeclaratorContext::MemberContext;
5555     CXXScopeSpec SS;
5556     ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5557
5558     if (SS.isNotEmpty()) {
5559       if (Tok.isNot(tok::star)) {
5560         // The scope spec really belongs to the direct-declarator.
5561         if (D.mayHaveIdentifier())
5562           D.getCXXScopeSpec() = SS;
5563         else
5564           AnnotateScopeToken(SS, true);
5565
5566         if (DirectDeclParser)
5567           (this->*DirectDeclParser)(D);
5568         return;
5569       }
5570
5571       SourceLocation Loc = ConsumeToken();
5572       D.SetRangeEnd(Loc);
5573       DeclSpec DS(AttrFactory);
5574       ParseTypeQualifierListOpt(DS);
5575       D.ExtendWithDeclSpec(DS);
5576
5577       // Recurse to parse whatever is left.
5578       ParseDeclaratorInternal(D, DirectDeclParser);
5579
5580       // Sema will have to catch (syntactically invalid) pointers into global
5581       // scope. It has to catch pointers into namespace scope anyway.
5582       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5583                         SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5584                     std::move(DS.getAttributes()),
5585                     /* Don't replace range end. */ SourceLocation());
5586       return;
5587     }
5588   }
5589
5590   tok::TokenKind Kind = Tok.getKind();
5591
5592   if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5593     DeclSpec DS(AttrFactory);
5594     ParseTypeQualifierListOpt(DS);
5595
5596     D.AddTypeInfo(
5597         DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5598         std::move(DS.getAttributes()), SourceLocation());
5599   }
5600
5601   // Not a pointer, C++ reference, or block.
5602   if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5603     if (DirectDeclParser)
5604       (this->*DirectDeclParser)(D);
5605     return;
5606   }
5607
5608   // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5609   // '&&' -> rvalue reference
5610   SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
5611   D.SetRangeEnd(Loc);
5612
5613   if (Kind == tok::star || Kind == tok::caret) {
5614     // Is a pointer.
5615     DeclSpec DS(AttrFactory);
5616
5617     // GNU attributes are not allowed here in a new-type-id, but Declspec and
5618     // C++11 attributes are allowed.
5619     unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5620                     ((D.getContext() != DeclaratorContext::CXXNewContext)
5621                          ? AR_GNUAttributesParsed
5622                          : AR_GNUAttributesParsedAndRejected);
5623     ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5624     D.ExtendWithDeclSpec(DS);
5625
5626     // Recursively parse the declarator.
5627     ParseDeclaratorInternal(D, DirectDeclParser);
5628     if (Kind == tok::star)
5629       // Remember that we parsed a pointer type, and remember the type-quals.
5630       D.AddTypeInfo(DeclaratorChunk::getPointer(
5631                         DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5632                         DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5633                         DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5634                     std::move(DS.getAttributes()), SourceLocation());
5635     else
5636       // Remember that we parsed a Block type, and remember the type-quals.
5637       D.AddTypeInfo(
5638           DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5639           std::move(DS.getAttributes()), SourceLocation());
5640   } else {
5641     // Is a reference
5642     DeclSpec DS(AttrFactory);
5643
5644     // Complain about rvalue references in C++03, but then go on and build
5645     // the declarator.
5646     if (Kind == tok::ampamp)
5647       Diag(Loc, getLangOpts().CPlusPlus11 ?
5648            diag::warn_cxx98_compat_rvalue_reference :
5649            diag::ext_rvalue_reference);
5650
5651     // GNU-style and C++11 attributes are allowed here, as is restrict.
5652     ParseTypeQualifierListOpt(DS);
5653     D.ExtendWithDeclSpec(DS);
5654
5655     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5656     // cv-qualifiers are introduced through the use of a typedef or of a
5657     // template type argument, in which case the cv-qualifiers are ignored.
5658     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5659       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5660         Diag(DS.getConstSpecLoc(),
5661              diag::err_invalid_reference_qualifier_application) << "const";
5662       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5663         Diag(DS.getVolatileSpecLoc(),
5664              diag::err_invalid_reference_qualifier_application) << "volatile";
5665       // 'restrict' is permitted as an extension.
5666       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5667         Diag(DS.getAtomicSpecLoc(),
5668              diag::err_invalid_reference_qualifier_application) << "_Atomic";
5669     }
5670
5671     // Recursively parse the declarator.
5672     ParseDeclaratorInternal(D, DirectDeclParser);
5673
5674     if (D.getNumTypeObjects() > 0) {
5675       // C++ [dcl.ref]p4: There shall be no references to references.
5676       DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5677       if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5678         if (const IdentifierInfo *II = D.getIdentifier())
5679           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5680            << II;
5681         else
5682           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5683             << "type name";
5684
5685         // Once we've complained about the reference-to-reference, we
5686         // can go ahead and build the (technically ill-formed)
5687         // declarator: reference collapsing will take care of it.
5688       }
5689     }
5690
5691     // Remember that we parsed a reference type.
5692     D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5693                                                 Kind == tok::amp),
5694                   std::move(DS.getAttributes()), SourceLocation());
5695   }
5696 }
5697
5698 // When correcting from misplaced brackets before the identifier, the location
5699 // is saved inside the declarator so that other diagnostic messages can use
5700 // them.  This extracts and returns that location, or returns the provided
5701 // location if a stored location does not exist.
5702 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5703                                                 SourceLocation Loc) {
5704   if (D.getName().StartLocation.isInvalid() &&
5705       D.getName().EndLocation.isValid())
5706     return D.getName().EndLocation;
5707
5708   return Loc;
5709 }
5710
5711 /// ParseDirectDeclarator
5712 ///       direct-declarator: [C99 6.7.5]
5713 /// [C99]   identifier
5714 ///         '(' declarator ')'
5715 /// [GNU]   '(' attributes declarator ')'
5716 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
5717 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5718 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5719 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5720 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
5721 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5722 ///                    attribute-specifier-seq[opt]
5723 ///         direct-declarator '(' parameter-type-list ')'
5724 ///         direct-declarator '(' identifier-list[opt] ')'
5725 /// [GNU]   direct-declarator '(' parameter-forward-declarations
5726 ///                    parameter-type-list[opt] ')'
5727 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
5728 ///                    cv-qualifier-seq[opt] exception-specification[opt]
5729 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5730 ///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5731 ///                    ref-qualifier[opt] exception-specification[opt]
5732 /// [C++]   declarator-id
5733 /// [C++11] declarator-id attribute-specifier-seq[opt]
5734 ///
5735 ///       declarator-id: [C++ 8]
5736 ///         '...'[opt] id-expression
5737 ///         '::'[opt] nested-name-specifier[opt] type-name
5738 ///
5739 ///       id-expression: [C++ 5.1]
5740 ///         unqualified-id
5741 ///         qualified-id
5742 ///
5743 ///       unqualified-id: [C++ 5.1]
5744 ///         identifier
5745 ///         operator-function-id
5746 ///         conversion-function-id
5747 ///          '~' class-name
5748 ///         template-id
5749 ///
5750 /// C++17 adds the following, which we also handle here:
5751 ///
5752 ///       simple-declaration:
5753 ///         <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5754 ///
5755 /// Note, any additional constructs added here may need corresponding changes
5756 /// in isConstructorDeclarator.
5757 void Parser::ParseDirectDeclarator(Declarator &D) {
5758   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5759
5760   if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5761     // This might be a C++17 structured binding.
5762     if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5763         D.getCXXScopeSpec().isEmpty())
5764       return ParseDecompositionDeclarator(D);
5765
5766     // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5767     // this context it is a bitfield. Also in range-based for statement colon
5768     // may delimit for-range-declaration.
5769     ColonProtectionRAIIObject X(
5770         *this, D.getContext() == DeclaratorContext::MemberContext ||
5771                    (D.getContext() == DeclaratorContext::ForContext &&
5772                     getLangOpts().CPlusPlus11));
5773
5774     // ParseDeclaratorInternal might already have parsed the scope.
5775     if (D.getCXXScopeSpec().isEmpty()) {
5776       bool EnteringContext =
5777           D.getContext() == DeclaratorContext::FileContext ||
5778           D.getContext() == DeclaratorContext::MemberContext;
5779       ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5780                                      EnteringContext);
5781     }
5782
5783     if (D.getCXXScopeSpec().isValid()) {
5784       if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5785                                              D.getCXXScopeSpec()))
5786         // Change the declaration context for name lookup, until this function
5787         // is exited (and the declarator has been parsed).
5788         DeclScopeObj.EnterDeclaratorScope();
5789       else if (getObjCDeclContext()) {
5790         // Ensure that we don't interpret the next token as an identifier when
5791         // dealing with declarations in an Objective-C container.
5792         D.SetIdentifier(nullptr, Tok.getLocation());
5793         D.setInvalidType(true);
5794         ConsumeToken();
5795         goto PastIdentifier;
5796       }
5797     }
5798
5799     // C++0x [dcl.fct]p14:
5800     //   There is a syntactic ambiguity when an ellipsis occurs at the end of a
5801     //   parameter-declaration-clause without a preceding comma. In this case,
5802     //   the ellipsis is parsed as part of the abstract-declarator if the type
5803     //   of the parameter either names a template parameter pack that has not
5804     //   been expanded or contains auto; otherwise, it is parsed as part of the
5805     //   parameter-declaration-clause.
5806     if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5807         !((D.getContext() == DeclaratorContext::PrototypeContext ||
5808            D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5809            D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5810           NextToken().is(tok::r_paren) &&
5811           !D.hasGroupingParens() &&
5812           !Actions.containsUnexpandedParameterPacks(D) &&
5813           D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5814       SourceLocation EllipsisLoc = ConsumeToken();
5815       if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5816         // The ellipsis was put in the wrong place. Recover, and explain to
5817         // the user what they should have done.
5818         ParseDeclarator(D);
5819         if (EllipsisLoc.isValid())
5820           DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5821         return;
5822       } else
5823         D.setEllipsisLoc(EllipsisLoc);
5824
5825       // The ellipsis can't be followed by a parenthesized declarator. We
5826       // check for that in ParseParenDeclarator, after we have disambiguated
5827       // the l_paren token.
5828     }
5829
5830     if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5831                     tok::tilde)) {
5832       // We found something that indicates the start of an unqualified-id.
5833       // Parse that unqualified-id.
5834       bool AllowConstructorName;
5835       bool AllowDeductionGuide;
5836       if (D.getDeclSpec().hasTypeSpecifier()) {
5837         AllowConstructorName = false;
5838         AllowDeductionGuide = false;
5839       } else if (D.getCXXScopeSpec().isSet()) {
5840         AllowConstructorName =
5841           (D.getContext() == DeclaratorContext::FileContext ||
5842            D.getContext() == DeclaratorContext::MemberContext);
5843         AllowDeductionGuide = false;
5844       } else {
5845         AllowConstructorName =
5846             (D.getContext() == DeclaratorContext::MemberContext);
5847         AllowDeductionGuide =
5848           (D.getContext() == DeclaratorContext::FileContext ||
5849            D.getContext() == DeclaratorContext::MemberContext);
5850       }
5851
5852       bool HadScope = D.getCXXScopeSpec().isValid();
5853       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5854                              /*EnteringContext=*/true,
5855                              /*AllowDestructorName=*/true, AllowConstructorName,
5856                              AllowDeductionGuide, nullptr, nullptr,
5857                              D.getName()) ||
5858           // Once we're past the identifier, if the scope was bad, mark the
5859           // whole declarator bad.
5860           D.getCXXScopeSpec().isInvalid()) {
5861         D.SetIdentifier(nullptr, Tok.getLocation());
5862         D.setInvalidType(true);
5863       } else {
5864         // ParseUnqualifiedId might have parsed a scope specifier during error
5865         // recovery. If it did so, enter that scope.
5866         if (!HadScope && D.getCXXScopeSpec().isValid() &&
5867             Actions.ShouldEnterDeclaratorScope(getCurScope(),
5868                                                D.getCXXScopeSpec()))
5869           DeclScopeObj.EnterDeclaratorScope();
5870
5871         // Parsed the unqualified-id; update range information and move along.
5872         if (D.getSourceRange().getBegin().isInvalid())
5873           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5874         D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5875       }
5876       goto PastIdentifier;
5877     }
5878
5879     if (D.getCXXScopeSpec().isNotEmpty()) {
5880       // We have a scope specifier but no following unqualified-id.
5881       Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5882            diag::err_expected_unqualified_id)
5883           << /*C++*/1;
5884       D.SetIdentifier(nullptr, Tok.getLocation());
5885       goto PastIdentifier;
5886     }
5887   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5888     assert(!getLangOpts().CPlusPlus &&
5889            "There's a C++-specific check for tok::identifier above");
5890     assert(Tok.getIdentifierInfo() && "Not an identifier?");
5891     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5892     D.SetRangeEnd(Tok.getLocation());
5893     ConsumeToken();
5894     goto PastIdentifier;
5895   } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5896     // We're not allowed an identifier here, but we got one. Try to figure out
5897     // if the user was trying to attach a name to the type, or whether the name
5898     // is some unrelated trailing syntax.
5899     bool DiagnoseIdentifier = false;
5900     if (D.hasGroupingParens())
5901       // An identifier within parens is unlikely to be intended to be anything
5902       // other than a name being "declared".
5903       DiagnoseIdentifier = true;
5904     else if (D.getContext() == DeclaratorContext::TemplateArgContext)
5905       // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5906       DiagnoseIdentifier =
5907           NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5908     else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5909              D.getContext() == DeclaratorContext::AliasTemplateContext)
5910       // The most likely error is that the ';' was forgotten.
5911       DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5912     else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5913               D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
5914              !isCXX11VirtSpecifier(Tok))
5915       DiagnoseIdentifier = NextToken().isOneOf(
5916           tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5917     if (DiagnoseIdentifier) {
5918       Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5919         << FixItHint::CreateRemoval(Tok.getLocation());
5920       D.SetIdentifier(nullptr, Tok.getLocation());
5921       ConsumeToken();
5922       goto PastIdentifier;
5923     }
5924   }
5925
5926   if (Tok.is(tok::l_paren)) {
5927     // If this might be an abstract-declarator followed by a direct-initializer,
5928     // check whether this is a valid declarator chunk. If it can't be, assume
5929     // that it's an initializer instead.
5930     if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5931       RevertingTentativeParsingAction PA(*this);
5932       if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5933               TPResult::False) {
5934         D.SetIdentifier(nullptr, Tok.getLocation());
5935         goto PastIdentifier;
5936       }
5937     }
5938
5939     // direct-declarator: '(' declarator ')'
5940     // direct-declarator: '(' attributes declarator ')'
5941     // Example: 'char (*X)'   or 'int (*XX)(void)'
5942     ParseParenDeclarator(D);
5943
5944     // If the declarator was parenthesized, we entered the declarator
5945     // scope when parsing the parenthesized declarator, then exited
5946     // the scope already. Re-enter the scope, if we need to.
5947     if (D.getCXXScopeSpec().isSet()) {
5948       // If there was an error parsing parenthesized declarator, declarator
5949       // scope may have been entered before. Don't do it again.
5950       if (!D.isInvalidType() &&
5951           Actions.ShouldEnterDeclaratorScope(getCurScope(),
5952                                              D.getCXXScopeSpec()))
5953         // Change the declaration context for name lookup, until this function
5954         // is exited (and the declarator has been parsed).
5955         DeclScopeObj.EnterDeclaratorScope();
5956     }
5957   } else if (D.mayOmitIdentifier()) {
5958     // This could be something simple like "int" (in which case the declarator
5959     // portion is empty), if an abstract-declarator is allowed.
5960     D.SetIdentifier(nullptr, Tok.getLocation());
5961
5962     // The grammar for abstract-pack-declarator does not allow grouping parens.
5963     // FIXME: Revisit this once core issue 1488 is resolved.
5964     if (D.hasEllipsis() && D.hasGroupingParens())
5965       Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5966            diag::ext_abstract_pack_declarator_parens);
5967   } else {
5968     if (Tok.getKind() == tok::annot_pragma_parser_crash)
5969       LLVM_BUILTIN_TRAP;
5970     if (Tok.is(tok::l_square))
5971       return ParseMisplacedBracketDeclarator(D);
5972     if (D.getContext() == DeclaratorContext::MemberContext) {
5973       // Objective-C++: Detect C++ keywords and try to prevent further errors by
5974       // treating these keyword as valid member names.
5975       if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
5976           Tok.getIdentifierInfo() &&
5977           Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5978         Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5979              diag::err_expected_member_name_or_semi_objcxx_keyword)
5980             << Tok.getIdentifierInfo()
5981             << (D.getDeclSpec().isEmpty() ? SourceRange()
5982                                           : D.getDeclSpec().getSourceRange());
5983         D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5984         D.SetRangeEnd(Tok.getLocation());
5985         ConsumeToken();
5986         goto PastIdentifier;
5987       }
5988       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5989            diag::err_expected_member_name_or_semi)
5990           << (D.getDeclSpec().isEmpty() ? SourceRange()
5991                                         : D.getDeclSpec().getSourceRange());
5992     } else if (getLangOpts().CPlusPlus) {
5993       if (Tok.isOneOf(tok::period, tok::arrow))
5994         Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5995       else {
5996         SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5997         if (Tok.isAtStartOfLine() && Loc.isValid())
5998           Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5999               << getLangOpts().CPlusPlus;
6000         else
6001           Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6002                diag::err_expected_unqualified_id)
6003               << getLangOpts().CPlusPlus;
6004       }
6005     } else {
6006       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
6007            diag::err_expected_either)
6008           << tok::identifier << tok::l_paren;
6009     }
6010     D.SetIdentifier(nullptr, Tok.getLocation());
6011     D.setInvalidType(true);
6012   }
6013
6014  PastIdentifier:
6015   assert(D.isPastIdentifier() &&
6016          "Haven't past the location of the identifier yet?");
6017
6018   // Don't parse attributes unless we have parsed an unparenthesized name.
6019   if (D.hasName() && !D.getNumTypeObjects())
6020     MaybeParseCXX11Attributes(D);
6021
6022   while (1) {
6023     if (Tok.is(tok::l_paren)) {
6024       // Enter function-declaration scope, limiting any declarators to the
6025       // function prototype scope, including parameter declarators.
6026       ParseScope PrototypeScope(this,
6027                                 Scope::FunctionPrototypeScope|Scope::DeclScope|
6028                                 (D.isFunctionDeclaratorAFunctionDeclaration()
6029                                    ? Scope::FunctionDeclarationScope : 0));
6030
6031       // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6032       // In such a case, check if we actually have a function declarator; if it
6033       // is not, the declarator has been fully parsed.
6034       bool IsAmbiguous = false;
6035       if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6036         // The name of the declarator, if any, is tentatively declared within
6037         // a possible direct initializer.
6038         TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6039         bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
6040         TentativelyDeclaredIdentifiers.pop_back();
6041         if (!IsFunctionDecl)
6042           break;
6043       }
6044       ParsedAttributes attrs(AttrFactory);
6045       BalancedDelimiterTracker T(*this, tok::l_paren);
6046       T.consumeOpen();
6047       ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6048       PrototypeScope.Exit();
6049     } else if (Tok.is(tok::l_square)) {
6050       ParseBracketDeclarator(D);
6051     } else if (Tok.is(tok::kw_requires) && D.hasGroupingParens()) {
6052       // This declarator is declaring a function, but the requires clause is
6053       // in the wrong place:
6054       //   void (f() requires true);
6055       // instead of
6056       //   void f() requires true;
6057       // or
6058       //   void (f()) requires true;
6059       Diag(Tok, diag::err_requires_clause_inside_parens);
6060       ConsumeToken();
6061       ExprResult TrailingRequiresClause = Actions.CorrectDelayedTyposInExpr(
6062          ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6063       if (TrailingRequiresClause.isUsable() && D.isFunctionDeclarator() &&
6064           !D.hasTrailingRequiresClause())
6065         // We're already ill-formed if we got here but we'll accept it anyway.
6066         D.setTrailingRequiresClause(TrailingRequiresClause.get());
6067     } else {
6068       break;
6069     }
6070   }
6071 }
6072
6073 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6074   assert(Tok.is(tok::l_square));
6075
6076   // If this doesn't look like a structured binding, maybe it's a misplaced
6077   // array declarator.
6078   // FIXME: Consume the l_square first so we don't need extra lookahead for
6079   // this.
6080   if (!(NextToken().is(tok::identifier) &&
6081         GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6082       !(NextToken().is(tok::r_square) &&
6083         GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6084     return ParseMisplacedBracketDeclarator(D);
6085
6086   BalancedDelimiterTracker T(*this, tok::l_square);
6087   T.consumeOpen();
6088
6089   SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6090   while (Tok.isNot(tok::r_square)) {
6091     if (!Bindings.empty()) {
6092       if (Tok.is(tok::comma))
6093         ConsumeToken();
6094       else {
6095         if (Tok.is(tok::identifier)) {
6096           SourceLocation EndLoc = getEndOfPreviousToken();
6097           Diag(EndLoc, diag::err_expected)
6098               << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6099         } else {
6100           Diag(Tok, diag::err_expected_comma_or_rsquare);
6101         }
6102
6103         SkipUntil(tok::r_square, tok::comma, tok::identifier,
6104                   StopAtSemi | StopBeforeMatch);
6105         if (Tok.is(tok::comma))
6106           ConsumeToken();
6107         else if (Tok.isNot(tok::identifier))
6108           break;
6109       }
6110     }
6111
6112     if (Tok.isNot(tok::identifier)) {
6113       Diag(Tok, diag::err_expected) << tok::identifier;
6114       break;
6115     }
6116
6117     Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6118     ConsumeToken();
6119   }
6120
6121   if (Tok.isNot(tok::r_square))
6122     // We've already diagnosed a problem here.
6123     T.skipToEnd();
6124   else {
6125     // C++17 does not allow the identifier-list in a structured binding
6126     // to be empty.
6127     if (Bindings.empty())
6128       Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6129
6130     T.consumeClose();
6131   }
6132
6133   return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6134                                     T.getCloseLocation());
6135 }
6136
6137 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
6138 /// only called before the identifier, so these are most likely just grouping
6139 /// parens for precedence.  If we find that these are actually function
6140 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6141 ///
6142 ///       direct-declarator:
6143 ///         '(' declarator ')'
6144 /// [GNU]   '(' attributes declarator ')'
6145 ///         direct-declarator '(' parameter-type-list ')'
6146 ///         direct-declarator '(' identifier-list[opt] ')'
6147 /// [GNU]   direct-declarator '(' parameter-forward-declarations
6148 ///                    parameter-type-list[opt] ')'
6149 ///
6150 void Parser::ParseParenDeclarator(Declarator &D) {
6151   BalancedDelimiterTracker T(*this, tok::l_paren);
6152   T.consumeOpen();
6153
6154   assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6155
6156   // Eat any attributes before we look at whether this is a grouping or function
6157   // declarator paren.  If this is a grouping paren, the attribute applies to
6158   // the type being built up, for example:
6159   //     int (__attribute__(()) *x)(long y)
6160   // If this ends up not being a grouping paren, the attribute applies to the
6161   // first argument, for example:
6162   //     int (__attribute__(()) int x)
6163   // In either case, we need to eat any attributes to be able to determine what
6164   // sort of paren this is.
6165   //
6166   ParsedAttributes attrs(AttrFactory);
6167   bool RequiresArg = false;
6168   if (Tok.is(tok::kw___attribute)) {
6169     ParseGNUAttributes(attrs);
6170
6171     // We require that the argument list (if this is a non-grouping paren) be
6172     // present even if the attribute list was empty.
6173     RequiresArg = true;
6174   }
6175
6176   // Eat any Microsoft extensions.
6177   ParseMicrosoftTypeAttributes(attrs);
6178
6179   // Eat any Borland extensions.
6180   if  (Tok.is(tok::kw___pascal))
6181     ParseBorlandTypeAttributes(attrs);
6182
6183   // If we haven't past the identifier yet (or where the identifier would be
6184   // stored, if this is an abstract declarator), then this is probably just
6185   // grouping parens. However, if this could be an abstract-declarator, then
6186   // this could also be the start of function arguments (consider 'void()').
6187   bool isGrouping;
6188
6189   if (!D.mayOmitIdentifier()) {
6190     // If this can't be an abstract-declarator, this *must* be a grouping
6191     // paren, because we haven't seen the identifier yet.
6192     isGrouping = true;
6193   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
6194              (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6195               NextToken().is(tok::r_paren)) || // C++ int(...)
6196              isDeclarationSpecifier() ||       // 'int(int)' is a function.
6197              isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a function.
6198     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6199     // considered to be a type, not a K&R identifier-list.
6200     isGrouping = false;
6201   } else {
6202     // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6203     isGrouping = true;
6204   }
6205
6206   // If this is a grouping paren, handle:
6207   // direct-declarator: '(' declarator ')'
6208   // direct-declarator: '(' attributes declarator ')'
6209   if (isGrouping) {
6210     SourceLocation EllipsisLoc = D.getEllipsisLoc();
6211     D.setEllipsisLoc(SourceLocation());
6212
6213     bool hadGroupingParens = D.hasGroupingParens();
6214     D.setGroupingParens(true);
6215     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6216     // Match the ')'.
6217     T.consumeClose();
6218     D.AddTypeInfo(
6219         DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6220         std::move(attrs), T.getCloseLocation());
6221
6222     D.setGroupingParens(hadGroupingParens);
6223
6224     // An ellipsis cannot be placed outside parentheses.
6225     if (EllipsisLoc.isValid())
6226       DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6227
6228     return;
6229   }
6230
6231   // Okay, if this wasn't a grouping paren, it must be the start of a function
6232   // argument list.  Recognize that this declarator will never have an
6233   // identifier (and remember where it would have been), then call into
6234   // ParseFunctionDeclarator to handle of argument list.
6235   D.SetIdentifier(nullptr, Tok.getLocation());
6236
6237   // Enter function-declaration scope, limiting any declarators to the
6238   // function prototype scope, including parameter declarators.
6239   ParseScope PrototypeScope(this,
6240                             Scope::FunctionPrototypeScope | Scope::DeclScope |
6241                             (D.isFunctionDeclaratorAFunctionDeclaration()
6242                                ? Scope::FunctionDeclarationScope : 0));
6243   ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6244   PrototypeScope.Exit();
6245 }
6246
6247 void Parser::InitCXXThisScopeForDeclaratorIfRelevant(
6248     const Declarator &D, const DeclSpec &DS,
6249     llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope) {
6250   // C++11 [expr.prim.general]p3:
6251   //   If a declaration declares a member function or member function
6252   //   template of a class X, the expression this is a prvalue of type
6253   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6254   //   and the end of the function-definition, member-declarator, or
6255   //   declarator.
6256   // FIXME: currently, "static" case isn't handled correctly.
6257   bool IsCXX11MemberFunction = getLangOpts().CPlusPlus11 &&
6258         D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6259         (D.getContext() == DeclaratorContext::MemberContext
6260          ? !D.getDeclSpec().isFriendSpecified()
6261          : D.getContext() == DeclaratorContext::FileContext &&
6262            D.getCXXScopeSpec().isValid() &&
6263            Actions.CurContext->isRecord());
6264   if (!IsCXX11MemberFunction)
6265     return;
6266
6267   Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6268   if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6269     Q.addConst();
6270   // FIXME: Collect C++ address spaces.
6271   // If there are multiple different address spaces, the source is invalid.
6272   // Carry on using the first addr space for the qualifiers of 'this'.
6273   // The diagnostic will be given later while creating the function
6274   // prototype for the method.
6275   if (getLangOpts().OpenCLCPlusPlus) {
6276     for (ParsedAttr &attr : DS.getAttributes()) {
6277       LangAS ASIdx = attr.asOpenCLLangAS();
6278       if (ASIdx != LangAS::Default) {
6279         Q.addAddressSpace(ASIdx);
6280         break;
6281       }
6282     }
6283   }
6284   ThisScope.emplace(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6285                     IsCXX11MemberFunction);
6286 }
6287
6288 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6289 /// declarator D up to a paren, which indicates that we are parsing function
6290 /// arguments.
6291 ///
6292 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6293 /// immediately after the open paren - they should be considered to be the
6294 /// first argument of a parameter.
6295 ///
6296 /// If RequiresArg is true, then the first argument of the function is required
6297 /// to be present and required to not be an identifier list.
6298 ///
6299 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6300 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6301 /// (C++11) attribute-specifier-seq[opt], (C++11) trailing-return-type[opt] and
6302 /// (C++2a) the trailing requires-clause.
6303 ///
6304 /// [C++11] exception-specification:
6305 ///           dynamic-exception-specification
6306 ///           noexcept-specification
6307 ///
6308 void Parser::ParseFunctionDeclarator(Declarator &D,
6309                                      ParsedAttributes &FirstArgAttrs,
6310                                      BalancedDelimiterTracker &Tracker,
6311                                      bool IsAmbiguous,
6312                                      bool RequiresArg) {
6313   assert(getCurScope()->isFunctionPrototypeScope() &&
6314          "Should call from a Function scope");
6315   // lparen is already consumed!
6316   assert(D.isPastIdentifier() && "Should not call before identifier!");
6317
6318   // This should be true when the function has typed arguments.
6319   // Otherwise, it is treated as a K&R-style function.
6320   bool HasProto = false;
6321   // Build up an array of information about the parsed arguments.
6322   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6323   // Remember where we see an ellipsis, if any.
6324   SourceLocation EllipsisLoc;
6325
6326   DeclSpec DS(AttrFactory);
6327   bool RefQualifierIsLValueRef = true;
6328   SourceLocation RefQualifierLoc;
6329   ExceptionSpecificationType ESpecType = EST_None;
6330   SourceRange ESpecRange;
6331   SmallVector<ParsedType, 2> DynamicExceptions;
6332   SmallVector<SourceRange, 2> DynamicExceptionRanges;
6333   ExprResult NoexceptExpr;
6334   CachedTokens *ExceptionSpecTokens = nullptr;
6335   ParsedAttributesWithRange FnAttrs(AttrFactory);
6336   TypeResult TrailingReturnType;
6337
6338   /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6339      EndLoc is the end location for the function declarator.
6340      They differ for trailing return types. */
6341   SourceLocation StartLoc, LocalEndLoc, EndLoc;
6342   SourceLocation LParenLoc, RParenLoc;
6343   LParenLoc = Tracker.getOpenLocation();
6344   StartLoc = LParenLoc;
6345
6346   if (isFunctionDeclaratorIdentifierList()) {
6347     if (RequiresArg)
6348       Diag(Tok, diag::err_argument_required_after_attribute);
6349
6350     ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6351
6352     Tracker.consumeClose();
6353     RParenLoc = Tracker.getCloseLocation();
6354     LocalEndLoc = RParenLoc;
6355     EndLoc = RParenLoc;
6356
6357     // If there are attributes following the identifier list, parse them and
6358     // prohibit them.
6359     MaybeParseCXX11Attributes(FnAttrs);
6360     ProhibitAttributes(FnAttrs);
6361   } else {
6362     if (Tok.isNot(tok::r_paren))
6363       ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6364                                       EllipsisLoc);
6365     else if (RequiresArg)
6366       Diag(Tok, diag::err_argument_required_after_attribute);
6367
6368     HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6369                                 || getLangOpts().OpenCL;
6370
6371     // If we have the closing ')', eat it.
6372     Tracker.consumeClose();
6373     RParenLoc = Tracker.getCloseLocation();
6374     LocalEndLoc = RParenLoc;
6375     EndLoc = RParenLoc;
6376
6377     if (getLangOpts().CPlusPlus) {
6378       // FIXME: Accept these components in any order, and produce fixits to
6379       // correct the order if the user gets it wrong. Ideally we should deal
6380       // with the pure-specifier in the same way.
6381
6382       // Parse cv-qualifier-seq[opt].
6383       ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6384                                 /*AtomicAllowed*/ false,
6385                                 /*IdentifierRequired=*/false,
6386                                 llvm::function_ref<void()>([&]() {
6387                                   Actions.CodeCompleteFunctionQualifiers(DS, D);
6388                                 }));
6389       if (!DS.getSourceRange().getEnd().isInvalid()) {
6390         EndLoc = DS.getSourceRange().getEnd();
6391       }
6392
6393       // Parse ref-qualifier[opt].
6394       if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6395         EndLoc = RefQualifierLoc;
6396
6397       llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
6398       InitCXXThisScopeForDeclaratorIfRelevant(D, DS, ThisScope);
6399
6400       // Parse exception-specification[opt].
6401       bool Delayed = D.isFirstDeclarationOfMember() &&
6402                      D.isFunctionDeclaratorAFunctionDeclaration();
6403       if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6404           GetLookAheadToken(0).is(tok::kw_noexcept) &&
6405           GetLookAheadToken(1).is(tok::l_paren) &&
6406           GetLookAheadToken(2).is(tok::kw_noexcept) &&
6407           GetLookAheadToken(3).is(tok::l_paren) &&
6408           GetLookAheadToken(4).is(tok::identifier) &&
6409           GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6410         // HACK: We've got an exception-specification
6411         //   noexcept(noexcept(swap(...)))
6412         // or
6413         //   noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6414         // on a 'swap' member function. This is a libstdc++ bug; the lookup
6415         // for 'swap' will only find the function we're currently declaring,
6416         // whereas it expects to find a non-member swap through ADL. Turn off
6417         // delayed parsing to give it a chance to find what it expects.
6418         Delayed = false;
6419       }
6420       ESpecType = tryParseExceptionSpecification(Delayed,
6421                                                  ESpecRange,
6422                                                  DynamicExceptions,
6423                                                  DynamicExceptionRanges,
6424                                                  NoexceptExpr,
6425                                                  ExceptionSpecTokens);
6426       if (ESpecType != EST_None)
6427         EndLoc = ESpecRange.getEnd();
6428
6429       // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6430       // after the exception-specification.
6431       MaybeParseCXX11Attributes(FnAttrs);
6432
6433       // Parse trailing-return-type[opt].
6434       LocalEndLoc = EndLoc;
6435       if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6436         Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6437         if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6438           StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6439         LocalEndLoc = Tok.getLocation();
6440         SourceRange Range;
6441         TrailingReturnType =
6442             ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6443         EndLoc = Range.getEnd();
6444       }
6445     } else if (standardAttributesAllowed()) {
6446       MaybeParseCXX11Attributes(FnAttrs);
6447     }
6448   }
6449
6450   // Collect non-parameter declarations from the prototype if this is a function
6451   // declaration. They will be moved into the scope of the function. Only do
6452   // this in C and not C++, where the decls will continue to live in the
6453   // surrounding context.
6454   SmallVector<NamedDecl *, 0> DeclsInPrototype;
6455   if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6456       !getLangOpts().CPlusPlus) {
6457     for (Decl *D : getCurScope()->decls()) {
6458       NamedDecl *ND = dyn_cast<NamedDecl>(D);
6459       if (!ND || isa<ParmVarDecl>(ND))
6460         continue;
6461       DeclsInPrototype.push_back(ND);
6462     }
6463   }
6464
6465   // Remember that we parsed a function type, and remember the attributes.
6466   D.AddTypeInfo(DeclaratorChunk::getFunction(
6467                     HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6468                     ParamInfo.size(), EllipsisLoc, RParenLoc,
6469                     RefQualifierIsLValueRef, RefQualifierLoc,
6470                     /*MutableLoc=*/SourceLocation(),
6471                     ESpecType, ESpecRange, DynamicExceptions.data(),
6472                     DynamicExceptionRanges.data(), DynamicExceptions.size(),
6473                     NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6474                     ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6475                     LocalEndLoc, D, TrailingReturnType, &DS),
6476                 std::move(FnAttrs), EndLoc);
6477 }
6478
6479 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6480 /// true if a ref-qualifier is found.
6481 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6482                                SourceLocation &RefQualifierLoc) {
6483   if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6484     Diag(Tok, getLangOpts().CPlusPlus11 ?
6485          diag::warn_cxx98_compat_ref_qualifier :
6486          diag::ext_ref_qualifier);
6487
6488     RefQualifierIsLValueRef = Tok.is(tok::amp);
6489     RefQualifierLoc = ConsumeToken();
6490     return true;
6491   }
6492   return false;
6493 }
6494
6495 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6496 /// identifier list form for a K&R-style function:  void foo(a,b,c)
6497 ///
6498 /// Note that identifier-lists are only allowed for normal declarators, not for
6499 /// abstract-declarators.
6500 bool Parser::isFunctionDeclaratorIdentifierList() {
6501   return !getLangOpts().CPlusPlus
6502          && Tok.is(tok::identifier)
6503          && !TryAltiVecVectorToken()
6504          // K&R identifier lists can't have typedefs as identifiers, per C99
6505          // 6.7.5.3p11.
6506          && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6507          // Identifier lists follow a really simple grammar: the identifiers can
6508          // be followed *only* by a ", identifier" or ")".  However, K&R
6509          // identifier lists are really rare in the brave new modern world, and
6510          // it is very common for someone to typo a type in a non-K&R style
6511          // list.  If we are presented with something like: "void foo(intptr x,
6512          // float y)", we don't want to start parsing the function declarator as
6513          // though it is a K&R style declarator just because intptr is an
6514          // invalid type.
6515          //
6516          // To handle this, we check to see if the token after the first
6517          // identifier is a "," or ")".  Only then do we parse it as an
6518          // identifier list.
6519          && (!Tok.is(tok::eof) &&
6520              (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6521 }
6522
6523 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6524 /// we found a K&R-style identifier list instead of a typed parameter list.
6525 ///
6526 /// After returning, ParamInfo will hold the parsed parameters.
6527 ///
6528 ///       identifier-list: [C99 6.7.5]
6529 ///         identifier
6530 ///         identifier-list ',' identifier
6531 ///
6532 void Parser::ParseFunctionDeclaratorIdentifierList(
6533        Declarator &D,
6534        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6535   // If there was no identifier specified for the declarator, either we are in
6536   // an abstract-declarator, or we are in a parameter declarator which was found
6537   // to be abstract.  In abstract-declarators, identifier lists are not valid:
6538   // diagnose this.
6539   if (!D.getIdentifier())
6540     Diag(Tok, diag::ext_ident_list_in_param);
6541
6542   // Maintain an efficient lookup of params we have seen so far.
6543   llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6544
6545   do {
6546     // If this isn't an identifier, report the error and skip until ')'.
6547     if (Tok.isNot(tok::identifier)) {
6548       Diag(Tok, diag::err_expected) << tok::identifier;
6549       SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6550       // Forget we parsed anything.
6551       ParamInfo.clear();
6552       return;
6553     }
6554
6555     IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6556
6557     // Reject 'typedef int y; int test(x, y)', but continue parsing.
6558     if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6559       Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6560
6561     // Verify that the argument identifier has not already been mentioned.
6562     if (!ParamsSoFar.insert(ParmII).second) {
6563       Diag(Tok, diag::err_param_redefinition) << ParmII;
6564     } else {
6565       // Remember this identifier in ParamInfo.
6566       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6567                                                      Tok.getLocation(),
6568                                                      nullptr));
6569     }
6570
6571     // Eat the identifier.
6572     ConsumeToken();
6573     // The list continues if we see a comma.
6574   } while (TryConsumeToken(tok::comma));
6575 }
6576
6577 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6578 /// after the opening parenthesis. This function will not parse a K&R-style
6579 /// identifier list.
6580 ///
6581 /// D is the declarator being parsed.  If FirstArgAttrs is non-null, then the
6582 /// caller parsed those arguments immediately after the open paren - they should
6583 /// be considered to be part of the first parameter.
6584 ///
6585 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6586 /// be the location of the ellipsis, if any was parsed.
6587 ///
6588 ///       parameter-type-list: [C99 6.7.5]
6589 ///         parameter-list
6590 ///         parameter-list ',' '...'
6591 /// [C++]   parameter-list '...'
6592 ///
6593 ///       parameter-list: [C99 6.7.5]
6594 ///         parameter-declaration
6595 ///         parameter-list ',' parameter-declaration
6596 ///
6597 ///       parameter-declaration: [C99 6.7.5]
6598 ///         declaration-specifiers declarator
6599 /// [C++]   declaration-specifiers declarator '=' assignment-expression
6600 /// [C++11]                                       initializer-clause
6601 /// [GNU]   declaration-specifiers declarator attributes
6602 ///         declaration-specifiers abstract-declarator[opt]
6603 /// [C++]   declaration-specifiers abstract-declarator[opt]
6604 ///           '=' assignment-expression
6605 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
6606 /// [C++11] attribute-specifier-seq parameter-declaration
6607 ///
6608 void Parser::ParseParameterDeclarationClause(
6609        Declarator &D,
6610        ParsedAttributes &FirstArgAttrs,
6611        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6612        SourceLocation &EllipsisLoc) {
6613
6614   // Avoid exceeding the maximum function scope depth.
6615   // See https://bugs.llvm.org/show_bug.cgi?id=19607
6616   // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
6617   // getFunctionPrototypeDepth() - 1.
6618   if (getCurScope()->getFunctionPrototypeDepth() - 1 >
6619       ParmVarDecl::getMaxFunctionScopeDepth()) {
6620     Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
6621         << ParmVarDecl::getMaxFunctionScopeDepth();
6622     cutOffParsing();
6623     return;
6624   }
6625
6626   do {
6627     // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6628     // before deciding this was a parameter-declaration-clause.
6629     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6630       break;
6631
6632     // Parse the declaration-specifiers.
6633     // Just use the ParsingDeclaration "scope" of the declarator.
6634     DeclSpec DS(AttrFactory);
6635
6636     // Parse any C++11 attributes.
6637     MaybeParseCXX11Attributes(DS.getAttributes());
6638
6639     // Skip any Microsoft attributes before a param.
6640     MaybeParseMicrosoftAttributes(DS.getAttributes());
6641
6642     SourceLocation DSStart = Tok.getLocation();
6643
6644     // If the caller parsed attributes for the first argument, add them now.
6645     // Take them so that we only apply the attributes to the first parameter.
6646     // FIXME: If we can leave the attributes in the token stream somehow, we can
6647     // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6648     // too much hassle.
6649     DS.takeAttributesFrom(FirstArgAttrs);
6650
6651     ParseDeclarationSpecifiers(DS);
6652
6653
6654     // Parse the declarator.  This is "PrototypeContext" or
6655     // "LambdaExprParameterContext", because we must accept either
6656     // 'declarator' or 'abstract-declarator' here.
6657     Declarator ParmDeclarator(
6658         DS, D.getContext() == DeclaratorContext::LambdaExprContext
6659                 ? DeclaratorContext::LambdaExprParameterContext
6660                 : DeclaratorContext::PrototypeContext);
6661     ParseDeclarator(ParmDeclarator);
6662
6663     // Parse GNU attributes, if present.
6664     MaybeParseGNUAttributes(ParmDeclarator);
6665
6666     if (Tok.is(tok::kw_requires)) {
6667       // User tried to define a requires clause in a parameter declaration,
6668       // which is surely not a function declaration.
6669       // void f(int (*g)(int, int) requires true);
6670       Diag(Tok,
6671            diag::err_requires_clause_on_declarator_not_declaring_a_function);
6672       ConsumeToken();
6673       Actions.CorrectDelayedTyposInExpr(
6674          ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true));
6675     }
6676
6677     // Remember this parsed parameter in ParamInfo.
6678     IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6679
6680     // DefArgToks is used when the parsing of default arguments needs
6681     // to be delayed.
6682     std::unique_ptr<CachedTokens> DefArgToks;
6683
6684     // If no parameter was specified, verify that *something* was specified,
6685     // otherwise we have a missing type and identifier.
6686     if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6687         ParmDeclarator.getNumTypeObjects() == 0) {
6688       // Completely missing, emit error.
6689       Diag(DSStart, diag::err_missing_param);
6690     } else {
6691       // Otherwise, we have something.  Add it and let semantic analysis try
6692       // to grok it and add the result to the ParamInfo we are building.
6693
6694       // Last chance to recover from a misplaced ellipsis in an attempted
6695       // parameter pack declaration.
6696       if (Tok.is(tok::ellipsis) &&
6697           (NextToken().isNot(tok::r_paren) ||
6698            (!ParmDeclarator.getEllipsisLoc().isValid() &&
6699             !Actions.isUnexpandedParameterPackPermitted())) &&
6700           Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6701         DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6702
6703       // Inform the actions module about the parameter declarator, so it gets
6704       // added to the current scope.
6705       Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6706       // Parse the default argument, if any. We parse the default
6707       // arguments in all dialects; the semantic analysis in
6708       // ActOnParamDefaultArgument will reject the default argument in
6709       // C.
6710       if (Tok.is(tok::equal)) {
6711         SourceLocation EqualLoc = Tok.getLocation();
6712
6713         // Parse the default argument
6714         if (D.getContext() == DeclaratorContext::MemberContext) {
6715           // If we're inside a class definition, cache the tokens
6716           // corresponding to the default argument. We'll actually parse
6717           // them when we see the end of the class definition.
6718           DefArgToks.reset(new CachedTokens);
6719
6720           SourceLocation ArgStartLoc = NextToken().getLocation();
6721           if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6722             DefArgToks.reset();
6723             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6724           } else {
6725             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6726                                                       ArgStartLoc);
6727           }
6728         } else {
6729           // Consume the '='.
6730           ConsumeToken();
6731
6732           // The argument isn't actually potentially evaluated unless it is
6733           // used.
6734           EnterExpressionEvaluationContext Eval(
6735               Actions,
6736               Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6737               Param);
6738
6739           ExprResult DefArgResult;
6740           if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6741             Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6742             DefArgResult = ParseBraceInitializer();
6743           } else
6744             DefArgResult = ParseAssignmentExpression();
6745           DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6746           if (DefArgResult.isInvalid()) {
6747             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6748             SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6749           } else {
6750             // Inform the actions module about the default argument
6751             Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6752                                               DefArgResult.get());
6753           }
6754         }
6755       }
6756
6757       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6758                                           ParmDeclarator.getIdentifierLoc(),
6759                                           Param, std::move(DefArgToks)));
6760     }
6761
6762     if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6763       if (!getLangOpts().CPlusPlus) {
6764         // We have ellipsis without a preceding ',', which is ill-formed
6765         // in C. Complain and provide the fix.
6766         Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6767             << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6768       } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6769                  Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6770         // It looks like this was supposed to be a parameter pack. Warn and
6771         // point out where the ellipsis should have gone.
6772         SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6773         Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6774           << ParmEllipsis.isValid() << ParmEllipsis;
6775         if (ParmEllipsis.isValid()) {
6776           Diag(ParmEllipsis,
6777                diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6778         } else {
6779           Diag(ParmDeclarator.getIdentifierLoc(),
6780                diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6781             << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6782                                           "...")
6783             << !ParmDeclarator.hasName();
6784         }
6785         Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6786           << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6787       }
6788
6789       // We can't have any more parameters after an ellipsis.
6790       break;
6791     }
6792
6793     // If the next token is a comma, consume it and keep reading arguments.
6794   } while (TryConsumeToken(tok::comma));
6795 }
6796
6797 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
6798 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6799 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6800 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6801 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
6802 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6803 ///                           attribute-specifier-seq[opt]
6804 void Parser::ParseBracketDeclarator(Declarator &D) {
6805   if (CheckProhibitedCXX11Attribute())
6806     return;
6807
6808   BalancedDelimiterTracker T(*this, tok::l_square);
6809   T.consumeOpen();
6810
6811   // C array syntax has many features, but by-far the most common is [] and [4].
6812   // This code does a fast path to handle some of the most obvious cases.
6813   if (Tok.getKind() == tok::r_square) {
6814     T.consumeClose();
6815     ParsedAttributes attrs(AttrFactory);
6816     MaybeParseCXX11Attributes(attrs);
6817
6818     // Remember that we parsed the empty array type.
6819     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6820                                             T.getOpenLocation(),
6821                                             T.getCloseLocation()),
6822                   std::move(attrs), T.getCloseLocation());
6823     return;
6824   } else if (Tok.getKind() == tok::numeric_constant &&
6825              GetLookAheadToken(1).is(tok::r_square)) {
6826     // [4] is very common.  Parse the numeric constant expression.
6827     ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6828     ConsumeToken();
6829
6830     T.consumeClose();
6831     ParsedAttributes attrs(AttrFactory);
6832     MaybeParseCXX11Attributes(attrs);
6833
6834     // Remember that we parsed a array type, and remember its features.
6835     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6836                                             T.getOpenLocation(),
6837                                             T.getCloseLocation()),
6838                   std::move(attrs), T.getCloseLocation());
6839     return;
6840   } else if (Tok.getKind() == tok::code_completion) {
6841     Actions.CodeCompleteBracketDeclarator(getCurScope());
6842     return cutOffParsing();
6843   }
6844
6845   // If valid, this location is the position where we read the 'static' keyword.
6846   SourceLocation StaticLoc;
6847   TryConsumeToken(tok::kw_static, StaticLoc);
6848
6849   // If there is a type-qualifier-list, read it now.
6850   // Type qualifiers in an array subscript are a C99 feature.
6851   DeclSpec DS(AttrFactory);
6852   ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6853
6854   // If we haven't already read 'static', check to see if there is one after the
6855   // type-qualifier-list.
6856   if (!StaticLoc.isValid())
6857     TryConsumeToken(tok::kw_static, StaticLoc);
6858
6859   // Handle "direct-declarator [ type-qual-list[opt] * ]".
6860   bool isStar = false;
6861   ExprResult NumElements;
6862
6863   // Handle the case where we have '[*]' as the array size.  However, a leading
6864   // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
6865   // the token after the star is a ']'.  Since stars in arrays are
6866   // infrequent, use of lookahead is not costly here.
6867   if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6868     ConsumeToken();  // Eat the '*'.
6869
6870     if (StaticLoc.isValid()) {
6871       Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6872       StaticLoc = SourceLocation();  // Drop the static.
6873     }
6874     isStar = true;
6875   } else if (Tok.isNot(tok::r_square)) {
6876     // Note, in C89, this production uses the constant-expr production instead
6877     // of assignment-expr.  The only difference is that assignment-expr allows
6878     // things like '=' and '*='.  Sema rejects these in C89 mode because they
6879     // are not i-c-e's, so we don't need to distinguish between the two here.
6880
6881     // Parse the constant-expression or assignment-expression now (depending
6882     // on dialect).
6883     if (getLangOpts().CPlusPlus) {
6884       NumElements = ParseConstantExpression();
6885     } else {
6886       EnterExpressionEvaluationContext Unevaluated(
6887           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6888       NumElements =
6889           Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6890     }
6891   } else {
6892     if (StaticLoc.isValid()) {
6893       Diag(StaticLoc, diag::err_unspecified_size_with_static);
6894       StaticLoc = SourceLocation();  // Drop the static.
6895     }
6896   }
6897
6898   // If there was an error parsing the assignment-expression, recover.
6899   if (NumElements.isInvalid()) {
6900     D.setInvalidType(true);
6901     // If the expression was invalid, skip it.
6902     SkipUntil(tok::r_square, StopAtSemi);
6903     return;
6904   }
6905
6906   T.consumeClose();
6907
6908   MaybeParseCXX11Attributes(DS.getAttributes());
6909
6910   // Remember that we parsed a array type, and remember its features.
6911   D.AddTypeInfo(
6912       DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6913                                 isStar, NumElements.get(), T.getOpenLocation(),
6914                                 T.getCloseLocation()),
6915       std::move(DS.getAttributes()), T.getCloseLocation());
6916 }
6917
6918 /// Diagnose brackets before an identifier.
6919 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6920   assert(Tok.is(tok::l_square) && "Missing opening bracket");
6921   assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6922
6923   SourceLocation StartBracketLoc = Tok.getLocation();
6924   Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6925
6926   while (Tok.is(tok::l_square)) {
6927     ParseBracketDeclarator(TempDeclarator);
6928   }
6929
6930   // Stuff the location of the start of the brackets into the Declarator.
6931   // The diagnostics from ParseDirectDeclarator will make more sense if
6932   // they use this location instead.
6933   if (Tok.is(tok::semi))
6934     D.getName().EndLocation = StartBracketLoc;
6935
6936   SourceLocation SuggestParenLoc = Tok.getLocation();
6937
6938   // Now that the brackets are removed, try parsing the declarator again.
6939   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6940
6941   // Something went wrong parsing the brackets, in which case,
6942   // ParseBracketDeclarator has emitted an error, and we don't need to emit
6943   // one here.
6944   if (TempDeclarator.getNumTypeObjects() == 0)
6945     return;
6946
6947   // Determine if parens will need to be suggested in the diagnostic.
6948   bool NeedParens = false;
6949   if (D.getNumTypeObjects() != 0) {
6950     switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6951     case DeclaratorChunk::Pointer:
6952     case DeclaratorChunk::Reference:
6953     case DeclaratorChunk::BlockPointer:
6954     case DeclaratorChunk::MemberPointer:
6955     case DeclaratorChunk::Pipe:
6956       NeedParens = true;
6957       break;
6958     case DeclaratorChunk::Array:
6959     case DeclaratorChunk::Function:
6960     case DeclaratorChunk::Paren:
6961       break;
6962     }
6963   }
6964
6965   if (NeedParens) {
6966     // Create a DeclaratorChunk for the inserted parens.
6967     SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6968     D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
6969                   SourceLocation());
6970   }
6971
6972   // Adding back the bracket info to the end of the Declarator.
6973   for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6974     const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6975     D.AddTypeInfo(Chunk, SourceLocation());
6976   }
6977
6978   // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6979   // If parentheses are required, always suggest them.
6980   if (!D.getIdentifier() && !NeedParens)
6981     return;
6982
6983   SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
6984
6985   // Generate the move bracket error message.
6986   SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6987   SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6988
6989   if (NeedParens) {
6990     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6991         << getLangOpts().CPlusPlus
6992         << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6993         << FixItHint::CreateInsertion(EndLoc, ")")
6994         << FixItHint::CreateInsertionFromRange(
6995                EndLoc, CharSourceRange(BracketRange, true))
6996         << FixItHint::CreateRemoval(BracketRange);
6997   } else {
6998     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6999         << getLangOpts().CPlusPlus
7000         << FixItHint::CreateInsertionFromRange(
7001                EndLoc, CharSourceRange(BracketRange, true))
7002         << FixItHint::CreateRemoval(BracketRange);
7003   }
7004 }
7005
7006 /// [GNU]   typeof-specifier:
7007 ///           typeof ( expressions )
7008 ///           typeof ( type-name )
7009 /// [GNU/C++] typeof unary-expression
7010 ///
7011 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
7012   assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
7013   Token OpTok = Tok;
7014   SourceLocation StartLoc = ConsumeToken();
7015
7016   const bool hasParens = Tok.is(tok::l_paren);
7017
7018   EnterExpressionEvaluationContext Unevaluated(
7019       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
7020       Sema::ReuseLambdaContextDecl);
7021
7022   bool isCastExpr;
7023   ParsedType CastTy;
7024   SourceRange CastRange;
7025   ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
7026       ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
7027   if (hasParens)
7028     DS.setTypeofParensRange(CastRange);
7029
7030   if (CastRange.getEnd().isInvalid())
7031     // FIXME: Not accurate, the range gets one token more than it should.
7032     DS.SetRangeEnd(Tok.getLocation());
7033   else
7034     DS.SetRangeEnd(CastRange.getEnd());
7035
7036   if (isCastExpr) {
7037     if (!CastTy) {
7038       DS.SetTypeSpecError();
7039       return;
7040     }
7041
7042     const char *PrevSpec = nullptr;
7043     unsigned DiagID;
7044     // Check for duplicate type specifiers (e.g. "int typeof(int)").
7045     if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
7046                            DiagID, CastTy,
7047                            Actions.getASTContext().getPrintingPolicy()))
7048       Diag(StartLoc, DiagID) << PrevSpec;
7049     return;
7050   }
7051
7052   // If we get here, the operand to the typeof was an expression.
7053   if (Operand.isInvalid()) {
7054     DS.SetTypeSpecError();
7055     return;
7056   }
7057
7058   // We might need to transform the operand if it is potentially evaluated.
7059   Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7060   if (Operand.isInvalid()) {
7061     DS.SetTypeSpecError();
7062     return;
7063   }
7064
7065   const char *PrevSpec = nullptr;
7066   unsigned DiagID;
7067   // Check for duplicate type specifiers (e.g. "int typeof(int)").
7068   if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
7069                          DiagID, Operand.get(),
7070                          Actions.getASTContext().getPrintingPolicy()))
7071     Diag(StartLoc, DiagID) << PrevSpec;
7072 }
7073
7074 /// [C11]   atomic-specifier:
7075 ///           _Atomic ( type-name )
7076 ///
7077 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7078   assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7079          "Not an atomic specifier");
7080
7081   SourceLocation StartLoc = ConsumeToken();
7082   BalancedDelimiterTracker T(*this, tok::l_paren);
7083   if (T.consumeOpen())
7084     return;
7085
7086   TypeResult Result = ParseTypeName();
7087   if (Result.isInvalid()) {
7088     SkipUntil(tok::r_paren, StopAtSemi);
7089     return;
7090   }
7091
7092   // Match the ')'
7093   T.consumeClose();
7094
7095   if (T.getCloseLocation().isInvalid())
7096     return;
7097
7098   DS.setTypeofParensRange(T.getRange());
7099   DS.SetRangeEnd(T.getCloseLocation());
7100
7101   const char *PrevSpec = nullptr;
7102   unsigned DiagID;
7103   if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7104                          DiagID, Result.get(),
7105                          Actions.getASTContext().getPrintingPolicy()))
7106     Diag(StartLoc, DiagID) << PrevSpec;
7107 }
7108
7109 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7110 /// from TryAltiVecVectorToken.
7111 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7112   Token Next = NextToken();
7113   switch (Next.getKind()) {
7114   default: return false;
7115   case tok::kw_short:
7116   case tok::kw_long:
7117   case tok::kw_signed:
7118   case tok::kw_unsigned:
7119   case tok::kw_void:
7120   case tok::kw_char:
7121   case tok::kw_int:
7122   case tok::kw_float:
7123   case tok::kw_double:
7124   case tok::kw_bool:
7125   case tok::kw___bool:
7126   case tok::kw___pixel:
7127     Tok.setKind(tok::kw___vector);
7128     return true;
7129   case tok::identifier:
7130     if (Next.getIdentifierInfo() == Ident_pixel) {
7131       Tok.setKind(tok::kw___vector);
7132       return true;
7133     }
7134     if (Next.getIdentifierInfo() == Ident_bool) {
7135       Tok.setKind(tok::kw___vector);
7136       return true;
7137     }
7138     return false;
7139   }
7140 }
7141
7142 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7143                                       const char *&PrevSpec, unsigned &DiagID,
7144                                       bool &isInvalid) {
7145   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7146   if (Tok.getIdentifierInfo() == Ident_vector) {
7147     Token Next = NextToken();
7148     switch (Next.getKind()) {
7149     case tok::kw_short:
7150     case tok::kw_long:
7151     case tok::kw_signed:
7152     case tok::kw_unsigned:
7153     case tok::kw_void:
7154     case tok::kw_char:
7155     case tok::kw_int:
7156     case tok::kw_float:
7157     case tok::kw_double:
7158     case tok::kw_bool:
7159     case tok::kw___bool:
7160     case tok::kw___pixel:
7161       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7162       return true;
7163     case tok::identifier:
7164       if (Next.getIdentifierInfo() == Ident_pixel) {
7165         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7166         return true;
7167       }
7168       if (Next.getIdentifierInfo() == Ident_bool) {
7169         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7170         return true;
7171       }
7172       break;
7173     default:
7174       break;
7175     }
7176   } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7177              DS.isTypeAltiVecVector()) {
7178     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7179     return true;
7180   } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7181              DS.isTypeAltiVecVector()) {
7182     isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
7183     return true;
7184   }
7185   return false;
7186 }