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