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