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