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