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