ParseDecl.cpp revision b53e417ba487f4193ef3b0485b420e0fdae643a2
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 "clang/Parse/ParseDiagnostic.h"
16#include "clang/Basic/OpenCL.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/PrettyDeclStackTrace.h"
20#include "RAIIObjectsForParser.h"
21#include "llvm/ADT/SmallSet.h"
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// C99 6.7: Declarations.
26//===----------------------------------------------------------------------===//
27
28/// ParseTypeName
29///       type-name: [C99 6.7.6]
30///         specifier-qualifier-list abstract-declarator[opt]
31///
32/// Called type-id in C++.
33TypeResult Parser::ParseTypeName(SourceRange *Range,
34                                 Declarator::TheContext Context) {
35  // Parse the common declaration-specifiers piece.
36  DeclSpec DS(AttrFactory);
37  ParseSpecifierQualifierList(DS);
38
39  // Parse the abstract-declarator, if present.
40  Declarator DeclaratorInfo(DS, Context);
41  ParseDeclarator(DeclaratorInfo);
42  if (Range)
43    *Range = DeclaratorInfo.getSourceRange();
44
45  if (DeclaratorInfo.isInvalidType())
46    return true;
47
48  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
49}
50
51/// ParseGNUAttributes - Parse a non-empty attributes list.
52///
53/// [GNU] attributes:
54///         attribute
55///         attributes attribute
56///
57/// [GNU]  attribute:
58///          '__attribute__' '(' '(' attribute-list ')' ')'
59///
60/// [GNU]  attribute-list:
61///          attrib
62///          attribute_list ',' attrib
63///
64/// [GNU]  attrib:
65///          empty
66///          attrib-name
67///          attrib-name '(' identifier ')'
68///          attrib-name '(' identifier ',' nonempty-expr-list ')'
69///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
70///
71/// [GNU]  attrib-name:
72///          identifier
73///          typespec
74///          typequal
75///          storageclass
76///
77/// FIXME: The GCC grammar/code for this construct implies we need two
78/// token lookahead. Comment from gcc: "If they start with an identifier
79/// which is followed by a comma or close parenthesis, then the arguments
80/// start with that identifier; otherwise they are an expression list."
81///
82/// At the moment, I am not doing 2 token lookahead. I am also unaware of
83/// any attributes that don't work (based on my limited testing). Most
84/// attributes are very simple in practice. Until we find a bug, I don't see
85/// a pressing need to implement the 2 token lookahead.
86
87void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
88                                SourceLocation *endLoc) {
89  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
90
91  while (Tok.is(tok::kw___attribute)) {
92    ConsumeToken();
93    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
94                         "attribute")) {
95      SkipUntil(tok::r_paren, true); // skip until ) or ;
96      return;
97    }
98    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
99      SkipUntil(tok::r_paren, true); // skip until ) or ;
100      return;
101    }
102    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
103    while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
104           Tok.is(tok::comma)) {
105
106      if (Tok.is(tok::comma)) {
107        // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
108        ConsumeToken();
109        continue;
110      }
111      // we have an identifier or declaration specifier (const, int, etc.)
112      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
113      SourceLocation AttrNameLoc = ConsumeToken();
114
115      // Availability attributes have their own grammar.
116      if (AttrName->isStr("availability"))
117        ParseAvailabilityAttribute(*AttrName, AttrNameLoc, attrs, endLoc);
118      // check if we have a "parameterized" attribute
119      else if (Tok.is(tok::l_paren)) {
120        ConsumeParen(); // ignore the left paren loc for now
121
122        if (Tok.is(tok::identifier)) {
123          IdentifierInfo *ParmName = Tok.getIdentifierInfo();
124          SourceLocation ParmLoc = ConsumeToken();
125
126          if (Tok.is(tok::r_paren)) {
127            // __attribute__(( mode(byte) ))
128            ConsumeParen(); // ignore the right paren loc for now
129            attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
130                         ParmName, ParmLoc, 0, 0);
131          } else if (Tok.is(tok::comma)) {
132            ConsumeToken();
133            // __attribute__(( format(printf, 1, 2) ))
134            ExprVector ArgExprs(Actions);
135            bool ArgExprsOk = true;
136
137            // now parse the non-empty comma separated list of expressions
138            while (1) {
139              ExprResult ArgExpr(ParseAssignmentExpression());
140              if (ArgExpr.isInvalid()) {
141                ArgExprsOk = false;
142                SkipUntil(tok::r_paren);
143                break;
144              } else {
145                ArgExprs.push_back(ArgExpr.release());
146              }
147              if (Tok.isNot(tok::comma))
148                break;
149              ConsumeToken(); // Eat the comma, move to the next argument
150            }
151            if (ArgExprsOk && Tok.is(tok::r_paren)) {
152              ConsumeParen(); // ignore the right paren loc for now
153              attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
154                           ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
155            }
156          }
157        } else { // not an identifier
158          switch (Tok.getKind()) {
159          case tok::r_paren:
160          // parse a possibly empty comma separated list of expressions
161            // __attribute__(( nonnull() ))
162            ConsumeParen(); // ignore the right paren loc for now
163            attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
164                         0, SourceLocation(), 0, 0);
165            break;
166          case tok::kw_char:
167          case tok::kw_wchar_t:
168          case tok::kw_char16_t:
169          case tok::kw_char32_t:
170          case tok::kw_bool:
171          case tok::kw_short:
172          case tok::kw_int:
173          case tok::kw_long:
174          case tok::kw_signed:
175          case tok::kw_unsigned:
176          case tok::kw_float:
177          case tok::kw_double:
178          case tok::kw_void:
179          case tok::kw_typeof: {
180            AttributeList *attr
181              = attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
182                             0, SourceLocation(), 0, 0);
183            if (attr->getKind() == AttributeList::AT_IBOutletCollection)
184              Diag(Tok, diag::err_iboutletcollection_builtintype);
185            // If it's a builtin type name, eat it and expect a rparen
186            // __attribute__(( vec_type_hint(char) ))
187            ConsumeToken();
188            if (Tok.is(tok::r_paren))
189              ConsumeParen();
190            break;
191          }
192          default:
193            // __attribute__(( aligned(16) ))
194            ExprVector ArgExprs(Actions);
195            bool ArgExprsOk = true;
196
197            // now parse the list of expressions
198            while (1) {
199              ExprResult ArgExpr(ParseAssignmentExpression());
200              if (ArgExpr.isInvalid()) {
201                ArgExprsOk = false;
202                SkipUntil(tok::r_paren);
203                break;
204              } else {
205                ArgExprs.push_back(ArgExpr.release());
206              }
207              if (Tok.isNot(tok::comma))
208                break;
209              ConsumeToken(); // Eat the comma, move to the next argument
210            }
211            // Match the ')'.
212            if (ArgExprsOk && Tok.is(tok::r_paren)) {
213              ConsumeParen(); // ignore the right paren loc for now
214              attrs.addNew(AttrName, AttrNameLoc, 0,
215                           AttrNameLoc, 0, SourceLocation(),
216                           ArgExprs.take(), ArgExprs.size());
217            }
218            break;
219          }
220        }
221      } else {
222        attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
223                     0, SourceLocation(), 0, 0);
224      }
225    }
226    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
227      SkipUntil(tok::r_paren, false);
228    SourceLocation Loc = Tok.getLocation();
229    if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
230      SkipUntil(tok::r_paren, false);
231    }
232    if (endLoc)
233      *endLoc = Loc;
234  }
235}
236
237/// ParseMicrosoftDeclSpec - Parse an __declspec construct
238///
239/// [MS] decl-specifier:
240///             __declspec ( extended-decl-modifier-seq )
241///
242/// [MS] extended-decl-modifier-seq:
243///             extended-decl-modifier[opt]
244///             extended-decl-modifier extended-decl-modifier-seq
245
246void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &attrs) {
247  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
248
249  ConsumeToken();
250  if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
251                       "declspec")) {
252    SkipUntil(tok::r_paren, true); // skip until ) or ;
253    return;
254  }
255  while (Tok.getIdentifierInfo()) {
256    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
257    SourceLocation AttrNameLoc = ConsumeToken();
258    if (Tok.is(tok::l_paren)) {
259      ConsumeParen();
260      // FIXME: This doesn't parse __declspec(property(get=get_func_name))
261      // correctly.
262      ExprResult ArgExpr(ParseAssignmentExpression());
263      if (!ArgExpr.isInvalid()) {
264        Expr *ExprList = ArgExpr.take();
265        attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
266                     SourceLocation(), &ExprList, 1, true);
267      }
268      if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
269        SkipUntil(tok::r_paren, false);
270    } else {
271      attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
272                   0, SourceLocation(), 0, 0, true);
273    }
274  }
275  if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
276    SkipUntil(tok::r_paren, false);
277  return;
278}
279
280void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
281  // Treat these like attributes
282  // FIXME: Allow Sema to distinguish between these and real attributes!
283  while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
284         Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl)   ||
285         Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64)) {
286    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
287    SourceLocation AttrNameLoc = ConsumeToken();
288    if (Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64))
289      // FIXME: Support these properly!
290      continue;
291    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
292                 SourceLocation(), 0, 0, true);
293  }
294}
295
296void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
297  // Treat these like attributes
298  while (Tok.is(tok::kw___pascal)) {
299    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
300    SourceLocation AttrNameLoc = ConsumeToken();
301    attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
302                 SourceLocation(), 0, 0, true);
303  }
304}
305
306void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
307  // Treat these like attributes
308  while (Tok.is(tok::kw___kernel)) {
309    SourceLocation AttrNameLoc = ConsumeToken();
310    attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
311                 AttrNameLoc, 0, AttrNameLoc, 0,
312                 SourceLocation(), 0, 0, false);
313  }
314}
315
316void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
317  SourceLocation Loc = Tok.getLocation();
318  switch(Tok.getKind()) {
319    // OpenCL qualifiers:
320    case tok::kw___private:
321    case tok::kw_private:
322      DS.getAttributes().addNewInteger(
323          Actions.getASTContext(),
324          PP.getIdentifierInfo("address_space"), Loc, 0);
325      break;
326
327    case tok::kw___global:
328      DS.getAttributes().addNewInteger(
329          Actions.getASTContext(),
330          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
331      break;
332
333    case tok::kw___local:
334      DS.getAttributes().addNewInteger(
335          Actions.getASTContext(),
336          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
337      break;
338
339    case tok::kw___constant:
340      DS.getAttributes().addNewInteger(
341          Actions.getASTContext(),
342          PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
343      break;
344
345    case tok::kw___read_only:
346      DS.getAttributes().addNewInteger(
347          Actions.getASTContext(),
348          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
349      break;
350
351    case tok::kw___write_only:
352      DS.getAttributes().addNewInteger(
353          Actions.getASTContext(),
354          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
355      break;
356
357    case tok::kw___read_write:
358      DS.getAttributes().addNewInteger(
359          Actions.getASTContext(),
360          PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
361      break;
362    default: break;
363  }
364}
365
366/// \brief Parse a version number.
367///
368/// version:
369///   simple-integer
370///   simple-integer ',' simple-integer
371///   simple-integer ',' simple-integer ',' simple-integer
372VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
373  Range = Tok.getLocation();
374
375  if (!Tok.is(tok::numeric_constant)) {
376    Diag(Tok, diag::err_expected_version);
377    SkipUntil(tok::comma, tok::r_paren, true, true, true);
378    return VersionTuple();
379  }
380
381  // Parse the major (and possibly minor and subminor) versions, which
382  // are stored in the numeric constant. We utilize a quirk of the
383  // lexer, which is that it handles something like 1.2.3 as a single
384  // numeric constant, rather than two separate tokens.
385  llvm::SmallString<512> Buffer;
386  Buffer.resize(Tok.getLength()+1);
387  const char *ThisTokBegin = &Buffer[0];
388
389  // Get the spelling of the token, which eliminates trigraphs, etc.
390  bool Invalid = false;
391  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
392  if (Invalid)
393    return VersionTuple();
394
395  // Parse the major version.
396  unsigned AfterMajor = 0;
397  unsigned Major = 0;
398  while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
399    Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
400    ++AfterMajor;
401  }
402
403  if (AfterMajor == 0) {
404    Diag(Tok, diag::err_expected_version);
405    SkipUntil(tok::comma, tok::r_paren, true, true, true);
406    return VersionTuple();
407  }
408
409  if (AfterMajor == ActualLength) {
410    ConsumeToken();
411
412    // We only had a single version component.
413    if (Major == 0) {
414      Diag(Tok, diag::err_zero_version);
415      return VersionTuple();
416    }
417
418    return VersionTuple(Major);
419  }
420
421  if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
422    Diag(Tok, diag::err_expected_version);
423    SkipUntil(tok::comma, tok::r_paren, true, true, true);
424    return VersionTuple();
425  }
426
427  // Parse the minor version.
428  unsigned AfterMinor = AfterMajor + 1;
429  unsigned Minor = 0;
430  while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
431    Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
432    ++AfterMinor;
433  }
434
435  if (AfterMinor == ActualLength) {
436    ConsumeToken();
437
438    // We had major.minor.
439    if (Major == 0 && Minor == 0) {
440      Diag(Tok, diag::err_zero_version);
441      return VersionTuple();
442    }
443
444    return VersionTuple(Major, Minor);
445  }
446
447  // If what follows is not a '.', we have a problem.
448  if (ThisTokBegin[AfterMinor] != '.') {
449    Diag(Tok, diag::err_expected_version);
450    SkipUntil(tok::comma, tok::r_paren, true, true, true);
451    return VersionTuple();
452  }
453
454  // Parse the subminor version.
455  unsigned AfterSubminor = AfterMinor + 1;
456  unsigned Subminor = 0;
457  while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
458    Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
459    ++AfterSubminor;
460  }
461
462  if (AfterSubminor != ActualLength) {
463    Diag(Tok, diag::err_expected_version);
464    SkipUntil(tok::comma, tok::r_paren, true, true, true);
465    return VersionTuple();
466  }
467  ConsumeToken();
468  return VersionTuple(Major, Minor, Subminor);
469}
470
471/// \brief Parse the contents of the "availability" attribute.
472///
473/// availability-attribute:
474///   'availability' '(' platform ',' version-arg-list ')'
475///
476/// platform:
477///   identifier
478///
479/// version-arg-list:
480///   version-arg
481///   version-arg ',' version-arg-list
482///
483/// version-arg:
484///   'introduced' '=' version
485///   'deprecated' '=' version
486///   'removed' = version
487///   'unavailable'
488void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
489                                        SourceLocation AvailabilityLoc,
490                                        ParsedAttributes &attrs,
491                                        SourceLocation *endLoc) {
492  SourceLocation PlatformLoc;
493  IdentifierInfo *Platform = 0;
494
495  enum { Introduced, Deprecated, Obsoleted, Unknown };
496  AvailabilityChange Changes[Unknown];
497
498  // Opening '('.
499  SourceLocation LParenLoc;
500  if (!Tok.is(tok::l_paren)) {
501    Diag(Tok, diag::err_expected_lparen);
502    return;
503  }
504  LParenLoc = ConsumeParen();
505
506  // Parse the platform name,
507  if (Tok.isNot(tok::identifier)) {
508    Diag(Tok, diag::err_availability_expected_platform);
509    SkipUntil(tok::r_paren);
510    return;
511  }
512  Platform = Tok.getIdentifierInfo();
513  PlatformLoc = ConsumeToken();
514
515  // Parse the ',' following the platform name.
516  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
517    return;
518
519  // If we haven't grabbed the pointers for the identifiers
520  // "introduced", "deprecated", and "obsoleted", do so now.
521  if (!Ident_introduced) {
522    Ident_introduced = PP.getIdentifierInfo("introduced");
523    Ident_deprecated = PP.getIdentifierInfo("deprecated");
524    Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
525    Ident_unavailable = PP.getIdentifierInfo("unavailable");
526  }
527
528  // Parse the set of introductions/deprecations/removals.
529  SourceLocation UnavailableLoc;
530  do {
531    if (Tok.isNot(tok::identifier)) {
532      Diag(Tok, diag::err_availability_expected_change);
533      SkipUntil(tok::r_paren);
534      return;
535    }
536    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
537    SourceLocation KeywordLoc = ConsumeToken();
538
539    if (Keyword == Ident_unavailable) {
540      if (UnavailableLoc.isValid()) {
541        Diag(KeywordLoc, diag::err_availability_redundant)
542          << Keyword << SourceRange(UnavailableLoc);
543      }
544      UnavailableLoc = KeywordLoc;
545
546      if (Tok.isNot(tok::comma))
547        break;
548
549      ConsumeToken();
550      continue;
551    }
552
553    if (Tok.isNot(tok::equal)) {
554      Diag(Tok, diag::err_expected_equal_after)
555        << Keyword;
556      SkipUntil(tok::r_paren);
557      return;
558    }
559    ConsumeToken();
560
561    SourceRange VersionRange;
562    VersionTuple Version = ParseVersionTuple(VersionRange);
563
564    if (Version.empty()) {
565      SkipUntil(tok::r_paren);
566      return;
567    }
568
569    unsigned Index;
570    if (Keyword == Ident_introduced)
571      Index = Introduced;
572    else if (Keyword == Ident_deprecated)
573      Index = Deprecated;
574    else if (Keyword == Ident_obsoleted)
575      Index = Obsoleted;
576    else
577      Index = Unknown;
578
579    if (Index < Unknown) {
580      if (!Changes[Index].KeywordLoc.isInvalid()) {
581        Diag(KeywordLoc, diag::err_availability_redundant)
582          << Keyword
583          << SourceRange(Changes[Index].KeywordLoc,
584                         Changes[Index].VersionRange.getEnd());
585      }
586
587      Changes[Index].KeywordLoc = KeywordLoc;
588      Changes[Index].Version = Version;
589      Changes[Index].VersionRange = VersionRange;
590    } else {
591      Diag(KeywordLoc, diag::err_availability_unknown_change)
592        << Keyword << VersionRange;
593    }
594
595    if (Tok.isNot(tok::comma))
596      break;
597
598    ConsumeToken();
599  } while (true);
600
601  // Closing ')'.
602  SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
603  if (RParenLoc.isInvalid())
604    return;
605
606  if (endLoc)
607    *endLoc = RParenLoc;
608
609  // The 'unavailable' availability cannot be combined with any other
610  // availability changes. Make sure that hasn't happened.
611  if (UnavailableLoc.isValid()) {
612    bool Complained = false;
613    for (unsigned Index = Introduced; Index != Unknown; ++Index) {
614      if (Changes[Index].KeywordLoc.isValid()) {
615        if (!Complained) {
616          Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
617            << SourceRange(Changes[Index].KeywordLoc,
618                           Changes[Index].VersionRange.getEnd());
619          Complained = true;
620        }
621
622        // Clear out the availability.
623        Changes[Index] = AvailabilityChange();
624      }
625    }
626  }
627
628  // Record this attribute
629  attrs.addNew(&Availability, AvailabilityLoc,
630               0, SourceLocation(),
631               Platform, PlatformLoc,
632               Changes[Introduced],
633               Changes[Deprecated],
634               Changes[Obsoleted],
635               UnavailableLoc, false, false);
636}
637
638void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
639  Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
640    << attrs.Range;
641}
642
643/// ParseDeclaration - Parse a full 'declaration', which consists of
644/// declaration-specifiers, some number of declarators, and a semicolon.
645/// 'Context' should be a Declarator::TheContext value.  This returns the
646/// location of the semicolon in DeclEnd.
647///
648///       declaration: [C99 6.7]
649///         block-declaration ->
650///           simple-declaration
651///           others                   [FIXME]
652/// [C++]   template-declaration
653/// [C++]   namespace-definition
654/// [C++]   using-directive
655/// [C++]   using-declaration
656/// [C++0x] static_assert-declaration
657///         others... [FIXME]
658///
659Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
660                                                unsigned Context,
661                                                SourceLocation &DeclEnd,
662                                          ParsedAttributesWithRange &attrs) {
663  ParenBraceBracketBalancer BalancerRAIIObj(*this);
664
665  Decl *SingleDecl = 0;
666  switch (Tok.getKind()) {
667  case tok::kw_template:
668  case tok::kw_export:
669    ProhibitAttributes(attrs);
670    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
671    break;
672  case tok::kw_inline:
673    // Could be the start of an inline namespace. Allowed as an ext in C++03.
674    if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) {
675      ProhibitAttributes(attrs);
676      SourceLocation InlineLoc = ConsumeToken();
677      SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
678      break;
679    }
680    return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
681                                  true);
682  case tok::kw_namespace:
683    ProhibitAttributes(attrs);
684    SingleDecl = ParseNamespace(Context, DeclEnd);
685    break;
686  case tok::kw_using:
687    SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
688                                                  DeclEnd, attrs);
689    break;
690  case tok::kw_static_assert:
691    ProhibitAttributes(attrs);
692    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
693    break;
694  default:
695    return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
696  }
697
698  // This routine returns a DeclGroup, if the thing we parsed only contains a
699  // single decl, convert it now.
700  return Actions.ConvertDeclToDeclGroup(SingleDecl);
701}
702
703///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
704///         declaration-specifiers init-declarator-list[opt] ';'
705///[C90/C++]init-declarator-list ';'                             [TODO]
706/// [OMP]   threadprivate-directive                              [TODO]
707///
708/// If RequireSemi is false, this does not check for a ';' at the end of the
709/// declaration.  If it is true, it checks for and eats it.
710Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(StmtVector &Stmts,
711                                                      unsigned Context,
712                                                      SourceLocation &DeclEnd,
713                                                      ParsedAttributes &attrs,
714                                                      bool RequireSemi) {
715  // Parse the common declaration-specifiers piece.
716  ParsingDeclSpec DS(*this);
717  DS.takeAttributesFrom(attrs);
718  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
719                             getDeclSpecContextFromDeclaratorContext(Context));
720  StmtResult R = Actions.ActOnVlaStmt(DS);
721  if (R.isUsable())
722    Stmts.push_back(R.release());
723
724  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
725  // declaration-specifiers init-declarator-list[opt] ';'
726  if (Tok.is(tok::semi)) {
727    if (RequireSemi) ConsumeToken();
728    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
729                                                           DS);
730    DS.complete(TheDecl);
731    return Actions.ConvertDeclToDeclGroup(TheDecl);
732  }
733
734  return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd);
735}
736
737/// ParseDeclGroup - Having concluded that this is either a function
738/// definition or a group of object declarations, actually parse the
739/// result.
740Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
741                                              unsigned Context,
742                                              bool AllowFunctionDefinitions,
743                                              SourceLocation *DeclEnd) {
744  // Parse the first declarator.
745  ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
746  ParseDeclarator(D);
747
748  // Bail out if the first declarator didn't seem well-formed.
749  if (!D.hasName() && !D.mayOmitIdentifier()) {
750    // Skip until ; or }.
751    SkipUntil(tok::r_brace, true, true);
752    if (Tok.is(tok::semi))
753      ConsumeToken();
754    return DeclGroupPtrTy();
755  }
756
757  // Check to see if we have a function *definition* which must have a body.
758  if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
759      // Look at the next token to make sure that this isn't a function
760      // declaration.  We have to check this because __attribute__ might be the
761      // start of a function definition in GCC-extended K&R C.
762      !isDeclarationAfterDeclarator()) {
763
764    if (isStartOfFunctionDefinition(D)) {
765      if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
766        Diag(Tok, diag::err_function_declared_typedef);
767
768        // Recover by treating the 'typedef' as spurious.
769        DS.ClearStorageClassSpecs();
770      }
771
772      Decl *TheDecl = ParseFunctionDefinition(D);
773      return Actions.ConvertDeclToDeclGroup(TheDecl);
774    }
775
776    if (isDeclarationSpecifier()) {
777      // If there is an invalid declaration specifier right after the function
778      // prototype, then we must be in a missing semicolon case where this isn't
779      // actually a body.  Just fall through into the code that handles it as a
780      // prototype, and let the top-level code handle the erroneous declspec
781      // where it would otherwise expect a comma or semicolon.
782    } else {
783      Diag(Tok, diag::err_expected_fn_body);
784      SkipUntil(tok::semi);
785      return DeclGroupPtrTy();
786    }
787  }
788
789  llvm::SmallVector<Decl *, 8> DeclsInGroup;
790  Decl *FirstDecl = ParseDeclarationAfterDeclarator(D);
791  D.complete(FirstDecl);
792  if (FirstDecl)
793    DeclsInGroup.push_back(FirstDecl);
794
795  // If we don't have a comma, it is either the end of the list (a ';') or an
796  // error, bail out.
797  while (Tok.is(tok::comma)) {
798    // Consume the comma.
799    ConsumeToken();
800
801    // Parse the next declarator.
802    D.clear();
803
804    // Accept attributes in an init-declarator.  In the first declarator in a
805    // declaration, these would be part of the declspec.  In subsequent
806    // declarators, they become part of the declarator itself, so that they
807    // don't apply to declarators after *this* one.  Examples:
808    //    short __attribute__((common)) var;    -> declspec
809    //    short var __attribute__((common));    -> declarator
810    //    short x, __attribute__((common)) var;    -> declarator
811    MaybeParseGNUAttributes(D);
812
813    ParseDeclarator(D);
814
815    Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
816    D.complete(ThisDecl);
817    if (ThisDecl)
818      DeclsInGroup.push_back(ThisDecl);
819  }
820
821  if (DeclEnd)
822    *DeclEnd = Tok.getLocation();
823
824  if (Context != Declarator::ForContext &&
825      ExpectAndConsume(tok::semi,
826                       Context == Declarator::FileContext
827                         ? diag::err_invalid_token_after_toplevel_declarator
828                         : diag::err_expected_semi_declaration)) {
829    // Okay, there was no semicolon and one was expected.  If we see a
830    // declaration specifier, just assume it was missing and continue parsing.
831    // Otherwise things are very confused and we skip to recover.
832    if (!isDeclarationSpecifier()) {
833      SkipUntil(tok::r_brace, true, true);
834      if (Tok.is(tok::semi))
835        ConsumeToken();
836    }
837  }
838
839  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
840                                         DeclsInGroup.data(),
841                                         DeclsInGroup.size());
842}
843
844/// \brief Parse 'declaration' after parsing 'declaration-specifiers
845/// declarator'. This method parses the remainder of the declaration
846/// (including any attributes or initializer, among other things) and
847/// finalizes the declaration.
848///
849///       init-declarator: [C99 6.7]
850///         declarator
851///         declarator '=' initializer
852/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
853/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
854/// [C++]   declarator initializer[opt]
855///
856/// [C++] initializer:
857/// [C++]   '=' initializer-clause
858/// [C++]   '(' expression-list ')'
859/// [C++0x] '=' 'default'                                                [TODO]
860/// [C++0x] '=' 'delete'
861///
862/// According to the standard grammar, =default and =delete are function
863/// definitions, but that definitely doesn't fit with the parser here.
864///
865Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
866                                     const ParsedTemplateInfo &TemplateInfo) {
867  // If a simple-asm-expr is present, parse it.
868  if (Tok.is(tok::kw_asm)) {
869    SourceLocation Loc;
870    ExprResult AsmLabel(ParseSimpleAsm(&Loc));
871    if (AsmLabel.isInvalid()) {
872      SkipUntil(tok::semi, true, true);
873      return 0;
874    }
875
876    D.setAsmLabel(AsmLabel.release());
877    D.SetRangeEnd(Loc);
878  }
879
880  MaybeParseGNUAttributes(D);
881
882  // Inform the current actions module that we just parsed this declarator.
883  Decl *ThisDecl = 0;
884  switch (TemplateInfo.Kind) {
885  case ParsedTemplateInfo::NonTemplate:
886    ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
887    break;
888
889  case ParsedTemplateInfo::Template:
890  case ParsedTemplateInfo::ExplicitSpecialization:
891    ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
892                             MultiTemplateParamsArg(Actions,
893                                          TemplateInfo.TemplateParams->data(),
894                                          TemplateInfo.TemplateParams->size()),
895                                               D);
896    break;
897
898  case ParsedTemplateInfo::ExplicitInstantiation: {
899    DeclResult ThisRes
900      = Actions.ActOnExplicitInstantiation(getCurScope(),
901                                           TemplateInfo.ExternLoc,
902                                           TemplateInfo.TemplateLoc,
903                                           D);
904    if (ThisRes.isInvalid()) {
905      SkipUntil(tok::semi, true, true);
906      return 0;
907    }
908
909    ThisDecl = ThisRes.get();
910    break;
911    }
912  }
913
914  bool TypeContainsAuto =
915    D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
916
917  // Parse declarator '=' initializer.
918  if (isTokenEqualOrMistypedEqualEqual(
919                               diag::err_invalid_equalequal_after_declarator)) {
920    ConsumeToken();
921    if (Tok.is(tok::kw_delete)) {
922      SourceLocation DelLoc = ConsumeToken();
923
924      if (!getLang().CPlusPlus0x)
925        Diag(DelLoc, diag::warn_deleted_function_accepted_as_extension);
926
927      Actions.SetDeclDeleted(ThisDecl, DelLoc);
928    } else {
929      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
930        EnterScope(0);
931        Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
932      }
933
934      if (Tok.is(tok::code_completion)) {
935        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
936        ConsumeCodeCompletionToken();
937        SkipUntil(tok::comma, true, true);
938        return ThisDecl;
939      }
940
941      ExprResult Init(ParseInitializer());
942
943      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
944        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
945        ExitScope();
946      }
947
948      if (Init.isInvalid()) {
949        SkipUntil(tok::comma, true, true);
950        Actions.ActOnInitializerError(ThisDecl);
951      } else
952        Actions.AddInitializerToDecl(ThisDecl, Init.take(),
953                                     /*DirectInit=*/false, TypeContainsAuto);
954    }
955  } else if (Tok.is(tok::l_paren)) {
956    // Parse C++ direct initializer: '(' expression-list ')'
957    SourceLocation LParenLoc = ConsumeParen();
958    ExprVector Exprs(Actions);
959    CommaLocsTy CommaLocs;
960
961    if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
962      EnterScope(0);
963      Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
964    }
965
966    if (ParseExpressionList(Exprs, CommaLocs)) {
967      SkipUntil(tok::r_paren);
968
969      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
970        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
971        ExitScope();
972      }
973    } else {
974      // Match the ')'.
975      SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
976
977      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
978             "Unexpected number of commas!");
979
980      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
981        Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
982        ExitScope();
983      }
984
985      Actions.AddCXXDirectInitializerToDecl(ThisDecl, LParenLoc,
986                                            move_arg(Exprs),
987                                            RParenLoc,
988                                            TypeContainsAuto);
989    }
990  } else {
991    Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
992  }
993
994  Actions.FinalizeDeclaration(ThisDecl);
995
996  return ThisDecl;
997}
998
999/// ParseSpecifierQualifierList
1000///        specifier-qualifier-list:
1001///          type-specifier specifier-qualifier-list[opt]
1002///          type-qualifier specifier-qualifier-list[opt]
1003/// [GNU]    attributes     specifier-qualifier-list[opt]
1004///
1005void Parser::ParseSpecifierQualifierList(DeclSpec &DS) {
1006  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
1007  /// parse declaration-specifiers and complain about extra stuff.
1008  ParseDeclarationSpecifiers(DS);
1009
1010  // Validate declspec for type-name.
1011  unsigned Specs = DS.getParsedSpecifiers();
1012  if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
1013      !DS.hasAttributes())
1014    Diag(Tok, diag::err_typename_requires_specqual);
1015
1016  // Issue diagnostic and remove storage class if present.
1017  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
1018    if (DS.getStorageClassSpecLoc().isValid())
1019      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
1020    else
1021      Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
1022    DS.ClearStorageClassSpecs();
1023  }
1024
1025  // Issue diagnostic and remove function specfier if present.
1026  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
1027    if (DS.isInlineSpecified())
1028      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
1029    if (DS.isVirtualSpecified())
1030      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
1031    if (DS.isExplicitSpecified())
1032      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
1033    DS.ClearFunctionSpecs();
1034  }
1035}
1036
1037/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
1038/// specified token is valid after the identifier in a declarator which
1039/// immediately follows the declspec.  For example, these things are valid:
1040///
1041///      int x   [             4];         // direct-declarator
1042///      int x   (             int y);     // direct-declarator
1043///  int(int x   )                         // direct-declarator
1044///      int x   ;                         // simple-declaration
1045///      int x   =             17;         // init-declarator-list
1046///      int x   ,             y;          // init-declarator-list
1047///      int x   __asm__       ("foo");    // init-declarator-list
1048///      int x   :             4;          // struct-declarator
1049///      int x   {             5};         // C++'0x unified initializers
1050///
1051/// This is not, because 'x' does not immediately follow the declspec (though
1052/// ')' happens to be valid anyway).
1053///    int (x)
1054///
1055static bool isValidAfterIdentifierInDeclarator(const Token &T) {
1056  return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
1057         T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
1058         T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
1059}
1060
1061
1062/// ParseImplicitInt - This method is called when we have an non-typename
1063/// identifier in a declspec (which normally terminates the decl spec) when
1064/// the declspec has no type specifier.  In this case, the declspec is either
1065/// malformed or is "implicit int" (in K&R and C89).
1066///
1067/// This method handles diagnosing this prettily and returns false if the
1068/// declspec is done being processed.  If it recovers and thinks there may be
1069/// other pieces of declspec after it, it returns true.
1070///
1071bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
1072                              const ParsedTemplateInfo &TemplateInfo,
1073                              AccessSpecifier AS) {
1074  assert(Tok.is(tok::identifier) && "should have identifier");
1075
1076  SourceLocation Loc = Tok.getLocation();
1077  // If we see an identifier that is not a type name, we normally would
1078  // parse it as the identifer being declared.  However, when a typename
1079  // is typo'd or the definition is not included, this will incorrectly
1080  // parse the typename as the identifier name and fall over misparsing
1081  // later parts of the diagnostic.
1082  //
1083  // As such, we try to do some look-ahead in cases where this would
1084  // otherwise be an "implicit-int" case to see if this is invalid.  For
1085  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
1086  // an identifier with implicit int, we'd get a parse error because the
1087  // next token is obviously invalid for a type.  Parse these as a case
1088  // with an invalid type specifier.
1089  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
1090
1091  // Since we know that this either implicit int (which is rare) or an
1092  // error, we'd do lookahead to try to do better recovery.
1093  if (isValidAfterIdentifierInDeclarator(NextToken())) {
1094    // If this token is valid for implicit int, e.g. "static x = 4", then
1095    // we just avoid eating the identifier, so it will be parsed as the
1096    // identifier in the declarator.
1097    return false;
1098  }
1099
1100  // Otherwise, if we don't consume this token, we are going to emit an
1101  // error anyway.  Try to recover from various common problems.  Check
1102  // to see if this was a reference to a tag name without a tag specified.
1103  // This is a common problem in C (saying 'foo' instead of 'struct foo').
1104  //
1105  // C++ doesn't need this, and isTagName doesn't take SS.
1106  if (SS == 0) {
1107    const char *TagName = 0;
1108    tok::TokenKind TagKind = tok::unknown;
1109
1110    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
1111      default: break;
1112      case DeclSpec::TST_enum:  TagName="enum"  ;TagKind=tok::kw_enum  ;break;
1113      case DeclSpec::TST_union: TagName="union" ;TagKind=tok::kw_union ;break;
1114      case DeclSpec::TST_struct:TagName="struct";TagKind=tok::kw_struct;break;
1115      case DeclSpec::TST_class: TagName="class" ;TagKind=tok::kw_class ;break;
1116    }
1117
1118    if (TagName) {
1119      Diag(Loc, diag::err_use_of_tag_name_without_tag)
1120        << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
1121        << FixItHint::CreateInsertion(Tok.getLocation(),TagName);
1122
1123      // Parse this as a tag as if the missing tag were present.
1124      if (TagKind == tok::kw_enum)
1125        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1126      else
1127        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
1128      return true;
1129    }
1130  }
1131
1132  // This is almost certainly an invalid type name. Let the action emit a
1133  // diagnostic and attempt to recover.
1134  ParsedType T;
1135  if (Actions.DiagnoseUnknownTypeName(*Tok.getIdentifierInfo(), Loc,
1136                                      getCurScope(), SS, T)) {
1137    // The action emitted a diagnostic, so we don't have to.
1138    if (T) {
1139      // The action has suggested that the type T could be used. Set that as
1140      // the type in the declaration specifiers, consume the would-be type
1141      // name token, and we're done.
1142      const char *PrevSpec;
1143      unsigned DiagID;
1144      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
1145      DS.SetRangeEnd(Tok.getLocation());
1146      ConsumeToken();
1147
1148      // There may be other declaration specifiers after this.
1149      return true;
1150    }
1151
1152    // Fall through; the action had no suggestion for us.
1153  } else {
1154    // The action did not emit a diagnostic, so emit one now.
1155    SourceRange R;
1156    if (SS) R = SS->getRange();
1157    Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
1158  }
1159
1160  // Mark this as an error.
1161  const char *PrevSpec;
1162  unsigned DiagID;
1163  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
1164  DS.SetRangeEnd(Tok.getLocation());
1165  ConsumeToken();
1166
1167  // TODO: Could inject an invalid typedef decl in an enclosing scope to
1168  // avoid rippling error messages on subsequent uses of the same type,
1169  // could be useful if #include was forgotten.
1170  return false;
1171}
1172
1173/// \brief Determine the declaration specifier context from the declarator
1174/// context.
1175///
1176/// \param Context the declarator context, which is one of the
1177/// Declarator::TheContext enumerator values.
1178Parser::DeclSpecContext
1179Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
1180  if (Context == Declarator::MemberContext)
1181    return DSC_class;
1182  if (Context == Declarator::FileContext)
1183    return DSC_top_level;
1184  return DSC_normal;
1185}
1186
1187/// ParseDeclarationSpecifiers
1188///       declaration-specifiers: [C99 6.7]
1189///         storage-class-specifier declaration-specifiers[opt]
1190///         type-specifier declaration-specifiers[opt]
1191/// [C99]   function-specifier declaration-specifiers[opt]
1192/// [GNU]   attributes declaration-specifiers[opt]
1193///
1194///       storage-class-specifier: [C99 6.7.1]
1195///         'typedef'
1196///         'extern'
1197///         'static'
1198///         'auto'
1199///         'register'
1200/// [C++]   'mutable'
1201/// [GNU]   '__thread'
1202///       function-specifier: [C99 6.7.4]
1203/// [C99]   'inline'
1204/// [C++]   'virtual'
1205/// [C++]   'explicit'
1206/// [OpenCL] '__kernel'
1207///       'friend': [C++ dcl.friend]
1208///       'constexpr': [C++0x dcl.constexpr]
1209
1210///
1211void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
1212                                        const ParsedTemplateInfo &TemplateInfo,
1213                                        AccessSpecifier AS,
1214                                        DeclSpecContext DSContext) {
1215  DS.SetRangeStart(Tok.getLocation());
1216  DS.SetRangeEnd(Tok.getLocation());
1217  while (1) {
1218    bool isInvalid = false;
1219    const char *PrevSpec = 0;
1220    unsigned DiagID = 0;
1221
1222    SourceLocation Loc = Tok.getLocation();
1223
1224    switch (Tok.getKind()) {
1225    default:
1226    DoneWithDeclSpec:
1227      // If this is not a declaration specifier token, we're done reading decl
1228      // specifiers.  First verify that DeclSpec's are consistent.
1229      DS.Finish(Diags, PP);
1230      return;
1231
1232    case tok::code_completion: {
1233      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
1234      if (DS.hasTypeSpecifier()) {
1235        bool AllowNonIdentifiers
1236          = (getCurScope()->getFlags() & (Scope::ControlScope |
1237                                          Scope::BlockScope |
1238                                          Scope::TemplateParamScope |
1239                                          Scope::FunctionPrototypeScope |
1240                                          Scope::AtCatchScope)) == 0;
1241        bool AllowNestedNameSpecifiers
1242          = DSContext == DSC_top_level ||
1243            (DSContext == DSC_class && DS.isFriendSpecified());
1244
1245        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
1246                                     AllowNonIdentifiers,
1247                                     AllowNestedNameSpecifiers);
1248        ConsumeCodeCompletionToken();
1249        return;
1250      }
1251
1252      if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
1253        CCC = Sema::PCC_LocalDeclarationSpecifiers;
1254      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
1255        CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
1256                                    : Sema::PCC_Template;
1257      else if (DSContext == DSC_class)
1258        CCC = Sema::PCC_Class;
1259      else if (ObjCImpDecl)
1260        CCC = Sema::PCC_ObjCImplementation;
1261
1262      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
1263      ConsumeCodeCompletionToken();
1264      return;
1265    }
1266
1267    case tok::coloncolon: // ::foo::bar
1268      // C++ scope specifier.  Annotate and loop, or bail out on error.
1269      if (TryAnnotateCXXScopeToken(true)) {
1270        if (!DS.hasTypeSpecifier())
1271          DS.SetTypeSpecError();
1272        goto DoneWithDeclSpec;
1273      }
1274      if (Tok.is(tok::coloncolon)) // ::new or ::delete
1275        goto DoneWithDeclSpec;
1276      continue;
1277
1278    case tok::annot_cxxscope: {
1279      if (DS.hasTypeSpecifier())
1280        goto DoneWithDeclSpec;
1281
1282      CXXScopeSpec SS;
1283      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
1284                                                   Tok.getAnnotationRange(),
1285                                                   SS);
1286
1287      // We are looking for a qualified typename.
1288      Token Next = NextToken();
1289      if (Next.is(tok::annot_template_id) &&
1290          static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
1291            ->Kind == TNK_Type_template) {
1292        // We have a qualified template-id, e.g., N::A<int>
1293
1294        // C++ [class.qual]p2:
1295        //   In a lookup in which the constructor is an acceptable lookup
1296        //   result and the nested-name-specifier nominates a class C:
1297        //
1298        //     - if the name specified after the
1299        //       nested-name-specifier, when looked up in C, is the
1300        //       injected-class-name of C (Clause 9), or
1301        //
1302        //     - if the name specified after the nested-name-specifier
1303        //       is the same as the identifier or the
1304        //       simple-template-id's template-name in the last
1305        //       component of the nested-name-specifier,
1306        //
1307        //   the name is instead considered to name the constructor of
1308        //   class C.
1309        //
1310        // Thus, if the template-name is actually the constructor
1311        // name, then the code is ill-formed; this interpretation is
1312        // reinforced by the NAD status of core issue 635.
1313        TemplateIdAnnotation *TemplateId
1314          = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue());
1315        if ((DSContext == DSC_top_level ||
1316             (DSContext == DSC_class && DS.isFriendSpecified())) &&
1317            TemplateId->Name &&
1318            Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
1319          if (isConstructorDeclarator()) {
1320            // The user meant this to be an out-of-line constructor
1321            // definition, but template arguments are not allowed
1322            // there.  Just allow this as a constructor; we'll
1323            // complain about it later.
1324            goto DoneWithDeclSpec;
1325          }
1326
1327          // The user meant this to name a type, but it actually names
1328          // a constructor with some extraneous template
1329          // arguments. Complain, then parse it as a type as the user
1330          // intended.
1331          Diag(TemplateId->TemplateNameLoc,
1332               diag::err_out_of_line_template_id_names_constructor)
1333            << TemplateId->Name;
1334        }
1335
1336        DS.getTypeSpecScope() = SS;
1337        ConsumeToken(); // The C++ scope.
1338        assert(Tok.is(tok::annot_template_id) &&
1339               "ParseOptionalCXXScopeSpecifier not working");
1340        AnnotateTemplateIdTokenAsType();
1341        continue;
1342      }
1343
1344      if (Next.is(tok::annot_typename)) {
1345        DS.getTypeSpecScope() = SS;
1346        ConsumeToken(); // The C++ scope.
1347        if (Tok.getAnnotationValue()) {
1348          ParsedType T = getTypeAnnotation(Tok);
1349          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1350                                         Tok.getAnnotationEndLoc(),
1351                                         PrevSpec, DiagID, T);
1352        }
1353        else
1354          DS.SetTypeSpecError();
1355        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1356        ConsumeToken(); // The typename
1357      }
1358
1359      if (Next.isNot(tok::identifier))
1360        goto DoneWithDeclSpec;
1361
1362      // If we're in a context where the identifier could be a class name,
1363      // check whether this is a constructor declaration.
1364      if ((DSContext == DSC_top_level ||
1365           (DSContext == DSC_class && DS.isFriendSpecified())) &&
1366          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
1367                                     &SS)) {
1368        if (isConstructorDeclarator())
1369          goto DoneWithDeclSpec;
1370
1371        // As noted in C++ [class.qual]p2 (cited above), when the name
1372        // of the class is qualified in a context where it could name
1373        // a constructor, its a constructor name. However, we've
1374        // looked at the declarator, and the user probably meant this
1375        // to be a type. Complain that it isn't supposed to be treated
1376        // as a type, then proceed to parse it as a type.
1377        Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
1378          << Next.getIdentifierInfo();
1379      }
1380
1381      ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
1382                                               Next.getLocation(),
1383                                               getCurScope(), &SS,
1384                                               false, false, ParsedType(),
1385                                               /*NonTrivialSourceInfo=*/true);
1386
1387      // If the referenced identifier is not a type, then this declspec is
1388      // erroneous: We already checked about that it has no type specifier, and
1389      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
1390      // typename.
1391      if (TypeRep == 0) {
1392        ConsumeToken();   // Eat the scope spec so the identifier is current.
1393        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
1394        goto DoneWithDeclSpec;
1395      }
1396
1397      DS.getTypeSpecScope() = SS;
1398      ConsumeToken(); // The C++ scope.
1399
1400      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1401                                     DiagID, TypeRep);
1402      if (isInvalid)
1403        break;
1404
1405      DS.SetRangeEnd(Tok.getLocation());
1406      ConsumeToken(); // The typename.
1407
1408      continue;
1409    }
1410
1411    case tok::annot_typename: {
1412      if (Tok.getAnnotationValue()) {
1413        ParsedType T = getTypeAnnotation(Tok);
1414        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1415                                       DiagID, T);
1416      } else
1417        DS.SetTypeSpecError();
1418
1419      if (isInvalid)
1420        break;
1421
1422      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1423      ConsumeToken(); // The typename
1424
1425      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1426      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1427      // Objective-C interface.
1428      if (Tok.is(tok::less) && getLang().ObjC1)
1429        ParseObjCProtocolQualifiers(DS);
1430
1431      continue;
1432    }
1433
1434      // typedef-name
1435    case tok::identifier: {
1436      // In C++, check to see if this is a scope specifier like foo::bar::, if
1437      // so handle it as such.  This is important for ctor parsing.
1438      if (getLang().CPlusPlus) {
1439        if (TryAnnotateCXXScopeToken(true)) {
1440          if (!DS.hasTypeSpecifier())
1441            DS.SetTypeSpecError();
1442          goto DoneWithDeclSpec;
1443        }
1444        if (!Tok.is(tok::identifier))
1445          continue;
1446      }
1447
1448      // This identifier can only be a typedef name if we haven't already seen
1449      // a type-specifier.  Without this check we misparse:
1450      //  typedef int X; struct Y { short X; };  as 'short int'.
1451      if (DS.hasTypeSpecifier())
1452        goto DoneWithDeclSpec;
1453
1454      // Check for need to substitute AltiVec keyword tokens.
1455      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1456        break;
1457
1458      // It has to be available as a typedef too!
1459      ParsedType TypeRep =
1460        Actions.getTypeName(*Tok.getIdentifierInfo(),
1461                            Tok.getLocation(), getCurScope());
1462
1463      // If this is not a typedef name, don't parse it as part of the declspec,
1464      // it must be an implicit int or an error.
1465      if (!TypeRep) {
1466        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
1467        goto DoneWithDeclSpec;
1468      }
1469
1470      // If we're in a context where the identifier could be a class name,
1471      // check whether this is a constructor declaration.
1472      if (getLang().CPlusPlus && DSContext == DSC_class &&
1473          Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
1474          isConstructorDeclarator())
1475        goto DoneWithDeclSpec;
1476
1477      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
1478                                     DiagID, TypeRep);
1479      if (isInvalid)
1480        break;
1481
1482      DS.SetRangeEnd(Tok.getLocation());
1483      ConsumeToken(); // The identifier
1484
1485      // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1486      // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1487      // Objective-C interface.
1488      if (Tok.is(tok::less) && getLang().ObjC1)
1489        ParseObjCProtocolQualifiers(DS);
1490
1491      // Need to support trailing type qualifiers (e.g. "id<p> const").
1492      // If a type specifier follows, it will be diagnosed elsewhere.
1493      continue;
1494    }
1495
1496      // type-name
1497    case tok::annot_template_id: {
1498      TemplateIdAnnotation *TemplateId
1499        = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
1500      if (TemplateId->Kind != TNK_Type_template) {
1501        // This template-id does not refer to a type name, so we're
1502        // done with the type-specifiers.
1503        goto DoneWithDeclSpec;
1504      }
1505
1506      // If we're in a context where the template-id could be a
1507      // constructor name or specialization, check whether this is a
1508      // constructor declaration.
1509      if (getLang().CPlusPlus && DSContext == DSC_class &&
1510          Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
1511          isConstructorDeclarator())
1512        goto DoneWithDeclSpec;
1513
1514      // Turn the template-id annotation token into a type annotation
1515      // token, then try again to parse it as a type-specifier.
1516      AnnotateTemplateIdTokenAsType();
1517      continue;
1518    }
1519
1520    // GNU attributes support.
1521    case tok::kw___attribute:
1522      ParseGNUAttributes(DS.getAttributes());
1523      continue;
1524
1525    // Microsoft declspec support.
1526    case tok::kw___declspec:
1527      ParseMicrosoftDeclSpec(DS.getAttributes());
1528      continue;
1529
1530    // Microsoft single token adornments.
1531    case tok::kw___forceinline:
1532      // FIXME: Add handling here!
1533      break;
1534
1535    case tok::kw___ptr64:
1536    case tok::kw___w64:
1537    case tok::kw___cdecl:
1538    case tok::kw___stdcall:
1539    case tok::kw___fastcall:
1540    case tok::kw___thiscall:
1541      ParseMicrosoftTypeAttributes(DS.getAttributes());
1542      continue;
1543
1544    // Borland single token adornments.
1545    case tok::kw___pascal:
1546      ParseBorlandTypeAttributes(DS.getAttributes());
1547      continue;
1548
1549    // OpenCL single token adornments.
1550    case tok::kw___kernel:
1551      ParseOpenCLAttributes(DS.getAttributes());
1552      continue;
1553
1554    // storage-class-specifier
1555    case tok::kw_typedef:
1556      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_typedef, Loc, PrevSpec,
1557                                         DiagID, getLang());
1558      break;
1559    case tok::kw_extern:
1560      if (DS.isThreadSpecified())
1561        Diag(Tok, diag::ext_thread_before) << "extern";
1562      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_extern, Loc, PrevSpec,
1563                                         DiagID, getLang());
1564      break;
1565    case tok::kw___private_extern__:
1566      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_private_extern, Loc,
1567                                         PrevSpec, DiagID, getLang());
1568      break;
1569    case tok::kw_static:
1570      if (DS.isThreadSpecified())
1571        Diag(Tok, diag::ext_thread_before) << "static";
1572      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_static, Loc, PrevSpec,
1573                                         DiagID, getLang());
1574      break;
1575    case tok::kw_auto:
1576      if (getLang().CPlusPlus0x) {
1577        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
1578          isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1579                                           DiagID, getLang());
1580          if (!isInvalid)
1581            Diag(Tok, diag::auto_storage_class)
1582              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
1583        }
1584        else
1585          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
1586                                         DiagID);
1587      }
1588      else
1589        isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_auto, Loc, PrevSpec,
1590                                           DiagID, getLang());
1591      break;
1592    case tok::kw_register:
1593      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_register, Loc, PrevSpec,
1594                                         DiagID, getLang());
1595      break;
1596    case tok::kw_mutable:
1597      isInvalid = DS.SetStorageClassSpec(DeclSpec::SCS_mutable, Loc, PrevSpec,
1598                                         DiagID, getLang());
1599      break;
1600    case tok::kw___thread:
1601      isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
1602      break;
1603
1604    // function-specifier
1605    case tok::kw_inline:
1606      isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
1607      break;
1608    case tok::kw_virtual:
1609      isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
1610      break;
1611    case tok::kw_explicit:
1612      isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
1613      break;
1614
1615    // friend
1616    case tok::kw_friend:
1617      if (DSContext == DSC_class)
1618        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
1619      else {
1620        PrevSpec = ""; // not actually used by the diagnostic
1621        DiagID = diag::err_friend_invalid_in_context;
1622        isInvalid = true;
1623      }
1624      break;
1625
1626    // constexpr
1627    case tok::kw_constexpr:
1628      isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
1629      break;
1630
1631    // type-specifier
1632    case tok::kw_short:
1633      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
1634                                      DiagID);
1635      break;
1636    case tok::kw_long:
1637      if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1638        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1639                                        DiagID);
1640      else
1641        isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1642                                        DiagID);
1643      break;
1644    case tok::kw_signed:
1645      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
1646                                     DiagID);
1647      break;
1648    case tok::kw_unsigned:
1649      isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1650                                     DiagID);
1651      break;
1652    case tok::kw__Complex:
1653      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1654                                        DiagID);
1655      break;
1656    case tok::kw__Imaginary:
1657      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1658                                        DiagID);
1659      break;
1660    case tok::kw_void:
1661      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
1662                                     DiagID);
1663      break;
1664    case tok::kw_char:
1665      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
1666                                     DiagID);
1667      break;
1668    case tok::kw_int:
1669      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
1670                                     DiagID);
1671      break;
1672    case tok::kw_float:
1673      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
1674                                     DiagID);
1675      break;
1676    case tok::kw_double:
1677      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
1678                                     DiagID);
1679      break;
1680    case tok::kw_wchar_t:
1681      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
1682                                     DiagID);
1683      break;
1684    case tok::kw_char16_t:
1685      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
1686                                     DiagID);
1687      break;
1688    case tok::kw_char32_t:
1689      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
1690                                     DiagID);
1691      break;
1692    case tok::kw_bool:
1693    case tok::kw__Bool:
1694      if (Tok.is(tok::kw_bool) &&
1695          DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
1696          DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
1697        PrevSpec = ""; // Not used by the diagnostic.
1698        DiagID = diag::err_bool_redeclaration;
1699        isInvalid = true;
1700      } else {
1701        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
1702                                       DiagID);
1703      }
1704      break;
1705    case tok::kw__Decimal32:
1706      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1707                                     DiagID);
1708      break;
1709    case tok::kw__Decimal64:
1710      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1711                                     DiagID);
1712      break;
1713    case tok::kw__Decimal128:
1714      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1715                                     DiagID);
1716      break;
1717    case tok::kw___vector:
1718      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1719      break;
1720    case tok::kw___pixel:
1721      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1722      break;
1723
1724    // class-specifier:
1725    case tok::kw_class:
1726    case tok::kw_struct:
1727    case tok::kw_union: {
1728      tok::TokenKind Kind = Tok.getKind();
1729      ConsumeToken();
1730      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
1731      continue;
1732    }
1733
1734    // enum-specifier:
1735    case tok::kw_enum:
1736      ConsumeToken();
1737      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
1738      continue;
1739
1740    // cv-qualifier:
1741    case tok::kw_const:
1742      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
1743                                 getLang());
1744      break;
1745    case tok::kw_volatile:
1746      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
1747                                 getLang());
1748      break;
1749    case tok::kw_restrict:
1750      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
1751                                 getLang());
1752      break;
1753
1754    // C++ typename-specifier:
1755    case tok::kw_typename:
1756      if (TryAnnotateTypeOrScopeToken()) {
1757        DS.SetTypeSpecError();
1758        goto DoneWithDeclSpec;
1759      }
1760      if (!Tok.is(tok::kw_typename))
1761        continue;
1762      break;
1763
1764    // GNU typeof support.
1765    case tok::kw_typeof:
1766      ParseTypeofSpecifier(DS);
1767      continue;
1768
1769    case tok::kw_decltype:
1770      ParseDecltypeSpecifier(DS);
1771      continue;
1772
1773    // OpenCL qualifiers:
1774    case tok::kw_private:
1775      if (!getLang().OpenCL)
1776        goto DoneWithDeclSpec;
1777    case tok::kw___private:
1778    case tok::kw___global:
1779    case tok::kw___local:
1780    case tok::kw___constant:
1781    case tok::kw___read_only:
1782    case tok::kw___write_only:
1783    case tok::kw___read_write:
1784      ParseOpenCLQualifiers(DS);
1785      break;
1786
1787    case tok::less:
1788      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
1789      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
1790      // but we support it.
1791      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
1792        goto DoneWithDeclSpec;
1793
1794      if (!ParseObjCProtocolQualifiers(DS))
1795        Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
1796          << FixItHint::CreateInsertion(Loc, "id")
1797          << SourceRange(Loc, DS.getSourceRange().getEnd());
1798
1799      // Need to support trailing type qualifiers (e.g. "id<p> const").
1800      // If a type specifier follows, it will be diagnosed elsewhere.
1801      continue;
1802    }
1803    // If the specifier wasn't legal, issue a diagnostic.
1804    if (isInvalid) {
1805      assert(PrevSpec && "Method did not return previous specifier!");
1806      assert(DiagID);
1807
1808      if (DiagID == diag::ext_duplicate_declspec)
1809        Diag(Tok, DiagID)
1810          << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
1811      else
1812        Diag(Tok, DiagID) << PrevSpec;
1813    }
1814
1815    DS.SetRangeEnd(Tok.getLocation());
1816    ConsumeToken();
1817  }
1818}
1819
1820/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
1821/// primarily follow the C++ grammar with additions for C99 and GNU,
1822/// which together subsume the C grammar. Note that the C++
1823/// type-specifier also includes the C type-qualifier (for const,
1824/// volatile, and C99 restrict). Returns true if a type-specifier was
1825/// found (and parsed), false otherwise.
1826///
1827///       type-specifier: [C++ 7.1.5]
1828///         simple-type-specifier
1829///         class-specifier
1830///         enum-specifier
1831///         elaborated-type-specifier  [TODO]
1832///         cv-qualifier
1833///
1834///       cv-qualifier: [C++ 7.1.5.1]
1835///         'const'
1836///         'volatile'
1837/// [C99]   'restrict'
1838///
1839///       simple-type-specifier: [ C++ 7.1.5.2]
1840///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
1841///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
1842///         'char'
1843///         'wchar_t'
1844///         'bool'
1845///         'short'
1846///         'int'
1847///         'long'
1848///         'signed'
1849///         'unsigned'
1850///         'float'
1851///         'double'
1852///         'void'
1853/// [C99]   '_Bool'
1854/// [C99]   '_Complex'
1855/// [C99]   '_Imaginary'  // Removed in TC2?
1856/// [GNU]   '_Decimal32'
1857/// [GNU]   '_Decimal64'
1858/// [GNU]   '_Decimal128'
1859/// [GNU]   typeof-specifier
1860/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
1861/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
1862/// [C++0x] 'decltype' ( expression )
1863/// [AltiVec] '__vector'
1864bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
1865                                        const char *&PrevSpec,
1866                                        unsigned &DiagID,
1867                                        const ParsedTemplateInfo &TemplateInfo,
1868                                        bool SuppressDeclarations) {
1869  SourceLocation Loc = Tok.getLocation();
1870
1871  switch (Tok.getKind()) {
1872  case tok::identifier:   // foo::bar
1873    // If we already have a type specifier, this identifier is not a type.
1874    if (DS.getTypeSpecType() != DeclSpec::TST_unspecified ||
1875        DS.getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
1876        DS.getTypeSpecSign() != DeclSpec::TSS_unspecified)
1877      return false;
1878    // Check for need to substitute AltiVec keyword tokens.
1879    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
1880      break;
1881    // Fall through.
1882  case tok::kw_typename:  // typename foo::bar
1883    // Annotate typenames and C++ scope specifiers.  If we get one, just
1884    // recurse to handle whatever we get.
1885    if (TryAnnotateTypeOrScopeToken())
1886      return true;
1887    if (Tok.is(tok::identifier))
1888      return false;
1889    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1890                                      TemplateInfo, SuppressDeclarations);
1891  case tok::coloncolon:   // ::foo::bar
1892    if (NextToken().is(tok::kw_new) ||    // ::new
1893        NextToken().is(tok::kw_delete))   // ::delete
1894      return false;
1895
1896    // Annotate typenames and C++ scope specifiers.  If we get one, just
1897    // recurse to handle whatever we get.
1898    if (TryAnnotateTypeOrScopeToken())
1899      return true;
1900    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
1901                                      TemplateInfo, SuppressDeclarations);
1902
1903  // simple-type-specifier:
1904  case tok::annot_typename: {
1905    if (ParsedType T = getTypeAnnotation(Tok)) {
1906      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
1907                                     Tok.getAnnotationEndLoc(), PrevSpec,
1908                                     DiagID, T);
1909    } else
1910      DS.SetTypeSpecError();
1911    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1912    ConsumeToken(); // The typename
1913
1914    // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1915    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1916    // Objective-C interface.  If we don't have Objective-C or a '<', this is
1917    // just a normal reference to a typedef name.
1918    if (Tok.is(tok::less) && getLang().ObjC1)
1919      ParseObjCProtocolQualifiers(DS);
1920
1921    return true;
1922  }
1923
1924  case tok::kw_short:
1925    isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
1926    break;
1927  case tok::kw_long:
1928    if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
1929      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
1930                                      DiagID);
1931    else
1932      isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
1933                                      DiagID);
1934    break;
1935  case tok::kw_signed:
1936    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
1937    break;
1938  case tok::kw_unsigned:
1939    isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
1940                                   DiagID);
1941    break;
1942  case tok::kw__Complex:
1943    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
1944                                      DiagID);
1945    break;
1946  case tok::kw__Imaginary:
1947    isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
1948                                      DiagID);
1949    break;
1950  case tok::kw_void:
1951    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
1952    break;
1953  case tok::kw_char:
1954    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
1955    break;
1956  case tok::kw_int:
1957    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
1958    break;
1959  case tok::kw_float:
1960    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
1961    break;
1962  case tok::kw_double:
1963    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
1964    break;
1965  case tok::kw_wchar_t:
1966    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
1967    break;
1968  case tok::kw_char16_t:
1969    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
1970    break;
1971  case tok::kw_char32_t:
1972    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
1973    break;
1974  case tok::kw_bool:
1975  case tok::kw__Bool:
1976    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
1977    break;
1978  case tok::kw__Decimal32:
1979    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
1980                                   DiagID);
1981    break;
1982  case tok::kw__Decimal64:
1983    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
1984                                   DiagID);
1985    break;
1986  case tok::kw__Decimal128:
1987    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
1988                                   DiagID);
1989    break;
1990  case tok::kw___vector:
1991    isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
1992    break;
1993  case tok::kw___pixel:
1994    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
1995    break;
1996
1997  // class-specifier:
1998  case tok::kw_class:
1999  case tok::kw_struct:
2000  case tok::kw_union: {
2001    tok::TokenKind Kind = Tok.getKind();
2002    ConsumeToken();
2003    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
2004                        SuppressDeclarations);
2005    return true;
2006  }
2007
2008  // enum-specifier:
2009  case tok::kw_enum:
2010    ConsumeToken();
2011    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
2012    return true;
2013
2014  // cv-qualifier:
2015  case tok::kw_const:
2016    isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
2017                               DiagID, getLang());
2018    break;
2019  case tok::kw_volatile:
2020    isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
2021                               DiagID, getLang());
2022    break;
2023  case tok::kw_restrict:
2024    isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
2025                               DiagID, getLang());
2026    break;
2027
2028  // GNU typeof support.
2029  case tok::kw_typeof:
2030    ParseTypeofSpecifier(DS);
2031    return true;
2032
2033  // C++0x decltype support.
2034  case tok::kw_decltype:
2035    ParseDecltypeSpecifier(DS);
2036    return true;
2037
2038  // OpenCL qualifiers:
2039  case tok::kw_private:
2040    if (!getLang().OpenCL)
2041      return false;
2042  case tok::kw___private:
2043  case tok::kw___global:
2044  case tok::kw___local:
2045  case tok::kw___constant:
2046  case tok::kw___read_only:
2047  case tok::kw___write_only:
2048  case tok::kw___read_write:
2049    ParseOpenCLQualifiers(DS);
2050    break;
2051
2052  // C++0x auto support.
2053  case tok::kw_auto:
2054    if (!getLang().CPlusPlus0x)
2055      return false;
2056
2057    isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID);
2058    break;
2059
2060  case tok::kw___ptr64:
2061  case tok::kw___w64:
2062  case tok::kw___cdecl:
2063  case tok::kw___stdcall:
2064  case tok::kw___fastcall:
2065  case tok::kw___thiscall:
2066    ParseMicrosoftTypeAttributes(DS.getAttributes());
2067    return true;
2068
2069  case tok::kw___pascal:
2070    ParseBorlandTypeAttributes(DS.getAttributes());
2071    return true;
2072
2073  default:
2074    // Not a type-specifier; do nothing.
2075    return false;
2076  }
2077
2078  // If the specifier combination wasn't legal, issue a diagnostic.
2079  if (isInvalid) {
2080    assert(PrevSpec && "Method did not return previous specifier!");
2081    // Pick between error or extwarn.
2082    Diag(Tok, DiagID) << PrevSpec;
2083  }
2084  DS.SetRangeEnd(Tok.getLocation());
2085  ConsumeToken(); // whatever we parsed above.
2086  return true;
2087}
2088
2089/// ParseStructDeclaration - Parse a struct declaration without the terminating
2090/// semicolon.
2091///
2092///       struct-declaration:
2093///         specifier-qualifier-list struct-declarator-list
2094/// [GNU]   __extension__ struct-declaration
2095/// [GNU]   specifier-qualifier-list
2096///       struct-declarator-list:
2097///         struct-declarator
2098///         struct-declarator-list ',' struct-declarator
2099/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
2100///       struct-declarator:
2101///         declarator
2102/// [GNU]   declarator attributes[opt]
2103///         declarator[opt] ':' constant-expression
2104/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
2105///
2106void Parser::
2107ParseStructDeclaration(DeclSpec &DS, FieldCallback &Fields) {
2108  if (Tok.is(tok::kw___extension__)) {
2109    // __extension__ silences extension warnings in the subexpression.
2110    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
2111    ConsumeToken();
2112    return ParseStructDeclaration(DS, Fields);
2113  }
2114
2115  // Parse the common specifier-qualifiers-list piece.
2116  ParseSpecifierQualifierList(DS);
2117
2118  // If there are no declarators, this is a free-standing declaration
2119  // specifier. Let the actions module cope with it.
2120  if (Tok.is(tok::semi)) {
2121    Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS);
2122    return;
2123  }
2124
2125  // Read struct-declarators until we find the semicolon.
2126  bool FirstDeclarator = true;
2127  while (1) {
2128    ParsingDeclRAIIObject PD(*this);
2129    FieldDeclarator DeclaratorInfo(DS);
2130
2131    // Attributes are only allowed here on successive declarators.
2132    if (!FirstDeclarator)
2133      MaybeParseGNUAttributes(DeclaratorInfo.D);
2134
2135    /// struct-declarator: declarator
2136    /// struct-declarator: declarator[opt] ':' constant-expression
2137    if (Tok.isNot(tok::colon)) {
2138      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
2139      ColonProtectionRAIIObject X(*this);
2140      ParseDeclarator(DeclaratorInfo.D);
2141    }
2142
2143    if (Tok.is(tok::colon)) {
2144      ConsumeToken();
2145      ExprResult Res(ParseConstantExpression());
2146      if (Res.isInvalid())
2147        SkipUntil(tok::semi, true, true);
2148      else
2149        DeclaratorInfo.BitfieldSize = Res.release();
2150    }
2151
2152    // If attributes exist after the declarator, parse them.
2153    MaybeParseGNUAttributes(DeclaratorInfo.D);
2154
2155    // We're done with this declarator;  invoke the callback.
2156    Decl *D = Fields.invoke(DeclaratorInfo);
2157    PD.complete(D);
2158
2159    // If we don't have a comma, it is either the end of the list (a ';')
2160    // or an error, bail out.
2161    if (Tok.isNot(tok::comma))
2162      return;
2163
2164    // Consume the comma.
2165    ConsumeToken();
2166
2167    FirstDeclarator = false;
2168  }
2169}
2170
2171/// ParseStructUnionBody
2172///       struct-contents:
2173///         struct-declaration-list
2174/// [EXT]   empty
2175/// [GNU]   "struct-declaration-list" without terminatoring ';'
2176///       struct-declaration-list:
2177///         struct-declaration
2178///         struct-declaration-list struct-declaration
2179/// [OBC]   '@' 'defs' '(' class-name ')'
2180///
2181void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
2182                                  unsigned TagType, Decl *TagDecl) {
2183  PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
2184                                      "parsing struct/union body");
2185
2186  SourceLocation LBraceLoc = ConsumeBrace();
2187
2188  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
2189  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
2190
2191  // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
2192  // C++.
2193  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2194    Diag(Tok, diag::ext_empty_struct_union)
2195      << (TagType == TST_union);
2196
2197  llvm::SmallVector<Decl *, 32> FieldDecls;
2198
2199  // While we still have something to read, read the declarations in the struct.
2200  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
2201    // Each iteration of this loop reads one struct-declaration.
2202
2203    // Check for extraneous top-level semicolon.
2204    if (Tok.is(tok::semi)) {
2205      Diag(Tok, diag::ext_extra_struct_semi)
2206        << DeclSpec::getSpecifierName((DeclSpec::TST)TagType)
2207        << FixItHint::CreateRemoval(Tok.getLocation());
2208      ConsumeToken();
2209      continue;
2210    }
2211
2212    // Parse all the comma separated declarators.
2213    DeclSpec DS(AttrFactory);
2214
2215    if (!Tok.is(tok::at)) {
2216      struct CFieldCallback : FieldCallback {
2217        Parser &P;
2218        Decl *TagDecl;
2219        llvm::SmallVectorImpl<Decl *> &FieldDecls;
2220
2221        CFieldCallback(Parser &P, Decl *TagDecl,
2222                       llvm::SmallVectorImpl<Decl *> &FieldDecls) :
2223          P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
2224
2225        virtual Decl *invoke(FieldDeclarator &FD) {
2226          // Install the declarator into the current TagDecl.
2227          Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
2228                              FD.D.getDeclSpec().getSourceRange().getBegin(),
2229                                                 FD.D, FD.BitfieldSize);
2230          FieldDecls.push_back(Field);
2231          return Field;
2232        }
2233      } Callback(*this, TagDecl, FieldDecls);
2234
2235      ParseStructDeclaration(DS, Callback);
2236    } else { // Handle @defs
2237      ConsumeToken();
2238      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
2239        Diag(Tok, diag::err_unexpected_at);
2240        SkipUntil(tok::semi, true);
2241        continue;
2242      }
2243      ConsumeToken();
2244      ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
2245      if (!Tok.is(tok::identifier)) {
2246        Diag(Tok, diag::err_expected_ident);
2247        SkipUntil(tok::semi, true);
2248        continue;
2249      }
2250      llvm::SmallVector<Decl *, 16> Fields;
2251      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
2252                        Tok.getIdentifierInfo(), Fields);
2253      FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
2254      ConsumeToken();
2255      ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
2256    }
2257
2258    if (Tok.is(tok::semi)) {
2259      ConsumeToken();
2260    } else if (Tok.is(tok::r_brace)) {
2261      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
2262      break;
2263    } else {
2264      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
2265      // Skip to end of block or statement to avoid ext-warning on extra ';'.
2266      SkipUntil(tok::r_brace, true, true);
2267      // If we stopped at a ';', eat it.
2268      if (Tok.is(tok::semi)) ConsumeToken();
2269    }
2270  }
2271
2272  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2273
2274  ParsedAttributes attrs(AttrFactory);
2275  // If attributes exist after struct contents, parse them.
2276  MaybeParseGNUAttributes(attrs);
2277
2278  Actions.ActOnFields(getCurScope(),
2279                      RecordLoc, TagDecl, FieldDecls.data(), FieldDecls.size(),
2280                      LBraceLoc, RBraceLoc,
2281                      attrs.getList());
2282  StructScope.Exit();
2283  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc);
2284}
2285
2286/// ParseEnumSpecifier
2287///       enum-specifier: [C99 6.7.2.2]
2288///         'enum' identifier[opt] '{' enumerator-list '}'
2289///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
2290/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
2291///                                                 '}' attributes[opt]
2292///         'enum' identifier
2293/// [GNU]   'enum' attributes[opt] identifier
2294///
2295/// [C++0x] enum-head '{' enumerator-list[opt] '}'
2296/// [C++0x] enum-head '{' enumerator-list ','  '}'
2297///
2298///       enum-head: [C++0x]
2299///         enum-key attributes[opt] identifier[opt] enum-base[opt]
2300///         enum-key attributes[opt] nested-name-specifier identifier enum-base[opt]
2301///
2302///       enum-key: [C++0x]
2303///         'enum'
2304///         'enum' 'class'
2305///         'enum' 'struct'
2306///
2307///       enum-base: [C++0x]
2308///         ':' type-specifier-seq
2309///
2310/// [C++] elaborated-type-specifier:
2311/// [C++]   'enum' '::'[opt] nested-name-specifier[opt] identifier
2312///
2313void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
2314                                const ParsedTemplateInfo &TemplateInfo,
2315                                AccessSpecifier AS) {
2316  // Parse the tag portion of this.
2317  if (Tok.is(tok::code_completion)) {
2318    // Code completion for an enum name.
2319    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
2320    ConsumeCodeCompletionToken();
2321  }
2322
2323  // If attributes exist after tag, parse them.
2324  ParsedAttributes attrs(AttrFactory);
2325  MaybeParseGNUAttributes(attrs);
2326
2327  CXXScopeSpec &SS = DS.getTypeSpecScope();
2328  if (getLang().CPlusPlus) {
2329    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
2330      return;
2331
2332    if (SS.isSet() && Tok.isNot(tok::identifier)) {
2333      Diag(Tok, diag::err_expected_ident);
2334      if (Tok.isNot(tok::l_brace)) {
2335        // Has no name and is not a definition.
2336        // Skip the rest of this declarator, up until the comma or semicolon.
2337        SkipUntil(tok::comma, true);
2338        return;
2339      }
2340    }
2341  }
2342
2343  bool AllowFixedUnderlyingType = getLang().CPlusPlus0x || getLang().Microsoft;
2344  bool IsScopedEnum = false;
2345  bool IsScopedUsingClassTag = false;
2346
2347  if (getLang().CPlusPlus0x &&
2348      (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
2349    IsScopedEnum = true;
2350    IsScopedUsingClassTag = Tok.is(tok::kw_class);
2351    ConsumeToken();
2352  }
2353
2354  // Must have either 'enum name' or 'enum {...}'.
2355  if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
2356      (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
2357    Diag(Tok, diag::err_expected_ident_lbrace);
2358
2359    // Skip the rest of this declarator, up until the comma or semicolon.
2360    SkipUntil(tok::comma, true);
2361    return;
2362  }
2363
2364  // If an identifier is present, consume and remember it.
2365  IdentifierInfo *Name = 0;
2366  SourceLocation NameLoc;
2367  if (Tok.is(tok::identifier)) {
2368    Name = Tok.getIdentifierInfo();
2369    NameLoc = ConsumeToken();
2370  }
2371
2372  if (!Name && IsScopedEnum) {
2373    // C++0x 7.2p2: The optional identifier shall not be omitted in the
2374    // declaration of a scoped enumeration.
2375    Diag(Tok, diag::err_scoped_enum_missing_identifier);
2376    IsScopedEnum = false;
2377    IsScopedUsingClassTag = false;
2378  }
2379
2380  TypeResult BaseType;
2381
2382  // Parse the fixed underlying type.
2383  if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
2384    bool PossibleBitfield = false;
2385    if (getCurScope()->getFlags() & Scope::ClassScope) {
2386      // If we're in class scope, this can either be an enum declaration with
2387      // an underlying type, or a declaration of a bitfield member. We try to
2388      // use a simple disambiguation scheme first to catch the common cases
2389      // (integer literal, sizeof); if it's still ambiguous, we then consider
2390      // anything that's a simple-type-specifier followed by '(' as an
2391      // expression. This suffices because function types are not valid
2392      // underlying types anyway.
2393      TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
2394      // If the next token starts an expression, we know we're parsing a
2395      // bit-field. This is the common case.
2396      if (TPR == TPResult::True())
2397        PossibleBitfield = true;
2398      // If the next token starts a type-specifier-seq, it may be either a
2399      // a fixed underlying type or the start of a function-style cast in C++;
2400      // lookahead one more token to see if it's obvious that we have a
2401      // fixed underlying type.
2402      else if (TPR == TPResult::False() &&
2403               GetLookAheadToken(2).getKind() == tok::semi) {
2404        // Consume the ':'.
2405        ConsumeToken();
2406      } else {
2407        // We have the start of a type-specifier-seq, so we have to perform
2408        // tentative parsing to determine whether we have an expression or a
2409        // type.
2410        TentativeParsingAction TPA(*this);
2411
2412        // Consume the ':'.
2413        ConsumeToken();
2414
2415        if ((getLang().CPlusPlus &&
2416             isCXXDeclarationSpecifier() != TPResult::True()) ||
2417            (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
2418          // We'll parse this as a bitfield later.
2419          PossibleBitfield = true;
2420          TPA.Revert();
2421        } else {
2422          // We have a type-specifier-seq.
2423          TPA.Commit();
2424        }
2425      }
2426    } else {
2427      // Consume the ':'.
2428      ConsumeToken();
2429    }
2430
2431    if (!PossibleBitfield) {
2432      SourceRange Range;
2433      BaseType = ParseTypeName(&Range);
2434
2435      if (!getLang().CPlusPlus0x)
2436        Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
2437          << Range;
2438    }
2439  }
2440
2441  // There are three options here.  If we have 'enum foo;', then this is a
2442  // forward declaration.  If we have 'enum foo {...' then this is a
2443  // definition. Otherwise we have something like 'enum foo xyz', a reference.
2444  //
2445  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
2446  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
2447  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
2448  //
2449  Sema::TagUseKind TUK;
2450  if (Tok.is(tok::l_brace))
2451    TUK = Sema::TUK_Definition;
2452  else if (Tok.is(tok::semi))
2453    TUK = Sema::TUK_Declaration;
2454  else
2455    TUK = Sema::TUK_Reference;
2456
2457  // enums cannot be templates, although they can be referenced from a
2458  // template.
2459  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
2460      TUK != Sema::TUK_Reference) {
2461    Diag(Tok, diag::err_enum_template);
2462
2463    // Skip the rest of this declarator, up until the comma or semicolon.
2464    SkipUntil(tok::comma, true);
2465    return;
2466  }
2467
2468  if (!Name && TUK != Sema::TUK_Definition) {
2469    Diag(Tok, diag::err_enumerator_unnamed_no_def);
2470
2471    // Skip the rest of this declarator, up until the comma or semicolon.
2472    SkipUntil(tok::comma, true);
2473    return;
2474  }
2475
2476  bool Owned = false;
2477  bool IsDependent = false;
2478  const char *PrevSpec = 0;
2479  unsigned DiagID;
2480  Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
2481                                   StartLoc, SS, Name, NameLoc, attrs.getList(),
2482                                   AS,
2483                                   MultiTemplateParamsArg(Actions),
2484                                   Owned, IsDependent, IsScopedEnum,
2485                                   IsScopedUsingClassTag, BaseType);
2486
2487  if (IsDependent) {
2488    // This enum has a dependent nested-name-specifier. Handle it as a
2489    // dependent tag.
2490    if (!Name) {
2491      DS.SetTypeSpecError();
2492      Diag(Tok, diag::err_expected_type_name_after_typename);
2493      return;
2494    }
2495
2496    TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
2497                                                TUK, SS, Name, StartLoc,
2498                                                NameLoc);
2499    if (Type.isInvalid()) {
2500      DS.SetTypeSpecError();
2501      return;
2502    }
2503
2504    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
2505                           NameLoc.isValid() ? NameLoc : StartLoc,
2506                           PrevSpec, DiagID, Type.get()))
2507      Diag(StartLoc, DiagID) << PrevSpec;
2508
2509    return;
2510  }
2511
2512  if (!TagDecl) {
2513    // The action failed to produce an enumeration tag. If this is a
2514    // definition, consume the entire definition.
2515    if (Tok.is(tok::l_brace)) {
2516      ConsumeBrace();
2517      SkipUntil(tok::r_brace);
2518    }
2519
2520    DS.SetTypeSpecError();
2521    return;
2522  }
2523
2524  if (Tok.is(tok::l_brace))
2525    ParseEnumBody(StartLoc, TagDecl);
2526
2527  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
2528                         NameLoc.isValid() ? NameLoc : StartLoc,
2529                         PrevSpec, DiagID, TagDecl, Owned))
2530    Diag(StartLoc, DiagID) << PrevSpec;
2531}
2532
2533/// ParseEnumBody - Parse a {} enclosed enumerator-list.
2534///       enumerator-list:
2535///         enumerator
2536///         enumerator-list ',' enumerator
2537///       enumerator:
2538///         enumeration-constant
2539///         enumeration-constant '=' constant-expression
2540///       enumeration-constant:
2541///         identifier
2542///
2543void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
2544  // Enter the scope of the enum body and start the definition.
2545  ParseScope EnumScope(this, Scope::DeclScope);
2546  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
2547
2548  SourceLocation LBraceLoc = ConsumeBrace();
2549
2550  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
2551  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
2552    Diag(Tok, diag::error_empty_enum);
2553
2554  llvm::SmallVector<Decl *, 32> EnumConstantDecls;
2555
2556  Decl *LastEnumConstDecl = 0;
2557
2558  // Parse the enumerator-list.
2559  while (Tok.is(tok::identifier)) {
2560    IdentifierInfo *Ident = Tok.getIdentifierInfo();
2561    SourceLocation IdentLoc = ConsumeToken();
2562
2563    // If attributes exist after the enumerator, parse them.
2564    ParsedAttributes attrs(AttrFactory);
2565    MaybeParseGNUAttributes(attrs);
2566
2567    SourceLocation EqualLoc;
2568    ExprResult AssignedVal;
2569    if (Tok.is(tok::equal)) {
2570      EqualLoc = ConsumeToken();
2571      AssignedVal = ParseConstantExpression();
2572      if (AssignedVal.isInvalid())
2573        SkipUntil(tok::comma, tok::r_brace, true, true);
2574    }
2575
2576    // Install the enumerator constant into EnumDecl.
2577    Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
2578                                                    LastEnumConstDecl,
2579                                                    IdentLoc, Ident,
2580                                                    attrs.getList(), EqualLoc,
2581                                                    AssignedVal.release());
2582    EnumConstantDecls.push_back(EnumConstDecl);
2583    LastEnumConstDecl = EnumConstDecl;
2584
2585    if (Tok.is(tok::identifier)) {
2586      // We're missing a comma between enumerators.
2587      SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
2588      Diag(Loc, diag::err_enumerator_list_missing_comma)
2589        << FixItHint::CreateInsertion(Loc, ", ");
2590      continue;
2591    }
2592
2593    if (Tok.isNot(tok::comma))
2594      break;
2595    SourceLocation CommaLoc = ConsumeToken();
2596
2597    if (Tok.isNot(tok::identifier) &&
2598        !(getLang().C99 || getLang().CPlusPlus0x))
2599      Diag(CommaLoc, diag::ext_enumerator_list_comma)
2600        << getLang().CPlusPlus
2601        << FixItHint::CreateRemoval(CommaLoc);
2602  }
2603
2604  // Eat the }.
2605  SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc);
2606
2607  // If attributes exist after the identifier list, parse them.
2608  ParsedAttributes attrs(AttrFactory);
2609  MaybeParseGNUAttributes(attrs);
2610
2611  Actions.ActOnEnumBody(StartLoc, LBraceLoc, RBraceLoc, EnumDecl,
2612                        EnumConstantDecls.data(), EnumConstantDecls.size(),
2613                        getCurScope(), attrs.getList());
2614
2615  EnumScope.Exit();
2616  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, RBraceLoc);
2617}
2618
2619/// isTypeSpecifierQualifier - Return true if the current token could be the
2620/// start of a type-qualifier-list.
2621bool Parser::isTypeQualifier() const {
2622  switch (Tok.getKind()) {
2623  default: return false;
2624
2625    // type-qualifier only in OpenCL
2626  case tok::kw_private:
2627    return getLang().OpenCL;
2628
2629    // type-qualifier
2630  case tok::kw_const:
2631  case tok::kw_volatile:
2632  case tok::kw_restrict:
2633  case tok::kw___private:
2634  case tok::kw___local:
2635  case tok::kw___global:
2636  case tok::kw___constant:
2637  case tok::kw___read_only:
2638  case tok::kw___read_write:
2639  case tok::kw___write_only:
2640    return true;
2641  }
2642}
2643
2644/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
2645/// is definitely a type-specifier.  Return false if it isn't part of a type
2646/// specifier or if we're not sure.
2647bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
2648  switch (Tok.getKind()) {
2649  default: return false;
2650    // type-specifiers
2651  case tok::kw_short:
2652  case tok::kw_long:
2653  case tok::kw_signed:
2654  case tok::kw_unsigned:
2655  case tok::kw__Complex:
2656  case tok::kw__Imaginary:
2657  case tok::kw_void:
2658  case tok::kw_char:
2659  case tok::kw_wchar_t:
2660  case tok::kw_char16_t:
2661  case tok::kw_char32_t:
2662  case tok::kw_int:
2663  case tok::kw_float:
2664  case tok::kw_double:
2665  case tok::kw_bool:
2666  case tok::kw__Bool:
2667  case tok::kw__Decimal32:
2668  case tok::kw__Decimal64:
2669  case tok::kw__Decimal128:
2670  case tok::kw___vector:
2671
2672    // struct-or-union-specifier (C99) or class-specifier (C++)
2673  case tok::kw_class:
2674  case tok::kw_struct:
2675  case tok::kw_union:
2676    // enum-specifier
2677  case tok::kw_enum:
2678
2679    // typedef-name
2680  case tok::annot_typename:
2681    return true;
2682  }
2683}
2684
2685/// isTypeSpecifierQualifier - Return true if the current token could be the
2686/// start of a specifier-qualifier-list.
2687bool Parser::isTypeSpecifierQualifier() {
2688  switch (Tok.getKind()) {
2689  default: return false;
2690
2691  case tok::identifier:   // foo::bar
2692    if (TryAltiVecVectorToken())
2693      return true;
2694    // Fall through.
2695  case tok::kw_typename:  // typename T::type
2696    // Annotate typenames and C++ scope specifiers.  If we get one, just
2697    // recurse to handle whatever we get.
2698    if (TryAnnotateTypeOrScopeToken())
2699      return true;
2700    if (Tok.is(tok::identifier))
2701      return false;
2702    return isTypeSpecifierQualifier();
2703
2704  case tok::coloncolon:   // ::foo::bar
2705    if (NextToken().is(tok::kw_new) ||    // ::new
2706        NextToken().is(tok::kw_delete))   // ::delete
2707      return false;
2708
2709    if (TryAnnotateTypeOrScopeToken())
2710      return true;
2711    return isTypeSpecifierQualifier();
2712
2713    // GNU attributes support.
2714  case tok::kw___attribute:
2715    // GNU typeof support.
2716  case tok::kw_typeof:
2717
2718    // type-specifiers
2719  case tok::kw_short:
2720  case tok::kw_long:
2721  case tok::kw_signed:
2722  case tok::kw_unsigned:
2723  case tok::kw__Complex:
2724  case tok::kw__Imaginary:
2725  case tok::kw_void:
2726  case tok::kw_char:
2727  case tok::kw_wchar_t:
2728  case tok::kw_char16_t:
2729  case tok::kw_char32_t:
2730  case tok::kw_int:
2731  case tok::kw_float:
2732  case tok::kw_double:
2733  case tok::kw_bool:
2734  case tok::kw__Bool:
2735  case tok::kw__Decimal32:
2736  case tok::kw__Decimal64:
2737  case tok::kw__Decimal128:
2738  case tok::kw___vector:
2739
2740    // struct-or-union-specifier (C99) or class-specifier (C++)
2741  case tok::kw_class:
2742  case tok::kw_struct:
2743  case tok::kw_union:
2744    // enum-specifier
2745  case tok::kw_enum:
2746
2747    // type-qualifier
2748  case tok::kw_const:
2749  case tok::kw_volatile:
2750  case tok::kw_restrict:
2751
2752    // typedef-name
2753  case tok::annot_typename:
2754    return true;
2755
2756    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2757  case tok::less:
2758    return getLang().ObjC1;
2759
2760  case tok::kw___cdecl:
2761  case tok::kw___stdcall:
2762  case tok::kw___fastcall:
2763  case tok::kw___thiscall:
2764  case tok::kw___w64:
2765  case tok::kw___ptr64:
2766  case tok::kw___pascal:
2767
2768  case tok::kw___private:
2769  case tok::kw___local:
2770  case tok::kw___global:
2771  case tok::kw___constant:
2772  case tok::kw___read_only:
2773  case tok::kw___read_write:
2774  case tok::kw___write_only:
2775
2776    return true;
2777
2778  case tok::kw_private:
2779    return getLang().OpenCL;
2780  }
2781}
2782
2783/// isDeclarationSpecifier() - Return true if the current token is part of a
2784/// declaration specifier.
2785///
2786/// \param DisambiguatingWithExpression True to indicate that the purpose of
2787/// this check is to disambiguate between an expression and a declaration.
2788bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
2789  switch (Tok.getKind()) {
2790  default: return false;
2791
2792  case tok::kw_private:
2793    return getLang().OpenCL;
2794
2795  case tok::identifier:   // foo::bar
2796    // Unfortunate hack to support "Class.factoryMethod" notation.
2797    if (getLang().ObjC1 && NextToken().is(tok::period))
2798      return false;
2799    if (TryAltiVecVectorToken())
2800      return true;
2801    // Fall through.
2802  case tok::kw_typename: // typename T::type
2803    // Annotate typenames and C++ scope specifiers.  If we get one, just
2804    // recurse to handle whatever we get.
2805    if (TryAnnotateTypeOrScopeToken())
2806      return true;
2807    if (Tok.is(tok::identifier))
2808      return false;
2809
2810    // If we're in Objective-C and we have an Objective-C class type followed
2811    // by an identifier and then either ':' or ']', in a place where an
2812    // expression is permitted, then this is probably a class message send
2813    // missing the initial '['. In this case, we won't consider this to be
2814    // the start of a declaration.
2815    if (DisambiguatingWithExpression &&
2816        isStartOfObjCClassMessageMissingOpenBracket())
2817      return false;
2818
2819    return isDeclarationSpecifier();
2820
2821  case tok::coloncolon:   // ::foo::bar
2822    if (NextToken().is(tok::kw_new) ||    // ::new
2823        NextToken().is(tok::kw_delete))   // ::delete
2824      return false;
2825
2826    // Annotate typenames and C++ scope specifiers.  If we get one, just
2827    // recurse to handle whatever we get.
2828    if (TryAnnotateTypeOrScopeToken())
2829      return true;
2830    return isDeclarationSpecifier();
2831
2832    // storage-class-specifier
2833  case tok::kw_typedef:
2834  case tok::kw_extern:
2835  case tok::kw___private_extern__:
2836  case tok::kw_static:
2837  case tok::kw_auto:
2838  case tok::kw_register:
2839  case tok::kw___thread:
2840
2841    // type-specifiers
2842  case tok::kw_short:
2843  case tok::kw_long:
2844  case tok::kw_signed:
2845  case tok::kw_unsigned:
2846  case tok::kw__Complex:
2847  case tok::kw__Imaginary:
2848  case tok::kw_void:
2849  case tok::kw_char:
2850  case tok::kw_wchar_t:
2851  case tok::kw_char16_t:
2852  case tok::kw_char32_t:
2853
2854  case tok::kw_int:
2855  case tok::kw_float:
2856  case tok::kw_double:
2857  case tok::kw_bool:
2858  case tok::kw__Bool:
2859  case tok::kw__Decimal32:
2860  case tok::kw__Decimal64:
2861  case tok::kw__Decimal128:
2862  case tok::kw___vector:
2863
2864    // struct-or-union-specifier (C99) or class-specifier (C++)
2865  case tok::kw_class:
2866  case tok::kw_struct:
2867  case tok::kw_union:
2868    // enum-specifier
2869  case tok::kw_enum:
2870
2871    // type-qualifier
2872  case tok::kw_const:
2873  case tok::kw_volatile:
2874  case tok::kw_restrict:
2875
2876    // function-specifier
2877  case tok::kw_inline:
2878  case tok::kw_virtual:
2879  case tok::kw_explicit:
2880
2881    // typedef-name
2882  case tok::annot_typename:
2883
2884    // GNU typeof support.
2885  case tok::kw_typeof:
2886
2887    // GNU attributes.
2888  case tok::kw___attribute:
2889    return true;
2890
2891    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
2892  case tok::less:
2893    return getLang().ObjC1;
2894
2895  case tok::kw___declspec:
2896  case tok::kw___cdecl:
2897  case tok::kw___stdcall:
2898  case tok::kw___fastcall:
2899  case tok::kw___thiscall:
2900  case tok::kw___w64:
2901  case tok::kw___ptr64:
2902  case tok::kw___forceinline:
2903  case tok::kw___pascal:
2904
2905  case tok::kw___private:
2906  case tok::kw___local:
2907  case tok::kw___global:
2908  case tok::kw___constant:
2909  case tok::kw___read_only:
2910  case tok::kw___read_write:
2911  case tok::kw___write_only:
2912
2913    return true;
2914  }
2915}
2916
2917bool Parser::isConstructorDeclarator() {
2918  TentativeParsingAction TPA(*this);
2919
2920  // Parse the C++ scope specifier.
2921  CXXScopeSpec SS;
2922  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
2923    TPA.Revert();
2924    return false;
2925  }
2926
2927  // Parse the constructor name.
2928  if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
2929    // We already know that we have a constructor name; just consume
2930    // the token.
2931    ConsumeToken();
2932  } else {
2933    TPA.Revert();
2934    return false;
2935  }
2936
2937  // Current class name must be followed by a left parentheses.
2938  if (Tok.isNot(tok::l_paren)) {
2939    TPA.Revert();
2940    return false;
2941  }
2942  ConsumeParen();
2943
2944  // A right parentheses or ellipsis signals that we have a constructor.
2945  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
2946    TPA.Revert();
2947    return true;
2948  }
2949
2950  // If we need to, enter the specified scope.
2951  DeclaratorScopeObj DeclScopeObj(*this, SS);
2952  if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2953    DeclScopeObj.EnterDeclaratorScope();
2954
2955  // Optionally skip Microsoft attributes.
2956  ParsedAttributes Attrs(AttrFactory);
2957  MaybeParseMicrosoftAttributes(Attrs);
2958
2959  // Check whether the next token(s) are part of a declaration
2960  // specifier, in which case we have the start of a parameter and,
2961  // therefore, we know that this is a constructor.
2962  bool IsConstructor = isDeclarationSpecifier();
2963  TPA.Revert();
2964  return IsConstructor;
2965}
2966
2967/// ParseTypeQualifierListOpt
2968///          type-qualifier-list: [C99 6.7.5]
2969///            type-qualifier
2970/// [vendor]   attributes
2971///              [ only if VendorAttributesAllowed=true ]
2972///            type-qualifier-list type-qualifier
2973/// [vendor]   type-qualifier-list attributes
2974///              [ only if VendorAttributesAllowed=true ]
2975/// [C++0x]    attribute-specifier[opt] is allowed before cv-qualifier-seq
2976///              [ only if CXX0XAttributesAllowed=true ]
2977/// Note: vendor can be GNU, MS, etc.
2978///
2979void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
2980                                       bool VendorAttributesAllowed,
2981                                       bool CXX0XAttributesAllowed) {
2982  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
2983    SourceLocation Loc = Tok.getLocation();
2984    ParsedAttributesWithRange attrs(AttrFactory);
2985    ParseCXX0XAttributes(attrs);
2986    if (CXX0XAttributesAllowed)
2987      DS.takeAttributesFrom(attrs);
2988    else
2989      Diag(Loc, diag::err_attributes_not_allowed);
2990  }
2991
2992  SourceLocation EndLoc;
2993
2994  while (1) {
2995    bool isInvalid = false;
2996    const char *PrevSpec = 0;
2997    unsigned DiagID = 0;
2998    SourceLocation Loc = Tok.getLocation();
2999
3000    switch (Tok.getKind()) {
3001    case tok::code_completion:
3002      Actions.CodeCompleteTypeQualifiers(DS);
3003      ConsumeCodeCompletionToken();
3004      break;
3005
3006    case tok::kw_const:
3007      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, DiagID,
3008                                 getLang());
3009      break;
3010    case tok::kw_volatile:
3011      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
3012                                 getLang());
3013      break;
3014    case tok::kw_restrict:
3015      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
3016                                 getLang());
3017      break;
3018
3019    // OpenCL qualifiers:
3020    case tok::kw_private:
3021      if (!getLang().OpenCL)
3022        goto DoneWithTypeQuals;
3023    case tok::kw___private:
3024    case tok::kw___global:
3025    case tok::kw___local:
3026    case tok::kw___constant:
3027    case tok::kw___read_only:
3028    case tok::kw___write_only:
3029    case tok::kw___read_write:
3030      ParseOpenCLQualifiers(DS);
3031      break;
3032
3033    case tok::kw___w64:
3034    case tok::kw___ptr64:
3035    case tok::kw___cdecl:
3036    case tok::kw___stdcall:
3037    case tok::kw___fastcall:
3038    case tok::kw___thiscall:
3039      if (VendorAttributesAllowed) {
3040        ParseMicrosoftTypeAttributes(DS.getAttributes());
3041        continue;
3042      }
3043      goto DoneWithTypeQuals;
3044    case tok::kw___pascal:
3045      if (VendorAttributesAllowed) {
3046        ParseBorlandTypeAttributes(DS.getAttributes());
3047        continue;
3048      }
3049      goto DoneWithTypeQuals;
3050    case tok::kw___attribute:
3051      if (VendorAttributesAllowed) {
3052        ParseGNUAttributes(DS.getAttributes());
3053        continue; // do *not* consume the next token!
3054      }
3055      // otherwise, FALL THROUGH!
3056    default:
3057      DoneWithTypeQuals:
3058      // If this is not a type-qualifier token, we're done reading type
3059      // qualifiers.  First verify that DeclSpec's are consistent.
3060      DS.Finish(Diags, PP);
3061      if (EndLoc.isValid())
3062        DS.SetRangeEnd(EndLoc);
3063      return;
3064    }
3065
3066    // If the specifier combination wasn't legal, issue a diagnostic.
3067    if (isInvalid) {
3068      assert(PrevSpec && "Method did not return previous specifier!");
3069      Diag(Tok, DiagID) << PrevSpec;
3070    }
3071    EndLoc = ConsumeToken();
3072  }
3073}
3074
3075
3076/// ParseDeclarator - Parse and verify a newly-initialized declarator.
3077///
3078void Parser::ParseDeclarator(Declarator &D) {
3079  /// This implements the 'declarator' production in the C grammar, then checks
3080  /// for well-formedness and issues diagnostics.
3081  ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3082}
3083
3084/// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
3085/// is parsed by the function passed to it. Pass null, and the direct-declarator
3086/// isn't parsed at all, making this function effectively parse the C++
3087/// ptr-operator production.
3088///
3089///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
3090/// [C]     pointer[opt] direct-declarator
3091/// [C++]   direct-declarator
3092/// [C++]   ptr-operator declarator
3093///
3094///       pointer: [C99 6.7.5]
3095///         '*' type-qualifier-list[opt]
3096///         '*' type-qualifier-list[opt] pointer
3097///
3098///       ptr-operator:
3099///         '*' cv-qualifier-seq[opt]
3100///         '&'
3101/// [C++0x] '&&'
3102/// [GNU]   '&' restrict[opt] attributes[opt]
3103/// [GNU?]  '&&' restrict[opt] attributes[opt]
3104///         '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
3105void Parser::ParseDeclaratorInternal(Declarator &D,
3106                                     DirectDeclParseFunction DirectDeclParser) {
3107  if (Diags.hasAllExtensionsSilenced())
3108    D.setExtension();
3109
3110  // C++ member pointers start with a '::' or a nested-name.
3111  // Member pointers get special handling, since there's no place for the
3112  // scope spec in the generic path below.
3113  if (getLang().CPlusPlus &&
3114      (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
3115       Tok.is(tok::annot_cxxscope))) {
3116    CXXScopeSpec SS;
3117    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
3118
3119    if (SS.isNotEmpty()) {
3120      if (Tok.isNot(tok::star)) {
3121        // The scope spec really belongs to the direct-declarator.
3122        D.getCXXScopeSpec() = SS;
3123        if (DirectDeclParser)
3124          (this->*DirectDeclParser)(D);
3125        return;
3126      }
3127
3128      SourceLocation Loc = ConsumeToken();
3129      D.SetRangeEnd(Loc);
3130      DeclSpec DS(AttrFactory);
3131      ParseTypeQualifierListOpt(DS);
3132      D.ExtendWithDeclSpec(DS);
3133
3134      // Recurse to parse whatever is left.
3135      ParseDeclaratorInternal(D, DirectDeclParser);
3136
3137      // Sema will have to catch (syntactically invalid) pointers into global
3138      // scope. It has to catch pointers into namespace scope anyway.
3139      D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
3140                                                      Loc),
3141                    DS.getAttributes(),
3142                    /* Don't replace range end. */SourceLocation());
3143      return;
3144    }
3145  }
3146
3147  tok::TokenKind Kind = Tok.getKind();
3148  // Not a pointer, C++ reference, or block.
3149  if (Kind != tok::star && Kind != tok::caret &&
3150      (Kind != tok::amp || !getLang().CPlusPlus) &&
3151      // We parse rvalue refs in C++03, because otherwise the errors are scary.
3152      (Kind != tok::ampamp || !getLang().CPlusPlus)) {
3153    if (DirectDeclParser)
3154      (this->*DirectDeclParser)(D);
3155    return;
3156  }
3157
3158  // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
3159  // '&&' -> rvalue reference
3160  SourceLocation Loc = ConsumeToken();  // Eat the *, ^, & or &&.
3161  D.SetRangeEnd(Loc);
3162
3163  if (Kind == tok::star || Kind == tok::caret) {
3164    // Is a pointer.
3165    DeclSpec DS(AttrFactory);
3166
3167    ParseTypeQualifierListOpt(DS);
3168    D.ExtendWithDeclSpec(DS);
3169
3170    // Recursively parse the declarator.
3171    ParseDeclaratorInternal(D, DirectDeclParser);
3172    if (Kind == tok::star)
3173      // Remember that we parsed a pointer type, and remember the type-quals.
3174      D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
3175                                                DS.getConstSpecLoc(),
3176                                                DS.getVolatileSpecLoc(),
3177                                                DS.getRestrictSpecLoc()),
3178                    DS.getAttributes(),
3179                    SourceLocation());
3180    else
3181      // Remember that we parsed a Block type, and remember the type-quals.
3182      D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
3183                                                     Loc),
3184                    DS.getAttributes(),
3185                    SourceLocation());
3186  } else {
3187    // Is a reference
3188    DeclSpec DS(AttrFactory);
3189
3190    // Complain about rvalue references in C++03, but then go on and build
3191    // the declarator.
3192    if (Kind == tok::ampamp && !getLang().CPlusPlus0x)
3193      Diag(Loc, diag::ext_rvalue_reference);
3194
3195    // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
3196    // cv-qualifiers are introduced through the use of a typedef or of a
3197    // template type argument, in which case the cv-qualifiers are ignored.
3198    //
3199    // [GNU] Retricted references are allowed.
3200    // [GNU] Attributes on references are allowed.
3201    // [C++0x] Attributes on references are not allowed.
3202    ParseTypeQualifierListOpt(DS, true, false);
3203    D.ExtendWithDeclSpec(DS);
3204
3205    if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
3206      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3207        Diag(DS.getConstSpecLoc(),
3208             diag::err_invalid_reference_qualifier_application) << "const";
3209      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3210        Diag(DS.getVolatileSpecLoc(),
3211             diag::err_invalid_reference_qualifier_application) << "volatile";
3212    }
3213
3214    // Recursively parse the declarator.
3215    ParseDeclaratorInternal(D, DirectDeclParser);
3216
3217    if (D.getNumTypeObjects() > 0) {
3218      // C++ [dcl.ref]p4: There shall be no references to references.
3219      DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
3220      if (InnerChunk.Kind == DeclaratorChunk::Reference) {
3221        if (const IdentifierInfo *II = D.getIdentifier())
3222          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3223           << II;
3224        else
3225          Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
3226            << "type name";
3227
3228        // Once we've complained about the reference-to-reference, we
3229        // can go ahead and build the (technically ill-formed)
3230        // declarator: reference collapsing will take care of it.
3231      }
3232    }
3233
3234    // Remember that we parsed a reference type. It doesn't have type-quals.
3235    D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
3236                                                Kind == tok::amp),
3237                  DS.getAttributes(),
3238                  SourceLocation());
3239  }
3240}
3241
3242/// ParseDirectDeclarator
3243///       direct-declarator: [C99 6.7.5]
3244/// [C99]   identifier
3245///         '(' declarator ')'
3246/// [GNU]   '(' attributes declarator ')'
3247/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3248/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3249/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3250/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3251/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3252///         direct-declarator '(' parameter-type-list ')'
3253///         direct-declarator '(' identifier-list[opt] ')'
3254/// [GNU]   direct-declarator '(' parameter-forward-declarations
3255///                    parameter-type-list[opt] ')'
3256/// [C++]   direct-declarator '(' parameter-declaration-clause ')'
3257///                    cv-qualifier-seq[opt] exception-specification[opt]
3258/// [C++]   declarator-id
3259///
3260///       declarator-id: [C++ 8]
3261///         '...'[opt] id-expression
3262///         '::'[opt] nested-name-specifier[opt] type-name
3263///
3264///       id-expression: [C++ 5.1]
3265///         unqualified-id
3266///         qualified-id
3267///
3268///       unqualified-id: [C++ 5.1]
3269///         identifier
3270///         operator-function-id
3271///         conversion-function-id
3272///          '~' class-name
3273///         template-id
3274///
3275void Parser::ParseDirectDeclarator(Declarator &D) {
3276  DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
3277
3278  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
3279    // ParseDeclaratorInternal might already have parsed the scope.
3280    if (D.getCXXScopeSpec().isEmpty()) {
3281      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), true);
3282    }
3283
3284    if (D.getCXXScopeSpec().isValid()) {
3285      if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3286        // Change the declaration context for name lookup, until this function
3287        // is exited (and the declarator has been parsed).
3288        DeclScopeObj.EnterDeclaratorScope();
3289    }
3290
3291    // C++0x [dcl.fct]p14:
3292    //   There is a syntactic ambiguity when an ellipsis occurs at the end
3293    //   of a parameter-declaration-clause without a preceding comma. In
3294    //   this case, the ellipsis is parsed as part of the
3295    //   abstract-declarator if the type of the parameter names a template
3296    //   parameter pack that has not been expanded; otherwise, it is parsed
3297    //   as part of the parameter-declaration-clause.
3298    if (Tok.is(tok::ellipsis) &&
3299        !((D.getContext() == Declarator::PrototypeContext ||
3300           D.getContext() == Declarator::BlockLiteralContext) &&
3301          NextToken().is(tok::r_paren) &&
3302          !Actions.containsUnexpandedParameterPacks(D)))
3303      D.setEllipsisLoc(ConsumeToken());
3304
3305    if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
3306        Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
3307      // We found something that indicates the start of an unqualified-id.
3308      // Parse that unqualified-id.
3309      bool AllowConstructorName;
3310      if (D.getDeclSpec().hasTypeSpecifier())
3311        AllowConstructorName = false;
3312      else if (D.getCXXScopeSpec().isSet())
3313        AllowConstructorName =
3314          (D.getContext() == Declarator::FileContext ||
3315           (D.getContext() == Declarator::MemberContext &&
3316            D.getDeclSpec().isFriendSpecified()));
3317      else
3318        AllowConstructorName = (D.getContext() == Declarator::MemberContext);
3319
3320      if (ParseUnqualifiedId(D.getCXXScopeSpec(),
3321                             /*EnteringContext=*/true,
3322                             /*AllowDestructorName=*/true,
3323                             AllowConstructorName,
3324                             ParsedType(),
3325                             D.getName()) ||
3326          // Once we're past the identifier, if the scope was bad, mark the
3327          // whole declarator bad.
3328          D.getCXXScopeSpec().isInvalid()) {
3329        D.SetIdentifier(0, Tok.getLocation());
3330        D.setInvalidType(true);
3331      } else {
3332        // Parsed the unqualified-id; update range information and move along.
3333        if (D.getSourceRange().getBegin().isInvalid())
3334          D.SetRangeBegin(D.getName().getSourceRange().getBegin());
3335        D.SetRangeEnd(D.getName().getSourceRange().getEnd());
3336      }
3337      goto PastIdentifier;
3338    }
3339  } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
3340    assert(!getLang().CPlusPlus &&
3341           "There's a C++-specific check for tok::identifier above");
3342    assert(Tok.getIdentifierInfo() && "Not an identifier?");
3343    D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
3344    ConsumeToken();
3345    goto PastIdentifier;
3346  }
3347
3348  if (Tok.is(tok::l_paren)) {
3349    // direct-declarator: '(' declarator ')'
3350    // direct-declarator: '(' attributes declarator ')'
3351    // Example: 'char (*X)'   or 'int (*XX)(void)'
3352    ParseParenDeclarator(D);
3353
3354    // If the declarator was parenthesized, we entered the declarator
3355    // scope when parsing the parenthesized declarator, then exited
3356    // the scope already. Re-enter the scope, if we need to.
3357    if (D.getCXXScopeSpec().isSet()) {
3358      // If there was an error parsing parenthesized declarator, declarator
3359      // scope may have been enterred before. Don't do it again.
3360      if (!D.isInvalidType() &&
3361          Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
3362        // Change the declaration context for name lookup, until this function
3363        // is exited (and the declarator has been parsed).
3364        DeclScopeObj.EnterDeclaratorScope();
3365    }
3366  } else if (D.mayOmitIdentifier()) {
3367    // This could be something simple like "int" (in which case the declarator
3368    // portion is empty), if an abstract-declarator is allowed.
3369    D.SetIdentifier(0, Tok.getLocation());
3370  } else {
3371    if (D.getContext() == Declarator::MemberContext)
3372      Diag(Tok, diag::err_expected_member_name_or_semi)
3373        << D.getDeclSpec().getSourceRange();
3374    else if (getLang().CPlusPlus)
3375      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
3376    else
3377      Diag(Tok, diag::err_expected_ident_lparen);
3378    D.SetIdentifier(0, Tok.getLocation());
3379    D.setInvalidType(true);
3380  }
3381
3382 PastIdentifier:
3383  assert(D.isPastIdentifier() &&
3384         "Haven't past the location of the identifier yet?");
3385
3386  // Don't parse attributes unless we have an identifier.
3387  if (D.getIdentifier())
3388    MaybeParseCXX0XAttributes(D);
3389
3390  while (1) {
3391    if (Tok.is(tok::l_paren)) {
3392      // The paren may be part of a C++ direct initializer, eg. "int x(1);".
3393      // In such a case, check if we actually have a function declarator; if it
3394      // is not, the declarator has been fully parsed.
3395      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
3396        // When not in file scope, warn for ambiguous function declarators, just
3397        // in case the author intended it as a variable definition.
3398        bool warnIfAmbiguous = D.getContext() != Declarator::FileContext;
3399        if (!isCXXFunctionDeclarator(warnIfAmbiguous))
3400          break;
3401      }
3402      ParsedAttributes attrs(AttrFactory);
3403      ParseFunctionDeclarator(ConsumeParen(), D, attrs);
3404    } else if (Tok.is(tok::l_square)) {
3405      ParseBracketDeclarator(D);
3406    } else {
3407      break;
3408    }
3409  }
3410}
3411
3412/// ParseParenDeclarator - We parsed the declarator D up to a paren.  This is
3413/// only called before the identifier, so these are most likely just grouping
3414/// parens for precedence.  If we find that these are actually function
3415/// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
3416///
3417///       direct-declarator:
3418///         '(' declarator ')'
3419/// [GNU]   '(' attributes declarator ')'
3420///         direct-declarator '(' parameter-type-list ')'
3421///         direct-declarator '(' identifier-list[opt] ')'
3422/// [GNU]   direct-declarator '(' parameter-forward-declarations
3423///                    parameter-type-list[opt] ')'
3424///
3425void Parser::ParseParenDeclarator(Declarator &D) {
3426  SourceLocation StartLoc = ConsumeParen();
3427  assert(!D.isPastIdentifier() && "Should be called before passing identifier");
3428
3429  // Eat any attributes before we look at whether this is a grouping or function
3430  // declarator paren.  If this is a grouping paren, the attribute applies to
3431  // the type being built up, for example:
3432  //     int (__attribute__(()) *x)(long y)
3433  // If this ends up not being a grouping paren, the attribute applies to the
3434  // first argument, for example:
3435  //     int (__attribute__(()) int x)
3436  // In either case, we need to eat any attributes to be able to determine what
3437  // sort of paren this is.
3438  //
3439  ParsedAttributes attrs(AttrFactory);
3440  bool RequiresArg = false;
3441  if (Tok.is(tok::kw___attribute)) {
3442    ParseGNUAttributes(attrs);
3443
3444    // We require that the argument list (if this is a non-grouping paren) be
3445    // present even if the attribute list was empty.
3446    RequiresArg = true;
3447  }
3448  // Eat any Microsoft extensions.
3449  if  (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
3450       Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
3451       Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64)) {
3452    ParseMicrosoftTypeAttributes(attrs);
3453  }
3454  // Eat any Borland extensions.
3455  if  (Tok.is(tok::kw___pascal))
3456    ParseBorlandTypeAttributes(attrs);
3457
3458  // If we haven't past the identifier yet (or where the identifier would be
3459  // stored, if this is an abstract declarator), then this is probably just
3460  // grouping parens. However, if this could be an abstract-declarator, then
3461  // this could also be the start of function arguments (consider 'void()').
3462  bool isGrouping;
3463
3464  if (!D.mayOmitIdentifier()) {
3465    // If this can't be an abstract-declarator, this *must* be a grouping
3466    // paren, because we haven't seen the identifier yet.
3467    isGrouping = true;
3468  } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
3469             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(...)
3470             isDeclarationSpecifier()) {       // 'int(int)' is a function.
3471    // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
3472    // considered to be a type, not a K&R identifier-list.
3473    isGrouping = false;
3474  } else {
3475    // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
3476    isGrouping = true;
3477  }
3478
3479  // If this is a grouping paren, handle:
3480  // direct-declarator: '(' declarator ')'
3481  // direct-declarator: '(' attributes declarator ')'
3482  if (isGrouping) {
3483    bool hadGroupingParens = D.hasGroupingParens();
3484    D.setGroupingParens(true);
3485
3486    ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
3487    // Match the ')'.
3488    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, StartLoc);
3489    D.AddTypeInfo(DeclaratorChunk::getParen(StartLoc, EndLoc),
3490                  attrs, EndLoc);
3491
3492    D.setGroupingParens(hadGroupingParens);
3493    return;
3494  }
3495
3496  // Okay, if this wasn't a grouping paren, it must be the start of a function
3497  // argument list.  Recognize that this declarator will never have an
3498  // identifier (and remember where it would have been), then call into
3499  // ParseFunctionDeclarator to handle of argument list.
3500  D.SetIdentifier(0, Tok.getLocation());
3501
3502  ParseFunctionDeclarator(StartLoc, D, attrs, RequiresArg);
3503}
3504
3505/// ParseFunctionDeclarator - We are after the identifier and have parsed the
3506/// declarator D up to a paren, which indicates that we are parsing function
3507/// arguments.
3508///
3509/// If AttrList is non-null, then the caller parsed those arguments immediately
3510/// after the open paren - they should be considered to be the first argument of
3511/// a parameter.  If RequiresArg is true, then the first argument of the
3512/// function is required to be present and required to not be an identifier
3513/// list.
3514///
3515/// This method also handles this portion of the grammar:
3516///       parameter-type-list: [C99 6.7.5]
3517///         parameter-list
3518///         parameter-list ',' '...'
3519/// [C++]   parameter-list '...'
3520///
3521///       parameter-list: [C99 6.7.5]
3522///         parameter-declaration
3523///         parameter-list ',' parameter-declaration
3524///
3525///       parameter-declaration: [C99 6.7.5]
3526///         declaration-specifiers declarator
3527/// [C++]   declaration-specifiers declarator '=' assignment-expression
3528/// [GNU]   declaration-specifiers declarator attributes
3529///         declaration-specifiers abstract-declarator[opt]
3530/// [C++]   declaration-specifiers abstract-declarator[opt]
3531///           '=' assignment-expression
3532/// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
3533///
3534/// For C++, after the parameter-list, it also parses "cv-qualifier-seq[opt]",
3535/// C++0x "ref-qualifier[opt]" and "exception-specification[opt]".
3536///
3537/// [C++0x] exception-specification:
3538///           dynamic-exception-specification
3539///           noexcept-specification
3540///
3541void Parser::ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
3542                                     ParsedAttributes &attrs,
3543                                     bool RequiresArg) {
3544  // lparen is already consumed!
3545  assert(D.isPastIdentifier() && "Should not call before identifier!");
3546
3547  ParsedType TrailingReturnType;
3548
3549  // This parameter list may be empty.
3550  if (Tok.is(tok::r_paren)) {
3551    if (RequiresArg)
3552      Diag(Tok, diag::err_argument_required_after_attribute);
3553
3554    SourceLocation EndLoc = ConsumeParen();  // Eat the closing ')'.
3555
3556    // cv-qualifier-seq[opt].
3557    DeclSpec DS(AttrFactory);
3558    SourceLocation RefQualifierLoc;
3559    bool RefQualifierIsLValueRef = true;
3560    ExceptionSpecificationType ESpecType = EST_None;
3561    SourceRange ESpecRange;
3562    llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3563    llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3564    ExprResult NoexceptExpr;
3565    if (getLang().CPlusPlus) {
3566      MaybeParseCXX0XAttributes(attrs);
3567
3568      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3569      if (!DS.getSourceRange().getEnd().isInvalid())
3570        EndLoc = DS.getSourceRange().getEnd();
3571
3572      // Parse ref-qualifier[opt]
3573      if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3574        if (!getLang().CPlusPlus0x)
3575          Diag(Tok, diag::ext_ref_qualifier);
3576
3577        RefQualifierIsLValueRef = Tok.is(tok::amp);
3578        RefQualifierLoc = ConsumeToken();
3579        EndLoc = RefQualifierLoc;
3580      }
3581
3582      // Parse exception-specification[opt].
3583      ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3584                                                   DynamicExceptions,
3585                                                   DynamicExceptionRanges,
3586                                                   NoexceptExpr);
3587      if (ESpecType != EST_None)
3588        EndLoc = ESpecRange.getEnd();
3589
3590      // Parse trailing-return-type.
3591      if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3592        TrailingReturnType = ParseTrailingReturnType().get();
3593      }
3594    }
3595
3596    // Remember that we parsed a function type, and remember the attributes.
3597    // int() -> no prototype, no '...'.
3598    D.AddTypeInfo(DeclaratorChunk::getFunction(/*prototype*/getLang().CPlusPlus,
3599                                               /*variadic*/ false,
3600                                               SourceLocation(),
3601                                               /*arglist*/ 0, 0,
3602                                               DS.getTypeQualifiers(),
3603                                               RefQualifierIsLValueRef,
3604                                               RefQualifierLoc,
3605                                               ESpecType, ESpecRange.getBegin(),
3606                                               DynamicExceptions.data(),
3607                                               DynamicExceptionRanges.data(),
3608                                               DynamicExceptions.size(),
3609                                               NoexceptExpr.isUsable() ?
3610                                                 NoexceptExpr.get() : 0,
3611                                               LParenLoc, EndLoc, D,
3612                                               TrailingReturnType),
3613                  attrs, EndLoc);
3614    return;
3615  }
3616
3617  // Alternatively, this parameter list may be an identifier list form for a
3618  // K&R-style function:  void foo(a,b,c)
3619  if (!getLang().CPlusPlus && Tok.is(tok::identifier)
3620      && !TryAltiVecVectorToken()) {
3621    if (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) {
3622      // K&R identifier lists can't have typedefs as identifiers, per
3623      // C99 6.7.5.3p11.
3624      if (RequiresArg)
3625        Diag(Tok, diag::err_argument_required_after_attribute);
3626
3627      // Identifier list.  Note that '(' identifier-list ')' is only allowed for
3628      // normal declarators, not for abstract-declarators.  Get the first
3629      // identifier.
3630      Token FirstTok = Tok;
3631      ConsumeToken();  // eat the first identifier.
3632
3633      // Identifier lists follow a really simple grammar: the identifiers can
3634      // be followed *only* by a ", moreidentifiers" or ")".  However, K&R
3635      // identifier lists are really rare in the brave new modern world, and it
3636      // is very common for someone to typo a type in a non-k&r style list.  If
3637      // we are presented with something like: "void foo(intptr x, float y)",
3638      // we don't want to start parsing the function declarator as though it is
3639      // a K&R style declarator just because intptr is an invalid type.
3640      //
3641      // To handle this, we check to see if the token after the first identifier
3642      // is a "," or ")".  Only if so, do we parse it as an identifier list.
3643      if (Tok.is(tok::comma) || Tok.is(tok::r_paren))
3644        return ParseFunctionDeclaratorIdentifierList(LParenLoc,
3645                                                   FirstTok.getIdentifierInfo(),
3646                                                     FirstTok.getLocation(), D);
3647
3648      // If we get here, the code is invalid.  Push the first identifier back
3649      // into the token stream and parse the first argument as an (invalid)
3650      // normal argument declarator.
3651      PP.EnterToken(Tok);
3652      Tok = FirstTok;
3653    }
3654  }
3655
3656  // Finally, a normal, non-empty parameter type list.
3657
3658  // Build up an array of information about the parsed arguments.
3659  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3660
3661  // Enter function-declaration scope, limiting any declarators to the
3662  // function prototype scope, including parameter declarators.
3663  ParseScope PrototypeScope(this,
3664                            Scope::FunctionPrototypeScope|Scope::DeclScope);
3665
3666  bool IsVariadic = false;
3667  SourceLocation EllipsisLoc;
3668  while (1) {
3669    if (Tok.is(tok::ellipsis)) {
3670      IsVariadic = true;
3671      EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3672      break;
3673    }
3674
3675    // Parse the declaration-specifiers.
3676    // Just use the ParsingDeclaration "scope" of the declarator.
3677    DeclSpec DS(AttrFactory);
3678
3679    // Skip any Microsoft attributes before a param.
3680    if (getLang().Microsoft && Tok.is(tok::l_square))
3681      ParseMicrosoftAttributes(DS.getAttributes());
3682
3683    SourceLocation DSStart = Tok.getLocation();
3684
3685    // If the caller parsed attributes for the first argument, add them now.
3686    // Take them so that we only apply the attributes to the first parameter.
3687    DS.takeAttributesFrom(attrs);
3688
3689    ParseDeclarationSpecifiers(DS);
3690
3691    // Parse the declarator.  This is "PrototypeContext", because we must
3692    // accept either 'declarator' or 'abstract-declarator' here.
3693    Declarator ParmDecl(DS, Declarator::PrototypeContext);
3694    ParseDeclarator(ParmDecl);
3695
3696    // Parse GNU attributes, if present.
3697    MaybeParseGNUAttributes(ParmDecl);
3698
3699    // Remember this parsed parameter in ParamInfo.
3700    IdentifierInfo *ParmII = ParmDecl.getIdentifier();
3701
3702    // DefArgToks is used when the parsing of default arguments needs
3703    // to be delayed.
3704    CachedTokens *DefArgToks = 0;
3705
3706    // If no parameter was specified, verify that *something* was specified,
3707    // otherwise we have a missing type and identifier.
3708    if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
3709        ParmDecl.getNumTypeObjects() == 0) {
3710      // Completely missing, emit error.
3711      Diag(DSStart, diag::err_missing_param);
3712    } else {
3713      // Otherwise, we have something.  Add it and let semantic analysis try
3714      // to grok it and add the result to the ParamInfo we are building.
3715
3716      // Inform the actions module about the parameter declarator, so it gets
3717      // added to the current scope.
3718      Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
3719
3720      // Parse the default argument, if any. We parse the default
3721      // arguments in all dialects; the semantic analysis in
3722      // ActOnParamDefaultArgument will reject the default argument in
3723      // C.
3724      if (Tok.is(tok::equal)) {
3725        SourceLocation EqualLoc = Tok.getLocation();
3726
3727        // Parse the default argument
3728        if (D.getContext() == Declarator::MemberContext) {
3729          // If we're inside a class definition, cache the tokens
3730          // corresponding to the default argument. We'll actually parse
3731          // them when we see the end of the class definition.
3732          // FIXME: Templates will require something similar.
3733          // FIXME: Can we use a smart pointer for Toks?
3734          DefArgToks = new CachedTokens;
3735
3736          if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
3737                                    /*StopAtSemi=*/true,
3738                                    /*ConsumeFinalToken=*/false)) {
3739            delete DefArgToks;
3740            DefArgToks = 0;
3741            Actions.ActOnParamDefaultArgumentError(Param);
3742          } else {
3743            // Mark the end of the default argument so that we know when to
3744            // stop when we parse it later on.
3745            Token DefArgEnd;
3746            DefArgEnd.startToken();
3747            DefArgEnd.setKind(tok::cxx_defaultarg_end);
3748            DefArgEnd.setLocation(Tok.getLocation());
3749            DefArgToks->push_back(DefArgEnd);
3750            Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
3751                                                (*DefArgToks)[1].getLocation());
3752          }
3753        } else {
3754          // Consume the '='.
3755          ConsumeToken();
3756
3757          // The argument isn't actually potentially evaluated unless it is
3758          // used.
3759          EnterExpressionEvaluationContext Eval(Actions,
3760                                              Sema::PotentiallyEvaluatedIfUsed);
3761
3762          ExprResult DefArgResult(ParseAssignmentExpression());
3763          if (DefArgResult.isInvalid()) {
3764            Actions.ActOnParamDefaultArgumentError(Param);
3765            SkipUntil(tok::comma, tok::r_paren, true, true);
3766          } else {
3767            // Inform the actions module about the default argument
3768            Actions.ActOnParamDefaultArgument(Param, EqualLoc,
3769                                              DefArgResult.take());
3770          }
3771        }
3772      }
3773
3774      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3775                                          ParmDecl.getIdentifierLoc(), Param,
3776                                          DefArgToks));
3777    }
3778
3779    // If the next token is a comma, consume it and keep reading arguments.
3780    if (Tok.isNot(tok::comma)) {
3781      if (Tok.is(tok::ellipsis)) {
3782        IsVariadic = true;
3783        EllipsisLoc = ConsumeToken();     // Consume the ellipsis.
3784
3785        if (!getLang().CPlusPlus) {
3786          // We have ellipsis without a preceding ',', which is ill-formed
3787          // in C. Complain and provide the fix.
3788          Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
3789            << FixItHint::CreateInsertion(EllipsisLoc, ", ");
3790        }
3791      }
3792
3793      break;
3794    }
3795
3796    // Consume the comma.
3797    ConsumeToken();
3798  }
3799
3800  // If we have the closing ')', eat it.
3801  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3802
3803  DeclSpec DS(AttrFactory);
3804  SourceLocation RefQualifierLoc;
3805  bool RefQualifierIsLValueRef = true;
3806  ExceptionSpecificationType ESpecType = EST_None;
3807  SourceRange ESpecRange;
3808  llvm::SmallVector<ParsedType, 2> DynamicExceptions;
3809  llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
3810  ExprResult NoexceptExpr;
3811
3812  if (getLang().CPlusPlus) {
3813    MaybeParseCXX0XAttributes(attrs);
3814
3815    // Parse cv-qualifier-seq[opt].
3816    ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3817      if (!DS.getSourceRange().getEnd().isInvalid())
3818        EndLoc = DS.getSourceRange().getEnd();
3819
3820    // Parse ref-qualifier[opt]
3821    if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
3822      if (!getLang().CPlusPlus0x)
3823        Diag(Tok, diag::ext_ref_qualifier);
3824
3825      RefQualifierIsLValueRef = Tok.is(tok::amp);
3826      RefQualifierLoc = ConsumeToken();
3827      EndLoc = RefQualifierLoc;
3828    }
3829
3830    // FIXME: We should leave the prototype scope before parsing the exception
3831    // specification, and then reenter it when parsing the trailing return type.
3832    // FIXMEFIXME: Why? That wouldn't be right for the noexcept clause.
3833
3834    // Parse exception-specification[opt].
3835    ESpecType = MaybeParseExceptionSpecification(ESpecRange,
3836                                                 DynamicExceptions,
3837                                                 DynamicExceptionRanges,
3838                                                 NoexceptExpr);
3839    if (ESpecType != EST_None)
3840      EndLoc = ESpecRange.getEnd();
3841
3842    // Parse trailing-return-type.
3843    if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
3844      TrailingReturnType = ParseTrailingReturnType().get();
3845    }
3846  }
3847
3848  // Leave prototype scope.
3849  PrototypeScope.Exit();
3850
3851  // Remember that we parsed a function type, and remember the attributes.
3852  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/true, IsVariadic,
3853                                             EllipsisLoc,
3854                                             ParamInfo.data(), ParamInfo.size(),
3855                                             DS.getTypeQualifiers(),
3856                                             RefQualifierIsLValueRef,
3857                                             RefQualifierLoc,
3858                                             ESpecType, ESpecRange.getBegin(),
3859                                             DynamicExceptions.data(),
3860                                             DynamicExceptionRanges.data(),
3861                                             DynamicExceptions.size(),
3862                                             NoexceptExpr.isUsable() ?
3863                                               NoexceptExpr.get() : 0,
3864                                             LParenLoc, EndLoc, D,
3865                                             TrailingReturnType),
3866                attrs, EndLoc);
3867}
3868
3869/// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
3870/// we found a K&R-style identifier list instead of a type argument list.  The
3871/// first identifier has already been consumed, and the current token is the
3872/// token right after it.
3873///
3874///       identifier-list: [C99 6.7.5]
3875///         identifier
3876///         identifier-list ',' identifier
3877///
3878void Parser::ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
3879                                                   IdentifierInfo *FirstIdent,
3880                                                   SourceLocation FirstIdentLoc,
3881                                                   Declarator &D) {
3882  // Build up an array of information about the parsed arguments.
3883  llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
3884  llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
3885
3886  // If there was no identifier specified for the declarator, either we are in
3887  // an abstract-declarator, or we are in a parameter declarator which was found
3888  // to be abstract.  In abstract-declarators, identifier lists are not valid:
3889  // diagnose this.
3890  if (!D.getIdentifier())
3891    Diag(FirstIdentLoc, diag::ext_ident_list_in_param);
3892
3893  // The first identifier was already read, and is known to be the first
3894  // identifier in the list.  Remember this identifier in ParamInfo.
3895  ParamsSoFar.insert(FirstIdent);
3896  ParamInfo.push_back(DeclaratorChunk::ParamInfo(FirstIdent, FirstIdentLoc, 0));
3897
3898  while (Tok.is(tok::comma)) {
3899    // Eat the comma.
3900    ConsumeToken();
3901
3902    // If this isn't an identifier, report the error and skip until ')'.
3903    if (Tok.isNot(tok::identifier)) {
3904      Diag(Tok, diag::err_expected_ident);
3905      SkipUntil(tok::r_paren);
3906      return;
3907    }
3908
3909    IdentifierInfo *ParmII = Tok.getIdentifierInfo();
3910
3911    // Reject 'typedef int y; int test(x, y)', but continue parsing.
3912    if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
3913      Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
3914
3915    // Verify that the argument identifier has not already been mentioned.
3916    if (!ParamsSoFar.insert(ParmII)) {
3917      Diag(Tok, diag::err_param_redefinition) << ParmII;
3918    } else {
3919      // Remember this identifier in ParamInfo.
3920      ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
3921                                                     Tok.getLocation(),
3922                                                     0));
3923    }
3924
3925    // Eat the identifier.
3926    ConsumeToken();
3927  }
3928
3929  // If we have the closing ')', eat it and we're done.
3930  SourceLocation RLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc);
3931
3932  // Remember that we parsed a function type, and remember the attributes.  This
3933  // function type is always a K&R style function type, which is not varargs and
3934  // has no prototype.
3935  ParsedAttributes attrs(AttrFactory);
3936  D.AddTypeInfo(DeclaratorChunk::getFunction(/*proto*/false, /*varargs*/false,
3937                                             SourceLocation(),
3938                                             &ParamInfo[0], ParamInfo.size(),
3939                                             /*TypeQuals*/0,
3940                                             true, SourceLocation(),
3941                                             EST_None, SourceLocation(), 0, 0,
3942                                             0, 0, LParenLoc, RLoc, D),
3943                attrs, RLoc);
3944}
3945
3946/// [C90]   direct-declarator '[' constant-expression[opt] ']'
3947/// [C99]   direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
3948/// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
3949/// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr ']'
3950/// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
3951void Parser::ParseBracketDeclarator(Declarator &D) {
3952  SourceLocation StartLoc = ConsumeBracket();
3953
3954  // C array syntax has many features, but by-far the most common is [] and [4].
3955  // This code does a fast path to handle some of the most obvious cases.
3956  if (Tok.getKind() == tok::r_square) {
3957    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3958    ParsedAttributes attrs(AttrFactory);
3959    MaybeParseCXX0XAttributes(attrs);
3960
3961    // Remember that we parsed the empty array type.
3962    ExprResult NumElements;
3963    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
3964                                            StartLoc, EndLoc),
3965                  attrs, EndLoc);
3966    return;
3967  } else if (Tok.getKind() == tok::numeric_constant &&
3968             GetLookAheadToken(1).is(tok::r_square)) {
3969    // [4] is very common.  Parse the numeric constant expression.
3970    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
3971    ConsumeToken();
3972
3973    SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
3974    ParsedAttributes attrs(AttrFactory);
3975    MaybeParseCXX0XAttributes(attrs);
3976
3977    // Remember that we parsed a array type, and remember its features.
3978    D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
3979                                            ExprRes.release(),
3980                                            StartLoc, EndLoc),
3981                  attrs, EndLoc);
3982    return;
3983  }
3984
3985  // If valid, this location is the position where we read the 'static' keyword.
3986  SourceLocation StaticLoc;
3987  if (Tok.is(tok::kw_static))
3988    StaticLoc = ConsumeToken();
3989
3990  // If there is a type-qualifier-list, read it now.
3991  // Type qualifiers in an array subscript are a C99 feature.
3992  DeclSpec DS(AttrFactory);
3993  ParseTypeQualifierListOpt(DS, false /*no attributes*/);
3994
3995  // If we haven't already read 'static', check to see if there is one after the
3996  // type-qualifier-list.
3997  if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
3998    StaticLoc = ConsumeToken();
3999
4000  // Handle "direct-declarator [ type-qual-list[opt] * ]".
4001  bool isStar = false;
4002  ExprResult NumElements;
4003
4004  // Handle the case where we have '[*]' as the array size.  However, a leading
4005  // star could be the start of an expression, for example 'X[*p + 4]'.  Verify
4006  // the the token after the star is a ']'.  Since stars in arrays are
4007  // infrequent, use of lookahead is not costly here.
4008  if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
4009    ConsumeToken();  // Eat the '*'.
4010
4011    if (StaticLoc.isValid()) {
4012      Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
4013      StaticLoc = SourceLocation();  // Drop the static.
4014    }
4015    isStar = true;
4016  } else if (Tok.isNot(tok::r_square)) {
4017    // Note, in C89, this production uses the constant-expr production instead
4018    // of assignment-expr.  The only difference is that assignment-expr allows
4019    // things like '=' and '*='.  Sema rejects these in C89 mode because they
4020    // are not i-c-e's, so we don't need to distinguish between the two here.
4021
4022    // Parse the constant-expression or assignment-expression now (depending
4023    // on dialect).
4024    if (getLang().CPlusPlus)
4025      NumElements = ParseConstantExpression();
4026    else
4027      NumElements = ParseAssignmentExpression();
4028  }
4029
4030  // If there was an error parsing the assignment-expression, recover.
4031  if (NumElements.isInvalid()) {
4032    D.setInvalidType(true);
4033    // If the expression was invalid, skip it.
4034    SkipUntil(tok::r_square);
4035    return;
4036  }
4037
4038  SourceLocation EndLoc = MatchRHSPunctuation(tok::r_square, StartLoc);
4039
4040  ParsedAttributes attrs(AttrFactory);
4041  MaybeParseCXX0XAttributes(attrs);
4042
4043  // Remember that we parsed a array type, and remember its features.
4044  D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
4045                                          StaticLoc.isValid(), isStar,
4046                                          NumElements.release(),
4047                                          StartLoc, EndLoc),
4048                attrs, EndLoc);
4049}
4050
4051/// [GNU]   typeof-specifier:
4052///           typeof ( expressions )
4053///           typeof ( type-name )
4054/// [GNU/C++] typeof unary-expression
4055///
4056void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
4057  assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
4058  Token OpTok = Tok;
4059  SourceLocation StartLoc = ConsumeToken();
4060
4061  const bool hasParens = Tok.is(tok::l_paren);
4062
4063  bool isCastExpr;
4064  ParsedType CastTy;
4065  SourceRange CastRange;
4066  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
4067                                                          CastTy, CastRange);
4068  if (hasParens)
4069    DS.setTypeofParensRange(CastRange);
4070
4071  if (CastRange.getEnd().isInvalid())
4072    // FIXME: Not accurate, the range gets one token more than it should.
4073    DS.SetRangeEnd(Tok.getLocation());
4074  else
4075    DS.SetRangeEnd(CastRange.getEnd());
4076
4077  if (isCastExpr) {
4078    if (!CastTy) {
4079      DS.SetTypeSpecError();
4080      return;
4081    }
4082
4083    const char *PrevSpec = 0;
4084    unsigned DiagID;
4085    // Check for duplicate type specifiers (e.g. "int typeof(int)").
4086    if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
4087                           DiagID, CastTy))
4088      Diag(StartLoc, DiagID) << PrevSpec;
4089    return;
4090  }
4091
4092  // If we get here, the operand to the typeof was an expresion.
4093  if (Operand.isInvalid()) {
4094    DS.SetTypeSpecError();
4095    return;
4096  }
4097
4098  const char *PrevSpec = 0;
4099  unsigned DiagID;
4100  // Check for duplicate type specifiers (e.g. "int typeof(int)").
4101  if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
4102                         DiagID, Operand.get()))
4103    Diag(StartLoc, DiagID) << PrevSpec;
4104}
4105
4106
4107/// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
4108/// from TryAltiVecVectorToken.
4109bool Parser::TryAltiVecVectorTokenOutOfLine() {
4110  Token Next = NextToken();
4111  switch (Next.getKind()) {
4112  default: return false;
4113  case tok::kw_short:
4114  case tok::kw_long:
4115  case tok::kw_signed:
4116  case tok::kw_unsigned:
4117  case tok::kw_void:
4118  case tok::kw_char:
4119  case tok::kw_int:
4120  case tok::kw_float:
4121  case tok::kw_double:
4122  case tok::kw_bool:
4123  case tok::kw___pixel:
4124    Tok.setKind(tok::kw___vector);
4125    return true;
4126  case tok::identifier:
4127    if (Next.getIdentifierInfo() == Ident_pixel) {
4128      Tok.setKind(tok::kw___vector);
4129      return true;
4130    }
4131    return false;
4132  }
4133}
4134
4135bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
4136                                      const char *&PrevSpec, unsigned &DiagID,
4137                                      bool &isInvalid) {
4138  if (Tok.getIdentifierInfo() == Ident_vector) {
4139    Token Next = NextToken();
4140    switch (Next.getKind()) {
4141    case tok::kw_short:
4142    case tok::kw_long:
4143    case tok::kw_signed:
4144    case tok::kw_unsigned:
4145    case tok::kw_void:
4146    case tok::kw_char:
4147    case tok::kw_int:
4148    case tok::kw_float:
4149    case tok::kw_double:
4150    case tok::kw_bool:
4151    case tok::kw___pixel:
4152      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4153      return true;
4154    case tok::identifier:
4155      if (Next.getIdentifierInfo() == Ident_pixel) {
4156        isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
4157        return true;
4158      }
4159      break;
4160    default:
4161      break;
4162    }
4163  } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
4164             DS.isTypeAltiVecVector()) {
4165    isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
4166    return true;
4167  }
4168  return false;
4169}
4170