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