Coverage Report

Created: 2023-05-31 04:38

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