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