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   // Save late-parsed attributes for now; they need to be parsed in the
2018   // appropriate function scope after the function Decl has been constructed.
2019   // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
2020   LateParsedAttrList LateParsedAttrs(true);
2021   if (D.isFunctionDeclarator()) {
2022     MaybeParseGNUAttributes(D, &LateParsedAttrs);
2023 
2024     // The _Noreturn keyword can't appear here, unlike the GNU noreturn
2025     // attribute. If we find the keyword here, tell the user to put it
2026     // at the start instead.
2027     if (Tok.is(tok::kw__Noreturn)) {
2028       SourceLocation Loc = ConsumeToken();
2029       const char *PrevSpec;
2030       unsigned DiagID;
2031 
2032       // We can offer a fixit if it's valid to mark this function as _Noreturn
2033       // and we don't have any other declarators in this declaration.
2034       bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2035       MaybeParseGNUAttributes(D, &LateParsedAttrs);
2036       Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2037 
2038       Diag(Loc, diag::err_c11_noreturn_misplaced)
2039           << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
2040           << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2041                     : FixItHint());
2042     }
2043   }
2044 
2045   // Check to see if we have a function *definition* which must have a body.
2046   if (D.isFunctionDeclarator() &&
2047       // Look at the next token to make sure that this isn't a function
2048       // declaration.  We have to check this because __attribute__ might be the
2049       // start of a function definition in GCC-extended K&R C.
2050       !isDeclarationAfterDeclarator()) {
2051 
2052     // Function definitions are only allowed at file scope and in C++ classes.
2053     // The C++ inline method definition case is handled elsewhere, so we only
2054     // need to handle the file scope definition case.
2055     if (Context == DeclaratorContext::FileContext) {
2056       if (isStartOfFunctionDefinition(D)) {
2057         if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2058           Diag(Tok, diag::err_function_declared_typedef);
2059 
2060           // Recover by treating the 'typedef' as spurious.
2061           DS.ClearStorageClassSpecs();
2062         }
2063 
2064         Decl *TheDecl =
2065           ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
2066         return Actions.ConvertDeclToDeclGroup(TheDecl);
2067       }
2068 
2069       if (isDeclarationSpecifier()) {
2070         // If there is an invalid declaration specifier right after the
2071         // function prototype, then we must be in a missing semicolon case
2072         // where this isn't actually a body.  Just fall through into the code
2073         // that handles it as a prototype, and let the top-level code handle
2074         // the erroneous declspec where it would otherwise expect a comma or
2075         // semicolon.
2076       } else {
2077         Diag(Tok, diag::err_expected_fn_body);
2078         SkipUntil(tok::semi);
2079         return nullptr;
2080       }
2081     } else {
2082       if (Tok.is(tok::l_brace)) {
2083         Diag(Tok, diag::err_function_definition_not_allowed);
2084         SkipMalformedDecl();
2085         return nullptr;
2086       }
2087     }
2088   }
2089 
2090   if (ParseAsmAttributesAfterDeclarator(D))
2091     return nullptr;
2092 
2093   // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2094   // must parse and analyze the for-range-initializer before the declaration is
2095   // analyzed.
2096   //
2097   // Handle the Objective-C for-in loop variable similarly, although we
2098   // don't need to parse the container in advance.
2099   if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
2100     bool IsForRangeLoop = false;
2101     if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2102       IsForRangeLoop = true;
2103       if (getLangOpts().OpenMP)
2104         Actions.startOpenMPCXXRangeFor();
2105       if (Tok.is(tok::l_brace))
2106         FRI->RangeExpr = ParseBraceInitializer();
2107       else
2108         FRI->RangeExpr = ParseExpression();
2109     }
2110 
2111     Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2112     if (IsForRangeLoop) {
2113       Actions.ActOnCXXForRangeDecl(ThisDecl);
2114     } else {
2115       // Obj-C for loop
2116       if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2117         VD->setObjCForDecl(true);
2118     }
2119     Actions.FinalizeDeclaration(ThisDecl);
2120     D.complete(ThisDecl);
2121     return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2122   }
2123 
2124   SmallVector<Decl *, 8> DeclsInGroup;
2125   Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2126       D, ParsedTemplateInfo(), FRI);
2127   if (LateParsedAttrs.size() > 0)
2128     ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2129   D.complete(FirstDecl);
2130   if (FirstDecl)
2131     DeclsInGroup.push_back(FirstDecl);
2132 
2133   bool ExpectSemi = Context != DeclaratorContext::ForContext;
2134 
2135   // If we don't have a comma, it is either the end of the list (a ';') or an
2136   // error, bail out.
2137   SourceLocation CommaLoc;
2138   while (TryConsumeToken(tok::comma, CommaLoc)) {
2139     if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
2140       // This comma was followed by a line-break and something which can't be
2141       // the start of a declarator. The comma was probably a typo for a
2142       // semicolon.
2143       Diag(CommaLoc, diag::err_expected_semi_declaration)
2144         << FixItHint::CreateReplacement(CommaLoc, ";");
2145       ExpectSemi = false;
2146       break;
2147     }
2148 
2149     // Parse the next declarator.
2150     D.clear();
2151     D.setCommaLoc(CommaLoc);
2152 
2153     // Accept attributes in an init-declarator.  In the first declarator in a
2154     // declaration, these would be part of the declspec.  In subsequent
2155     // declarators, they become part of the declarator itself, so that they
2156     // don't apply to declarators after *this* one.  Examples:
2157     //    short __attribute__((common)) var;    -> declspec
2158     //    short var __attribute__((common));    -> declarator
2159     //    short x, __attribute__((common)) var;    -> declarator
2160     MaybeParseGNUAttributes(D);
2161 
2162     // MSVC parses but ignores qualifiers after the comma as an extension.
2163     if (getLangOpts().MicrosoftExt)
2164       DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2165 
2166     ParseDeclarator(D);
2167     if (!D.isInvalidType()) {
2168       Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2169       D.complete(ThisDecl);
2170       if (ThisDecl)
2171         DeclsInGroup.push_back(ThisDecl);
2172     }
2173   }
2174 
2175   if (DeclEnd)
2176     *DeclEnd = Tok.getLocation();
2177 
2178   if (ExpectSemi &&
2179       ExpectAndConsumeSemi(Context == DeclaratorContext::FileContext
2180                            ? diag::err_invalid_token_after_toplevel_declarator
2181                            : diag::err_expected_semi_declaration)) {
2182     // Okay, there was no semicolon and one was expected.  If we see a
2183     // declaration specifier, just assume it was missing and continue parsing.
2184     // Otherwise things are very confused and we skip to recover.
2185     if (!isDeclarationSpecifier()) {
2186       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2187       TryConsumeToken(tok::semi);
2188     }
2189   }
2190 
2191   return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2192 }
2193 
2194 /// Parse an optional simple-asm-expr and attributes, and attach them to a
2195 /// declarator. Returns true on an error.
2196 bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2197   // If a simple-asm-expr is present, parse it.
2198   if (Tok.is(tok::kw_asm)) {
2199     SourceLocation Loc;
2200     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
2201     if (AsmLabel.isInvalid()) {
2202       SkipUntil(tok::semi, StopBeforeMatch);
2203       return true;
2204     }
2205 
2206     D.setAsmLabel(AsmLabel.get());
2207     D.SetRangeEnd(Loc);
2208   }
2209 
2210   MaybeParseGNUAttributes(D);
2211   return false;
2212 }
2213 
2214 /// Parse 'declaration' after parsing 'declaration-specifiers
2215 /// declarator'. This method parses the remainder of the declaration
2216 /// (including any attributes or initializer, among other things) and
2217 /// finalizes the declaration.
2218 ///
2219 ///       init-declarator: [C99 6.7]
2220 ///         declarator
2221 ///         declarator '=' initializer
2222 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
2223 /// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2224 /// [C++]   declarator initializer[opt]
2225 ///
2226 /// [C++] initializer:
2227 /// [C++]   '=' initializer-clause
2228 /// [C++]   '(' expression-list ')'
2229 /// [C++0x] '=' 'default'                                                [TODO]
2230 /// [C++0x] '=' 'delete'
2231 /// [C++0x] braced-init-list
2232 ///
2233 /// According to the standard grammar, =default and =delete are function
2234 /// definitions, but that definitely doesn't fit with the parser here.
2235 ///
2236 Decl *Parser::ParseDeclarationAfterDeclarator(
2237     Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2238   if (ParseAsmAttributesAfterDeclarator(D))
2239     return nullptr;
2240 
2241   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2242 }
2243 
2244 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2245     Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2246   // RAII type used to track whether we're inside an initializer.
2247   struct InitializerScopeRAII {
2248     Parser &P;
2249     Declarator &D;
2250     Decl *ThisDecl;
2251 
2252     InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2253         : P(P), D(D), ThisDecl(ThisDecl) {
2254       if (ThisDecl && P.getLangOpts().CPlusPlus) {
2255         Scope *S = nullptr;
2256         if (D.getCXXScopeSpec().isSet()) {
2257           P.EnterScope(0);
2258           S = P.getCurScope();
2259         }
2260         P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2261       }
2262     }
2263     ~InitializerScopeRAII() { pop(); }
2264     void pop() {
2265       if (ThisDecl && P.getLangOpts().CPlusPlus) {
2266         Scope *S = nullptr;
2267         if (D.getCXXScopeSpec().isSet())
2268           S = P.getCurScope();
2269         P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2270         if (S)
2271           P.ExitScope();
2272       }
2273       ThisDecl = nullptr;
2274     }
2275   };
2276 
2277   // Inform the current actions module that we just parsed this declarator.
2278   Decl *ThisDecl = nullptr;
2279   switch (TemplateInfo.Kind) {
2280   case ParsedTemplateInfo::NonTemplate:
2281     ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2282     break;
2283 
2284   case ParsedTemplateInfo::Template:
2285   case ParsedTemplateInfo::ExplicitSpecialization: {
2286     ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2287                                                *TemplateInfo.TemplateParams,
2288                                                D);
2289     if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
2290       // Re-direct this decl to refer to the templated decl so that we can
2291       // initialize it.
2292       ThisDecl = VT->getTemplatedDecl();
2293     break;
2294   }
2295   case ParsedTemplateInfo::ExplicitInstantiation: {
2296     if (Tok.is(tok::semi)) {
2297       DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2298           getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2299       if (ThisRes.isInvalid()) {
2300         SkipUntil(tok::semi, StopBeforeMatch);
2301         return nullptr;
2302       }
2303       ThisDecl = ThisRes.get();
2304     } else {
2305       // FIXME: This check should be for a variable template instantiation only.
2306 
2307       // Check that this is a valid instantiation
2308       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2309         // If the declarator-id is not a template-id, issue a diagnostic and
2310         // recover by ignoring the 'template' keyword.
2311         Diag(Tok, diag::err_template_defn_explicit_instantiation)
2312             << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2313         ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2314       } else {
2315         SourceLocation LAngleLoc =
2316             PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2317         Diag(D.getIdentifierLoc(),
2318              diag::err_explicit_instantiation_with_definition)
2319             << SourceRange(TemplateInfo.TemplateLoc)
2320             << FixItHint::CreateInsertion(LAngleLoc, "<>");
2321 
2322         // Recover as if it were an explicit specialization.
2323         TemplateParameterLists FakedParamLists;
2324         FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2325             0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2326             LAngleLoc, nullptr));
2327 
2328         ThisDecl =
2329             Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2330       }
2331     }
2332     break;
2333     }
2334   }
2335 
2336   // Parse declarator '=' initializer.
2337   // If a '==' or '+=' is found, suggest a fixit to '='.
2338   if (isTokenEqualOrEqualTypo()) {
2339     SourceLocation EqualLoc = ConsumeToken();
2340 
2341     if (Tok.is(tok::kw_delete)) {
2342       if (D.isFunctionDeclarator())
2343         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2344           << 1 /* delete */;
2345       else
2346         Diag(ConsumeToken(), diag::err_deleted_non_function);
2347     } else if (Tok.is(tok::kw_default)) {
2348       if (D.isFunctionDeclarator())
2349         Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2350           << 0 /* default */;
2351       else
2352         Diag(ConsumeToken(), diag::err_default_special_members)
2353             << getLangOpts().CPlusPlus2a;
2354     } else {
2355       InitializerScopeRAII InitScope(*this, D, ThisDecl);
2356 
2357       if (Tok.is(tok::code_completion)) {
2358         Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2359         Actions.FinalizeDeclaration(ThisDecl);
2360         cutOffParsing();
2361         return nullptr;
2362       }
2363 
2364       PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2365       ExprResult Init = ParseInitializer();
2366 
2367       // If this is the only decl in (possibly) range based for statement,
2368       // our best guess is that the user meant ':' instead of '='.
2369       if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
2370         Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2371             << FixItHint::CreateReplacement(EqualLoc, ":");
2372         // We are trying to stop parser from looking for ';' in this for
2373         // statement, therefore preventing spurious errors to be issued.
2374         FRI->ColonLoc = EqualLoc;
2375         Init = ExprError();
2376         FRI->RangeExpr = Init;
2377       }
2378 
2379       InitScope.pop();
2380 
2381       if (Init.isInvalid()) {
2382         SmallVector<tok::TokenKind, 2> StopTokens;
2383         StopTokens.push_back(tok::comma);
2384         if (D.getContext() == DeclaratorContext::ForContext ||
2385             D.getContext() == DeclaratorContext::InitStmtContext)
2386           StopTokens.push_back(tok::r_paren);
2387         SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2388         Actions.ActOnInitializerError(ThisDecl);
2389       } else
2390         Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2391                                      /*DirectInit=*/false);
2392     }
2393   } else if (Tok.is(tok::l_paren)) {
2394     // Parse C++ direct initializer: '(' expression-list ')'
2395     BalancedDelimiterTracker T(*this, tok::l_paren);
2396     T.consumeOpen();
2397 
2398     ExprVector Exprs;
2399     CommaLocsTy CommaLocs;
2400 
2401     InitializerScopeRAII InitScope(*this, D, ThisDecl);
2402 
2403     auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2404     auto RunSignatureHelp = [&]() {
2405       QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2406           getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2407           ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2408       CalledSignatureHelp = true;
2409       return PreferredType;
2410     };
2411     auto SetPreferredType = [&] {
2412       PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2413     };
2414 
2415     llvm::function_ref<void()> ExpressionStarts;
2416     if (ThisVarDecl) {
2417       // ParseExpressionList can sometimes succeed even when ThisDecl is not
2418       // VarDecl. This is an error and it is reported in a call to
2419       // Actions.ActOnInitializerError(). However, we call
2420       // ProduceConstructorSignatureHelp only on VarDecls.
2421       ExpressionStarts = SetPreferredType;
2422     }
2423     if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2424       if (ThisVarDecl && PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2425         Actions.ProduceConstructorSignatureHelp(
2426             getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2427             ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2428         CalledSignatureHelp = true;
2429       }
2430       Actions.ActOnInitializerError(ThisDecl);
2431       SkipUntil(tok::r_paren, StopAtSemi);
2432     } else {
2433       // Match the ')'.
2434       T.consumeClose();
2435 
2436       assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2437              "Unexpected number of commas!");
2438 
2439       InitScope.pop();
2440 
2441       ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2442                                                           T.getCloseLocation(),
2443                                                           Exprs);
2444       Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2445                                    /*DirectInit=*/true);
2446     }
2447   } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
2448              (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
2449     // Parse C++0x braced-init-list.
2450     Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2451 
2452     InitializerScopeRAII InitScope(*this, D, ThisDecl);
2453 
2454     ExprResult Init(ParseBraceInitializer());
2455 
2456     InitScope.pop();
2457 
2458     if (Init.isInvalid()) {
2459       Actions.ActOnInitializerError(ThisDecl);
2460     } else
2461       Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2462 
2463   } else {
2464     Actions.ActOnUninitializedDecl(ThisDecl);
2465   }
2466 
2467   Actions.FinalizeDeclaration(ThisDecl);
2468 
2469   return ThisDecl;
2470 }
2471 
2472 /// ParseSpecifierQualifierList
2473 ///        specifier-qualifier-list:
2474 ///          type-specifier specifier-qualifier-list[opt]
2475 ///          type-qualifier specifier-qualifier-list[opt]
2476 /// [GNU]    attributes     specifier-qualifier-list[opt]
2477 ///
2478 void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2479                                          DeclSpecContext DSC) {
2480   /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
2481   /// parse declaration-specifiers and complain about extra stuff.
2482   /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2483   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2484 
2485   // Validate declspec for type-name.
2486   unsigned Specs = DS.getParsedSpecifiers();
2487   if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
2488     Diag(Tok, diag::err_expected_type);
2489     DS.SetTypeSpecError();
2490   } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
2491     Diag(Tok, diag::err_typename_requires_specqual);
2492     if (!DS.hasTypeSpecifier())
2493       DS.SetTypeSpecError();
2494   }
2495 
2496   // Issue diagnostic and remove storage class if present.
2497   if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2498     if (DS.getStorageClassSpecLoc().isValid())
2499       Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2500     else
2501       Diag(DS.getThreadStorageClassSpecLoc(),
2502            diag::err_typename_invalid_storageclass);
2503     DS.ClearStorageClassSpecs();
2504   }
2505 
2506   // Issue diagnostic and remove function specifier if present.
2507   if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2508     if (DS.isInlineSpecified())
2509       Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2510     if (DS.isVirtualSpecified())
2511       Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2512     if (DS.hasExplicitSpecifier())
2513       Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2514     DS.ClearFunctionSpecs();
2515   }
2516 
2517   // Issue diagnostic and remove constexpr specifier if present.
2518   if (DS.hasConstexprSpecifier() && DSC != DeclSpecContext::DSC_condition) {
2519     Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2520         << DS.getConstexprSpecifier();
2521     DS.ClearConstexprSpec();
2522   }
2523 }
2524 
2525 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2526 /// specified token is valid after the identifier in a declarator which
2527 /// immediately follows the declspec.  For example, these things are valid:
2528 ///
2529 ///      int x   [             4];         // direct-declarator
2530 ///      int x   (             int y);     // direct-declarator
2531 ///  int(int x   )                         // direct-declarator
2532 ///      int x   ;                         // simple-declaration
2533 ///      int x   =             17;         // init-declarator-list
2534 ///      int x   ,             y;          // init-declarator-list
2535 ///      int x   __asm__       ("foo");    // init-declarator-list
2536 ///      int x   :             4;          // struct-declarator
2537 ///      int x   {             5};         // C++'0x unified initializers
2538 ///
2539 /// This is not, because 'x' does not immediately follow the declspec (though
2540 /// ')' happens to be valid anyway).
2541 ///    int (x)
2542 ///
2543 static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2544   return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2545                    tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2546                    tok::colon);
2547 }
2548 
2549 /// ParseImplicitInt - This method is called when we have an non-typename
2550 /// identifier in a declspec (which normally terminates the decl spec) when
2551 /// the declspec has no type specifier.  In this case, the declspec is either
2552 /// malformed or is "implicit int" (in K&R and C89).
2553 ///
2554 /// This method handles diagnosing this prettily and returns false if the
2555 /// declspec is done being processed.  If it recovers and thinks there may be
2556 /// other pieces of declspec after it, it returns true.
2557 ///
2558 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2559                               const ParsedTemplateInfo &TemplateInfo,
2560                               AccessSpecifier AS, DeclSpecContext DSC,
2561                               ParsedAttributesWithRange &Attrs) {
2562   assert(Tok.is(tok::identifier) && "should have identifier");
2563 
2564   SourceLocation Loc = Tok.getLocation();
2565   // If we see an identifier that is not a type name, we normally would
2566   // parse it as the identifier being declared.  However, when a typename
2567   // is typo'd or the definition is not included, this will incorrectly
2568   // parse the typename as the identifier name and fall over misparsing
2569   // later parts of the diagnostic.
2570   //
2571   // As such, we try to do some look-ahead in cases where this would
2572   // otherwise be an "implicit-int" case to see if this is invalid.  For
2573   // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2574   // an identifier with implicit int, we'd get a parse error because the
2575   // next token is obviously invalid for a type.  Parse these as a case
2576   // with an invalid type specifier.
2577   assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2578 
2579   // Since we know that this either implicit int (which is rare) or an
2580   // error, do lookahead to try to do better recovery. This never applies
2581   // within a type specifier. Outside of C++, we allow this even if the
2582   // language doesn't "officially" support implicit int -- we support
2583   // implicit int as an extension in C99 and C11.
2584   if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
2585       isValidAfterIdentifierInDeclarator(NextToken())) {
2586     // If this token is valid for implicit int, e.g. "static x = 4", then
2587     // we just avoid eating the identifier, so it will be parsed as the
2588     // identifier in the declarator.
2589     return false;
2590   }
2591 
2592   // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2593   // for incomplete declarations such as `pipe p`.
2594   if (getLangOpts().OpenCLCPlusPlus && DS.isTypeSpecPipe())
2595     return false;
2596 
2597   if (getLangOpts().CPlusPlus &&
2598       DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
2599     // Don't require a type specifier if we have the 'auto' storage class
2600     // specifier in C++98 -- we'll promote it to a type specifier.
2601     if (SS)
2602       AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2603     return false;
2604   }
2605 
2606   if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
2607       getLangOpts().MSVCCompat) {
2608     // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2609     // Give Sema a chance to recover if we are in a template with dependent base
2610     // classes.
2611     if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2612             *Tok.getIdentifierInfo(), Tok.getLocation(),
2613             DSC == DeclSpecContext::DSC_template_type_arg)) {
2614       const char *PrevSpec;
2615       unsigned DiagID;
2616       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2617                          Actions.getASTContext().getPrintingPolicy());
2618       DS.SetRangeEnd(Tok.getLocation());
2619       ConsumeToken();
2620       return false;
2621     }
2622   }
2623 
2624   // Otherwise, if we don't consume this token, we are going to emit an
2625   // error anyway.  Try to recover from various common problems.  Check
2626   // to see if this was a reference to a tag name without a tag specified.
2627   // This is a common problem in C (saying 'foo' instead of 'struct foo').
2628   //
2629   // C++ doesn't need this, and isTagName doesn't take SS.
2630   if (SS == nullptr) {
2631     const char *TagName = nullptr, *FixitTagName = nullptr;
2632     tok::TokenKind TagKind = tok::unknown;
2633 
2634     switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2635       default: break;
2636       case DeclSpec::TST_enum:
2637         TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2638       case DeclSpec::TST_union:
2639         TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2640       case DeclSpec::TST_struct:
2641         TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2642       case DeclSpec::TST_interface:
2643         TagName="__interface"; FixitTagName = "__interface ";
2644         TagKind=tok::kw___interface;break;
2645       case DeclSpec::TST_class:
2646         TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2647     }
2648 
2649     if (TagName) {
2650       IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2651       LookupResult R(Actions, TokenName, SourceLocation(),
2652                      Sema::LookupOrdinaryName);
2653 
2654       Diag(Loc, diag::err_use_of_tag_name_without_tag)
2655         << TokenName << TagName << getLangOpts().CPlusPlus
2656         << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2657 
2658       if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2659         for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2660              I != IEnd; ++I)
2661           Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2662             << TokenName << TagName;
2663       }
2664 
2665       // Parse this as a tag as if the missing tag were present.
2666       if (TagKind == tok::kw_enum)
2667         ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2668                            DeclSpecContext::DSC_normal);
2669       else
2670         ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2671                             /*EnteringContext*/ false,
2672                             DeclSpecContext::DSC_normal, Attrs);
2673       return true;
2674     }
2675   }
2676 
2677   // Determine whether this identifier could plausibly be the name of something
2678   // being declared (with a missing type).
2679   if (!isTypeSpecifier(DSC) && (!SS || DSC == DeclSpecContext::DSC_top_level ||
2680                                 DSC == DeclSpecContext::DSC_class)) {
2681     // Look ahead to the next token to try to figure out what this declaration
2682     // was supposed to be.
2683     switch (NextToken().getKind()) {
2684     case tok::l_paren: {
2685       // static x(4); // 'x' is not a type
2686       // x(int n);    // 'x' is not a type
2687       // x (*p)[];    // 'x' is a type
2688       //
2689       // Since we're in an error case, we can afford to perform a tentative
2690       // parse to determine which case we're in.
2691       TentativeParsingAction PA(*this);
2692       ConsumeToken();
2693       TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2694       PA.Revert();
2695 
2696       if (TPR != TPResult::False) {
2697         // The identifier is followed by a parenthesized declarator.
2698         // It's supposed to be a type.
2699         break;
2700       }
2701 
2702       // If we're in a context where we could be declaring a constructor,
2703       // check whether this is a constructor declaration with a bogus name.
2704       if (DSC == DeclSpecContext::DSC_class ||
2705           (DSC == DeclSpecContext::DSC_top_level && SS)) {
2706         IdentifierInfo *II = Tok.getIdentifierInfo();
2707         if (Actions.isCurrentClassNameTypo(II, SS)) {
2708           Diag(Loc, diag::err_constructor_bad_name)
2709             << Tok.getIdentifierInfo() << II
2710             << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2711           Tok.setIdentifierInfo(II);
2712         }
2713       }
2714       // Fall through.
2715       LLVM_FALLTHROUGH;
2716     }
2717     case tok::comma:
2718     case tok::equal:
2719     case tok::kw_asm:
2720     case tok::l_brace:
2721     case tok::l_square:
2722     case tok::semi:
2723       // This looks like a variable or function declaration. The type is
2724       // probably missing. We're done parsing decl-specifiers.
2725       // But only if we are not in a function prototype scope.
2726       if (getCurScope()->isFunctionPrototypeScope())
2727         break;
2728       if (SS)
2729         AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2730       return false;
2731 
2732     default:
2733       // This is probably supposed to be a type. This includes cases like:
2734       //   int f(itn);
2735       //   struct S { unsinged : 4; };
2736       break;
2737     }
2738   }
2739 
2740   // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2741   // and attempt to recover.
2742   ParsedType T;
2743   IdentifierInfo *II = Tok.getIdentifierInfo();
2744   bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
2745   Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2746                                   IsTemplateName);
2747   if (T) {
2748     // The action has suggested that the type T could be used. Set that as
2749     // the type in the declaration specifiers, consume the would-be type
2750     // name token, and we're done.
2751     const char *PrevSpec;
2752     unsigned DiagID;
2753     DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2754                        Actions.getASTContext().getPrintingPolicy());
2755     DS.SetRangeEnd(Tok.getLocation());
2756     ConsumeToken();
2757     // There may be other declaration specifiers after this.
2758     return true;
2759   } else if (II != Tok.getIdentifierInfo()) {
2760     // If no type was suggested, the correction is to a keyword
2761     Tok.setKind(II->getTokenID());
2762     // There may be other declaration specifiers after this.
2763     return true;
2764   }
2765 
2766   // Otherwise, the action had no suggestion for us.  Mark this as an error.
2767   DS.SetTypeSpecError();
2768   DS.SetRangeEnd(Tok.getLocation());
2769   ConsumeToken();
2770 
2771   // Eat any following template arguments.
2772   if (IsTemplateName) {
2773     SourceLocation LAngle, RAngle;
2774     TemplateArgList Args;
2775     ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2776   }
2777 
2778   // TODO: Could inject an invalid typedef decl in an enclosing scope to
2779   // avoid rippling error messages on subsequent uses of the same type,
2780   // could be useful if #include was forgotten.
2781   return true;
2782 }
2783 
2784 /// Determine the declaration specifier context from the declarator
2785 /// context.
2786 ///
2787 /// \param Context the declarator context, which is one of the
2788 /// DeclaratorContext enumerator values.
2789 Parser::DeclSpecContext
2790 Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2791   if (Context == DeclaratorContext::MemberContext)
2792     return DeclSpecContext::DSC_class;
2793   if (Context == DeclaratorContext::FileContext)
2794     return DeclSpecContext::DSC_top_level;
2795   if (Context == DeclaratorContext::TemplateParamContext)
2796     return DeclSpecContext::DSC_template_param;
2797   if (Context == DeclaratorContext::TemplateArgContext ||
2798       Context == DeclaratorContext::TemplateTypeArgContext)
2799     return DeclSpecContext::DSC_template_type_arg;
2800   if (Context == DeclaratorContext::TrailingReturnContext ||
2801       Context == DeclaratorContext::TrailingReturnVarContext)
2802     return DeclSpecContext::DSC_trailing;
2803   if (Context == DeclaratorContext::AliasDeclContext ||
2804       Context == DeclaratorContext::AliasTemplateContext)
2805     return DeclSpecContext::DSC_alias_declaration;
2806   return DeclSpecContext::DSC_normal;
2807 }
2808 
2809 /// ParseAlignArgument - Parse the argument to an alignment-specifier.
2810 ///
2811 /// FIXME: Simply returns an alignof() expression if the argument is a
2812 /// type. Ideally, the type should be propagated directly into Sema.
2813 ///
2814 /// [C11]   type-id
2815 /// [C11]   constant-expression
2816 /// [C++0x] type-id ...[opt]
2817 /// [C++0x] assignment-expression ...[opt]
2818 ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2819                                       SourceLocation &EllipsisLoc) {
2820   ExprResult ER;
2821   if (isTypeIdInParens()) {
2822     SourceLocation TypeLoc = Tok.getLocation();
2823     ParsedType Ty = ParseTypeName().get();
2824     SourceRange TypeRange(Start, Tok.getLocation());
2825     ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2826                                                Ty.getAsOpaquePtr(), TypeRange);
2827   } else
2828     ER = ParseConstantExpression();
2829 
2830   if (getLangOpts().CPlusPlus11)
2831     TryConsumeToken(tok::ellipsis, EllipsisLoc);
2832 
2833   return ER;
2834 }
2835 
2836 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2837 /// attribute to Attrs.
2838 ///
2839 /// alignment-specifier:
2840 /// [C11]   '_Alignas' '(' type-id ')'
2841 /// [C11]   '_Alignas' '(' constant-expression ')'
2842 /// [C++11] 'alignas' '(' type-id ...[opt] ')'
2843 /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2844 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2845                                      SourceLocation *EndLoc) {
2846   assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2847          "Not an alignment-specifier!");
2848 
2849   IdentifierInfo *KWName = Tok.getIdentifierInfo();
2850   SourceLocation KWLoc = ConsumeToken();
2851 
2852   BalancedDelimiterTracker T(*this, tok::l_paren);
2853   if (T.expectAndConsume())
2854     return;
2855 
2856   SourceLocation EllipsisLoc;
2857   ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2858   if (ArgExpr.isInvalid()) {
2859     T.skipToEnd();
2860     return;
2861   }
2862 
2863   T.consumeClose();
2864   if (EndLoc)
2865     *EndLoc = T.getCloseLocation();
2866 
2867   ArgsVector ArgExprs;
2868   ArgExprs.push_back(ArgExpr.get());
2869   Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2870                ParsedAttr::AS_Keyword, EllipsisLoc);
2871 }
2872 
2873 /// Determine whether we're looking at something that might be a declarator
2874 /// in a simple-declaration. If it can't possibly be a declarator, maybe
2875 /// diagnose a missing semicolon after a prior tag definition in the decl
2876 /// specifier.
2877 ///
2878 /// \return \c true if an error occurred and this can't be any kind of
2879 /// declaration.
2880 bool
2881 Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2882                                               DeclSpecContext DSContext,
2883                                               LateParsedAttrList *LateAttrs) {
2884   assert(DS.hasTagDefinition() && "shouldn't call this");
2885 
2886   bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2887                           DSContext == DeclSpecContext::DSC_top_level);
2888 
2889   if (getLangOpts().CPlusPlus &&
2890       Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2891                   tok::annot_template_id) &&
2892       TryAnnotateCXXScopeToken(EnteringContext)) {
2893     SkipMalformedDecl();
2894     return true;
2895   }
2896 
2897   bool HasScope = Tok.is(tok::annot_cxxscope);
2898   // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2899   Token AfterScope = HasScope ? NextToken() : Tok;
2900 
2901   // Determine whether the following tokens could possibly be a
2902   // declarator.
2903   bool MightBeDeclarator = true;
2904   if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2905     // A declarator-id can't start with 'typename'.
2906     MightBeDeclarator = false;
2907   } else if (AfterScope.is(tok::annot_template_id)) {
2908     // If we have a type expressed as a template-id, this cannot be a
2909     // declarator-id (such a type cannot be redeclared in a simple-declaration).
2910     TemplateIdAnnotation *Annot =
2911         static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2912     if (Annot->Kind == TNK_Type_template)
2913       MightBeDeclarator = false;
2914   } else if (AfterScope.is(tok::identifier)) {
2915     const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
2916 
2917     // These tokens cannot come after the declarator-id in a
2918     // simple-declaration, and are likely to come after a type-specifier.
2919     if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2920                      tok::annot_cxxscope, tok::coloncolon)) {
2921       // Missing a semicolon.
2922       MightBeDeclarator = false;
2923     } else if (HasScope) {
2924       // If the declarator-id has a scope specifier, it must redeclare a
2925       // previously-declared entity. If that's a type (and this is not a
2926       // typedef), that's an error.
2927       CXXScopeSpec SS;
2928       Actions.RestoreNestedNameSpecifierAnnotation(
2929           Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2930       IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2931       Sema::NameClassification Classification = Actions.ClassifyName(
2932           getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2933           /*CCC=*/nullptr);
2934       switch (Classification.getKind()) {
2935       case Sema::NC_Error:
2936         SkipMalformedDecl();
2937         return true;
2938 
2939       case Sema::NC_Keyword:
2940         llvm_unreachable("typo correction is not possible here");
2941 
2942       case Sema::NC_Type:
2943       case Sema::NC_TypeTemplate:
2944       case Sema::NC_UndeclaredNonType:
2945       case Sema::NC_UndeclaredTemplate:
2946         // Not a previously-declared non-type entity.
2947         MightBeDeclarator = false;
2948         break;
2949 
2950       case Sema::NC_Unknown:
2951       case Sema::NC_NonType:
2952       case Sema::NC_DependentNonType:
2953       case Sema::NC_ContextIndependentExpr:
2954       case Sema::NC_VarTemplate:
2955       case Sema::NC_FunctionTemplate:
2956         // Might be a redeclaration of a prior entity.
2957         break;
2958       }
2959     }
2960   }
2961 
2962   if (MightBeDeclarator)
2963     return false;
2964 
2965   const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2966   Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2967        diag::err_expected_after)
2968       << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2969 
2970   // Try to recover from the typo, by dropping the tag definition and parsing
2971   // the problematic tokens as a type.
2972   //
2973   // FIXME: Split the DeclSpec into pieces for the standalone
2974   // declaration and pieces for the following declaration, instead
2975   // of assuming that all the other pieces attach to new declaration,
2976   // and call ParsedFreeStandingDeclSpec as appropriate.
2977   DS.ClearTypeSpecType();
2978   ParsedTemplateInfo NotATemplate;
2979   ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
2980   return false;
2981 }
2982 
2983 // Choose the apprpriate diagnostic error for why fixed point types are
2984 // disabled, set the previous specifier, and mark as invalid.
2985 static void SetupFixedPointError(const LangOptions &LangOpts,
2986                                  const char *&PrevSpec, unsigned &DiagID,
2987                                  bool &isInvalid) {
2988   assert(!LangOpts.FixedPoint);
2989   DiagID = diag::err_fixed_point_not_enabled;
2990   PrevSpec = "";  // Not used by diagnostic
2991   isInvalid = true;
2992 }
2993 
2994 /// ParseDeclarationSpecifiers
2995 ///       declaration-specifiers: [C99 6.7]
2996 ///         storage-class-specifier declaration-specifiers[opt]
2997 ///         type-specifier declaration-specifiers[opt]
2998 /// [C99]   function-specifier declaration-specifiers[opt]
2999 /// [C11]   alignment-specifier declaration-specifiers[opt]
3000 /// [GNU]   attributes declaration-specifiers[opt]
3001 /// [Clang] '__module_private__' declaration-specifiers[opt]
3002 /// [ObjC1] '__kindof' declaration-specifiers[opt]
3003 ///
3004 ///       storage-class-specifier: [C99 6.7.1]
3005 ///         'typedef'
3006 ///         'extern'
3007 ///         'static'
3008 ///         'auto'
3009 ///         'register'
3010 /// [C++]   'mutable'
3011 /// [C++11] 'thread_local'
3012 /// [C11]   '_Thread_local'
3013 /// [GNU]   '__thread'
3014 ///       function-specifier: [C99 6.7.4]
3015 /// [C99]   'inline'
3016 /// [C++]   'virtual'
3017 /// [C++]   'explicit'
3018 /// [OpenCL] '__kernel'
3019 ///       'friend': [C++ dcl.friend]
3020 ///       'constexpr': [C++0x dcl.constexpr]
3021 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3022                                         const ParsedTemplateInfo &TemplateInfo,
3023                                         AccessSpecifier AS,
3024                                         DeclSpecContext DSContext,
3025                                         LateParsedAttrList *LateAttrs) {
3026   if (DS.getSourceRange().isInvalid()) {
3027     // Start the range at the current token but make the end of the range
3028     // invalid.  This will make the entire range invalid unless we successfully
3029     // consume a token.
3030     DS.SetRangeStart(Tok.getLocation());
3031     DS.SetRangeEnd(SourceLocation());
3032   }
3033 
3034   bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3035                           DSContext == DeclSpecContext::DSC_top_level);
3036   bool AttrsLastTime = false;
3037   ParsedAttributesWithRange attrs(AttrFactory);
3038   // We use Sema's policy to get bool macros right.
3039   PrintingPolicy Policy = Actions.getPrintingPolicy();
3040   while (1) {
3041     bool isInvalid = false;
3042     bool isStorageClass = false;
3043     const char *PrevSpec = nullptr;
3044     unsigned DiagID = 0;
3045 
3046     // This value needs to be set to the location of the last token if the last
3047     // token of the specifier is already consumed.
3048     SourceLocation ConsumedEnd;
3049 
3050     // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3051     // implementation for VS2013 uses _Atomic as an identifier for one of the
3052     // classes in <atomic>.
3053     //
3054     // A typedef declaration containing _Atomic<...> is among the places where
3055     // the class is used.  If we are currently parsing such a declaration, treat
3056     // the token as an identifier.
3057     if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
3058         DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
3059         !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
3060       Tok.setKind(tok::identifier);
3061 
3062     SourceLocation Loc = Tok.getLocation();
3063 
3064     switch (Tok.getKind()) {
3065     default:
3066     DoneWithDeclSpec:
3067       if (!AttrsLastTime)
3068         ProhibitAttributes(attrs);
3069       else {
3070         // Reject C++11 attributes that appertain to decl specifiers as
3071         // we don't support any C++11 attributes that appertain to decl
3072         // specifiers. This also conforms to what g++ 4.8 is doing.
3073         ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3074 
3075         DS.takeAttributesFrom(attrs);
3076       }
3077 
3078       // If this is not a declaration specifier token, we're done reading decl
3079       // specifiers.  First verify that DeclSpec's are consistent.
3080       DS.Finish(Actions, Policy);
3081       return;
3082 
3083     case tok::l_square:
3084     case tok::kw_alignas:
3085       if (!standardAttributesAllowed() || !isCXX11AttributeSpecifier())
3086         goto DoneWithDeclSpec;
3087 
3088       ProhibitAttributes(attrs);
3089       // FIXME: It would be good to recover by accepting the attributes,
3090       //        but attempting to do that now would cause serious
3091       //        madness in terms of diagnostics.
3092       attrs.clear();
3093       attrs.Range = SourceRange();
3094 
3095       ParseCXX11Attributes(attrs);
3096       AttrsLastTime = true;
3097       continue;
3098 
3099     case tok::code_completion: {
3100       Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3101       if (DS.hasTypeSpecifier()) {
3102         bool AllowNonIdentifiers
3103           = (getCurScope()->getFlags() & (Scope::ControlScope |
3104                                           Scope::BlockScope |
3105                                           Scope::TemplateParamScope |
3106                                           Scope::FunctionPrototypeScope |
3107                                           Scope::AtCatchScope)) == 0;
3108         bool AllowNestedNameSpecifiers
3109           = DSContext == DeclSpecContext::DSC_top_level ||
3110             (DSContext == DeclSpecContext::DSC_class && DS.isFriendSpecified());
3111 
3112         Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3113                                      AllowNonIdentifiers,
3114                                      AllowNestedNameSpecifiers);
3115         return cutOffParsing();
3116       }
3117 
3118       if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
3119         CCC = Sema::PCC_LocalDeclarationSpecifiers;
3120       else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3121         CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3122                                                       : Sema::PCC_Template;
3123       else if (DSContext == DeclSpecContext::DSC_class)
3124         CCC = Sema::PCC_Class;
3125       else if (CurParsedObjCImpl)
3126         CCC = Sema::PCC_ObjCImplementation;
3127 
3128       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3129       return cutOffParsing();
3130     }
3131 
3132     case tok::coloncolon: // ::foo::bar
3133       // C++ scope specifier.  Annotate and loop, or bail out on error.
3134       if (TryAnnotateCXXScopeToken(EnteringContext)) {
3135         if (!DS.hasTypeSpecifier())
3136           DS.SetTypeSpecError();
3137         goto DoneWithDeclSpec;
3138       }
3139       if (Tok.is(tok::coloncolon)) // ::new or ::delete
3140         goto DoneWithDeclSpec;
3141       continue;
3142 
3143     case tok::annot_cxxscope: {
3144       if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
3145         goto DoneWithDeclSpec;
3146 
3147       CXXScopeSpec SS;
3148       Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3149                                                    Tok.getAnnotationRange(),
3150                                                    SS);
3151 
3152       // We are looking for a qualified typename.
3153       Token Next = NextToken();
3154       if (Next.is(tok::annot_template_id) &&
3155           static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
3156             ->Kind == TNK_Type_template) {
3157         // We have a qualified template-id, e.g., N::A<int>
3158 
3159         // If this would be a valid constructor declaration with template
3160         // arguments, we will reject the attempt to form an invalid type-id
3161         // referring to the injected-class-name when we annotate the token,
3162         // per C++ [class.qual]p2.
3163         //
3164         // To improve diagnostics for this case, parse the declaration as a
3165         // constructor (and reject the extra template arguments later).
3166         TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
3167         if ((DSContext == DeclSpecContext::DSC_top_level ||
3168              DSContext == DeclSpecContext::DSC_class) &&
3169             TemplateId->Name &&
3170             Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
3171             isConstructorDeclarator(/*Unqualified*/ false)) {
3172           // The user meant this to be an out-of-line constructor
3173           // definition, but template arguments are not allowed
3174           // there.  Just allow this as a constructor; we'll
3175           // complain about it later.
3176           goto DoneWithDeclSpec;
3177         }
3178 
3179         DS.getTypeSpecScope() = SS;
3180         ConsumeAnnotationToken(); // The C++ scope.
3181         assert(Tok.is(tok::annot_template_id) &&
3182                "ParseOptionalCXXScopeSpecifier not working");
3183         AnnotateTemplateIdTokenAsType();
3184         continue;
3185       }
3186 
3187       if (Next.is(tok::annot_typename)) {
3188         DS.getTypeSpecScope() = SS;
3189         ConsumeAnnotationToken(); // The C++ scope.
3190         if (Tok.getAnnotationValue()) {
3191           ParsedType T = getTypeAnnotation(Tok);
3192           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3193                                          Tok.getAnnotationEndLoc(),
3194                                          PrevSpec, DiagID, T, Policy);
3195           if (isInvalid)
3196             break;
3197         }
3198         else
3199           DS.SetTypeSpecError();
3200         DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3201         ConsumeAnnotationToken(); // The typename
3202       }
3203 
3204       if (Next.isNot(tok::identifier))
3205         goto DoneWithDeclSpec;
3206 
3207       // Check whether this is a constructor declaration. If we're in a
3208       // context where the identifier could be a class name, and it has the
3209       // shape of a constructor declaration, process it as one.
3210       if ((DSContext == DeclSpecContext::DSC_top_level ||
3211            DSContext == DeclSpecContext::DSC_class) &&
3212           Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3213                                      &SS) &&
3214           isConstructorDeclarator(/*Unqualified*/ false))
3215         goto DoneWithDeclSpec;
3216 
3217       ParsedType TypeRep =
3218           Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3219                               getCurScope(), &SS, false, false, nullptr,
3220                               /*IsCtorOrDtorName=*/false,
3221                               /*WantNontrivialTypeSourceInfo=*/true,
3222                               isClassTemplateDeductionContext(DSContext));
3223 
3224       // If the referenced identifier is not a type, then this declspec is
3225       // erroneous: We already checked about that it has no type specifier, and
3226       // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3227       // typename.
3228       if (!TypeRep) {
3229         // Eat the scope spec so the identifier is current.
3230         ConsumeAnnotationToken();
3231         ParsedAttributesWithRange Attrs(AttrFactory);
3232         if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3233           if (!Attrs.empty()) {
3234             AttrsLastTime = true;
3235             attrs.takeAllFrom(Attrs);
3236           }
3237           continue;
3238         }
3239         goto DoneWithDeclSpec;
3240       }
3241 
3242       DS.getTypeSpecScope() = SS;
3243       ConsumeAnnotationToken(); // The C++ scope.
3244 
3245       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3246                                      DiagID, TypeRep, Policy);
3247       if (isInvalid)
3248         break;
3249 
3250       DS.SetRangeEnd(Tok.getLocation());
3251       ConsumeToken(); // The typename.
3252 
3253       continue;
3254     }
3255 
3256     case tok::annot_typename: {
3257       // If we've previously seen a tag definition, we were almost surely
3258       // missing a semicolon after it.
3259       if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
3260         goto DoneWithDeclSpec;
3261 
3262       if (Tok.getAnnotationValue()) {
3263         ParsedType T = getTypeAnnotation(Tok);
3264         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3265                                        DiagID, T, Policy);
3266       } else
3267         DS.SetTypeSpecError();
3268 
3269       if (isInvalid)
3270         break;
3271 
3272       DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3273       ConsumeAnnotationToken(); // The typename
3274 
3275       continue;
3276     }
3277 
3278     case tok::kw___is_signed:
3279       // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3280       // typically treats it as a trait. If we see __is_signed as it appears
3281       // in libstdc++, e.g.,
3282       //
3283       //   static const bool __is_signed;
3284       //
3285       // then treat __is_signed as an identifier rather than as a keyword.
3286       if (DS.getTypeSpecType() == TST_bool &&
3287           DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3288           DS.getStorageClassSpec() == DeclSpec::SCS_static)
3289         TryKeywordIdentFallback(true);
3290 
3291       // We're done with the declaration-specifiers.
3292       goto DoneWithDeclSpec;
3293 
3294       // typedef-name
3295     case tok::kw___super:
3296     case tok::kw_decltype:
3297     case tok::identifier: {
3298       // This identifier can only be a typedef name if we haven't already seen
3299       // a type-specifier.  Without this check we misparse:
3300       //  typedef int X; struct Y { short X; };  as 'short int'.
3301       if (DS.hasTypeSpecifier())
3302         goto DoneWithDeclSpec;
3303 
3304       // If the token is an identifier named "__declspec" and Microsoft
3305       // extensions are not enabled, it is likely that there will be cascading
3306       // parse errors if this really is a __declspec attribute. Attempt to
3307       // recognize that scenario and recover gracefully.
3308       if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
3309           Tok.getIdentifierInfo()->getName().equals("__declspec")) {
3310         Diag(Loc, diag::err_ms_attributes_not_enabled);
3311 
3312         // The next token should be an open paren. If it is, eat the entire
3313         // attribute declaration and continue.
3314         if (NextToken().is(tok::l_paren)) {
3315           // Consume the __declspec identifier.
3316           ConsumeToken();
3317 
3318           // Eat the parens and everything between them.
3319           BalancedDelimiterTracker T(*this, tok::l_paren);
3320           if (T.consumeOpen()) {
3321             assert(false && "Not a left paren?");
3322             return;
3323           }
3324           T.skipToEnd();
3325           continue;
3326         }
3327       }
3328 
3329       // In C++, check to see if this is a scope specifier like foo::bar::, if
3330       // so handle it as such.  This is important for ctor parsing.
3331       if (getLangOpts().CPlusPlus) {
3332         if (TryAnnotateCXXScopeToken(EnteringContext)) {
3333           DS.SetTypeSpecError();
3334           goto DoneWithDeclSpec;
3335         }
3336         if (!Tok.is(tok::identifier))
3337           continue;
3338       }
3339 
3340       // Check for need to substitute AltiVec keyword tokens.
3341       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3342         break;
3343 
3344       // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3345       //                allow the use of a typedef name as a type specifier.
3346       if (DS.isTypeAltiVecVector())
3347         goto DoneWithDeclSpec;
3348 
3349       if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3350           isObjCInstancetype()) {
3351         ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3352         assert(TypeRep);
3353         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3354                                        DiagID, TypeRep, Policy);
3355         if (isInvalid)
3356           break;
3357 
3358         DS.SetRangeEnd(Loc);
3359         ConsumeToken();
3360         continue;
3361       }
3362 
3363       // If we're in a context where the identifier could be a class name,
3364       // check whether this is a constructor declaration.
3365       if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3366           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
3367           isConstructorDeclarator(/*Unqualified*/true))
3368         goto DoneWithDeclSpec;
3369 
3370       ParsedType TypeRep = Actions.getTypeName(
3371           *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3372           false, false, nullptr, false, false,
3373           isClassTemplateDeductionContext(DSContext));
3374 
3375       // If this is not a typedef name, don't parse it as part of the declspec,
3376       // it must be an implicit int or an error.
3377       if (!TypeRep) {
3378         ParsedAttributesWithRange Attrs(AttrFactory);
3379         if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3380           if (!Attrs.empty()) {
3381             AttrsLastTime = true;
3382             attrs.takeAllFrom(Attrs);
3383           }
3384           continue;
3385         }
3386         goto DoneWithDeclSpec;
3387       }
3388 
3389       // Likewise, if this is a context where the identifier could be a template
3390       // name, check whether this is a deduction guide declaration.
3391       if (getLangOpts().CPlusPlus17 &&
3392           (DSContext == DeclSpecContext::DSC_class ||
3393            DSContext == DeclSpecContext::DSC_top_level) &&
3394           Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3395                                        Tok.getLocation()) &&
3396           isConstructorDeclarator(/*Unqualified*/ true,
3397                                   /*DeductionGuide*/ true))
3398         goto DoneWithDeclSpec;
3399 
3400       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3401                                      DiagID, TypeRep, Policy);
3402       if (isInvalid)
3403         break;
3404 
3405       DS.SetRangeEnd(Tok.getLocation());
3406       ConsumeToken(); // The identifier
3407 
3408       // Objective-C supports type arguments and protocol references
3409       // following an Objective-C object or object pointer
3410       // type. Handle either one of them.
3411       if (Tok.is(tok::less) && getLangOpts().ObjC) {
3412         SourceLocation NewEndLoc;
3413         TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3414                                   Loc, TypeRep, /*consumeLastToken=*/true,
3415                                   NewEndLoc);
3416         if (NewTypeRep.isUsable()) {
3417           DS.UpdateTypeRep(NewTypeRep.get());
3418           DS.SetRangeEnd(NewEndLoc);
3419         }
3420       }
3421 
3422       // Need to support trailing type qualifiers (e.g. "id<p> const").
3423       // If a type specifier follows, it will be diagnosed elsewhere.
3424       continue;
3425     }
3426 
3427       // type-name
3428     case tok::annot_template_id: {
3429       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3430       if (TemplateId->Kind != TNK_Type_template &&
3431           TemplateId->Kind != TNK_Undeclared_template) {
3432         // This template-id does not refer to a type name, so we're
3433         // done with the type-specifiers.
3434         goto DoneWithDeclSpec;
3435       }
3436 
3437       // If we're in a context where the template-id could be a
3438       // constructor name or specialization, check whether this is a
3439       // constructor declaration.
3440       if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3441           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
3442           isConstructorDeclarator(TemplateId->SS.isEmpty()))
3443         goto DoneWithDeclSpec;
3444 
3445       // Turn the template-id annotation token into a type annotation
3446       // token, then try again to parse it as a type-specifier.
3447       AnnotateTemplateIdTokenAsType();
3448       continue;
3449     }
3450 
3451     // GNU attributes support.
3452     case tok::kw___attribute:
3453       ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
3454       continue;
3455 
3456     // Microsoft declspec support.
3457     case tok::kw___declspec:
3458       ParseMicrosoftDeclSpecs(DS.getAttributes());
3459       continue;
3460 
3461     // Microsoft single token adornments.
3462     case tok::kw___forceinline: {
3463       isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3464       IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3465       SourceLocation AttrNameLoc = Tok.getLocation();
3466       DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3467                                 nullptr, 0, ParsedAttr::AS_Keyword);
3468       break;
3469     }
3470 
3471     case tok::kw___unaligned:
3472       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3473                                  getLangOpts());
3474       break;
3475 
3476     case tok::kw___sptr:
3477     case tok::kw___uptr:
3478     case tok::kw___ptr64:
3479     case tok::kw___ptr32:
3480     case tok::kw___w64:
3481     case tok::kw___cdecl:
3482     case tok::kw___stdcall:
3483     case tok::kw___fastcall:
3484     case tok::kw___thiscall:
3485     case tok::kw___regcall:
3486     case tok::kw___vectorcall:
3487       ParseMicrosoftTypeAttributes(DS.getAttributes());
3488       continue;
3489 
3490     // Borland single token adornments.
3491     case tok::kw___pascal:
3492       ParseBorlandTypeAttributes(DS.getAttributes());
3493       continue;
3494 
3495     // OpenCL single token adornments.
3496     case tok::kw___kernel:
3497       ParseOpenCLKernelAttributes(DS.getAttributes());
3498       continue;
3499 
3500     // Nullability type specifiers.
3501     case tok::kw__Nonnull:
3502     case tok::kw__Nullable:
3503     case tok::kw__Null_unspecified:
3504       ParseNullabilityTypeSpecifiers(DS.getAttributes());
3505       continue;
3506 
3507     // Objective-C 'kindof' types.
3508     case tok::kw___kindof:
3509       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3510                                 nullptr, 0, ParsedAttr::AS_Keyword);
3511       (void)ConsumeToken();
3512       continue;
3513 
3514     // storage-class-specifier
3515     case tok::kw_typedef:
3516       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3517                                          PrevSpec, DiagID, Policy);
3518       isStorageClass = true;
3519       break;
3520     case tok::kw_extern:
3521       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3522         Diag(Tok, diag::ext_thread_before) << "extern";
3523       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3524                                          PrevSpec, DiagID, Policy);
3525       isStorageClass = true;
3526       break;
3527     case tok::kw___private_extern__:
3528       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3529                                          Loc, PrevSpec, DiagID, Policy);
3530       isStorageClass = true;
3531       break;
3532     case tok::kw_static:
3533       if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3534         Diag(Tok, diag::ext_thread_before) << "static";
3535       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3536                                          PrevSpec, DiagID, Policy);
3537       isStorageClass = true;
3538       break;
3539     case tok::kw_auto:
3540       if (getLangOpts().CPlusPlus11) {
3541         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3542           isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3543                                              PrevSpec, DiagID, Policy);
3544           if (!isInvalid)
3545             Diag(Tok, diag::ext_auto_storage_class)
3546               << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3547         } else
3548           isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3549                                          DiagID, Policy);
3550       } else
3551         isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3552                                            PrevSpec, DiagID, Policy);
3553       isStorageClass = true;
3554       break;
3555     case tok::kw___auto_type:
3556       Diag(Tok, diag::ext_auto_type);
3557       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3558                                      DiagID, Policy);
3559       break;
3560     case tok::kw_register:
3561       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3562                                          PrevSpec, DiagID, Policy);
3563       isStorageClass = true;
3564       break;
3565     case tok::kw_mutable:
3566       isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3567                                          PrevSpec, DiagID, Policy);
3568       isStorageClass = true;
3569       break;
3570     case tok::kw___thread:
3571       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3572                                                PrevSpec, DiagID);
3573       isStorageClass = true;
3574       break;
3575     case tok::kw_thread_local:
3576       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3577                                                PrevSpec, DiagID);
3578       isStorageClass = true;
3579       break;
3580     case tok::kw__Thread_local:
3581       if (!getLangOpts().C11)
3582         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3583       isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3584                                                Loc, PrevSpec, DiagID);
3585       isStorageClass = true;
3586       break;
3587 
3588     // function-specifier
3589     case tok::kw_inline:
3590       isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3591       break;
3592     case tok::kw_virtual:
3593       // C++ for OpenCL does not allow virtual function qualifier, to avoid
3594       // function pointers restricted in OpenCL v2.0 s6.9.a.
3595       if (getLangOpts().OpenCLCPlusPlus) {
3596         DiagID = diag::err_openclcxx_virtual_function;
3597         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3598         isInvalid = true;
3599       }
3600       else {
3601         isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3602       }
3603       break;
3604     case tok::kw_explicit: {
3605       SourceLocation ExplicitLoc = Loc;
3606       SourceLocation CloseParenLoc;
3607       ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3608       ConsumedEnd = ExplicitLoc;
3609       ConsumeToken(); // kw_explicit
3610       if (Tok.is(tok::l_paren)) {
3611         if (getLangOpts().CPlusPlus2a) {
3612           ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3613           BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3614           Tracker.consumeOpen();
3615           ExplicitExpr = ParseConstantExpression();
3616           ConsumedEnd = Tok.getLocation();
3617           if (ExplicitExpr.isUsable()) {
3618             CloseParenLoc = Tok.getLocation();
3619             Tracker.consumeClose();
3620             ExplicitSpec =
3621                 Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3622           } else
3623             Tracker.skipToEnd();
3624         } else
3625           Diag(Tok.getLocation(), diag::warn_cxx2a_compat_explicit_bool);
3626       }
3627       isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3628                                              ExplicitSpec, CloseParenLoc);
3629       break;
3630     }
3631     case tok::kw__Noreturn:
3632       if (!getLangOpts().C11)
3633         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3634       isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3635       break;
3636 
3637     // alignment-specifier
3638     case tok::kw__Alignas:
3639       if (!getLangOpts().C11)
3640         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3641       ParseAlignmentSpecifier(DS.getAttributes());
3642       continue;
3643 
3644     // friend
3645     case tok::kw_friend:
3646       if (DSContext == DeclSpecContext::DSC_class)
3647         isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3648       else {
3649         PrevSpec = ""; // not actually used by the diagnostic
3650         DiagID = diag::err_friend_invalid_in_context;
3651         isInvalid = true;
3652       }
3653       break;
3654 
3655     // Modules
3656     case tok::kw___module_private__:
3657       isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3658       break;
3659 
3660     // constexpr, consteval, constinit specifiers
3661     case tok::kw_constexpr:
3662       isInvalid = DS.SetConstexprSpec(CSK_constexpr, Loc, PrevSpec, DiagID);
3663       break;
3664     case tok::kw_consteval:
3665       isInvalid = DS.SetConstexprSpec(CSK_consteval, Loc, PrevSpec, DiagID);
3666       break;
3667     case tok::kw_constinit:
3668       isInvalid = DS.SetConstexprSpec(CSK_constinit, Loc, PrevSpec, DiagID);
3669       break;
3670 
3671     // type-specifier
3672     case tok::kw_short:
3673       isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
3674                                       DiagID, Policy);
3675       break;
3676     case tok::kw_long:
3677       if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
3678         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
3679                                         DiagID, Policy);
3680       else
3681         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3682                                         DiagID, Policy);
3683       break;
3684     case tok::kw___int64:
3685         isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
3686                                         DiagID, Policy);
3687       break;
3688     case tok::kw_signed:
3689       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
3690                                      DiagID);
3691       break;
3692     case tok::kw_unsigned:
3693       isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
3694                                      DiagID);
3695       break;
3696     case tok::kw__Complex:
3697       if (!getLangOpts().C99)
3698         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3699       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3700                                         DiagID);
3701       break;
3702     case tok::kw__Imaginary:
3703       if (!getLangOpts().C99)
3704         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3705       isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3706                                         DiagID);
3707       break;
3708     case tok::kw_void:
3709       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3710                                      DiagID, Policy);
3711       break;
3712     case tok::kw_char:
3713       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3714                                      DiagID, Policy);
3715       break;
3716     case tok::kw_int:
3717       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3718                                      DiagID, Policy);
3719       break;
3720     case tok::kw___int128:
3721       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3722                                      DiagID, Policy);
3723       break;
3724     case tok::kw_half:
3725       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3726                                      DiagID, Policy);
3727       break;
3728     case tok::kw_float:
3729       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3730                                      DiagID, Policy);
3731       break;
3732     case tok::kw_double:
3733       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3734                                      DiagID, Policy);
3735       break;
3736     case tok::kw__Float16:
3737       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3738                                      DiagID, Policy);
3739       break;
3740     case tok::kw__Accum:
3741       if (!getLangOpts().FixedPoint) {
3742         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3743       } else {
3744         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3745                                        DiagID, Policy);
3746       }
3747       break;
3748     case tok::kw__Fract:
3749       if (!getLangOpts().FixedPoint) {
3750         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3751       } else {
3752         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3753                                        DiagID, Policy);
3754       }
3755       break;
3756     case tok::kw__Sat:
3757       if (!getLangOpts().FixedPoint) {
3758         SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3759       } else {
3760         isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3761       }
3762       break;
3763     case tok::kw___float128:
3764       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3765                                      DiagID, Policy);
3766       break;
3767     case tok::kw_wchar_t:
3768       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3769                                      DiagID, Policy);
3770       break;
3771     case tok::kw_char8_t:
3772       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3773                                      DiagID, Policy);
3774       break;
3775     case tok::kw_char16_t:
3776       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3777                                      DiagID, Policy);
3778       break;
3779     case tok::kw_char32_t:
3780       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3781                                      DiagID, Policy);
3782       break;
3783     case tok::kw_bool:
3784     case tok::kw__Bool:
3785       if (Tok.is(tok::kw__Bool) && !getLangOpts().C99)
3786         Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3787 
3788       if (Tok.is(tok::kw_bool) &&
3789           DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
3790           DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
3791         PrevSpec = ""; // Not used by the diagnostic.
3792         DiagID = diag::err_bool_redeclaration;
3793         // For better error recovery.
3794         Tok.setKind(tok::identifier);
3795         isInvalid = true;
3796       } else {
3797         isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3798                                        DiagID, Policy);
3799       }
3800       break;
3801     case tok::kw__Decimal32:
3802       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3803                                      DiagID, Policy);
3804       break;
3805     case tok::kw__Decimal64:
3806       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3807                                      DiagID, Policy);
3808       break;
3809     case tok::kw__Decimal128:
3810       isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3811                                      DiagID, Policy);
3812       break;
3813     case tok::kw___vector:
3814       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3815       break;
3816     case tok::kw___pixel:
3817       isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3818       break;
3819     case tok::kw___bool:
3820       isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3821       break;
3822     case tok::kw_pipe:
3823       if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200 &&
3824                                     !getLangOpts().OpenCLCPlusPlus)) {
3825         // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
3826         // support the "pipe" word as identifier.
3827         Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3828         goto DoneWithDeclSpec;
3829       }
3830       isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
3831       break;
3832 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
3833   case tok::kw_##ImgType##_t: \
3834     isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
3835                                    DiagID, Policy); \
3836     break;
3837 #include "clang/Basic/OpenCLImageTypes.def"
3838     case tok::kw___unknown_anytype:
3839       isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
3840                                      PrevSpec, DiagID, Policy);
3841       break;
3842 
3843     // class-specifier:
3844     case tok::kw_class:
3845     case tok::kw_struct:
3846     case tok::kw___interface:
3847     case tok::kw_union: {
3848       tok::TokenKind Kind = Tok.getKind();
3849       ConsumeToken();
3850 
3851       // These are attributes following class specifiers.
3852       // To produce better diagnostic, we parse them when
3853       // parsing class specifier.
3854       ParsedAttributesWithRange Attributes(AttrFactory);
3855       ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
3856                           EnteringContext, DSContext, Attributes);
3857 
3858       // If there are attributes following class specifier,
3859       // take them over and handle them here.
3860       if (!Attributes.empty()) {
3861         AttrsLastTime = true;
3862         attrs.takeAllFrom(Attributes);
3863       }
3864       continue;
3865     }
3866 
3867     // enum-specifier:
3868     case tok::kw_enum:
3869       ConsumeToken();
3870       ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
3871       continue;
3872 
3873     // cv-qualifier:
3874     case tok::kw_const:
3875       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
3876                                  getLangOpts());
3877       break;
3878     case tok::kw_volatile:
3879       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3880                                  getLangOpts());
3881       break;
3882     case tok::kw_restrict:
3883       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3884                                  getLangOpts());
3885       break;
3886 
3887     // C++ typename-specifier:
3888     case tok::kw_typename:
3889       if (TryAnnotateTypeOrScopeToken()) {
3890         DS.SetTypeSpecError();
3891         goto DoneWithDeclSpec;
3892       }
3893       if (!Tok.is(tok::kw_typename))
3894         continue;
3895       break;
3896 
3897     // GNU typeof support.
3898     case tok::kw_typeof:
3899       ParseTypeofSpecifier(DS);
3900       continue;
3901 
3902     case tok::annot_decltype:
3903       ParseDecltypeSpecifier(DS);
3904       continue;
3905 
3906     case tok::annot_pragma_pack:
3907       HandlePragmaPack();
3908       continue;
3909 
3910     case tok::annot_pragma_ms_pragma:
3911       HandlePragmaMSPragma();
3912       continue;
3913 
3914     case tok::annot_pragma_ms_vtordisp:
3915       HandlePragmaMSVtorDisp();
3916       continue;
3917 
3918     case tok::annot_pragma_ms_pointers_to_members:
3919       HandlePragmaMSPointersToMembers();
3920       continue;
3921 
3922     case tok::kw___underlying_type:
3923       ParseUnderlyingTypeSpecifier(DS);
3924       continue;
3925 
3926     case tok::kw__Atomic:
3927       // C11 6.7.2.4/4:
3928       //   If the _Atomic keyword is immediately followed by a left parenthesis,
3929       //   it is interpreted as a type specifier (with a type name), not as a
3930       //   type qualifier.
3931       if (!getLangOpts().C11)
3932         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3933 
3934       if (NextToken().is(tok::l_paren)) {
3935         ParseAtomicSpecifier(DS);
3936         continue;
3937       }
3938       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
3939                                  getLangOpts());
3940       break;
3941 
3942     // OpenCL address space qualifiers:
3943     case tok::kw___generic:
3944       // generic address space is introduced only in OpenCL v2.0
3945       // see OpenCL C Spec v2.0 s6.5.5
3946       if (Actions.getLangOpts().OpenCLVersion < 200 &&
3947           !Actions.getLangOpts().OpenCLCPlusPlus) {
3948         DiagID = diag::err_opencl_unknown_type_specifier;
3949         PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3950         isInvalid = true;
3951         break;
3952       }
3953       LLVM_FALLTHROUGH;
3954     case tok::kw_private:
3955       // It's fine (but redundant) to check this for __generic on the
3956       // fallthrough path; we only form the __generic token in OpenCL mode.
3957       if (!getLangOpts().OpenCL)
3958         goto DoneWithDeclSpec;
3959       LLVM_FALLTHROUGH;
3960     case tok::kw___private:
3961     case tok::kw___global:
3962     case tok::kw___local:
3963     case tok::kw___constant:
3964     // OpenCL access qualifiers:
3965     case tok::kw___read_only:
3966     case tok::kw___write_only:
3967     case tok::kw___read_write:
3968       ParseOpenCLQualifiers(DS.getAttributes());
3969       break;
3970 
3971     case tok::less:
3972       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
3973       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
3974       // but we support it.
3975       if (DS.hasTypeSpecifier() || !getLangOpts().ObjC)
3976         goto DoneWithDeclSpec;
3977 
3978       SourceLocation StartLoc = Tok.getLocation();
3979       SourceLocation EndLoc;
3980       TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
3981       if (Type.isUsable()) {
3982         if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
3983                                PrevSpec, DiagID, Type.get(),
3984                                Actions.getASTContext().getPrintingPolicy()))
3985           Diag(StartLoc, DiagID) << PrevSpec;
3986 
3987         DS.SetRangeEnd(EndLoc);
3988       } else {
3989         DS.SetTypeSpecError();
3990       }
3991 
3992       // Need to support trailing type qualifiers (e.g. "id<p> const").
3993       // If a type specifier follows, it will be diagnosed elsewhere.
3994       continue;
3995     }
3996 
3997     DS.SetRangeEnd(ConsumedEnd.isValid() ? ConsumedEnd : Tok.getLocation());
3998 
3999     // If the specifier wasn't legal, issue a diagnostic.
4000     if (isInvalid) {
4001       assert(PrevSpec && "Method did not return previous specifier!");
4002       assert(DiagID);
4003 
4004       if (DiagID == diag::ext_duplicate_declspec ||
4005           DiagID == diag::ext_warn_duplicate_declspec ||
4006           DiagID == diag::err_duplicate_declspec)
4007         Diag(Loc, DiagID) << PrevSpec
4008                           << FixItHint::CreateRemoval(
4009                                  SourceRange(Loc, DS.getEndLoc()));
4010       else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4011         Diag(Loc, DiagID) << getLangOpts().OpenCLCPlusPlus
4012                           << getLangOpts().getOpenCLVersionTuple().getAsString()
4013                           << PrevSpec << isStorageClass;
4014       } else
4015         Diag(Loc, DiagID) << PrevSpec;
4016     }
4017 
4018     if (DiagID != diag::err_bool_redeclaration && ConsumedEnd.isInvalid())
4019       // After an error the next token can be an annotation token.
4020       ConsumeAnyToken();
4021 
4022     AttrsLastTime = false;
4023   }
4024 }
4025 
4026 /// ParseStructDeclaration - Parse a struct declaration without the terminating
4027 /// semicolon.
4028 ///
4029 /// Note that a struct declaration refers to a declaration in a struct,
4030 /// not to the declaration of a struct.
4031 ///
4032 ///       struct-declaration:
4033 /// [C2x]   attributes-specifier-seq[opt]
4034 ///           specifier-qualifier-list struct-declarator-list
4035 /// [GNU]   __extension__ struct-declaration
4036 /// [GNU]   specifier-qualifier-list
4037 ///       struct-declarator-list:
4038 ///         struct-declarator
4039 ///         struct-declarator-list ',' struct-declarator
4040 /// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
4041 ///       struct-declarator:
4042 ///         declarator
4043 /// [GNU]   declarator attributes[opt]
4044 ///         declarator[opt] ':' constant-expression
4045 /// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
4046 ///
4047 void Parser::ParseStructDeclaration(
4048     ParsingDeclSpec &DS,
4049     llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4050 
4051   if (Tok.is(tok::kw___extension__)) {
4052     // __extension__ silences extension warnings in the subexpression.
4053     ExtensionRAIIObject O(Diags);  // Use RAII to do this.
4054     ConsumeToken();
4055     return ParseStructDeclaration(DS, FieldsCallback);
4056   }
4057 
4058   // Parse leading attributes.
4059   ParsedAttributesWithRange Attrs(AttrFactory);
4060   MaybeParseCXX11Attributes(Attrs);
4061   DS.takeAttributesFrom(Attrs);
4062 
4063   // Parse the common specifier-qualifiers-list piece.
4064   ParseSpecifierQualifierList(DS);
4065 
4066   // If there are no declarators, this is a free-standing declaration
4067   // specifier. Let the actions module cope with it.
4068   if (Tok.is(tok::semi)) {
4069     RecordDecl *AnonRecord = nullptr;
4070     Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4071                                                        DS, AnonRecord);
4072     assert(!AnonRecord && "Did not expect anonymous struct or union here");
4073     DS.complete(TheDecl);
4074     return;
4075   }
4076 
4077   // Read struct-declarators until we find the semicolon.
4078   bool FirstDeclarator = true;
4079   SourceLocation CommaLoc;
4080   while (1) {
4081     ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4082     DeclaratorInfo.D.setCommaLoc(CommaLoc);
4083 
4084     // Attributes are only allowed here on successive declarators.
4085     if (!FirstDeclarator)
4086       MaybeParseGNUAttributes(DeclaratorInfo.D);
4087 
4088     /// struct-declarator: declarator
4089     /// struct-declarator: declarator[opt] ':' constant-expression
4090     if (Tok.isNot(tok::colon)) {
4091       // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4092       ColonProtectionRAIIObject X(*this);
4093       ParseDeclarator(DeclaratorInfo.D);
4094     } else
4095       DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4096 
4097     if (TryConsumeToken(tok::colon)) {
4098       ExprResult Res(ParseConstantExpression());
4099       if (Res.isInvalid())
4100         SkipUntil(tok::semi, StopBeforeMatch);
4101       else
4102         DeclaratorInfo.BitfieldSize = Res.get();
4103     }
4104 
4105     // If attributes exist after the declarator, parse them.
4106     MaybeParseGNUAttributes(DeclaratorInfo.D);
4107 
4108     // We're done with this declarator;  invoke the callback.
4109     FieldsCallback(DeclaratorInfo);
4110 
4111     // If we don't have a comma, it is either the end of the list (a ';')
4112     // or an error, bail out.
4113     if (!TryConsumeToken(tok::comma, CommaLoc))
4114       return;
4115 
4116     FirstDeclarator = false;
4117   }
4118 }
4119 
4120 /// ParseStructUnionBody
4121 ///       struct-contents:
4122 ///         struct-declaration-list
4123 /// [EXT]   empty
4124 /// [GNU]   "struct-declaration-list" without terminatoring ';'
4125 ///       struct-declaration-list:
4126 ///         struct-declaration
4127 ///         struct-declaration-list struct-declaration
4128 /// [OBC]   '@' 'defs' '(' class-name ')'
4129 ///
4130 void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4131                                   DeclSpec::TST TagType, Decl *TagDecl) {
4132   PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4133                                       "parsing struct/union body");
4134   assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4135 
4136   BalancedDelimiterTracker T(*this, tok::l_brace);
4137   if (T.consumeOpen())
4138     return;
4139 
4140   ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4141   Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4142 
4143   SmallVector<Decl *, 32> FieldDecls;
4144 
4145   // While we still have something to read, read the declarations in the struct.
4146   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4147          Tok.isNot(tok::eof)) {
4148     // Each iteration of this loop reads one struct-declaration.
4149 
4150     // Check for extraneous top-level semicolon.
4151     if (Tok.is(tok::semi)) {
4152       ConsumeExtraSemi(InsideStruct, TagType);
4153       continue;
4154     }
4155 
4156     // Parse _Static_assert declaration.
4157     if (Tok.is(tok::kw__Static_assert)) {
4158       SourceLocation DeclEnd;
4159       ParseStaticAssertDeclaration(DeclEnd);
4160       continue;
4161     }
4162 
4163     if (Tok.is(tok::annot_pragma_pack)) {
4164       HandlePragmaPack();
4165       continue;
4166     }
4167 
4168     if (Tok.is(tok::annot_pragma_align)) {
4169       HandlePragmaAlign();
4170       continue;
4171     }
4172 
4173     if (Tok.is(tok::annot_pragma_openmp)) {
4174       // Result can be ignored, because it must be always empty.
4175       AccessSpecifier AS = AS_none;
4176       ParsedAttributesWithRange Attrs(AttrFactory);
4177       (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4178       continue;
4179     }
4180 
4181     if (tok::isPragmaAnnotation(Tok.getKind())) {
4182       Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4183           << DeclSpec::getSpecifierName(
4184                  TagType, Actions.getASTContext().getPrintingPolicy());
4185       ConsumeAnnotationToken();
4186       continue;
4187     }
4188 
4189     if (!Tok.is(tok::at)) {
4190       auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4191         // Install the declarator into the current TagDecl.
4192         Decl *Field =
4193             Actions.ActOnField(getCurScope(), TagDecl,
4194                                FD.D.getDeclSpec().getSourceRange().getBegin(),
4195                                FD.D, FD.BitfieldSize);
4196         FieldDecls.push_back(Field);
4197         FD.complete(Field);
4198       };
4199 
4200       // Parse all the comma separated declarators.
4201       ParsingDeclSpec DS(*this);
4202       ParseStructDeclaration(DS, CFieldCallback);
4203     } else { // Handle @defs
4204       ConsumeToken();
4205       if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4206         Diag(Tok, diag::err_unexpected_at);
4207         SkipUntil(tok::semi);
4208         continue;
4209       }
4210       ConsumeToken();
4211       ExpectAndConsume(tok::l_paren);
4212       if (!Tok.is(tok::identifier)) {
4213         Diag(Tok, diag::err_expected) << tok::identifier;
4214         SkipUntil(tok::semi);
4215         continue;
4216       }
4217       SmallVector<Decl *, 16> Fields;
4218       Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4219                         Tok.getIdentifierInfo(), Fields);
4220       FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
4221       ConsumeToken();
4222       ExpectAndConsume(tok::r_paren);
4223     }
4224 
4225     if (TryConsumeToken(tok::semi))
4226       continue;
4227 
4228     if (Tok.is(tok::r_brace)) {
4229       ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4230       break;
4231     }
4232 
4233     ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4234     // Skip to end of block or statement to avoid ext-warning on extra ';'.
4235     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4236     // If we stopped at a ';', eat it.
4237     TryConsumeToken(tok::semi);
4238   }
4239 
4240   T.consumeClose();
4241 
4242   ParsedAttributes attrs(AttrFactory);
4243   // If attributes exist after struct contents, parse them.
4244   MaybeParseGNUAttributes(attrs);
4245 
4246   Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4247                       T.getOpenLocation(), T.getCloseLocation(), attrs);
4248   StructScope.Exit();
4249   Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4250 }
4251 
4252 /// ParseEnumSpecifier
4253 ///       enum-specifier: [C99 6.7.2.2]
4254 ///         'enum' identifier[opt] '{' enumerator-list '}'
4255 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4256 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4257 ///                                                 '}' attributes[opt]
4258 /// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4259 ///                                                 '}'
4260 ///         'enum' identifier
4261 /// [GNU]   'enum' attributes[opt] identifier
4262 ///
4263 /// [C++11] enum-head '{' enumerator-list[opt] '}'
4264 /// [C++11] enum-head '{' enumerator-list ','  '}'
4265 ///
4266 ///       enum-head: [C++11]
4267 ///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4268 ///         enum-key attribute-specifier-seq[opt] nested-name-specifier
4269 ///             identifier enum-base[opt]
4270 ///
4271 ///       enum-key: [C++11]
4272 ///         'enum'
4273 ///         'enum' 'class'
4274 ///         'enum' 'struct'
4275 ///
4276 ///       enum-base: [C++11]
4277 ///         ':' type-specifier-seq
4278 ///
4279 /// [C++] elaborated-type-specifier:
4280 /// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
4281 ///
4282 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4283                                 const ParsedTemplateInfo &TemplateInfo,
4284                                 AccessSpecifier AS, DeclSpecContext DSC) {
4285   // Parse the tag portion of this.
4286   if (Tok.is(tok::code_completion)) {
4287     // Code completion for an enum name.
4288     Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4289     return cutOffParsing();
4290   }
4291 
4292   // If attributes exist after tag, parse them.
4293   ParsedAttributesWithRange attrs(AttrFactory);
4294   MaybeParseGNUAttributes(attrs);
4295   MaybeParseCXX11Attributes(attrs);
4296   MaybeParseMicrosoftDeclSpecs(attrs);
4297 
4298   SourceLocation ScopedEnumKWLoc;
4299   bool IsScopedUsingClassTag = false;
4300 
4301   // In C++11, recognize 'enum class' and 'enum struct'.
4302   if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4303     Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
4304                                         : diag::ext_scoped_enum);
4305     IsScopedUsingClassTag = Tok.is(tok::kw_class);
4306     ScopedEnumKWLoc = ConsumeToken();
4307 
4308     // Attributes are not allowed between these keywords.  Diagnose,
4309     // but then just treat them like they appeared in the right place.
4310     ProhibitAttributes(attrs);
4311 
4312     // They are allowed afterwards, though.
4313     MaybeParseGNUAttributes(attrs);
4314     MaybeParseCXX11Attributes(attrs);
4315     MaybeParseMicrosoftDeclSpecs(attrs);
4316   }
4317 
4318   // C++11 [temp.explicit]p12:
4319   //   The usual access controls do not apply to names used to specify
4320   //   explicit instantiations.
4321   // We extend this to also cover explicit specializations.  Note that
4322   // we don't suppress if this turns out to be an elaborated type
4323   // specifier.
4324   bool shouldDelayDiagsInTag =
4325     (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4326      TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
4327   SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4328 
4329   // Enum definitions should not be parsed in a trailing-return-type.
4330   bool AllowDeclaration = DSC != DeclSpecContext::DSC_trailing;
4331 
4332   CXXScopeSpec &SS = DS.getTypeSpecScope();
4333   if (getLangOpts().CPlusPlus) {
4334     // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
4335     // if a fixed underlying type is allowed.
4336     ColonProtectionRAIIObject X(*this, AllowDeclaration);
4337 
4338     CXXScopeSpec Spec;
4339     if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
4340                                        /*EnteringContext=*/true))
4341       return;
4342 
4343     if (Spec.isSet() && Tok.isNot(tok::identifier)) {
4344       Diag(Tok, diag::err_expected) << tok::identifier;
4345       if (Tok.isNot(tok::l_brace)) {
4346         // Has no name and is not a definition.
4347         // Skip the rest of this declarator, up until the comma or semicolon.
4348         SkipUntil(tok::comma, StopAtSemi);
4349         return;
4350       }
4351     }
4352 
4353     SS = Spec;
4354   }
4355 
4356   // Must have either 'enum name' or 'enum {...}'.
4357   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
4358       !(AllowDeclaration && Tok.is(tok::colon))) {
4359     Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4360 
4361     // Skip the rest of this declarator, up until the comma or semicolon.
4362     SkipUntil(tok::comma, StopAtSemi);
4363     return;
4364   }
4365 
4366   // If an identifier is present, consume and remember it.
4367   IdentifierInfo *Name = nullptr;
4368   SourceLocation NameLoc;
4369   if (Tok.is(tok::identifier)) {
4370     Name = Tok.getIdentifierInfo();
4371     NameLoc = ConsumeToken();
4372   }
4373 
4374   if (!Name && ScopedEnumKWLoc.isValid()) {
4375     // C++0x 7.2p2: The optional identifier shall not be omitted in the
4376     // declaration of a scoped enumeration.
4377     Diag(Tok, diag::err_scoped_enum_missing_identifier);
4378     ScopedEnumKWLoc = SourceLocation();
4379     IsScopedUsingClassTag = false;
4380   }
4381 
4382   // Okay, end the suppression area.  We'll decide whether to emit the
4383   // diagnostics in a second.
4384   if (shouldDelayDiagsInTag)
4385     diagsFromTag.done();
4386 
4387   TypeResult BaseType;
4388 
4389   // Parse the fixed underlying type.
4390   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4391   if (AllowDeclaration && Tok.is(tok::colon)) {
4392     bool PossibleBitfield = false;
4393     if (CanBeBitfield) {
4394       // If we're in class scope, this can either be an enum declaration with
4395       // an underlying type, or a declaration of a bitfield member. We try to
4396       // use a simple disambiguation scheme first to catch the common cases
4397       // (integer literal, sizeof); if it's still ambiguous, we then consider
4398       // anything that's a simple-type-specifier followed by '(' as an
4399       // expression. This suffices because function types are not valid
4400       // underlying types anyway.
4401       EnterExpressionEvaluationContext Unevaluated(
4402           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4403       TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
4404       // If the next token starts an expression, we know we're parsing a
4405       // bit-field. This is the common case.
4406       if (TPR == TPResult::True)
4407         PossibleBitfield = true;
4408       // If the next token starts a type-specifier-seq, it may be either a
4409       // a fixed underlying type or the start of a function-style cast in C++;
4410       // lookahead one more token to see if it's obvious that we have a
4411       // fixed underlying type.
4412       else if (TPR == TPResult::False &&
4413                GetLookAheadToken(2).getKind() == tok::semi) {
4414         // Consume the ':'.
4415         ConsumeToken();
4416       } else {
4417         // We have the start of a type-specifier-seq, so we have to perform
4418         // tentative parsing to determine whether we have an expression or a
4419         // type.
4420         TentativeParsingAction TPA(*this);
4421 
4422         // Consume the ':'.
4423         ConsumeToken();
4424 
4425         // If we see a type specifier followed by an open-brace, we have an
4426         // ambiguity between an underlying type and a C++11 braced
4427         // function-style cast. Resolve this by always treating it as an
4428         // underlying type.
4429         // FIXME: The standard is not entirely clear on how to disambiguate in
4430         // this case.
4431         if ((getLangOpts().CPlusPlus &&
4432              isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
4433             (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
4434           // We'll parse this as a bitfield later.
4435           PossibleBitfield = true;
4436           TPA.Revert();
4437         } else {
4438           // We have a type-specifier-seq.
4439           TPA.Commit();
4440         }
4441       }
4442     } else {
4443       // Consume the ':'.
4444       ConsumeToken();
4445     }
4446 
4447     if (!PossibleBitfield) {
4448       SourceRange Range;
4449       BaseType = ParseTypeName(&Range);
4450 
4451       if (!getLangOpts().ObjC) {
4452         if (getLangOpts().CPlusPlus11)
4453           Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
4454         else if (getLangOpts().CPlusPlus)
4455           Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type);
4456         else if (getLangOpts().MicrosoftExt)
4457           Diag(StartLoc, diag::ext_ms_c_enum_fixed_underlying_type);
4458         else
4459           Diag(StartLoc, diag::ext_clang_c_enum_fixed_underlying_type);
4460       }
4461     }
4462   }
4463 
4464   // There are four options here.  If we have 'friend enum foo;' then this is a
4465   // friend declaration, and cannot have an accompanying definition. If we have
4466   // 'enum foo;', then this is a forward declaration.  If we have
4467   // 'enum foo {...' then this is a definition. Otherwise we have something
4468   // like 'enum foo xyz', a reference.
4469   //
4470   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4471   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4472   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4473   //
4474   Sema::TagUseKind TUK;
4475   if (!AllowDeclaration) {
4476     TUK = Sema::TUK_Reference;
4477   } else if (Tok.is(tok::l_brace)) {
4478     if (DS.isFriendSpecified()) {
4479       Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4480         << SourceRange(DS.getFriendSpecLoc());
4481       ConsumeBrace();
4482       SkipUntil(tok::r_brace, StopAtSemi);
4483       TUK = Sema::TUK_Friend;
4484     } else {
4485       TUK = Sema::TUK_Definition;
4486     }
4487   } else if (!isTypeSpecifier(DSC) &&
4488              (Tok.is(tok::semi) ||
4489               (Tok.isAtStartOfLine() &&
4490                !isValidAfterTypeSpecifier(CanBeBitfield)))) {
4491     TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
4492     if (Tok.isNot(tok::semi)) {
4493       // A semicolon was missing after this declaration. Diagnose and recover.
4494       ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4495       PP.EnterToken(Tok, /*IsReinject=*/true);
4496       Tok.setKind(tok::semi);
4497     }
4498   } else {
4499     TUK = Sema::TUK_Reference;
4500   }
4501 
4502   // If this is an elaborated type specifier, and we delayed
4503   // diagnostics before, just merge them into the current pool.
4504   if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
4505     diagsFromTag.redelay();
4506   }
4507 
4508   MultiTemplateParamsArg TParams;
4509   if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4510       TUK != Sema::TUK_Reference) {
4511     if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4512       // Skip the rest of this declarator, up until the comma or semicolon.
4513       Diag(Tok, diag::err_enum_template);
4514       SkipUntil(tok::comma, StopAtSemi);
4515       return;
4516     }
4517 
4518     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4519       // Enumerations can't be explicitly instantiated.
4520       DS.SetTypeSpecError();
4521       Diag(StartLoc, diag::err_explicit_instantiation_enum);
4522       return;
4523     }
4524 
4525     assert(TemplateInfo.TemplateParams && "no template parameters");
4526     TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4527                                      TemplateInfo.TemplateParams->size());
4528   }
4529 
4530   if (TUK == Sema::TUK_Reference)
4531     ProhibitAttributes(attrs);
4532 
4533   if (!Name && TUK != Sema::TUK_Definition) {
4534     Diag(Tok, diag::err_enumerator_unnamed_no_def);
4535 
4536     // Skip the rest of this declarator, up until the comma or semicolon.
4537     SkipUntil(tok::comma, StopAtSemi);
4538     return;
4539   }
4540 
4541   stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4542 
4543   Sema::SkipBodyInfo SkipBody;
4544   if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
4545       NextToken().is(tok::identifier))
4546     SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4547                                               NextToken().getIdentifierInfo(),
4548                                               NextToken().getLocation());
4549 
4550   bool Owned = false;
4551   bool IsDependent = false;
4552   const char *PrevSpec = nullptr;
4553   unsigned DiagID;
4554   Decl *TagDecl = Actions.ActOnTag(
4555       getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4556       attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4557       ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4558       DSC == DeclSpecContext::DSC_type_specifier,
4559       DSC == DeclSpecContext::DSC_template_param ||
4560           DSC == DeclSpecContext::DSC_template_type_arg,
4561       &SkipBody);
4562 
4563   if (SkipBody.ShouldSkip) {
4564     assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4565 
4566     BalancedDelimiterTracker T(*this, tok::l_brace);
4567     T.consumeOpen();
4568     T.skipToEnd();
4569 
4570     if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4571                            NameLoc.isValid() ? NameLoc : StartLoc,
4572                            PrevSpec, DiagID, TagDecl, Owned,
4573                            Actions.getASTContext().getPrintingPolicy()))
4574       Diag(StartLoc, DiagID) << PrevSpec;
4575     return;
4576   }
4577 
4578   if (IsDependent) {
4579     // This enum has a dependent nested-name-specifier. Handle it as a
4580     // dependent tag.
4581     if (!Name) {
4582       DS.SetTypeSpecError();
4583       Diag(Tok, diag::err_expected_type_name_after_typename);
4584       return;
4585     }
4586 
4587     TypeResult Type = Actions.ActOnDependentTag(
4588         getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4589     if (Type.isInvalid()) {
4590       DS.SetTypeSpecError();
4591       return;
4592     }
4593 
4594     if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4595                            NameLoc.isValid() ? NameLoc : StartLoc,
4596                            PrevSpec, DiagID, Type.get(),
4597                            Actions.getASTContext().getPrintingPolicy()))
4598       Diag(StartLoc, DiagID) << PrevSpec;
4599 
4600     return;
4601   }
4602 
4603   if (!TagDecl) {
4604     // The action failed to produce an enumeration tag. If this is a
4605     // definition, consume the entire definition.
4606     if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4607       ConsumeBrace();
4608       SkipUntil(tok::r_brace, StopAtSemi);
4609     }
4610 
4611     DS.SetTypeSpecError();
4612     return;
4613   }
4614 
4615   if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
4616     Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
4617     ParseEnumBody(StartLoc, D);
4618     if (SkipBody.CheckSameAsPrevious &&
4619         !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
4620       DS.SetTypeSpecError();
4621       return;
4622     }
4623   }
4624 
4625   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4626                          NameLoc.isValid() ? NameLoc : StartLoc,
4627                          PrevSpec, DiagID, TagDecl, Owned,
4628                          Actions.getASTContext().getPrintingPolicy()))
4629     Diag(StartLoc, DiagID) << PrevSpec;
4630 }
4631 
4632 /// ParseEnumBody - Parse a {} enclosed enumerator-list.
4633 ///       enumerator-list:
4634 ///         enumerator
4635 ///         enumerator-list ',' enumerator
4636 ///       enumerator:
4637 ///         enumeration-constant attributes[opt]
4638 ///         enumeration-constant attributes[opt] '=' constant-expression
4639 ///       enumeration-constant:
4640 ///         identifier
4641 ///
4642 void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4643   // Enter the scope of the enum body and start the definition.
4644   ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4645   Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4646 
4647   BalancedDelimiterTracker T(*this, tok::l_brace);
4648   T.consumeOpen();
4649 
4650   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4651   if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
4652     Diag(Tok, diag::err_empty_enum);
4653 
4654   SmallVector<Decl *, 32> EnumConstantDecls;
4655   SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4656 
4657   Decl *LastEnumConstDecl = nullptr;
4658 
4659   // Parse the enumerator-list.
4660   while (Tok.isNot(tok::r_brace)) {
4661     // Parse enumerator. If failed, try skipping till the start of the next
4662     // enumerator definition.
4663     if (Tok.isNot(tok::identifier)) {
4664       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4665       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4666           TryConsumeToken(tok::comma))
4667         continue;
4668       break;
4669     }
4670     IdentifierInfo *Ident = Tok.getIdentifierInfo();
4671     SourceLocation IdentLoc = ConsumeToken();
4672 
4673     // If attributes exist after the enumerator, parse them.
4674     ParsedAttributesWithRange attrs(AttrFactory);
4675     MaybeParseGNUAttributes(attrs);
4676     ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
4677     if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
4678       if (getLangOpts().CPlusPlus)
4679         Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4680                                     ? diag::warn_cxx14_compat_ns_enum_attribute
4681                                     : diag::ext_ns_enum_attribute)
4682             << 1 /*enumerator*/;
4683       ParseCXX11Attributes(attrs);
4684     }
4685 
4686     SourceLocation EqualLoc;
4687     ExprResult AssignedVal;
4688     EnumAvailabilityDiags.emplace_back(*this);
4689 
4690     EnterExpressionEvaluationContext ConstantEvaluated(
4691         Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4692     if (TryConsumeToken(tok::equal, EqualLoc)) {
4693       AssignedVal = ParseConstantExpressionInExprEvalContext();
4694       if (AssignedVal.isInvalid())
4695         SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4696     }
4697 
4698     // Install the enumerator constant into EnumDecl.
4699     Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4700         getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4701         EqualLoc, AssignedVal.get());
4702     EnumAvailabilityDiags.back().done();
4703 
4704     EnumConstantDecls.push_back(EnumConstDecl);
4705     LastEnumConstDecl = EnumConstDecl;
4706 
4707     if (Tok.is(tok::identifier)) {
4708       // We're missing a comma between enumerators.
4709       SourceLocation Loc = getEndOfPreviousToken();
4710       Diag(Loc, diag::err_enumerator_list_missing_comma)
4711         << FixItHint::CreateInsertion(Loc, ", ");
4712       continue;
4713     }
4714 
4715     // Emumerator definition must be finished, only comma or r_brace are
4716     // allowed here.
4717     SourceLocation CommaLoc;
4718     if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
4719       if (EqualLoc.isValid())
4720         Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4721                                                            << tok::comma;
4722       else
4723         Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4724       if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4725         if (TryConsumeToken(tok::comma, CommaLoc))
4726           continue;
4727       } else {
4728         break;
4729       }
4730     }
4731 
4732     // If comma is followed by r_brace, emit appropriate warning.
4733     if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
4734       if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
4735         Diag(CommaLoc, getLangOpts().CPlusPlus ?
4736                diag::ext_enumerator_list_comma_cxx :
4737                diag::ext_enumerator_list_comma_c)
4738           << FixItHint::CreateRemoval(CommaLoc);
4739       else if (getLangOpts().CPlusPlus11)
4740         Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4741           << FixItHint::CreateRemoval(CommaLoc);
4742       break;
4743     }
4744   }
4745 
4746   // Eat the }.
4747   T.consumeClose();
4748 
4749   // If attributes exist after the identifier list, parse them.
4750   ParsedAttributes attrs(AttrFactory);
4751   MaybeParseGNUAttributes(attrs);
4752 
4753   Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4754                         getCurScope(), attrs);
4755 
4756   // Now handle enum constant availability diagnostics.
4757   assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4758   for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
4759     ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4760     EnumAvailabilityDiags[i].redelay();
4761     PD.complete(EnumConstantDecls[i]);
4762   }
4763 
4764   EnumScope.Exit();
4765   Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4766 
4767   // The next token must be valid after an enum definition. If not, a ';'
4768   // was probably forgotten.
4769   bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4770   if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4771     ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4772     // Push this token back into the preprocessor and change our current token
4773     // to ';' so that the rest of the code recovers as though there were an
4774     // ';' after the definition.
4775     PP.EnterToken(Tok, /*IsReinject=*/true);
4776     Tok.setKind(tok::semi);
4777   }
4778 }
4779 
4780 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4781 /// is definitely a type-specifier.  Return false if it isn't part of a type
4782 /// specifier or if we're not sure.
4783 bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4784   switch (Tok.getKind()) {
4785   default: return false;
4786     // type-specifiers
4787   case tok::kw_short:
4788   case tok::kw_long:
4789   case tok::kw___int64:
4790   case tok::kw___int128:
4791   case tok::kw_signed:
4792   case tok::kw_unsigned:
4793   case tok::kw__Complex:
4794   case tok::kw__Imaginary:
4795   case tok::kw_void:
4796   case tok::kw_char:
4797   case tok::kw_wchar_t:
4798   case tok::kw_char8_t:
4799   case tok::kw_char16_t:
4800   case tok::kw_char32_t:
4801   case tok::kw_int:
4802   case tok::kw_half:
4803   case tok::kw_float:
4804   case tok::kw_double:
4805   case tok::kw__Accum:
4806   case tok::kw__Fract:
4807   case tok::kw__Float16:
4808   case tok::kw___float128:
4809   case tok::kw_bool:
4810   case tok::kw__Bool:
4811   case tok::kw__Decimal32:
4812   case tok::kw__Decimal64:
4813   case tok::kw__Decimal128:
4814   case tok::kw___vector:
4815 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4816 #include "clang/Basic/OpenCLImageTypes.def"
4817 
4818     // struct-or-union-specifier (C99) or class-specifier (C++)
4819   case tok::kw_class:
4820   case tok::kw_struct:
4821   case tok::kw___interface:
4822   case tok::kw_union:
4823     // enum-specifier
4824   case tok::kw_enum:
4825 
4826     // typedef-name
4827   case tok::annot_typename:
4828     return true;
4829   }
4830 }
4831 
4832 /// isTypeSpecifierQualifier - Return true if the current token could be the
4833 /// start of a specifier-qualifier-list.
4834 bool Parser::isTypeSpecifierQualifier() {
4835   switch (Tok.getKind()) {
4836   default: return false;
4837 
4838   case tok::identifier:   // foo::bar
4839     if (TryAltiVecVectorToken())
4840       return true;
4841     LLVM_FALLTHROUGH;
4842   case tok::kw_typename:  // typename T::type
4843     // Annotate typenames and C++ scope specifiers.  If we get one, just
4844     // recurse to handle whatever we get.
4845     if (TryAnnotateTypeOrScopeToken())
4846       return true;
4847     if (Tok.is(tok::identifier))
4848       return false;
4849     return isTypeSpecifierQualifier();
4850 
4851   case tok::coloncolon:   // ::foo::bar
4852     if (NextToken().is(tok::kw_new) ||    // ::new
4853         NextToken().is(tok::kw_delete))   // ::delete
4854       return false;
4855 
4856     if (TryAnnotateTypeOrScopeToken())
4857       return true;
4858     return isTypeSpecifierQualifier();
4859 
4860     // GNU attributes support.
4861   case tok::kw___attribute:
4862     // GNU typeof support.
4863   case tok::kw_typeof:
4864 
4865     // type-specifiers
4866   case tok::kw_short:
4867   case tok::kw_long:
4868   case tok::kw___int64:
4869   case tok::kw___int128:
4870   case tok::kw_signed:
4871   case tok::kw_unsigned:
4872   case tok::kw__Complex:
4873   case tok::kw__Imaginary:
4874   case tok::kw_void:
4875   case tok::kw_char:
4876   case tok::kw_wchar_t:
4877   case tok::kw_char8_t:
4878   case tok::kw_char16_t:
4879   case tok::kw_char32_t:
4880   case tok::kw_int:
4881   case tok::kw_half:
4882   case tok::kw_float:
4883   case tok::kw_double:
4884   case tok::kw__Accum:
4885   case tok::kw__Fract:
4886   case tok::kw__Float16:
4887   case tok::kw___float128:
4888   case tok::kw_bool:
4889   case tok::kw__Bool:
4890   case tok::kw__Decimal32:
4891   case tok::kw__Decimal64:
4892   case tok::kw__Decimal128:
4893   case tok::kw___vector:
4894 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
4895 #include "clang/Basic/OpenCLImageTypes.def"
4896 
4897     // struct-or-union-specifier (C99) or class-specifier (C++)
4898   case tok::kw_class:
4899   case tok::kw_struct:
4900   case tok::kw___interface:
4901   case tok::kw_union:
4902     // enum-specifier
4903   case tok::kw_enum:
4904 
4905     // type-qualifier
4906   case tok::kw_const:
4907   case tok::kw_volatile:
4908   case tok::kw_restrict:
4909   case tok::kw__Sat:
4910 
4911     // Debugger support.
4912   case tok::kw___unknown_anytype:
4913 
4914     // typedef-name
4915   case tok::annot_typename:
4916     return true;
4917 
4918     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
4919   case tok::less:
4920     return getLangOpts().ObjC;
4921 
4922   case tok::kw___cdecl:
4923   case tok::kw___stdcall:
4924   case tok::kw___fastcall:
4925   case tok::kw___thiscall:
4926   case tok::kw___regcall:
4927   case tok::kw___vectorcall:
4928   case tok::kw___w64:
4929   case tok::kw___ptr64:
4930   case tok::kw___ptr32:
4931   case tok::kw___pascal:
4932   case tok::kw___unaligned:
4933 
4934   case tok::kw__Nonnull:
4935   case tok::kw__Nullable:
4936   case tok::kw__Null_unspecified:
4937 
4938   case tok::kw___kindof:
4939 
4940   case tok::kw___private:
4941   case tok::kw___local:
4942   case tok::kw___global:
4943   case tok::kw___constant:
4944   case tok::kw___generic:
4945   case tok::kw___read_only:
4946   case tok::kw___read_write:
4947   case tok::kw___write_only:
4948     return true;
4949 
4950   case tok::kw_private:
4951     return getLangOpts().OpenCL;
4952 
4953   // C11 _Atomic
4954   case tok::kw__Atomic:
4955     return true;
4956   }
4957 }
4958 
4959 /// isDeclarationSpecifier() - Return true if the current token is part of a
4960 /// declaration specifier.
4961 ///
4962 /// \param DisambiguatingWithExpression True to indicate that the purpose of
4963 /// this check is to disambiguate between an expression and a declaration.
4964 bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
4965   switch (Tok.getKind()) {
4966   default: return false;
4967 
4968   case tok::kw_pipe:
4969     return (getLangOpts().OpenCL && getLangOpts().OpenCLVersion >= 200) ||
4970            getLangOpts().OpenCLCPlusPlus;
4971 
4972   case tok::identifier:   // foo::bar
4973     // Unfortunate hack to support "Class.factoryMethod" notation.
4974     if (getLangOpts().ObjC && NextToken().is(tok::period))
4975       return false;
4976     if (TryAltiVecVectorToken())
4977       return true;
4978     LLVM_FALLTHROUGH;
4979   case tok::kw_decltype: // decltype(T())::type
4980   case tok::kw_typename: // typename T::type
4981     // Annotate typenames and C++ scope specifiers.  If we get one, just
4982     // recurse to handle whatever we get.
4983     if (TryAnnotateTypeOrScopeToken())
4984       return true;
4985     if (Tok.is(tok::identifier))
4986       return false;
4987 
4988     // If we're in Objective-C and we have an Objective-C class type followed
4989     // by an identifier and then either ':' or ']', in a place where an
4990     // expression is permitted, then this is probably a class message send
4991     // missing the initial '['. In this case, we won't consider this to be
4992     // the start of a declaration.
4993     if (DisambiguatingWithExpression &&
4994         isStartOfObjCClassMessageMissingOpenBracket())
4995       return false;
4996 
4997     return isDeclarationSpecifier();
4998 
4999   case tok::coloncolon:   // ::foo::bar
5000     if (NextToken().is(tok::kw_new) ||    // ::new
5001         NextToken().is(tok::kw_delete))   // ::delete
5002       return false;
5003 
5004     // Annotate typenames and C++ scope specifiers.  If we get one, just
5005     // recurse to handle whatever we get.
5006     if (TryAnnotateTypeOrScopeToken())
5007       return true;
5008     return isDeclarationSpecifier();
5009 
5010     // storage-class-specifier
5011   case tok::kw_typedef:
5012   case tok::kw_extern:
5013   case tok::kw___private_extern__:
5014   case tok::kw_static:
5015   case tok::kw_auto:
5016   case tok::kw___auto_type:
5017   case tok::kw_register:
5018   case tok::kw___thread:
5019   case tok::kw_thread_local:
5020   case tok::kw__Thread_local:
5021 
5022     // Modules
5023   case tok::kw___module_private__:
5024 
5025     // Debugger support
5026   case tok::kw___unknown_anytype:
5027 
5028     // type-specifiers
5029   case tok::kw_short:
5030   case tok::kw_long:
5031   case tok::kw___int64:
5032   case tok::kw___int128:
5033   case tok::kw_signed:
5034   case tok::kw_unsigned:
5035   case tok::kw__Complex:
5036   case tok::kw__Imaginary:
5037   case tok::kw_void:
5038   case tok::kw_char:
5039   case tok::kw_wchar_t:
5040   case tok::kw_char8_t:
5041   case tok::kw_char16_t:
5042   case tok::kw_char32_t:
5043 
5044   case tok::kw_int:
5045   case tok::kw_half:
5046   case tok::kw_float:
5047   case tok::kw_double:
5048   case tok::kw__Accum:
5049   case tok::kw__Fract:
5050   case tok::kw__Float16:
5051   case tok::kw___float128:
5052   case tok::kw_bool:
5053   case tok::kw__Bool:
5054   case tok::kw__Decimal32:
5055   case tok::kw__Decimal64:
5056   case tok::kw__Decimal128:
5057   case tok::kw___vector:
5058 
5059     // struct-or-union-specifier (C99) or class-specifier (C++)
5060   case tok::kw_class:
5061   case tok::kw_struct:
5062   case tok::kw_union:
5063   case tok::kw___interface:
5064     // enum-specifier
5065   case tok::kw_enum:
5066 
5067     // type-qualifier
5068   case tok::kw_const:
5069   case tok::kw_volatile:
5070   case tok::kw_restrict:
5071   case tok::kw__Sat:
5072 
5073     // function-specifier
5074   case tok::kw_inline:
5075   case tok::kw_virtual:
5076   case tok::kw_explicit:
5077   case tok::kw__Noreturn:
5078 
5079     // alignment-specifier
5080   case tok::kw__Alignas:
5081 
5082     // friend keyword.
5083   case tok::kw_friend:
5084 
5085     // static_assert-declaration
5086   case tok::kw__Static_assert:
5087 
5088     // GNU typeof support.
5089   case tok::kw_typeof:
5090 
5091     // GNU attributes.
5092   case tok::kw___attribute:
5093 
5094     // C++11 decltype and constexpr.
5095   case tok::annot_decltype:
5096   case tok::kw_constexpr:
5097 
5098     // C++20 consteval and constinit.
5099   case tok::kw_consteval:
5100   case tok::kw_constinit:
5101 
5102     // C11 _Atomic
5103   case tok::kw__Atomic:
5104     return true;
5105 
5106     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5107   case tok::less:
5108     return getLangOpts().ObjC;
5109 
5110     // typedef-name
5111   case tok::annot_typename:
5112     return !DisambiguatingWithExpression ||
5113            !isStartOfObjCClassMessageMissingOpenBracket();
5114 
5115   case tok::kw___declspec:
5116   case tok::kw___cdecl:
5117   case tok::kw___stdcall:
5118   case tok::kw___fastcall:
5119   case tok::kw___thiscall:
5120   case tok::kw___regcall:
5121   case tok::kw___vectorcall:
5122   case tok::kw___w64:
5123   case tok::kw___sptr:
5124   case tok::kw___uptr:
5125   case tok::kw___ptr64:
5126   case tok::kw___ptr32:
5127   case tok::kw___forceinline:
5128   case tok::kw___pascal:
5129   case tok::kw___unaligned:
5130 
5131   case tok::kw__Nonnull:
5132   case tok::kw__Nullable:
5133   case tok::kw__Null_unspecified:
5134 
5135   case tok::kw___kindof:
5136 
5137   case tok::kw___private:
5138   case tok::kw___local:
5139   case tok::kw___global:
5140   case tok::kw___constant:
5141   case tok::kw___generic:
5142   case tok::kw___read_only:
5143   case tok::kw___read_write:
5144   case tok::kw___write_only:
5145 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5146 #include "clang/Basic/OpenCLImageTypes.def"
5147 
5148     return true;
5149 
5150   case tok::kw_private:
5151     return getLangOpts().OpenCL;
5152   }
5153 }
5154 
5155 bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
5156   TentativeParsingAction TPA(*this);
5157 
5158   // Parse the C++ scope specifier.
5159   CXXScopeSpec SS;
5160   if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
5161                                      /*EnteringContext=*/true)) {
5162     TPA.Revert();
5163     return false;
5164   }
5165 
5166   // Parse the constructor name.
5167   if (Tok.is(tok::identifier)) {
5168     // We already know that we have a constructor name; just consume
5169     // the token.
5170     ConsumeToken();
5171   } else if (Tok.is(tok::annot_template_id)) {
5172     ConsumeAnnotationToken();
5173   } else {
5174     TPA.Revert();
5175     return false;
5176   }
5177 
5178   // There may be attributes here, appertaining to the constructor name or type
5179   // we just stepped past.
5180   SkipCXX11Attributes();
5181 
5182   // Current class name must be followed by a left parenthesis.
5183   if (Tok.isNot(tok::l_paren)) {
5184     TPA.Revert();
5185     return false;
5186   }
5187   ConsumeParen();
5188 
5189   // A right parenthesis, or ellipsis followed by a right parenthesis signals
5190   // that we have a constructor.
5191   if (Tok.is(tok::r_paren) ||
5192       (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
5193     TPA.Revert();
5194     return true;
5195   }
5196 
5197   // A C++11 attribute here signals that we have a constructor, and is an
5198   // attribute on the first constructor parameter.
5199   if (getLangOpts().CPlusPlus11 &&
5200       isCXX11AttributeSpecifier(/*Disambiguate*/ false,
5201                                 /*OuterMightBeMessageSend*/ true)) {
5202     TPA.Revert();
5203     return true;
5204   }
5205 
5206   // If we need to, enter the specified scope.
5207   DeclaratorScopeObj DeclScopeObj(*this, SS);
5208   if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
5209     DeclScopeObj.EnterDeclaratorScope();
5210 
5211   // Optionally skip Microsoft attributes.
5212   ParsedAttributes Attrs(AttrFactory);
5213   MaybeParseMicrosoftAttributes(Attrs);
5214 
5215   // Check whether the next token(s) are part of a declaration
5216   // specifier, in which case we have the start of a parameter and,
5217   // therefore, we know that this is a constructor.
5218   bool IsConstructor = false;
5219   if (isDeclarationSpecifier())
5220     IsConstructor = true;
5221   else if (Tok.is(tok::identifier) ||
5222            (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
5223     // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
5224     // This might be a parenthesized member name, but is more likely to
5225     // be a constructor declaration with an invalid argument type. Keep
5226     // looking.
5227     if (Tok.is(tok::annot_cxxscope))
5228       ConsumeAnnotationToken();
5229     ConsumeToken();
5230 
5231     // If this is not a constructor, we must be parsing a declarator,
5232     // which must have one of the following syntactic forms (see the
5233     // grammar extract at the start of ParseDirectDeclarator):
5234     switch (Tok.getKind()) {
5235     case tok::l_paren:
5236       // C(X   (   int));
5237     case tok::l_square:
5238       // C(X   [   5]);
5239       // C(X   [   [attribute]]);
5240     case tok::coloncolon:
5241       // C(X   ::   Y);
5242       // C(X   ::   *p);
5243       // Assume this isn't a constructor, rather than assuming it's a
5244       // constructor with an unnamed parameter of an ill-formed type.
5245       break;
5246 
5247     case tok::r_paren:
5248       // C(X   )
5249 
5250       // Skip past the right-paren and any following attributes to get to
5251       // the function body or trailing-return-type.
5252       ConsumeParen();
5253       SkipCXX11Attributes();
5254 
5255       if (DeductionGuide) {
5256         // C(X) -> ... is a deduction guide.
5257         IsConstructor = Tok.is(tok::arrow);
5258         break;
5259       }
5260       if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
5261         // Assume these were meant to be constructors:
5262         //   C(X)   :    (the name of a bit-field cannot be parenthesized).
5263         //   C(X)   try  (this is otherwise ill-formed).
5264         IsConstructor = true;
5265       }
5266       if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
5267         // If we have a constructor name within the class definition,
5268         // assume these were meant to be constructors:
5269         //   C(X)   {
5270         //   C(X)   ;
5271         // ... because otherwise we would be declaring a non-static data
5272         // member that is ill-formed because it's of the same type as its
5273         // surrounding class.
5274         //
5275         // FIXME: We can actually do this whether or not the name is qualified,
5276         // because if it is qualified in this context it must be being used as
5277         // a constructor name.
5278         // currently, so we're somewhat conservative here.
5279         IsConstructor = IsUnqualified;
5280       }
5281       break;
5282 
5283     default:
5284       IsConstructor = true;
5285       break;
5286     }
5287   }
5288 
5289   TPA.Revert();
5290   return IsConstructor;
5291 }
5292 
5293 /// ParseTypeQualifierListOpt
5294 ///          type-qualifier-list: [C99 6.7.5]
5295 ///            type-qualifier
5296 /// [vendor]   attributes
5297 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
5298 ///            type-qualifier-list type-qualifier
5299 /// [vendor]   type-qualifier-list attributes
5300 ///              [ only if AttrReqs & AR_VendorAttributesParsed ]
5301 /// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
5302 ///              [ only if AttReqs & AR_CXX11AttributesParsed ]
5303 /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
5304 /// AttrRequirements bitmask values.
5305 void Parser::ParseTypeQualifierListOpt(
5306     DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
5307     bool IdentifierRequired,
5308     Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
5309   if (standardAttributesAllowed() && (AttrReqs & AR_CXX11AttributesParsed) &&
5310       isCXX11AttributeSpecifier()) {
5311     ParsedAttributesWithRange attrs(AttrFactory);
5312     ParseCXX11Attributes(attrs);
5313     DS.takeAttributesFrom(attrs);
5314   }
5315 
5316   SourceLocation EndLoc;
5317 
5318   while (1) {
5319     bool isInvalid = false;
5320     const char *PrevSpec = nullptr;
5321     unsigned DiagID = 0;
5322     SourceLocation Loc = Tok.getLocation();
5323 
5324     switch (Tok.getKind()) {
5325     case tok::code_completion:
5326       if (CodeCompletionHandler)
5327         (*CodeCompletionHandler)();
5328       else
5329         Actions.CodeCompleteTypeQualifiers(DS);
5330       return cutOffParsing();
5331 
5332     case tok::kw_const:
5333       isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
5334                                  getLangOpts());
5335       break;
5336     case tok::kw_volatile:
5337       isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
5338                                  getLangOpts());
5339       break;
5340     case tok::kw_restrict:
5341       isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
5342                                  getLangOpts());
5343       break;
5344     case tok::kw__Atomic:
5345       if (!AtomicAllowed)
5346         goto DoneWithTypeQuals;
5347       if (!getLangOpts().C11)
5348         Diag(Tok, diag::ext_c11_feature) << Tok.getName();
5349       isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
5350                                  getLangOpts());
5351       break;
5352 
5353     // OpenCL qualifiers:
5354     case tok::kw_private:
5355       if (!getLangOpts().OpenCL)
5356         goto DoneWithTypeQuals;
5357       LLVM_FALLTHROUGH;
5358     case tok::kw___private:
5359     case tok::kw___global:
5360     case tok::kw___local:
5361     case tok::kw___constant:
5362     case tok::kw___generic:
5363     case tok::kw___read_only:
5364     case tok::kw___write_only:
5365     case tok::kw___read_write:
5366       ParseOpenCLQualifiers(DS.getAttributes());
5367       break;
5368 
5369     case tok::kw___unaligned:
5370       isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
5371                                  getLangOpts());
5372       break;
5373     case tok::kw___uptr:
5374       // GNU libc headers in C mode use '__uptr' as an identifier which conflicts
5375       // with the MS modifier keyword.
5376       if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
5377           IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
5378         if (TryKeywordIdentFallback(false))
5379           continue;
5380       }
5381       LLVM_FALLTHROUGH;
5382     case tok::kw___sptr:
5383     case tok::kw___w64:
5384     case tok::kw___ptr64:
5385     case tok::kw___ptr32:
5386     case tok::kw___cdecl:
5387     case tok::kw___stdcall:
5388     case tok::kw___fastcall:
5389     case tok::kw___thiscall:
5390     case tok::kw___regcall:
5391     case tok::kw___vectorcall:
5392       if (AttrReqs & AR_DeclspecAttributesParsed) {
5393         ParseMicrosoftTypeAttributes(DS.getAttributes());
5394         continue;
5395       }
5396       goto DoneWithTypeQuals;
5397     case tok::kw___pascal:
5398       if (AttrReqs & AR_VendorAttributesParsed) {
5399         ParseBorlandTypeAttributes(DS.getAttributes());
5400         continue;
5401       }
5402       goto DoneWithTypeQuals;
5403 
5404     // Nullability type specifiers.
5405     case tok::kw__Nonnull:
5406     case tok::kw__Nullable:
5407     case tok::kw__Null_unspecified:
5408       ParseNullabilityTypeSpecifiers(DS.getAttributes());
5409       continue;
5410 
5411     // Objective-C 'kindof' types.
5412     case tok::kw___kindof:
5413       DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
5414                                 nullptr, 0, ParsedAttr::AS_Keyword);
5415       (void)ConsumeToken();
5416       continue;
5417 
5418     case tok::kw___attribute:
5419       if (AttrReqs & AR_GNUAttributesParsedAndRejected)
5420         // When GNU attributes are expressly forbidden, diagnose their usage.
5421         Diag(Tok, diag::err_attributes_not_allowed);
5422 
5423       // Parse the attributes even if they are rejected to ensure that error
5424       // recovery is graceful.
5425       if (AttrReqs & AR_GNUAttributesParsed ||
5426           AttrReqs & AR_GNUAttributesParsedAndRejected) {
5427         ParseGNUAttributes(DS.getAttributes());
5428         continue; // do *not* consume the next token!
5429       }
5430       // otherwise, FALL THROUGH!
5431       LLVM_FALLTHROUGH;
5432     default:
5433       DoneWithTypeQuals:
5434       // If this is not a type-qualifier token, we're done reading type
5435       // qualifiers.  First verify that DeclSpec's are consistent.
5436       DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
5437       if (EndLoc.isValid())
5438         DS.SetRangeEnd(EndLoc);
5439       return;
5440     }
5441 
5442     // If the specifier combination wasn't legal, issue a diagnostic.
5443     if (isInvalid) {
5444       assert(PrevSpec && "Method did not return previous specifier!");
5445       Diag(Tok, DiagID) << PrevSpec;
5446     }
5447     EndLoc = ConsumeToken();
5448   }
5449 }
5450 
5451 /// ParseDeclarator - Parse and verify a newly-initialized declarator.
5452 ///
5453 void Parser::ParseDeclarator(Declarator &D) {
5454   /// This implements the 'declarator' production in the C grammar, then checks
5455   /// for well-formedness and issues diagnostics.
5456   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
5457 }
5458 
5459 static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
5460                                DeclaratorContext TheContext) {
5461   if (Kind == tok::star || Kind == tok::caret)
5462     return true;
5463 
5464   if (Kind == tok::kw_pipe &&
5465       ((Lang.OpenCL && Lang.OpenCLVersion >= 200) || Lang.OpenCLCPlusPlus))
5466     return true;
5467 
5468   if (!Lang.CPlusPlus)
5469     return false;
5470 
5471   if (Kind == tok::amp)
5472     return true;
5473 
5474   // We parse rvalue refs in C++03, because otherwise the errors are scary.
5475   // But we must not parse them in conversion-type-ids and new-type-ids, since
5476   // those can be legitimately followed by a && operator.
5477   // (The same thing can in theory happen after a trailing-return-type, but
5478   // since those are a C++11 feature, there is no rejects-valid issue there.)
5479   if (Kind == tok::ampamp)
5480     return Lang.CPlusPlus11 ||
5481            (TheContext != DeclaratorContext::ConversionIdContext &&
5482             TheContext != DeclaratorContext::CXXNewContext);
5483 
5484   return false;
5485 }
5486 
5487 // Indicates whether the given declarator is a pipe declarator.
5488 static bool isPipeDeclerator(const Declarator &D) {
5489   const unsigned NumTypes = D.getNumTypeObjects();
5490 
5491   for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
5492     if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
5493       return true;
5494 
5495   return false;
5496 }
5497 
5498 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
5499 /// is parsed by the function passed to it. Pass null, and the direct-declarator
5500 /// isn't parsed at all, making this function effectively parse the C++
5501 /// ptr-operator production.
5502 ///
5503 /// If the grammar of this construct is extended, matching changes must also be
5504 /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
5505 /// isConstructorDeclarator.
5506 ///
5507 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
5508 /// [C]     pointer[opt] direct-declarator
5509 /// [C++]   direct-declarator
5510 /// [C++]   ptr-operator declarator
5511 ///
5512 ///       pointer: [C99 6.7.5]
5513 ///         '*' type-qualifier-list[opt]
5514 ///         '*' type-qualifier-list[opt] pointer
5515 ///
5516 ///       ptr-operator:
5517 ///         '*' cv-qualifier-seq[opt]
5518 ///         '&'
5519 /// [C++0x] '&&'
5520 /// [GNU]   '&' restrict[opt] attributes[opt]
5521 /// [GNU?]  '&&' restrict[opt] attributes[opt]
5522 ///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
5523 void Parser::ParseDeclaratorInternal(Declarator &D,
5524                                      DirectDeclParseFunction DirectDeclParser) {
5525   if (Diags.hasAllExtensionsSilenced())
5526     D.setExtension();
5527 
5528   // C++ member pointers start with a '::' or a nested-name.
5529   // Member pointers get special handling, since there's no place for the
5530   // scope spec in the generic path below.
5531   if (getLangOpts().CPlusPlus &&
5532       (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
5533        (Tok.is(tok::identifier) &&
5534         (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
5535        Tok.is(tok::annot_cxxscope))) {
5536     bool EnteringContext =
5537         D.getContext() == DeclaratorContext::FileContext ||
5538         D.getContext() == DeclaratorContext::MemberContext;
5539     CXXScopeSpec SS;
5540     ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
5541 
5542     if (SS.isNotEmpty()) {
5543       if (Tok.isNot(tok::star)) {
5544         // The scope spec really belongs to the direct-declarator.
5545         if (D.mayHaveIdentifier())
5546           D.getCXXScopeSpec() = SS;
5547         else
5548           AnnotateScopeToken(SS, true);
5549 
5550         if (DirectDeclParser)
5551           (this->*DirectDeclParser)(D);
5552         return;
5553       }
5554 
5555       SourceLocation Loc = ConsumeToken();
5556       D.SetRangeEnd(Loc);
5557       DeclSpec DS(AttrFactory);
5558       ParseTypeQualifierListOpt(DS);
5559       D.ExtendWithDeclSpec(DS);
5560 
5561       // Recurse to parse whatever is left.
5562       ParseDeclaratorInternal(D, DirectDeclParser);
5563 
5564       // Sema will have to catch (syntactically invalid) pointers into global
5565       // scope. It has to catch pointers into namespace scope anyway.
5566       D.AddTypeInfo(DeclaratorChunk::getMemberPointer(
5567                         SS, DS.getTypeQualifiers(), DS.getEndLoc()),
5568                     std::move(DS.getAttributes()),
5569                     /* Don't replace range end. */ SourceLocation());
5570       return;
5571     }
5572   }
5573 
5574   tok::TokenKind Kind = Tok.getKind();
5575 
5576   if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
5577     DeclSpec DS(AttrFactory);
5578     ParseTypeQualifierListOpt(DS);
5579 
5580     D.AddTypeInfo(
5581         DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
5582         std::move(DS.getAttributes()), SourceLocation());
5583   }
5584 
5585   // Not a pointer, C++ reference, or block.
5586   if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
5587     if (DirectDeclParser)
5588       (this->*DirectDeclParser)(D);
5589     return;
5590   }
5591 
5592   // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
5593   // '&&' -> rvalue reference
5594   SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
5595   D.SetRangeEnd(Loc);
5596 
5597   if (Kind == tok::star || Kind == tok::caret) {
5598     // Is a pointer.
5599     DeclSpec DS(AttrFactory);
5600 
5601     // GNU attributes are not allowed here in a new-type-id, but Declspec and
5602     // C++11 attributes are allowed.
5603     unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
5604                     ((D.getContext() != DeclaratorContext::CXXNewContext)
5605                          ? AR_GNUAttributesParsed
5606                          : AR_GNUAttributesParsedAndRejected);
5607     ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
5608     D.ExtendWithDeclSpec(DS);
5609 
5610     // Recursively parse the declarator.
5611     ParseDeclaratorInternal(D, DirectDeclParser);
5612     if (Kind == tok::star)
5613       // Remember that we parsed a pointer type, and remember the type-quals.
5614       D.AddTypeInfo(DeclaratorChunk::getPointer(
5615                         DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(),
5616                         DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(),
5617                         DS.getAtomicSpecLoc(), DS.getUnalignedSpecLoc()),
5618                     std::move(DS.getAttributes()), SourceLocation());
5619     else
5620       // Remember that we parsed a Block type, and remember the type-quals.
5621       D.AddTypeInfo(
5622           DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc),
5623           std::move(DS.getAttributes()), SourceLocation());
5624   } else {
5625     // Is a reference
5626     DeclSpec DS(AttrFactory);
5627 
5628     // Complain about rvalue references in C++03, but then go on and build
5629     // the declarator.
5630     if (Kind == tok::ampamp)
5631       Diag(Loc, getLangOpts().CPlusPlus11 ?
5632            diag::warn_cxx98_compat_rvalue_reference :
5633            diag::ext_rvalue_reference);
5634 
5635     // GNU-style and C++11 attributes are allowed here, as is restrict.
5636     ParseTypeQualifierListOpt(DS);
5637     D.ExtendWithDeclSpec(DS);
5638 
5639     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
5640     // cv-qualifiers are introduced through the use of a typedef or of a
5641     // template type argument, in which case the cv-qualifiers are ignored.
5642     if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
5643       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5644         Diag(DS.getConstSpecLoc(),
5645              diag::err_invalid_reference_qualifier_application) << "const";
5646       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5647         Diag(DS.getVolatileSpecLoc(),
5648              diag::err_invalid_reference_qualifier_application) << "volatile";
5649       // 'restrict' is permitted as an extension.
5650       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5651         Diag(DS.getAtomicSpecLoc(),
5652              diag::err_invalid_reference_qualifier_application) << "_Atomic";
5653     }
5654 
5655     // Recursively parse the declarator.
5656     ParseDeclaratorInternal(D, DirectDeclParser);
5657 
5658     if (D.getNumTypeObjects() > 0) {
5659       // C++ [dcl.ref]p4: There shall be no references to references.
5660       DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
5661       if (InnerChunk.Kind == DeclaratorChunk::Reference) {
5662         if (const IdentifierInfo *II = D.getIdentifier())
5663           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5664            << II;
5665         else
5666           Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
5667             << "type name";
5668 
5669         // Once we've complained about the reference-to-reference, we
5670         // can go ahead and build the (technically ill-formed)
5671         // declarator: reference collapsing will take care of it.
5672       }
5673     }
5674 
5675     // Remember that we parsed a reference type.
5676     D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
5677                                                 Kind == tok::amp),
5678                   std::move(DS.getAttributes()), SourceLocation());
5679   }
5680 }
5681 
5682 // When correcting from misplaced brackets before the identifier, the location
5683 // is saved inside the declarator so that other diagnostic messages can use
5684 // them.  This extracts and returns that location, or returns the provided
5685 // location if a stored location does not exist.
5686 static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
5687                                                 SourceLocation Loc) {
5688   if (D.getName().StartLocation.isInvalid() &&
5689       D.getName().EndLocation.isValid())
5690     return D.getName().EndLocation;
5691 
5692   return Loc;
5693 }
5694 
5695 /// ParseDirectDeclarator
5696 ///       direct-declarator: [C99 6.7.5]
5697 /// [C99]   identifier
5698 ///         '(' declarator ')'
5699 /// [GNU]   '(' attributes declarator ')'
5700 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
5701 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
5702 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
5703 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
5704 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
5705 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
5706 ///                    attribute-specifier-seq[opt]
5707 ///         direct-declarator '(' parameter-type-list ')'
5708 ///         direct-declarator '(' identifier-list[opt] ')'
5709 /// [GNU]   direct-declarator '(' parameter-forward-declarations
5710 ///                    parameter-type-list[opt] ')'
5711 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
5712 ///                    cv-qualifier-seq[opt] exception-specification[opt]
5713 /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
5714 ///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
5715 ///                    ref-qualifier[opt] exception-specification[opt]
5716 /// [C++]   declarator-id
5717 /// [C++11] declarator-id attribute-specifier-seq[opt]
5718 ///
5719 ///       declarator-id: [C++ 8]
5720 ///         '...'[opt] id-expression
5721 ///         '::'[opt] nested-name-specifier[opt] type-name
5722 ///
5723 ///       id-expression: [C++ 5.1]
5724 ///         unqualified-id
5725 ///         qualified-id
5726 ///
5727 ///       unqualified-id: [C++ 5.1]
5728 ///         identifier
5729 ///         operator-function-id
5730 ///         conversion-function-id
5731 ///          '~' class-name
5732 ///         template-id
5733 ///
5734 /// C++17 adds the following, which we also handle here:
5735 ///
5736 ///       simple-declaration:
5737 ///         <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
5738 ///
5739 /// Note, any additional constructs added here may need corresponding changes
5740 /// in isConstructorDeclarator.
5741 void Parser::ParseDirectDeclarator(Declarator &D) {
5742   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
5743 
5744   if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
5745     // This might be a C++17 structured binding.
5746     if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
5747         D.getCXXScopeSpec().isEmpty())
5748       return ParseDecompositionDeclarator(D);
5749 
5750     // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
5751     // this context it is a bitfield. Also in range-based for statement colon
5752     // may delimit for-range-declaration.
5753     ColonProtectionRAIIObject X(
5754         *this, D.getContext() == DeclaratorContext::MemberContext ||
5755                    (D.getContext() == DeclaratorContext::ForContext &&
5756                     getLangOpts().CPlusPlus11));
5757 
5758     // ParseDeclaratorInternal might already have parsed the scope.
5759     if (D.getCXXScopeSpec().isEmpty()) {
5760       bool EnteringContext =
5761           D.getContext() == DeclaratorContext::FileContext ||
5762           D.getContext() == DeclaratorContext::MemberContext;
5763       ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
5764                                      EnteringContext);
5765     }
5766 
5767     if (D.getCXXScopeSpec().isValid()) {
5768       if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
5769                                              D.getCXXScopeSpec()))
5770         // Change the declaration context for name lookup, until this function
5771         // is exited (and the declarator has been parsed).
5772         DeclScopeObj.EnterDeclaratorScope();
5773       else if (getObjCDeclContext()) {
5774         // Ensure that we don't interpret the next token as an identifier when
5775         // dealing with declarations in an Objective-C container.
5776         D.SetIdentifier(nullptr, Tok.getLocation());
5777         D.setInvalidType(true);
5778         ConsumeToken();
5779         goto PastIdentifier;
5780       }
5781     }
5782 
5783     // C++0x [dcl.fct]p14:
5784     //   There is a syntactic ambiguity when an ellipsis occurs at the end of a
5785     //   parameter-declaration-clause without a preceding comma. In this case,
5786     //   the ellipsis is parsed as part of the abstract-declarator if the type
5787     //   of the parameter either names a template parameter pack that has not
5788     //   been expanded or contains auto; otherwise, it is parsed as part of the
5789     //   parameter-declaration-clause.
5790     if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
5791         !((D.getContext() == DeclaratorContext::PrototypeContext ||
5792            D.getContext() == DeclaratorContext::LambdaExprParameterContext ||
5793            D.getContext() == DeclaratorContext::BlockLiteralContext) &&
5794           NextToken().is(tok::r_paren) &&
5795           !D.hasGroupingParens() &&
5796           !Actions.containsUnexpandedParameterPacks(D) &&
5797           D.getDeclSpec().getTypeSpecType() != TST_auto)) {
5798       SourceLocation EllipsisLoc = ConsumeToken();
5799       if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
5800         // The ellipsis was put in the wrong place. Recover, and explain to
5801         // the user what they should have done.
5802         ParseDeclarator(D);
5803         if (EllipsisLoc.isValid())
5804           DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
5805         return;
5806       } else
5807         D.setEllipsisLoc(EllipsisLoc);
5808 
5809       // The ellipsis can't be followed by a parenthesized declarator. We
5810       // check for that in ParseParenDeclarator, after we have disambiguated
5811       // the l_paren token.
5812     }
5813 
5814     if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
5815                     tok::tilde)) {
5816       // We found something that indicates the start of an unqualified-id.
5817       // Parse that unqualified-id.
5818       bool AllowConstructorName;
5819       bool AllowDeductionGuide;
5820       if (D.getDeclSpec().hasTypeSpecifier()) {
5821         AllowConstructorName = false;
5822         AllowDeductionGuide = false;
5823       } else if (D.getCXXScopeSpec().isSet()) {
5824         AllowConstructorName =
5825           (D.getContext() == DeclaratorContext::FileContext ||
5826            D.getContext() == DeclaratorContext::MemberContext);
5827         AllowDeductionGuide = false;
5828       } else {
5829         AllowConstructorName =
5830             (D.getContext() == DeclaratorContext::MemberContext);
5831         AllowDeductionGuide =
5832           (D.getContext() == DeclaratorContext::FileContext ||
5833            D.getContext() == DeclaratorContext::MemberContext);
5834       }
5835 
5836       bool HadScope = D.getCXXScopeSpec().isValid();
5837       if (ParseUnqualifiedId(D.getCXXScopeSpec(),
5838                              /*EnteringContext=*/true,
5839                              /*AllowDestructorName=*/true, AllowConstructorName,
5840                              AllowDeductionGuide, nullptr, nullptr,
5841                              D.getName()) ||
5842           // Once we're past the identifier, if the scope was bad, mark the
5843           // whole declarator bad.
5844           D.getCXXScopeSpec().isInvalid()) {
5845         D.SetIdentifier(nullptr, Tok.getLocation());
5846         D.setInvalidType(true);
5847       } else {
5848         // ParseUnqualifiedId might have parsed a scope specifier during error
5849         // recovery. If it did so, enter that scope.
5850         if (!HadScope && D.getCXXScopeSpec().isValid() &&
5851             Actions.ShouldEnterDeclaratorScope(getCurScope(),
5852                                                D.getCXXScopeSpec()))
5853           DeclScopeObj.EnterDeclaratorScope();
5854 
5855         // Parsed the unqualified-id; update range information and move along.
5856         if (D.getSourceRange().getBegin().isInvalid())
5857           D.SetRangeBegin(D.getName().getSourceRange().getBegin());
5858         D.SetRangeEnd(D.getName().getSourceRange().getEnd());
5859       }
5860       goto PastIdentifier;
5861     }
5862 
5863     if (D.getCXXScopeSpec().isNotEmpty()) {
5864       // We have a scope specifier but no following unqualified-id.
5865       Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
5866            diag::err_expected_unqualified_id)
5867           << /*C++*/1;
5868       D.SetIdentifier(nullptr, Tok.getLocation());
5869       goto PastIdentifier;
5870     }
5871   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
5872     assert(!getLangOpts().CPlusPlus &&
5873            "There's a C++-specific check for tok::identifier above");
5874     assert(Tok.getIdentifierInfo() && "Not an identifier?");
5875     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5876     D.SetRangeEnd(Tok.getLocation());
5877     ConsumeToken();
5878     goto PastIdentifier;
5879   } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
5880     // We're not allowed an identifier here, but we got one. Try to figure out
5881     // if the user was trying to attach a name to the type, or whether the name
5882     // is some unrelated trailing syntax.
5883     bool DiagnoseIdentifier = false;
5884     if (D.hasGroupingParens())
5885       // An identifier within parens is unlikely to be intended to be anything
5886       // other than a name being "declared".
5887       DiagnoseIdentifier = true;
5888     else if (D.getContext() == DeclaratorContext::TemplateArgContext)
5889       // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
5890       DiagnoseIdentifier =
5891           NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
5892     else if (D.getContext() == DeclaratorContext::AliasDeclContext ||
5893              D.getContext() == DeclaratorContext::AliasTemplateContext)
5894       // The most likely error is that the ';' was forgotten.
5895       DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
5896     else if ((D.getContext() == DeclaratorContext::TrailingReturnContext ||
5897               D.getContext() == DeclaratorContext::TrailingReturnVarContext) &&
5898              !isCXX11VirtSpecifier(Tok))
5899       DiagnoseIdentifier = NextToken().isOneOf(
5900           tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
5901     if (DiagnoseIdentifier) {
5902       Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
5903         << FixItHint::CreateRemoval(Tok.getLocation());
5904       D.SetIdentifier(nullptr, Tok.getLocation());
5905       ConsumeToken();
5906       goto PastIdentifier;
5907     }
5908   }
5909 
5910   if (Tok.is(tok::l_paren)) {
5911     // If this might be an abstract-declarator followed by a direct-initializer,
5912     // check whether this is a valid declarator chunk. If it can't be, assume
5913     // that it's an initializer instead.
5914     if (D.mayOmitIdentifier() && D.mayBeFollowedByCXXDirectInit()) {
5915       RevertingTentativeParsingAction PA(*this);
5916       if (TryParseDeclarator(true, D.mayHaveIdentifier(), true) ==
5917               TPResult::False) {
5918         D.SetIdentifier(nullptr, Tok.getLocation());
5919         goto PastIdentifier;
5920       }
5921     }
5922 
5923     // direct-declarator: '(' declarator ')'
5924     // direct-declarator: '(' attributes declarator ')'
5925     // Example: 'char (*X)'   or 'int (*XX)(void)'
5926     ParseParenDeclarator(D);
5927 
5928     // If the declarator was parenthesized, we entered the declarator
5929     // scope when parsing the parenthesized declarator, then exited
5930     // the scope already. Re-enter the scope, if we need to.
5931     if (D.getCXXScopeSpec().isSet()) {
5932       // If there was an error parsing parenthesized declarator, declarator
5933       // scope may have been entered before. Don't do it again.
5934       if (!D.isInvalidType() &&
5935           Actions.ShouldEnterDeclaratorScope(getCurScope(),
5936                                              D.getCXXScopeSpec()))
5937         // Change the declaration context for name lookup, until this function
5938         // is exited (and the declarator has been parsed).
5939         DeclScopeObj.EnterDeclaratorScope();
5940     }
5941   } else if (D.mayOmitIdentifier()) {
5942     // This could be something simple like "int" (in which case the declarator
5943     // portion is empty), if an abstract-declarator is allowed.
5944     D.SetIdentifier(nullptr, Tok.getLocation());
5945 
5946     // The grammar for abstract-pack-declarator does not allow grouping parens.
5947     // FIXME: Revisit this once core issue 1488 is resolved.
5948     if (D.hasEllipsis() && D.hasGroupingParens())
5949       Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
5950            diag::ext_abstract_pack_declarator_parens);
5951   } else {
5952     if (Tok.getKind() == tok::annot_pragma_parser_crash)
5953       LLVM_BUILTIN_TRAP;
5954     if (Tok.is(tok::l_square))
5955       return ParseMisplacedBracketDeclarator(D);
5956     if (D.getContext() == DeclaratorContext::MemberContext) {
5957       // Objective-C++: Detect C++ keywords and try to prevent further errors by
5958       // treating these keyword as valid member names.
5959       if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
5960           Tok.getIdentifierInfo() &&
5961           Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
5962         Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5963              diag::err_expected_member_name_or_semi_objcxx_keyword)
5964             << Tok.getIdentifierInfo()
5965             << (D.getDeclSpec().isEmpty() ? SourceRange()
5966                                           : D.getDeclSpec().getSourceRange());
5967         D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
5968         D.SetRangeEnd(Tok.getLocation());
5969         ConsumeToken();
5970         goto PastIdentifier;
5971       }
5972       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5973            diag::err_expected_member_name_or_semi)
5974           << (D.getDeclSpec().isEmpty() ? SourceRange()
5975                                         : D.getDeclSpec().getSourceRange());
5976     } else if (getLangOpts().CPlusPlus) {
5977       if (Tok.isOneOf(tok::period, tok::arrow))
5978         Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
5979       else {
5980         SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
5981         if (Tok.isAtStartOfLine() && Loc.isValid())
5982           Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
5983               << getLangOpts().CPlusPlus;
5984         else
5985           Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5986                diag::err_expected_unqualified_id)
5987               << getLangOpts().CPlusPlus;
5988       }
5989     } else {
5990       Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
5991            diag::err_expected_either)
5992           << tok::identifier << tok::l_paren;
5993     }
5994     D.SetIdentifier(nullptr, Tok.getLocation());
5995     D.setInvalidType(true);
5996   }
5997 
5998  PastIdentifier:
5999   assert(D.isPastIdentifier() &&
6000          "Haven't past the location of the identifier yet?");
6001 
6002   // Don't parse attributes unless we have parsed an unparenthesized name.
6003   if (D.hasName() && !D.getNumTypeObjects())
6004     MaybeParseCXX11Attributes(D);
6005 
6006   while (1) {
6007     if (Tok.is(tok::l_paren)) {
6008       // Enter function-declaration scope, limiting any declarators to the
6009       // function prototype scope, including parameter declarators.
6010       ParseScope PrototypeScope(this,
6011                                 Scope::FunctionPrototypeScope|Scope::DeclScope|
6012                                 (D.isFunctionDeclaratorAFunctionDeclaration()
6013                                    ? Scope::FunctionDeclarationScope : 0));
6014 
6015       // The paren may be part of a C++ direct initializer, eg. "int x(1);".
6016       // In such a case, check if we actually have a function declarator; if it
6017       // is not, the declarator has been fully parsed.
6018       bool IsAmbiguous = false;
6019       if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
6020         // The name of the declarator, if any, is tentatively declared within
6021         // a possible direct initializer.
6022         TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
6023         bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
6024         TentativelyDeclaredIdentifiers.pop_back();
6025         if (!IsFunctionDecl)
6026           break;
6027       }
6028       ParsedAttributes attrs(AttrFactory);
6029       BalancedDelimiterTracker T(*this, tok::l_paren);
6030       T.consumeOpen();
6031       ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
6032       PrototypeScope.Exit();
6033     } else if (Tok.is(tok::l_square)) {
6034       ParseBracketDeclarator(D);
6035     } else {
6036       break;
6037     }
6038   }
6039 }
6040 
6041 void Parser::ParseDecompositionDeclarator(Declarator &D) {
6042   assert(Tok.is(tok::l_square));
6043 
6044   // If this doesn't look like a structured binding, maybe it's a misplaced
6045   // array declarator.
6046   // FIXME: Consume the l_square first so we don't need extra lookahead for
6047   // this.
6048   if (!(NextToken().is(tok::identifier) &&
6049         GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
6050       !(NextToken().is(tok::r_square) &&
6051         GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
6052     return ParseMisplacedBracketDeclarator(D);
6053 
6054   BalancedDelimiterTracker T(*this, tok::l_square);
6055   T.consumeOpen();
6056 
6057   SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
6058   while (Tok.isNot(tok::r_square)) {
6059     if (!Bindings.empty()) {
6060       if (Tok.is(tok::comma))
6061         ConsumeToken();
6062       else {
6063         if (Tok.is(tok::identifier)) {
6064           SourceLocation EndLoc = getEndOfPreviousToken();
6065           Diag(EndLoc, diag::err_expected)
6066               << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
6067         } else {
6068           Diag(Tok, diag::err_expected_comma_or_rsquare);
6069         }
6070 
6071         SkipUntil(tok::r_square, tok::comma, tok::identifier,
6072                   StopAtSemi | StopBeforeMatch);
6073         if (Tok.is(tok::comma))
6074           ConsumeToken();
6075         else if (Tok.isNot(tok::identifier))
6076           break;
6077       }
6078     }
6079 
6080     if (Tok.isNot(tok::identifier)) {
6081       Diag(Tok, diag::err_expected) << tok::identifier;
6082       break;
6083     }
6084 
6085     Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
6086     ConsumeToken();
6087   }
6088 
6089   if (Tok.isNot(tok::r_square))
6090     // We've already diagnosed a problem here.
6091     T.skipToEnd();
6092   else {
6093     // C++17 does not allow the identifier-list in a structured binding
6094     // to be empty.
6095     if (Bindings.empty())
6096       Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
6097 
6098     T.consumeClose();
6099   }
6100 
6101   return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
6102                                     T.getCloseLocation());
6103 }
6104 
6105 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
6106 /// only called before the identifier, so these are most likely just grouping
6107 /// parens for precedence.  If we find that these are actually function
6108 /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
6109 ///
6110 ///       direct-declarator:
6111 ///         '(' declarator ')'
6112 /// [GNU]   '(' attributes declarator ')'
6113 ///         direct-declarator '(' parameter-type-list ')'
6114 ///         direct-declarator '(' identifier-list[opt] ')'
6115 /// [GNU]   direct-declarator '(' parameter-forward-declarations
6116 ///                    parameter-type-list[opt] ')'
6117 ///
6118 void Parser::ParseParenDeclarator(Declarator &D) {
6119   BalancedDelimiterTracker T(*this, tok::l_paren);
6120   T.consumeOpen();
6121 
6122   assert(!D.isPastIdentifier() && "Should be called before passing identifier");
6123 
6124   // Eat any attributes before we look at whether this is a grouping or function
6125   // declarator paren.  If this is a grouping paren, the attribute applies to
6126   // the type being built up, for example:
6127   //     int (__attribute__(()) *x)(long y)
6128   // If this ends up not being a grouping paren, the attribute applies to the
6129   // first argument, for example:
6130   //     int (__attribute__(()) int x)
6131   // In either case, we need to eat any attributes to be able to determine what
6132   // sort of paren this is.
6133   //
6134   ParsedAttributes attrs(AttrFactory);
6135   bool RequiresArg = false;
6136   if (Tok.is(tok::kw___attribute)) {
6137     ParseGNUAttributes(attrs);
6138 
6139     // We require that the argument list (if this is a non-grouping paren) be
6140     // present even if the attribute list was empty.
6141     RequiresArg = true;
6142   }
6143 
6144   // Eat any Microsoft extensions.
6145   ParseMicrosoftTypeAttributes(attrs);
6146 
6147   // Eat any Borland extensions.
6148   if  (Tok.is(tok::kw___pascal))
6149     ParseBorlandTypeAttributes(attrs);
6150 
6151   // If we haven't past the identifier yet (or where the identifier would be
6152   // stored, if this is an abstract declarator), then this is probably just
6153   // grouping parens. However, if this could be an abstract-declarator, then
6154   // this could also be the start of function arguments (consider 'void()').
6155   bool isGrouping;
6156 
6157   if (!D.mayOmitIdentifier()) {
6158     // If this can't be an abstract-declarator, this *must* be a grouping
6159     // paren, because we haven't seen the identifier yet.
6160     isGrouping = true;
6161   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
6162              (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
6163               NextToken().is(tok::r_paren)) || // C++ int(...)
6164              isDeclarationSpecifier() ||       // 'int(int)' is a function.
6165              isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a function.
6166     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
6167     // considered to be a type, not a K&R identifier-list.
6168     isGrouping = false;
6169   } else {
6170     // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
6171     isGrouping = true;
6172   }
6173 
6174   // If this is a grouping paren, handle:
6175   // direct-declarator: '(' declarator ')'
6176   // direct-declarator: '(' attributes declarator ')'
6177   if (isGrouping) {
6178     SourceLocation EllipsisLoc = D.getEllipsisLoc();
6179     D.setEllipsisLoc(SourceLocation());
6180 
6181     bool hadGroupingParens = D.hasGroupingParens();
6182     D.setGroupingParens(true);
6183     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6184     // Match the ')'.
6185     T.consumeClose();
6186     D.AddTypeInfo(
6187         DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()),
6188         std::move(attrs), T.getCloseLocation());
6189 
6190     D.setGroupingParens(hadGroupingParens);
6191 
6192     // An ellipsis cannot be placed outside parentheses.
6193     if (EllipsisLoc.isValid())
6194       DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
6195 
6196     return;
6197   }
6198 
6199   // Okay, if this wasn't a grouping paren, it must be the start of a function
6200   // argument list.  Recognize that this declarator will never have an
6201   // identifier (and remember where it would have been), then call into
6202   // ParseFunctionDeclarator to handle of argument list.
6203   D.SetIdentifier(nullptr, Tok.getLocation());
6204 
6205   // Enter function-declaration scope, limiting any declarators to the
6206   // function prototype scope, including parameter declarators.
6207   ParseScope PrototypeScope(this,
6208                             Scope::FunctionPrototypeScope | Scope::DeclScope |
6209                             (D.isFunctionDeclaratorAFunctionDeclaration()
6210                                ? Scope::FunctionDeclarationScope : 0));
6211   ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
6212   PrototypeScope.Exit();
6213 }
6214 
6215 /// ParseFunctionDeclarator - We are after the identifier and have parsed the
6216 /// declarator D up to a paren, which indicates that we are parsing function
6217 /// arguments.
6218 ///
6219 /// If FirstArgAttrs is non-null, then the caller parsed those arguments
6220 /// immediately after the open paren - they should be considered to be the
6221 /// first argument of a parameter.
6222 ///
6223 /// If RequiresArg is true, then the first argument of the function is required
6224 /// to be present and required to not be an identifier list.
6225 ///
6226 /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
6227 /// (C++11) ref-qualifier[opt], exception-specification[opt],
6228 /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
6229 ///
6230 /// [C++11] exception-specification:
6231 ///           dynamic-exception-specification
6232 ///           noexcept-specification
6233 ///
6234 void Parser::ParseFunctionDeclarator(Declarator &D,
6235                                      ParsedAttributes &FirstArgAttrs,
6236                                      BalancedDelimiterTracker &Tracker,
6237                                      bool IsAmbiguous,
6238                                      bool RequiresArg) {
6239   assert(getCurScope()->isFunctionPrototypeScope() &&
6240          "Should call from a Function scope");
6241   // lparen is already consumed!
6242   assert(D.isPastIdentifier() && "Should not call before identifier!");
6243 
6244   // This should be true when the function has typed arguments.
6245   // Otherwise, it is treated as a K&R-style function.
6246   bool HasProto = false;
6247   // Build up an array of information about the parsed arguments.
6248   SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
6249   // Remember where we see an ellipsis, if any.
6250   SourceLocation EllipsisLoc;
6251 
6252   DeclSpec DS(AttrFactory);
6253   bool RefQualifierIsLValueRef = true;
6254   SourceLocation RefQualifierLoc;
6255   ExceptionSpecificationType ESpecType = EST_None;
6256   SourceRange ESpecRange;
6257   SmallVector<ParsedType, 2> DynamicExceptions;
6258   SmallVector<SourceRange, 2> DynamicExceptionRanges;
6259   ExprResult NoexceptExpr;
6260   CachedTokens *ExceptionSpecTokens = nullptr;
6261   ParsedAttributesWithRange FnAttrs(AttrFactory);
6262   TypeResult TrailingReturnType;
6263 
6264   /* LocalEndLoc is the end location for the local FunctionTypeLoc.
6265      EndLoc is the end location for the function declarator.
6266      They differ for trailing return types. */
6267   SourceLocation StartLoc, LocalEndLoc, EndLoc;
6268   SourceLocation LParenLoc, RParenLoc;
6269   LParenLoc = Tracker.getOpenLocation();
6270   StartLoc = LParenLoc;
6271 
6272   if (isFunctionDeclaratorIdentifierList()) {
6273     if (RequiresArg)
6274       Diag(Tok, diag::err_argument_required_after_attribute);
6275 
6276     ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
6277 
6278     Tracker.consumeClose();
6279     RParenLoc = Tracker.getCloseLocation();
6280     LocalEndLoc = RParenLoc;
6281     EndLoc = RParenLoc;
6282 
6283     // If there are attributes following the identifier list, parse them and
6284     // prohibit them.
6285     MaybeParseCXX11Attributes(FnAttrs);
6286     ProhibitAttributes(FnAttrs);
6287   } else {
6288     if (Tok.isNot(tok::r_paren))
6289       ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
6290                                       EllipsisLoc);
6291     else if (RequiresArg)
6292       Diag(Tok, diag::err_argument_required_after_attribute);
6293 
6294     HasProto = ParamInfo.size() || getLangOpts().CPlusPlus
6295                                 || getLangOpts().OpenCL;
6296 
6297     // If we have the closing ')', eat it.
6298     Tracker.consumeClose();
6299     RParenLoc = Tracker.getCloseLocation();
6300     LocalEndLoc = RParenLoc;
6301     EndLoc = RParenLoc;
6302 
6303     if (getLangOpts().CPlusPlus) {
6304       // FIXME: Accept these components in any order, and produce fixits to
6305       // correct the order if the user gets it wrong. Ideally we should deal
6306       // with the pure-specifier in the same way.
6307 
6308       // Parse cv-qualifier-seq[opt].
6309       ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
6310                                 /*AtomicAllowed*/ false,
6311                                 /*IdentifierRequired=*/false,
6312                                 llvm::function_ref<void()>([&]() {
6313                                   Actions.CodeCompleteFunctionQualifiers(DS, D);
6314                                 }));
6315       if (!DS.getSourceRange().getEnd().isInvalid()) {
6316         EndLoc = DS.getSourceRange().getEnd();
6317       }
6318 
6319       // Parse ref-qualifier[opt].
6320       if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
6321         EndLoc = RefQualifierLoc;
6322 
6323       // C++11 [expr.prim.general]p3:
6324       //   If a declaration declares a member function or member function
6325       //   template of a class X, the expression this is a prvalue of type
6326       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6327       //   and the end of the function-definition, member-declarator, or
6328       //   declarator.
6329       // FIXME: currently, "static" case isn't handled correctly.
6330       bool IsCXX11MemberFunction =
6331         getLangOpts().CPlusPlus11 &&
6332         D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6333         (D.getContext() == DeclaratorContext::MemberContext
6334          ? !D.getDeclSpec().isFriendSpecified()
6335          : D.getContext() == DeclaratorContext::FileContext &&
6336            D.getCXXScopeSpec().isValid() &&
6337            Actions.CurContext->isRecord());
6338 
6339       Qualifiers Q = Qualifiers::fromCVRUMask(DS.getTypeQualifiers());
6340       if (D.getDeclSpec().hasConstexprSpecifier() && !getLangOpts().CPlusPlus14)
6341         Q.addConst();
6342       // FIXME: Collect C++ address spaces.
6343       // If there are multiple different address spaces, the source is invalid.
6344       // Carry on using the first addr space for the qualifiers of 'this'.
6345       // The diagnostic will be given later while creating the function
6346       // prototype for the method.
6347       if (getLangOpts().OpenCLCPlusPlus) {
6348         for (ParsedAttr &attr : DS.getAttributes()) {
6349           LangAS ASIdx = attr.asOpenCLLangAS();
6350           if (ASIdx != LangAS::Default) {
6351             Q.addAddressSpace(ASIdx);
6352             break;
6353           }
6354         }
6355       }
6356 
6357       Sema::CXXThisScopeRAII ThisScope(
6358           Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), Q,
6359           IsCXX11MemberFunction);
6360 
6361       // Parse exception-specification[opt].
6362       bool Delayed = D.isFirstDeclarationOfMember() &&
6363                      D.isFunctionDeclaratorAFunctionDeclaration();
6364       if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
6365           GetLookAheadToken(0).is(tok::kw_noexcept) &&
6366           GetLookAheadToken(1).is(tok::l_paren) &&
6367           GetLookAheadToken(2).is(tok::kw_noexcept) &&
6368           GetLookAheadToken(3).is(tok::l_paren) &&
6369           GetLookAheadToken(4).is(tok::identifier) &&
6370           GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
6371         // HACK: We've got an exception-specification
6372         //   noexcept(noexcept(swap(...)))
6373         // or
6374         //   noexcept(noexcept(swap(...)) && noexcept(swap(...)))
6375         // on a 'swap' member function. This is a libstdc++ bug; the lookup
6376         // for 'swap' will only find the function we're currently declaring,
6377         // whereas it expects to find a non-member swap through ADL. Turn off
6378         // delayed parsing to give it a chance to find what it expects.
6379         Delayed = false;
6380       }
6381       ESpecType = tryParseExceptionSpecification(Delayed,
6382                                                  ESpecRange,
6383                                                  DynamicExceptions,
6384                                                  DynamicExceptionRanges,
6385                                                  NoexceptExpr,
6386                                                  ExceptionSpecTokens);
6387       if (ESpecType != EST_None)
6388         EndLoc = ESpecRange.getEnd();
6389 
6390       // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
6391       // after the exception-specification.
6392       MaybeParseCXX11Attributes(FnAttrs);
6393 
6394       // Parse trailing-return-type[opt].
6395       LocalEndLoc = EndLoc;
6396       if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
6397         Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
6398         if (D.getDeclSpec().getTypeSpecType() == TST_auto)
6399           StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
6400         LocalEndLoc = Tok.getLocation();
6401         SourceRange Range;
6402         TrailingReturnType =
6403             ParseTrailingReturnType(Range, D.mayBeFollowedByCXXDirectInit());
6404         EndLoc = Range.getEnd();
6405       }
6406     } else if (standardAttributesAllowed()) {
6407       MaybeParseCXX11Attributes(FnAttrs);
6408     }
6409   }
6410 
6411   // Collect non-parameter declarations from the prototype if this is a function
6412   // declaration. They will be moved into the scope of the function. Only do
6413   // this in C and not C++, where the decls will continue to live in the
6414   // surrounding context.
6415   SmallVector<NamedDecl *, 0> DeclsInPrototype;
6416   if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
6417       !getLangOpts().CPlusPlus) {
6418     for (Decl *D : getCurScope()->decls()) {
6419       NamedDecl *ND = dyn_cast<NamedDecl>(D);
6420       if (!ND || isa<ParmVarDecl>(ND))
6421         continue;
6422       DeclsInPrototype.push_back(ND);
6423     }
6424   }
6425 
6426   // Remember that we parsed a function type, and remember the attributes.
6427   D.AddTypeInfo(DeclaratorChunk::getFunction(
6428                     HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(),
6429                     ParamInfo.size(), EllipsisLoc, RParenLoc,
6430                     RefQualifierIsLValueRef, RefQualifierLoc,
6431                     /*MutableLoc=*/SourceLocation(),
6432                     ESpecType, ESpecRange, DynamicExceptions.data(),
6433                     DynamicExceptionRanges.data(), DynamicExceptions.size(),
6434                     NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
6435                     ExceptionSpecTokens, DeclsInPrototype, StartLoc,
6436                     LocalEndLoc, D, TrailingReturnType, &DS),
6437                 std::move(FnAttrs), EndLoc);
6438 }
6439 
6440 /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
6441 /// true if a ref-qualifier is found.
6442 bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
6443                                SourceLocation &RefQualifierLoc) {
6444   if (Tok.isOneOf(tok::amp, tok::ampamp)) {
6445     Diag(Tok, getLangOpts().CPlusPlus11 ?
6446          diag::warn_cxx98_compat_ref_qualifier :
6447          diag::ext_ref_qualifier);
6448 
6449     RefQualifierIsLValueRef = Tok.is(tok::amp);
6450     RefQualifierLoc = ConsumeToken();
6451     return true;
6452   }
6453   return false;
6454 }
6455 
6456 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
6457 /// identifier list form for a K&R-style function:  void foo(a,b,c)
6458 ///
6459 /// Note that identifier-lists are only allowed for normal declarators, not for
6460 /// abstract-declarators.
6461 bool Parser::isFunctionDeclaratorIdentifierList() {
6462   return !getLangOpts().CPlusPlus
6463          && Tok.is(tok::identifier)
6464          && !TryAltiVecVectorToken()
6465          // K&R identifier lists can't have typedefs as identifiers, per C99
6466          // 6.7.5.3p11.
6467          && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
6468          // Identifier lists follow a really simple grammar: the identifiers can
6469          // be followed *only* by a ", identifier" or ")".  However, K&R
6470          // identifier lists are really rare in the brave new modern world, and
6471          // it is very common for someone to typo a type in a non-K&R style
6472          // list.  If we are presented with something like: "void foo(intptr x,
6473          // float y)", we don't want to start parsing the function declarator as
6474          // though it is a K&R style declarator just because intptr is an
6475          // invalid type.
6476          //
6477          // To handle this, we check to see if the token after the first
6478          // identifier is a "," or ")".  Only then do we parse it as an
6479          // identifier list.
6480          && (!Tok.is(tok::eof) &&
6481              (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
6482 }
6483 
6484 /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
6485 /// we found a K&R-style identifier list instead of a typed parameter list.
6486 ///
6487 /// After returning, ParamInfo will hold the parsed parameters.
6488 ///
6489 ///       identifier-list: [C99 6.7.5]
6490 ///         identifier
6491 ///         identifier-list ',' identifier
6492 ///
6493 void Parser::ParseFunctionDeclaratorIdentifierList(
6494        Declarator &D,
6495        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
6496   // If there was no identifier specified for the declarator, either we are in
6497   // an abstract-declarator, or we are in a parameter declarator which was found
6498   // to be abstract.  In abstract-declarators, identifier lists are not valid:
6499   // diagnose this.
6500   if (!D.getIdentifier())
6501     Diag(Tok, diag::ext_ident_list_in_param);
6502 
6503   // Maintain an efficient lookup of params we have seen so far.
6504   llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
6505 
6506   do {
6507     // If this isn't an identifier, report the error and skip until ')'.
6508     if (Tok.isNot(tok::identifier)) {
6509       Diag(Tok, diag::err_expected) << tok::identifier;
6510       SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
6511       // Forget we parsed anything.
6512       ParamInfo.clear();
6513       return;
6514     }
6515 
6516     IdentifierInfo *ParmII = Tok.getIdentifierInfo();
6517 
6518     // Reject 'typedef int y; int test(x, y)', but continue parsing.
6519     if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
6520       Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
6521 
6522     // Verify that the argument identifier has not already been mentioned.
6523     if (!ParamsSoFar.insert(ParmII).second) {
6524       Diag(Tok, diag::err_param_redefinition) << ParmII;
6525     } else {
6526       // Remember this identifier in ParamInfo.
6527       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6528                                                      Tok.getLocation(),
6529                                                      nullptr));
6530     }
6531 
6532     // Eat the identifier.
6533     ConsumeToken();
6534     // The list continues if we see a comma.
6535   } while (TryConsumeToken(tok::comma));
6536 }
6537 
6538 /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
6539 /// after the opening parenthesis. This function will not parse a K&R-style
6540 /// identifier list.
6541 ///
6542 /// D is the declarator being parsed.  If FirstArgAttrs is non-null, then the
6543 /// caller parsed those arguments immediately after the open paren - they should
6544 /// be considered to be part of the first parameter.
6545 ///
6546 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
6547 /// be the location of the ellipsis, if any was parsed.
6548 ///
6549 ///       parameter-type-list: [C99 6.7.5]
6550 ///         parameter-list
6551 ///         parameter-list ',' '...'
6552 /// [C++]   parameter-list '...'
6553 ///
6554 ///       parameter-list: [C99 6.7.5]
6555 ///         parameter-declaration
6556 ///         parameter-list ',' parameter-declaration
6557 ///
6558 ///       parameter-declaration: [C99 6.7.5]
6559 ///         declaration-specifiers declarator
6560 /// [C++]   declaration-specifiers declarator '=' assignment-expression
6561 /// [C++11]                                       initializer-clause
6562 /// [GNU]   declaration-specifiers declarator attributes
6563 ///         declaration-specifiers abstract-declarator[opt]
6564 /// [C++]   declaration-specifiers abstract-declarator[opt]
6565 ///           '=' assignment-expression
6566 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
6567 /// [C++11] attribute-specifier-seq parameter-declaration
6568 ///
6569 void Parser::ParseParameterDeclarationClause(
6570        Declarator &D,
6571        ParsedAttributes &FirstArgAttrs,
6572        SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
6573        SourceLocation &EllipsisLoc) {
6574 
6575   // Avoid exceeding the maximum function scope depth.
6576   // See https://bugs.llvm.org/show_bug.cgi?id=19607
6577   // Note Sema::ActOnParamDeclarator calls ParmVarDecl::setScopeInfo with
6578   // getFunctionPrototypeDepth() - 1.
6579   if (getCurScope()->getFunctionPrototypeDepth() - 1 >
6580       ParmVarDecl::getMaxFunctionScopeDepth()) {
6581     Diag(Tok.getLocation(), diag::err_function_scope_depth_exceeded)
6582         << ParmVarDecl::getMaxFunctionScopeDepth();
6583     cutOffParsing();
6584     return;
6585   }
6586 
6587   do {
6588     // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
6589     // before deciding this was a parameter-declaration-clause.
6590     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
6591       break;
6592 
6593     // Parse the declaration-specifiers.
6594     // Just use the ParsingDeclaration "scope" of the declarator.
6595     DeclSpec DS(AttrFactory);
6596 
6597     // Parse any C++11 attributes.
6598     MaybeParseCXX11Attributes(DS.getAttributes());
6599 
6600     // Skip any Microsoft attributes before a param.
6601     MaybeParseMicrosoftAttributes(DS.getAttributes());
6602 
6603     SourceLocation DSStart = Tok.getLocation();
6604 
6605     // If the caller parsed attributes for the first argument, add them now.
6606     // Take them so that we only apply the attributes to the first parameter.
6607     // FIXME: If we can leave the attributes in the token stream somehow, we can
6608     // get rid of a parameter (FirstArgAttrs) and this statement. It might be
6609     // too much hassle.
6610     DS.takeAttributesFrom(FirstArgAttrs);
6611 
6612     ParseDeclarationSpecifiers(DS);
6613 
6614 
6615     // Parse the declarator.  This is "PrototypeContext" or
6616     // "LambdaExprParameterContext", because we must accept either
6617     // 'declarator' or 'abstract-declarator' here.
6618     Declarator ParmDeclarator(
6619         DS, D.getContext() == DeclaratorContext::LambdaExprContext
6620                 ? DeclaratorContext::LambdaExprParameterContext
6621                 : DeclaratorContext::PrototypeContext);
6622     ParseDeclarator(ParmDeclarator);
6623 
6624     // Parse GNU attributes, if present.
6625     MaybeParseGNUAttributes(ParmDeclarator);
6626 
6627     // Remember this parsed parameter in ParamInfo.
6628     IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
6629 
6630     // DefArgToks is used when the parsing of default arguments needs
6631     // to be delayed.
6632     std::unique_ptr<CachedTokens> DefArgToks;
6633 
6634     // If no parameter was specified, verify that *something* was specified,
6635     // otherwise we have a missing type and identifier.
6636     if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
6637         ParmDeclarator.getNumTypeObjects() == 0) {
6638       // Completely missing, emit error.
6639       Diag(DSStart, diag::err_missing_param);
6640     } else {
6641       // Otherwise, we have something.  Add it and let semantic analysis try
6642       // to grok it and add the result to the ParamInfo we are building.
6643 
6644       // Last chance to recover from a misplaced ellipsis in an attempted
6645       // parameter pack declaration.
6646       if (Tok.is(tok::ellipsis) &&
6647           (NextToken().isNot(tok::r_paren) ||
6648            (!ParmDeclarator.getEllipsisLoc().isValid() &&
6649             !Actions.isUnexpandedParameterPackPermitted())) &&
6650           Actions.containsUnexpandedParameterPacks(ParmDeclarator))
6651         DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
6652 
6653       // Inform the actions module about the parameter declarator, so it gets
6654       // added to the current scope.
6655       Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
6656       // Parse the default argument, if any. We parse the default
6657       // arguments in all dialects; the semantic analysis in
6658       // ActOnParamDefaultArgument will reject the default argument in
6659       // C.
6660       if (Tok.is(tok::equal)) {
6661         SourceLocation EqualLoc = Tok.getLocation();
6662 
6663         // Parse the default argument
6664         if (D.getContext() == DeclaratorContext::MemberContext) {
6665           // If we're inside a class definition, cache the tokens
6666           // corresponding to the default argument. We'll actually parse
6667           // them when we see the end of the class definition.
6668           DefArgToks.reset(new CachedTokens);
6669 
6670           SourceLocation ArgStartLoc = NextToken().getLocation();
6671           if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
6672             DefArgToks.reset();
6673             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6674           } else {
6675             Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
6676                                                       ArgStartLoc);
6677           }
6678         } else {
6679           // Consume the '='.
6680           ConsumeToken();
6681 
6682           // The argument isn't actually potentially evaluated unless it is
6683           // used.
6684           EnterExpressionEvaluationContext Eval(
6685               Actions,
6686               Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
6687               Param);
6688 
6689           ExprResult DefArgResult;
6690           if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
6691             Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
6692             DefArgResult = ParseBraceInitializer();
6693           } else
6694             DefArgResult = ParseAssignmentExpression();
6695           DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
6696           if (DefArgResult.isInvalid()) {
6697             Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
6698             SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
6699           } else {
6700             // Inform the actions module about the default argument
6701             Actions.ActOnParamDefaultArgument(Param, EqualLoc,
6702                                               DefArgResult.get());
6703           }
6704         }
6705       }
6706 
6707       ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
6708                                           ParmDeclarator.getIdentifierLoc(),
6709                                           Param, std::move(DefArgToks)));
6710     }
6711 
6712     if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
6713       if (!getLangOpts().CPlusPlus) {
6714         // We have ellipsis without a preceding ',', which is ill-formed
6715         // in C. Complain and provide the fix.
6716         Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
6717             << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6718       } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
6719                  Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
6720         // It looks like this was supposed to be a parameter pack. Warn and
6721         // point out where the ellipsis should have gone.
6722         SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
6723         Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
6724           << ParmEllipsis.isValid() << ParmEllipsis;
6725         if (ParmEllipsis.isValid()) {
6726           Diag(ParmEllipsis,
6727                diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
6728         } else {
6729           Diag(ParmDeclarator.getIdentifierLoc(),
6730                diag::note_misplaced_ellipsis_vararg_add_ellipsis)
6731             << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
6732                                           "...")
6733             << !ParmDeclarator.hasName();
6734         }
6735         Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
6736           << FixItHint::CreateInsertion(EllipsisLoc, ", ");
6737       }
6738 
6739       // We can't have any more parameters after an ellipsis.
6740       break;
6741     }
6742 
6743     // If the next token is a comma, consume it and keep reading arguments.
6744   } while (TryConsumeToken(tok::comma));
6745 }
6746 
6747 /// [C90]   direct-declarator '[' constant-expression[opt] ']'
6748 /// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
6749 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
6750 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
6751 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
6752 /// [C++11] direct-declarator '[' constant-expression[opt] ']'
6753 ///                           attribute-specifier-seq[opt]
6754 void Parser::ParseBracketDeclarator(Declarator &D) {
6755   if (CheckProhibitedCXX11Attribute())
6756     return;
6757 
6758   BalancedDelimiterTracker T(*this, tok::l_square);
6759   T.consumeOpen();
6760 
6761   // C array syntax has many features, but by-far the most common is [] and [4].
6762   // This code does a fast path to handle some of the most obvious cases.
6763   if (Tok.getKind() == tok::r_square) {
6764     T.consumeClose();
6765     ParsedAttributes attrs(AttrFactory);
6766     MaybeParseCXX11Attributes(attrs);
6767 
6768     // Remember that we parsed the empty array type.
6769     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
6770                                             T.getOpenLocation(),
6771                                             T.getCloseLocation()),
6772                   std::move(attrs), T.getCloseLocation());
6773     return;
6774   } else if (Tok.getKind() == tok::numeric_constant &&
6775              GetLookAheadToken(1).is(tok::r_square)) {
6776     // [4] is very common.  Parse the numeric constant expression.
6777     ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
6778     ConsumeToken();
6779 
6780     T.consumeClose();
6781     ParsedAttributes attrs(AttrFactory);
6782     MaybeParseCXX11Attributes(attrs);
6783 
6784     // Remember that we parsed a array type, and remember its features.
6785     D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(),
6786                                             T.getOpenLocation(),
6787                                             T.getCloseLocation()),
6788                   std::move(attrs), T.getCloseLocation());
6789     return;
6790   } else if (Tok.getKind() == tok::code_completion) {
6791     Actions.CodeCompleteBracketDeclarator(getCurScope());
6792     return cutOffParsing();
6793   }
6794 
6795   // If valid, this location is the position where we read the 'static' keyword.
6796   SourceLocation StaticLoc;
6797   TryConsumeToken(tok::kw_static, StaticLoc);
6798 
6799   // If there is a type-qualifier-list, read it now.
6800   // Type qualifiers in an array subscript are a C99 feature.
6801   DeclSpec DS(AttrFactory);
6802   ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
6803 
6804   // If we haven't already read 'static', check to see if there is one after the
6805   // type-qualifier-list.
6806   if (!StaticLoc.isValid())
6807     TryConsumeToken(tok::kw_static, StaticLoc);
6808 
6809   // Handle "direct-declarator [ type-qual-list[opt] * ]".
6810   bool isStar = false;
6811   ExprResult NumElements;
6812 
6813   // Handle the case where we have '[*]' as the array size.  However, a leading
6814   // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
6815   // the token after the star is a ']'.  Since stars in arrays are
6816   // infrequent, use of lookahead is not costly here.
6817   if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
6818     ConsumeToken();  // Eat the '*'.
6819 
6820     if (StaticLoc.isValid()) {
6821       Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
6822       StaticLoc = SourceLocation();  // Drop the static.
6823     }
6824     isStar = true;
6825   } else if (Tok.isNot(tok::r_square)) {
6826     // Note, in C89, this production uses the constant-expr production instead
6827     // of assignment-expr.  The only difference is that assignment-expr allows
6828     // things like '=' and '*='.  Sema rejects these in C89 mode because they
6829     // are not i-c-e's, so we don't need to distinguish between the two here.
6830 
6831     // Parse the constant-expression or assignment-expression now (depending
6832     // on dialect).
6833     if (getLangOpts().CPlusPlus) {
6834       NumElements = ParseConstantExpression();
6835     } else {
6836       EnterExpressionEvaluationContext Unevaluated(
6837           Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6838       NumElements =
6839           Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
6840     }
6841   } else {
6842     if (StaticLoc.isValid()) {
6843       Diag(StaticLoc, diag::err_unspecified_size_with_static);
6844       StaticLoc = SourceLocation();  // Drop the static.
6845     }
6846   }
6847 
6848   // If there was an error parsing the assignment-expression, recover.
6849   if (NumElements.isInvalid()) {
6850     D.setInvalidType(true);
6851     // If the expression was invalid, skip it.
6852     SkipUntil(tok::r_square, StopAtSemi);
6853     return;
6854   }
6855 
6856   T.consumeClose();
6857 
6858   MaybeParseCXX11Attributes(DS.getAttributes());
6859 
6860   // Remember that we parsed a array type, and remember its features.
6861   D.AddTypeInfo(
6862       DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(),
6863                                 isStar, NumElements.get(), T.getOpenLocation(),
6864                                 T.getCloseLocation()),
6865       std::move(DS.getAttributes()), T.getCloseLocation());
6866 }
6867 
6868 /// Diagnose brackets before an identifier.
6869 void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
6870   assert(Tok.is(tok::l_square) && "Missing opening bracket");
6871   assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
6872 
6873   SourceLocation StartBracketLoc = Tok.getLocation();
6874   Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
6875 
6876   while (Tok.is(tok::l_square)) {
6877     ParseBracketDeclarator(TempDeclarator);
6878   }
6879 
6880   // Stuff the location of the start of the brackets into the Declarator.
6881   // The diagnostics from ParseDirectDeclarator will make more sense if
6882   // they use this location instead.
6883   if (Tok.is(tok::semi))
6884     D.getName().EndLocation = StartBracketLoc;
6885 
6886   SourceLocation SuggestParenLoc = Tok.getLocation();
6887 
6888   // Now that the brackets are removed, try parsing the declarator again.
6889   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
6890 
6891   // Something went wrong parsing the brackets, in which case,
6892   // ParseBracketDeclarator has emitted an error, and we don't need to emit
6893   // one here.
6894   if (TempDeclarator.getNumTypeObjects() == 0)
6895     return;
6896 
6897   // Determine if parens will need to be suggested in the diagnostic.
6898   bool NeedParens = false;
6899   if (D.getNumTypeObjects() != 0) {
6900     switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
6901     case DeclaratorChunk::Pointer:
6902     case DeclaratorChunk::Reference:
6903     case DeclaratorChunk::BlockPointer:
6904     case DeclaratorChunk::MemberPointer:
6905     case DeclaratorChunk::Pipe:
6906       NeedParens = true;
6907       break;
6908     case DeclaratorChunk::Array:
6909     case DeclaratorChunk::Function:
6910     case DeclaratorChunk::Paren:
6911       break;
6912     }
6913   }
6914 
6915   if (NeedParens) {
6916     // Create a DeclaratorChunk for the inserted parens.
6917     SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6918     D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc),
6919                   SourceLocation());
6920   }
6921 
6922   // Adding back the bracket info to the end of the Declarator.
6923   for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
6924     const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
6925     D.AddTypeInfo(Chunk, SourceLocation());
6926   }
6927 
6928   // The missing identifier would have been diagnosed in ParseDirectDeclarator.
6929   // If parentheses are required, always suggest them.
6930   if (!D.getIdentifier() && !NeedParens)
6931     return;
6932 
6933   SourceLocation EndBracketLoc = TempDeclarator.getEndLoc();
6934 
6935   // Generate the move bracket error message.
6936   SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
6937   SourceLocation EndLoc = PP.getLocForEndOfToken(D.getEndLoc());
6938 
6939   if (NeedParens) {
6940     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6941         << getLangOpts().CPlusPlus
6942         << FixItHint::CreateInsertion(SuggestParenLoc, "(")
6943         << FixItHint::CreateInsertion(EndLoc, ")")
6944         << FixItHint::CreateInsertionFromRange(
6945                EndLoc, CharSourceRange(BracketRange, true))
6946         << FixItHint::CreateRemoval(BracketRange);
6947   } else {
6948     Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
6949         << getLangOpts().CPlusPlus
6950         << FixItHint::CreateInsertionFromRange(
6951                EndLoc, CharSourceRange(BracketRange, true))
6952         << FixItHint::CreateRemoval(BracketRange);
6953   }
6954 }
6955 
6956 /// [GNU]   typeof-specifier:
6957 ///           typeof ( expressions )
6958 ///           typeof ( type-name )
6959 /// [GNU/C++] typeof unary-expression
6960 ///
6961 void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
6962   assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
6963   Token OpTok = Tok;
6964   SourceLocation StartLoc = ConsumeToken();
6965 
6966   const bool hasParens = Tok.is(tok::l_paren);
6967 
6968   EnterExpressionEvaluationContext Unevaluated(
6969       Actions, Sema::ExpressionEvaluationContext::Unevaluated,
6970       Sema::ReuseLambdaContextDecl);
6971 
6972   bool isCastExpr;
6973   ParsedType CastTy;
6974   SourceRange CastRange;
6975   ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
6976       ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
6977   if (hasParens)
6978     DS.setTypeofParensRange(CastRange);
6979 
6980   if (CastRange.getEnd().isInvalid())
6981     // FIXME: Not accurate, the range gets one token more than it should.
6982     DS.SetRangeEnd(Tok.getLocation());
6983   else
6984     DS.SetRangeEnd(CastRange.getEnd());
6985 
6986   if (isCastExpr) {
6987     if (!CastTy) {
6988       DS.SetTypeSpecError();
6989       return;
6990     }
6991 
6992     const char *PrevSpec = nullptr;
6993     unsigned DiagID;
6994     // Check for duplicate type specifiers (e.g. "int typeof(int)").
6995     if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
6996                            DiagID, CastTy,
6997                            Actions.getASTContext().getPrintingPolicy()))
6998       Diag(StartLoc, DiagID) << PrevSpec;
6999     return;
7000   }
7001 
7002   // If we get here, the operand to the typeof was an expression.
7003   if (Operand.isInvalid()) {
7004     DS.SetTypeSpecError();
7005     return;
7006   }
7007 
7008   // We might need to transform the operand if it is potentially evaluated.
7009   Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
7010   if (Operand.isInvalid()) {
7011     DS.SetTypeSpecError();
7012     return;
7013   }
7014 
7015   const char *PrevSpec = nullptr;
7016   unsigned DiagID;
7017   // Check for duplicate type specifiers (e.g. "int typeof(int)").
7018   if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
7019                          DiagID, Operand.get(),
7020                          Actions.getASTContext().getPrintingPolicy()))
7021     Diag(StartLoc, DiagID) << PrevSpec;
7022 }
7023 
7024 /// [C11]   atomic-specifier:
7025 ///           _Atomic ( type-name )
7026 ///
7027 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
7028   assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
7029          "Not an atomic specifier");
7030 
7031   SourceLocation StartLoc = ConsumeToken();
7032   BalancedDelimiterTracker T(*this, tok::l_paren);
7033   if (T.consumeOpen())
7034     return;
7035 
7036   TypeResult Result = ParseTypeName();
7037   if (Result.isInvalid()) {
7038     SkipUntil(tok::r_paren, StopAtSemi);
7039     return;
7040   }
7041 
7042   // Match the ')'
7043   T.consumeClose();
7044 
7045   if (T.getCloseLocation().isInvalid())
7046     return;
7047 
7048   DS.setTypeofParensRange(T.getRange());
7049   DS.SetRangeEnd(T.getCloseLocation());
7050 
7051   const char *PrevSpec = nullptr;
7052   unsigned DiagID;
7053   if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
7054                          DiagID, Result.get(),
7055                          Actions.getASTContext().getPrintingPolicy()))
7056     Diag(StartLoc, DiagID) << PrevSpec;
7057 }
7058 
7059 /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
7060 /// from TryAltiVecVectorToken.
7061 bool Parser::TryAltiVecVectorTokenOutOfLine() {
7062   Token Next = NextToken();
7063   switch (Next.getKind()) {
7064   default: return false;
7065   case tok::kw_short:
7066   case tok::kw_long:
7067   case tok::kw_signed:
7068   case tok::kw_unsigned:
7069   case tok::kw_void:
7070   case tok::kw_char:
7071   case tok::kw_int:
7072   case tok::kw_float:
7073   case tok::kw_double:
7074   case tok::kw_bool:
7075   case tok::kw___bool:
7076   case tok::kw___pixel:
7077     Tok.setKind(tok::kw___vector);
7078     return true;
7079   case tok::identifier:
7080     if (Next.getIdentifierInfo() == Ident_pixel) {
7081       Tok.setKind(tok::kw___vector);
7082       return true;
7083     }
7084     if (Next.getIdentifierInfo() == Ident_bool) {
7085       Tok.setKind(tok::kw___vector);
7086       return true;
7087     }
7088     return false;
7089   }
7090 }
7091 
7092 bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
7093                                       const char *&PrevSpec, unsigned &DiagID,
7094                                       bool &isInvalid) {
7095   const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
7096   if (Tok.getIdentifierInfo() == Ident_vector) {
7097     Token Next = NextToken();
7098     switch (Next.getKind()) {
7099     case tok::kw_short:
7100     case tok::kw_long:
7101     case tok::kw_signed:
7102     case tok::kw_unsigned:
7103     case tok::kw_void:
7104     case tok::kw_char:
7105     case tok::kw_int:
7106     case tok::kw_float:
7107     case tok::kw_double:
7108     case tok::kw_bool:
7109     case tok::kw___bool:
7110     case tok::kw___pixel:
7111       isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
7112       return true;
7113     case tok::identifier:
7114       if (Next.getIdentifierInfo() == Ident_pixel) {
7115         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7116         return true;
7117       }
7118       if (Next.getIdentifierInfo() == Ident_bool) {
7119         isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
7120         return true;
7121       }
7122       break;
7123     default:
7124       break;
7125     }
7126   } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
7127              DS.isTypeAltiVecVector()) {
7128     isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
7129     return true;
7130   } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
7131              DS.isTypeAltiVecVector()) {
7132     isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
7133     return true;
7134   }
7135   return false;
7136 }
7137