Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the Declaration portions of the Parser interfaces.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Parse/Parser.h"
14
#include "clang/Parse/RAIIObjectsForParser.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/DeclTemplate.h"
17
#include "clang/AST/PrettyDeclStackTrace.h"
18
#include "clang/Basic/AddressSpaces.h"
19
#include "clang/Basic/Attributes.h"
20
#include "clang/Basic/CharInfo.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/Parse/ParseDiagnostic.h"
23
#include "clang/Sema/Lookup.h"
24
#include "clang/Sema/ParsedTemplate.h"
25
#include "clang/Sema/Scope.h"
26
#include "clang/Sema/SemaDiagnostic.h"
27
#include "llvm/ADT/Optional.h"
28
#include "llvm/ADT/SmallSet.h"
29
#include "llvm/ADT/SmallString.h"
30
#include "llvm/ADT/StringSwitch.h"
31
32
using namespace clang;
33
34
//===----------------------------------------------------------------------===//
35
// C99 6.7: Declarations.
36
//===----------------------------------------------------------------------===//
37
38
/// ParseTypeName
39
///       type-name: [C99 6.7.6]
40
///         specifier-qualifier-list abstract-declarator[opt]
41
///
42
/// Called type-id in C++.
43
TypeResult Parser::ParseTypeName(SourceRange *Range,
44
                                 DeclaratorContext Context,
45
                                 AccessSpecifier AS,
46
                                 Decl **OwnedType,
47
4.15M
                                 ParsedAttributes *Attrs) {
48
4.15M
  DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
49
4.15M
  if (DSC == DeclSpecContext::DSC_normal)
50
272k
    DSC = DeclSpecContext::DSC_type_specifier;
51
52
  // Parse the common declaration-specifiers piece.
53
4.15M
  DeclSpec DS(AttrFactory);
54
4.15M
  if (Attrs)
55
74.3k
    DS.addAttributes(*Attrs);
56
4.15M
  ParseSpecifierQualifierList(DS, AS, DSC);
57
4.15M
  if (OwnedType)
58
74.3k
    *OwnedType = DS.isTypeSpecOwned() ? 
DS.getRepAsDecl()43
:
nullptr74.2k
;
59
60
  // Parse the abstract-declarator, if present.
61
4.15M
  Declarator DeclaratorInfo(DS, Context);
62
4.15M
  ParseDeclarator(DeclaratorInfo);
63
4.15M
  if (Range)
64
15.8k
    *Range = DeclaratorInfo.getSourceRange();
65
66
4.15M
  if (DeclaratorInfo.isInvalidType())
67
615
    return true;
68
69
4.15M
  return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
70
4.15M
}
71
72
/// Normalizes an attribute name by dropping prefixed and suffixed __.
73
152M
static StringRef normalizeAttrName(StringRef Name) {
74
152M
  if (Name.size() >= 4 && 
Name.startswith("__")152M
&&
Name.endswith("__")126M
)
75
18.3M
    return Name.drop_front(2).drop_back(2);
76
134M
  return Name;
77
152M
}
78
79
/// isAttributeLateParsed - Return true if the attribute has arguments that
80
/// require late parsing.
81
2.41M
static bool isAttributeLateParsed(const IdentifierInfo &II) {
82
2.41M
#define CLANG_ATTR_LATE_PARSED_LIST
83
2.41M
    return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
84
2.41M
#include "clang/Parse/AttrParserStringSwitches.inc"
85
2.41M
        .Default(false);
86
2.41M
#undef CLANG_ATTR_LATE_PARSED_LIST
87
2.41M
}
88
89
/// Check if the a start and end source location expand to the same macro.
90
static bool FindLocsWithCommonFileID(Preprocessor &PP, SourceLocation StartLoc,
91
62.0M
                                     SourceLocation EndLoc) {
92
62.0M
  if (!StartLoc.isMacroID() || 
!EndLoc.isMacroID()36.0M
)
93
26.0M
    return false;
94
95
36.0M
  SourceManager &SM = PP.getSourceManager();
96
36.0M
  if (SM.getFileID(StartLoc) != SM.getFileID(EndLoc))
97
14.9k
    return false;
98
99
35.9M
  bool AttrStartIsInMacro =
100
35.9M
      Lexer::isAtStartOfMacroExpansion(StartLoc, SM, PP.getLangOpts());
101
35.9M
  bool AttrEndIsInMacro =
102
35.9M
      Lexer::isAtEndOfMacroExpansion(EndLoc, SM, PP.getLangOpts());
103
35.9M
  return AttrStartIsInMacro && 
AttrEndIsInMacro6.31M
;
104
36.0M
}
105
106
void Parser::ParseAttributes(unsigned WhichAttrKinds,
107
                             ParsedAttributesWithRange &Attrs,
108
                             SourceLocation *End,
109
30.5M
                             LateParsedAttrList *LateAttrs) {
110
30.5M
  bool MoreToParse;
111
61.1M
  do {
112
    // Assume there's nothing left to parse, but if any attributes are in fact
113
    // parsed, loop to ensure all specified attribute combinations are parsed.
114
61.1M
    MoreToParse = false;
115
61.1M
    if (WhichAttrKinds & PAKM_CXX11)
116
1.46M
      MoreToParse |= MaybeParseCXX11Attributes(Attrs, End);
117
61.1M
    if (WhichAttrKinds & PAKM_GNU)
118
61.1M
      MoreToParse |= MaybeParseGNUAttributes(Attrs, End, LateAttrs);
119
61.1M
    if (WhichAttrKinds & PAKM_Declspec)
120
60.4M
      MoreToParse |= MaybeParseMicrosoftDeclSpecs(Attrs, End);
121
61.1M
  } while (MoreToParse);
122
30.5M
}
123
124
/// ParseGNUAttributes - Parse a non-empty attributes list.
125
///
126
/// [GNU] attributes:
127
///         attribute
128
///         attributes attribute
129
///
130
/// [GNU]  attribute:
131
///          '__attribute__' '(' '(' attribute-list ')' ')'
132
///
133
/// [GNU]  attribute-list:
134
///          attrib
135
///          attribute_list ',' attrib
136
///
137
/// [GNU]  attrib:
138
///          empty
139
///          attrib-name
140
///          attrib-name '(' identifier ')'
141
///          attrib-name '(' identifier ',' nonempty-expr-list ')'
142
///          attrib-name '(' argument-expression-list [C99 6.5.2] ')'
143
///
144
/// [GNU]  attrib-name:
145
///          identifier
146
///          typespec
147
///          typequal
148
///          storageclass
149
///
150
/// Whether an attribute takes an 'identifier' is determined by the
151
/// attrib-name. GCC's behavior here is not worth imitating:
152
///
153
///  * In C mode, if the attribute argument list starts with an identifier
154
///    followed by a ',' or an ')', and the identifier doesn't resolve to
155
///    a type, it is parsed as an identifier. If the attribute actually
156
///    wanted an expression, it's out of luck (but it turns out that no
157
///    attributes work that way, because C constant expressions are very
158
///    limited).
159
///  * In C++ mode, if the attribute argument list starts with an identifier,
160
///    and the attribute *wants* an identifier, it is parsed as an identifier.
161
///    At block scope, any additional tokens between the identifier and the
162
///    ',' or ')' are ignored, otherwise they produce a parse error.
163
///
164
/// We follow the C++ model, but don't allow junk after the identifier.
165
void Parser::ParseGNUAttributes(ParsedAttributesWithRange &Attrs,
166
                                SourceLocation *EndLoc,
167
32.8M
                                LateParsedAttrList *LateAttrs, Declarator *D) {
168
32.8M
  assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
169
170
0
  SourceLocation StartLoc = Tok.getLocation(), Loc;
171
172
32.8M
  if (!EndLoc)
173
30.7M
    EndLoc = &Loc;
174
175
94.9M
  while (Tok.is(tok::kw___attribute)) {
176
62.0M
    SourceLocation AttrTokLoc = ConsumeToken();
177
62.0M
    unsigned OldNumAttrs = Attrs.size();
178
62.0M
    unsigned OldNumLateAttrs = LateAttrs ? 
LateAttrs->size()3.05M
:
059.0M
;
179
180
62.0M
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
181
62.0M
                         "attribute")) {
182
0
      SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
183
0
      return;
184
0
    }
185
62.0M
    if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
186
0
      SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
187
0
      return;
188
0
    }
189
    // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
190
105M
    
do 62.0M
{
191
      // Eat preceeding commas to allow __attribute__((,,,foo))
192
149M
      while (TryConsumeToken(tok::comma))
193
43.5M
        ;
194
195
      // Expect an identifier or declaration specifier (const, int, etc.)
196
105M
      if (Tok.isAnnotation())
197
0
        break;
198
105M
      if (Tok.is(tok::code_completion)) {
199
1
        cutOffParsing();
200
1
        Actions.CodeCompleteAttribute(AttributeCommonInfo::Syntax::AS_GNU);
201
1
        break;
202
1
      }
203
105M
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
204
105M
      if (!AttrName)
205
53
        break;
206
207
105M
      SourceLocation AttrNameLoc = ConsumeToken();
208
209
105M
      if (Tok.isNot(tok::l_paren)) {
210
69.7M
        Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
211
69.7M
                     ParsedAttr::AS_GNU);
212
69.7M
        continue;
213
69.7M
      }
214
215
      // Handle "parameterized" attributes
216
35.8M
      if (!LateAttrs || 
!isAttributeLateParsed(*AttrName)2.41M
) {
217
35.8M
        ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, nullptr,
218
35.8M
                              SourceLocation(), ParsedAttr::AS_GNU, D);
219
35.8M
        continue;
220
35.8M
      }
221
222
      // Handle attributes with arguments that require late parsing.
223
10.6k
      LateParsedAttribute *LA =
224
10.6k
          new LateParsedAttribute(this, *AttrName, AttrNameLoc);
225
10.6k
      LateAttrs->push_back(LA);
226
227
      // Attributes in a class are parsed at the end of the class, along
228
      // with other late-parsed declarations.
229
10.6k
      if (!ClassStack.empty() && 
!LateAttrs->parseSoon()5.37k
)
230
5.36k
        getCurrentClass().LateParsedDeclarations.push_back(LA);
231
232
      // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
233
      // recursively consumes balanced parens.
234
10.6k
      LA->Toks.push_back(Tok);
235
10.6k
      ConsumeParen();
236
      // Consume everything up to and including the matching right parens.
237
10.6k
      ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
238
239
10.6k
      Token Eof;
240
10.6k
      Eof.startToken();
241
10.6k
      Eof.setLocation(Tok.getLocation());
242
10.6k
      LA->Toks.push_back(Eof);
243
105M
    } while (Tok.is(tok::comma));
244
245
62.0M
    if (ExpectAndConsume(tok::r_paren))
246
4
      SkipUntil(tok::r_paren, StopAtSemi);
247
62.0M
    SourceLocation Loc = Tok.getLocation();
248
62.0M
    if (ExpectAndConsume(tok::r_paren))
249
2
      SkipUntil(tok::r_paren, StopAtSemi);
250
62.0M
    if (EndLoc)
251
62.0M
      *EndLoc = Loc;
252
253
    // If this was declared in a macro, attach the macro IdentifierInfo to the
254
    // parsed attribute.
255
62.0M
    auto &SM = PP.getSourceManager();
256
62.0M
    if (!SM.isWrittenInBuiltinFile(SM.getSpellingLoc(AttrTokLoc)) &&
257
62.0M
        
FindLocsWithCommonFileID(PP, AttrTokLoc, Loc)62.0M
) {
258
3.95M
      CharSourceRange ExpansionRange = SM.getExpansionRange(AttrTokLoc);
259
3.95M
      StringRef FoundName =
260
3.95M
          Lexer::getSourceText(ExpansionRange, SM, PP.getLangOpts());
261
3.95M
      IdentifierInfo *MacroII = PP.getIdentifierInfo(FoundName);
262
263
11.4M
      for (unsigned i = OldNumAttrs; i < Attrs.size(); 
++i7.44M
)
264
7.44M
        Attrs[i].setMacroIdentifier(MacroII, ExpansionRange.getBegin());
265
266
3.95M
      if (LateAttrs) {
267
794k
        for (unsigned i = OldNumLateAttrs; i < LateAttrs->size(); 
++i10.5k
)
268
10.5k
          (*LateAttrs)[i]->MacroII = MacroII;
269
783k
      }
270
3.95M
    }
271
62.0M
  }
272
273
32.8M
  Attrs.Range = SourceRange(StartLoc, *EndLoc);
274
32.8M
}
275
276
/// Determine whether the given attribute has an identifier argument.
277
25.9M
static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
278
25.9M
#define CLANG_ATTR_IDENTIFIER_ARG_LIST
279
25.9M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
280
25.9M
#include "clang/Parse/AttrParserStringSwitches.inc"
281
25.9M
           .Default(false);
282
25.9M
#undef CLANG_ATTR_IDENTIFIER_ARG_LIST
283
25.9M
}
284
285
/// Determine whether the given attribute has a variadic identifier argument.
286
22.1k
static bool attributeHasVariadicIdentifierArg(const IdentifierInfo &II) {
287
22.1k
#define CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
288
22.1k
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
289
22.1k
#include "clang/Parse/AttrParserStringSwitches.inc"
290
22.1k
           .Default(false);
291
22.1k
#undef CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST
292
22.1k
}
293
294
/// Determine whether the given attribute treats kw_this as an identifier.
295
29.9M
static bool attributeTreatsKeywordThisAsIdentifier(const IdentifierInfo &II) {
296
29.9M
#define CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
297
29.9M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
298
29.9M
#include "clang/Parse/AttrParserStringSwitches.inc"
299
29.9M
           .Default(false);
300
29.9M
#undef CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST
301
29.9M
}
302
303
/// Determine whether the given attribute parses a type argument.
304
59.9M
static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
305
59.9M
#define CLANG_ATTR_TYPE_ARG_LIST
306
59.9M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
307
59.9M
#include "clang/Parse/AttrParserStringSwitches.inc"
308
59.9M
           .Default(false);
309
59.9M
#undef CLANG_ATTR_TYPE_ARG_LIST
310
59.9M
}
311
312
/// Determine whether the given attribute requires parsing its arguments
313
/// in an unevaluated context or not.
314
4.11M
static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
315
4.11M
#define CLANG_ATTR_ARG_CONTEXT_LIST
316
4.11M
  return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
317
4.11M
#include "clang/Parse/AttrParserStringSwitches.inc"
318
4.11M
           .Default(false);
319
4.11M
#undef CLANG_ATTR_ARG_CONTEXT_LIST
320
4.11M
}
321
322
31.8M
IdentifierLoc *Parser::ParseIdentifierLoc() {
323
31.8M
  assert(Tok.is(tok::identifier) && "expected an identifier");
324
0
  IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
325
31.8M
                                            Tok.getLocation(),
326
31.8M
                                            Tok.getIdentifierInfo());
327
31.8M
  ConsumeToken();
328
31.8M
  return IL;
329
31.8M
}
330
331
void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
332
                                       SourceLocation AttrNameLoc,
333
                                       ParsedAttributes &Attrs,
334
                                       SourceLocation *EndLoc,
335
                                       IdentifierInfo *ScopeName,
336
                                       SourceLocation ScopeLoc,
337
14.4k
                                       ParsedAttr::Syntax Syntax) {
338
14.4k
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
339
14.4k
  Parens.consumeOpen();
340
341
14.4k
  TypeResult T;
342
14.4k
  if (Tok.isNot(tok::r_paren))
343
14.4k
    T = ParseTypeName();
344
345
14.4k
  if (Parens.consumeClose())
346
5
    return;
347
348
14.4k
  if (T.isInvalid())
349
5
    return;
350
351
14.4k
  if (T.isUsable())
352
14.4k
    Attrs.addNewTypeAttr(&AttrName,
353
14.4k
                         SourceRange(AttrNameLoc, Parens.getCloseLocation()),
354
14.4k
                         ScopeName, ScopeLoc, T.get(), Syntax);
355
4
  else
356
4
    Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
357
4
                 ScopeName, ScopeLoc, nullptr, 0, Syntax);
358
14.4k
}
359
360
unsigned Parser::ParseAttributeArgsCommon(
361
    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
362
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
363
29.9M
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
364
  // Ignore the left paren location for now.
365
29.9M
  ConsumeParen();
366
367
29.9M
  bool ChangeKWThisToIdent = attributeTreatsKeywordThisAsIdentifier(*AttrName);
368
29.9M
  bool AttributeIsTypeArgAttr = attributeIsTypeArgAttr(*AttrName);
369
370
  // Interpret "kw_this" as an identifier if the attributed requests it.
371
29.9M
  if (ChangeKWThisToIdent && 
Tok.is(tok::kw_this)142
)
372
1
    Tok.setKind(tok::identifier);
373
374
29.9M
  ArgsVector ArgExprs;
375
29.9M
  if (Tok.is(tok::identifier)) {
376
    // If this attribute wants an 'identifier' argument, make it so.
377
25.9M
    bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName) ||
378
25.9M
                           
attributeHasVariadicIdentifierArg(*AttrName)10.9k
;
379
25.9M
    ParsedAttr::Kind AttrKind =
380
25.9M
        ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
381
382
    // If we don't know how to parse this attribute, but this is the only
383
    // token in this argument, assume it's meant to be an identifier.
384
25.9M
    if (AttrKind == ParsedAttr::UnknownAttribute ||
385
25.9M
        
AttrKind == ParsedAttr::IgnoredAttribute25.9M
) {
386
7
      const Token &Next = NextToken();
387
7
      IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
388
7
    }
389
390
25.9M
    if (IsIdentifierArg)
391
25.9M
      ArgExprs.push_back(ParseIdentifierLoc());
392
25.9M
  }
393
394
29.9M
  ParsedType TheParsedType;
395
29.9M
  if (!ArgExprs.empty() ? 
Tok.is(tok::comma)25.9M
:
Tok.isNot(tok::r_paren)4.01M
) {
396
    // Eat the comma.
397
4.04M
    if (!ArgExprs.empty())
398
35.5k
      ConsumeToken();
399
400
    // Parse the non-empty comma-separated list of expressions.
401
4.11M
    do {
402
      // Interpret "kw_this" as an identifier if the attributed requests it.
403
4.11M
      if (ChangeKWThisToIdent && 
Tok.is(tok::kw_this)269
)
404
4
        Tok.setKind(tok::identifier);
405
406
4.11M
      ExprResult ArgExpr;
407
4.11M
      if (AttributeIsTypeArgAttr) {
408
59
        TypeResult T = ParseTypeName();
409
59
        if (T.isInvalid()) {
410
4
          SkipUntil(tok::r_paren, StopAtSemi);
411
4
          return 0;
412
4
        }
413
55
        if (T.isUsable())
414
55
          TheParsedType = T.get();
415
55
        break; // FIXME: Multiple type arguments are not implemented.
416
4.11M
      } else if (Tok.is(tok::identifier) &&
417
4.11M
                 
attributeHasVariadicIdentifierArg(*AttrName)11.2k
) {
418
145
        ArgExprs.push_back(ParseIdentifierLoc());
419
4.11M
      } else {
420
4.11M
        bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
421
4.11M
        EnterExpressionEvaluationContext Unevaluated(
422
4.11M
            Actions,
423
4.11M
            Uneval ? 
Sema::ExpressionEvaluationContext::Unevaluated3.14k
424
4.11M
                   : 
Sema::ExpressionEvaluationContext::ConstantEvaluated4.11M
);
425
426
4.11M
        ExprResult ArgExpr(
427
4.11M
            Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
428
4.11M
        if (ArgExpr.isInvalid()) {
429
42
          SkipUntil(tok::r_paren, StopAtSemi);
430
42
          return 0;
431
42
        }
432
4.11M
        ArgExprs.push_back(ArgExpr.get());
433
4.11M
      }
434
      // Eat the comma, move to the next argument
435
4.11M
    } while (
TryConsumeToken(tok::comma)4.11M
);
436
4.04M
  }
437
438
29.9M
  SourceLocation RParen = Tok.getLocation();
439
29.9M
  if (!ExpectAndConsume(tok::r_paren)) {
440
29.9M
    SourceLocation AttrLoc = ScopeLoc.isValid() ? 
ScopeLoc225
:
AttrNameLoc29.9M
;
441
442
29.9M
    if (AttributeIsTypeArgAttr && 
!TheParsedType.get().isNull()58
) {
443
55
      Attrs.addNewTypeAttr(AttrName, SourceRange(AttrNameLoc, RParen),
444
55
                           ScopeName, ScopeLoc, TheParsedType, Syntax);
445
29.9M
    } else {
446
29.9M
      Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
447
29.9M
                   ArgExprs.data(), ArgExprs.size(), Syntax);
448
29.9M
    }
449
29.9M
  }
450
451
29.9M
  if (EndLoc)
452
29.9M
    *EndLoc = RParen;
453
454
29.9M
  return static_cast<unsigned>(ArgExprs.size() + !TheParsedType.get().isNull());
455
29.9M
}
456
457
/// Parse the arguments to a parameterized GNU attribute or
458
/// a C++11 attribute in "gnu" namespace.
459
void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
460
                                   SourceLocation AttrNameLoc,
461
                                   ParsedAttributes &Attrs,
462
                                   SourceLocation *EndLoc,
463
                                   IdentifierInfo *ScopeName,
464
                                   SourceLocation ScopeLoc,
465
                                   ParsedAttr::Syntax Syntax,
466
35.8M
                                   Declarator *D) {
467
468
35.8M
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
469
470
0
  ParsedAttr::Kind AttrKind =
471
35.8M
      ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
472
473
35.8M
  if (AttrKind == ParsedAttr::AT_Availability) {
474
5.85M
    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
475
5.85M
                               ScopeLoc, Syntax);
476
5.85M
    return;
477
30.0M
  } else if (AttrKind == ParsedAttr::AT_ExternalSourceSymbol) {
478
75
    ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
479
75
                                       ScopeName, ScopeLoc, Syntax);
480
75
    return;
481
30.0M
  } else if (AttrKind == ParsedAttr::AT_ObjCBridgeRelated) {
482
470
    ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
483
470
                                    ScopeName, ScopeLoc, Syntax);
484
470
    return;
485
30.0M
  } else if (AttrKind == ParsedAttr::AT_SwiftNewType) {
486
10.9k
    ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
487
10.9k
                               ScopeLoc, Syntax);
488
10.9k
    return;
489
30.0M
  } else if (AttrKind == ParsedAttr::AT_TypeTagForDatatype) {
490
179
    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
491
179
                                     ScopeName, ScopeLoc, Syntax);
492
179
    return;
493
30.0M
  } else if (attributeIsTypeArgAttr(*AttrName)) {
494
14.4k
    ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
495
14.4k
                              ScopeLoc, Syntax);
496
14.4k
    return;
497
14.4k
  }
498
499
  // These may refer to the function arguments, but need to be parsed early to
500
  // participate in determining whether it's a redeclaration.
501
29.9M
  llvm::Optional<ParseScope> PrototypeScope;
502
29.9M
  if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
503
29.9M
      
D11.3k
&&
D->isFunctionDeclarator()2.17k
) {
504
2.17k
    DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
505
2.17k
    PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
506
2.17k
                                     Scope::FunctionDeclarationScope |
507
2.17k
                                     Scope::DeclScope);
508
7.45k
    for (unsigned i = 0; i != FTI.NumParams; 
++i5.27k
) {
509
5.27k
      ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
510
5.27k
      Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
511
5.27k
    }
512
2.17k
  }
513
514
29.9M
  ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
515
29.9M
                           ScopeLoc, Syntax);
516
29.9M
}
517
518
unsigned Parser::ParseClangAttributeArgs(
519
    IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
520
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
521
159
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
522
159
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
523
524
0
  ParsedAttr::Kind AttrKind =
525
159
      ParsedAttr::getParsedKind(AttrName, ScopeName, Syntax);
526
527
159
  switch (AttrKind) {
528
133
  default:
529
133
    return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
530
133
                                    ScopeName, ScopeLoc, Syntax);
531
5
  case ParsedAttr::AT_ExternalSourceSymbol:
532
5
    ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
533
5
                                       ScopeName, ScopeLoc, Syntax);
534
5
    break;
535
8
  case ParsedAttr::AT_Availability:
536
8
    ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
537
8
                               ScopeLoc, Syntax);
538
8
    break;
539
4
  case ParsedAttr::AT_ObjCBridgeRelated:
540
4
    ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
541
4
                                    ScopeName, ScopeLoc, Syntax);
542
4
    break;
543
0
  case ParsedAttr::AT_SwiftNewType:
544
0
    ParseSwiftNewTypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
545
0
                               ScopeLoc, Syntax);
546
0
    break;
547
9
  case ParsedAttr::AT_TypeTagForDatatype:
548
9
    ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
549
9
                                     ScopeName, ScopeLoc, Syntax);
550
9
    break;
551
159
  }
552
26
  return !Attrs.empty() ? 
Attrs.begin()->getNumArgs()18
:
08
;
553
159
}
554
555
bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
556
                                        SourceLocation AttrNameLoc,
557
596
                                        ParsedAttributes &Attrs) {
558
  // If the attribute isn't known, we will not attempt to parse any
559
  // arguments.
560
596
  if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
561
596
                    getTargetInfo(), getLangOpts())) {
562
    // Eat the left paren, then skip to the ending right paren.
563
1
    ConsumeParen();
564
1
    SkipUntil(tok::r_paren);
565
1
    return false;
566
1
  }
567
568
595
  SourceLocation OpenParenLoc = Tok.getLocation();
569
570
595
  if (AttrName->getName() == "property") {
571
    // The property declspec is more complex in that it can take one or two
572
    // assignment expressions as a parameter, but the lhs of the assignment
573
    // must be named get or put.
574
575
127
    BalancedDelimiterTracker T(*this, tok::l_paren);
576
127
    T.expectAndConsume(diag::err_expected_lparen_after,
577
127
                       AttrName->getNameStart(), tok::r_paren);
578
579
127
    enum AccessorKind {
580
127
      AK_Invalid = -1,
581
127
      AK_Put = 0,
582
127
      AK_Get = 1 // indices into AccessorNames
583
127
    };
584
127
    IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
585
127
    bool HasInvalidAccessor = false;
586
587
    // Parse the accessor specifications.
588
164
    while (true) {
589
      // Stop if this doesn't look like an accessor spec.
590
164
      if (!Tok.is(tok::identifier)) {
591
        // If the user wrote a completely empty list, use a special diagnostic.
592
2
        if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
593
2
            AccessorNames[AK_Put] == nullptr &&
594
2
            AccessorNames[AK_Get] == nullptr) {
595
1
          Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
596
1
          break;
597
1
        }
598
599
1
        Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
600
1
        break;
601
2
      }
602
603
162
      AccessorKind Kind;
604
162
      SourceLocation KindLoc = Tok.getLocation();
605
162
      StringRef KindStr = Tok.getIdentifierInfo()->getName();
606
162
      if (KindStr == "get") {
607
121
        Kind = AK_Get;
608
121
      } else 
if (41
KindStr == "put"41
) {
609
38
        Kind = AK_Put;
610
611
        // Recover from the common mistake of using 'set' instead of 'put'.
612
38
      } else 
if (3
KindStr == "set"3
) {
613
1
        Diag(KindLoc, diag::err_ms_property_has_set_accessor)
614
1
            << FixItHint::CreateReplacement(KindLoc, "put");
615
1
        Kind = AK_Put;
616
617
        // Handle the mistake of forgetting the accessor kind by skipping
618
        // this accessor.
619
2
      } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
620
1
        Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
621
1
        ConsumeToken();
622
1
        HasInvalidAccessor = true;
623
1
        goto next_property_accessor;
624
625
        // Otherwise, complain about the unknown accessor kind.
626
1
      } else {
627
1
        Diag(KindLoc, diag::err_ms_property_unknown_accessor);
628
1
        HasInvalidAccessor = true;
629
1
        Kind = AK_Invalid;
630
631
        // Try to keep parsing unless it doesn't look like an accessor spec.
632
1
        if (!NextToken().is(tok::equal))
633
0
          break;
634
1
      }
635
636
      // Consume the identifier.
637
161
      ConsumeToken();
638
639
      // Consume the '='.
640
161
      if (!TryConsumeToken(tok::equal)) {
641
3
        Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
642
3
            << KindStr;
643
3
        break;
644
3
      }
645
646
      // Expect the method name.
647
158
      if (!Tok.is(tok::identifier)) {
648
1
        Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
649
1
        break;
650
1
      }
651
652
157
      if (Kind == AK_Invalid) {
653
        // Just drop invalid accessors.
654
156
      } else if (AccessorNames[Kind] != nullptr) {
655
        // Complain about the repeated accessor, ignore it, and keep parsing.
656
1
        Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
657
155
      } else {
658
155
        AccessorNames[Kind] = Tok.getIdentifierInfo();
659
155
      }
660
157
      ConsumeToken();
661
662
158
    next_property_accessor:
663
      // Keep processing accessors until we run out.
664
158
      if (TryConsumeToken(tok::comma))
665
37
        continue;
666
667
      // If we run into the ')', stop without consuming it.
668
121
      if (Tok.is(tok::r_paren))
669
120
        break;
670
671
1
      Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
672
1
      break;
673
121
    }
674
675
    // Only add the property attribute if it was well-formed.
676
127
    if (!HasInvalidAccessor)
677
125
      Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
678
125
                               AccessorNames[AK_Get], AccessorNames[AK_Put],
679
125
                               ParsedAttr::AS_Declspec);
680
127
    T.skipToEnd();
681
127
    return !HasInvalidAccessor;
682
127
  }
683
684
468
  unsigned NumArgs =
685
468
      ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
686
468
                               SourceLocation(), ParsedAttr::AS_Declspec);
687
688
  // If this attribute's args were parsed, and it was expected to have
689
  // arguments but none were provided, emit a diagnostic.
690
468
  if (!Attrs.empty() && 
Attrs.begin()->getMaxArgs()466
&&
!NumArgs465
) {
691
1
    Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
692
1
    return false;
693
1
  }
694
467
  return true;
695
468
}
696
697
/// [MS] decl-specifier:
698
///             __declspec ( extended-decl-modifier-seq )
699
///
700
/// [MS] extended-decl-modifier-seq:
701
///             extended-decl-modifier[opt]
702
///             extended-decl-modifier extended-decl-modifier-seq
703
void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
704
10.6k
                                     SourceLocation *End) {
705
10.6k
  assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
706
0
  assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
707
708
21.4k
  while (Tok.is(tok::kw___declspec)) {
709
10.8k
    ConsumeToken();
710
10.8k
    BalancedDelimiterTracker T(*this, tok::l_paren);
711
10.8k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
712
10.8k
                           tok::r_paren))
713
0
      return;
714
715
    // An empty declspec is perfectly legal and should not warn.  Additionally,
716
    // you can specify multiple attributes per declspec.
717
21.6k
    
while (10.8k
Tok.isNot(tok::r_paren)) {
718
      // Attribute not present.
719
10.8k
      if (TryConsumeToken(tok::comma))
720
3
        continue;
721
722
10.8k
      if (Tok.is(tok::code_completion)) {
723
1
        cutOffParsing();
724
1
        Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Declspec);
725
1
        return;
726
1
      }
727
728
      // We expect either a well-known identifier or a generic string.  Anything
729
      // else is a malformed declspec.
730
10.8k
      bool IsString = Tok.getKind() == tok::string_literal;
731
10.8k
      if (!IsString && 
Tok.getKind() != tok::identifier10.8k
&&
732
10.8k
          
Tok.getKind() != tok::kw_restrict2
) {
733
1
        Diag(Tok, diag::err_ms_declspec_type);
734
1
        T.skipToEnd();
735
1
        return;
736
1
      }
737
738
10.8k
      IdentifierInfo *AttrName;
739
10.8k
      SourceLocation AttrNameLoc;
740
10.8k
      if (IsString) {
741
2
        SmallString<8> StrBuffer;
742
2
        bool Invalid = false;
743
2
        StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
744
2
        if (Invalid) {
745
0
          T.skipToEnd();
746
0
          return;
747
0
        }
748
2
        AttrName = PP.getIdentifierInfo(Str);
749
2
        AttrNameLoc = ConsumeStringToken();
750
10.8k
      } else {
751
10.8k
        AttrName = Tok.getIdentifierInfo();
752
10.8k
        AttrNameLoc = ConsumeToken();
753
10.8k
      }
754
755
10.8k
      bool AttrHandled = false;
756
757
      // Parse attribute arguments.
758
10.8k
      if (Tok.is(tok::l_paren))
759
596
        AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
760
10.2k
      else if (AttrName->getName() == "property")
761
        // The property attribute must have an argument list.
762
1
        Diag(Tok.getLocation(), diag::err_expected_lparen_after)
763
1
            << AttrName->getName();
764
765
10.8k
      if (!AttrHandled)
766
10.2k
        Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
767
10.2k
                     ParsedAttr::AS_Declspec);
768
10.8k
    }
769
10.8k
    T.consumeClose();
770
10.8k
    if (End)
771
0
      *End = T.getCloseLocation();
772
10.8k
  }
773
10.6k
}
774
775
340k
void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
776
  // Treat these like attributes
777
341k
  while (true) {
778
341k
    switch (Tok.getKind()) {
779
115
    case tok::kw___fastcall:
780
282
    case tok::kw___stdcall:
781
329
    case tok::kw___thiscall:
782
436
    case tok::kw___regcall:
783
740
    case tok::kw___cdecl:
784
877
    case tok::kw___vectorcall:
785
897
    case tok::kw___ptr64:
786
898
    case tok::kw___w64:
787
938
    case tok::kw___ptr32:
788
956
    case tok::kw___sptr:
789
968
    case tok::kw___uptr: {
790
968
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
791
968
      SourceLocation AttrNameLoc = ConsumeToken();
792
968
      attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
793
968
                   ParsedAttr::AS_Keyword);
794
968
      break;
795
956
    }
796
340k
    default:
797
340k
      return;
798
341k
    }
799
341k
  }
800
340k
}
801
802
300
void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
803
300
  SourceLocation StartLoc = Tok.getLocation();
804
300
  SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
805
806
300
  if (EndLoc.isValid()) {
807
12
    SourceRange Range(StartLoc, EndLoc);
808
12
    Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
809
12
  }
810
300
}
811
812
300
SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
813
300
  SourceLocation EndLoc;
814
815
326
  while (true) {
816
326
    switch (Tok.getKind()) {
817
2
    case tok::kw_const:
818
4
    case tok::kw_volatile:
819
6
    case tok::kw___fastcall:
820
8
    case tok::kw___stdcall:
821
10
    case tok::kw___thiscall:
822
12
    case tok::kw___cdecl:
823
14
    case tok::kw___vectorcall:
824
16
    case tok::kw___ptr32:
825
18
    case tok::kw___ptr64:
826
20
    case tok::kw___w64:
827
22
    case tok::kw___unaligned:
828
24
    case tok::kw___sptr:
829
26
    case tok::kw___uptr:
830
26
      EndLoc = ConsumeToken();
831
26
      break;
832
300
    default:
833
300
      return EndLoc;
834
326
    }
835
326
  }
836
300
}
837
838
18
void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
839
  // Treat these like attributes
840
36
  while (Tok.is(tok::kw___pascal)) {
841
18
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
842
18
    SourceLocation AttrNameLoc = ConsumeToken();
843
18
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
844
18
                 ParsedAttr::AS_Keyword);
845
18
  }
846
18
}
847
848
1.14k
void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
849
  // Treat these like attributes
850
2.29k
  while (Tok.is(tok::kw___kernel)) {
851
1.14k
    IdentifierInfo *AttrName = Tok.getIdentifierInfo();
852
1.14k
    SourceLocation AttrNameLoc = ConsumeToken();
853
1.14k
    attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
854
1.14k
                 ParsedAttr::AS_Keyword);
855
1.14k
  }
856
1.14k
}
857
858
39.2k
void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
859
39.2k
  IdentifierInfo *AttrName = Tok.getIdentifierInfo();
860
39.2k
  SourceLocation AttrNameLoc = Tok.getLocation();
861
39.2k
  Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
862
39.2k
               ParsedAttr::AS_Keyword);
863
39.2k
}
864
865
658k
void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
866
  // Treat these like attributes, even though they're type specifiers.
867
1.31M
  while (true) {
868
1.31M
    switch (Tok.getKind()) {
869
103k
    case tok::kw__Nonnull:
870
629k
    case tok::kw__Nullable:
871
629k
    case tok::kw__Nullable_result:
872
658k
    case tok::kw__Null_unspecified: {
873
658k
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
874
658k
      SourceLocation AttrNameLoc = ConsumeToken();
875
658k
      if (!getLangOpts().ObjC)
876
52.6k
        Diag(AttrNameLoc, diag::ext_nullability)
877
52.6k
          << AttrName;
878
658k
      attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
879
658k
                   ParsedAttr::AS_Keyword);
880
658k
      break;
881
629k
    }
882
658k
    default:
883
658k
      return;
884
1.31M
    }
885
1.31M
  }
886
658k
}
887
888
5.65M
static bool VersionNumberSeparator(const char Separator) {
889
5.65M
  return (Separator == '.' || 
Separator == '_'89.8k
);
890
5.65M
}
891
892
/// Parse a version number.
893
///
894
/// version:
895
///   simple-integer
896
///   simple-integer '.' simple-integer
897
///   simple-integer '_' simple-integer
898
///   simple-integer '.' simple-integer '.' simple-integer
899
///   simple-integer '_' simple-integer '_' simple-integer
900
5.64M
VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
901
5.64M
  Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
902
903
5.64M
  if (!Tok.is(tok::numeric_constant)) {
904
1
    Diag(Tok, diag::err_expected_version);
905
1
    SkipUntil(tok::comma, tok::r_paren,
906
1
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
907
1
    return VersionTuple();
908
1
  }
909
910
  // Parse the major (and possibly minor and subminor) versions, which
911
  // are stored in the numeric constant. We utilize a quirk of the
912
  // lexer, which is that it handles something like 1.2.3 as a single
913
  // numeric constant, rather than two separate tokens.
914
5.64M
  SmallString<512> Buffer;
915
5.64M
  Buffer.resize(Tok.getLength()+1);
916
5.64M
  const char *ThisTokBegin = &Buffer[0];
917
918
  // Get the spelling of the token, which eliminates trigraphs, etc.
919
5.64M
  bool Invalid = false;
920
5.64M
  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
921
5.64M
  if (Invalid)
922
0
    return VersionTuple();
923
924
  // Parse the major version.
925
5.64M
  unsigned AfterMajor = 0;
926
5.64M
  unsigned Major = 0;
927
14.8M
  while (AfterMajor < ActualLength && 
isDigit(ThisTokBegin[AfterMajor])14.8M
) {
928
9.22M
    Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
929
9.22M
    ++AfterMajor;
930
9.22M
  }
931
932
5.64M
  if (AfterMajor == 0) {
933
0
    Diag(Tok, diag::err_expected_version);
934
0
    SkipUntil(tok::comma, tok::r_paren,
935
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
936
0
    return VersionTuple();
937
0
  }
938
939
5.64M
  if (AfterMajor == ActualLength) {
940
37.5k
    ConsumeToken();
941
942
    // We only had a single version component.
943
37.5k
    if (Major == 0) {
944
0
      Diag(Tok, diag::err_zero_version);
945
0
      return VersionTuple();
946
0
    }
947
948
37.5k
    return VersionTuple(Major);
949
37.5k
  }
950
951
5.60M
  const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
952
5.60M
  if (!VersionNumberSeparator(AfterMajorSeparator)
953
5.60M
      || (AfterMajor + 1 == ActualLength)) {
954
0
    Diag(Tok, diag::err_expected_version);
955
0
    SkipUntil(tok::comma, tok::r_paren,
956
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
957
0
    return VersionTuple();
958
0
  }
959
960
  // Parse the minor version.
961
5.60M
  unsigned AfterMinor = AfterMajor + 1;
962
5.60M
  unsigned Minor = 0;
963
11.7M
  while (AfterMinor < ActualLength && 
isDigit(ThisTokBegin[AfterMinor])6.15M
) {
964
6.10M
    Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
965
6.10M
    ++AfterMinor;
966
6.10M
  }
967
968
5.60M
  if (AfterMinor == ActualLength) {
969
5.55M
    ConsumeToken();
970
971
    // We had major.minor.
972
5.55M
    if (Major == 0 && 
Minor == 00
) {
973
0
      Diag(Tok, diag::err_zero_version);
974
0
      return VersionTuple();
975
0
    }
976
977
5.55M
    return VersionTuple(Major, Minor);
978
5.55M
  }
979
980
51.5k
  const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
981
  // If what follows is not a '.' or '_', we have a problem.
982
51.5k
  if (!VersionNumberSeparator(AfterMinorSeparator)) {
983
0
    Diag(Tok, diag::err_expected_version);
984
0
    SkipUntil(tok::comma, tok::r_paren,
985
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
986
0
    return VersionTuple();
987
0
  }
988
989
  // Warn if separators, be it '.' or '_', do not match.
990
51.5k
  if (AfterMajorSeparator != AfterMinorSeparator)
991
6
    Diag(Tok, diag::warn_expected_consistent_version_separator);
992
993
  // Parse the subminor version.
994
51.5k
  unsigned AfterSubminor = AfterMinor + 1;
995
51.5k
  unsigned Subminor = 0;
996
103k
  while (AfterSubminor < ActualLength && 
isDigit(ThisTokBegin[AfterSubminor])51.5k
) {
997
51.5k
    Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
998
51.5k
    ++AfterSubminor;
999
51.5k
  }
1000
1001
51.5k
  if (AfterSubminor != ActualLength) {
1002
0
    Diag(Tok, diag::err_expected_version);
1003
0
    SkipUntil(tok::comma, tok::r_paren,
1004
0
              StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
1005
0
    return VersionTuple();
1006
0
  }
1007
51.5k
  ConsumeToken();
1008
51.5k
  return VersionTuple(Major, Minor, Subminor);
1009
51.5k
}
1010
1011
/// Parse the contents of the "availability" attribute.
1012
///
1013
/// availability-attribute:
1014
///   'availability' '(' platform ',' opt-strict version-arg-list,
1015
///                      opt-replacement, opt-message')'
1016
///
1017
/// platform:
1018
///   identifier
1019
///
1020
/// opt-strict:
1021
///   'strict' ','
1022
///
1023
/// version-arg-list:
1024
///   version-arg
1025
///   version-arg ',' version-arg-list
1026
///
1027
/// version-arg:
1028
///   'introduced' '=' version
1029
///   'deprecated' '=' version
1030
///   'obsoleted' = version
1031
///   'unavailable'
1032
/// opt-replacement:
1033
///   'replacement' '=' <string>
1034
/// opt-message:
1035
///   'message' '=' <string>
1036
void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
1037
                                        SourceLocation AvailabilityLoc,
1038
                                        ParsedAttributes &attrs,
1039
                                        SourceLocation *endLoc,
1040
                                        IdentifierInfo *ScopeName,
1041
                                        SourceLocation ScopeLoc,
1042
5.85M
                                        ParsedAttr::Syntax Syntax) {
1043
5.85M
  enum { Introduced, Deprecated, Obsoleted, Unknown };
1044
5.85M
  AvailabilityChange Changes[Unknown];
1045
5.85M
  ExprResult MessageExpr, ReplacementExpr;
1046
1047
  // Opening '('.
1048
5.85M
  BalancedDelimiterTracker T(*this, tok::l_paren);
1049
5.85M
  if (T.consumeOpen()) {
1050
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1051
0
    return;
1052
0
  }
1053
1054
  // Parse the platform name.
1055
5.85M
  if (Tok.isNot(tok::identifier)) {
1056
0
    Diag(Tok, diag::err_availability_expected_platform);
1057
0
    SkipUntil(tok::r_paren, StopAtSemi);
1058
0
    return;
1059
0
  }
1060
5.85M
  IdentifierLoc *Platform = ParseIdentifierLoc();
1061
5.85M
  if (const IdentifierInfo *const Ident = Platform->Ident) {
1062
    // Canonicalize platform name from "macosx" to "macos".
1063
5.85M
    if (Ident->getName() == "macosx")
1064
908k
      Platform->Ident = PP.getIdentifierInfo("macos");
1065
    // Canonicalize platform name from "macosx_app_extension" to
1066
    // "macos_app_extension".
1067
4.94M
    else if (Ident->getName() == "macosx_app_extension")
1068
4
      Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
1069
4.94M
    else
1070
4.94M
      Platform->Ident = PP.getIdentifierInfo(
1071
4.94M
          AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
1072
5.85M
  }
1073
1074
  // Parse the ',' following the platform name.
1075
5.85M
  if (ExpectAndConsume(tok::comma)) {
1076
0
    SkipUntil(tok::r_paren, StopAtSemi);
1077
0
    return;
1078
0
  }
1079
1080
  // If we haven't grabbed the pointers for the identifiers
1081
  // "introduced", "deprecated", and "obsoleted", do so now.
1082
5.85M
  if (!Ident_introduced) {
1083
1.87k
    Ident_introduced = PP.getIdentifierInfo("introduced");
1084
1.87k
    Ident_deprecated = PP.getIdentifierInfo("deprecated");
1085
1.87k
    Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
1086
1.87k
    Ident_unavailable = PP.getIdentifierInfo("unavailable");
1087
1.87k
    Ident_message = PP.getIdentifierInfo("message");
1088
1.87k
    Ident_strict = PP.getIdentifierInfo("strict");
1089
1.87k
    Ident_replacement = PP.getIdentifierInfo("replacement");
1090
1.87k
  }
1091
1092
  // Parse the optional "strict", the optional "replacement" and the set of
1093
  // introductions/deprecations/removals.
1094
5.85M
  SourceLocation UnavailableLoc, StrictLoc;
1095
7.41M
  do {
1096
7.41M
    if (Tok.isNot(tok::identifier)) {
1097
0
      Diag(Tok, diag::err_availability_expected_change);
1098
0
      SkipUntil(tok::r_paren, StopAtSemi);
1099
0
      return;
1100
0
    }
1101
7.41M
    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1102
7.41M
    SourceLocation KeywordLoc = ConsumeToken();
1103
1104
7.41M
    if (Keyword == Ident_strict) {
1105
5
      if (StrictLoc.isValid()) {
1106
0
        Diag(KeywordLoc, diag::err_availability_redundant)
1107
0
          << Keyword << SourceRange(StrictLoc);
1108
0
      }
1109
5
      StrictLoc = KeywordLoc;
1110
5
      continue;
1111
5
    }
1112
1113
7.41M
    if (Keyword == Ident_unavailable) {
1114
1.17M
      if (UnavailableLoc.isValid()) {
1115
1
        Diag(KeywordLoc, diag::err_availability_redundant)
1116
1
          << Keyword << SourceRange(UnavailableLoc);
1117
1
      }
1118
1.17M
      UnavailableLoc = KeywordLoc;
1119
1.17M
      continue;
1120
1.17M
    }
1121
1122
6.24M
    if (Keyword == Ident_deprecated && 
Platform->Ident1.01M
&&
1123
6.24M
        
Platform->Ident->isStr("swift")1.01M
) {
1124
      // For swift, we deprecate for all versions.
1125
3
      if (Changes[Deprecated].KeywordLoc.isValid()) {
1126
0
        Diag(KeywordLoc, diag::err_availability_redundant)
1127
0
          << Keyword
1128
0
          << SourceRange(Changes[Deprecated].KeywordLoc);
1129
0
      }
1130
1131
3
      Changes[Deprecated].KeywordLoc = KeywordLoc;
1132
      // Use a fake version here.
1133
3
      Changes[Deprecated].Version = VersionTuple(1);
1134
3
      continue;
1135
3
    }
1136
1137
6.24M
    if (Tok.isNot(tok::equal)) {
1138
1
      Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
1139
1
      SkipUntil(tok::r_paren, StopAtSemi);
1140
1
      return;
1141
1
    }
1142
6.24M
    ConsumeToken();
1143
6.24M
    if (Keyword == Ident_message || 
Keyword == Ident_replacement5.72M
) {
1144
596k
      if (Tok.isNot(tok::string_literal)) {
1145
5
        Diag(Tok, diag::err_expected_string_literal)
1146
5
          << /*Source='availability attribute'*/2;
1147
5
        SkipUntil(tok::r_paren, StopAtSemi);
1148
5
        return;
1149
5
      }
1150
596k
      if (Keyword == Ident_message)
1151
516k
        MessageExpr = ParseStringLiteralExpression();
1152
80.1k
      else
1153
80.1k
        ReplacementExpr = ParseStringLiteralExpression();
1154
      // Also reject wide string literals.
1155
596k
      if (StringLiteral *MessageStringLiteral =
1156
596k
              cast_or_null<StringLiteral>(MessageExpr.get())) {
1157
516k
        if (!MessageStringLiteral->isAscii()) {
1158
4
          Diag(MessageStringLiteral->getSourceRange().getBegin(),
1159
4
               diag::err_expected_string_literal)
1160
4
            << /*Source='availability attribute'*/ 2;
1161
4
          SkipUntil(tok::r_paren, StopAtSemi);
1162
4
          return;
1163
4
        }
1164
516k
      }
1165
596k
      if (Keyword == Ident_message)
1166
516k
        break;
1167
80.1k
      else
1168
80.1k
        continue;
1169
596k
    }
1170
1171
    // Special handling of 'NA' only when applied to introduced or
1172
    // deprecated.
1173
5.64M
    if ((Keyword == Ident_introduced || 
Keyword == Ident_deprecated1.01M
) &&
1174
5.64M
        
Tok.is(tok::identifier)5.64M
) {
1175
6.14k
      IdentifierInfo *NA = Tok.getIdentifierInfo();
1176
6.14k
      if (NA->getName() == "NA") {
1177
6.14k
        ConsumeToken();
1178
6.14k
        if (Keyword == Ident_introduced)
1179
6.13k
          UnavailableLoc = KeywordLoc;
1180
6.14k
        continue;
1181
6.14k
      }
1182
6.14k
    }
1183
1184
5.64M
    SourceRange VersionRange;
1185
5.64M
    VersionTuple Version = ParseVersionTuple(VersionRange);
1186
1187
5.64M
    if (Version.empty()) {
1188
0
      SkipUntil(tok::r_paren, StopAtSemi);
1189
0
      return;
1190
0
    }
1191
1192
5.64M
    unsigned Index;
1193
5.64M
    if (Keyword == Ident_introduced)
1194
4.62M
      Index = Introduced;
1195
1.01M
    else if (Keyword == Ident_deprecated)
1196
1.01M
      Index = Deprecated;
1197
46
    else if (Keyword == Ident_obsoleted)
1198
45
      Index = Obsoleted;
1199
1
    else
1200
1
      Index = Unknown;
1201
1202
5.64M
    if (Index < Unknown) {
1203
5.64M
      if (!Changes[Index].KeywordLoc.isInvalid()) {
1204
1
        Diag(KeywordLoc, diag::err_availability_redundant)
1205
1
          << Keyword
1206
1
          << SourceRange(Changes[Index].KeywordLoc,
1207
1
                         Changes[Index].VersionRange.getEnd());
1208
1
      }
1209
1210
5.64M
      Changes[Index].KeywordLoc = KeywordLoc;
1211
5.64M
      Changes[Index].Version = Version;
1212
5.64M
      Changes[Index].VersionRange = VersionRange;
1213
5.64M
    } else {
1214
1
      Diag(KeywordLoc, diag::err_availability_unknown_change)
1215
1
        << Keyword << VersionRange;
1216
1
    }
1217
1218
6.90M
  } while (TryConsumeToken(tok::comma));
1219
1220
  // Closing ')'.
1221
5.85M
  if (T.consumeClose())
1222
1
    return;
1223
1224
5.85M
  if (endLoc)
1225
5.85M
    *endLoc = T.getCloseLocation();
1226
1227
  // The 'unavailable' availability cannot be combined with any other
1228
  // availability changes. Make sure that hasn't happened.
1229
5.85M
  if (UnavailableLoc.isValid()) {
1230
1.18M
    bool Complained = false;
1231
4.72M
    for (unsigned Index = Introduced; Index != Unknown; 
++Index3.54M
) {
1232
3.54M
      if (Changes[Index].KeywordLoc.isValid()) {
1233
1
        if (!Complained) {
1234
1
          Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
1235
1
            << SourceRange(Changes[Index].KeywordLoc,
1236
1
                           Changes[Index].VersionRange.getEnd());
1237
1
          Complained = true;
1238
1
        }
1239
1240
        // Clear out the availability.
1241
1
        Changes[Index] = AvailabilityChange();
1242
1
      }
1243
3.54M
    }
1244
1.18M
  }
1245
1246
  // Record this attribute
1247
5.85M
  attrs.addNew(&Availability,
1248
5.85M
               SourceRange(AvailabilityLoc, T.getCloseLocation()),
1249
5.85M
               ScopeName, ScopeLoc,
1250
5.85M
               Platform,
1251
5.85M
               Changes[Introduced],
1252
5.85M
               Changes[Deprecated],
1253
5.85M
               Changes[Obsoleted],
1254
5.85M
               UnavailableLoc, MessageExpr.get(),
1255
5.85M
               Syntax, StrictLoc, ReplacementExpr.get());
1256
5.85M
}
1257
1258
/// Parse the contents of the "external_source_symbol" attribute.
1259
///
1260
/// external-source-symbol-attribute:
1261
///   'external_source_symbol' '(' keyword-arg-list ')'
1262
///
1263
/// keyword-arg-list:
1264
///   keyword-arg
1265
///   keyword-arg ',' keyword-arg-list
1266
///
1267
/// keyword-arg:
1268
///   'language' '=' <string>
1269
///   'defined_in' '=' <string>
1270
///   'generated_declaration'
1271
void Parser::ParseExternalSourceSymbolAttribute(
1272
    IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
1273
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1274
80
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1275
  // Opening '('.
1276
80
  BalancedDelimiterTracker T(*this, tok::l_paren);
1277
80
  if (T.expectAndConsume())
1278
0
    return;
1279
1280
  // Initialize the pointers for the keyword identifiers when required.
1281
80
  if (!Ident_language) {
1282
24
    Ident_language = PP.getIdentifierInfo("language");
1283
24
    Ident_defined_in = PP.getIdentifierInfo("defined_in");
1284
24
    Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
1285
24
  }
1286
1287
80
  ExprResult Language;
1288
80
  bool HasLanguage = false;
1289
80
  ExprResult DefinedInExpr;
1290
80
  bool HasDefinedIn = false;
1291
80
  IdentifierLoc *GeneratedDeclaration = nullptr;
1292
1293
  // Parse the language/defined_in/generated_declaration keywords
1294
177
  do {
1295
177
    if (Tok.isNot(tok::identifier)) {
1296
5
      Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1297
5
      SkipUntil(tok::r_paren, StopAtSemi);
1298
5
      return;
1299
5
    }
1300
1301
172
    SourceLocation KeywordLoc = Tok.getLocation();
1302
172
    IdentifierInfo *Keyword = Tok.getIdentifierInfo();
1303
172
    if (Keyword == Ident_generated_declaration) {
1304
41
      if (GeneratedDeclaration) {
1305
4
        Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
1306
4
        SkipUntil(tok::r_paren, StopAtSemi);
1307
4
        return;
1308
4
      }
1309
37
      GeneratedDeclaration = ParseIdentifierLoc();
1310
37
      continue;
1311
41
    }
1312
1313
131
    if (Keyword != Ident_language && 
Keyword != Ident_defined_in64
) {
1314
2
      Diag(Tok, diag::err_external_source_symbol_expected_keyword);
1315
2
      SkipUntil(tok::r_paren, StopAtSemi);
1316
2
      return;
1317
2
    }
1318
1319
129
    ConsumeToken();
1320
129
    if (ExpectAndConsume(tok::equal, diag::err_expected_after,
1321
129
                         Keyword->getName())) {
1322
1
      SkipUntil(tok::r_paren, StopAtSemi);
1323
1
      return;
1324
1
    }
1325
1326
128
    bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
1327
128
    if (Keyword == Ident_language)
1328
66
      HasLanguage = true;
1329
62
    else
1330
62
      HasDefinedIn = true;
1331
1332
128
    if (Tok.isNot(tok::string_literal)) {
1333
9
      Diag(Tok, diag::err_expected_string_literal)
1334
9
          << /*Source='external_source_symbol attribute'*/ 3
1335
9
          << /*language | source container*/ (Keyword != Ident_language);
1336
9
      SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
1337
9
      continue;
1338
9
    }
1339
119
    if (Keyword == Ident_language) {
1340
61
      if (HadLanguage) {
1341
2
        Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1342
2
            << Keyword;
1343
2
        ParseStringLiteralExpression();
1344
2
        continue;
1345
2
      }
1346
59
      Language = ParseStringLiteralExpression();
1347
59
    } else {
1348
58
      assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
1349
58
      if (HadDefinedIn) {
1350
2
        Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
1351
2
            << Keyword;
1352
2
        ParseStringLiteralExpression();
1353
2
        continue;
1354
2
      }
1355
56
      DefinedInExpr = ParseStringLiteralExpression();
1356
56
    }
1357
165
  } while (TryConsumeToken(tok::comma));
1358
1359
  // Closing ')'.
1360
68
  if (T.consumeClose())
1361
3
    return;
1362
65
  if (EndLoc)
1363
63
    *EndLoc = T.getCloseLocation();
1364
1365
65
  ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
1366
65
                      GeneratedDeclaration};
1367
65
  Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
1368
65
               ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1369
65
}
1370
1371
/// Parse the contents of the "objc_bridge_related" attribute.
1372
/// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
1373
/// related_class:
1374
///     Identifier
1375
///
1376
/// opt-class_method:
1377
///     Identifier: | <empty>
1378
///
1379
/// opt-instance_method:
1380
///     Identifier | <empty>
1381
///
1382
void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
1383
                                SourceLocation ObjCBridgeRelatedLoc,
1384
                                ParsedAttributes &attrs,
1385
                                SourceLocation *endLoc,
1386
                                IdentifierInfo *ScopeName,
1387
                                SourceLocation ScopeLoc,
1388
474
                                ParsedAttr::Syntax Syntax) {
1389
  // Opening '('.
1390
474
  BalancedDelimiterTracker T(*this, tok::l_paren);
1391
474
  if (T.consumeOpen()) {
1392
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1393
0
    return;
1394
0
  }
1395
1396
  // Parse the related class name.
1397
474
  if (Tok.isNot(tok::identifier)) {
1398
4
    Diag(Tok, diag::err_objcbridge_related_expected_related_class);
1399
4
    SkipUntil(tok::r_paren, StopAtSemi);
1400
4
    return;
1401
4
  }
1402
470
  IdentifierLoc *RelatedClass = ParseIdentifierLoc();
1403
470
  if (ExpectAndConsume(tok::comma)) {
1404
0
    SkipUntil(tok::r_paren, StopAtSemi);
1405
0
    return;
1406
0
  }
1407
1408
  // Parse class method name.  It's non-optional in the sense that a trailing
1409
  // comma is required, but it can be the empty string, and then we record a
1410
  // nullptr.
1411
470
  IdentifierLoc *ClassMethod = nullptr;
1412
470
  if (Tok.is(tok::identifier)) {
1413
21
    ClassMethod = ParseIdentifierLoc();
1414
21
    if (!TryConsumeToken(tok::colon)) {
1415
2
      Diag(Tok, diag::err_objcbridge_related_selector_name);
1416
2
      SkipUntil(tok::r_paren, StopAtSemi);
1417
2
      return;
1418
2
    }
1419
21
  }
1420
468
  if (!TryConsumeToken(tok::comma)) {
1421
2
    if (Tok.is(tok::colon))
1422
1
      Diag(Tok, diag::err_objcbridge_related_selector_name);
1423
1
    else
1424
1
      Diag(Tok, diag::err_expected) << tok::comma;
1425
2
    SkipUntil(tok::r_paren, StopAtSemi);
1426
2
    return;
1427
2
  }
1428
1429
  // Parse instance method name.  Also non-optional but empty string is
1430
  // permitted.
1431
466
  IdentifierLoc *InstanceMethod = nullptr;
1432
466
  if (Tok.is(tok::identifier))
1433
19
    InstanceMethod = ParseIdentifierLoc();
1434
447
  else if (Tok.isNot(tok::r_paren)) {
1435
1
    Diag(Tok, diag::err_expected) << tok::r_paren;
1436
1
    SkipUntil(tok::r_paren, StopAtSemi);
1437
1
    return;
1438
1
  }
1439
1440
  // Closing ')'.
1441
465
  if (T.consumeClose())
1442
0
    return;
1443
1444
465
  if (endLoc)
1445
465
    *endLoc = T.getCloseLocation();
1446
1447
  // Record this attribute
1448
465
  attrs.addNew(&ObjCBridgeRelated,
1449
465
               SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
1450
465
               ScopeName, ScopeLoc,
1451
465
               RelatedClass,
1452
465
               ClassMethod,
1453
465
               InstanceMethod,
1454
465
               Syntax);
1455
465
}
1456
1457
1458
void Parser::ParseSwiftNewTypeAttribute(
1459
    IdentifierInfo &AttrName, SourceLocation AttrNameLoc,
1460
    ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
1461
10.9k
    SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax) {
1462
10.9k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1463
1464
  // Opening '('
1465
10.9k
  if (T.consumeOpen()) {
1466
0
    Diag(Tok, diag::err_expected) << tok::l_paren;
1467
0
    return;
1468
0
  }
1469
1470
10.9k
  if (Tok.is(tok::r_paren)) {
1471
1
    Diag(Tok.getLocation(), diag::err_argument_required_after_attribute);
1472
1
    T.consumeClose();
1473
1
    return;
1474
1
  }
1475
10.9k
  if (Tok.isNot(tok::kw_struct) && 
Tok.isNot(tok::kw_enum)5.36k
) {
1476
2
    Diag(Tok, diag::warn_attribute_type_not_supported)
1477
2
        << &AttrName << Tok.getIdentifierInfo();
1478
2
    if (!isTokenSpecial())
1479
2
      ConsumeToken();
1480
2
    T.consumeClose();
1481
2
    return;
1482
2
  }
1483
1484
10.9k
  auto *SwiftType = IdentifierLoc::create(Actions.Context, Tok.getLocation(),
1485
10.9k
                                          Tok.getIdentifierInfo());
1486
10.9k
  ConsumeToken();
1487
1488
  // Closing ')'
1489
10.9k
  if (T.consumeClose())
1490
0
    return;
1491
10.9k
  if (EndLoc)
1492
10.9k
    *EndLoc = T.getCloseLocation();
1493
1494
10.9k
  ArgsUnion Args[] = {SwiftType};
1495
10.9k
  Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, T.getCloseLocation()),
1496
10.9k
               ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
1497
10.9k
}
1498
1499
1500
void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
1501
                                              SourceLocation AttrNameLoc,
1502
                                              ParsedAttributes &Attrs,
1503
                                              SourceLocation *EndLoc,
1504
                                              IdentifierInfo *ScopeName,
1505
                                              SourceLocation ScopeLoc,
1506
188
                                              ParsedAttr::Syntax Syntax) {
1507
188
  assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
1508
1509
0
  BalancedDelimiterTracker T(*this, tok::l_paren);
1510
188
  T.consumeOpen();
1511
1512
188
  if (Tok.isNot(tok::identifier)) {
1513
0
    Diag(Tok, diag::err_expected) << tok::identifier;
1514
0
    T.skipToEnd();
1515
0
    return;
1516
0
  }
1517
188
  IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
1518
1519
188
  if (ExpectAndConsume(tok::comma)) {
1520
0
    T.skipToEnd();
1521
0
    return;
1522
0
  }
1523
1524
188
  SourceRange MatchingCTypeRange;
1525
188
  TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
1526
188
  if (MatchingCType.isInvalid()) {
1527
8
    T.skipToEnd();
1528
8
    return;
1529
8
  }
1530
1531
180
  bool LayoutCompatible = false;
1532
180
  bool MustBeNull = false;
1533
233
  while (TryConsumeToken(tok::comma)) {
1534
65
    if (Tok.isNot(tok::identifier)) {
1535
4
      Diag(Tok, diag::err_expected) << tok::identifier;
1536
4
      T.skipToEnd();
1537
4
      return;
1538
4
    }
1539
61
    IdentifierInfo *Flag = Tok.getIdentifierInfo();
1540
61
    if (Flag->isStr("layout_compatible"))
1541
46
      LayoutCompatible = true;
1542
15
    else if (Flag->isStr("must_be_null"))
1543
7
      MustBeNull = true;
1544
8
    else {
1545
8
      Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
1546
8
      T.skipToEnd();
1547
8
      return;
1548
8
    }
1549
53
    ConsumeToken(); // consume flag
1550
53
  }
1551
1552
168
  if (!T.consumeClose()) {
1553
168
    Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
1554
168
                                   ArgumentKind, MatchingCType.get(),
1555
168
                                   LayoutCompatible, MustBeNull, Syntax);
1556
168
  }
1557
1558
168
  if (EndLoc)
1559
168
    *EndLoc = T.getCloseLocation();
1560
168
}
1561
1562
/// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
1563
/// of a C++11 attribute-specifier in a location where an attribute is not
1564
/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
1565
/// situation.
1566
///
1567
/// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
1568
/// this doesn't appear to actually be an attribute-specifier, and the caller
1569
/// should try to parse it.
1570
12
bool Parser::DiagnoseProhibitedCXX11Attribute() {
1571
12
  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
1572
1573
0
  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
1574
4
  case CAK_NotAttributeSpecifier:
1575
    // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
1576
4
    return false;
1577
1578
4
  case CAK_InvalidAttributeSpecifier:
1579
4
    Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
1580
4
    return false;
1581
1582
4
  case CAK_AttributeSpecifier:
1583
    // Parse and discard the attributes.
1584
4
    SourceLocation BeginLoc = ConsumeBracket();
1585
4
    ConsumeBracket();
1586
4
    SkipUntil(tok::r_square);
1587
4
    assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
1588
0
    SourceLocation EndLoc = ConsumeBracket();
1589
4
    Diag(BeginLoc, diag::err_attributes_not_allowed)
1590
4
      << SourceRange(BeginLoc, EndLoc);
1591
4
    return true;
1592
12
  }
1593
0
  llvm_unreachable("All cases handled above.");
1594
0
}
1595
1596
/// We have found the opening square brackets of a C++11
1597
/// attribute-specifier in a location where an attribute is not permitted, but
1598
/// we know where the attributes ought to be written. Parse them anyway, and
1599
/// provide a fixit moving them to the right place.
1600
void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
1601
24
                                             SourceLocation CorrectLocation) {
1602
24
  assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
1603
24
         Tok.is(tok::kw_alignas));
1604
1605
  // Consume the attributes.
1606
0
  SourceLocation Loc = Tok.getLocation();
1607
24
  ParseCXX11Attributes(Attrs);
1608
24
  CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
1609
  // FIXME: use err_attributes_misplaced
1610
24
  Diag(Loc, diag::err_attributes_not_allowed)
1611
24
    << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1612
24
    << FixItHint::CreateRemoval(AttrRange);
1613
24
}
1614
1615
void Parser::DiagnoseProhibitedAttributes(
1616
112
    const SourceRange &Range, const SourceLocation CorrectLocation) {
1617
112
  if (CorrectLocation.isValid()) {
1618
13
    CharSourceRange AttrRange(Range, true);
1619
13
    Diag(CorrectLocation, diag::err_attributes_misplaced)
1620
13
        << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
1621
13
        << FixItHint::CreateRemoval(AttrRange);
1622
13
  } else
1623
99
    Diag(Range.getBegin(), diag::err_attributes_not_allowed) << Range;
1624
112
}
1625
1626
void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
1627
1.04M
                                     unsigned DiagID, bool DiagnoseEmptyAttrs) {
1628
1629
1.04M
  if (DiagnoseEmptyAttrs && 
Attrs.empty()1.03M
&&
Attrs.Range.isValid()998k
) {
1630
    // An attribute list has been parsed, but it was empty.
1631
    // This is the case for [[]].
1632
25
    const auto &LangOpts = getLangOpts();
1633
25
    auto &SM = PP.getSourceManager();
1634
25
    Token FirstLSquare;
1635
25
    Lexer::getRawToken(Attrs.Range.getBegin(), FirstLSquare, SM, LangOpts);
1636
1637
25
    if (FirstLSquare.is(tok::l_square)) {
1638
12
      llvm::Optional<Token> SecondLSquare =
1639
12
          Lexer::findNextToken(FirstLSquare.getLocation(), SM, LangOpts);
1640
1641
12
      if (SecondLSquare && SecondLSquare->is(tok::l_square)) {
1642
        // The attribute range starts with [[, but is empty. So this must
1643
        // be [[]], which we are supposed to diagnose because
1644
        // DiagnoseEmptyAttrs is true.
1645
12
        Diag(Attrs.Range.getBegin(), DiagID) << Attrs.Range;
1646
12
        return;
1647
12
      }
1648
12
    }
1649
25
  }
1650
1651
1.04M
  for (const ParsedAttr &AL : Attrs) {
1652
40.5k
    if (!AL.isCXX11Attribute() && 
!AL.isC2xAttribute()40.5k
)
1653
40.5k
      continue;
1654
30
    if (AL.getKind() == ParsedAttr::UnknownAttribute)
1655
7
      Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
1656
7
          << AL << AL.getRange();
1657
23
    else {
1658
23
      Diag(AL.getLoc(), DiagID) << AL;
1659
23
      AL.setInvalid();
1660
23
    }
1661
30
  }
1662
1.04M
}
1663
1664
274k
void Parser::DiagnoseCXX11AttributeExtension(ParsedAttributesWithRange &Attrs) {
1665
274k
  for (const ParsedAttr &PA : Attrs) {
1666
117k
    if (PA.isCXX11Attribute() || 
PA.isC2xAttribute()117k
)
1667
20
      Diag(PA.getLoc(), diag::ext_cxx11_attr_placement) << PA << PA.getRange();
1668
117k
  }
1669
274k
}
1670
1671
// Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
1672
// applies to var, not the type Foo.
1673
// As an exception to the rule, __declspec(align(...)) before the
1674
// class-key affects the type instead of the variable.
1675
// Also, Microsoft-style [attributes] seem to affect the type instead of the
1676
// variable.
1677
// This function moves attributes that should apply to the type off DS to Attrs.
1678
void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
1679
                                            DeclSpec &DS,
1680
2.49M
                                            Sema::TagUseKind TUK) {
1681
2.49M
  if (TUK == Sema::TUK_Reference)
1682
1.08M
    return;
1683
1684
1.40M
  llvm::SmallVector<ParsedAttr *, 1> ToBeMoved;
1685
1686
1.40M
  for (ParsedAttr &AL : DS.getAttributes()) {
1687
244
    if ((AL.getKind() == ParsedAttr::AT_Aligned &&
1688
244
         
AL.isDeclspecAttribute()49
) ||
1689
244
        
AL.isMicrosoftAttribute()236
)
1690
59
      ToBeMoved.push_back(&AL);
1691
244
  }
1692
1693
1.40M
  for (ParsedAttr *AL : ToBeMoved) {
1694
59
    DS.getAttributes().remove(AL);
1695
59
    Attrs.addAtEnd(AL);
1696
59
  }
1697
1.40M
}
1698
1699
/// ParseDeclaration - Parse a full 'declaration', which consists of
1700
/// declaration-specifiers, some number of declarators, and a semicolon.
1701
/// 'Context' should be a DeclaratorContext value.  This returns the
1702
/// location of the semicolon in DeclEnd.
1703
///
1704
///       declaration: [C99 6.7]
1705
///         block-declaration ->
1706
///           simple-declaration
1707
///           others                   [FIXME]
1708
/// [C++]   template-declaration
1709
/// [C++]   namespace-definition
1710
/// [C++]   using-directive
1711
/// [C++]   using-declaration
1712
/// [C++11/C11] static_assert-declaration
1713
///         others... [FIXME]
1714
///
1715
Parser::DeclGroupPtrTy
1716
Parser::ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd,
1717
                         ParsedAttributesWithRange &attrs,
1718
4.47M
                         SourceLocation *DeclSpecStart) {
1719
4.47M
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
1720
  // Must temporarily exit the objective-c container scope for
1721
  // parsing c none objective-c decls.
1722
4.47M
  ObjCDeclContextSwitch ObjCDC(*this);
1723
1724
4.47M
  Decl *SingleDecl = nullptr;
1725
4.47M
  switch (Tok.getKind()) {
1726
1.02M
  case tok::kw_template:
1727
1.02M
  case tok::kw_export:
1728
1.02M
    ProhibitAttributes(attrs);
1729
1.02M
    SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd, attrs);
1730
1.02M
    break;
1731
105k
  case tok::kw_inline:
1732
    // Could be the start of an inline namespace. Allowed as an ext in C++03.
1733
105k
    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
1734
105k
      ProhibitAttributes(attrs);
1735
105k
      SourceLocation InlineLoc = ConsumeToken();
1736
105k
      return ParseNamespace(Context, DeclEnd, InlineLoc);
1737
105k
    }
1738
6
    return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1739
6
                                  DeclSpecStart);
1740
144k
  case tok::kw_namespace:
1741
144k
    ProhibitAttributes(attrs);
1742
144k
    return ParseNamespace(Context, DeclEnd);
1743
147k
  case tok::kw_using:
1744
147k
    return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
1745
147k
                                            DeclEnd, attrs);
1746
23.9k
  case tok::kw_static_assert:
1747
26.7k
  case tok::kw__Static_assert:
1748
26.7k
    ProhibitAttributes(attrs);
1749
26.7k
    SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
1750
26.7k
    break;
1751
3.03M
  default:
1752
3.03M
    return ParseSimpleDeclaration(Context, DeclEnd, attrs, true, nullptr,
1753
3.03M
                                  DeclSpecStart);
1754
4.47M
  }
1755
1756
  // This routine returns a DeclGroup, if the thing we parsed only contains a
1757
  // single decl, convert it now.
1758
1.04M
  return Actions.ConvertDeclToDeclGroup(SingleDecl);
1759
4.47M
}
1760
1761
///       simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
1762
///         declaration-specifiers init-declarator-list[opt] ';'
1763
/// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
1764
///             init-declarator-list ';'
1765
///[C90/C++]init-declarator-list ';'                             [TODO]
1766
/// [OMP]   threadprivate-directive
1767
/// [OMP]   allocate-directive                                   [TODO]
1768
///
1769
///       for-range-declaration: [C++11 6.5p1: stmt.ranged]
1770
///         attribute-specifier-seq[opt] type-specifier-seq declarator
1771
///
1772
/// If RequireSemi is false, this does not check for a ';' at the end of the
1773
/// declaration.  If it is true, it checks for and eats it.
1774
///
1775
/// If FRI is non-null, we might be parsing a for-range-declaration instead
1776
/// of a simple-declaration. If we find that we are, we also parse the
1777
/// for-range-initializer, and place it here.
1778
///
1779
/// DeclSpecStart is used when decl-specifiers are parsed before parsing
1780
/// the Declaration. The SourceLocation for this Decl is set to
1781
/// DeclSpecStart if DeclSpecStart is non-null.
1782
Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(
1783
    DeclaratorContext Context, SourceLocation &DeclEnd,
1784
    ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI,
1785
3.15M
    SourceLocation *DeclSpecStart) {
1786
  // Parse the common declaration-specifiers piece.
1787
3.15M
  ParsingDeclSpec DS(*this);
1788
1789
3.15M
  DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
1790
3.15M
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
1791
1792
  // If we had a free-standing type definition with a missing semicolon, we
1793
  // may get this far before the problem becomes obvious.
1794
3.15M
  if (DS.hasTagDefinition() &&
1795
3.15M
      
DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext)288k
)
1796
0
    return nullptr;
1797
1798
  // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
1799
  // declaration-specifiers init-declarator-list[opt] ';'
1800
3.15M
  if (Tok.is(tok::semi)) {
1801
31.9k
    ProhibitAttributes(Attrs);
1802
31.9k
    DeclEnd = Tok.getLocation();
1803
31.9k
    if (RequireSemi) 
ConsumeToken()31.9k
;
1804
31.9k
    RecordDecl *AnonRecord = nullptr;
1805
31.9k
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
1806
31.9k
                                                       DS, AnonRecord);
1807
31.9k
    DS.complete(TheDecl);
1808
31.9k
    if (AnonRecord) {
1809
36
      Decl* decls[] = {AnonRecord, TheDecl};
1810
36
      return Actions.BuildDeclaratorGroup(decls);
1811
36
    }
1812
31.9k
    return Actions.ConvertDeclToDeclGroup(TheDecl);
1813
31.9k
  }
1814
1815
3.12M
  if (DeclSpecStart)
1816
2.39k
    DS.SetRangeStart(*DeclSpecStart);
1817
1818
3.12M
  DS.takeAttributesFrom(Attrs);
1819
3.12M
  return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
1820
3.15M
}
1821
1822
/// Returns true if this might be the start of a declarator, or a common typo
1823
/// for a declarator.
1824
134k
bool Parser::MightBeDeclarator(DeclaratorContext Context) {
1825
134k
  switch (Tok.getKind()) {
1826
0
  case tok::annot_cxxscope:
1827
0
  case tok::annot_template_id:
1828
0
  case tok::caret:
1829
0
  case tok::code_completion:
1830
0
  case tok::coloncolon:
1831
0
  case tok::ellipsis:
1832
3
  case tok::kw___attribute:
1833
6
  case tok::kw_operator:
1834
11
  case tok::l_paren:
1835
18
  case tok::star:
1836
18
    return true;
1837
1838
18
  case tok::amp:
1839
21
  case tok::ampamp:
1840
21
    return getLangOpts().CPlusPlus;
1841
1842
0
  case tok::l_square: // Might be an attribute on an unnamed bit-field.
1843
0
    return Context == DeclaratorContext::Member && getLangOpts().CPlusPlus11 &&
1844
0
           NextToken().is(tok::l_square);
1845
1846
1.92k
  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
1847
1.92k
    return Context == DeclaratorContext::Member || 
getLangOpts().CPlusPlus0
;
1848
1849
132k
  case tok::identifier:
1850
132k
    switch (NextToken().getKind()) {
1851
0
    case tok::code_completion:
1852
18
    case tok::coloncolon:
1853
14.9k
    case tok::comma:
1854
15.8k
    case tok::equal:
1855
15.8k
    case tok::equalequal: // Might be a typo for '='.
1856
15.8k
    case tok::kw_alignas:
1857
15.8k
    case tok::kw_asm:
1858
112k
    case tok::kw___attribute:
1859
112k
    case tok::l_brace:
1860
112k
    case tok::l_paren:
1861
112k
    case tok::l_square:
1862
112k
    case tok::less:
1863
112k
    case tok::r_brace:
1864
112k
    case tok::r_paren:
1865
112k
    case tok::r_square:
1866
113k
    case tok::semi:
1867
113k
      return true;
1868
1869
18.6k
    case tok::colon:
1870
      // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
1871
      // and in block scope it's probably a label. Inside a class definition,
1872
      // this is a bit-field.
1873
18.6k
      return Context == DeclaratorContext::Member ||
1874
18.6k
             
(3
getLangOpts().CPlusPlus3
&&
Context == DeclaratorContext::File3
);
1875
1876
18
    case tok::identifier: // Possible virt-specifier.
1877
18
      return getLangOpts().CPlusPlus11 && 
isCXX11VirtSpecifier(NextToken())14
;
1878
1879
10
    default:
1880
10
      return false;
1881
132k
    }
1882
1883
56
  default:
1884
56
    return false;
1885
134k
  }
1886
134k
}
1887
1888
/// Skip until we reach something which seems like a sensible place to pick
1889
/// up parsing after a malformed declaration. This will sometimes stop sooner
1890
/// than SkipUntil(tok::r_brace) would, but will never stop later.
1891
492
void Parser::SkipMalformedDecl() {
1892
1.10k
  while (true) {
1893
1.10k
    switch (Tok.getKind()) {
1894
77
    case tok::l_brace:
1895
      // Skip until matching }, then stop. We've probably skipped over
1896
      // a malformed class or function definition or similar.
1897
77
      ConsumeBrace();
1898
77
      SkipUntil(tok::r_brace);
1899
77
      if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
1900
        // This declaration isn't over yet. Keep skipping.
1901
4
        continue;
1902
4
      }
1903
73
      TryConsumeToken(tok::semi);
1904
73
      return;
1905
1906
0
    case tok::l_square:
1907
0
      ConsumeBracket();
1908
0
      SkipUntil(tok::r_square);
1909
0
      continue;
1910
1911
43
    case tok::l_paren:
1912
43
      ConsumeParen();
1913
43
      SkipUntil(tok::r_paren);
1914
43
      continue;
1915
1916
10
    case tok::r_brace:
1917
10
      return;
1918
1919
266
    case tok::semi:
1920
266
      ConsumeToken();
1921
266
      return;
1922
1923
2
    case tok::kw_inline:
1924
      // 'inline namespace' at the start of a line is almost certainly
1925
      // a good place to pick back up parsing, except in an Objective-C
1926
      // @interface context.
1927
2
      if (Tok.isAtStartOfLine() && 
NextToken().is(tok::kw_namespace)1
&&
1928
2
          
(1
!ParsingInObjCContainer1
||
CurParsedObjCImpl0
))
1929
1
        return;
1930
1
      break;
1931
1932
6
    case tok::kw_namespace:
1933
      // 'namespace' at the start of a line is almost certainly a good
1934
      // place to pick back up parsing, except in an Objective-C
1935
      // @interface context.
1936
6
      if (Tok.isAtStartOfLine() &&
1937
6
          
(4
!ParsingInObjCContainer4
||
CurParsedObjCImpl3
))
1938
2
        return;
1939
4
      break;
1940
1941
4
    case tok::at:
1942
      // @end is very much like } in Objective-C contexts.
1943
2
      if (NextToken().isObjCAtKeyword(tok::objc_end) &&
1944
2
          ParsingInObjCContainer)
1945
2
        return;
1946
0
      break;
1947
1948
2
    case tok::minus:
1949
15
    case tok::plus:
1950
      // - and + probably start new method declarations in Objective-C contexts.
1951
15
      if (Tok.isAtStartOfLine() && 
ParsingInObjCContainer4
)
1952
4
        return;
1953
11
      break;
1954
1955
122
    case tok::eof:
1956
122
    case tok::annot_module_begin:
1957
134
    case tok::annot_module_end:
1958
134
    case tok::annot_module_include:
1959
134
      return;
1960
1961
554
    default:
1962
554
      break;
1963
1.10k
    }
1964
1965
570
    ConsumeAnyToken();
1966
570
  }
1967
492
}
1968
1969
/// ParseDeclGroup - Having concluded that this is either a function
1970
/// definition or a group of object declarations, actually parse the
1971
/// result.
1972
Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
1973
                                              DeclaratorContext Context,
1974
                                              SourceLocation *DeclEnd,
1975
34.5M
                                              ForRangeInit *FRI) {
1976
  // Parse the first declarator.
1977
34.5M
  ParsingDeclarator D(*this, DS, Context);
1978
34.5M
  ParseDeclarator(D);
1979
1980
  // Bail out if the first declarator didn't seem well-formed.
1981
34.5M
  if (!D.hasName() && 
!D.mayOmitIdentifier()356
) {
1982
356
    SkipMalformedDecl();
1983
356
    return nullptr;
1984
356
  }
1985
1986
34.5M
  if (Tok.is(tok::kw_requires))
1987
37
    ParseTrailingRequiresClause(D);
1988
1989
  // Save late-parsed attributes for now; they need to be parsed in the
1990
  // appropriate function scope after the function Decl has been constructed.
1991
  // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
1992
34.5M
  LateParsedAttrList LateParsedAttrs(true);
1993
34.5M
  if (D.isFunctionDeclarator()) {
1994
30.4M
    MaybeParseGNUAttributes(D, &LateParsedAttrs);
1995
1996
    // The _Noreturn keyword can't appear here, unlike the GNU noreturn
1997
    // attribute. If we find the keyword here, tell the user to put it
1998
    // at the start instead.
1999
30.4M
    if (Tok.is(tok::kw__Noreturn)) {
2000
6
      SourceLocation Loc = ConsumeToken();
2001
6
      const char *PrevSpec;
2002
6
      unsigned DiagID;
2003
2004
      // We can offer a fixit if it's valid to mark this function as _Noreturn
2005
      // and we don't have any other declarators in this declaration.
2006
6
      bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
2007
6
      MaybeParseGNUAttributes(D, &LateParsedAttrs);
2008
6
      Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
2009
2010
6
      Diag(Loc, diag::err_c11_noreturn_misplaced)
2011
6
          << (Fixit ? FixItHint::CreateRemoval(Loc) : 
FixItHint()0
)
2012
6
          << (Fixit ? FixItHint::CreateInsertion(D.getBeginLoc(), "_Noreturn ")
2013
6
                    : 
FixItHint()0
);
2014
6
    }
2015
30.4M
  }
2016
2017
  // Check to see if we have a function *definition* which must have a body.
2018
34.5M
  if (D.isFunctionDeclarator()) {
2019
30.4M
    if (Tok.is(tok::equal) && 
NextToken().is(tok::code_completion)636
) {
2020
2
      cutOffParsing();
2021
2
      Actions.CodeCompleteAfterFunctionEquals(D);
2022
2
      return nullptr;
2023
2
    }
2024
    // Look at the next token to make sure that this isn't a function
2025
    // declaration.  We have to check this because __attribute__ might be the
2026
    // start of a function definition in GCC-extended K&R C.
2027
30.4M
    if (!isDeclarationAfterDeclarator()) {
2028
2029
      // Function definitions are only allowed at file scope and in C++ classes.
2030
      // The C++ inline method definition case is handled elsewhere, so we only
2031
      // need to handle the file scope definition case.
2032
2.47M
      if (Context == DeclaratorContext::File) {
2033
2.47M
        if (isStartOfFunctionDefinition(D)) {
2034
2.47M
          if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
2035
9
            Diag(Tok, diag::err_function_declared_typedef);
2036
2037
            // Recover by treating the 'typedef' as spurious.
2038
9
            DS.ClearStorageClassSpecs();
2039
9
          }
2040
2041
2.47M
          Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(),
2042
2.47M
                                                  &LateParsedAttrs);
2043
2.47M
          return Actions.ConvertDeclToDeclGroup(TheDecl);
2044
2.47M
        }
2045
2046
34
        if (isDeclarationSpecifier()) {
2047
          // If there is an invalid declaration specifier right after the
2048
          // function prototype, then we must be in a missing semicolon case
2049
          // where this isn't actually a body.  Just fall through into the code
2050
          // that handles it as a prototype, and let the top-level code handle
2051
          // the erroneous declspec where it would otherwise expect a comma or
2052
          // semicolon.
2053
32
        } else {
2054
32
          Diag(Tok, diag::err_expected_fn_body);
2055
32
          SkipUntil(tok::semi);
2056
32
          return nullptr;
2057
32
        }
2058
34
      } else {
2059
11
        if (Tok.is(tok::l_brace)) {
2060
8
          Diag(Tok, diag::err_function_definition_not_allowed);
2061
8
          SkipMalformedDecl();
2062
8
          return nullptr;
2063
8
        }
2064
11
      }
2065
2.47M
    }
2066
30.4M
  }
2067
2068
32.0M
  if (ParseAsmAttributesAfterDeclarator(D))
2069
8
    return nullptr;
2070
2071
  // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
2072
  // must parse and analyze the for-range-initializer before the declaration is
2073
  // analyzed.
2074
  //
2075
  // Handle the Objective-C for-in loop variable similarly, although we
2076
  // don't need to parse the container in advance.
2077
32.0M
  if (FRI && 
(118k
Tok.is(tok::colon)118k
||
isTokIdentifier_in()116k
)) {
2078
1.42k
    bool IsForRangeLoop = false;
2079
1.42k
    if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
2080
1.38k
      IsForRangeLoop = true;
2081
1.38k
      if (getLangOpts().OpenMP)
2082
123
        Actions.startOpenMPCXXRangeFor();
2083
1.38k
      if (Tok.is(tok::l_brace))
2084
10
        FRI->RangeExpr = ParseBraceInitializer();
2085
1.37k
      else
2086
1.37k
        FRI->RangeExpr = ParseExpression();
2087
1.38k
    }
2088
2089
1.42k
    Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2090
1.42k
    if (IsForRangeLoop) {
2091
1.38k
      Actions.ActOnCXXForRangeDecl(ThisDecl);
2092
1.38k
    } else {
2093
      // Obj-C for loop
2094
37
      if (auto *VD = dyn_cast_or_null<VarDecl>(ThisDecl))
2095
36
        VD->setObjCForDecl(true);
2096
37
    }
2097
1.42k
    Actions.FinalizeDeclaration(ThisDecl);
2098
1.42k
    D.complete(ThisDecl);
2099
1.42k
    return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
2100
1.42k
  }
2101
2102
32.0M
  SmallVector<Decl *, 8> DeclsInGroup;
2103
32.0M
  Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
2104
32.0M
      D, ParsedTemplateInfo(), FRI);
2105
32.0M
  if (LateParsedAttrs.size() > 0)
2106
654
    ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
2107
32.0M
  D.complete(FirstDecl);
2108
32.0M
  if (FirstDecl)
2109
32.0M
    DeclsInGroup.push_back(FirstDecl);
2110
2111
32.0M
  bool ExpectSemi = Context != DeclaratorContext::ForInit;
2112
2113
  // If we don't have a comma, it is either the end of the list (a ';') or an
2114
  // error, bail out.
2115
32.0M
  SourceLocation CommaLoc;
2116
32.2M
  while (TryConsumeToken(tok::comma, CommaLoc)) {
2117
172k
    if (Tok.isAtStartOfLine() && 
ExpectSemi113k
&&
!MightBeDeclarator(Context)113k
) {
2118
      // This comma was followed by a line-break and something which can't be
2119
      // the start of a declarator. The comma was probably a typo for a
2120
      // semicolon.
2121
40
      Diag(CommaLoc, diag::err_expected_semi_declaration)
2122
40
        << FixItHint::CreateReplacement(CommaLoc, ";");
2123
40
      ExpectSemi = false;
2124
40
      break;
2125
40
    }
2126
2127
    // Parse the next declarator.
2128
172k
    D.clear();
2129
172k
    D.setCommaLoc(CommaLoc);
2130
2131
    // Accept attributes in an init-declarator.  In the first declarator in a
2132
    // declaration, these would be part of the declspec.  In subsequent
2133
    // declarators, they become part of the declarator itself, so that they
2134
    // don't apply to declarators after *this* one.  Examples:
2135
    //    short __attribute__((common)) var;    -> declspec
2136
    //    short var __attribute__((common));    -> declarator
2137
    //    short x, __attribute__((common)) var;    -> declarator
2138
172k
    MaybeParseGNUAttributes(D);
2139
2140
    // MSVC parses but ignores qualifiers after the comma as an extension.
2141
172k
    if (getLangOpts().MicrosoftExt)
2142
300
      DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
2143
2144
172k
    ParseDeclarator(D);
2145
172k
    if (!D.isInvalidType()) {
2146
      // C++2a [dcl.decl]p1
2147
      //    init-declarator:
2148
      //        declarator initializer[opt]
2149
      //        declarator requires-clause
2150
172k
      if (Tok.is(tok::kw_requires))
2151
0
        ParseTrailingRequiresClause(D);
2152
172k
      Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
2153
172k
      D.complete(ThisDecl);
2154
172k
      if (ThisDecl)
2155
172k
        DeclsInGroup.push_back(ThisDecl);
2156
172k
    }
2157
172k
  }
2158
2159
32.0M
  if (DeclEnd)
2160
3.12M
    *DeclEnd = Tok.getLocation();
2161
2162
32.0M
  if (ExpectSemi && ExpectAndConsumeSemi(
2163
31.9M
                        Context == DeclaratorContext::File
2164
31.9M
                            ? 
diag::err_invalid_token_after_toplevel_declarator30.7M
2165
31.9M
                            : 
diag::err_expected_semi_declaration1.18M
)) {
2166
    // Okay, there was no semicolon and one was expected.  If we see a
2167
    // declaration specifier, just assume it was missing and continue parsing.
2168
    // Otherwise things are very confused and we skip to recover.
2169
279
    if (!isDeclarationSpecifier()) {
2170
254
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2171
254
      TryConsumeToken(tok::semi);
2172
254
    }
2173
279
  }
2174
2175
32.0M
  return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
2176
32.0M
}
2177
2178
/// Parse an optional simple-asm-expr and attributes, and attach them to a
2179
/// declarator. Returns true on an error.
2180
32.3M
bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
2181
  // If a simple-asm-expr is present, parse it.
2182
32.3M
  if (Tok.is(tok::kw_asm)) {
2183
55.9k
    SourceLocation Loc;
2184
55.9k
    ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2185
55.9k
    if (AsmLabel.isInvalid()) {
2186
8
      SkipUntil(tok::semi, StopBeforeMatch);
2187
8
      return true;
2188
8
    }
2189
2190
55.9k
    D.setAsmLabel(AsmLabel.get());
2191
55.9k
    D.SetRangeEnd(Loc);
2192
55.9k
  }
2193
2194
32.3M
  MaybeParseGNUAttributes(D);
2195
32.3M
  return false;
2196
32.3M
}
2197
2198
/// Parse 'declaration' after parsing 'declaration-specifiers
2199
/// declarator'. This method parses the remainder of the declaration
2200
/// (including any attributes or initializer, among other things) and
2201
/// finalizes the declaration.
2202
///
2203
///       init-declarator: [C99 6.7]
2204
///         declarator
2205
///         declarator '=' initializer
2206
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt]
2207
/// [GNU]   declarator simple-asm-expr[opt] attributes[opt] '=' initializer
2208
/// [C++]   declarator initializer[opt]
2209
///
2210
/// [C++] initializer:
2211
/// [C++]   '=' initializer-clause
2212
/// [C++]   '(' expression-list ')'
2213
/// [C++0x] '=' 'default'                                                [TODO]
2214
/// [C++0x] '=' 'delete'
2215
/// [C++0x] braced-init-list
2216
///
2217
/// According to the standard grammar, =default and =delete are function
2218
/// definitions, but that definitely doesn't fit with the parser here.
2219
///
2220
Decl *Parser::ParseDeclarationAfterDeclarator(
2221
301k
    Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
2222
301k
  if (ParseAsmAttributesAfterDeclarator(D))
2223
0
    return nullptr;
2224
2225
301k
  return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
2226
301k
}
2227
2228
Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
2229
32.3M
    Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
2230
  // RAII type used to track whether we're inside an initializer.
2231
32.3M
  struct InitializerScopeRAII {
2232
32.3M
    Parser &P;
2233
32.3M
    Declarator &D;
2234
32.3M
    Decl *ThisDecl;
2235
2236
32.3M
    InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
2237
32.3M
        : P(P), D(D), ThisDecl(ThisDecl) {
2238
729k
      if (ThisDecl && 
P.getLangOpts().CPlusPlus729k
) {
2239
645k
        Scope *S = nullptr;
2240
645k
        if (D.getCXXScopeSpec().isSet()) {
2241
2.29k
          P.EnterScope(0);
2242
2.29k
          S = P.getCurScope();
2243
2.29k
        }
2244
645k
        P.Actions.ActOnCXXEnterDeclInitializer(S, ThisDecl);
2245
645k
      }
2246
729k
    }
2247
32.3M
    ~InitializerScopeRAII() 
{ pop(); }729k
2248
32.3M
    void pop() {
2249
1.45M
      if (ThisDecl && 
P.getLangOpts().CPlusPlus729k
) {
2250
645k
        Scope *S = nullptr;
2251
645k
        if (D.getCXXScopeSpec().isSet())
2252
2.29k
          S = P.getCurScope();
2253
645k
        P.Actions.ActOnCXXExitDeclInitializer(S, ThisDecl);
2254
645k
        if (S)
2255
2.29k
          P.ExitScope();
2256
645k
      }
2257
1.45M
      ThisDecl = nullptr;
2258
1.45M
    }
2259
32.3M
  };
2260
2261
32.3M
  enum class InitKind { Uninitialized, Equal, CXXDirect, CXXBraced };
2262
32.3M
  InitKind TheInitKind;
2263
  // If a '==' or '+=' is found, suggest a fixit to '='.
2264
32.3M
  if (isTokenEqualOrEqualTypo())
2265
662k
    TheInitKind = InitKind::Equal;
2266
31.6M
  else if (Tok.is(tok::l_paren))
2267
61.4k
    TheInitKind = InitKind::CXXDirect;
2268
31.6M
  else if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)9.36M
&&
2269
31.6M
           
(5.72k
!CurParsedObjCImpl5.72k
||
!D.isFunctionDeclarator()1
))
2270
5.72k
    TheInitKind = InitKind::CXXBraced;
2271
31.6M
  else
2272
31.6M
    TheInitKind = InitKind::Uninitialized;
2273
32.3M
  if (TheInitKind != InitKind::Uninitialized)
2274
729k
    D.setHasInitializer();
2275
2276
  // Inform Sema that we just parsed this declarator.
2277
32.3M
  Decl *ThisDecl = nullptr;
2278
32.3M
  Decl *OuterDecl = nullptr;
2279
32.3M
  switch (TemplateInfo.Kind) {
2280
32.2M
  case ParsedTemplateInfo::NonTemplate:
2281
32.2M
    ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2282
32.2M
    break;
2283
2284
80.1k
  case ParsedTemplateInfo::Template:
2285
83.6k
  case ParsedTemplateInfo::ExplicitSpecialization: {
2286
83.6k
    ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
2287
83.6k
                                               *TemplateInfo.TemplateParams,
2288
83.6k
                                               D);
2289
83.6k
    if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) {
2290
      // Re-direct this decl to refer to the templated decl so that we can
2291
      // initialize it.
2292
2.08k
      ThisDecl = VT->getTemplatedDecl();
2293
2.08k
      OuterDecl = VT;
2294
2.08k
    }
2295
83.6k
    break;
2296
80.1k
  }
2297
45.8k
  case ParsedTemplateInfo::ExplicitInstantiation: {
2298
45.8k
    if (Tok.is(tok::semi)) {
2299
45.8k
      DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
2300
45.8k
          getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
2301
45.8k
      if (ThisRes.isInvalid()) {
2302
113
        SkipUntil(tok::semi, StopBeforeMatch);
2303
113
        return nullptr;
2304
113
      }
2305
45.7k
      ThisDecl = ThisRes.get();
2306
45.7k
    } else {
2307
      // FIXME: This check should be for a variable template instantiation only.
2308
2309
      // Check that this is a valid instantiation
2310
6
      if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
2311
        // If the declarator-id is not a template-id, issue a diagnostic and
2312
        // recover by ignoring the 'template' keyword.
2313
3
        Diag(Tok, diag::err_template_defn_explicit_instantiation)
2314
3
            << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
2315
3
        ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
2316
3
      } else {
2317
3
        SourceLocation LAngleLoc =
2318
3
            PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
2319
3
        Diag(D.getIdentifierLoc(),
2320
3
             diag::err_explicit_instantiation_with_definition)
2321
3
            << SourceRange(TemplateInfo.TemplateLoc)
2322
3
            << FixItHint::CreateInsertion(LAngleLoc, "<>");
2323
2324
        // Recover as if it were an explicit specialization.
2325
3
        TemplateParameterLists FakedParamLists;
2326
3
        FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
2327
3
            0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
2328
3
            LAngleLoc, nullptr));
2329
2330
3
        ThisDecl =
2331
3
            Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
2332
3
      }
2333
6
    }
2334
45.7k
    break;
2335
45.8k
    }
2336
32.3M
  }
2337
2338
32.3M
  switch (TheInitKind) {
2339
  // Parse declarator '=' initializer.
2340
662k
  case InitKind::Equal: {
2341
662k
    SourceLocation EqualLoc = ConsumeToken();
2342
2343
662k
    if (Tok.is(tok::kw_delete)) {
2344
3
      if (D.isFunctionDeclarator())
2345
1
        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2346
1
          << 1 /* delete */;
2347
2
      else
2348
2
        Diag(ConsumeToken(), diag::err_deleted_non_function);
2349
662k
    } else if (Tok.is(tok::kw_default)) {
2350
2
      if (D.isFunctionDeclarator())
2351
1
        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
2352
1
          << 0 /* default */;
2353
1
      else
2354
1
        Diag(ConsumeToken(), diag::err_default_special_members)
2355
1
            << getLangOpts().CPlusPlus20;
2356
662k
    } else {
2357
662k
      InitializerScopeRAII InitScope(*this, D, ThisDecl);
2358
2359
662k
      if (Tok.is(tok::code_completion)) {
2360
42
        cutOffParsing();
2361
42
        Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
2362
42
        Actions.FinalizeDeclaration(ThisDecl);
2363
42
        return nullptr;
2364
42
      }
2365
2366
662k
      PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2367
662k
      ExprResult Init = ParseInitializer();
2368
2369
      // If this is the only decl in (possibly) range based for statement,
2370
      // our best guess is that the user meant ':' instead of '='.
2371
662k
      if (Tok.is(tok::r_paren) && 
FRI5
&&
D.isFirstDeclarator()3
) {
2372
3
        Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
2373
3
            << FixItHint::CreateReplacement(EqualLoc, ":");
2374
        // We are trying to stop parser from looking for ';' in this for
2375
        // statement, therefore preventing spurious errors to be issued.
2376
3
        FRI->ColonLoc = EqualLoc;
2377
3
        Init = ExprError();
2378
3
        FRI->RangeExpr = Init;
2379
3
      }
2380
2381
662k
      InitScope.pop();
2382
2383
662k
      if (Init.isInvalid()) {
2384
1.44k
        SmallVector<tok::TokenKind, 2> StopTokens;
2385
1.44k
        StopTokens.push_back(tok::comma);
2386
1.44k
        if (D.getContext() == DeclaratorContext::ForInit ||
2387
1.44k
            
D.getContext() == DeclaratorContext::SelectionInit1.43k
)
2388
3
          StopTokens.push_back(tok::r_paren);
2389
1.44k
        SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
2390
1.44k
        Actions.ActOnInitializerError(ThisDecl);
2391
1.44k
      } else
2392
661k
        Actions.AddInitializerToDecl(ThisDecl, Init.get(),
2393
661k
                                     /*DirectInit=*/false);
2394
662k
    }
2395
662k
    break;
2396
662k
  }
2397
662k
  case InitKind::CXXDirect: {
2398
    // Parse C++ direct initializer: '(' expression-list ')'
2399
61.4k
    BalancedDelimiterTracker T(*this, tok::l_paren);
2400
61.4k
    T.consumeOpen();
2401
2402
61.4k
    ExprVector Exprs;
2403
61.4k
    CommaLocsTy CommaLocs;
2404
2405
61.4k
    InitializerScopeRAII InitScope(*this, D, ThisDecl);
2406
2407
61.4k
    auto ThisVarDecl = dyn_cast_or_null<VarDecl>(ThisDecl);
2408
61.4k
    auto RunSignatureHelp = [&]() {
2409
13
      QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2410
13
          getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2411
13
          ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2412
13
      CalledSignatureHelp = true;
2413
13
      return PreferredType;
2414
13
    };
2415
90.3k
    auto SetPreferredType = [&] {
2416
90.3k
      PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
2417
90.3k
    };
2418
2419
61.4k
    llvm::function_ref<void()> ExpressionStarts;
2420
61.4k
    if (ThisVarDecl) {
2421
      // ParseExpressionList can sometimes succeed even when ThisDecl is not
2422
      // VarDecl. This is an error and it is reported in a call to
2423
      // Actions.ActOnInitializerError(). However, we call
2424
      // ProduceConstructorSignatureHelp only on VarDecls.
2425
61.4k
      ExpressionStarts = SetPreferredType;
2426
61.4k
    }
2427
61.4k
    if (ParseExpressionList(Exprs, CommaLocs, ExpressionStarts)) {
2428
77
      if (ThisVarDecl && 
PP.isCodeCompletionReached()76
&&
!CalledSignatureHelp19
) {
2429
2
        Actions.ProduceConstructorSignatureHelp(
2430
2
            getCurScope(), ThisVarDecl->getType()->getCanonicalTypeInternal(),
2431
2
            ThisDecl->getLocation(), Exprs, T.getOpenLocation());
2432
2
        CalledSignatureHelp = true;
2433
2
      }
2434
77
      Actions.ActOnInitializerError(ThisDecl);
2435
77
      SkipUntil(tok::r_paren, StopAtSemi);
2436
61.3k
    } else {
2437
      // Match the ')'.
2438
61.3k
      T.consumeClose();
2439
2440
61.3k
      assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
2441
61.3k
             "Unexpected number of commas!");
2442
2443
0
      InitScope.pop();
2444
2445
61.3k
      ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
2446
61.3k
                                                          T.getCloseLocation(),
2447
61.3k
                                                          Exprs);
2448
61.3k
      Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
2449
61.3k
                                   /*DirectInit=*/true);
2450
61.3k
    }
2451
0
    break;
2452
662k
  }
2453
5.72k
  case InitKind::CXXBraced: {
2454
    // Parse C++0x braced-init-list.
2455
5.72k
    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2456
2457
5.72k
    InitializerScopeRAII InitScope(*this, D, ThisDecl);
2458
2459
5.72k
    PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
2460
5.72k
    ExprResult Init(ParseBraceInitializer());
2461
2462
5.72k
    InitScope.pop();
2463
2464
5.72k
    if (Init.isInvalid()) {
2465
12
      Actions.ActOnInitializerError(ThisDecl);
2466
12
    } else
2467
5.70k
      Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
2468
5.72k
    break;
2469
662k
  }
2470
31.6M
  case InitKind::Uninitialized: {
2471
31.6M
    Actions.ActOnUninitializedDecl(ThisDecl);
2472
31.6M
    break;
2473
662k
  }
2474
32.3M
  }
2475
2476
32.3M
  Actions.FinalizeDeclaration(ThisDecl);
2477
32.3M
  return OuterDecl ? 
OuterDecl2.08k
:
ThisDecl32.3M
;
2478
32.3M
}
2479
2480
/// ParseSpecifierQualifierList
2481
///        specifier-qualifier-list:
2482
///          type-specifier specifier-qualifier-list[opt]
2483
///          type-qualifier specifier-qualifier-list[opt]
2484
/// [GNU]    attributes     specifier-qualifier-list[opt]
2485
///
2486
void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
2487
13.0M
                                         DeclSpecContext DSC) {
2488
  /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
2489
  /// parse declaration-specifiers and complain about extra stuff.
2490
  /// TODO: diagnose attribute-specifiers and alignment-specifiers.
2491
13.0M
  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
2492
2493
  // Validate declspec for type-name.
2494
13.0M
  unsigned Specs = DS.getParsedSpecifiers();
2495
13.0M
  if (isTypeSpecifier(DSC) && 
!DS.hasTypeSpecifier()4.36M
) {
2496
154
    Diag(Tok, diag::err_expected_type);
2497
154
    DS.SetTypeSpecError();
2498
13.0M
  } else if (Specs == DeclSpec::PQ_None && 
!DS.hasAttributes()46
) {
2499
29
    Diag(Tok, diag::err_typename_requires_specqual);
2500
29
    if (!DS.hasTypeSpecifier())
2501
29
      DS.SetTypeSpecError();
2502
29
  }
2503
2504
  // Issue diagnostic and remove storage class if present.
2505
13.0M
  if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
2506
16
    if (DS.getStorageClassSpecLoc().isValid())
2507
11
      Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
2508
5
    else
2509
5
      Diag(DS.getThreadStorageClassSpecLoc(),
2510
5
           diag::err_typename_invalid_storageclass);
2511
16
    DS.ClearStorageClassSpecs();
2512
16
  }
2513
2514
  // Issue diagnostic and remove function specifier if present.
2515
13.0M
  if (Specs & DeclSpec::PQ_FunctionSpecifier) {
2516
6
    if (DS.isInlineSpecified())
2517
2
      Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
2518
6
    if (DS.isVirtualSpecified())
2519
2
      Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
2520
6
    if (DS.hasExplicitSpecifier())
2521
2
      Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
2522
6
    DS.ClearFunctionSpecs();
2523
6
  }
2524
2525
  // Issue diagnostic and remove constexpr specifier if present.
2526
13.0M
  if (DS.hasConstexprSpecifier() && 
DSC != DeclSpecContext::DSC_condition34
) {
2527
7
    Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr)
2528
7
        << static_cast<int>(DS.getConstexprSpecifier());
2529
7
    DS.ClearConstexprSpec();
2530
7
  }
2531
13.0M
}
2532
2533
/// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
2534
/// specified token is valid after the identifier in a declarator which
2535
/// immediately follows the declspec.  For example, these things are valid:
2536
///
2537
///      int x   [             4];         // direct-declarator
2538
///      int x   (             int y);     // direct-declarator
2539
///  int(int x   )                         // direct-declarator
2540
///      int x   ;                         // simple-declaration
2541
///      int x   =             17;         // init-declarator-list
2542
///      int x   ,             y;          // init-declarator-list
2543
///      int x   __asm__       ("foo");    // init-declarator-list
2544
///      int x   :             4;          // struct-declarator
2545
///      int x   {             5};         // C++'0x unified initializers
2546
///
2547
/// This is not, because 'x' does not immediately follow the declspec (though
2548
/// ')' happens to be valid anyway).
2549
///    int (x)
2550
///
2551
438
static bool isValidAfterIdentifierInDeclarator(const Token &T) {
2552
438
  return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
2553
438
                   tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
2554
438
                   tok::colon);
2555
438
}
2556
2557
/// ParseImplicitInt - This method is called when we have an non-typename
2558
/// identifier in a declspec (which normally terminates the decl spec) when
2559
/// the declspec has no type specifier.  In this case, the declspec is either
2560
/// malformed or is "implicit int" (in K&R and C89).
2561
///
2562
/// This method handles diagnosing this prettily and returns false if the
2563
/// declspec is done being processed.  If it recovers and thinks there may be
2564
/// other pieces of declspec after it, it returns true.
2565
///
2566
bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
2567
                              const ParsedTemplateInfo &TemplateInfo,
2568
                              AccessSpecifier AS, DeclSpecContext DSC,
2569
1.74k
                              ParsedAttributesWithRange &Attrs) {
2570
1.74k
  assert(Tok.is(tok::identifier) && "should have identifier");
2571
2572
0
  SourceLocation Loc = Tok.getLocation();
2573
  // If we see an identifier that is not a type name, we normally would
2574
  // parse it as the identifier being declared.  However, when a typename
2575
  // is typo'd or the definition is not included, this will incorrectly
2576
  // parse the typename as the identifier name and fall over misparsing
2577
  // later parts of the diagnostic.
2578
  //
2579
  // As such, we try to do some look-ahead in cases where this would
2580
  // otherwise be an "implicit-int" case to see if this is invalid.  For
2581
  // example: "static foo_t x = 4;"  In this case, if we parsed foo_t as
2582
  // an identifier with implicit int, we'd get a parse error because the
2583
  // next token is obviously invalid for a type.  Parse these as a case
2584
  // with an invalid type specifier.
2585
1.74k
  assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
2586
2587
  // Since we know that this either implicit int (which is rare) or an
2588
  // error, do lookahead to try to do better recovery. This never applies
2589
  // within a type specifier. Outside of C++, we allow this even if the
2590
  // language doesn't "officially" support implicit int -- we support
2591
  // implicit int as an extension in C99 and C11.
2592
1.74k
  if (!isTypeSpecifier(DSC) && 
!getLangOpts().CPlusPlus1.59k
&&
2593
1.74k
      
isValidAfterIdentifierInDeclarator(NextToken())438
) {
2594
    // If this token is valid for implicit int, e.g. "static x = 4", then
2595
    // we just avoid eating the identifier, so it will be parsed as the
2596
    // identifier in the declarator.
2597
111
    return false;
2598
111
  }
2599
2600
  // Early exit as Sema has a dedicated missing_actual_pipe_type diagnostic
2601
  // for incomplete declarations such as `pipe p`.
2602
1.63k
  if (getLangOpts().OpenCLCPlusPlus && 
DS.isTypeSpecPipe()5
)
2603
3
    return false;
2604
2605
1.63k
  if (getLangOpts().CPlusPlus &&
2606
1.63k
      
DS.getStorageClassSpec() == DeclSpec::SCS_auto1.29k
) {
2607
    // Don't require a type specifier if we have the 'auto' storage class
2608
    // specifier in C++98 -- we'll promote it to a type specifier.
2609
74
    if (SS)
2610
3
      AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2611
74
    return false;
2612
74
  }
2613
2614
1.55k
  if (getLangOpts().CPlusPlus && 
(1.21k
!SS1.21k
||
SS->isEmpty()517
) &&
2615
1.55k
      
getLangOpts().MSVCCompat699
) {
2616
    // Lookup of an unqualified type name has failed in MSVC compatibility mode.
2617
    // Give Sema a chance to recover if we are in a template with dependent base
2618
    // classes.
2619
41
    if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
2620
41
            *Tok.getIdentifierInfo(), Tok.getLocation(),
2621
41
            DSC == DeclSpecContext::DSC_template_type_arg)) {
2622
15
      const char *PrevSpec;
2623
15
      unsigned DiagID;
2624
15
      DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2625
15
                         Actions.getASTContext().getPrintingPolicy());
2626
15
      DS.SetRangeEnd(Tok.getLocation());
2627
15
      ConsumeToken();
2628
15
      return false;
2629
15
    }
2630
41
  }
2631
2632
  // Otherwise, if we don't consume this token, we are going to emit an
2633
  // error anyway.  Try to recover from various common problems.  Check
2634
  // to see if this was a reference to a tag name without a tag specified.
2635
  // This is a common problem in C (saying 'foo' instead of 'struct foo').
2636
  //
2637
  // C++ doesn't need this, and isTagName doesn't take SS.
2638
1.54k
  if (SS == nullptr) {
2639
1.02k
    const char *TagName = nullptr, *FixitTagName = nullptr;
2640
1.02k
    tok::TokenKind TagKind = tok::unknown;
2641
2642
1.02k
    switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
2643
988
      default: break;
2644
988
      case DeclSpec::TST_enum:
2645
11
        TagName="enum"  ; FixitTagName = "enum "  ; TagKind=tok::kw_enum ;break;
2646
0
      case DeclSpec::TST_union:
2647
0
        TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
2648
18
      case DeclSpec::TST_struct:
2649
18
        TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
2650
0
      case DeclSpec::TST_interface:
2651
0
        TagName="__interface"; FixitTagName = "__interface ";
2652
0
        TagKind=tok::kw___interface;break;
2653
9
      case DeclSpec::TST_class:
2654
9
        TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
2655
1.02k
    }
2656
2657
1.02k
    if (TagName) {
2658
38
      IdentifierInfo *TokenName = Tok.getIdentifierInfo();
2659
38
      LookupResult R(Actions, TokenName, SourceLocation(),
2660
38
                     Sema::LookupOrdinaryName);
2661
2662
38
      Diag(Loc, diag::err_use_of_tag_name_without_tag)
2663
38
        << TokenName << TagName << getLangOpts().CPlusPlus
2664
38
        << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
2665
2666
38
      if (Actions.LookupParsedName(R, getCurScope(), SS)) {
2667
23
        for (LookupResult::iterator I = R.begin(), IEnd = R.end();
2668
46
             I != IEnd; 
++I23
)
2669
23
          Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
2670
23
            << TokenName << TagName;
2671
23
      }
2672
2673
      // Parse this as a tag as if the missing tag were present.
2674
38
      if (TagKind == tok::kw_enum)
2675
11
        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS,
2676
11
                           DeclSpecContext::DSC_normal);
2677
27
      else
2678
27
        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
2679
27
                            /*EnteringContext*/ false,
2680
27
                            DeclSpecContext::DSC_normal, Attrs);
2681
38
      return true;
2682
38
    }
2683
1.02k
  }
2684
2685
  // Determine whether this identifier could plausibly be the name of something
2686
  // being declared (with a missing type).
2687
1.50k
  if (!isTypeSpecifier(DSC) && 
(1.37k
!SS1.37k
||
DSC == DeclSpecContext::DSC_top_level481
||
2688
1.37k
                                
DSC == DeclSpecContext::DSC_class295
)) {
2689
    // Look ahead to the next token to try to figure out what this declaration
2690
    // was supposed to be.
2691
1.19k
    switch (NextToken().getKind()) {
2692
69
    case tok::l_paren: {
2693
      // static x(4); // 'x' is not a type
2694
      // x(int n);    // 'x' is not a type
2695
      // x (*p)[];    // 'x' is a type
2696
      //
2697
      // Since we're in an error case, we can afford to perform a tentative
2698
      // parse to determine which case we're in.
2699
69
      TentativeParsingAction PA(*this);
2700
69
      ConsumeToken();
2701
69
      TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
2702
69
      PA.Revert();
2703
2704
69
      if (TPR != TPResult::False) {
2705
        // The identifier is followed by a parenthesized declarator.
2706
        // It's supposed to be a type.
2707
2
        break;
2708
2
      }
2709
2710
      // If we're in a context where we could be declaring a constructor,
2711
      // check whether this is a constructor declaration with a bogus name.
2712
67
      if (DSC == DeclSpecContext::DSC_class ||
2713
67
          
(41
DSC == DeclSpecContext::DSC_top_level41
&&
SS39
)) {
2714
44
        IdentifierInfo *II = Tok.getIdentifierInfo();
2715
44
        if (Actions.isCurrentClassNameTypo(II, SS)) {
2716
10
          Diag(Loc, diag::err_constructor_bad_name)
2717
10
            << Tok.getIdentifierInfo() << II
2718
10
            << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
2719
10
          Tok.setIdentifierInfo(II);
2720
10
        }
2721
44
      }
2722
      // Fall through.
2723
67
      LLVM_FALLTHROUGH;
2724
67
    }
2725
79
    case tok::comma:
2726
108
    case tok::equal:
2727
108
    case tok::kw_asm:
2728
123
    case tok::l_brace:
2729
126
    case tok::l_square:
2730
186
    case tok::semi:
2731
      // This looks like a variable or function declaration. The type is
2732
      // probably missing. We're done parsing decl-specifiers.
2733
      // But only if we are not in a function prototype scope.
2734
186
      if (getCurScope()->isFunctionPrototypeScope())
2735
8
        break;
2736
178
      if (SS)
2737
46
        AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
2738
178
      return false;
2739
2740
1.00k
    default:
2741
      // This is probably supposed to be a type. This includes cases like:
2742
      //   int f(itn);
2743
      //   struct S { unsigned : 4; };
2744
1.00k
      break;
2745
1.19k
    }
2746
1.19k
  }
2747
2748
  // This is almost certainly an invalid type name. Let Sema emit a diagnostic
2749
  // and attempt to recover.
2750
1.32k
  ParsedType T;
2751
1.32k
  IdentifierInfo *II = Tok.getIdentifierInfo();
2752
1.32k
  bool IsTemplateName = getLangOpts().CPlusPlus && 
NextToken().is(tok::less)1.00k
;
2753
1.32k
  Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
2754
1.32k
                                  IsTemplateName);
2755
1.32k
  if (T) {
2756
    // The action has suggested that the type T could be used. Set that as
2757
    // the type in the declaration specifiers, consume the would-be type
2758
    // name token, and we're done.
2759
363
    const char *PrevSpec;
2760
363
    unsigned DiagID;
2761
363
    DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
2762
363
                       Actions.getASTContext().getPrintingPolicy());
2763
363
    DS.SetRangeEnd(Tok.getLocation());
2764
363
    ConsumeToken();
2765
    // There may be other declaration specifiers after this.
2766
363
    return true;
2767
964
  } else if (II != Tok.getIdentifierInfo()) {
2768
    // If no type was suggested, the correction is to a keyword
2769
12
    Tok.setKind(II->getTokenID());
2770
    // There may be other declaration specifiers after this.
2771
12
    return true;
2772
12
  }
2773
2774
  // Otherwise, the action had no suggestion for us.  Mark this as an error.
2775
952
  DS.SetTypeSpecError();
2776
952
  DS.SetRangeEnd(Tok.getLocation());
2777
952
  ConsumeToken();
2778
2779
  // Eat any following template arguments.
2780
952
  if (IsTemplateName) {
2781
8
    SourceLocation LAngle, RAngle;
2782
8
    TemplateArgList Args;
2783
8
    ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
2784
8
  }
2785
2786
  // TODO: Could inject an invalid typedef decl in an enclosing scope to
2787
  // avoid rippling error messages on subsequent uses of the same type,
2788
  // could be useful if #include was forgotten.
2789
952
  return true;
2790
1.32k
}
2791
2792
/// Determine the declaration specifier context from the declarator
2793
/// context.
2794
///
2795
/// \param Context the declarator context, which is one of the
2796
/// DeclaratorContext enumerator values.
2797
Parser::DeclSpecContext
2798
8.35M
Parser::getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context) {
2799
8.35M
  if (Context == DeclaratorContext::Member)
2800
0
    return DeclSpecContext::DSC_class;
2801
8.35M
  if (Context == DeclaratorContext::File)
2802
2.86M
    return DeclSpecContext::DSC_top_level;
2803
5.49M
  if (Context == DeclaratorContext::TemplateParam)
2804
0
    return DeclSpecContext::DSC_template_param;
2805
5.49M
  if (Context == DeclaratorContext::TemplateArg ||
2806
5.49M
      
Context == DeclaratorContext::TemplateTypeArg1.79M
)
2807
3.79M
    return DeclSpecContext::DSC_template_type_arg;
2808
1.69M
  if (Context == DeclaratorContext::TrailingReturn ||
2809
1.69M
      
Context == DeclaratorContext::TrailingReturnVar1.69M
)
2810
14.1k
    return DeclSpecContext::DSC_trailing;
2811
1.68M
  if (Context == DeclaratorContext::AliasDecl ||
2812
1.68M
      
Context == DeclaratorContext::AliasTemplate1.65M
)
2813
74.3k
    return DeclSpecContext::DSC_alias_declaration;
2814
1.60M
  return DeclSpecContext::DSC_normal;
2815
1.68M
}
2816
2817
/// ParseAlignArgument - Parse the argument to an alignment-specifier.
2818
///
2819
/// FIXME: Simply returns an alignof() expression if the argument is a
2820
/// type. Ideally, the type should be propagated directly into Sema.
2821
///
2822
/// [C11]   type-id
2823
/// [C11]   constant-expression
2824
/// [C++0x] type-id ...[opt]
2825
/// [C++0x] assignment-expression ...[opt]
2826
ExprResult Parser::ParseAlignArgument(SourceLocation Start,
2827
9.45k
                                      SourceLocation &EllipsisLoc) {
2828
9.45k
  ExprResult ER;
2829
9.45k
  if (isTypeIdInParens()) {
2830
499
    SourceLocation TypeLoc = Tok.getLocation();
2831
499
    ParsedType Ty = ParseTypeName().get();
2832
499
    SourceRange TypeRange(Start, Tok.getLocation());
2833
499
    ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
2834
499
                                               Ty.getAsOpaquePtr(), TypeRange);
2835
499
  } else
2836
8.95k
    ER = ParseConstantExpression();
2837
2838
9.45k
  if (getLangOpts().CPlusPlus11)
2839
9.40k
    TryConsumeToken(tok::ellipsis, EllipsisLoc);
2840
2841
9.45k
  return ER;
2842
9.45k
}
2843
2844
/// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
2845
/// attribute to Attrs.
2846
///
2847
/// alignment-specifier:
2848
/// [C11]   '_Alignas' '(' type-id ')'
2849
/// [C11]   '_Alignas' '(' constant-expression ')'
2850
/// [C++11] 'alignas' '(' type-id ...[opt] ')'
2851
/// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
2852
void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
2853
9.45k
                                     SourceLocation *EndLoc) {
2854
9.45k
  assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
2855
9.45k
         "Not an alignment-specifier!");
2856
2857
0
  IdentifierInfo *KWName = Tok.getIdentifierInfo();
2858
9.45k
  SourceLocation KWLoc = ConsumeToken();
2859
2860
9.45k
  BalancedDelimiterTracker T(*this, tok::l_paren);
2861
9.45k
  if (T.expectAndConsume())
2862
1
    return;
2863
2864
9.45k
  SourceLocation EllipsisLoc;
2865
9.45k
  ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
2866
9.45k
  if (ArgExpr.isInvalid()) {
2867
10
    T.skipToEnd();
2868
10
    return;
2869
10
  }
2870
2871
9.44k
  T.consumeClose();
2872
9.44k
  if (EndLoc)
2873
8.26k
    *EndLoc = T.getCloseLocation();
2874
2875
9.44k
  ArgsVector ArgExprs;
2876
9.44k
  ArgExprs.push_back(ArgExpr.get());
2877
9.44k
  Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
2878
9.44k
               ParsedAttr::AS_Keyword, EllipsisLoc);
2879
9.44k
}
2880
2881
953
ExprResult Parser::ParseExtIntegerArgument() {
2882
953
  assert(Tok.is(tok::kw__ExtInt) && "Not an extended int type");
2883
0
  ConsumeToken();
2884
2885
953
  BalancedDelimiterTracker T(*this, tok::l_paren);
2886
953
  if (T.expectAndConsume())
2887
1
    return ExprError();
2888
2889
952
  ExprResult ER = ParseConstantExpression();
2890
952
  if (ER.isInvalid()) {
2891
1
    T.skipToEnd();
2892
1
    return ExprError();
2893
1
  }
2894
2895
951
  if(T.consumeClose())
2896
1
    return ExprError();
2897
950
  return ER;
2898
951
}
2899
2900
/// Determine whether we're looking at something that might be a declarator
2901
/// in a simple-declaration. If it can't possibly be a declarator, maybe
2902
/// diagnose a missing semicolon after a prior tag definition in the decl
2903
/// specifier.
2904
///
2905
/// \return \c true if an error occurred and this can't be any kind of
2906
/// declaration.
2907
bool
2908
Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
2909
                                              DeclSpecContext DSContext,
2910
1.11M
                                              LateParsedAttrList *LateAttrs) {
2911
1.11M
  assert(DS.hasTagDefinition() && "shouldn't call this");
2912
2913
1.11M
  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
2914
1.11M
                          
DSContext == DeclSpecContext::DSC_top_level1.07M
);
2915
2916
1.11M
  if (getLangOpts().CPlusPlus &&
2917
1.11M
      Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
2918
342k
                  tok::annot_template_id) &&
2919
1.11M
      
TryAnnotateCXXScopeToken(EnteringContext)59.2k
) {
2920
0
    SkipMalformedDecl();
2921
0
    return true;
2922
0
  }
2923
2924
1.11M
  bool HasScope = Tok.is(tok::annot_cxxscope);
2925
  // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
2926
1.11M
  Token AfterScope = HasScope ? 
NextToken()20
:
Tok1.11M
;
2927
2928
  // Determine whether the following tokens could possibly be a
2929
  // declarator.
2930
1.11M
  bool MightBeDeclarator = true;
2931
1.11M
  if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
2932
    // A declarator-id can't start with 'typename'.
2933
0
    MightBeDeclarator = false;
2934
1.11M
  } else if (AfterScope.is(tok::annot_template_id)) {
2935
    // If we have a type expressed as a template-id, this cannot be a
2936
    // declarator-id (such a type cannot be redeclared in a simple-declaration).
2937
8
    TemplateIdAnnotation *Annot =
2938
8
        static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
2939
8
    if (Annot->Kind == TNK_Type_template)
2940
8
      MightBeDeclarator = false;
2941
1.11M
  } else if (AfterScope.is(tok::identifier)) {
2942
263k
    const Token &Next = HasScope ? 
GetLookAheadToken(2)10
:
NextToken()263k
;
2943
2944
    // These tokens cannot come after the declarator-id in a
2945
    // simple-declaration, and are likely to come after a type-specifier.
2946
263k
    if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
2947
263k
                     tok::annot_cxxscope, tok::coloncolon)) {
2948
      // Missing a semicolon.
2949
5
      MightBeDeclarator = false;
2950
263k
    } else if (HasScope) {
2951
      // If the declarator-id has a scope specifier, it must redeclare a
2952
      // previously-declared entity. If that's a type (and this is not a
2953
      // typedef), that's an error.
2954
9
      CXXScopeSpec SS;
2955
9
      Actions.RestoreNestedNameSpecifierAnnotation(
2956
9
          Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
2957
9
      IdentifierInfo *Name = AfterScope.getIdentifierInfo();
2958
9
      Sema::NameClassification Classification = Actions.ClassifyName(
2959
9
          getCurScope(), SS, Name, AfterScope.getLocation(), Next,
2960
9
          /*CCC=*/nullptr);
2961
9
      switch (Classification.getKind()) {
2962
0
      case Sema::NC_Error:
2963
0
        SkipMalformedDecl();
2964
0
        return true;
2965
2966
0
      case Sema::NC_Keyword:
2967
0
        llvm_unreachable("typo correction is not possible here");
2968
2969
1
      case Sema::NC_Type:
2970
1
      case Sema::NC_TypeTemplate:
2971
1
      case Sema::NC_UndeclaredNonType:
2972
1
      case Sema::NC_UndeclaredTemplate:
2973
        // Not a previously-declared non-type entity.
2974
1
        MightBeDeclarator = false;
2975
1
        break;
2976
2977
1
      case Sema::NC_Unknown:
2978
5
      case Sema::NC_NonType:
2979
5
      case Sema::NC_DependentNonType:
2980
8
      case Sema::NC_OverloadSet:
2981
8
      case Sema::NC_VarTemplate:
2982
8
      case Sema::NC_FunctionTemplate:
2983
8
      case Sema::NC_Concept:
2984
        // Might be a redeclaration of a prior entity.
2985
8
        break;
2986
9
      }
2987
9
    }
2988
263k
  }
2989
2990
1.11M
  if (MightBeDeclarator)
2991
1.11M
    return false;
2992
2993
14
  const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
2994
14
  Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getEndLoc()),
2995
14
       diag::err_expected_after)
2996
14
      << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
2997
2998
  // Try to recover from the typo, by dropping the tag definition and parsing
2999
  // the problematic tokens as a type.
3000
  //
3001
  // FIXME: Split the DeclSpec into pieces for the standalone
3002
  // declaration and pieces for the following declaration, instead
3003
  // of assuming that all the other pieces attach to new declaration,
3004
  // and call ParsedFreeStandingDeclSpec as appropriate.
3005
14
  DS.ClearTypeSpecType();
3006
14
  ParsedTemplateInfo NotATemplate;
3007
14
  ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
3008
14
  return false;
3009
1.11M
}
3010
3011
// Choose the apprpriate diagnostic error for why fixed point types are
3012
// disabled, set the previous specifier, and mark as invalid.
3013
static void SetupFixedPointError(const LangOptions &LangOpts,
3014
                                 const char *&PrevSpec, unsigned &DiagID,
3015
9
                                 bool &isInvalid) {
3016
9
  assert(!LangOpts.FixedPoint);
3017
0
  DiagID = diag::err_fixed_point_not_enabled;
3018
9
  PrevSpec = "";  // Not used by diagnostic
3019
9
  isInvalid = true;
3020
9
}
3021
3022
/// ParseDeclarationSpecifiers
3023
///       declaration-specifiers: [C99 6.7]
3024
///         storage-class-specifier declaration-specifiers[opt]
3025
///         type-specifier declaration-specifiers[opt]
3026
/// [C99]   function-specifier declaration-specifiers[opt]
3027
/// [C11]   alignment-specifier declaration-specifiers[opt]
3028
/// [GNU]   attributes declaration-specifiers[opt]
3029
/// [Clang] '__module_private__' declaration-specifiers[opt]
3030
/// [ObjC1] '__kindof' declaration-specifiers[opt]
3031
///
3032
///       storage-class-specifier: [C99 6.7.1]
3033
///         'typedef'
3034
///         'extern'
3035
///         'static'
3036
///         'auto'
3037
///         'register'
3038
/// [C++]   'mutable'
3039
/// [C++11] 'thread_local'
3040
/// [C11]   '_Thread_local'
3041
/// [GNU]   '__thread'
3042
///       function-specifier: [C99 6.7.4]
3043
/// [C99]   'inline'
3044
/// [C++]   'virtual'
3045
/// [C++]   'explicit'
3046
/// [OpenCL] '__kernel'
3047
///       'friend': [C++ dcl.friend]
3048
///       'constexpr': [C++0x dcl.constexpr]
3049
void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
3050
                                        const ParsedTemplateInfo &TemplateInfo,
3051
                                        AccessSpecifier AS,
3052
                                        DeclSpecContext DSContext,
3053
143M
                                        LateParsedAttrList *LateAttrs) {
3054
143M
  if (DS.getSourceRange().isInvalid()) {
3055
    // Start the range at the current token but make the end of the range
3056
    // invalid.  This will make the entire range invalid unless we successfully
3057
    // consume a token.
3058
143M
    DS.SetRangeStart(Tok.getLocation());
3059
143M
    DS.SetRangeEnd(SourceLocation());
3060
143M
  }
3061
3062
143M
  bool EnteringContext = (DSContext == DeclSpecContext::DSC_class ||
3063
143M
                          
DSContext == DeclSpecContext::DSC_top_level141M
);
3064
143M
  bool AttrsLastTime = false;
3065
143M
  ParsedAttributesWithRange attrs(AttrFactory);
3066
  // We use Sema's policy to get bool macros right.
3067
143M
  PrintingPolicy Policy = Actions.getPrintingPolicy();
3068
388M
  while (1) {
3069
388M
    bool isInvalid = false;
3070
388M
    bool isStorageClass = false;
3071
388M
    const char *PrevSpec = nullptr;
3072
388M
    unsigned DiagID = 0;
3073
3074
    // This value needs to be set to the location of the last token if the last
3075
    // token of the specifier is already consumed.
3076
388M
    SourceLocation ConsumedEnd;
3077
3078
    // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
3079
    // implementation for VS2013 uses _Atomic as an identifier for one of the
3080
    // classes in <atomic>.
3081
    //
3082
    // A typedef declaration containing _Atomic<...> is among the places where
3083
    // the class is used.  If we are currently parsing such a declaration, treat
3084
    // the token as an identifier.
3085
388M
    if (getLangOpts().MSVCCompat && 
Tok.is(tok::kw__Atomic)1.00M
&&
3086
388M
        
DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef37
&&
3087
388M
        
!DS.hasTypeSpecifier()6
&&
GetLookAheadToken(1).is(tok::less)6
)
3088
4
      Tok.setKind(tok::identifier);
3089
3090
388M
    SourceLocation Loc = Tok.getLocation();
3091
3092
    // Helper for image types in OpenCL.
3093
388M
    auto handleOpenCLImageKW = [&] (StringRef Ext, TypeSpecifierType ImageTypeSpec) {
3094
      // Check if the image type is supported and otherwise turn the keyword into an identifier
3095
      // because image types from extensions are not reserved identifiers.
3096
8.20k
      if (!StringRef(Ext).empty() && 
!getActions().getOpenCLOptions().isSupported(Ext, getLangOpts())1.08k
) {
3097
4
        Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3098
4
        Tok.setKind(tok::identifier);
3099
4
        return false;
3100
4
      }
3101
8.20k
      isInvalid = DS.SetTypeSpecType(ImageTypeSpec, Loc, PrevSpec, DiagID, Policy);
3102
8.20k
      return true;
3103
8.20k
    };
3104
3105
    // Turn off usual access checking for template specializations and
3106
    // instantiations.
3107
388M
    bool IsTemplateSpecOrInst =
3108
388M
        (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
3109
388M
         
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization388M
);
3110
3111
388M
    switch (Tok.getKind()) {
3112
81.3M
    default:
3113
143M
    DoneWithDeclSpec:
3114
143M
      if (!AttrsLastTime)
3115
143M
        ProhibitAttributes(attrs);
3116
39
      else {
3117
        // Reject C++11 attributes that appertain to decl specifiers as
3118
        // we don't support any C++11 attributes that appertain to decl
3119
        // specifiers. This also conforms to what g++ 4.8 is doing.
3120
39
        ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
3121
3122
39
        DS.takeAttributesFrom(attrs);
3123
39
      }
3124
3125
      // If this is not a declaration specifier token, we're done reading decl
3126
      // specifiers.  First verify that DeclSpec's are consistent.
3127
143M
      DS.Finish(Actions, Policy);
3128
143M
      return;
3129
3130
21.5k
    case tok::l_square:
3131
21.5k
    case tok::kw_alignas:
3132
21.5k
      if (!standardAttributesAllowed() || 
!isCXX11AttributeSpecifier()14.3k
)
3133
21.4k
        goto DoneWithDeclSpec;
3134
3135
52
      ProhibitAttributes(attrs);
3136
      // FIXME: It would be good to recover by accepting the attributes,
3137
      //        but attempting to do that now would cause serious
3138
      //        madness in terms of diagnostics.
3139
52
      attrs.clear();
3140
52
      attrs.Range = SourceRange();
3141
3142
52
      ParseCXX11Attributes(attrs);
3143
52
      AttrsLastTime = true;
3144
52
      continue;
3145
3146
45
    case tok::code_completion: {
3147
45
      Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
3148
45
      if (DS.hasTypeSpecifier()) {
3149
35
        bool AllowNonIdentifiers
3150
35
          = (getCurScope()->getFlags() & (Scope::ControlScope |
3151
35
                                          Scope::BlockScope |
3152
35
                                          Scope::TemplateParamScope |
3153
35
                                          Scope::FunctionPrototypeScope |
3154
35
                                          Scope::AtCatchScope)) == 0;
3155
35
        bool AllowNestedNameSpecifiers
3156
35
          = DSContext == DeclSpecContext::DSC_top_level ||
3157
35
            
(24
DSContext == DeclSpecContext::DSC_class24
&&
DS.isFriendSpecified()13
);
3158
3159
35
        cutOffParsing();
3160
35
        Actions.CodeCompleteDeclSpec(getCurScope(), DS,
3161
35
                                     AllowNonIdentifiers,
3162
35
                                     AllowNestedNameSpecifiers);
3163
35
        return;
3164
35
      }
3165
3166
10
      if (getCurScope()->getFnParent() || 
getCurScope()->getBlockParent()9
)
3167
1
        CCC = Sema::PCC_LocalDeclarationSpecifiers;
3168
9
      else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
3169
0
        CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
3170
0
                                                      : Sema::PCC_Template;
3171
9
      else if (DSContext == DeclSpecContext::DSC_class)
3172
8
        CCC = Sema::PCC_Class;
3173
1
      else if (CurParsedObjCImpl)
3174
0
        CCC = Sema::PCC_ObjCImplementation;
3175
3176
10
      cutOffParsing();
3177
10
      Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
3178
10
      return;
3179
45
    }
3180
3181
620
    case tok::coloncolon: // ::foo::bar
3182
      // C++ scope specifier.  Annotate and loop, or bail out on error.
3183
620
      if (TryAnnotateCXXScopeToken(EnteringContext)) {
3184
0
        if (!DS.hasTypeSpecifier())
3185
0
          DS.SetTypeSpecError();
3186
0
        goto DoneWithDeclSpec;
3187
0
      }
3188
620
      if (Tok.is(tok::coloncolon)) // ::new or ::delete
3189
3
        goto DoneWithDeclSpec;
3190
617
      continue;
3191
3192
142k
    case tok::annot_cxxscope: {
3193
142k
      if (DS.hasTypeSpecifier() || 
DS.isTypeAltiVecVector()142k
)
3194
59
        goto DoneWithDeclSpec;
3195
3196
142k
      CXXScopeSpec SS;
3197
142k
      Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3198
142k
                                                   Tok.getAnnotationRange(),
3199
142k
                                                   SS);
3200
3201
      // We are looking for a qualified typename.
3202
142k
      Token Next = NextToken();
3203
3204
142k
      TemplateIdAnnotation *TemplateId = Next.is(tok::annot_template_id)
3205
142k
                                             ? 
takeTemplateIdAnnotation(Next)21.0k
3206
142k
                                             : 
nullptr121k
;
3207
142k
      if (TemplateId && 
TemplateId->hasInvalidName()21.0k
) {
3208
        // We found something like 'T::U<Args> x', but U is not a template.
3209
        // Assume it was supposed to be a type.
3210
6
        DS.SetTypeSpecError();
3211
6
        ConsumeAnnotationToken();
3212
6
        break;
3213
6
      }
3214
3215
142k
      if (TemplateId && 
TemplateId->Kind == TNK_Type_template20.9k
) {
3216
        // We have a qualified template-id, e.g., N::A<int>
3217
3218
        // If this would be a valid constructor declaration with template
3219
        // arguments, we will reject the attempt to form an invalid type-id
3220
        // referring to the injected-class-name when we annotate the token,
3221
        // per C++ [class.qual]p2.
3222
        //
3223
        // To improve diagnostics for this case, parse the declaration as a
3224
        // constructor (and reject the extra template arguments later).
3225
20.9k
        if ((DSContext == DeclSpecContext::DSC_top_level ||
3226
20.9k
             
DSContext == DeclSpecContext::DSC_class17.6k
) &&
3227
20.9k
            
TemplateId->Name10.0k
&&
3228
20.9k
            
Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)10.0k
&&
3229
20.9k
            
isConstructorDeclarator(/*Unqualified=*/false)25
) {
3230
          // The user meant this to be an out-of-line constructor
3231
          // definition, but template arguments are not allowed
3232
          // there.  Just allow this as a constructor; we'll
3233
          // complain about it later.
3234
16
          goto DoneWithDeclSpec;
3235
16
        }
3236
3237
20.9k
        DS.getTypeSpecScope() = SS;
3238
20.9k
        ConsumeAnnotationToken(); // The C++ scope.
3239
20.9k
        assert(Tok.is(tok::annot_template_id) &&
3240
20.9k
               "ParseOptionalCXXScopeSpecifier not working");
3241
0
        AnnotateTemplateIdTokenAsType(SS);
3242
20.9k
        continue;
3243
20.9k
      }
3244
3245
121k
      if (TemplateId && 
TemplateId->Kind == TNK_Concept_template33
&&
3246
121k
          
GetLookAheadToken(2).isOneOf(tok::kw_auto, tok::kw_decltype)25
) {
3247
25
        DS.getTypeSpecScope() = SS;
3248
        // This is a qualified placeholder-specifier, e.g., ::C<int> auto ...
3249
        // Consume the scope annotation and continue to consume the template-id
3250
        // as a placeholder-specifier.
3251
25
        ConsumeAnnotationToken();
3252
25
        continue;
3253
25
      }
3254
3255
121k
      if (Next.is(tok::annot_typename)) {
3256
0
        DS.getTypeSpecScope() = SS;
3257
0
        ConsumeAnnotationToken(); // The C++ scope.
3258
0
        TypeResult T = getTypeAnnotation(Tok);
3259
0
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
3260
0
                                       Tok.getAnnotationEndLoc(),
3261
0
                                       PrevSpec, DiagID, T, Policy);
3262
0
        if (isInvalid)
3263
0
          break;
3264
0
        DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3265
0
        ConsumeAnnotationToken(); // The typename
3266
0
      }
3267
3268
121k
      if (Next.isNot(tok::identifier))
3269
4.87k
        goto DoneWithDeclSpec;
3270
3271
      // Check whether this is a constructor declaration. If we're in a
3272
      // context where the identifier could be a class name, and it has the
3273
      // shape of a constructor declaration, process it as one.
3274
116k
      if ((DSContext == DeclSpecContext::DSC_top_level ||
3275
116k
           
DSContext == DeclSpecContext::DSC_class67.1k
) &&
3276
116k
          Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
3277
69.7k
                                     &SS) &&
3278
116k
          
isConstructorDeclarator(/*Unqualified*/ false)35.7k
)
3279
35.7k
        goto DoneWithDeclSpec;
3280
3281
      // C++20 [temp.spec] 13.9/6.
3282
      // This disables the access checking rules for function template explicit
3283
      // instantiation and explicit specialization:
3284
      // - `return type`.
3285
80.3k
      SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3286
3287
80.3k
      ParsedType TypeRep =
3288
80.3k
          Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
3289
80.3k
                              getCurScope(), &SS, false, false, nullptr,
3290
80.3k
                              /*IsCtorOrDtorName=*/false,
3291
80.3k
                              /*WantNontrivialTypeSourceInfo=*/true,
3292
80.3k
                              isClassTemplateDeductionContext(DSContext));
3293
3294
80.3k
      if (IsTemplateSpecOrInst)
3295
7.39k
        SAC.done();
3296
3297
      // If the referenced identifier is not a type, then this declspec is
3298
      // erroneous: We already checked about that it has no type specifier, and
3299
      // C++ doesn't have implicit int.  Diagnose it as a typo w.r.t. to the
3300
      // typename.
3301
80.3k
      if (!TypeRep) {
3302
529
        if (TryAnnotateTypeConstraint())
3303
0
          goto DoneWithDeclSpec;
3304
529
        if (Tok.isNot(tok::annot_cxxscope) ||
3305
529
            NextToken().isNot(tok::identifier))
3306
9
          continue;
3307
        // Eat the scope spec so the identifier is current.
3308
520
        ConsumeAnnotationToken();
3309
520
        ParsedAttributesWithRange Attrs(AttrFactory);
3310
520
        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
3311
471
          if (!Attrs.empty()) {
3312
0
            AttrsLastTime = true;
3313
0
            attrs.takeAllFrom(Attrs);
3314
0
          }
3315
471
          continue;
3316
471
        }
3317
49
        goto DoneWithDeclSpec;
3318
520
      }
3319
3320
79.8k
      DS.getTypeSpecScope() = SS;
3321
79.8k
      ConsumeAnnotationToken(); // The C++ scope.
3322
3323
79.8k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3324
79.8k
                                     DiagID, TypeRep, Policy);
3325
79.8k
      if (isInvalid)
3326
0
        break;
3327
3328
79.8k
      DS.SetRangeEnd(Tok.getLocation());
3329
79.8k
      ConsumeToken(); // The typename.
3330
3331
79.8k
      continue;
3332
79.8k
    }
3333
3334
39.1M
    case tok::annot_typename: {
3335
      // If we've previously seen a tag definition, we were almost surely
3336
      // missing a semicolon after it.
3337
39.1M
      if (DS.hasTypeSpecifier() && 
DS.hasTagDefinition()3
)
3338
0
        goto DoneWithDeclSpec;
3339
3340
39.1M
      TypeResult T = getTypeAnnotation(Tok);
3341
39.1M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3342
39.1M
                                     DiagID, T, Policy);
3343
39.1M
      if (isInvalid)
3344
3
        break;
3345
3346
39.1M
      DS.SetRangeEnd(Tok.getAnnotationEndLoc());
3347
39.1M
      ConsumeAnnotationToken(); // The typename
3348
3349
39.1M
      continue;
3350
39.1M
    }
3351
3352
1
    case tok::kw___is_signed:
3353
      // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
3354
      // typically treats it as a trait. If we see __is_signed as it appears
3355
      // in libstdc++, e.g.,
3356
      //
3357
      //   static const bool __is_signed;
3358
      //
3359
      // then treat __is_signed as an identifier rather than as a keyword.
3360
1
      if (DS.getTypeSpecType() == TST_bool &&
3361
1
          DS.getTypeQualifiers() == DeclSpec::TQ_const &&
3362
1
          DS.getStorageClassSpec() == DeclSpec::SCS_static)
3363
1
        TryKeywordIdentFallback(true);
3364
3365
      // We're done with the declaration-specifiers.
3366
1
      goto DoneWithDeclSpec;
3367
3368
      // typedef-name
3369
7
    case tok::kw___super:
3370
26.5k
    case tok::kw_decltype:
3371
154M
    case tok::identifier: {
3372
      // This identifier can only be a typedef name if we haven't already seen
3373
      // a type-specifier.  Without this check we misparse:
3374
      //  typedef int X; struct Y { short X; };  as 'short int'.
3375
154M
      if (DS.hasTypeSpecifier())
3376
62.2M
        goto DoneWithDeclSpec;
3377
3378
      // If the token is an identifier named "__declspec" and Microsoft
3379
      // extensions are not enabled, it is likely that there will be cascading
3380
      // parse errors if this really is a __declspec attribute. Attempt to
3381
      // recognize that scenario and recover gracefully.
3382
92.2M
      if (!getLangOpts().DeclSpecKeyword && 
Tok.is(tok::identifier)92.0M
&&
3383
92.2M
          
Tok.getIdentifierInfo()->getName().equals("__declspec")92.0M
) {
3384
2
        Diag(Loc, diag::err_ms_attributes_not_enabled);
3385
3386
        // The next token should be an open paren. If it is, eat the entire
3387
        // attribute declaration and continue.
3388
2
        if (NextToken().is(tok::l_paren)) {
3389
          // Consume the __declspec identifier.
3390
2
          ConsumeToken();
3391
3392
          // Eat the parens and everything between them.
3393
2
          BalancedDelimiterTracker T(*this, tok::l_paren);
3394
2
          if (T.consumeOpen()) {
3395
0
            assert(false && "Not a left paren?");
3396
0
            return;
3397
0
          }
3398
2
          T.skipToEnd();
3399
2
          continue;
3400
2
        }
3401
2
      }
3402
3403
      // In C++, check to see if this is a scope specifier like foo::bar::, if
3404
      // so handle it as such.  This is important for ctor parsing.
3405
92.2M
      if (getLangOpts().CPlusPlus) {
3406
        // C++20 [temp.spec] 13.9/6.
3407
        // This disables the access checking rules for function template
3408
        // explicit instantiation and explicit specialization:
3409
        // - `return type`.
3410
26.7M
        SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
3411
3412
26.7M
        const bool Success = TryAnnotateCXXScopeToken(EnteringContext);
3413
3414
26.7M
        if (IsTemplateSpecOrInst)
3415
23.8k
          SAC.done();
3416
3417
26.7M
        if (Success) {
3418
24
          if (IsTemplateSpecOrInst)
3419
0
            SAC.redelay();
3420
24
          DS.SetTypeSpecError();
3421
24
          goto DoneWithDeclSpec;
3422
24
        }
3423
3424
26.7M
        if (!Tok.is(tok::identifier))
3425
767k
          continue;
3426
26.7M
      }
3427
3428
      // Check for need to substitute AltiVec keyword tokens.
3429
91.4M
      if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
3430
435k
        break;
3431
3432
      // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
3433
      //                allow the use of a typedef name as a type specifier.
3434
91.0M
      if (DS.isTypeAltiVecVector())
3435
9.26k
        goto DoneWithDeclSpec;
3436
3437
91.0M
      if (DSContext == DeclSpecContext::DSC_objc_method_result &&
3438
91.0M
          
isObjCInstancetype()110k
) {
3439
109k
        ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
3440
109k
        assert(TypeRep);
3441
0
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3442
109k
                                       DiagID, TypeRep, Policy);
3443
109k
        if (isInvalid)
3444
0
          break;
3445
3446
109k
        DS.SetRangeEnd(Loc);
3447
109k
        ConsumeToken();
3448
109k
        continue;
3449
109k
      }
3450
3451
      // If we're in a context where the identifier could be a class name,
3452
      // check whether this is a constructor declaration.
3453
90.9M
      if (getLangOpts().CPlusPlus && 
DSContext == DeclSpecContext::DSC_class25.9M
&&
3454
90.9M
          
Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope())1.44M
&&
3455
90.9M
          
isConstructorDeclarator(/*Unqualified*/true)352k
)
3456
241k
        goto DoneWithDeclSpec;
3457
3458
90.6M
      ParsedType TypeRep = Actions.getTypeName(
3459
90.6M
          *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
3460
90.6M
          false, false, nullptr, false, false,
3461
90.6M
          isClassTemplateDeductionContext(DSContext));
3462
3463
      // If this is not a typedef name, don't parse it as part of the declspec,
3464
      // it must be an implicit int or an error.
3465
90.6M
      if (!TypeRep) {
3466
1.24k
        if (TryAnnotateTypeConstraint())
3467
0
          goto DoneWithDeclSpec;
3468
1.24k
        if (Tok.isNot(tok::identifier))
3469
21
          continue;
3470
1.22k
        ParsedAttributesWithRange Attrs(AttrFactory);
3471
1.22k
        if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
3472
894
          if (!Attrs.empty()) {
3473
0
            AttrsLastTime = true;
3474
0
            attrs.takeAllFrom(Attrs);
3475
0
          }
3476
894
          continue;
3477
894
        }
3478
332
        goto DoneWithDeclSpec;
3479
1.22k
      }
3480
3481
      // Likewise, if this is a context where the identifier could be a template
3482
      // name, check whether this is a deduction guide declaration.
3483
90.6M
      if (getLangOpts().CPlusPlus17 &&
3484
90.6M
          
(196k
DSContext == DeclSpecContext::DSC_class196k
||
3485
196k
           
DSContext == DeclSpecContext::DSC_top_level163k
) &&
3486
90.6M
          Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
3487
80.0k
                                       Tok.getLocation()) &&
3488
90.6M
          isConstructorDeclarator(/*Unqualified*/ true,
3489
639
                                  /*DeductionGuide*/ true))
3490
423
        goto DoneWithDeclSpec;
3491
3492
90.6M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
3493
90.6M
                                     DiagID, TypeRep, Policy);
3494
90.6M
      if (isInvalid)
3495
0
        break;
3496
3497
90.6M
      DS.SetRangeEnd(Tok.getLocation());
3498
90.6M
      ConsumeToken(); // The identifier
3499
3500
      // Objective-C supports type arguments and protocol references
3501
      // following an Objective-C object or object pointer
3502
      // type. Handle either one of them.
3503
90.6M
      if (Tok.is(tok::less) && 
getLangOpts().ObjC51.9k
) {
3504
51.9k
        SourceLocation NewEndLoc;
3505
51.9k
        TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
3506
51.9k
                                  Loc, TypeRep, /*consumeLastToken=*/true,
3507
51.9k
                                  NewEndLoc);
3508
51.9k
        if (NewTypeRep.isUsable()) {
3509
51.9k
          DS.UpdateTypeRep(NewTypeRep.get());
3510
51.9k
          DS.SetRangeEnd(NewEndLoc);
3511
51.9k
        }
3512
51.9k
      }
3513
3514
      // Need to support trailing type qualifiers (e.g. "id<p> const").
3515
      // If a type specifier follows, it will be diagnosed elsewhere.
3516
90.6M
      continue;
3517
90.6M
    }
3518
3519
      // type-name or placeholder-specifier
3520
621k
    case tok::annot_template_id: {
3521
621k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3522
3523
621k
      if (TemplateId->hasInvalidName()) {
3524
0
        DS.SetTypeSpecError();
3525
0
        break;
3526
0
      }
3527
3528
621k
      if (TemplateId->Kind == TNK_Concept_template) {
3529
        // If we've already diagnosed that this type-constraint has invalid
3530
        // arguemnts, drop it and just form 'auto' or 'decltype(auto)'.
3531
140
        if (TemplateId->hasInvalidArgs())
3532
2
          TemplateId = nullptr;
3533
3534
140
        if (NextToken().is(tok::identifier)) {
3535
1
          Diag(Loc, diag::err_placeholder_expected_auto_or_decltype_auto)
3536
1
              << FixItHint::CreateInsertion(NextToken().getLocation(), "auto");
3537
          // Attempt to continue as if 'auto' was placed here.
3538
1
          isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3539
1
                                         TemplateId, Policy);
3540
1
          break;
3541
1
        }
3542
139
        if (!NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
3543
0
            goto DoneWithDeclSpec;
3544
139
        ConsumeAnnotationToken();
3545
139
        SourceLocation AutoLoc = Tok.getLocation();
3546
139
        if (TryConsumeToken(tok::kw_decltype)) {
3547
13
          BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3548
13
          if (Tracker.consumeOpen()) {
3549
            // Something like `void foo(Iterator decltype i)`
3550
1
            Diag(Tok, diag::err_expected) << tok::l_paren;
3551
12
          } else {
3552
12
            if (!TryConsumeToken(tok::kw_auto)) {
3553
              // Something like `void foo(Iterator decltype(int) i)`
3554
1
              Tracker.skipToEnd();
3555
1
              Diag(Tok, diag::err_placeholder_expected_auto_or_decltype_auto)
3556
1
                << FixItHint::CreateReplacement(SourceRange(AutoLoc,
3557
1
                                                            Tok.getLocation()),
3558
1
                                                "auto");
3559
11
            } else {
3560
11
              Tracker.consumeClose();
3561
11
            }
3562
12
          }
3563
13
          ConsumedEnd = Tok.getLocation();
3564
          // Even if something went wrong above, continue as if we've seen
3565
          // `decltype(auto)`.
3566
13
          isInvalid = DS.SetTypeSpecType(TST_decltype_auto, Loc, PrevSpec,
3567
13
                                         DiagID, TemplateId, Policy);
3568
126
        } else {
3569
126
          isInvalid = DS.SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID,
3570
126
                                         TemplateId, Policy);
3571
126
        }
3572
139
        break;
3573
139
      }
3574
3575
621k
      if (TemplateId->Kind != TNK_Type_template &&
3576
621k
          
TemplateId->Kind != TNK_Undeclared_template111
) {
3577
        // This template-id does not refer to a type name, so we're
3578
        // done with the type-specifiers.
3579
12
        goto DoneWithDeclSpec;
3580
12
      }
3581
3582
      // If we're in a context where the template-id could be a
3583
      // constructor name or specialization, check whether this is a
3584
      // constructor declaration.
3585
621k
      if (getLangOpts().CPlusPlus && DSContext == DeclSpecContext::DSC_class &&
3586
621k
          
Actions.isCurrentClassName(*TemplateId->Name, getCurScope())67.7k
&&
3587
621k
          
isConstructorDeclarator(/*Unqualified=*/true)11.5k
)
3588
30
        goto DoneWithDeclSpec;
3589
3590
      // Turn the template-id annotation token into a type annotation
3591
      // token, then try again to parse it as a type-specifier.
3592
621k
      CXXScopeSpec SS;
3593
621k
      AnnotateTemplateIdTokenAsType(SS);
3594
621k
      continue;
3595
621k
    }
3596
3597
    // Attributes support.
3598
29.8M
    case tok::kw___attribute:
3599
29.8M
    case tok::kw___declspec:
3600
29.8M
      ParseAttributes(PAKM_GNU | PAKM_Declspec, DS.getAttributes(), nullptr,
3601
29.8M
                      LateAttrs);
3602
29.8M
      continue;
3603
3604
    // Microsoft single token adornments.
3605
23
    case tok::kw___forceinline: {
3606
23
      isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
3607
23
      IdentifierInfo *AttrName = Tok.getIdentifierInfo();
3608
23
      SourceLocation AttrNameLoc = Tok.getLocation();
3609
23
      DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
3610
23
                                nullptr, 0, ParsedAttr::AS_Keyword);
3611
23
      break;
3612
29.8M
    }
3613
3614
129
    case tok::kw___unaligned:
3615
129
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
3616
129
                                 getLangOpts());
3617
129
      break;
3618
3619
2
    case tok::kw___sptr:
3620
2
    case tok::kw___uptr:
3621
2
    case tok::kw___ptr64:
3622
6
    case tok::kw___ptr32:
3623
7
    case tok::kw___w64:
3624
273
    case tok::kw___cdecl:
3625
404
    case tok::kw___stdcall:
3626
495
    case tok::kw___fastcall:
3627
530
    case tok::kw___thiscall:
3628
633
    case tok::kw___regcall:
3629
755
    case tok::kw___vectorcall:
3630
755
      ParseMicrosoftTypeAttributes(DS.getAttributes());
3631
755
      continue;
3632
3633
    // Borland single token adornments.
3634
14
    case tok::kw___pascal:
3635
14
      ParseBorlandTypeAttributes(DS.getAttributes());
3636
14
      continue;
3637
3638
    // OpenCL single token adornments.
3639
1.14k
    case tok::kw___kernel:
3640
1.14k
      ParseOpenCLKernelAttributes(DS.getAttributes());
3641
1.14k
      continue;
3642
3643
    // Nullability type specifiers.
3644
36.0k
    case tok::kw__Nonnull:
3645
347k
    case tok::kw__Nullable:
3646
347k
    case tok::kw__Nullable_result:
3647
367k
    case tok::kw__Null_unspecified:
3648
367k
      ParseNullabilityTypeSpecifiers(DS.getAttributes());
3649
367k
      continue;
3650
3651
    // Objective-C 'kindof' types.
3652
1.29k
    case tok::kw___kindof:
3653
1.29k
      DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
3654
1.29k
                                nullptr, 0, ParsedAttr::AS_Keyword);
3655
1.29k
      (void)ConsumeToken();
3656
1.29k
      continue;
3657
3658
    // storage-class-specifier
3659
2.27M
    case tok::kw_typedef:
3660
2.27M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
3661
2.27M
                                         PrevSpec, DiagID, Policy);
3662
2.27M
      isStorageClass = true;
3663
2.27M
      break;
3664
1.97M
    case tok::kw_extern:
3665
1.97M
      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3666
2
        Diag(Tok, diag::ext_thread_before) << "extern";
3667
1.97M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
3668
1.97M
                                         PrevSpec, DiagID, Policy);
3669
1.97M
      isStorageClass = true;
3670
1.97M
      break;
3671
66
    case tok::kw___private_extern__:
3672
66
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
3673
66
                                         Loc, PrevSpec, DiagID, Policy);
3674
66
      isStorageClass = true;
3675
66
      break;
3676
28.1M
    case tok::kw_static:
3677
28.1M
      if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
3678
11
        Diag(Tok, diag::ext_thread_before) << "static";
3679
28.1M
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
3680
28.1M
                                         PrevSpec, DiagID, Policy);
3681
28.1M
      isStorageClass = true;
3682
28.1M
      break;
3683
29.2k
    case tok::kw_auto:
3684
29.2k
      if (getLangOpts().CPlusPlus11) {
3685
29.0k
        if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
3686
35
          isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3687
35
                                             PrevSpec, DiagID, Policy);
3688
35
          if (!isInvalid)
3689
31
            Diag(Tok, diag::ext_auto_storage_class)
3690
31
              << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3691
35
        } else
3692
29.0k
          isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
3693
29.0k
                                         DiagID, Policy);
3694
29.0k
      } else
3695
143
        isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
3696
143
                                           PrevSpec, DiagID, Policy);
3697
29.2k
      isStorageClass = true;
3698
29.2k
      break;
3699
35
    case tok::kw___auto_type:
3700
35
      Diag(Tok, diag::ext_auto_type);
3701
35
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
3702
35
                                     DiagID, Policy);
3703
35
      break;
3704
682
    case tok::kw_register:
3705
682
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
3706
682
                                         PrevSpec, DiagID, Policy);
3707
682
      isStorageClass = true;
3708
682
      break;
3709
3.02k
    case tok::kw_mutable:
3710
3.02k
      isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
3711
3.02k
                                         PrevSpec, DiagID, Policy);
3712
3.02k
      isStorageClass = true;
3713
3.02k
      break;
3714
329
    case tok::kw___thread:
3715
329
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
3716
329
                                               PrevSpec, DiagID);
3717
329
      isStorageClass = true;
3718
329
      break;
3719
567
    case tok::kw_thread_local:
3720
567
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
3721
567
                                               PrevSpec, DiagID);
3722
567
      isStorageClass = true;
3723
567
      break;
3724
98
    case tok::kw__Thread_local:
3725
98
      if (!getLangOpts().C11)
3726
77
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3727
98
      isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
3728
98
                                               Loc, PrevSpec, DiagID);
3729
98
      isStorageClass = true;
3730
98
      break;
3731
3732
    // function-specifier
3733
28.2M
    case tok::kw_inline:
3734
28.2M
      isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
3735
28.2M
      break;
3736
52.1k
    case tok::kw_virtual:
3737
      // C++ for OpenCL does not allow virtual function qualifier, to avoid
3738
      // function pointers restricted in OpenCL v2.0 s6.9.a.
3739
52.1k
      if (getLangOpts().OpenCLCPlusPlus &&
3740
52.1k
          !getActions().getOpenCLOptions().isAvailableOption(
3741
6
              "__cl_clang_function_pointers", getLangOpts())) {
3742
3
        DiagID = diag::err_openclcxx_virtual_function;
3743
3
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
3744
3
        isInvalid = true;
3745
52.1k
      } else {
3746
52.1k
        isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
3747
52.1k
      }
3748
52.1k
      break;
3749
66.4k
    case tok::kw_explicit: {
3750
66.4k
      SourceLocation ExplicitLoc = Loc;
3751
66.4k
      SourceLocation CloseParenLoc;
3752
66.4k
      ExplicitSpecifier ExplicitSpec(nullptr, ExplicitSpecKind::ResolvedTrue);
3753
66.4k
      ConsumedEnd = ExplicitLoc;
3754
66.4k
      ConsumeToken(); // kw_explicit
3755
66.4k
      if (Tok.is(tok::l_paren)) {
3756
148
        if (getLangOpts().CPlusPlus20 || 
isExplicitBool() == TPResult::True44
) {
3757
142
          Diag(Tok.getLocation(), getLangOpts().CPlusPlus20
3758
142
                                      ? 
diag::warn_cxx17_compat_explicit_bool104
3759
142
                                      : 
diag::ext_explicit_bool38
);
3760
3761
142
          ExprResult ExplicitExpr(static_cast<Expr *>(nullptr));
3762
142
          BalancedDelimiterTracker Tracker(*this, tok::l_paren);
3763
142
          Tracker.consumeOpen();
3764
142
          ExplicitExpr = ParseConstantExpression();
3765
142
          ConsumedEnd = Tok.getLocation();
3766
142
          if (ExplicitExpr.isUsable()) {
3767
133
            CloseParenLoc = Tok.getLocation();
3768
133
            Tracker.consumeClose();
3769
133
            ExplicitSpec =
3770
133
                Actions.ActOnExplicitBoolSpecifier(ExplicitExpr.get());
3771
133
          } else
3772
9
            Tracker.skipToEnd();
3773
142
        } else {
3774
6
          Diag(Tok.getLocation(), diag::warn_cxx20_compat_explicit_bool);
3775
6
        }
3776
148
      }
3777
66.4k
      isInvalid = DS.setFunctionSpecExplicit(ExplicitLoc, PrevSpec, DiagID,
3778
66.4k
                                             ExplicitSpec, CloseParenLoc);
3779
66.4k
      break;
3780
347k
    }
3781
66
    case tok::kw__Noreturn:
3782
66
      if (!getLangOpts().C11)
3783
40
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3784
66
      isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
3785
66
      break;
3786
3787
    // alignment-specifier
3788
1.18k
    case tok::kw__Alignas:
3789
1.18k
      if (!getLangOpts().C11)
3790
1.14k
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3791
1.18k
      ParseAlignmentSpecifier(DS.getAttributes());
3792
1.18k
      continue;
3793
3794
    // friend
3795
47.1k
    case tok::kw_friend:
3796
47.1k
      if (DSContext == DeclSpecContext::DSC_class)
3797
47.1k
        isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
3798
15
      else {
3799
15
        PrevSpec = ""; // not actually used by the diagnostic
3800
15
        DiagID = diag::err_friend_invalid_in_context;
3801
15
        isInvalid = true;
3802
15
      }
3803
47.1k
      break;
3804
3805
    // Modules
3806
52
    case tok::kw___module_private__:
3807
52
      isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
3808
52
      break;
3809
3810
    // constexpr, consteval, constinit specifiers
3811
316k
    case tok::kw_constexpr:
3812
316k
      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, Loc,
3813
316k
                                      PrevSpec, DiagID);
3814
316k
      break;
3815
151
    case tok::kw_consteval:
3816
151
      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Consteval, Loc,
3817
151
                                      PrevSpec, DiagID);
3818
151
      break;
3819
75
    case tok::kw_constinit:
3820
75
      isInvalid = DS.SetConstexprSpec(ConstexprSpecKind::Constinit, Loc,
3821
75
                                      PrevSpec, DiagID);
3822
75
      break;
3823
3824
    // type-specifier
3825
424k
    case tok::kw_short:
3826
424k
      isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec,
3827
424k
                                      DiagID, Policy);
3828
424k
      break;
3829
1.01M
    case tok::kw_long:
3830
1.01M
      if (DS.getTypeSpecWidth() != TypeSpecifierWidth::Long)
3831
720k
        isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec,
3832
720k
                                        DiagID, Policy);
3833
291k
      else
3834
291k
        isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
3835
291k
                                        PrevSpec, DiagID, Policy);
3836
1.01M
      break;
3837
3.00k
    case tok::kw___int64:
3838
3.00k
      isInvalid = DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc,
3839
3.00k
                                      PrevSpec, DiagID, Policy);
3840
3.00k
      break;
3841
213k
    case tok::kw_signed:
3842
213k
      isInvalid =
3843
213k
          DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
3844
213k
      break;
3845
1.04M
    case tok::kw_unsigned:
3846
1.04M
      isInvalid = DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec,
3847
1.04M
                                     DiagID);
3848
1.04M
      break;
3849
8.13k
    case tok::kw__Complex:
3850
8.13k
      if (!getLangOpts().C99)
3851
2.24k
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3852
8.13k
      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
3853
8.13k
                                        DiagID);
3854
8.13k
      break;
3855
4
    case tok::kw__Imaginary:
3856
4
      if (!getLangOpts().C99)
3857
2
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3858
4
      isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
3859
4
                                        DiagID);
3860
4
      break;
3861
4.12M
    case tok::kw_void:
3862
4.12M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
3863
4.12M
                                     DiagID, Policy);
3864
4.12M
      break;
3865
1.20M
    case tok::kw_char:
3866
1.20M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
3867
1.20M
                                     DiagID, Policy);
3868
1.20M
      break;
3869
2.52M
    case tok::kw_int:
3870
2.52M
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
3871
2.52M
                                     DiagID, Policy);
3872
2.52M
      break;
3873
953
    case tok::kw__ExtInt: {
3874
953
      ExprResult ER = ParseExtIntegerArgument();
3875
953
      if (ER.isInvalid())
3876
3
        continue;
3877
950
      isInvalid = DS.SetExtIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
3878
950
      ConsumedEnd = PrevTokLocation;
3879
950
      break;
3880
953
    }
3881
8.79k
    case tok::kw___int128:
3882
8.79k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
3883
8.79k
                                     DiagID, Policy);
3884
8.79k
      break;
3885
18.9k
    case tok::kw_half:
3886
18.9k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
3887
18.9k
                                     DiagID, Policy);
3888
18.9k
      break;
3889
704
    case tok::kw___bf16:
3890
704
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec,
3891
704
                                     DiagID, Policy);
3892
704
      break;
3893
380k
    case tok::kw_float:
3894
380k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
3895
380k
                                     DiagID, Policy);
3896
380k
      break;
3897
408k
    case tok::kw_double:
3898
408k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
3899
408k
                                     DiagID, Policy);
3900
408k
      break;
3901
21.9k
    case tok::kw__Float16:
3902
21.9k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
3903
21.9k
                                     DiagID, Policy);
3904
21.9k
      break;
3905
1.01k
    case tok::kw__Accum:
3906
1.01k
      if (!getLangOpts().FixedPoint) {
3907
9
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3908
1.00k
      } else {
3909
1.00k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec,
3910
1.00k
                                       DiagID, Policy);
3911
1.00k
      }
3912
1.01k
      break;
3913
554
    case tok::kw__Fract:
3914
554
      if (!getLangOpts().FixedPoint) {
3915
0
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3916
554
      } else {
3917
554
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec,
3918
554
                                       DiagID, Policy);
3919
554
      }
3920
554
      break;
3921
561
    case tok::kw__Sat:
3922
561
      if (!getLangOpts().FixedPoint) {
3923
0
        SetupFixedPointError(getLangOpts(), PrevSpec, DiagID, isInvalid);
3924
561
      } else {
3925
561
        isInvalid = DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
3926
561
      }
3927
561
      break;
3928
431
    case tok::kw___float128:
3929
431
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
3930
431
                                     DiagID, Policy);
3931
431
      break;
3932
106
    case tok::kw___ibm128:
3933
106
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec,
3934
106
                                     DiagID, Policy);
3935
106
      break;
3936
131k
    case tok::kw_wchar_t:
3937
131k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
3938
131k
                                     DiagID, Policy);
3939
131k
      break;
3940
56
    case tok::kw_char8_t:
3941
56
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec,
3942
56
                                     DiagID, Policy);
3943
56
      break;
3944
9.47k
    case tok::kw_char16_t:
3945
9.47k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
3946
9.47k
                                     DiagID, Policy);
3947
9.47k
      break;
3948
9.47k
    case tok::kw_char32_t:
3949
9.47k
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
3950
9.47k
                                     DiagID, Policy);
3951
9.47k
      break;
3952
551k
    case tok::kw_bool:
3953
705k
    case tok::kw__Bool:
3954
705k
      if (Tok.is(tok::kw__Bool) && 
!getLangOpts().C99153k
)
3955
2
        Diag(Tok, diag::ext_c99_feature) << Tok.getName();
3956
3957
705k
      if (Tok.is(tok::kw_bool) &&
3958
705k
          
DS.getTypeSpecType() != DeclSpec::TST_unspecified551k
&&
3959
705k
          
DS.getStorageClassSpec() == DeclSpec::SCS_typedef3
) {
3960
3
        PrevSpec = ""; // Not used by the diagnostic.
3961
3
        DiagID = diag::err_bool_redeclaration;
3962
        // For better error recovery.
3963
3
        Tok.setKind(tok::identifier);
3964
3
        isInvalid = true;
3965
705k
      } else {
3966
705k
        isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
3967
705k
                                       DiagID, Policy);
3968
705k
      }
3969
705k
      break;
3970
5
    case tok::kw__Decimal32:
3971
5
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
3972
5
                                     DiagID, Policy);
3973
5
      break;
3974
0
    case tok::kw__Decimal64:
3975
0
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
3976
0
                                     DiagID, Policy);
3977
0
      break;
3978
2
    case tok::kw__Decimal128:
3979
2
      isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
3980
2
                                     DiagID, Policy);
3981
2
      break;
3982
447k
    case tok::kw___vector:
3983
447k
      isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
3984
447k
      break;
3985
20
    case tok::kw___pixel:
3986
20
      isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
3987
20
      break;
3988
19.5k
    case tok::kw___bool:
3989
19.5k
      isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
3990
19.5k
      break;
3991
256
    case tok::kw_pipe:
3992
256
      if (!getLangOpts().OpenCL ||
3993
256
          getLangOpts().getOpenCLCompatibleVersion() < 200) {
3994
        // OpenCL 2.0 and later define this keyword. OpenCL 1.2 and earlier
3995
        // should support the "pipe" word as identifier.
3996
1
        Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
3997
1
        Tok.setKind(tok::identifier);
3998
1
        goto DoneWithDeclSpec;
3999
255
      } else if (!getLangOpts().OpenCLPipes) {
4000
4
        DiagID = diag::err_opencl_unknown_type_specifier;
4001
4
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4002
4
        isInvalid = true;
4003
4
      } else
4004
251
        isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
4005
255
      break;
4006
// We only need to enumerate each image type once.
4007
255
#define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
4008
255
#define IMAGE_WRITE_TYPE(Type, Id, Ext)
4009
255
#define IMAGE_READ_TYPE(ImgType, Id, Ext) \
4010
8.20k
    case tok::kw_##ImgType##_t: \
4011
8.20k
      if (!handleOpenCLImageKW(Ext, DeclSpec::TST_##ImgType##_t)) \
4012
8.20k
        
goto DoneWithDeclSpec4
; \
4013
8.20k
      break;
4014
255
#include "clang/Basic/OpenCLImageTypes.def"
4015
1.03k
    case tok::kw___unknown_anytype:
4016
62
      isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
4017
62
                                     PrevSpec, DiagID, Policy);
4018
62
      break;
4019
4020
    // class-specifier:
4021
158k
    case tok::kw_class:
4022
1.73M
    case tok::kw_struct:
4023
1.73M
    case tok::kw___interface:
4024
1.77M
    case tok::kw_union: {
4025
1.77M
      tok::TokenKind Kind = Tok.getKind();
4026
1.77M
      ConsumeToken();
4027
4028
      // These are attributes following class specifiers.
4029
      // To produce better diagnostic, we parse them when
4030
      // parsing class specifier.
4031
1.77M
      ParsedAttributesWithRange Attributes(AttrFactory);
4032
1.77M
      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
4033
1.77M
                          EnteringContext, DSContext, Attributes);
4034
4035
      // If there are attributes following class specifier,
4036
      // take them over and handle them here.
4037
1.77M
      if (!Attributes.empty()) {
4038
0
        AttrsLastTime = true;
4039
0
        attrs.takeAllFrom(Attributes);
4040
0
      }
4041
1.77M
      continue;
4042
1.73M
    }
4043
4044
    // enum-specifier:
4045
941k
    case tok::kw_enum:
4046
941k
      ConsumeToken();
4047
941k
      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
4048
941k
      continue;
4049
4050
    // cv-qualifier:
4051
5.43M
    case tok::kw_const:
4052
5.43M
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
4053
5.43M
                                 getLangOpts());
4054
5.43M
      break;
4055
98.0k
    case tok::kw_volatile:
4056
98.0k
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
4057
98.0k
                                 getLangOpts());
4058
98.0k
      break;
4059
288
    case tok::kw_restrict:
4060
288
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
4061
288
                                 getLangOpts());
4062
288
      break;
4063
4064
    // C++ typename-specifier:
4065
371k
    case tok::kw_typename:
4066
371k
      if (TryAnnotateTypeOrScopeToken()) {
4067
4
        DS.SetTypeSpecError();
4068
4
        goto DoneWithDeclSpec;
4069
4
      }
4070
371k
      if (!Tok.is(tok::kw_typename))
4071
371k
        continue;
4072
0
      break;
4073
4074
    // GNU typeof support.
4075
3.08k
    case tok::kw_typeof:
4076
3.08k
      ParseTypeofSpecifier(DS);
4077
3.08k
      continue;
4078
4079
38.3k
    case tok::annot_decltype:
4080
38.3k
      ParseDecltypeSpecifier(DS);
4081
38.3k
      continue;
4082
4083
1
    case tok::annot_pragma_pack:
4084
1
      HandlePragmaPack();
4085
1
      continue;
4086
4087
0
    case tok::annot_pragma_ms_pragma:
4088
0
      HandlePragmaMSPragma();
4089
0
      continue;
4090
4091
0
    case tok::annot_pragma_ms_vtordisp:
4092
0
      HandlePragmaMSVtorDisp();
4093
0
      continue;
4094
4095
0
    case tok::annot_pragma_ms_pointers_to_members:
4096
0
      HandlePragmaMSPointersToMembers();
4097
0
      continue;
4098
4099
509
    case tok::kw___underlying_type:
4100
509
      ParseUnderlyingTypeSpecifier(DS);
4101
509
      continue;
4102
4103
2.57k
    case tok::kw__Atomic:
4104
      // C11 6.7.2.4/4:
4105
      //   If the _Atomic keyword is immediately followed by a left parenthesis,
4106
      //   it is interpreted as a type specifier (with a type name), not as a
4107
      //   type qualifier.
4108
2.57k
      if (!getLangOpts().C11)
4109
1.29k
        Diag(Tok, diag::ext_c11_feature) << Tok.getName();
4110
4111
2.57k
      if (NextToken().is(tok::l_paren)) {
4112
2.44k
        ParseAtomicSpecifier(DS);
4113
2.44k
        continue;
4114
2.44k
      }
4115
127
      isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
4116
127
                                 getLangOpts());
4117
127
      break;
4118
4119
    // OpenCL address space qualifiers:
4120
1.83k
    case tok::kw___generic:
4121
      // generic address space is introduced only in OpenCL v2.0
4122
      // see OpenCL C Spec v2.0 s6.5.5
4123
      // OpenCL v3.0 introduces __opencl_c_generic_address_space
4124
      // feature macro to indicate if generic address space is supported
4125
1.83k
      if (!Actions.getLangOpts().OpenCLGenericAddressSpace) {
4126
26
        DiagID = diag::err_opencl_unknown_type_specifier;
4127
26
        PrevSpec = Tok.getIdentifierInfo()->getNameStart();
4128
26
        isInvalid = true;
4129
26
        break;
4130
26
      }
4131
1.83k
      
LLVM_FALLTHROUGH1.81k
;1.81k
4132
1.85k
    case tok::kw_private:
4133
      // It's fine (but redundant) to check this for __generic on the
4134
      // fallthrough path; we only form the __generic token in OpenCL mode.
4135
1.85k
      if (!getLangOpts().OpenCL)
4136
3
        goto DoneWithDeclSpec;
4137
1.85k
      
LLVM_FALLTHROUGH1.85k
;1.85k
4138
5.09k
    case tok::kw___private:
4139
17.7k
    case tok::kw___global:
4140
28.4k
    case tok::kw___local:
4141
30.6k
    case tok::kw___constant:
4142
    // OpenCL access qualifiers:
4143
34.5k
    case tok::kw___read_only:
4144
36.6k
    case tok::kw___write_only:
4145
38.8k
    case tok::kw___read_write:
4146
38.8k
      ParseOpenCLQualifiers(DS.getAttributes());
4147
38.8k
      break;
4148
4149
19
    case tok::less:
4150
      // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
4151
      // "id<SomeProtocol>".  This is hopelessly old fashioned and dangerous,
4152
      // but we support it.
4153
19
      if (DS.hasTypeSpecifier() || 
!getLangOpts().ObjC9
)
4154
12
        goto DoneWithDeclSpec;
4155
4156
7
      SourceLocation StartLoc = Tok.getLocation();
4157
7
      SourceLocation EndLoc;
4158
7
      TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
4159
7
      if (Type.isUsable()) {
4160
7
        if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
4161
7
                               PrevSpec, DiagID, Type.get(),
4162
7
                               Actions.getASTContext().getPrintingPolicy()))
4163
0
          Diag(StartLoc, DiagID) << PrevSpec;
4164
4165
7
        DS.SetRangeEnd(EndLoc);
4166
7
      } else {
4167
0
        DS.SetTypeSpecError();
4168
0
      }
4169
4170
      // Need to support trailing type qualifiers (e.g. "id<p> const").
4171
      // If a type specifier follows, it will be diagnosed elsewhere.
4172
7
      continue;
4173
388M
    }
4174
4175
79.9M
    DS.SetRangeEnd(ConsumedEnd.isValid() ? 
ConsumedEnd67.4k
:
Tok.getLocation()79.8M
);
4176
4177
    // If the specifier wasn't legal, issue a diagnostic.
4178
79.9M
    if (isInvalid) {
4179
231
      assert(PrevSpec && "Method did not return previous specifier!");
4180
0
      assert(DiagID);
4181
4182
231
      if (DiagID == diag::ext_duplicate_declspec ||
4183
231
          DiagID == diag::ext_warn_duplicate_declspec ||
4184
231
          
DiagID == diag::err_duplicate_declspec187
)
4185
46
        Diag(Loc, DiagID) << PrevSpec
4186
46
                          << FixItHint::CreateRemoval(
4187
46
                                 SourceRange(Loc, DS.getEndLoc()));
4188
185
      else if (DiagID == diag::err_opencl_unknown_type_specifier) {
4189
45
        Diag(Loc, DiagID) << getLangOpts().getOpenCLVersionString() << PrevSpec
4190
45
                          << isStorageClass;
4191
45
      } else
4192
140
        Diag(Loc, DiagID) << PrevSpec;
4193
231
    }
4194
4195
79.9M
    if (DiagID != diag::err_bool_redeclaration && 
ConsumedEnd.isInvalid()79.9M
)
4196
      // After an error the next token can be an annotation token.
4197
79.8M
      ConsumeAnyToken();
4198
4199
79.9M
    AttrsLastTime = false;
4200
79.9M
  }
4201
143M
}
4202
4203
/// ParseStructDeclaration - Parse a struct declaration without the terminating
4204
/// semicolon.
4205
///
4206
/// Note that a struct declaration refers to a declaration in a struct,
4207
/// not to the declaration of a struct.
4208
///
4209
///       struct-declaration:
4210
/// [C2x]   attributes-specifier-seq[opt]
4211
///           specifier-qualifier-list struct-declarator-list
4212
/// [GNU]   __extension__ struct-declaration
4213
/// [GNU]   specifier-qualifier-list
4214
///       struct-declarator-list:
4215
///         struct-declarator
4216
///         struct-declarator-list ',' struct-declarator
4217
/// [GNU]   struct-declarator-list ',' attributes[opt] struct-declarator
4218
///       struct-declarator:
4219
///         declarator
4220
/// [GNU]   declarator attributes[opt]
4221
///         declarator[opt] ':' constant-expression
4222
/// [GNU]   declarator[opt] ':' constant-expression attributes[opt]
4223
///
4224
void Parser::ParseStructDeclaration(
4225
    ParsingDeclSpec &DS,
4226
2.27M
    llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
4227
4228
2.27M
  if (Tok.is(tok::kw___extension__)) {
4229
    // __extension__ silences extension warnings in the subexpression.
4230
2
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
4231
2
    ConsumeToken();
4232
2
    return ParseStructDeclaration(DS, FieldsCallback);
4233
2
  }
4234
4235
  // Parse leading attributes.
4236
2.27M
  ParsedAttributesWithRange Attrs(AttrFactory);
4237
2.27M
  MaybeParseCXX11Attributes(Attrs);
4238
2.27M
  DS.takeAttributesFrom(Attrs);
4239
4240
  // Parse the common specifier-qualifiers-list piece.
4241
2.27M
  ParseSpecifierQualifierList(DS);
4242
4243
  // If there are no declarators, this is a free-standing declaration
4244
  // specifier. Let the actions module cope with it.
4245
2.27M
  if (Tok.is(tok::semi)) {
4246
320
    RecordDecl *AnonRecord = nullptr;
4247
320
    Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
4248
320
                                                       DS, AnonRecord);
4249
320
    assert(!AnonRecord && "Did not expect anonymous struct or union here");
4250
0
    DS.complete(TheDecl);
4251
320
    return;
4252
320
  }
4253
4254
  // Read struct-declarators until we find the semicolon.
4255
2.27M
  bool FirstDeclarator = true;
4256
2.27M
  SourceLocation CommaLoc;
4257
2.29M
  while (1) {
4258
2.29M
    ParsingFieldDeclarator DeclaratorInfo(*this, DS);
4259
2.29M
    DeclaratorInfo.D.setCommaLoc(CommaLoc);
4260
4261
    // Attributes are only allowed here on successive declarators.
4262
2.29M
    if (!FirstDeclarator) {
4263
      // However, this does not apply for [[]] attributes (which could show up
4264
      // before or after the __attribute__ attributes).
4265
12.6k
      DiagnoseAndSkipCXX11Attributes();
4266
12.6k
      MaybeParseGNUAttributes(DeclaratorInfo.D);
4267
12.6k
      DiagnoseAndSkipCXX11Attributes();
4268
12.6k
    }
4269
4270
    /// struct-declarator: declarator
4271
    /// struct-declarator: declarator[opt] ':' constant-expression
4272
2.29M
    if (Tok.isNot(tok::colon)) {
4273
      // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
4274
2.28M
      ColonProtectionRAIIObject X(*this);
4275
2.28M
      ParseDeclarator(DeclaratorInfo.D);
4276
2.28M
    } else
4277
1.71k
      DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
4278
4279
2.29M
    if (TryConsumeToken(tok::colon)) {
4280
30.0k
      ExprResult Res(ParseConstantExpression());
4281
30.0k
      if (Res.isInvalid())
4282
1
        SkipUntil(tok::semi, StopBeforeMatch);
4283
30.0k
      else
4284
30.0k
        DeclaratorInfo.BitfieldSize = Res.get();
4285
30.0k
    }
4286
4287
    // If attributes exist after the declarator, parse them.
4288
2.29M
    MaybeParseGNUAttributes(DeclaratorInfo.D);
4289
4290
    // We're done with this declarator;  invoke the callback.
4291
2.29M
    FieldsCallback(DeclaratorInfo);
4292
4293
    // If we don't have a comma, it is either the end of the list (a ';')
4294
    // or an error, bail out.
4295
2.29M
    if (!TryConsumeToken(tok::comma, CommaLoc))
4296
2.27M
      return;
4297
4298
12.6k
    FirstDeclarator = false;
4299
12.6k
  }
4300
2.27M
}
4301
4302
/// ParseStructUnionBody
4303
///       struct-contents:
4304
///         struct-declaration-list
4305
/// [EXT]   empty
4306
/// [GNU]   "struct-declaration-list" without terminating ';'
4307
///       struct-declaration-list:
4308
///         struct-declaration
4309
///         struct-declaration-list struct-declaration
4310
/// [OBC]   '@' 'defs' '(' class-name ')'
4311
///
4312
void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
4313
395k
                                  DeclSpec::TST TagType, RecordDecl *TagDecl) {
4314
395k
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
4315
395k
                                      "parsing struct/union body");
4316
395k
  assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
4317
4318
0
  BalancedDelimiterTracker T(*this, tok::l_brace);
4319
395k
  if (T.consumeOpen())
4320
0
    return;
4321
4322
395k
  ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
4323
395k
  Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
4324
4325
  // While we still have something to read, read the declarations in the struct.
4326
2.19M
  while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
4327
2.19M
         
Tok.isNot(tok::eof)1.79M
) {
4328
    // Each iteration of this loop reads one struct-declaration.
4329
4330
    // Check for extraneous top-level semicolon.
4331
1.79M
    if (Tok.is(tok::semi)) {
4332
5
      ConsumeExtraSemi(InsideStruct, TagType);
4333
5
      continue;
4334
5
    }
4335
4336
    // Parse _Static_assert declaration.
4337
1.79M
    if (Tok.isOneOf(tok::kw__Static_assert, tok::kw_static_assert)) {
4338
43
      SourceLocation DeclEnd;
4339
43
      ParseStaticAssertDeclaration(DeclEnd);
4340
43
      continue;
4341
43
    }
4342
4343
1.79M
    if (Tok.is(tok::annot_pragma_pack)) {
4344
6
      HandlePragmaPack();
4345
6
      continue;
4346
6
    }
4347
4348
1.79M
    if (Tok.is(tok::annot_pragma_align)) {
4349
2
      HandlePragmaAlign();
4350
2
      continue;
4351
2
    }
4352
4353
1.79M
    if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
4354
      // Result can be ignored, because it must be always empty.
4355
21
      AccessSpecifier AS = AS_none;
4356
21
      ParsedAttributesWithRange Attrs(AttrFactory);
4357
21
      (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
4358
21
      continue;
4359
21
    }
4360
4361
1.79M
    if (tok::isPragmaAnnotation(Tok.getKind())) {
4362
2
      Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
4363
2
          << DeclSpec::getSpecifierName(
4364
2
                 TagType, Actions.getASTContext().getPrintingPolicy());
4365
2
      ConsumeAnnotationToken();
4366
2
      continue;
4367
2
    }
4368
4369
1.79M
    if (!Tok.is(tok::at)) {
4370
1.80M
      auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
4371
        // Install the declarator into the current TagDecl.
4372
1.80M
        Decl *Field =
4373
1.80M
            Actions.ActOnField(getCurScope(), TagDecl,
4374
1.80M
                               FD.D.getDeclSpec().getSourceRange().getBegin(),
4375
1.80M
                               FD.D, FD.BitfieldSize);
4376
1.80M
        FD.complete(Field);
4377
1.80M
      };
4378
4379
      // Parse all the comma separated declarators.
4380
1.79M
      ParsingDeclSpec DS(*this);
4381
1.79M
      ParseStructDeclaration(DS, CFieldCallback);
4382
1.79M
    } else { // Handle @defs
4383
8
      ConsumeToken();
4384
8
      if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
4385
4
        Diag(Tok, diag::err_unexpected_at);
4386
4
        SkipUntil(tok::semi);
4387
4
        continue;
4388
4
      }
4389
4
      ConsumeToken();
4390
4
      ExpectAndConsume(tok::l_paren);
4391
4
      if (!Tok.is(tok::identifier)) {
4392
0
        Diag(Tok, diag::err_expected) << tok::identifier;
4393
0
        SkipUntil(tok::semi);
4394
0
        continue;
4395
0
      }
4396
4
      SmallVector<Decl *, 16> Fields;
4397
4
      Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
4398
4
                        Tok.getIdentifierInfo(), Fields);
4399
4
      ConsumeToken();
4400
4
      ExpectAndConsume(tok::r_paren);
4401
4
    }
4402
4403
1.79M
    if (TryConsumeToken(tok::semi))
4404
1.79M
      continue;
4405
4406
22
    if (Tok.is(tok::r_brace)) {
4407
10
      ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
4408
10
      break;
4409
10
    }
4410
4411
12
    ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
4412
    // Skip to end of block or statement to avoid ext-warning on extra ';'.
4413
12
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
4414
    // If we stopped at a ';', eat it.
4415
12
    TryConsumeToken(tok::semi);
4416
12
  }
4417
4418
395k
  T.consumeClose();
4419
4420
395k
  ParsedAttributes attrs(AttrFactory);
4421
  // If attributes exist after struct contents, parse them.
4422
395k
  MaybeParseGNUAttributes(attrs);
4423
4424
395k
  SmallVector<Decl *, 32> FieldDecls(TagDecl->field_begin(),
4425
395k
                                     TagDecl->field_end());
4426
4427
395k
  Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls,
4428
395k
                      T.getOpenLocation(), T.getCloseLocation(), attrs);
4429
395k
  StructScope.Exit();
4430
395k
  Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
4431
395k
}
4432
4433
/// ParseEnumSpecifier
4434
///       enum-specifier: [C99 6.7.2.2]
4435
///         'enum' identifier[opt] '{' enumerator-list '}'
4436
///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
4437
/// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
4438
///                                                 '}' attributes[opt]
4439
/// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
4440
///                                                 '}'
4441
///         'enum' identifier
4442
/// [GNU]   'enum' attributes[opt] identifier
4443
///
4444
/// [C++11] enum-head '{' enumerator-list[opt] '}'
4445
/// [C++11] enum-head '{' enumerator-list ','  '}'
4446
///
4447
///       enum-head: [C++11]
4448
///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
4449
///         enum-key attribute-specifier-seq[opt] nested-name-specifier
4450
///             identifier enum-base[opt]
4451
///
4452
///       enum-key: [C++11]
4453
///         'enum'
4454
///         'enum' 'class'
4455
///         'enum' 'struct'
4456
///
4457
///       enum-base: [C++11]
4458
///         ':' type-specifier-seq
4459
///
4460
/// [C++] elaborated-type-specifier:
4461
/// [C++]   'enum' nested-name-specifier[opt] identifier
4462
///
4463
void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
4464
                                const ParsedTemplateInfo &TemplateInfo,
4465
941k
                                AccessSpecifier AS, DeclSpecContext DSC) {
4466
  // Parse the tag portion of this.
4467
941k
  if (Tok.is(tok::code_completion)) {
4468
    // Code completion for an enum name.
4469
2
    cutOffParsing();
4470
2
    Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
4471
2
    return;
4472
2
  }
4473
4474
  // If attributes exist after tag, parse them.
4475
941k
  ParsedAttributesWithRange attrs(AttrFactory);
4476
941k
  MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4477
4478
941k
  SourceLocation ScopedEnumKWLoc;
4479
941k
  bool IsScopedUsingClassTag = false;
4480
4481
  // In C++11, recognize 'enum class' and 'enum struct'.
4482
941k
  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
4483
2.73k
    Diag(Tok, getLangOpts().CPlusPlus11 ? 
diag::warn_cxx98_compat_scoped_enum2.66k
4484
2.73k
                                        : 
diag::ext_scoped_enum70
);
4485
2.73k
    IsScopedUsingClassTag = Tok.is(tok::kw_class);
4486
2.73k
    ScopedEnumKWLoc = ConsumeToken();
4487
4488
    // Attributes are not allowed between these keywords.  Diagnose,
4489
    // but then just treat them like they appeared in the right place.
4490
2.73k
    ProhibitAttributes(attrs);
4491
4492
    // They are allowed afterwards, though.
4493
2.73k
    MaybeParseAttributes(PAKM_GNU | PAKM_Declspec | PAKM_CXX11, attrs);
4494
2.73k
  }
4495
4496
  // C++11 [temp.explicit]p12:
4497
  //   The usual access controls do not apply to names used to specify
4498
  //   explicit instantiations.
4499
  // We extend this to also cover explicit specializations.  Note that
4500
  // we don't suppress if this turns out to be an elaborated type
4501
  // specifier.
4502
941k
  bool shouldDelayDiagsInTag =
4503
941k
    (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
4504
941k
     
TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization941k
);
4505
941k
  SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
4506
4507
  // Determine whether this declaration is permitted to have an enum-base.
4508
941k
  AllowDefiningTypeSpec AllowEnumSpecifier =
4509
941k
      isDefiningTypeSpecifierContext(DSC);
4510
941k
  bool CanBeOpaqueEnumDeclaration =
4511
941k
      DS.isEmpty() && 
isOpaqueEnumDeclarationContext(DSC)859k
;
4512
941k
  bool CanHaveEnumBase = (getLangOpts().CPlusPlus11 || 
getLangOpts().ObjC714k
||
4513
941k
                          
getLangOpts().MicrosoftExt266k
) &&
4514
941k
                         
(675k
AllowEnumSpecifier == AllowDefiningTypeSpec::Yes675k
||
4515
675k
                          
CanBeOpaqueEnumDeclaration92
);
4516
4517
941k
  CXXScopeSpec &SS = DS.getTypeSpecScope();
4518
941k
  if (getLangOpts().CPlusPlus) {
4519
    // "enum foo : bar;" is not a potential typo for "enum foo::bar;".
4520
227k
    ColonProtectionRAIIObject X(*this);
4521
4522
227k
    CXXScopeSpec Spec;
4523
227k
    if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
4524
227k
                                       /*ObjectHadErrors=*/false,
4525
227k
                                       /*EnteringContext=*/true))
4526
0
      return;
4527
4528
227k
    if (Spec.isSet() && 
Tok.isNot(tok::identifier)215
) {
4529
8
      Diag(Tok, diag::err_expected) << tok::identifier;
4530
8
      if (Tok.isNot(tok::l_brace)) {
4531
        // Has no name and is not a definition.
4532
        // Skip the rest of this declarator, up until the comma or semicolon.
4533
8
        SkipUntil(tok::comma, StopAtSemi);
4534
8
        return;
4535
8
      }
4536
8
    }
4537
4538
227k
    SS = Spec;
4539
227k
  }
4540
4541
  // Must have either 'enum name' or 'enum {...}' or (rarely) 'enum : T { ... }'.
4542
941k
  if (Tok.isNot(tok::identifier) && 
Tok.isNot(tok::l_brace)376k
&&
4543
941k
      
Tok.isNot(tok::colon)30.0k
) {
4544
3
    Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
4545
4546
    // Skip the rest of this declarator, up until the comma or semicolon.
4547
3
    SkipUntil(tok::comma, StopAtSemi);
4548
3
    return;
4549
3
  }
4550
4551
  // If an identifier is present, consume and remember it.
4552
941k
  IdentifierInfo *Name = nullptr;
4553
941k
  SourceLocation NameLoc;
4554
941k
  if (Tok.is(tok::identifier)) {
4555
564k
    Name = Tok.getIdentifierInfo();
4556
564k
    NameLoc = ConsumeToken();
4557
564k
  }
4558
4559
941k
  if (!Name && 
ScopedEnumKWLoc.isValid()376k
) {
4560
    // C++0x 7.2p2: The optional identifier shall not be omitted in the
4561
    // declaration of a scoped enumeration.
4562
8
    Diag(Tok, diag::err_scoped_enum_missing_identifier);
4563
8
    ScopedEnumKWLoc = SourceLocation();
4564
8
    IsScopedUsingClassTag = false;
4565
8
  }
4566
4567
  // Okay, end the suppression area.  We'll decide whether to emit the
4568
  // diagnostics in a second.
4569
941k
  if (shouldDelayDiagsInTag)
4570
66
    diagsFromTag.done();
4571
4572
941k
  TypeResult BaseType;
4573
941k
  SourceRange BaseRange;
4574
4575
941k
  bool CanBeBitfield = (getCurScope()->getFlags() & Scope::ClassScope) &&
4576
941k
                       
ScopedEnumKWLoc.isInvalid()12.3k
&&
Name12.1k
;
4577
4578
  // Parse the fixed underlying type.
4579
941k
  if (Tok.is(tok::colon)) {
4580
    // This might be an enum-base or part of some unrelated enclosing context.
4581
    //
4582
    // 'enum E : base' is permitted in two circumstances:
4583
    //
4584
    // 1) As a defining-type-specifier, when followed by '{'.
4585
    // 2) As the sole constituent of a complete declaration -- when DS is empty
4586
    //    and the next token is ';'.
4587
    //
4588
    // The restriction to defining-type-specifiers is important to allow parsing
4589
    //   a ? new enum E : int{}
4590
    //   _Generic(a, enum E : int{})
4591
    // properly.
4592
    //
4593
    // One additional consideration applies:
4594
    //
4595
    // C++ [dcl.enum]p1:
4596
    //   A ':' following "enum nested-name-specifier[opt] identifier" within
4597
    //   the decl-specifier-seq of a member-declaration is parsed as part of
4598
    //   an enum-base.
4599
    //
4600
    // Other language modes supporting enumerations with fixed underlying types
4601
    // do not have clear rules on this, so we disambiguate to determine whether
4602
    // the tokens form a bit-field width or an enum-base.
4603
4604
170k
    if (CanBeBitfield && 
!isEnumBase(CanBeOpaqueEnumDeclaration)175
) {
4605
      // Outside C++11, do not interpret the tokens as an enum-base if they do
4606
      // not make sense as one. In C++11, it's an error if this happens.
4607
19
      if (getLangOpts().CPlusPlus11)
4608
13
        Diag(Tok.getLocation(), diag::err_anonymous_enum_bitfield);
4609
170k
    } else if (CanHaveEnumBase || 
!ColonIsSacred77
) {
4610
170k
      SourceLocation ColonLoc = ConsumeToken();
4611
4612
      // Parse a type-specifier-seq as a type. We can't just ParseTypeName here,
4613
      // because under -fms-extensions,
4614
      //   enum E : int *p;
4615
      // declares 'enum E : int; E *p;' not 'enum E : int*; E p;'.
4616
170k
      DeclSpec DS(AttrFactory);
4617
170k
      ParseSpecifierQualifierList(DS, AS, DeclSpecContext::DSC_type_specifier);
4618
170k
      Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
4619
170k
      BaseType = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4620
4621
170k
      BaseRange = SourceRange(ColonLoc, DeclaratorInfo.getSourceRange().getEnd());
4622
4623
170k
      if (!getLangOpts().ObjC) {
4624
4.18k
        if (getLangOpts().CPlusPlus11)
4625
4.12k
          Diag(ColonLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type)
4626
4.12k
              << BaseRange;
4627
62
        else if (getLangOpts().CPlusPlus)
4628
16
          Diag(ColonLoc, diag::ext_cxx11_enum_fixed_underlying_type)
4629
16
              << BaseRange;
4630
46
        else if (getLangOpts().MicrosoftExt)
4631
7
          Diag(ColonLoc, diag::ext_ms_c_enum_fixed_underlying_type)
4632
7
              << BaseRange;
4633
39
        else
4634
39
          Diag(ColonLoc, diag::ext_clang_c_enum_fixed_underlying_type)
4635
39
              << BaseRange;
4636
4.18k
      }
4637
170k
    }
4638
170k
  }
4639
4640
  // There are four options here.  If we have 'friend enum foo;' then this is a
4641
  // friend declaration, and cannot have an accompanying definition. If we have
4642
  // 'enum foo;', then this is a forward declaration.  If we have
4643
  // 'enum foo {...' then this is a definition. Otherwise we have something
4644
  // like 'enum foo xyz', a reference.
4645
  //
4646
  // This is needed to handle stuff like this right (C99 6.7.2.3p11):
4647
  // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
4648
  // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
4649
  //
4650
941k
  Sema::TagUseKind TUK;
4651
941k
  if (AllowEnumSpecifier == AllowDefiningTypeSpec::No)
4652
55
    TUK = Sema::TUK_Reference;
4653
941k
  else if (Tok.is(tok::l_brace)) {
4654
465k
    if (DS.isFriendSpecified()) {
4655
4
      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
4656
4
        << SourceRange(DS.getFriendSpecLoc());
4657
4
      ConsumeBrace();
4658
4
      SkipUntil(tok::r_brace, StopAtSemi);
4659
      // Discard any other definition-only pieces.
4660
4
      attrs.clear();
4661
4
      ScopedEnumKWLoc = SourceLocation();
4662
4
      IsScopedUsingClassTag = false;
4663
4
      BaseType = TypeResult();
4664
4
      TUK = Sema::TUK_Friend;
4665
465k
    } else {
4666
465k
      TUK = Sema::TUK_Definition;
4667
465k
    }
4668
475k
  } else if (!isTypeSpecifier(DSC) &&
4669
475k
             
(475k
Tok.is(tok::semi)475k
||
4670
475k
              
(475k
Tok.isAtStartOfLine()475k
&&
4671
475k
               
!isValidAfterTypeSpecifier(CanBeBitfield)33
))) {
4672
    // An opaque-enum-declaration is required to be standalone (no preceding or
4673
    // following tokens in the declaration). Sema enforces this separately by
4674
    // diagnosing anything else in the DeclSpec.
4675
427
    TUK = DS.isFriendSpecified() ? 
Sema::TUK_Friend20
:
Sema::TUK_Declaration407
;
4676
427
    if (Tok.isNot(tok::semi)) {
4677
      // A semicolon was missing after this declaration. Diagnose and recover.
4678
2
      ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4679
2
      PP.EnterToken(Tok, /*IsReinject=*/true);
4680
2
      Tok.setKind(tok::semi);
4681
2
    }
4682
475k
  } else {
4683
475k
    TUK = Sema::TUK_Reference;
4684
475k
  }
4685
4686
941k
  bool IsElaboratedTypeSpecifier =
4687
941k
      TUK == Sema::TUK_Reference || 
TUK == Sema::TUK_Friend466k
;
4688
4689
  // If this is an elaborated type specifier nested in a larger declaration,
4690
  // and we delayed diagnostics before, just merge them into the current pool.
4691
941k
  if (TUK == Sema::TUK_Reference && 
shouldDelayDiagsInTag475k
) {
4692
0
    diagsFromTag.redelay();
4693
0
  }
4694
4695
941k
  MultiTemplateParamsArg TParams;
4696
941k
  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
4697
941k
      
TUK != Sema::TUK_Reference100
) {
4698
99
    if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
4699
      // Skip the rest of this declarator, up until the comma or semicolon.
4700
1
      Diag(Tok, diag::err_enum_template);
4701
1
      SkipUntil(tok::comma, StopAtSemi);
4702
1
      return;
4703
1
    }
4704
4705
98
    if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
4706
      // Enumerations can't be explicitly instantiated.
4707
5
      DS.SetTypeSpecError();
4708
5
      Diag(StartLoc, diag::err_explicit_instantiation_enum);
4709
5
      return;
4710
5
    }
4711
4712
93
    assert(TemplateInfo.TemplateParams && "no template parameters");
4713
0
    TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
4714
93
                                     TemplateInfo.TemplateParams->size());
4715
93
  }
4716
4717
941k
  if (!Name && 
TUK != Sema::TUK_Definition376k
) {
4718
2
    Diag(Tok, diag::err_enumerator_unnamed_no_def);
4719
4720
    // Skip the rest of this declarator, up until the comma or semicolon.
4721
2
    SkipUntil(tok::comma, StopAtSemi);
4722
2
    return;
4723
2
  }
4724
4725
  // An elaborated-type-specifier has a much more constrained grammar:
4726
  //
4727
  //   'enum' nested-name-specifier[opt] identifier
4728
  //
4729
  // If we parsed any other bits, reject them now.
4730
  //
4731
  // MSVC and (for now at least) Objective-C permit a full enum-specifier
4732
  // or opaque-enum-declaration anywhere.
4733
941k
  if (IsElaboratedTypeSpecifier && 
!getLangOpts().MicrosoftExt475k
&&
4734
941k
      
!getLangOpts().ObjC475k
) {
4735
403k
    ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
4736
403k
                            /*DiagnoseEmptyAttrs=*/true);
4737
403k
    if (BaseType.isUsable())
4738
440
      Diag(BaseRange.getBegin(), diag::ext_enum_base_in_type_specifier)
4739
440
          << (AllowEnumSpecifier == AllowDefiningTypeSpec::Yes) << BaseRange;
4740
402k
    else if (ScopedEnumKWLoc.isValid())
4741
21
      Diag(ScopedEnumKWLoc, diag::ext_elaborated_enum_class)
4742
21
        << FixItHint::CreateRemoval(ScopedEnumKWLoc) << IsScopedUsingClassTag;
4743
403k
  }
4744
4745
941k
  stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
4746
4747
941k
  Sema::SkipBodyInfo SkipBody;
4748
941k
  if (!Name && 
TUK == Sema::TUK_Definition376k
&&
Tok.is(tok::l_brace)376k
&&
4749
941k
      
NextToken().is(tok::identifier)376k
)
4750
376k
    SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
4751
376k
                                              NextToken().getIdentifierInfo(),
4752
376k
                                              NextToken().getLocation());
4753
4754
941k
  bool Owned = false;
4755
941k
  bool IsDependent = false;
4756
941k
  const char *PrevSpec = nullptr;
4757
941k
  unsigned DiagID;
4758
941k
  Decl *TagDecl = Actions.ActOnTag(
4759
941k
      getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc,
4760
941k
      attrs, AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
4761
941k
      ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType,
4762
941k
      DSC == DeclSpecContext::DSC_type_specifier,
4763
941k
      DSC == DeclSpecContext::DSC_template_param ||
4764
941k
          
DSC == DeclSpecContext::DSC_template_type_arg941k
,
4765
941k
      &SkipBody);
4766
4767
941k
  if (SkipBody.ShouldSkip) {
4768
18
    assert(TUK == Sema::TUK_Definition && "can only skip a definition");
4769
4770
0
    BalancedDelimiterTracker T(*this, tok::l_brace);
4771
18
    T.consumeOpen();
4772
18
    T.skipToEnd();
4773
4774
18
    if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4775
18
                           NameLoc.isValid() ? 
NameLoc13
:
StartLoc5
,
4776
18
                           PrevSpec, DiagID, TagDecl, Owned,
4777
18
                           Actions.getASTContext().getPrintingPolicy()))
4778
0
      Diag(StartLoc, DiagID) << PrevSpec;
4779
18
    return;
4780
18
  }
4781
4782
941k
  if (IsDependent) {
4783
    // This enum has a dependent nested-name-specifier. Handle it as a
4784
    // dependent tag.
4785
14
    if (!Name) {
4786
0
      DS.SetTypeSpecError();
4787
0
      Diag(Tok, diag::err_expected_type_name_after_typename);
4788
0
      return;
4789
0
    }
4790
4791
14
    TypeResult Type = Actions.ActOnDependentTag(
4792
14
        getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
4793
14
    if (Type.isInvalid()) {
4794
0
      DS.SetTypeSpecError();
4795
0
      return;
4796
0
    }
4797
4798
14
    if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
4799
14
                           NameLoc.isValid() ? NameLoc : 
StartLoc0
,
4800
14
                           PrevSpec, DiagID, Type.get(),
4801
14
                           Actions.getASTContext().getPrintingPolicy()))
4802
0
      Diag(StartLoc, DiagID) << PrevSpec;
4803
4804
14
    return;
4805
14
  }
4806
4807
941k
  if (!TagDecl) {
4808
    // The action failed to produce an enumeration tag. If this is a
4809
    // definition, consume the entire definition.
4810
75
    if (Tok.is(tok::l_brace) && 
TUK != Sema::TUK_Reference47
) {
4811
47
      ConsumeBrace();
4812
47
      SkipUntil(tok::r_brace, StopAtSemi);
4813
47
    }
4814
4815
75
    DS.SetTypeSpecError();
4816
75
    return;
4817
75
  }
4818
4819
941k
  if (Tok.is(tok::l_brace) && 
TUK == Sema::TUK_Definition465k
) {
4820
465k
    Decl *D = SkipBody.CheckSameAsPrevious ? 
SkipBody.New4
:
TagDecl465k
;
4821
465k
    ParseEnumBody(StartLoc, D);
4822
465k
    if (SkipBody.CheckSameAsPrevious &&
4823
465k
        
!Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)4
) {
4824
2
      DS.SetTypeSpecError();
4825
2
      return;
4826
2
    }
4827
465k
  }
4828
4829
941k
  if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
4830
941k
                         NameLoc.isValid() ? 
NameLoc564k
:
StartLoc376k
,
4831
941k
                         PrevSpec, DiagID, TagDecl, Owned,
4832
941k
                         Actions.getASTContext().getPrintingPolicy()))
4833
0
    Diag(StartLoc, DiagID) << PrevSpec;
4834
941k
}
4835
4836
/// ParseEnumBody - Parse a {} enclosed enumerator-list.
4837
///       enumerator-list:
4838
///         enumerator
4839
///         enumerator-list ',' enumerator
4840
///       enumerator:
4841
///         enumeration-constant attributes[opt]
4842
///         enumeration-constant attributes[opt] '=' constant-expression
4843
///       enumeration-constant:
4844
///         identifier
4845
///
4846
465k
void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
4847
  // Enter the scope of the enum body and start the definition.
4848
465k
  ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
4849
465k
  Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
4850
4851
465k
  BalancedDelimiterTracker T(*this, tok::l_brace);
4852
465k
  T.consumeOpen();
4853
4854
  // C does not allow an empty enumerator-list, C++ does [dcl.enum].
4855
465k
  if (Tok.is(tok::r_brace) && 
!getLangOpts().CPlusPlus1.61k
)
4856
1
    Diag(Tok, diag::err_empty_enum);
4857
4858
465k
  SmallVector<Decl *, 32> EnumConstantDecls;
4859
465k
  SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
4860
4861
465k
  Decl *LastEnumConstDecl = nullptr;
4862
4863
  // Parse the enumerator-list.
4864
4.21M
  while (Tok.isNot(tok::r_brace)) {
4865
    // Parse enumerator. If failed, try skipping till the start of the next
4866
    // enumerator definition.
4867
3.79M
    if (Tok.isNot(tok::identifier)) {
4868
9
      Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
4869
9
      if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
4870
9
          TryConsumeToken(tok::comma))
4871
2
        continue;
4872
7
      break;
4873
9
    }
4874
3.79M
    IdentifierInfo *Ident = Tok.getIdentifierInfo();
4875
3.79M
    SourceLocation IdentLoc = ConsumeToken();
4876
4877
    // If attributes exist after the enumerator, parse them.
4878
3.79M
    ParsedAttributesWithRange attrs(AttrFactory);
4879
3.79M
    MaybeParseGNUAttributes(attrs);
4880
3.79M
    if (standardAttributesAllowed() && 
isCXX11AttributeSpecifier()565k
) {
4881
16
      if (getLangOpts().CPlusPlus)
4882
9
        Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
4883
9
                                    ? 
diag::warn_cxx14_compat_ns_enum_attribute7
4884
9
                                    : 
diag::ext_ns_enum_attribute2
)
4885
9
            << 1 /*enumerator*/;
4886
16
      ParseCXX11Attributes(attrs);
4887
16
    }
4888
4889
3.79M
    SourceLocation EqualLoc;
4890
3.79M
    ExprResult AssignedVal;
4891
3.79M
    EnumAvailabilityDiags.emplace_back(*this);
4892
4893
3.79M
    EnterExpressionEvaluationContext ConstantEvaluated(
4894
3.79M
        Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4895
3.79M
    if (TryConsumeToken(tok::equal, EqualLoc)) {
4896
3.62M
      AssignedVal = ParseConstantExpressionInExprEvalContext();
4897
3.62M
      if (AssignedVal.isInvalid())
4898
7
        SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
4899
3.62M
    }
4900
4901
    // Install the enumerator constant into EnumDecl.
4902
3.79M
    Decl *EnumConstDecl = Actions.ActOnEnumConstant(
4903
3.79M
        getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs,
4904
3.79M
        EqualLoc, AssignedVal.get());
4905
3.79M
    EnumAvailabilityDiags.back().done();
4906
4907
3.79M
    EnumConstantDecls.push_back(EnumConstDecl);
4908
3.79M
    LastEnumConstDecl = EnumConstDecl;
4909
4910
3.79M
    if (Tok.is(tok::identifier)) {
4911
      // We're missing a comma between enumerators.
4912
4
      SourceLocation Loc = getEndOfPreviousToken();
4913
4
      Diag(Loc, diag::err_enumerator_list_missing_comma)
4914
4
        << FixItHint::CreateInsertion(Loc, ", ");
4915
4
      continue;
4916
4
    }
4917
4918
    // Emumerator definition must be finished, only comma or r_brace are
4919
    // allowed here.
4920
3.79M
    SourceLocation CommaLoc;
4921
3.79M
    if (Tok.isNot(tok::r_brace) && 
!TryConsumeToken(tok::comma, CommaLoc)3.36M
) {
4922
7
      if (EqualLoc.isValid())
4923
5
        Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
4924
5
                                                           << tok::comma;
4925
2
      else
4926
2
        Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
4927
7
      if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
4928
7
        if (TryConsumeToken(tok::comma, CommaLoc))
4929
2
          continue;
4930
7
      } else {
4931
0
        break;
4932
0
      }
4933
7
    }
4934
4935
    // If comma is followed by r_brace, emit appropriate warning.
4936
3.79M
    if (Tok.is(tok::r_brace) && 
CommaLoc.isValid()464k
) {
4937
42.2k
      if (!getLangOpts().C99 && 
!getLangOpts().CPlusPlus117.24k
)
4938
8
        Diag(CommaLoc, getLangOpts().CPlusPlus ?
4939
7
               diag::ext_enumerator_list_comma_cxx :
4940
8
               
diag::ext_enumerator_list_comma_c1
)
4941
8
          << FixItHint::CreateRemoval(CommaLoc);
4942
42.2k
      else if (getLangOpts().CPlusPlus11)
4943
7.23k
        Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
4944
7.23k
          << FixItHint::CreateRemoval(CommaLoc);
4945
42.2k
      break;
4946
42.2k
    }
4947
3.79M
  }
4948
4949
  // Eat the }.
4950
465k
  T.consumeClose();
4951
4952
  // If attributes exist after the identifier list, parse them.
4953
465k
  ParsedAttributes attrs(AttrFactory);
4954
465k
  MaybeParseGNUAttributes(attrs);
4955
4956
465k
  Actions.ActOnEnumBody(StartLoc, T.getRange(), EnumDecl, EnumConstantDecls,
4957
465k
                        getCurScope(), attrs);
4958
4959
  // Now handle enum constant availability diagnostics.
4960
465k
  assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
4961
4.25M
  for (size_t i = 0, e = EnumConstantDecls.size(); i != e; 
++i3.79M
) {
4962
3.79M
    ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
4963
3.79M
    EnumAvailabilityDiags[i].redelay();
4964
3.79M
    PD.complete(EnumConstantDecls[i]);
4965
3.79M
  }
4966
4967
465k
  EnumScope.Exit();
4968
465k
  Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
4969
4970
  // The next token must be valid after an enum definition. If not, a ';'
4971
  // was probably forgotten.
4972
465k
  bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
4973
465k
  if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
4974
6
    ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
4975
    // Push this token back into the preprocessor and change our current token
4976
    // to ';' so that the rest of the code recovers as though there were an
4977
    // ';' after the definition.
4978
6
    PP.EnterToken(Tok, /*IsReinject=*/true);
4979
6
    Tok.setKind(tok::semi);
4980
6
  }
4981
465k
}
4982
4983
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
4984
/// is definitely a type-specifier.  Return false if it isn't part of a type
4985
/// specifier or if we're not sure.
4986
70.0k
bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
4987
70.0k
  switch (Tok.getKind()) {
4988
70.0k
  default: return false;
4989
    // type-specifiers
4990
0
  case tok::kw_short:
4991
0
  case tok::kw_long:
4992
0
  case tok::kw___int64:
4993
0
  case tok::kw___int128:
4994
0
  case tok::kw_signed:
4995
0
  case tok::kw_unsigned:
4996
0
  case tok::kw__Complex:
4997
0
  case tok::kw__Imaginary:
4998
7
  case tok::kw_void:
4999
7
  case tok::kw_char:
5000
7
  case tok::kw_wchar_t:
5001
7
  case tok::kw_char8_t:
5002
7
  case tok::kw_char16_t:
5003
7
  case tok::kw_char32_t:
5004
37
  case tok::kw_int:
5005
37
  case tok::kw__ExtInt:
5006
37
  case tok::kw___bf16:
5007
37
  case tok::kw_half:
5008
37
  case tok::kw_float:
5009
38
  case tok::kw_double:
5010
38
  case tok::kw__Accum:
5011
38
  case tok::kw__Fract:
5012
38
  case tok::kw__Float16:
5013
38
  case tok::kw___float128:
5014
38
  case tok::kw___ibm128:
5015
38
  case tok::kw_bool:
5016
38
  case tok::kw__Bool:
5017
38
  case tok::kw__Decimal32:
5018
38
  case tok::kw__Decimal64:
5019
38
  case tok::kw__Decimal128:
5020
38
  case tok::kw___vector:
5021
456
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5022
456
#include 
"clang/Basic/OpenCLImageTypes.def"38
5023
5024
    // struct-or-union-specifier (C99) or class-specifier (C++)
5025
456
  case tok::kw_class:
5026
38
  case tok::kw_struct:
5027
38
  case tok::kw___interface:
5028
38
  case tok::kw_union:
5029
    // enum-specifier
5030
38
  case tok::kw_enum:
5031
5032
    // typedef-name
5033
38
  case tok::annot_typename:
5034
38
    return true;
5035
70.0k
  }
5036
70.0k
}
5037
5038
/// isTypeSpecifierQualifier - Return true if the current token could be the
5039
/// start of a specifier-qualifier-list.
5040
11.2M
bool Parser::isTypeSpecifierQualifier() {
5041
11.2M
  switch (Tok.getKind()) {
5042
348k
  default: return false;
5043
5044
5.51M
  case tok::identifier:   // foo::bar
5045
5.51M
    if (TryAltiVecVectorToken())
5046
157k
      return true;
5047
5.51M
    
LLVM_FALLTHROUGH5.35M
;5.35M
5048
5.35M
  case tok::kw_typename:  // typename T::type
5049
    // Annotate typenames and C++ scope specifiers.  If we get one, just
5050
    // recurse to handle whatever we get.
5051
5.35M
    if (TryAnnotateTypeOrScopeToken())
5052
0
      return true;
5053
5.35M
    if (Tok.is(tok::identifier))
5054
491k
      return false;
5055
4.86M
    return isTypeSpecifierQualifier();
5056
5057
0
  case tok::coloncolon:   // ::foo::bar
5058
0
    if (NextToken().is(tok::kw_new) ||    // ::new
5059
0
        NextToken().is(tok::kw_delete))   // ::delete
5060
0
      return false;
5061
5062
0
    if (TryAnnotateTypeOrScopeToken())
5063
0
      return true;
5064
0
    return isTypeSpecifierQualifier();
5065
5066
    // GNU attributes support.
5067
1.09k
  case tok::kw___attribute:
5068
    // GNU typeof support.
5069
1.59k
  case tok::kw_typeof:
5070
5071
    // type-specifiers
5072
4.10k
  case tok::kw_short:
5073
13.2k
  case tok::kw_long:
5074
13.2k
  case tok::kw___int64:
5075
13.2k
  case tok::kw___int128:
5076
15.6k
  case tok::kw_signed:
5077
48.1k
  case tok::kw_unsigned:
5078
48.1k
  case tok::kw__Complex:
5079
48.1k
  case tok::kw__Imaginary:
5080
303k
  case tok::kw_void:
5081
307k
  case tok::kw_char:
5082
307k
  case tok::kw_wchar_t:
5083
307k
  case tok::kw_char8_t:
5084
307k
  case tok::kw_char16_t:
5085
307k
  case tok::kw_char32_t:
5086
351k
  case tok::kw_int:
5087
351k
  case tok::kw__ExtInt:
5088
351k
  case tok::kw_half:
5089
351k
  case tok::kw___bf16:
5090
357k
  case tok::kw_float:
5091
368k
  case tok::kw_double:
5092
368k
  case tok::kw__Accum:
5093
368k
  case tok::kw__Fract:
5094
368k
  case tok::kw__Float16:
5095
368k
  case tok::kw___float128:
5096
368k
  case tok::kw___ibm128:
5097
368k
  case tok::kw_bool:
5098
368k
  case tok::kw__Bool:
5099
368k
  case tok::kw__Decimal32:
5100
368k
  case tok::kw__Decimal64:
5101
368k
  case tok::kw__Decimal128:
5102
403k
  case tok::kw___vector:
5103
4.83M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
5104
4.83M
#include 
"clang/Basic/OpenCLImageTypes.def"403k
5105
5106
    // struct-or-union-specifier (C99) or class-specifier (C++)
5107
4.83M
  case tok::kw_class:
5108
416k
  case tok::kw_struct:
5109
416k
  case tok::kw___interface:
5110
418k
  case tok::kw_union:
5111
    // enum-specifier
5112
418k
  case tok::kw_enum:
5113
5114
    // type-qualifier
5115
486k
  case tok::kw_const:
5116
488k
  case tok::kw_volatile:
5117
488k
  case tok::kw_restrict:
5118
489k
  case tok::kw__Sat:
5119
5120
    // Debugger support.
5121
489k
  case tok::kw___unknown_anytype:
5122
5123
    // typedef-name
5124
5.35M
  case tok::annot_typename:
5125
5.35M
    return true;
5126
5127
    // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
5128
3
  case tok::less:
5129
3
    return getLangOpts().ObjC;
5130
5131
0
  case tok::kw___cdecl:
5132
0
  case tok::kw___stdcall:
5133
0
  case tok::kw___fastcall:
5134
0
  case tok::kw___thiscall:
5135
0
  case tok::kw___regcall:
5136
0
  case tok::kw___vectorcall:
5137
0
  case tok::kw___w64:
5138
0
  case tok::kw___ptr64:
5139
0
  case tok::kw___ptr32:
5140
0
  case tok::kw___pascal:
5141
1
  case tok::kw___unaligned:
5142
5143
9
  case tok::kw__Nonnull:
5144
19
  case tok::kw__Nullable:
5145
20
  case tok::kw__Nullable_result:
5146
20
  case tok::kw__Null_unspecified:
5147
5148
227
  case tok::kw___kindof:
5149
5150
402
  case tok::kw___private:
5151
536
  case tok::kw___local:
5152
701
  case tok::kw___global:
5153
753
  case tok::kw___constant:
5154
1.00k
  case tok::kw___generic:
5155
1.00k
  case tok::kw___read_only:
5156
1.00k
  case tok::kw___read_write:
5157
1.00k
  case tok::kw___write_only:
5158
1.00k
    return true;
5159
5160
0
  case tok::kw_private:
5161
0
    return getLangOpts().OpenCL;
5162
5163
  // C11 _Atomic
5164
95
  case tok::kw__Atomic:
5165
95
    return true;
5166
11.2M
  }
5167
11.2M
}
5168
5169
/// isDeclarationSpecifier() - Return true if the current token is part of a
5170
/// declaration specifier.
5171
///
5172
/// \param DisambiguatingWithExpression True to indicate that the purpose of
5173
/// this check is to disambiguate between an expression and a declaration.
5174
1.69M
bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
5175
1.69M
  switch (Tok.getKind()) {
5176
713k
  default: return false;
5177
5178
  // OpenCL 2.0 and later define this keyword.
5179
9
  case tok::kw_pipe:
5180
9
    return getLangOpts().OpenCL &&
5181
9
           getLangOpts().getOpenCLCompatibleVersion() >= 200;
5182
5183
199k
  case tok::identifier:   // foo::bar
5184
    // Unfortunate hack to support "Class.factoryMethod" notation.
5185
199k
    if (getLangOpts().ObjC && 
NextToken().is(tok::period)5.05k
)
5186
82
      return false;
5187
199k
    if (TryAltiVecVectorToken())
5188
8.05k
      return true;
5189
199k
    
LLVM_FALLTHROUGH191k
;191k
5190
191k
  case tok::kw_decltype: // decltype(T())::type
5191
191k
  case tok::kw_typename: // typename T::type
5192
    // Annotate typenames and C++ scope specifiers.  If we get one, just
5193
    // recurse to handle whatever we get.
5194
191k
    if (TryAnnotateTypeOrScopeToken())
5195
1
      return true;
5196
191k
    if (TryAnnotateTypeConstraint())
5197
0
      return true;
5198
191k
    if (Tok.is(tok::identifier))
5199
7.87k
      return false;
5200
5201