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