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