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