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