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