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