Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseExpr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
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
/// \file
10
/// Provides the Expression parsing implementation.
11
///
12
/// Expressions in C99 basically consist of a bunch of binary operators with
13
/// unary operators and other random stuff at the leaves.
14
///
15
/// In the C99 grammar, these unary operators bind tightest and are represented
16
/// as the 'cast-expression' production.  Everything else is either a binary
17
/// operator (e.g. '/') or a ternary operator ("?:").  The unary leaves are
18
/// handled by ParseCastExpression, the higher level pieces are handled by
19
/// ParseBinaryExpression.
20
///
21
//===----------------------------------------------------------------------===//
22
23
#include "clang/Parse/Parser.h"
24
#include "clang/AST/ASTContext.h"
25
#include "clang/AST/ExprCXX.h"
26
#include "clang/Basic/PrettyStackTrace.h"
27
#include "clang/Parse/RAIIObjectsForParser.h"
28
#include "clang/Sema/DeclSpec.h"
29
#include "clang/Sema/ParsedTemplate.h"
30
#include "clang/Sema/Scope.h"
31
#include "clang/Sema/TypoCorrection.h"
32
#include "llvm/ADT/SmallVector.h"
33
using namespace clang;
34
35
/// Simple precedence-based parser for binary/ternary operators.
36
///
37
/// Note: we diverge from the C99 grammar when parsing the assignment-expression
38
/// production.  C99 specifies that the LHS of an assignment operator should be
39
/// parsed as a unary-expression, but consistency dictates that it be a
40
/// conditional-expession.  In practice, the important thing here is that the
41
/// LHS of an assignment has to be an l-value, which productions between
42
/// unary-expression and conditional-expression don't produce.  Because we want
43
/// consistency, we parse the LHS as a conditional-expression, then check for
44
/// l-value-ness in semantic analysis stages.
45
///
46
/// \verbatim
47
///       pm-expression: [C++ 5.5]
48
///         cast-expression
49
///         pm-expression '.*' cast-expression
50
///         pm-expression '->*' cast-expression
51
///
52
///       multiplicative-expression: [C99 6.5.5]
53
///     Note: in C++, apply pm-expression instead of cast-expression
54
///         cast-expression
55
///         multiplicative-expression '*' cast-expression
56
///         multiplicative-expression '/' cast-expression
57
///         multiplicative-expression '%' cast-expression
58
///
59
///       additive-expression: [C99 6.5.6]
60
///         multiplicative-expression
61
///         additive-expression '+' multiplicative-expression
62
///         additive-expression '-' multiplicative-expression
63
///
64
///       shift-expression: [C99 6.5.7]
65
///         additive-expression
66
///         shift-expression '<<' additive-expression
67
///         shift-expression '>>' additive-expression
68
///
69
///       compare-expression: [C++20 expr.spaceship]
70
///         shift-expression
71
///         compare-expression '<=>' shift-expression
72
///
73
///       relational-expression: [C99 6.5.8]
74
///         compare-expression
75
///         relational-expression '<' compare-expression
76
///         relational-expression '>' compare-expression
77
///         relational-expression '<=' compare-expression
78
///         relational-expression '>=' compare-expression
79
///
80
///       equality-expression: [C99 6.5.9]
81
///         relational-expression
82
///         equality-expression '==' relational-expression
83
///         equality-expression '!=' relational-expression
84
///
85
///       AND-expression: [C99 6.5.10]
86
///         equality-expression
87
///         AND-expression '&' equality-expression
88
///
89
///       exclusive-OR-expression: [C99 6.5.11]
90
///         AND-expression
91
///         exclusive-OR-expression '^' AND-expression
92
///
93
///       inclusive-OR-expression: [C99 6.5.12]
94
///         exclusive-OR-expression
95
///         inclusive-OR-expression '|' exclusive-OR-expression
96
///
97
///       logical-AND-expression: [C99 6.5.13]
98
///         inclusive-OR-expression
99
///         logical-AND-expression '&&' inclusive-OR-expression
100
///
101
///       logical-OR-expression: [C99 6.5.14]
102
///         logical-AND-expression
103
///         logical-OR-expression '||' logical-AND-expression
104
///
105
///       conditional-expression: [C99 6.5.15]
106
///         logical-OR-expression
107
///         logical-OR-expression '?' expression ':' conditional-expression
108
/// [GNU]   logical-OR-expression '?' ':' conditional-expression
109
/// [C++] the third operand is an assignment-expression
110
///
111
///       assignment-expression: [C99 6.5.16]
112
///         conditional-expression
113
///         unary-expression assignment-operator assignment-expression
114
/// [C++]   throw-expression [C++ 15]
115
///
116
///       assignment-operator: one of
117
///         = *= /= %= += -= <<= >>= &= ^= |=
118
///
119
///       expression: [C99 6.5.17]
120
///         assignment-expression ...[opt]
121
///         expression ',' assignment-expression ...[opt]
122
/// \endverbatim
123
6.86M
ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124
6.86M
  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125
6.86M
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
126
6.86M
}
127
128
/// This routine is called when the '@' is seen and consumed.
129
/// Current token is an Identifier and is not a 'try'. This
130
/// routine is necessary to disambiguate \@try-statement from,
131
/// for example, \@encode-expression.
132
///
133
ExprResult
134
301
Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
135
301
  ExprResult LHS(ParseObjCAtExpression(AtLoc));
136
301
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
137
301
}
138
139
/// This routine is called when a leading '__extension__' is seen and
140
/// consumed.  This is necessary because the token gets consumed in the
141
/// process of disambiguating between an expression and a declaration.
142
ExprResult
143
3.60k
Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
144
3.60k
  ExprResult LHS(true);
145
3.60k
  {
146
    // Silence extension warnings in the sub-expression
147
3.60k
    ExtensionRAIIObject O(Diags);
148
149
3.60k
    LHS = ParseCastExpression(AnyCastExpr);
150
3.60k
  }
151
152
3.60k
  if (!LHS.isInvalid())
153
3.60k
    LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
154
3.60k
                               LHS.get());
155
156
3.60k
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
157
3.60k
}
158
159
/// Parse an expr that doesn't include (top-level) commas.
160
22.8M
ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161
22.8M
  if (Tok.is(tok::code_completion)) {
162
221
    cutOffParsing();
163
221
    Actions.CodeCompleteExpression(getCurScope(),
164
221
                                   PreferredType.get(Tok.getLocation()));
165
221
    return ExprError();
166
221
  }
167
168
22.8M
  if (Tok.is(tok::kw_throw))
169
14.9k
    return ParseThrowExpression();
170
22.8M
  if (Tok.is(tok::kw_co_yield))
171
288
    return ParseCoyieldExpression();
172
173
22.8M
  ExprResult LHS = ParseCastExpression(AnyCastExpr,
174
22.8M
                                       /*isAddressOfOperand=*/false,
175
22.8M
                                       isTypeCast);
176
22.8M
  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
177
22.8M
}
178
179
/// Parse an assignment expression where part of an Objective-C message
180
/// send has already been parsed.
181
///
182
/// In this case \p LBracLoc indicates the location of the '[' of the message
183
/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
184
/// the receiver of the message.
185
///
186
/// Since this handles full assignment-expression's, it handles postfix
187
/// expressions and other binary operators for these expressions as well.
188
ExprResult
189
Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
190
                                                    SourceLocation SuperLoc,
191
                                                    ParsedType ReceiverType,
192
68
                                                    Expr *ReceiverExpr) {
193
68
  ExprResult R
194
68
    = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
195
68
                                     ReceiverType, ReceiverExpr);
196
68
  R = ParsePostfixExpressionSuffix(R);
197
68
  return ParseRHSOfBinaryExpression(R, prec::Assignment);
198
68
}
199
200
ExprResult
201
4.62M
Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
202
4.62M
  assert(Actions.ExprEvalContexts.back().Context ==
203
4.62M
             Sema::ExpressionEvaluationContext::ConstantEvaluated &&
204
4.62M
         "Call this function only if your ExpressionEvaluationContext is "
205
4.62M
         "already ConstantEvaluated");
206
0
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
207
4.62M
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
208
4.62M
  return Actions.ActOnConstantExpression(Res);
209
4.62M
}
210
211
160k
ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
212
  // C++03 [basic.def.odr]p2:
213
  //   An expression is potentially evaluated unless it appears where an
214
  //   integral constant expression is required (see 5.19) [...].
215
  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
216
160k
  EnterExpressionEvaluationContext ConstantEvaluated(
217
160k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
218
160k
  return ParseConstantExpressionInExprEvalContext(isTypeCast);
219
160k
}
220
221
13.9k
ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
222
13.9k
  EnterExpressionEvaluationContext ConstantEvaluated(
223
13.9k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
224
13.9k
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
225
13.9k
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
226
13.9k
  return Actions.ActOnCaseExpr(CaseLoc, Res);
227
13.9k
}
228
229
/// Parse a constraint-expression.
230
///
231
/// \verbatim
232
///       constraint-expression: C++2a[temp.constr.decl]p1
233
///         logical-or-expression
234
/// \endverbatim
235
350
ExprResult Parser::ParseConstraintExpression() {
236
350
  EnterExpressionEvaluationContext ConstantEvaluated(
237
350
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
238
350
  ExprResult LHS(ParseCastExpression(AnyCastExpr));
239
350
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
240
350
  if (Res.isUsable() && 
!Actions.CheckConstraintExpression(Res.get())347
) {
241
6
    Actions.CorrectDelayedTyposInExpr(Res);
242
6
    return ExprError();
243
6
  }
244
344
  return Res;
245
350
}
246
247
/// \brief Parse a constraint-logical-and-expression.
248
///
249
/// \verbatim
250
///       C++2a[temp.constr.decl]p1
251
///       constraint-logical-and-expression:
252
///         primary-expression
253
///         constraint-logical-and-expression '&&' primary-expression
254
///
255
/// \endverbatim
256
ExprResult
257
506
Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
258
506
  EnterExpressionEvaluationContext ConstantEvaluated(
259
506
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
260
506
  bool NotPrimaryExpression = false;
261
537
  auto ParsePrimary = [&] () {
262
537
    ExprResult E = ParseCastExpression(PrimaryExprOnly,
263
537
                                       /*isAddressOfOperand=*/false,
264
537
                                       /*isTypeCast=*/NotTypeCast,
265
537
                                       /*isVectorLiteral=*/false,
266
537
                                       &NotPrimaryExpression);
267
537
    if (E.isInvalid())
268
6
      return ExprError();
269
531
    auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
270
22
        E = ParsePostfixExpressionSuffix(E);
271
        // Use InclusiveOr, the precedence just after '&&' to not parse the
272
        // next arguments to the logical and.
273
22
        E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
274
22
        if (!E.isInvalid())
275
20
          Diag(E.get()->getExprLoc(),
276
20
               Note
277
20
               ? 
diag::note_unparenthesized_non_primary_expr_in_requires_clause4
278
20
               : 
diag::err_unparenthesized_non_primary_expr_in_requires_clause16
)
279
20
               << FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
280
20
               << FixItHint::CreateInsertion(
281
20
                   PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
282
20
               << E.get()->getSourceRange();
283
22
        return E;
284
22
    };
285
286
531
    if (NotPrimaryExpression ||
287
        // Check if the following tokens must be a part of a non-primary
288
        // expression
289
531
        getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
290
523
                           /*CPlusPlus11=*/true) > prec::LogicalAnd ||
291
        // Postfix operators other than '(' (which will be checked for in
292
        // CheckConstraintExpression).
293
531
        
Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus)519
||
294
531
        
(519
Tok.is(tok::l_square)519
&&
!NextToken().is(tok::l_square)0
)) {
295
12
      E = RecoverFromNonPrimary(E, /*Note=*/false);
296
12
      if (E.isInvalid())
297
0
        return ExprError();
298
12
      NotPrimaryExpression = false;
299
12
    }
300
531
    bool PossibleNonPrimary;
301
531
    bool IsConstraintExpr =
302
531
        Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
303
531
                                          IsTrailingRequiresClause);
304
531
    if (!IsConstraintExpr || 
PossibleNonPrimary525
) {
305
      // Atomic constraint might be an unparenthesized non-primary expression
306
      // (such as a binary operator), in which case we might get here (e.g. in
307
      // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
308
      // the rest of the addition expression). Try to parse the rest of it here.
309
12
      if (PossibleNonPrimary)
310
10
        E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
311
12
      Actions.CorrectDelayedTyposInExpr(E);
312
12
      return ExprError();
313
12
    }
314
519
    return E;
315
531
  };
316
506
  ExprResult LHS = ParsePrimary();
317
506
  if (LHS.isInvalid())
318
18
    return ExprError();
319
519
  
while (488
Tok.is(tok::ampamp)) {
320
31
    SourceLocation LogicalAndLoc = ConsumeToken();
321
31
    ExprResult RHS = ParsePrimary();
322
31
    if (RHS.isInvalid()) {
323
0
      Actions.CorrectDelayedTyposInExpr(LHS);
324
0
      return ExprError();
325
0
    }
326
31
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
327
31
                                       tok::ampamp, LHS.get(), RHS.get());
328
31
    if (!Op.isUsable()) {
329
0
      Actions.CorrectDelayedTyposInExpr(RHS);
330
0
      Actions.CorrectDelayedTyposInExpr(LHS);
331
0
      return ExprError();
332
0
    }
333
31
    LHS = Op;
334
31
  }
335
488
  return LHS;
336
488
}
337
338
/// \brief Parse a constraint-logical-or-expression.
339
///
340
/// \verbatim
341
///       C++2a[temp.constr.decl]p1
342
///       constraint-logical-or-expression:
343
///         constraint-logical-and-expression
344
///         constraint-logical-or-expression '||'
345
///             constraint-logical-and-expression
346
///
347
/// \endverbatim
348
ExprResult
349
498
Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
350
498
  ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
351
498
  if (!LHS.isUsable())
352
18
    return ExprError();
353
488
  
while (480
Tok.is(tok::pipepipe)) {
354
8
    SourceLocation LogicalOrLoc = ConsumeToken();
355
8
    ExprResult RHS =
356
8
        ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
357
8
    if (!RHS.isUsable()) {
358
0
      Actions.CorrectDelayedTyposInExpr(LHS);
359
0
      return ExprError();
360
0
    }
361
8
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
362
8
                                       tok::pipepipe, LHS.get(), RHS.get());
363
8
    if (!Op.isUsable()) {
364
0
      Actions.CorrectDelayedTyposInExpr(RHS);
365
0
      Actions.CorrectDelayedTyposInExpr(LHS);
366
0
      return ExprError();
367
0
    }
368
8
    LHS = Op;
369
8
  }
370
480
  return LHS;
371
480
}
372
373
30.3k
bool Parser::isNotExpressionStart() {
374
30.3k
  tok::TokenKind K = Tok.getKind();
375
30.3k
  if (K == tok::l_brace || 
K == tok::r_brace30.3k
||
376
30.3k
      
K == tok::kw_for30.3k
||
K == tok::kw_while30.3k
||
377
30.3k
      
K == tok::kw_if30.3k
||
K == tok::kw_else30.3k
||
378
30.3k
      
K == tok::kw_goto30.3k
||
K == tok::kw_try30.3k
)
379
5
    return true;
380
  // If this is a decl-specifier, we can't be at the start of an expression.
381
30.3k
  return isKnownToBeDeclarationSpecifier();
382
30.3k
}
383
384
4.34M
bool Parser::isFoldOperator(prec::Level Level) const {
385
4.34M
  return Level > prec::Unknown && 
Level != prec::Conditional3.32M
&&
386
4.34M
         
Level != prec::Spaceship3.26M
;
387
4.34M
}
388
389
1.02M
bool Parser::isFoldOperator(tok::TokenKind Kind) const {
390
1.02M
  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
391
1.02M
}
392
393
/// Parse a binary expression that starts with \p LHS and has a
394
/// precedence of at least \p MinPrec.
395
ExprResult
396
34.5M
Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
397
34.5M
  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
398
34.5M
                                               GreaterThanIsOperator,
399
34.5M
                                               getLangOpts().CPlusPlus11);
400
34.5M
  SourceLocation ColonLoc;
401
402
34.5M
  auto SavedType = PreferredType;
403
37.8M
  while (true) {
404
    // Every iteration may rely on a preferred type for the whole expression.
405
37.8M
    PreferredType = SavedType;
406
    // If this token has a lower precedence than we are allowed to parse (e.g.
407
    // because we are called recursively, or because the token is not a binop),
408
    // then we are done!
409
37.8M
    if (NextTokPrec < MinPrec)
410
34.5M
      return LHS;
411
412
    // Consume the operator, saving the operator token for error reporting.
413
3.32M
    Token OpToken = Tok;
414
3.32M
    ConsumeToken();
415
416
3.32M
    if (OpToken.is(tok::caretcaret)) {
417
2
      return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
418
2
    }
419
420
    // If we're potentially in a template-id, we may now be able to determine
421
    // whether we're actually in one or not.
422
3.32M
    if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
423
3.32M
                        tok::greatergreatergreater) &&
424
3.32M
        
checkPotentialAngleBracketDelimiter(OpToken)145k
)
425
18
      return ExprError();
426
427
    // Bail out when encountering a comma followed by a token which can't
428
    // possibly be the start of an expression. For instance:
429
    //   int f() { return 1, }
430
    // We can't do this before consuming the comma, because
431
    // isNotExpressionStart() looks at the token stream.
432
3.32M
    if (OpToken.is(tok::comma) && 
isNotExpressionStart()30.3k
) {
433
21
      PP.EnterToken(Tok, /*IsReinject*/true);
434
21
      Tok = OpToken;
435
21
      return LHS;
436
21
    }
437
438
    // If the next token is an ellipsis, then this is a fold-expression. Leave
439
    // it alone so we can handle it in the paren expression.
440
3.32M
    if (isFoldOperator(NextTokPrec) && 
Tok.is(tok::ellipsis)3.26M
) {
441
      // FIXME: We can't check this via lookahead before we consume the token
442
      // because that tickles a lexer bug.
443
368
      PP.EnterToken(Tok, /*IsReinject*/true);
444
368
      Tok = OpToken;
445
368
      return LHS;
446
368
    }
447
448
    // In Objective-C++, alternative operator tokens can be used as keyword args
449
    // in message expressions. Unconsume the token so that it can reinterpreted
450
    // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
451
    //   [foo meth:0 and:0];
452
    //   [foo not_eq];
453
3.32M
    if (getLangOpts().ObjC && 
getLangOpts().CPlusPlus672k
&&
454
3.32M
        
Tok.isOneOf(tok::colon, tok::r_square)227k
&&
455
3.32M
        
OpToken.getIdentifierInfo() != nullptr31
) {
456
16
      PP.EnterToken(Tok, /*IsReinject*/true);
457
16
      Tok = OpToken;
458
16
      return LHS;
459
16
    }
460
461
    // Special case handling for the ternary operator.
462
3.32M
    ExprResult TernaryMiddle(true);
463
3.32M
    if (NextTokPrec == prec::Conditional) {
464
53.2k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)43.4k
) {
465
        // Parse a braced-init-list here for error recovery purposes.
466
1
        SourceLocation BraceLoc = Tok.getLocation();
467
1
        TernaryMiddle = ParseBraceInitializer();
468
1
        if (!TernaryMiddle.isInvalid()) {
469
1
          Diag(BraceLoc, diag::err_init_list_bin_op)
470
1
              << /*RHS*/ 1 << PP.getSpelling(OpToken)
471
1
              << Actions.getExprRange(TernaryMiddle.get());
472
1
          TernaryMiddle = ExprError();
473
1
        }
474
53.2k
      } else if (Tok.isNot(tok::colon)) {
475
        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
476
52.9k
        ColonProtectionRAIIObject X(*this);
477
478
        // Handle this production specially:
479
        //   logical-OR-expression '?' expression ':' conditional-expression
480
        // In particular, the RHS of the '?' is 'expression', not
481
        // 'logical-OR-expression' as we might expect.
482
52.9k
        TernaryMiddle = ParseExpression();
483
52.9k
      } else {
484
        // Special case handling of "X ? Y : Z" where Y is empty:
485
        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
486
274
        TernaryMiddle = nullptr;
487
274
        Diag(Tok, diag::ext_gnu_conditional_expr);
488
274
      }
489
490
53.2k
      if (TernaryMiddle.isInvalid()) {
491
26
        Actions.CorrectDelayedTyposInExpr(LHS);
492
26
        LHS = ExprError();
493
26
        TernaryMiddle = nullptr;
494
26
      }
495
496
53.2k
      if (!TryConsumeToken(tok::colon, ColonLoc)) {
497
        // Otherwise, we're missing a ':'.  Assume that this was a typo that
498
        // the user forgot. If we're not in a macro expansion, we can suggest
499
        // a fixit hint. If there were two spaces before the current token,
500
        // suggest inserting the colon in between them, otherwise insert ": ".
501
9
        SourceLocation FILoc = Tok.getLocation();
502
9
        const char *FIText = ": ";
503
9
        const SourceManager &SM = PP.getSourceManager();
504
9
        if (FILoc.isFileID() || 
PP.isAtStartOfMacroExpansion(FILoc, &FILoc)2
) {
505
9
          assert(FILoc.isFileID());
506
0
          bool IsInvalid = false;
507
9
          const char *SourcePtr =
508
9
            SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
509
9
          if (!IsInvalid && *SourcePtr == ' ') {
510
9
            SourcePtr =
511
9
              SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
512
9
            if (!IsInvalid && *SourcePtr == ' ') {
513
0
              FILoc = FILoc.getLocWithOffset(-1);
514
0
              FIText = ":";
515
0
            }
516
9
          }
517
9
        }
518
519
0
        Diag(Tok, diag::err_expected)
520
9
            << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
521
9
        Diag(OpToken, diag::note_matching) << tok::question;
522
9
        ColonLoc = Tok.getLocation();
523
9
      }
524
53.2k
    }
525
526
0
    PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
527
3.32M
                              OpToken.getKind());
528
    // Parse another leaf here for the RHS of the operator.
529
    // ParseCastExpression works here because all RHS expressions in C have it
530
    // as a prefix, at least. However, in C++, an assignment-expression could
531
    // be a throw-expression, which is not a valid cast-expression.
532
    // Therefore we need some special-casing here.
533
    // Also note that the third operand of the conditional operator is
534
    // an assignment-expression in C++, and in C++11, we can have a
535
    // braced-init-list on the RHS of an assignment. For better diagnostics,
536
    // parse as if we were allowed braced-init-lists everywhere, and check that
537
    // they only appear on the RHS of assignments later.
538
3.32M
    ExprResult RHS;
539
3.32M
    bool RHSIsInitList = false;
540
3.32M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)2.14M
) {
541
87
      RHS = ParseBraceInitializer();
542
87
      RHSIsInitList = true;
543
3.32M
    } else if (getLangOpts().CPlusPlus && 
NextTokPrec <= prec::Conditional2.17M
)
544
608k
      RHS = ParseAssignmentExpression();
545
2.71M
    else
546
2.71M
      RHS = ParseCastExpression(AnyCastExpr);
547
548
3.32M
    if (RHS.isInvalid()) {
549
      // FIXME: Errors generated by the delayed typo correction should be
550
      // printed before errors from parsing the RHS, not after.
551
777
      Actions.CorrectDelayedTyposInExpr(LHS);
552
777
      if (TernaryMiddle.isUsable())
553
4
        TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
554
777
      LHS = ExprError();
555
777
    }
556
557
    // Remember the precedence of this operator and get the precedence of the
558
    // operator immediately to the right of the RHS.
559
3.32M
    prec::Level ThisPrec = NextTokPrec;
560
3.32M
    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
561
3.32M
                                     getLangOpts().CPlusPlus11);
562
563
    // Assignment and conditional expressions are right-associative.
564
3.32M
    bool isRightAssoc = ThisPrec == prec::Conditional ||
565
3.32M
                        
ThisPrec == prec::Assignment3.26M
;
566
567
    // Get the precedence of the operator to the right of the RHS.  If it binds
568
    // more tightly with RHS than we do, evaluate it completely first.
569
3.32M
    if (ThisPrec < NextTokPrec ||
570
3.32M
        
(3.17M
ThisPrec == NextTokPrec3.17M
&&
isRightAssoc118k
)) {
571
150k
      if (!RHS.isInvalid() && 
RHSIsInitList150k
) {
572
4
        Diag(Tok, diag::err_init_list_bin_op)
573
4
          << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
574
4
        RHS = ExprError();
575
4
      }
576
      // If this is left-associative, only parse things on the RHS that bind
577
      // more tightly than the current operator.  If it is left-associative, it
578
      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
579
      // A=(B=(C=D)), where each paren is a level of recursion here.
580
      // The function takes ownership of the RHS.
581
150k
      RHS = ParseRHSOfBinaryExpression(RHS,
582
150k
                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
583
150k
      RHSIsInitList = false;
584
585
150k
      if (RHS.isInvalid()) {
586
        // FIXME: Errors generated by the delayed typo correction should be
587
        // printed before errors from ParseRHSOfBinaryExpression, not after.
588
9
        Actions.CorrectDelayedTyposInExpr(LHS);
589
9
        if (TernaryMiddle.isUsable())
590
0
          TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
591
9
        LHS = ExprError();
592
9
      }
593
594
150k
      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
595
150k
                                       getLangOpts().CPlusPlus11);
596
150k
    }
597
598
3.32M
    if (!RHS.isInvalid() && 
RHSIsInitList3.31M
) {
599
83
      if (ThisPrec == prec::Assignment) {
600
80
        Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
601
80
          << Actions.getExprRange(RHS.get());
602
80
      } else 
if (3
ColonLoc.isValid()3
) {
603
1
        Diag(ColonLoc, diag::err_init_list_bin_op)
604
1
          << /*RHS*/1 << ":"
605
1
          << Actions.getExprRange(RHS.get());
606
1
        LHS = ExprError();
607
2
      } else {
608
2
        Diag(OpToken, diag::err_init_list_bin_op)
609
2
          << /*RHS*/1 << PP.getSpelling(OpToken)
610
2
          << Actions.getExprRange(RHS.get());
611
2
        LHS = ExprError();
612
2
      }
613
83
    }
614
615
3.32M
    ExprResult OrigLHS = LHS;
616
3.32M
    if (!LHS.isInvalid()) {
617
      // Combine the LHS and RHS into the LHS (e.g. build AST).
618
3.31M
      if (TernaryMiddle.isInvalid()) {
619
        // If we're using '>>' as an operator within a template
620
        // argument list (in C++98), suggest the addition of
621
        // parentheses so that the code remains well-formed in C++0x.
622
3.26M
        if (!GreaterThanIsOperator && 
OpToken.is(tok::greatergreater)113k
)
623
4
          SuggestParentheses(OpToken.getLocation(),
624
4
                             diag::warn_cxx11_right_shift_in_template_arg,
625
4
                         SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
626
4
                                     Actions.getExprRange(RHS.get()).getEnd()));
627
628
3.26M
        ExprResult BinOp =
629
3.26M
            Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
630
3.26M
                               OpToken.getKind(), LHS.get(), RHS.get());
631
3.26M
        if (BinOp.isInvalid())
632
5.80k
          BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
633
5.80k
                                             RHS.get()->getEndLoc(),
634
5.80k
                                             {LHS.get(), RHS.get()});
635
636
3.26M
        LHS = BinOp;
637
3.26M
      } else {
638
53.0k
        ExprResult CondOp = Actions.ActOnConditionalOp(
639
53.0k
            OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
640
53.0k
            RHS.get());
641
53.0k
        if (CondOp.isInvalid()) {
642
353
          std::vector<clang::Expr *> Args;
643
          // TernaryMiddle can be null for the GNU conditional expr extension.
644
353
          if (TernaryMiddle.get())
645
342
            Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
646
11
          else
647
11
            Args = {LHS.get(), RHS.get()};
648
353
          CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
649
353
                                              RHS.get()->getEndLoc(), Args);
650
353
        }
651
652
53.0k
        LHS = CondOp;
653
53.0k
      }
654
      // In this case, ActOnBinOp or ActOnConditionalOp performed the
655
      // CorrectDelayedTyposInExpr check.
656
3.31M
      if (!getLangOpts().CPlusPlus)
657
1.14M
        continue;
658
3.31M
    }
659
660
    // Ensure potential typos aren't left undiagnosed.
661
2.17M
    if (LHS.isInvalid()) {
662
1.30k
      Actions.CorrectDelayedTyposInExpr(OrigLHS);
663
1.30k
      Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
664
1.30k
      Actions.CorrectDelayedTyposInExpr(RHS);
665
1.30k
    }
666
2.17M
  }
667
34.5M
}
668
669
/// Parse a cast-expression, unary-expression or primary-expression, based
670
/// on \p ExprType.
671
///
672
/// \p isAddressOfOperand exists because an id-expression that is the
673
/// operand of address-of gets special treatment due to member pointers.
674
///
675
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
676
                                       bool isAddressOfOperand,
677
                                       TypeCastState isTypeCast,
678
                                       bool isVectorLiteral,
679
36.5M
                                       bool *NotPrimaryExpression) {
680
36.5M
  bool NotCastExpr;
681
36.5M
  ExprResult Res = ParseCastExpression(ParseKind,
682
36.5M
                                       isAddressOfOperand,
683
36.5M
                                       NotCastExpr,
684
36.5M
                                       isTypeCast,
685
36.5M
                                       isVectorLiteral,
686
36.5M
                                       NotPrimaryExpression);
687
36.5M
  if (NotCastExpr)
688
15.0k
    Diag(Tok, diag::err_expected_expression);
689
36.5M
  return Res;
690
36.5M
}
691
692
namespace {
693
class CastExpressionIdValidator final : public CorrectionCandidateCallback {
694
 public:
695
  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
696
12.9M
      : NextToken(Next), AllowNonTypes(AllowNonTypes) {
697
12.9M
    WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
698
12.9M
  }
699
700
440
  bool ValidateCandidate(const TypoCorrection &candidate) override {
701
440
    NamedDecl *ND = candidate.getCorrectionDecl();
702
440
    if (!ND)
703
15
      return candidate.isKeyword();
704
705
425
    if (isa<TypeDecl>(ND))
706
57
      return WantTypeSpecifiers;
707
708
368
    if (!AllowNonTypes || 
!CorrectionCandidateCallback::ValidateCandidate(candidate)360
)
709
8
      return false;
710
711
360
    if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
712
307
      return true;
713
714
53
    for (auto *C : candidate) {
715
53
      NamedDecl *ND = C->getUnderlyingDecl();
716
53
      if (isa<ValueDecl>(ND) && 
!isa<FunctionDecl>(ND)50
)
717
44
        return true;
718
53
    }
719
9
    return false;
720
53
  }
721
722
3.03k
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
723
3.03k
    return std::make_unique<CastExpressionIdValidator>(*this);
724
3.03k
  }
725
726
 private:
727
  Token NextToken;
728
  bool AllowNonTypes;
729
};
730
}
731
732
/// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
733
/// a unary-expression.
734
///
735
/// \p isAddressOfOperand exists because an id-expression that is the operand
736
/// of address-of gets special treatment due to member pointers. NotCastExpr
737
/// is set to true if the token is not the start of a cast-expression, and no
738
/// diagnostic is emitted in this case and no tokens are consumed.
739
///
740
/// \verbatim
741
///       cast-expression: [C99 6.5.4]
742
///         unary-expression
743
///         '(' type-name ')' cast-expression
744
///
745
///       unary-expression:  [C99 6.5.3]
746
///         postfix-expression
747
///         '++' unary-expression
748
///         '--' unary-expression
749
/// [Coro]  'co_await' cast-expression
750
///         unary-operator cast-expression
751
///         'sizeof' unary-expression
752
///         'sizeof' '(' type-name ')'
753
/// [C++11] 'sizeof' '...' '(' identifier ')'
754
/// [GNU]   '__alignof' unary-expression
755
/// [GNU]   '__alignof' '(' type-name ')'
756
/// [C11]   '_Alignof' '(' type-name ')'
757
/// [C++11] 'alignof' '(' type-id ')'
758
/// [GNU]   '&&' identifier
759
/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
760
/// [C++]   new-expression
761
/// [C++]   delete-expression
762
///
763
///       unary-operator: one of
764
///         '&'  '*'  '+'  '-'  '~'  '!'
765
/// [GNU]   '__extension__'  '__real'  '__imag'
766
///
767
///       primary-expression: [C99 6.5.1]
768
/// [C99]   identifier
769
/// [C++]   id-expression
770
///         constant
771
///         string-literal
772
/// [C++]   boolean-literal  [C++ 2.13.5]
773
/// [C++11] 'nullptr'        [C++11 2.14.7]
774
/// [C++11] user-defined-literal
775
///         '(' expression ')'
776
/// [C11]   generic-selection
777
/// [C++2a] requires-expression
778
///         '__func__'        [C99 6.4.2.2]
779
/// [GNU]   '__FUNCTION__'
780
/// [MS]    '__FUNCDNAME__'
781
/// [MS]    'L__FUNCTION__'
782
/// [MS]    '__FUNCSIG__'
783
/// [MS]    'L__FUNCSIG__'
784
/// [GNU]   '__PRETTY_FUNCTION__'
785
/// [GNU]   '(' compound-statement ')'
786
/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
787
/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
788
/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
789
///                                     assign-expr ')'
790
/// [GNU]   '__builtin_FILE' '(' ')'
791
/// [GNU]   '__builtin_FUNCTION' '(' ')'
792
/// [GNU]   '__builtin_LINE' '(' ')'
793
/// [CLANG] '__builtin_COLUMN' '(' ')'
794
/// [GNU]   '__builtin_source_location' '(' ')'
795
/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
796
/// [GNU]   '__null'
797
/// [OBJC]  '[' objc-message-expr ']'
798
/// [OBJC]  '\@selector' '(' objc-selector-arg ')'
799
/// [OBJC]  '\@protocol' '(' identifier ')'
800
/// [OBJC]  '\@encode' '(' type-name ')'
801
/// [OBJC]  objc-string-literal
802
/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
803
/// [C++11] simple-type-specifier braced-init-list                  [C++11 5.2.3]
804
/// [C++]   typename-specifier '(' expression-list[opt] ')'         [C++ 5.2.3]
805
/// [C++11] typename-specifier braced-init-list                     [C++11 5.2.3]
806
/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
807
/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
808
/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
809
/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
810
/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
811
/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
812
/// [C++]   'this'          [C++ 9.3.2]
813
/// [G++]   unary-type-trait '(' type-id ')'
814
/// [G++]   binary-type-trait '(' type-id ',' type-id ')'           [TODO]
815
/// [EMBT]  array-type-trait '(' type-id ',' integer ')'
816
/// [clang] '^' block-literal
817
///
818
///       constant: [C99 6.4.4]
819
///         integer-constant
820
///         floating-constant
821
///         enumeration-constant -> identifier
822
///         character-constant
823
///
824
///       id-expression: [C++ 5.1]
825
///                   unqualified-id
826
///                   qualified-id
827
///
828
///       unqualified-id: [C++ 5.1]
829
///                   identifier
830
///                   operator-function-id
831
///                   conversion-function-id
832
///                   '~' class-name
833
///                   template-id
834
///
835
///       new-expression: [C++ 5.3.4]
836
///                   '::'[opt] 'new' new-placement[opt] new-type-id
837
///                                     new-initializer[opt]
838
///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
839
///                                     new-initializer[opt]
840
///
841
///       delete-expression: [C++ 5.3.5]
842
///                   '::'[opt] 'delete' cast-expression
843
///                   '::'[opt] 'delete' '[' ']' cast-expression
844
///
845
/// [GNU/Embarcadero] unary-type-trait:
846
///                   '__is_arithmetic'
847
///                   '__is_floating_point'
848
///                   '__is_integral'
849
///                   '__is_lvalue_expr'
850
///                   '__is_rvalue_expr'
851
///                   '__is_complete_type'
852
///                   '__is_void'
853
///                   '__is_array'
854
///                   '__is_function'
855
///                   '__is_reference'
856
///                   '__is_lvalue_reference'
857
///                   '__is_rvalue_reference'
858
///                   '__is_fundamental'
859
///                   '__is_object'
860
///                   '__is_scalar'
861
///                   '__is_compound'
862
///                   '__is_pointer'
863
///                   '__is_member_object_pointer'
864
///                   '__is_member_function_pointer'
865
///                   '__is_member_pointer'
866
///                   '__is_const'
867
///                   '__is_volatile'
868
///                   '__is_trivial'
869
///                   '__is_standard_layout'
870
///                   '__is_signed'
871
///                   '__is_unsigned'
872
///
873
/// [GNU] unary-type-trait:
874
///                   '__has_nothrow_assign'
875
///                   '__has_nothrow_copy'
876
///                   '__has_nothrow_constructor'
877
///                   '__has_trivial_assign'                  [TODO]
878
///                   '__has_trivial_copy'                    [TODO]
879
///                   '__has_trivial_constructor'
880
///                   '__has_trivial_destructor'
881
///                   '__has_virtual_destructor'
882
///                   '__is_abstract'                         [TODO]
883
///                   '__is_class'
884
///                   '__is_empty'                            [TODO]
885
///                   '__is_enum'
886
///                   '__is_final'
887
///                   '__is_pod'
888
///                   '__is_polymorphic'
889
///                   '__is_sealed'                           [MS]
890
///                   '__is_trivial'
891
///                   '__is_union'
892
///                   '__has_unique_object_representations'
893
///
894
/// [Clang] unary-type-trait:
895
///                   '__is_aggregate'
896
///                   '__trivially_copyable'
897
///
898
///       binary-type-trait:
899
/// [GNU]             '__is_base_of'
900
/// [MS]              '__is_convertible_to'
901
///                   '__is_convertible'
902
///                   '__is_same'
903
///
904
/// [Embarcadero] array-type-trait:
905
///                   '__array_rank'
906
///                   '__array_extent'
907
///
908
/// [Embarcadero] expression-trait:
909
///                   '__is_lvalue_expr'
910
///                   '__is_rvalue_expr'
911
/// \endverbatim
912
///
913
ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
914
                                       bool isAddressOfOperand,
915
                                       bool &NotCastExpr,
916
                                       TypeCastState isTypeCast,
917
                                       bool isVectorLiteral,
918
37.8M
                                       bool *NotPrimaryExpression) {
919
37.8M
  ExprResult Res;
920
37.8M
  tok::TokenKind SavedKind = Tok.getKind();
921
37.8M
  auto SavedType = PreferredType;
922
37.8M
  NotCastExpr = false;
923
924
  // Are postfix-expression suffix operators permitted after this
925
  // cast-expression? If not, and we find some, we'll parse them anyway and
926
  // diagnose them.
927
37.8M
  bool AllowSuffix = true;
928
929
  // This handles all of cast-expression, unary-expression, postfix-expression,
930
  // and primary-expression.  We handle them together like this for efficiency
931
  // and to simplify handling of an expression starting with a '(' token: which
932
  // may be one of a parenthesized expression, cast-expression, compound literal
933
  // expression, or statement expression.
934
  //
935
  // If the parsed tokens consist of a primary-expression, the cases below
936
  // break out of the switch;  at the end we call ParsePostfixExpressionSuffix
937
  // to handle the postfix expression suffixes.  Cases that cannot be followed
938
  // by postfix exprs should set AllowSuffix to false.
939
37.8M
  switch (SavedKind) {
940
5.71M
  case tok::l_paren: {
941
    // If this expression is limited to being a unary-expression, the paren can
942
    // not start a cast expression.
943
5.71M
    ParenParseOption ParenExprType;
944
5.71M
    switch (ParseKind) {
945
2.78k
      case CastParseKind::UnaryExprOnly:
946
2.78k
        if (!getLangOpts().CPlusPlus)
947
0
          ParenExprType = CompoundLiteral;
948
2.78k
        LLVM_FALLTHROUGH;
949
5.71M
      case CastParseKind::AnyCastExpr:
950
5.71M
        ParenExprType = ParenParseOption::CastExpr;
951
5.71M
        break;
952
149
      case CastParseKind::PrimaryExprOnly:
953
149
        ParenExprType = FoldExpr;
954
149
        break;
955
5.71M
    }
956
5.71M
    ParsedType CastTy;
957
5.71M
    SourceLocation RParenLoc;
958
5.71M
    Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
959
5.71M
                               isTypeCast == IsTypeCast, CastTy, RParenLoc);
960
961
    // FIXME: What should we do if a vector literal is followed by a
962
    // postfix-expression suffix? Usually postfix operators are permitted on
963
    // literals.
964
5.71M
    if (isVectorLiteral)
965
167
      return Res;
966
967
5.71M
    switch (ParenExprType) {
968
1.01M
    case SimpleExpr:   break;    // Nothing else to do.
969
8.94k
    case CompoundStmt: break;  // Nothing else to do.
970
53.3k
    case CompoundLiteral:
971
      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
972
      // postfix-expression exist, parse them now.
973
53.3k
      break;
974
4.63M
    case CastExpr:
975
      // We have parsed the cast-expression and no postfix-expr pieces are
976
      // following.
977
4.63M
      return Res;
978
241
    case FoldExpr:
979
      // We only parsed a fold-expression. There might be postfix-expr pieces
980
      // afterwards; parse them now.
981
241
      break;
982
5.71M
    }
983
984
1.07M
    break;
985
5.71M
  }
986
987
    // primary-expression
988
7.70M
  case tok::numeric_constant:
989
    // constant: integer-constant
990
    // constant: floating-constant
991
992
7.70M
    Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
993
7.70M
    ConsumeToken();
994
7.70M
    break;
995
996
135k
  case tok::kw_true:
997
260k
  case tok::kw_false:
998
260k
    Res = ParseCXXBoolLiteral();
999
260k
    break;
1000
1001
518
  case tok::kw___objc_yes:
1002
923
  case tok::kw___objc_no:
1003
923
    Res = ParseObjCBoolLiteral();
1004
923
    break;
1005
1006
100k
  case tok::kw_nullptr:
1007
100k
    Diag(Tok, diag::warn_cxx98_compat_nullptr);
1008
100k
    Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
1009
100k
    break;
1010
1011
16
  case tok::annot_primary_expr:
1012
668k
  case tok::annot_overload_set:
1013
668k
    Res = getExprAnnotation(Tok);
1014
668k
    if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1015
668k
      Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1016
668k
    ConsumeAnnotationToken();
1017
668k
    if (!Res.isInvalid() && 
Tok.is(tok::less)668k
)
1018
22
      checkPotentialAngleBracket(Res);
1019
668k
    break;
1020
1021
1.75M
  case tok::annot_non_type:
1022
1.75M
  case tok::annot_non_type_dependent:
1023
1.76M
  case tok::annot_non_type_undeclared: {
1024
1.76M
    CXXScopeSpec SS;
1025
1.76M
    Token Replacement;
1026
1.76M
    Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1027
1.76M
    assert(!Res.isUnset() &&
1028
1.76M
           "should not perform typo correction on annotation token");
1029
0
    break;
1030
1.75M
  }
1031
1032
3
  case tok::kw___super:
1033
370
  case tok::kw_decltype:
1034
    // Annotate the token and tail recurse.
1035
370
    if (TryAnnotateTypeOrScopeToken())
1036
0
      return ExprError();
1037
370
    assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1038
0
    return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1039
370
                               isVectorLiteral, NotPrimaryExpression);
1040
1041
13.8M
  case tok::identifier: {      // primary-expression: identifier
1042
                               // unqualified-id: identifier
1043
                               // constant: enumeration-constant
1044
    // Turn a potentially qualified name into a annot_typename or
1045
    // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
1046
13.8M
    if (getLangOpts().CPlusPlus) {
1047
      // Avoid the unnecessary parse-time lookup in the common case
1048
      // where the syntax forbids a type.
1049
6.66M
      const Token &Next = NextToken();
1050
1051
      // If this identifier was reverted from a token ID, and the next token
1052
      // is a parenthesis, this is likely to be a use of a type trait. Check
1053
      // those tokens.
1054
6.66M
      if (Next.is(tok::l_paren) &&
1055
6.66M
          
Tok.is(tok::identifier)1.01M
&&
1056
6.66M
          
Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()1.01M
) {
1057
104
        IdentifierInfo *II = Tok.getIdentifierInfo();
1058
        // Build up the mapping of revertible type traits, for future use.
1059
104
        if (RevertibleTypeTraits.empty()) {
1060
153
#define RTT_JOIN(X,Y) X##Y
1061
3
#define REVERTIBLE_TYPE_TRAIT(Name)                         \
1062
153
          RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
1063
153
            = RTT_JOIN(tok::kw_,Name)
1064
1065
3
          REVERTIBLE_TYPE_TRAIT(__is_abstract);
1066
3
          REVERTIBLE_TYPE_TRAIT(__is_aggregate);
1067
3
          REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
1068
3
          REVERTIBLE_TYPE_TRAIT(__is_array);
1069
3
          REVERTIBLE_TYPE_TRAIT(__is_assignable);
1070
3
          REVERTIBLE_TYPE_TRAIT(__is_base_of);
1071
3
          REVERTIBLE_TYPE_TRAIT(__is_class);
1072
3
          REVERTIBLE_TYPE_TRAIT(__is_complete_type);
1073
3
          REVERTIBLE_TYPE_TRAIT(__is_compound);
1074
3
          REVERTIBLE_TYPE_TRAIT(__is_const);
1075
3
          REVERTIBLE_TYPE_TRAIT(__is_constructible);
1076
3
          REVERTIBLE_TYPE_TRAIT(__is_convertible);
1077
3
          REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
1078
3
          REVERTIBLE_TYPE_TRAIT(__is_destructible);
1079
3
          REVERTIBLE_TYPE_TRAIT(__is_empty);
1080
3
          REVERTIBLE_TYPE_TRAIT(__is_enum);
1081
3
          REVERTIBLE_TYPE_TRAIT(__is_floating_point);
1082
3
          REVERTIBLE_TYPE_TRAIT(__is_final);
1083
3
          REVERTIBLE_TYPE_TRAIT(__is_function);
1084
3
          REVERTIBLE_TYPE_TRAIT(__is_fundamental);
1085
3
          REVERTIBLE_TYPE_TRAIT(__is_integral);
1086
3
          REVERTIBLE_TYPE_TRAIT(__is_interface_class);
1087
3
          REVERTIBLE_TYPE_TRAIT(__is_literal);
1088
3
          REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
1089
3
          REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
1090
3
          REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
1091
3
          REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
1092
3
          REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
1093
3
          REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
1094
3
          REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
1095
3
          REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
1096
3
          REVERTIBLE_TYPE_TRAIT(__is_object);
1097
3
          REVERTIBLE_TYPE_TRAIT(__is_pod);
1098
3
          REVERTIBLE_TYPE_TRAIT(__is_pointer);
1099
3
          REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
1100
3
          REVERTIBLE_TYPE_TRAIT(__is_reference);
1101
3
          REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
1102
3
          REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
1103
3
          REVERTIBLE_TYPE_TRAIT(__is_same);
1104
3
          REVERTIBLE_TYPE_TRAIT(__is_scalar);
1105
3
          REVERTIBLE_TYPE_TRAIT(__is_sealed);
1106
3
          REVERTIBLE_TYPE_TRAIT(__is_signed);
1107
3
          REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
1108
3
          REVERTIBLE_TYPE_TRAIT(__is_trivial);
1109
3
          REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
1110
3
          REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
1111
3
          REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
1112
3
          REVERTIBLE_TYPE_TRAIT(__is_union);
1113
3
          REVERTIBLE_TYPE_TRAIT(__is_unsigned);
1114
3
          REVERTIBLE_TYPE_TRAIT(__is_void);
1115
3
          REVERTIBLE_TYPE_TRAIT(__is_volatile);
1116
3
#undef REVERTIBLE_TYPE_TRAIT
1117
3
#undef RTT_JOIN
1118
3
        }
1119
1120
        // If we find that this is in fact the name of a type trait,
1121
        // update the token kind in place and parse again to treat it as
1122
        // the appropriate kind of type trait.
1123
104
        llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
1124
104
          = RevertibleTypeTraits.find(II);
1125
104
        if (Known != RevertibleTypeTraits.end()) {
1126
104
          Tok.setKind(Known->second);
1127
104
          return ParseCastExpression(ParseKind, isAddressOfOperand,
1128
104
                                     NotCastExpr, isTypeCast,
1129
104
                                     isVectorLiteral, NotPrimaryExpression);
1130
104
        }
1131
104
      }
1132
1133
6.66M
      if ((!ColonIsSacred && 
Next.is(tok::colon)6.38M
) ||
1134
6.66M
          Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1135
6.66M
                       tok::l_brace)) {
1136
        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1137
1.99M
        if (TryAnnotateTypeOrScopeToken())
1138
9
          return ExprError();
1139
1.99M
        if (!Tok.is(tok::identifier))
1140
988k
          return ParseCastExpression(ParseKind, isAddressOfOperand,
1141
988k
                                     NotCastExpr, isTypeCast,
1142
988k
                                     isVectorLiteral,
1143
988k
                                     NotPrimaryExpression);
1144
1.99M
      }
1145
6.66M
    }
1146
1147
    // Consume the identifier so that we can see if it is followed by a '(' or
1148
    // '.'.
1149
12.9M
    IdentifierInfo &II = *Tok.getIdentifierInfo();
1150
12.9M
    SourceLocation ILoc = ConsumeToken();
1151
1152
    // Support 'Class.property' and 'super.property' notation.
1153
12.9M
    if (getLangOpts().ObjC && 
Tok.is(tok::period)1.25M
&&
1154
12.9M
        
(33.9k
Actions.getTypeName(II, ILoc, getCurScope())33.9k
||
1155
         // Allow the base to be 'super' if in an objc-method.
1156
33.9k
         
(33.7k
&II == Ident_super33.7k
&&
getCurScope()->isInObjcMethodScope()79
))) {
1157
274
      ConsumeToken();
1158
1159
274
      if (Tok.is(tok::code_completion) && 
&II != Ident_super4
) {
1160
3
        cutOffParsing();
1161
3
        Actions.CodeCompleteObjCClassPropertyRefExpr(
1162
3
            getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1163
3
        return ExprError();
1164
3
      }
1165
      // Allow either an identifier or the keyword 'class' (in C++).
1166
271
      if (Tok.isNot(tok::identifier) &&
1167
271
          
!(2
getLangOpts().CPlusPlus2
&&
Tok.is(tok::kw_class)1
)) {
1168
1
        Diag(Tok, diag::err_expected_property_name);
1169
1
        return ExprError();
1170
1
      }
1171
270
      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1172
270
      SourceLocation PropertyLoc = ConsumeToken();
1173
1174
270
      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
1175
270
                                              ILoc, PropertyLoc);
1176
270
      break;
1177
271
    }
1178
1179
    // In an Objective-C method, if we have "super" followed by an identifier,
1180
    // the token sequence is ill-formed. However, if there's a ':' or ']' after
1181
    // that identifier, this is probably a message send with a missing open
1182
    // bracket. Treat it as such.
1183
12.9M
    if (getLangOpts().ObjC && 
&II == Ident_super1.25M
&&
!InMessageExpression256
&&
1184
12.9M
        
getCurScope()->isInObjcMethodScope()34
&&
1185
12.9M
        
(31
(31
Tok.is(tok::identifier)31
&&
1186
31
         
(28
NextToken().is(tok::colon)28
||
NextToken().is(tok::r_square)2
)) ||
1187
31
         
Tok.is(tok::code_completion)3
)) {
1188
29
      Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1189
29
                                           nullptr);
1190
29
      break;
1191
29
    }
1192
1193
    // If we have an Objective-C class name followed by an identifier
1194
    // and either ':' or ']', this is an Objective-C class message
1195
    // send that's missing the opening '['. Recovery
1196
    // appropriately. Also take this path if we're performing code
1197
    // completion after an Objective-C class name.
1198
12.9M
    if (getLangOpts().ObjC &&
1199
12.9M
        
(1.25M
(1.25M
Tok.is(tok::identifier)1.25M
&&
!InMessageExpression11.5k
) ||
1200
1.25M
         
Tok.is(tok::code_completion)1.25M
)) {
1201
161
      const Token& Next = NextToken();
1202
161
      if (Tok.is(tok::code_completion) ||
1203
161
          
Next.is(tok::colon)118
||
Next.is(tok::r_square)115
)
1204
119
        if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1205
74
          if (Typ.get()->isObjCObjectOrInterfaceType()) {
1206
            // Fake up a Declarator to use with ActOnTypeName.
1207
74
            DeclSpec DS(AttrFactory);
1208
74
            DS.SetRangeStart(ILoc);
1209
74
            DS.SetRangeEnd(ILoc);
1210
74
            const char *PrevSpec = nullptr;
1211
74
            unsigned DiagID;
1212
74
            DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1213
74
                               Actions.getASTContext().getPrintingPolicy());
1214
1215
74
            Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1216
74
            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1217
74
                                                  DeclaratorInfo);
1218
74
            if (Ty.isInvalid())
1219
0
              break;
1220
1221
74
            Res = ParseObjCMessageExpressionBody(SourceLocation(),
1222
74
                                                 SourceLocation(),
1223
74
                                                 Ty.get(), nullptr);
1224
74
            break;
1225
74
          }
1226
161
    }
1227
1228
    // Make sure to pass down the right value for isAddressOfOperand.
1229
12.9M
    if (isAddressOfOperand && 
isPostfixExpressionSuffixStart()103k
)
1230
26.1k
      isAddressOfOperand = false;
1231
1232
    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1233
    // need to know whether or not this identifier is a function designator or
1234
    // not.
1235
12.9M
    UnqualifiedId Name;
1236
12.9M
    CXXScopeSpec ScopeSpec;
1237
12.9M
    SourceLocation TemplateKWLoc;
1238
12.9M
    Token Replacement;
1239
12.9M
    CastExpressionIdValidator Validator(
1240
12.9M
        /*Next=*/Tok,
1241
12.9M
        /*AllowTypes=*/isTypeCast != NotTypeCast,
1242
12.9M
        /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1243
12.9M
    Validator.IsAddressOfOperand = isAddressOfOperand;
1244
12.9M
    if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1245
126
      Validator.WantExpressionKeywords = false;
1246
126
      Validator.WantRemainingKeywords = false;
1247
12.9M
    } else {
1248
12.9M
      Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1249
12.9M
    }
1250
12.9M
    Name.setIdentifier(&II, ILoc);
1251
12.9M
    Res = Actions.ActOnIdExpression(
1252
12.9M
        getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1253
12.9M
        isAddressOfOperand, &Validator,
1254
12.9M
        /*IsInlineAsmIdentifier=*/false,
1255
12.9M
        Tok.is(tok::r_paren) ? 
nullptr3.20M
:
&Replacement9.69M
);
1256
12.9M
    if (!Res.isInvalid() && 
Res.isUnset()12.8M
) {
1257
2
      UnconsumeToken(Replacement);
1258
2
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1259
2
                                 NotCastExpr, isTypeCast,
1260
2
                                 /*isVectorLiteral=*/false,
1261
2
                                 NotPrimaryExpression);
1262
2
    }
1263
12.9M
    if (!Res.isInvalid() && 
Tok.is(tok::less)12.8M
)
1264
191k
      checkPotentialAngleBracket(Res);
1265
12.9M
    break;
1266
12.9M
  }
1267
565k
  case tok::char_constant:     // constant: character-constant
1268
566k
  case tok::wide_char_constant:
1269
566k
  case tok::utf8_char_constant:
1270
566k
  case tok::utf16_char_constant:
1271
567k
  case tok::utf32_char_constant:
1272
567k
    Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1273
567k
    ConsumeToken();
1274
567k
    break;
1275
370
  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
1276
567
  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
1277
576
  case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
1278
589
  case tok::kw___FUNCSIG__:     // primary-expression: __FUNCSIG__ [MS]
1279
597
  case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
1280
603
  case tok::kw_L__FUNCSIG__:    // primary-expression: L__FUNCSIG__ [MS]
1281
822
  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
1282
822
    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1283
822
    ConsumeToken();
1284
822
    break;
1285
3.07M
  case tok::string_literal:    // primary-expression: string-literal
1286
3.08M
  case tok::wide_string_literal:
1287
3.08M
  case tok::utf8_string_literal:
1288
3.08M
  case tok::utf16_string_literal:
1289
3.08M
  case tok::utf32_string_literal:
1290
3.08M
    Res = ParseStringLiteralExpression(true);
1291
3.08M
    break;
1292
215
  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
1293
215
    Res = ParseGenericSelectionExpression();
1294
215
    break;
1295
16
  case tok::kw___builtin_available:
1296
16
    Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1297
16
    break;
1298
1.09k
  case tok::kw___builtin_va_arg:
1299
1.44k
  case tok::kw___builtin_offsetof:
1300
1.51k
  case tok::kw___builtin_choose_expr:
1301
1.55k
  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1302
23.2k
  case tok::kw___builtin_convertvector:
1303
23.2k
  case tok::kw___builtin_COLUMN:
1304
23.2k
  case tok::kw___builtin_FILE:
1305
23.2k
  case tok::kw___builtin_FUNCTION:
1306
23.3k
  case tok::kw___builtin_LINE:
1307
23.3k
  case tok::kw___builtin_source_location:
1308
23.3k
    if (NotPrimaryExpression)
1309
0
      *NotPrimaryExpression = true;
1310
    // This parses the complete suffix; we can return early.
1311
23.3k
    return ParseBuiltinPrimaryExpression();
1312
4.67k
  case tok::kw___null:
1313
4.67k
    Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1314
4.67k
    break;
1315
1316
202k
  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
1317
236k
  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
1318
236k
    if (NotPrimaryExpression)
1319
0
      *NotPrimaryExpression = true;
1320
    // C++ [expr.unary] has:
1321
    //   unary-expression:
1322
    //     ++ cast-expression
1323
    //     -- cast-expression
1324
236k
    Token SavedTok = Tok;
1325
236k
    ConsumeToken();
1326
1327
236k
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1328
236k
                             SavedTok.getLocation());
1329
    // One special case is implicitly handled here: if the preceding tokens are
1330
    // an ambiguous cast expression, such as "(T())++", then we recurse to
1331
    // determine whether the '++' is prefix or postfix.
1332
236k
    Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1333
226k
                                  UnaryExprOnly : 
AnyCastExpr9.54k
,
1334
236k
                              /*isAddressOfOperand*/false, NotCastExpr,
1335
236k
                              NotTypeCast);
1336
236k
    if (NotCastExpr) {
1337
      // If we return with NotCastExpr = true, we must not consume any tokens,
1338
      // so put the token back where we found it.
1339
7
      assert(Res.isInvalid());
1340
0
      UnconsumeToken(SavedTok);
1341
7
      return ExprError();
1342
7
    }
1343
236k
    if (!Res.isInvalid()) {
1344
236k
      Expr *Arg = Res.get();
1345
236k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1346
236k
                                 SavedKind, Arg);
1347
236k
      if (Res.isInvalid())
1348
72
        Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1349
72
                                         Arg->getEndLoc(), Arg);
1350
236k
    }
1351
236k
    return Res;
1352
236k
  }
1353
115k
  case tok::amp: {         // unary-expression: '&' cast-expression
1354
115k
    if (NotPrimaryExpression)
1355
0
      *NotPrimaryExpression = true;
1356
    // Special treatment because of member pointers
1357
115k
    SourceLocation SavedLoc = ConsumeToken();
1358
115k
    PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1359
115k
    Res = ParseCastExpression(AnyCastExpr, true);
1360
115k
    if (!Res.isInvalid()) {
1361
115k
      Expr *Arg = Res.get();
1362
115k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1363
115k
      if (Res.isInvalid())
1364
213
        Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1365
213
                                         Arg);
1366
115k
    }
1367
115k
    return Res;
1368
236k
  }
1369
1370
342k
  case tok::star:          // unary-expression: '*' cast-expression
1371
343k
  case tok::plus:          // unary-expression: '+' cast-expression
1372
1.30M
  case tok::minus:         // unary-expression: '-' cast-expression
1373
1.36M
  case tok::tilde:         // unary-expression: '~' cast-expression
1374
1.51M
  case tok::exclaim:       // unary-expression: '!' cast-expression
1375
1.51M
  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
1376
1.51M
  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
1377
1.51M
    if (NotPrimaryExpression)
1378
0
      *NotPrimaryExpression = true;
1379
1.51M
    SourceLocation SavedLoc = ConsumeToken();
1380
1.51M
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1381
1.51M
    Res = ParseCastExpression(AnyCastExpr);
1382
1.51M
    if (!Res.isInvalid()) {
1383
1.51M
      Expr *Arg = Res.get();
1384
1.51M
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1385
1.51M
      if (Res.isInvalid())
1386
190
        Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1387
1.51M
    }
1388
1.51M
    return Res;
1389
1.51M
  }
1390
1391
472
  case tok::kw_co_await: {  // unary-expression: 'co_await' cast-expression
1392
472
    if (NotPrimaryExpression)
1393
0
      *NotPrimaryExpression = true;
1394
472
    SourceLocation CoawaitLoc = ConsumeToken();
1395
472
    Res = ParseCastExpression(AnyCastExpr);
1396
472
    if (!Res.isInvalid())
1397
472
      Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1398
472
    return Res;
1399
1.51M
  }
1400
1401
32.4k
  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1402
    // __extension__ silences extension warnings in the subexpression.
1403
32.4k
    if (NotPrimaryExpression)
1404
0
      *NotPrimaryExpression = true;
1405
32.4k
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1406
32.4k
    SourceLocation SavedLoc = ConsumeToken();
1407
32.4k
    Res = ParseCastExpression(AnyCastExpr);
1408
32.4k
    if (!Res.isInvalid())
1409
32.4k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1410
32.4k
    return Res;
1411
1.51M
  }
1412
133
  case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
1413
133
    if (!getLangOpts().C11)
1414
67
      Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1415
133
    LLVM_FALLTHROUGH;
1416
5.71k
  case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
1417
8.75k
  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
1418
                           // unary-expression: '__alignof' '(' type-name ')'
1419
126k
  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
1420
                           // unary-expression: 'sizeof' '(' type-name ')'
1421
126k
  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
1422
  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1423
127k
  case tok::kw___builtin_omp_required_simd_align:
1424
127k
    if (NotPrimaryExpression)
1425
4
      *NotPrimaryExpression = true;
1426
127k
    AllowSuffix = false;
1427
127k
    Res = ParseUnaryExprOrTypeTraitExpression();
1428
127k
    break;
1429
321
  case tok::ampamp: {      // unary-expression: '&&' identifier
1430
321
    if (NotPrimaryExpression)
1431
0
      *NotPrimaryExpression = true;
1432
321
    SourceLocation AmpAmpLoc = ConsumeToken();
1433
321
    if (Tok.isNot(tok::identifier))
1434
0
      return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1435
1436
321
    if (getCurScope()->getFnParent() == nullptr)
1437
1
      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1438
1439
320
    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1440
320
    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1441
320
                                                Tok.getLocation());
1442
320
    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1443
320
    ConsumeToken();
1444
320
    AllowSuffix = false;
1445
320
    break;
1446
321
  }
1447
5.40k
  case tok::kw_const_cast:
1448
6.70k
  case tok::kw_dynamic_cast:
1449
12.9k
  case tok::kw_reinterpret_cast:
1450
163k
  case tok::kw_static_cast:
1451
163k
  case tok::kw_addrspace_cast:
1452
163k
    if (NotPrimaryExpression)
1453
0
      *NotPrimaryExpression = true;
1454
163k
    Res = ParseCXXCasts();
1455
163k
    break;
1456
697
  case tok::kw___builtin_bit_cast:
1457
697
    if (NotPrimaryExpression)
1458
0
      *NotPrimaryExpression = true;
1459
697
    Res = ParseBuiltinBitCast();
1460
697
    break;
1461
1.92k
  case tok::kw_typeid:
1462
1.92k
    if (NotPrimaryExpression)
1463
0
      *NotPrimaryExpression = true;
1464
1.92k
    Res = ParseCXXTypeid();
1465
1.92k
    break;
1466
178
  case tok::kw___uuidof:
1467
178
    if (NotPrimaryExpression)
1468
0
      *NotPrimaryExpression = true;
1469
178
    Res = ParseCXXUuidof();
1470
178
    break;
1471
217k
  case tok::kw_this:
1472
217k
    Res = ParseCXXThis();
1473
217k
    break;
1474
74
  case tok::kw___builtin_sycl_unique_stable_name:
1475
74
    Res = ParseSYCLUniqueStableNameExpression();
1476
74
    break;
1477
1478
260k
  case tok::annot_typename:
1479
260k
    if (isStartOfObjCClassMessageMissingOpenBracket()) {
1480
81
      TypeResult Type = getTypeAnnotation(Tok);
1481
1482
      // Fake up a Declarator to use with ActOnTypeName.
1483
81
      DeclSpec DS(AttrFactory);
1484
81
      DS.SetRangeStart(Tok.getLocation());
1485
81
      DS.SetRangeEnd(Tok.getLastLoc());
1486
1487
81
      const char *PrevSpec = nullptr;
1488
81
      unsigned DiagID;
1489
81
      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1490
81
                         PrevSpec, DiagID, Type,
1491
81
                         Actions.getASTContext().getPrintingPolicy());
1492
1493
81
      Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
1494
81
      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1495
81
      if (Ty.isInvalid())
1496
0
        break;
1497
1498
81
      ConsumeAnnotationToken();
1499
81
      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1500
81
                                           Ty.get(), nullptr);
1501
81
      break;
1502
81
    }
1503
260k
    
LLVM_FALLTHROUGH260k
;260k
1504
1505
260k
  case tok::annot_decltype:
1506
260k
  case tok::kw_char:
1507
260k
  case tok::kw_wchar_t:
1508
260k
  case tok::kw_char8_t:
1509
260k
  case tok::kw_char16_t:
1510
260k
  case tok::kw_char32_t:
1511
264k
  case tok::kw_bool:
1512
264k
  case tok::kw_short:
1513
265k
  case tok::kw_int:
1514
265k
  case tok::kw_long:
1515
265k
  case tok::kw___int64:
1516
265k
  case tok::kw___int128:
1517
265k
  case tok::kw__ExtInt:
1518
265k
  case tok::kw__BitInt:
1519
265k
  case tok::kw_signed:
1520
265k
  case tok::kw_unsigned:
1521
265k
  case tok::kw_half:
1522
265k
  case tok::kw_float:
1523
265k
  case tok::kw_double:
1524
265k
  case tok::kw___bf16:
1525
265k
  case tok::kw__Float16:
1526
265k
  case tok::kw___float128:
1527
265k
  case tok::kw___ibm128:
1528
267k
  case tok::kw_void:
1529
267k
  case tok::kw_auto:
1530
290k
  case tok::kw_typename:
1531
290k
  case tok::kw_typeof:
1532
290k
  case tok::kw___vector:
1533
3.49M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1534
3.49M
#include 
"clang/Basic/OpenCLImageTypes.def"290k
1535
3.49M
  {
1536
3.49M
    if (
!getLangOpts().CPlusPlus290k
) {
1537
295
      Diag(Tok, diag::err_expected_expression);
1538
295
      return ExprError();
1539
295
    }
1540
1541
    // Everything henceforth is a postfix-expression.
1542
290k
    if (NotPrimaryExpression)
1543
4
      *NotPrimaryExpression = true;
1544
1545
290k
    if (SavedKind == tok::kw_typename) {
1546
      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1547
      //                     typename-specifier braced-init-list
1548
23.2k
      if (TryAnnotateTypeOrScopeToken())
1549
7
        return ExprError();
1550
1551
23.2k
      if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1552
        // We are trying to parse a simple-type-specifier but might not get such
1553
        // a token after error recovery.
1554
0
        return ExprError();
1555
23.2k
    }
1556
1557
    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1558
    //                     simple-type-specifier braced-init-list
1559
    //
1560
290k
    DeclSpec DS(AttrFactory);
1561
1562
290k
    ParseCXXSimpleTypeSpecifier(DS);
1563
290k
    if (Tok.isNot(tok::l_paren) &&
1564
290k
        
(7.38k
!getLangOpts().CPlusPlus117.38k
||
Tok.isNot(tok::l_brace)7.36k
))
1565
53
      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1566
53
                         << DS.getSourceRange());
1567
1568
290k
    if (Tok.is(tok::l_brace))
1569
7.32k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1570
1571
290k
    Res = ParseCXXTypeConstructExpression(DS);
1572
290k
    break;
1573
290k
  }
1574
1575
1.05M
  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1576
    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1577
    // (We can end up in this situation after tentative parsing.)
1578
1.05M
    if (TryAnnotateTypeOrScopeToken())
1579
0
      return ExprError();
1580
1.05M
    if (!Tok.is(tok::annot_cxxscope))
1581
4
      return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1582
4
                                 isTypeCast, isVectorLiteral,
1583
4
                                 NotPrimaryExpression);
1584
1585
1.05M
    Token Next = NextToken();
1586
1.05M
    if (Next.is(tok::annot_template_id)) {
1587
84.5k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1588
84.5k
      if (TemplateId->Kind == TNK_Type_template) {
1589
        // We have a qualified template-id that we know refers to a
1590
        // type, translate it into a type and continue parsing as a
1591
        // cast expression.
1592
0
        CXXScopeSpec SS;
1593
0
        ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1594
0
                                       /*ObjectHasErrors=*/false,
1595
0
                                       /*EnteringContext=*/false);
1596
0
        AnnotateTemplateIdTokenAsType(SS);
1597
0
        return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1598
0
                                   isTypeCast, isVectorLiteral,
1599
0
                                   NotPrimaryExpression);
1600
0
      }
1601
84.5k
    }
1602
1603
    // Parse as an id-expression.
1604
1.05M
    Res = ParseCXXIdExpression(isAddressOfOperand);
1605
1.05M
    break;
1606
1.05M
  }
1607
1608
88.6k
  case tok::annot_template_id: { // [C++]          template-id
1609
88.6k
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1610
88.6k
    if (TemplateId->Kind == TNK_Type_template) {
1611
      // We have a template-id that we know refers to a type,
1612
      // translate it into a type and continue parsing as a cast
1613
      // expression.
1614
49
      CXXScopeSpec SS;
1615
49
      AnnotateTemplateIdTokenAsType(SS);
1616
49
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1617
49
                                 NotCastExpr, isTypeCast, isVectorLiteral,
1618
49
                                 NotPrimaryExpression);
1619
49
    }
1620
1621
    // Fall through to treat the template-id as an id-expression.
1622
88.6k
    
LLVM_FALLTHROUGH88.6k
;
1623
88.6k
  }
1624
1625
90.7k
  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1626
90.7k
    Res = ParseCXXIdExpression(isAddressOfOperand);
1627
90.7k
    break;
1628
1629
77.6k
  case tok::coloncolon: {
1630
    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1631
    // annotates the token, tail recurse.
1632
77.6k
    if (TryAnnotateTypeOrScopeToken())
1633
4
      return ExprError();
1634
77.6k
    if (!Tok.is(tok::coloncolon))
1635
70.1k
      return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1636
70.1k
                                 isVectorLiteral, NotPrimaryExpression);
1637
1638
    // ::new -> [C++] new-expression
1639
    // ::delete -> [C++] delete-expression
1640
7.53k
    SourceLocation CCLoc = ConsumeToken();
1641
7.53k
    if (Tok.is(tok::kw_new)) {
1642
7.48k
      if (NotPrimaryExpression)
1643
0
        *NotPrimaryExpression = true;
1644
7.48k
      Res = ParseCXXNewExpression(true, CCLoc);
1645
7.48k
      AllowSuffix = false;
1646
7.48k
      break;
1647
7.48k
    }
1648
52
    if (Tok.is(tok::kw_delete)) {
1649
52
      if (NotPrimaryExpression)
1650
0
        *NotPrimaryExpression = true;
1651
52
      Res = ParseCXXDeleteExpression(true, CCLoc);
1652
52
      AllowSuffix = false;
1653
52
      break;
1654
52
    }
1655
1656
    // This is not a type name or scope specifier, it is an invalid expression.
1657
0
    Diag(CCLoc, diag::err_expected_expression);
1658
0
    return ExprError();
1659
52
  }
1660
1661
9.31k
  case tok::kw_new: // [C++] new-expression
1662
9.31k
    if (NotPrimaryExpression)
1663
0
      *NotPrimaryExpression = true;
1664
9.31k
    Res = ParseCXXNewExpression(false, Tok.getLocation());
1665
9.31k
    AllowSuffix = false;
1666
9.31k
    break;
1667
1668
5.31k
  case tok::kw_delete: // [C++] delete-expression
1669
5.31k
    if (NotPrimaryExpression)
1670
0
      *NotPrimaryExpression = true;
1671
5.31k
    Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1672
5.31k
    AllowSuffix = false;
1673
5.31k
    break;
1674
1675
256
  case tok::kw_requires: // [C++2a] requires-expression
1676
256
    Res = ParseRequiresExpression();
1677
256
    AllowSuffix = false;
1678
256
    break;
1679
1680
8.38k
  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1681
8.38k
    if (NotPrimaryExpression)
1682
0
      *NotPrimaryExpression = true;
1683
8.38k
    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1684
8.38k
    SourceLocation KeyLoc = ConsumeToken();
1685
8.38k
    BalancedDelimiterTracker T(*this, tok::l_paren);
1686
1687
8.38k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1688
0
      return ExprError();
1689
    // C++11 [expr.unary.noexcept]p1:
1690
    //   The noexcept operator determines whether the evaluation of its operand,
1691
    //   which is an unevaluated operand, can throw an exception.
1692
8.38k
    EnterExpressionEvaluationContext Unevaluated(
1693
8.38k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1694
8.38k
    Res = ParseExpression();
1695
1696
8.38k
    T.consumeClose();
1697
1698
8.38k
    if (!Res.isInvalid())
1699
8.37k
      Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1700
8.37k
                                      T.getCloseLocation());
1701
8.38k
    AllowSuffix = false;
1702
8.38k
    break;
1703
8.38k
  }
1704
1705
0
#define TYPE_TRAIT(N,Spelling,K) \
1706
759k
  case tok::kw_##Spelling:
1707
28.2k
#include 
"clang/Basic/TokenKinds.def"8.38k
1708
28.2k
    Res = ParseTypeTrait();
1709
28.2k
    break;
1710
1711
10
  case tok::kw___array_rank:
1712
509
  case tok::kw___array_extent:
1713
509
    if (NotPrimaryExpression)
1714
0
      *NotPrimaryExpression = true;
1715
509
    Res = ParseArrayTypeTrait();
1716
509
    break;
1717
1718
224
  case tok::kw___is_lvalue_expr:
1719
439
  case tok::kw___is_rvalue_expr:
1720
439
    if (NotPrimaryExpression)
1721
0
      *NotPrimaryExpression = true;
1722
439
    Res = ParseExpressionTrait();
1723
439
    break;
1724
1725
8.46k
  case tok::at: {
1726
8.46k
    if (NotPrimaryExpression)
1727
0
      *NotPrimaryExpression = true;
1728
8.46k
    SourceLocation AtLoc = ConsumeToken();
1729
8.46k
    return ParseObjCAtExpression(AtLoc);
1730
224
  }
1731
3.33k
  case tok::caret:
1732
3.33k
    Res = ParseBlockLiteralExpression();
1733
3.33k
    break;
1734
98
  case tok::code_completion: {
1735
98
    cutOffParsing();
1736
98
    Actions.CodeCompleteExpression(getCurScope(),
1737
98
                                   PreferredType.get(Tok.getLocation()));
1738
98
    return ExprError();
1739
224
  }
1740
30.9k
  case tok::l_square:
1741
30.9k
    if (getLangOpts().CPlusPlus11) {
1742
11.1k
      if (getLangOpts().ObjC) {
1743
        // C++11 lambda expressions and Objective-C message sends both start with a
1744
        // square bracket.  There are three possibilities here:
1745
        // we have a valid lambda expression, we have an invalid lambda
1746
        // expression, or we have something that doesn't appear to be a lambda.
1747
        // If we're in the last case, we fall back to ParseObjCMessageExpression.
1748
2.96k
        Res = TryParseLambdaExpression();
1749
2.96k
        if (!Res.isInvalid() && 
!Res.get()2.95k
) {
1750
          // We assume Objective-C++ message expressions are not
1751
          // primary-expressions.
1752
2.75k
          if (NotPrimaryExpression)
1753
0
            *NotPrimaryExpression = true;
1754
2.75k
          Res = ParseObjCMessageExpression();
1755
2.75k
        }
1756
2.96k
        break;
1757
2.96k
      }
1758
8.14k
      Res = ParseLambdaExpression();
1759
8.14k
      break;
1760
11.1k
    }
1761
19.8k
    if (getLangOpts().ObjC) {
1762
19.7k
      Res = ParseObjCMessageExpression();
1763
19.7k
      break;
1764
19.7k
    }
1765
19.8k
    
LLVM_FALLTHROUGH13
;13
1766
15.6k
  default:
1767
15.6k
    NotCastExpr = true;
1768
15.6k
    return ExprError();
1769
37.8M
  }
1770
1771
  // Check to see whether Res is a function designator only. If it is and we
1772
  // are compiling for OpenCL, we need to return an error as this implies
1773
  // that the address of the function is being taken, which is illegal in CL.
1774
1775
30.1M
  if (ParseKind == PrimaryExprOnly)
1776
    // This is strictly a primary-expression - no postfix-expr pieces should be
1777
    // parsed.
1778
535
    return Res;
1779
1780
30.1M
  if (!AllowSuffix) {
1781
    // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1782
    // error already.
1783
158k
    if (Res.isInvalid())
1784
752
      return Res;
1785
1786
157k
    switch (Tok.getKind()) {
1787
5
    case tok::l_square:
1788
6
    case tok::l_paren:
1789
6
    case tok::plusplus:
1790
6
    case tok::minusminus:
1791
      // "expected ';'" or similar is probably the right diagnostic here. Let
1792
      // the caller decide what to do.
1793
6
      if (Tok.isAtStartOfLine())
1794
1
        return Res;
1795
1796
6
      
LLVM_FALLTHROUGH5
;5
1797
5
    case tok::period:
1798
7
    case tok::arrow:
1799
7
      break;
1800
1801
157k
    default:
1802
157k
      return Res;
1803
157k
    }
1804
1805
    // This was a unary-expression for which a postfix-expression suffix is
1806
    // not permitted by the grammar (eg, a sizeof expression or
1807
    // new-expression or similar). Diagnose but parse the suffix anyway.
1808
7
    Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1809
7
        << Tok.getKind() << Res.get()->getSourceRange()
1810
7
        << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1811
7
        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1812
7
                                      ")");
1813
7
  }
1814
1815
  // These can be followed by postfix-expr pieces.
1816
30.0M
  PreferredType = SavedType;
1817
30.0M
  Res = ParsePostfixExpressionSuffix(Res);
1818
30.0M
  if (getLangOpts().OpenCL &&
1819
30.0M
      !getActions().getOpenCLOptions().isAvailableOption(
1820
87.7k
          "__cl_clang_function_pointers", getLangOpts()))
1821
87.7k
    if (Expr *PostfixExpr = Res.get()) {
1822
87.5k
      QualType Ty = PostfixExpr->getType();
1823
87.5k
      if (!Ty.isNull() && 
Ty->isFunctionType()87.3k
) {
1824
10
        Diag(PostfixExpr->getExprLoc(),
1825
10
             diag::err_opencl_taking_function_address_parser);
1826
10
        return ExprError();
1827
10
      }
1828
87.5k
    }
1829
1830
30.0M
  return Res;
1831
30.0M
}
1832
1833
/// Once the leading part of a postfix-expression is parsed, this
1834
/// method parses any suffixes that apply.
1835
///
1836
/// \verbatim
1837
///       postfix-expression: [C99 6.5.2]
1838
///         primary-expression
1839
///         postfix-expression '[' expression ']'
1840
///         postfix-expression '[' braced-init-list ']'
1841
///         postfix-expression '[' expression-list [opt] ']'  [C++2b 12.4.5]
1842
///         postfix-expression '(' argument-expression-list[opt] ')'
1843
///         postfix-expression '.' identifier
1844
///         postfix-expression '->' identifier
1845
///         postfix-expression '++'
1846
///         postfix-expression '--'
1847
///         '(' type-name ')' '{' initializer-list '}'
1848
///         '(' type-name ')' '{' initializer-list ',' '}'
1849
///
1850
///       argument-expression-list: [C99 6.5.2]
1851
///         argument-expression ...[opt]
1852
///         argument-expression-list ',' assignment-expression ...[opt]
1853
/// \endverbatim
1854
ExprResult
1855
30.0M
Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1856
  // Now that the primary-expression piece of the postfix-expression has been
1857
  // parsed, see if there are any postfix-expression pieces here.
1858
30.0M
  SourceLocation Loc;
1859
30.0M
  auto SavedType = PreferredType;
1860
36.3M
  while (true) {
1861
    // Each iteration relies on preferred type for the whole expression.
1862
36.3M
    PreferredType = SavedType;
1863
36.3M
    switch (Tok.getKind()) {
1864
69
    case tok::code_completion:
1865
69
      if (InMessageExpression)
1866
58
        return LHS;
1867
1868
11
      cutOffParsing();
1869
11
      Actions.CodeCompletePostfixExpression(
1870
11
          getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1871
11
      return ExprError();
1872
1873
20.6k
    case tok::identifier:
1874
      // If we see identifier: after an expression, and we're not already in a
1875
      // message send, then this is probably a message send with a missing
1876
      // opening bracket '['.
1877
20.6k
      if (getLangOpts().ObjC && 
!InMessageExpression18.9k
&&
1878
20.6k
          
(282
NextToken().is(tok::colon)282
||
NextToken().is(tok::r_square)196
)) {
1879
174
        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1880
174
                                             nullptr, LHS.get());
1881
174
        break;
1882
174
      }
1883
      // Fall through; this isn't a message send.
1884
20.6k
      
LLVM_FALLTHROUGH20.5k
;20.5k
1885
1886
30.0M
    default:  // Not a postfix-expression suffix.
1887
30.0M
      return LHS;
1888
275k
    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1889
      // If we have a array postfix expression that starts on a new line and
1890
      // Objective-C is enabled, it is highly likely that the user forgot a
1891
      // semicolon after the base expression and that the array postfix-expr is
1892
      // actually another message send.  In this case, do some look-ahead to see
1893
      // if the contents of the square brackets are obviously not a valid
1894
      // expression and recover by pretending there is no suffix.
1895
275k
      if (getLangOpts().ObjC && 
Tok.isAtStartOfLine()59.1k
&&
1896
275k
          
isSimpleObjCMessageExpression()5
)
1897
4
        return LHS;
1898
1899
      // Reject array indices starting with a lambda-expression. '[[' is
1900
      // reserved for attributes.
1901
275k
      if (CheckProhibitedCXX11Attribute()) {
1902
2
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
1903
2
        return ExprError();
1904
2
      }
1905
275k
      BalancedDelimiterTracker T(*this, tok::l_square);
1906
275k
      T.consumeOpen();
1907
275k
      Loc = T.getOpenLocation();
1908
275k
      ExprResult Length, Stride;
1909
275k
      SourceLocation ColonLocFirst, ColonLocSecond;
1910
275k
      ExprVector ArgExprs;
1911
275k
      bool HasError = false;
1912
275k
      PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1913
1914
      // We try to parse a list of indexes in all language mode first
1915
      // and, in we find 0 or one index, we try to parse an OpenMP array
1916
      // section. This allow us to support C++2b multi dimensional subscript and
1917
      // OpenMp sections in the same language mode.
1918
275k
      if (!getLangOpts().OpenMP || 
Tok.isNot(tok::colon)105k
) {
1919
267k
        if (!getLangOpts().CPlusPlus2b) {
1920
267k
          ExprResult Idx;
1921
267k
          if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)175k
) {
1922
4
            Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1923
4
            Idx = ParseBraceInitializer();
1924
267k
          } else {
1925
267k
            Idx = ParseExpression(); // May be a comma expression
1926
267k
          }
1927
267k
          LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1928
267k
          Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1929
267k
          if (Idx.isInvalid()) {
1930
130
            HasError = true;
1931
267k
          } else {
1932
267k
            ArgExprs.push_back(Idx.get());
1933
267k
          }
1934
267k
        } else 
if (320
Tok.isNot(tok::r_square)320
) {
1935
308
          CommaLocsTy CommaLocs;
1936
308
          if (ParseExpressionList(ArgExprs, CommaLocs)) {
1937
0
            LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1938
0
            HasError = true;
1939
0
          }
1940
308
          assert(
1941
308
              (ArgExprs.empty() || ArgExprs.size() == CommaLocs.size() + 1) &&
1942
308
              "Unexpected number of commas!");
1943
308
        }
1944
267k
      }
1945
1946
275k
      if (ArgExprs.size() <= 1 && 
getLangOpts().OpenMP275k
) {
1947
105k
        ColonProtectionRAIIObject RAII(*this);
1948
105k
        if (Tok.is(tok::colon)) {
1949
          // Consume ':'
1950
12.9k
          ColonLocFirst = ConsumeToken();
1951
12.9k
          if (Tok.isNot(tok::r_square) &&
1952
12.9k
              
(9.80k
getLangOpts().OpenMP < 509.80k
||
1953
9.80k
               
((7.02k
Tok.isNot(tok::colon)7.02k
&&
getLangOpts().OpenMP >= 507.00k
)))) {
1954
9.78k
            Length = ParseExpression();
1955
9.78k
            Length = Actions.CorrectDelayedTyposInExpr(Length);
1956
9.78k
          }
1957
12.9k
        }
1958
105k
        if (getLangOpts().OpenMP >= 50 &&
1959
105k
            
(85.0k
OMPClauseKind == llvm::omp::Clause::OMPC_to85.0k
||
1960
85.0k
             
OMPClauseKind == llvm::omp::Clause::OMPC_from84.1k
) &&
1961
105k
            
Tok.is(tok::colon)1.53k
) {
1962
          // Consume ':'
1963
215
          ColonLocSecond = ConsumeToken();
1964
215
          if (Tok.isNot(tok::r_square)) {
1965
167
            Stride = ParseExpression();
1966
167
          }
1967
215
        }
1968
105k
      }
1969
1970
275k
      SourceLocation RLoc = Tok.getLocation();
1971
275k
      LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1972
1973
275k
      if (!LHS.isInvalid() && 
!HasError275k
&&
!Length.isInvalid()275k
&&
1974
275k
          
!Stride.isInvalid()274k
&&
Tok.is(tok::r_square)274k
) {
1975
274k
        if (ColonLocFirst.isValid() || 
ColonLocSecond.isValid()262k
) {
1976
12.3k
          LHS = Actions.ActOnOMPArraySectionExpr(
1977
12.3k
              LHS.get(), Loc, ArgExprs.empty() ? 
nullptr7.25k
:
ArgExprs[0]5.09k
,
1978
12.3k
              ColonLocFirst, ColonLocSecond, Length.get(), Stride.get(), RLoc);
1979
262k
        } else {
1980
262k
          LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1981
262k
                                                ArgExprs, RLoc);
1982
262k
        }
1983
274k
      } else {
1984
773
        LHS = ExprError();
1985
773
      }
1986
1987
      // Match the ']'.
1988
275k
      T.consumeClose();
1989
275k
      break;
1990
275k
    }
1991
1992
4.76M
    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1993
4.76M
    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1994
                               //   '(' argument-expression-list[opt] ')'
1995
4.76M
      tok::TokenKind OpKind = Tok.getKind();
1996
4.76M
      InMessageExpressionRAIIObject InMessage(*this, false);
1997
1998
4.76M
      Expr *ExecConfig = nullptr;
1999
2000
4.76M
      BalancedDelimiterTracker PT(*this, tok::l_paren);
2001
2002
4.76M
      if (OpKind == tok::lesslessless) {
2003
184
        ExprVector ExecConfigExprs;
2004
184
        CommaLocsTy ExecConfigCommaLocs;
2005
184
        SourceLocation OpenLoc = ConsumeToken();
2006
2007
184
        if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
2008
1
          (void)Actions.CorrectDelayedTyposInExpr(LHS);
2009
1
          LHS = ExprError();
2010
1
        }
2011
2012
184
        SourceLocation CloseLoc;
2013
184
        if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
2014
183
        } else 
if (1
LHS.isInvalid()1
) {
2015
0
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
2016
1
        } else {
2017
          // There was an error closing the brackets
2018
1
          Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
2019
1
          Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
2020
1
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
2021
1
          LHS = ExprError();
2022
1
        }
2023
2024
184
        if (!LHS.isInvalid()) {
2025
180
          if (ExpectAndConsume(tok::l_paren))
2026
1
            LHS = ExprError();
2027
179
          else
2028
179
            Loc = PrevTokLocation;
2029
180
        }
2030
2031
184
        if (!LHS.isInvalid()) {
2032
179
          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
2033
179
                                    OpenLoc,
2034
179
                                    ExecConfigExprs,
2035
179
                                    CloseLoc);
2036
179
          if (ECResult.isInvalid())
2037
2
            LHS = ExprError();
2038
177
          else
2039
177
            ExecConfig = ECResult.get();
2040
179
        }
2041
4.76M
      } else {
2042
4.76M
        PT.consumeOpen();
2043
4.76M
        Loc = PT.getOpenLocation();
2044
4.76M
      }
2045
2046
4.76M
      ExprVector ArgExprs;
2047
4.76M
      CommaLocsTy CommaLocs;
2048
4.76M
      auto RunSignatureHelp = [&]() -> QualType {
2049
189
        QualType PreferredType = Actions.ProduceCallSignatureHelp(
2050
189
            LHS.get(), ArgExprs, PT.getOpenLocation());
2051
189
        CalledSignatureHelp = true;
2052
189
        return PreferredType;
2053
189
      };
2054
4.76M
      if (OpKind == tok::l_paren || 
!LHS.isInvalid()184
) {
2055
4.76M
        if (Tok.isNot(tok::r_paren)) {
2056
8.62M
          if (
ParseExpressionList(ArgExprs, CommaLocs, [&] 3.59M
{
2057
8.62M
                PreferredType.enterFunctionArgument(Tok.getLocation(),
2058
8.62M
                                                    RunSignatureHelp);
2059
8.62M
              })) {
2060
3.24k
            (void)Actions.CorrectDelayedTyposInExpr(LHS);
2061
            // If we got an error when parsing expression list, we don't call
2062
            // the CodeCompleteCall handler inside the parser. So call it here
2063
            // to make sure we get overload suggestions even when we are in the
2064
            // middle of a parameter.
2065
3.24k
            if (PP.isCodeCompletionReached() && 
!CalledSignatureHelp184
)
2066
4
              RunSignatureHelp();
2067
3.24k
            LHS = ExprError();
2068
3.58M
          } else if (LHS.isInvalid()) {
2069
229
            for (auto &E : ArgExprs)
2070
350
              Actions.CorrectDelayedTyposInExpr(E);
2071
229
          }
2072
3.59M
        }
2073
4.76M
      }
2074
2075
      // Match the ')'.
2076
4.76M
      if (LHS.isInvalid()) {
2077
3.65k
        SkipUntil(tok::r_paren, StopAtSemi);
2078
4.76M
      } else if (Tok.isNot(tok::r_paren)) {
2079
1.14k
        bool HadDelayedTypo = false;
2080
1.14k
        if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2081
0
          HadDelayedTypo = true;
2082
1.14k
        for (auto &E : ArgExprs)
2083
1.14k
          if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2084
11
            HadDelayedTypo = true;
2085
        // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2086
        // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2087
        // the unmatched l_paren.
2088
1.14k
        if (HadDelayedTypo)
2089
11
          SkipUntil(tok::r_paren, StopAtSemi);
2090
1.13k
        else
2091
1.13k
          PT.consumeClose();
2092
1.14k
        LHS = ExprError();
2093
4.76M
      } else {
2094
4.76M
        assert(
2095
4.76M
            (ArgExprs.size() == 0 || ArgExprs.size() - 1 == CommaLocs.size()) &&
2096
4.76M
            "Unexpected number of commas!");
2097
0
        Expr *Fn = LHS.get();
2098
4.76M
        SourceLocation RParLoc = Tok.getLocation();
2099
4.76M
        LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2100
4.76M
                                    ExecConfig);
2101
4.76M
        if (LHS.isInvalid()) {
2102
7.54k
          ArgExprs.insert(ArgExprs.begin(), Fn);
2103
7.54k
          LHS =
2104
7.54k
              Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2105
7.54k
        }
2106
4.76M
        PT.consumeClose();
2107
4.76M
      }
2108
2109
0
      break;
2110
4.76M
    }
2111
318k
    case tok::arrow:
2112
1.18M
    case tok::period: {
2113
      // postfix-expression: p-e '->' template[opt] id-expression
2114
      // postfix-expression: p-e '.' template[opt] id-expression
2115
1.18M
      tok::TokenKind OpKind = Tok.getKind();
2116
1.18M
      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
2117
2118
1.18M
      CXXScopeSpec SS;
2119
1.18M
      ParsedType ObjectType;
2120
1.18M
      bool MayBePseudoDestructor = false;
2121
1.18M
      Expr* OrigLHS = !LHS.isInvalid() ? 
LHS.get()1.18M
:
nullptr44
;
2122
2123
1.18M
      PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2124
2125
1.18M
      if (getLangOpts().CPlusPlus && 
!LHS.isInvalid()1.05M
) {
2126
1.05M
        Expr *Base = OrigLHS;
2127
1.05M
        const Type* BaseType = Base->getType().getTypePtrOrNull();
2128
1.05M
        if (BaseType && 
Tok.is(tok::l_paren)1.05M
&&
2129
1.05M
            
(13
BaseType->isFunctionType()13
||
2130
13
             
BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember)8
)) {
2131
10
          Diag(OpLoc, diag::err_function_is_not_record)
2132
10
              << OpKind << Base->getSourceRange()
2133
10
              << FixItHint::CreateRemoval(OpLoc);
2134
10
          return ParsePostfixExpressionSuffix(Base);
2135
10
        }
2136
2137
1.05M
        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2138
1.05M
                                                   OpKind, ObjectType,
2139
1.05M
                                                   MayBePseudoDestructor);
2140
1.05M
        if (LHS.isInvalid()) {
2141
          // Clang will try to perform expression based completion as a
2142
          // fallback, which is confusing in case of member references. So we
2143
          // stop here without any completions.
2144
176
          if (Tok.is(tok::code_completion)) {
2145
0
            cutOffParsing();
2146
0
            return ExprError();
2147
0
          }
2148
176
          break;
2149
176
        }
2150
1.05M
        ParseOptionalCXXScopeSpecifier(
2151
1.05M
            SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2152
1.05M
            /*EnteringContext=*/false, &MayBePseudoDestructor);
2153
1.05M
        if (SS.isNotEmpty())
2154
710
          ObjectType = nullptr;
2155
1.05M
      }
2156
2157
1.18M
      if (Tok.is(tok::code_completion)) {
2158
162
        tok::TokenKind CorrectedOpKind =
2159
162
            OpKind == tok::arrow ? 
tok::period44
:
tok::arrow118
;
2160
162
        ExprResult CorrectedLHS(/*Invalid=*/true);
2161
162
        if (getLangOpts().CPlusPlus && 
OrigLHS113
) {
2162
          // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2163
          // hack.
2164
112
          Sema::TentativeAnalysisScope Trap(Actions);
2165
112
          CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2166
112
              getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2167
112
              MayBePseudoDestructor);
2168
112
        }
2169
2170
162
        Expr *Base = LHS.get();
2171
162
        Expr *CorrectedBase = CorrectedLHS.get();
2172
162
        if (!CorrectedBase && 
!getLangOpts().CPlusPlus50
)
2173
49
          CorrectedBase = Base;
2174
2175
        // Code completion for a member access expression.
2176
162
        cutOffParsing();
2177
162
        Actions.CodeCompleteMemberReferenceExpr(
2178
162
            getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2179
162
            Base && 
ExprStatementTokLoc == Base->getBeginLoc()161
,
2180
162
            PreferredType.get(Tok.getLocation()));
2181
2182
162
        return ExprError();
2183
162
      }
2184
2185
1.18M
      if (MayBePseudoDestructor && 
!LHS.isInvalid()6.32k
) {
2186
6.32k
        LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2187
6.32k
                                       ObjectType);
2188
6.32k
        break;
2189
6.32k
      }
2190
2191
      // Either the action has told us that this cannot be a
2192
      // pseudo-destructor expression (based on the type of base
2193
      // expression), or we didn't see a '~' in the right place. We
2194
      // can still parse a destructor name here, but in that case it
2195
      // names a real destructor.
2196
      // Allow explicit constructor calls in Microsoft mode.
2197
      // FIXME: Add support for explicit call of template constructor.
2198
1.17M
      SourceLocation TemplateKWLoc;
2199
1.17M
      UnqualifiedId Name;
2200
1.17M
      if (getLangOpts().ObjC && 
OpKind == tok::period195k
&&
2201
1.17M
          
Tok.is(tok::kw_class)104k
) {
2202
        // Objective-C++:
2203
        //   After a '.' in a member access expression, treat the keyword
2204
        //   'class' as if it were an identifier.
2205
        //
2206
        // This hack allows property access to the 'class' method because it is
2207
        // such a common method name. For other C++ keywords that are
2208
        // Objective-C method names, one must use the message send syntax.
2209
2
        IdentifierInfo *Id = Tok.getIdentifierInfo();
2210
2
        SourceLocation Loc = ConsumeToken();
2211
2
        Name.setIdentifier(Id, Loc);
2212
1.17M
      } else if (ParseUnqualifiedId(
2213
1.17M
                     SS, ObjectType, LHS.get() && 
LHS.get()->containsErrors()1.17M
,
2214
1.17M
                     /*EnteringContext=*/false,
2215
1.17M
                     /*AllowDestructorName=*/true,
2216
                     /*AllowConstructorName=*/
2217
1.17M
                     getLangOpts().MicrosoftExt && 
SS.isNotEmpty()3.71k
,
2218
1.17M
                     /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2219
324
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
2220
324
        LHS = ExprError();
2221
324
      }
2222
2223
1.17M
      if (!LHS.isInvalid())
2224
1.17M
        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2225
1.17M
                                            OpKind, SS, TemplateKWLoc, Name,
2226
1.17M
                                 CurParsedObjCImpl ? 
CurParsedObjCImpl->Dcl2.21k
2227
1.17M
                                                   : 
nullptr1.17M
);
2228
1.17M
      if (!LHS.isInvalid()) {
2229
1.17M
        if (Tok.is(tok::less))
2230
3.24k
          checkPotentialAngleBracket(LHS);
2231
1.17M
      } else 
if (808
OrigLHS808
&&
Name.isValid()765
) {
2232
        // Preserve the LHS if the RHS is an invalid member.
2233
454
        LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2234
454
                                         Name.getEndLoc(), {OrigLHS});
2235
454
      }
2236
1.17M
      break;
2237
1.18M
    }
2238
41.8k
    case tok::plusplus:    // postfix-expression: postfix-expression '++'
2239
43.2k
    case tok::minusminus:  // postfix-expression: postfix-expression '--'
2240
43.2k
      if (!LHS.isInvalid()) {
2241
43.2k
        Expr *Arg = LHS.get();
2242
43.2k
        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2243
43.2k
                                          Tok.getKind(), Arg);
2244
43.2k
        if (LHS.isInvalid())
2245
90
          LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2246
90
                                           Tok.getLocation(), Arg);
2247
43.2k
      }
2248
43.2k
      ConsumeToken();
2249
43.2k
      break;
2250
36.3M
    }
2251
36.3M
  }
2252
30.0M
}
2253
2254
/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2255
/// vec_step and we are at the start of an expression or a parenthesized
2256
/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2257
/// expression (isCastExpr == false) or the type (isCastExpr == true).
2258
///
2259
/// \verbatim
2260
///       unary-expression:  [C99 6.5.3]
2261
///         'sizeof' unary-expression
2262
///         'sizeof' '(' type-name ')'
2263
/// [GNU]   '__alignof' unary-expression
2264
/// [GNU]   '__alignof' '(' type-name ')'
2265
/// [C11]   '_Alignof' '(' type-name ')'
2266
/// [C++0x] 'alignof' '(' type-id ')'
2267
///
2268
/// [GNU]   typeof-specifier:
2269
///           typeof ( expressions )
2270
///           typeof ( type-name )
2271
/// [GNU/C++] typeof unary-expression
2272
///
2273
/// [OpenCL 1.1 6.11.12] vec_step built-in function:
2274
///           vec_step ( expressions )
2275
///           vec_step ( type-name )
2276
/// \endverbatim
2277
ExprResult
2278
Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2279
                                           bool &isCastExpr,
2280
                                           ParsedType &CastTy,
2281
82.3k
                                           SourceRange &CastRange) {
2282
2283
82.3k
  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
2284
82.3k
                       tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2285
82.3k
                       tok::kw___builtin_omp_required_simd_align) &&
2286
82.3k
         "Not a typeof/sizeof/alignof/vec_step expression!");
2287
2288
0
  ExprResult Operand;
2289
2290
  // If the operand doesn't start with an '(', it must be an expression.
2291
82.3k
  if (Tok.isNot(tok::l_paren)) {
2292
    // If construct allows a form without parenthesis, user may forget to put
2293
    // pathenthesis around type name.
2294
828
    if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2295
828
                      tok::kw__Alignof)) {
2296
822
      if (isTypeIdUnambiguously()) {
2297
9
        DeclSpec DS(AttrFactory);
2298
9
        ParseSpecifierQualifierList(DS);
2299
9
        Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
2300
9
        ParseDeclarator(DeclaratorInfo);
2301
2302
9
        SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2303
9
        SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2304
9
        if (LParenLoc.isInvalid() || 
RParenLoc.isInvalid()8
) {
2305
1
          Diag(OpTok.getLocation(),
2306
1
               diag::err_expected_parentheses_around_typename)
2307
1
              << OpTok.getName();
2308
8
        } else {
2309
8
          Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2310
8
              << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
2311
8
              << FixItHint::CreateInsertion(RParenLoc, ")");
2312
8
        }
2313
9
        isCastExpr = true;
2314
9
        return ExprEmpty();
2315
9
      }
2316
822
    }
2317
2318
819
    isCastExpr = false;
2319
819
    if (OpTok.is(tok::kw_typeof) && 
!getLangOpts().CPlusPlus6
) {
2320
0
      Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2321
0
                                          << tok::l_paren;
2322
0
      return ExprError();
2323
0
    }
2324
2325
819
    Operand = ParseCastExpression(UnaryExprOnly);
2326
81.4k
  } else {
2327
    // If it starts with a '(', we know that it is either a parenthesized
2328
    // type-name, or it is a unary-expression that starts with a compound
2329
    // literal, or starts with a primary-expression that is a parenthesized
2330
    // expression.
2331
81.4k
    ParenParseOption ExprType = CastExpr;
2332
81.4k
    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2333
2334
81.4k
    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2335
81.4k
                                   false, CastTy, RParenLoc);
2336
81.4k
    CastRange = SourceRange(LParenLoc, RParenLoc);
2337
2338
    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2339
    // a type.
2340
81.4k
    if (ExprType == CastExpr) {
2341
66.0k
      isCastExpr = true;
2342
66.0k
      return ExprEmpty();
2343
66.0k
    }
2344
2345
15.4k
    if (getLangOpts().CPlusPlus || 
OpTok.isNot(tok::kw_typeof)1.64k
) {
2346
      // GNU typeof in C requires the expression to be parenthesized. Not so for
2347
      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2348
      // the start of a unary-expression, but doesn't include any postfix
2349
      // pieces. Parse these now if present.
2350
14.9k
      if (!Operand.isInvalid())
2351
14.9k
        Operand = ParsePostfixExpressionSuffix(Operand.get());
2352
14.9k
    }
2353
15.4k
  }
2354
2355
  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2356
16.3k
  isCastExpr = false;
2357
16.3k
  return Operand;
2358
82.3k
}
2359
2360
/// Parse a __builtin_sycl_unique_stable_name expression.  Accepts a type-id as
2361
/// a parameter.
2362
74
ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
2363
74
  assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
2364
74
         "Not __builtin_sycl_unique_stable_name");
2365
2366
0
  SourceLocation OpLoc = ConsumeToken();
2367
74
  BalancedDelimiterTracker T(*this, tok::l_paren);
2368
2369
  // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2370
74
  if (T.expectAndConsume(diag::err_expected_lparen_after,
2371
74
                         "__builtin_sycl_unique_stable_name"))
2372
2
    return ExprError();
2373
2374
72
  TypeResult Ty = ParseTypeName();
2375
2376
72
  if (Ty.isInvalid()) {
2377
8
    T.skipToEnd();
2378
8
    return ExprError();
2379
8
  }
2380
2381
64
  if (T.consumeClose())
2382
2
    return ExprError();
2383
2384
62
  return Actions.ActOnSYCLUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2385
62
                                               T.getCloseLocation(), Ty.get());
2386
64
}
2387
2388
/// Parse a sizeof or alignof expression.
2389
///
2390
/// \verbatim
2391
///       unary-expression:  [C99 6.5.3]
2392
///         'sizeof' unary-expression
2393
///         'sizeof' '(' type-name ')'
2394
/// [C++11] 'sizeof' '...' '(' identifier ')'
2395
/// [GNU]   '__alignof' unary-expression
2396
/// [GNU]   '__alignof' '(' type-name ')'
2397
/// [C11]   '_Alignof' '(' type-name ')'
2398
/// [C++11] 'alignof' '(' type-id ')'
2399
/// \endverbatim
2400
127k
ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2401
127k
  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2402
127k
                     tok::kw__Alignof, tok::kw_vec_step,
2403
127k
                     tok::kw___builtin_omp_required_simd_align) &&
2404
127k
         "Not a sizeof/alignof/vec_step expression!");
2405
0
  Token OpTok = Tok;
2406
127k
  ConsumeToken();
2407
2408
  // [C++11] 'sizeof' '...' '(' identifier ')'
2409
127k
  if (Tok.is(tok::ellipsis) && 
OpTok.is(tok::kw_sizeof)47.5k
) {
2410
47.5k
    SourceLocation EllipsisLoc = ConsumeToken();
2411
47.5k
    SourceLocation LParenLoc, RParenLoc;
2412
47.5k
    IdentifierInfo *Name = nullptr;
2413
47.5k
    SourceLocation NameLoc;
2414
47.5k
    if (Tok.is(tok::l_paren)) {
2415
47.5k
      BalancedDelimiterTracker T(*this, tok::l_paren);
2416
47.5k
      T.consumeOpen();
2417
47.5k
      LParenLoc = T.getOpenLocation();
2418
47.5k
      if (Tok.is(tok::identifier)) {
2419
47.5k
        Name = Tok.getIdentifierInfo();
2420
47.5k
        NameLoc = ConsumeToken();
2421
47.5k
        T.consumeClose();
2422
47.5k
        RParenLoc = T.getCloseLocation();
2423
47.5k
        if (RParenLoc.isInvalid())
2424
0
          RParenLoc = PP.getLocForEndOfToken(NameLoc);
2425
47.5k
      } else {
2426
0
        Diag(Tok, diag::err_expected_parameter_pack);
2427
0
        SkipUntil(tok::r_paren, StopAtSemi);
2428
0
      }
2429
47.5k
    } else 
if (1
Tok.is(tok::identifier)1
) {
2430
1
      Name = Tok.getIdentifierInfo();
2431
1
      NameLoc = ConsumeToken();
2432
1
      LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2433
1
      RParenLoc = PP.getLocForEndOfToken(NameLoc);
2434
1
      Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2435
1
        << Name
2436
1
        << FixItHint::CreateInsertion(LParenLoc, "(")
2437
1
        << FixItHint::CreateInsertion(RParenLoc, ")");
2438
1
    } else {
2439
0
      Diag(Tok, diag::err_sizeof_parameter_pack);
2440
0
    }
2441
2442
47.5k
    if (!Name)
2443
0
      return ExprError();
2444
2445
47.5k
    EnterExpressionEvaluationContext Unevaluated(
2446
47.5k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2447
47.5k
        Sema::ReuseLambdaContextDecl);
2448
2449
47.5k
    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2450
47.5k
                                                OpTok.getLocation(),
2451
47.5k
                                                *Name, NameLoc,
2452
47.5k
                                                RParenLoc);
2453
47.5k
  }
2454
2455
79.4k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2456
5.71k
    Diag(OpTok, diag::warn_cxx98_compat_alignof);
2457
2458
79.4k
  EnterExpressionEvaluationContext Unevaluated(
2459
79.4k
      Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2460
79.4k
      Sema::ReuseLambdaContextDecl);
2461
2462
79.4k
  bool isCastExpr;
2463
79.4k
  ParsedType CastTy;
2464
79.4k
  SourceRange CastRange;
2465
79.4k
  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2466
79.4k
                                                          isCastExpr,
2467
79.4k
                                                          CastTy,
2468
79.4k
                                                          CastRange);
2469
2470
79.4k
  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2471
79.4k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2472
5.71k
    ExprKind = UETT_AlignOf;
2473
73.7k
  else if (OpTok.is(tok::kw___alignof))
2474
3.04k
    ExprKind = UETT_PreferredAlignOf;
2475
70.7k
  else if (OpTok.is(tok::kw_vec_step))
2476
45
    ExprKind = UETT_VecStep;
2477
70.6k
  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2478
29
    ExprKind = UETT_OpenMPRequiredSimdAlign;
2479
2480
79.4k
  if (isCastExpr)
2481
65.9k
    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2482
65.9k
                                                 ExprKind,
2483
65.9k
                                                 /*IsType=*/true,
2484
65.9k
                                                 CastTy.getAsOpaquePtr(),
2485
65.9k
                                                 CastRange);
2486
2487
13.5k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2488
39
    Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2489
2490
  // If we get here, the operand to the sizeof/alignof was an expression.
2491
13.5k
  if (!Operand.isInvalid())
2492
13.5k
    Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2493
13.5k
                                                    ExprKind,
2494
13.5k
                                                    /*IsType=*/false,
2495
13.5k
                                                    Operand.get(),
2496
13.5k
                                                    CastRange);
2497
13.5k
  return Operand;
2498
79.4k
}
2499
2500
/// ParseBuiltinPrimaryExpression
2501
///
2502
/// \verbatim
2503
///       primary-expression: [C99 6.5.1]
2504
/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2505
/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2506
/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2507
///                                     assign-expr ')'
2508
/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2509
/// [GNU]   '__builtin_FILE' '(' ')'
2510
/// [GNU]   '__builtin_FUNCTION' '(' ')'
2511
/// [GNU]   '__builtin_LINE' '(' ')'
2512
/// [CLANG] '__builtin_COLUMN' '(' ')'
2513
/// [GNU]   '__builtin_source_location' '(' ')'
2514
/// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
2515
///
2516
/// [GNU] offsetof-member-designator:
2517
/// [GNU]   identifier
2518
/// [GNU]   offsetof-member-designator '.' identifier
2519
/// [GNU]   offsetof-member-designator '[' expression ']'
2520
/// \endverbatim
2521
23.3k
ExprResult Parser::ParseBuiltinPrimaryExpression() {
2522
23.3k
  ExprResult Res;
2523
23.3k
  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2524
2525
23.3k
  tok::TokenKind T = Tok.getKind();
2526
23.3k
  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
2527
2528
  // All of these start with an open paren.
2529
23.3k
  if (Tok.isNot(tok::l_paren))
2530
0
    return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2531
0
                                                         << tok::l_paren);
2532
2533
23.3k
  BalancedDelimiterTracker PT(*this, tok::l_paren);
2534
23.3k
  PT.consumeOpen();
2535
2536
  // TODO: Build AST.
2537
2538
23.3k
  switch (T) {
2539
0
  default: llvm_unreachable("Not a builtin primary expression!");
2540
1.09k
  case tok::kw___builtin_va_arg: {
2541
1.09k
    ExprResult Expr(ParseAssignmentExpression());
2542
2543
1.09k
    if (ExpectAndConsume(tok::comma)) {
2544
0
      SkipUntil(tok::r_paren, StopAtSemi);
2545
0
      Expr = ExprError();
2546
0
    }
2547
2548
1.09k
    TypeResult Ty = ParseTypeName();
2549
2550
1.09k
    if (Tok.isNot(tok::r_paren)) {
2551
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2552
0
      Expr = ExprError();
2553
0
    }
2554
2555
1.09k
    if (Expr.isInvalid() || Ty.isInvalid())
2556
0
      Res = ExprError();
2557
1.09k
    else
2558
1.09k
      Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2559
1.09k
    break;
2560
0
  }
2561
353
  case tok::kw___builtin_offsetof: {
2562
353
    SourceLocation TypeLoc = Tok.getLocation();
2563
353
    TypeResult Ty = ParseTypeName();
2564
353
    if (Ty.isInvalid()) {
2565
1
      SkipUntil(tok::r_paren, StopAtSemi);
2566
1
      return ExprError();
2567
1
    }
2568
2569
352
    if (ExpectAndConsume(tok::comma)) {
2570
0
      SkipUntil(tok::r_paren, StopAtSemi);
2571
0
      return ExprError();
2572
0
    }
2573
2574
    // We must have at least one identifier here.
2575
352
    if (Tok.isNot(tok::identifier)) {
2576
0
      Diag(Tok, diag::err_expected) << tok::identifier;
2577
0
      SkipUntil(tok::r_paren, StopAtSemi);
2578
0
      return ExprError();
2579
0
    }
2580
2581
    // Keep track of the various subcomponents we see.
2582
352
    SmallVector<Sema::OffsetOfComponent, 4> Comps;
2583
2584
352
    Comps.push_back(Sema::OffsetOfComponent());
2585
352
    Comps.back().isBrackets = false;
2586
352
    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2587
352
    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2588
2589
    // FIXME: This loop leaks the index expressions on error.
2590
413
    while (true) {
2591
413
      if (Tok.is(tok::period)) {
2592
        // offsetof-member-designator: offsetof-member-designator '.' identifier
2593
19
        Comps.push_back(Sema::OffsetOfComponent());
2594
19
        Comps.back().isBrackets = false;
2595
19
        Comps.back().LocStart = ConsumeToken();
2596
2597
19
        if (Tok.isNot(tok::identifier)) {
2598
0
          Diag(Tok, diag::err_expected) << tok::identifier;
2599
0
          SkipUntil(tok::r_paren, StopAtSemi);
2600
0
          return ExprError();
2601
0
        }
2602
19
        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2603
19
        Comps.back().LocEnd = ConsumeToken();
2604
2605
394
      } else if (Tok.is(tok::l_square)) {
2606
42
        if (CheckProhibitedCXX11Attribute())
2607
0
          return ExprError();
2608
2609
        // offsetof-member-designator: offsetof-member-design '[' expression ']'
2610
42
        Comps.push_back(Sema::OffsetOfComponent());
2611
42
        Comps.back().isBrackets = true;
2612
42
        BalancedDelimiterTracker ST(*this, tok::l_square);
2613
42
        ST.consumeOpen();
2614
42
        Comps.back().LocStart = ST.getOpenLocation();
2615
42
        Res = ParseExpression();
2616
42
        if (Res.isInvalid()) {
2617
0
          SkipUntil(tok::r_paren, StopAtSemi);
2618
0
          return Res;
2619
0
        }
2620
42
        Comps.back().U.E = Res.get();
2621
2622
42
        ST.consumeClose();
2623
42
        Comps.back().LocEnd = ST.getCloseLocation();
2624
352
      } else {
2625
352
        if (Tok.isNot(tok::r_paren)) {
2626
2
          PT.consumeClose();
2627
2
          Res = ExprError();
2628
350
        } else if (Ty.isInvalid()) {
2629
0
          Res = ExprError();
2630
350
        } else {
2631
350
          PT.consumeClose();
2632
350
          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2633
350
                                             Ty.get(), Comps,
2634
350
                                             PT.getCloseLocation());
2635
350
        }
2636
352
        break;
2637
352
      }
2638
413
    }
2639
352
    break;
2640
352
  }
2641
352
  case tok::kw___builtin_choose_expr: {
2642
61
    ExprResult Cond(ParseAssignmentExpression());
2643
61
    if (Cond.isInvalid()) {
2644
0
      SkipUntil(tok::r_paren, StopAtSemi);
2645
0
      return Cond;
2646
0
    }
2647
61
    if (ExpectAndConsume(tok::comma)) {
2648
0
      SkipUntil(tok::r_paren, StopAtSemi);
2649
0
      return ExprError();
2650
0
    }
2651
2652
61
    ExprResult Expr1(ParseAssignmentExpression());
2653
61
    if (Expr1.isInvalid()) {
2654
0
      SkipUntil(tok::r_paren, StopAtSemi);
2655
0
      return Expr1;
2656
0
    }
2657
61
    if (ExpectAndConsume(tok::comma)) {
2658
0
      SkipUntil(tok::r_paren, StopAtSemi);
2659
0
      return ExprError();
2660
0
    }
2661
2662
61
    ExprResult Expr2(ParseAssignmentExpression());
2663
61
    if (Expr2.isInvalid()) {
2664
0
      SkipUntil(tok::r_paren, StopAtSemi);
2665
0
      return Expr2;
2666
0
    }
2667
61
    if (Tok.isNot(tok::r_paren)) {
2668
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2669
0
      return ExprError();
2670
0
    }
2671
61
    Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2672
61
                                  Expr2.get(), ConsumeParen());
2673
61
    break;
2674
61
  }
2675
45
  case tok::kw___builtin_astype: {
2676
    // The first argument is an expression to be converted, followed by a comma.
2677
45
    ExprResult Expr(ParseAssignmentExpression());
2678
45
    if (Expr.isInvalid()) {
2679
0
      SkipUntil(tok::r_paren, StopAtSemi);
2680
0
      return ExprError();
2681
0
    }
2682
2683
45
    if (ExpectAndConsume(tok::comma)) {
2684
0
      SkipUntil(tok::r_paren, StopAtSemi);
2685
0
      return ExprError();
2686
0
    }
2687
2688
    // Second argument is the type to bitcast to.
2689
45
    TypeResult DestTy = ParseTypeName();
2690
45
    if (DestTy.isInvalid())
2691
0
      return ExprError();
2692
2693
    // Attempt to consume the r-paren.
2694
45
    if (Tok.isNot(tok::r_paren)) {
2695
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2696
0
      SkipUntil(tok::r_paren, StopAtSemi);
2697
0
      return ExprError();
2698
0
    }
2699
2700
45
    Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2701
45
                                  ConsumeParen());
2702
45
    break;
2703
45
  }
2704
21.6k
  case tok::kw___builtin_convertvector: {
2705
    // The first argument is an expression to be converted, followed by a comma.
2706
21.6k
    ExprResult Expr(ParseAssignmentExpression());
2707
21.6k
    if (Expr.isInvalid()) {
2708
0
      SkipUntil(tok::r_paren, StopAtSemi);
2709
0
      return ExprError();
2710
0
    }
2711
2712
21.6k
    if (ExpectAndConsume(tok::comma)) {
2713
0
      SkipUntil(tok::r_paren, StopAtSemi);
2714
0
      return ExprError();
2715
0
    }
2716
2717
    // Second argument is the type to bitcast to.
2718
21.6k
    TypeResult DestTy = ParseTypeName();
2719
21.6k
    if (DestTy.isInvalid())
2720
0
      return ExprError();
2721
2722
    // Attempt to consume the r-paren.
2723
21.6k
    if (Tok.isNot(tok::r_paren)) {
2724
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2725
0
      SkipUntil(tok::r_paren, StopAtSemi);
2726
0
      return ExprError();
2727
0
    }
2728
2729
21.6k
    Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2730
21.6k
                                         ConsumeParen());
2731
21.6k
    break;
2732
21.6k
  }
2733
17
  case tok::kw___builtin_COLUMN:
2734
39
  case tok::kw___builtin_FILE:
2735
57
  case tok::kw___builtin_FUNCTION:
2736
108
  case tok::kw___builtin_LINE:
2737
128
  case tok::kw___builtin_source_location: {
2738
    // Attempt to consume the r-paren.
2739
128
    if (Tok.isNot(tok::r_paren)) {
2740
8
      Diag(Tok, diag::err_expected) << tok::r_paren;
2741
8
      SkipUntil(tok::r_paren, StopAtSemi);
2742
8
      return ExprError();
2743
8
    }
2744
120
    SourceLocExpr::IdentKind Kind = [&] {
2745
120
      switch (T) {
2746
20
      case tok::kw___builtin_FILE:
2747
20
        return SourceLocExpr::File;
2748
16
      case tok::kw___builtin_FUNCTION:
2749
16
        return SourceLocExpr::Function;
2750
49
      case tok::kw___builtin_LINE:
2751
49
        return SourceLocExpr::Line;
2752
15
      case tok::kw___builtin_COLUMN:
2753
15
        return SourceLocExpr::Column;
2754
20
      case tok::kw___builtin_source_location:
2755
20
        return SourceLocExpr::SourceLocStruct;
2756
0
      default:
2757
0
        llvm_unreachable("invalid keyword");
2758
120
      }
2759
120
    }();
2760
120
    Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2761
120
    break;
2762
128
  }
2763
23.3k
  }
2764
2765
23.3k
  if (Res.isInvalid())
2766
43
    return ExprError();
2767
2768
  // These can be followed by postfix-expr pieces because they are
2769
  // primary-expressions.
2770
23.2k
  return ParsePostfixExpressionSuffix(Res.get());
2771
23.3k
}
2772
2773
149
bool Parser::tryParseOpenMPArrayShapingCastPart() {
2774
149
  assert(Tok.is(tok::l_square) && "Expected open bracket");
2775
0
  bool ErrorFound = true;
2776
149
  TentativeParsingAction TPA(*this);
2777
295
  do {
2778
295
    if (Tok.isNot(tok::l_square))
2779
0
      break;
2780
    // Consume '['
2781
295
    ConsumeBracket();
2782
    // Skip inner expression.
2783
295
    while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
2784
295
                      StopAtSemi | StopBeforeMatch))
2785
0
      ;
2786
295
    if (Tok.isNot(tok::r_square))
2787
6
      break;
2788
    // Consume ']'
2789
289
    ConsumeBracket();
2790
    // Found ')' - done.
2791
289
    if (Tok.is(tok::r_paren)) {
2792
137
      ErrorFound = false;
2793
137
      break;
2794
137
    }
2795
289
  } while (
Tok.isNot(tok::annot_pragma_openmp_end)152
);
2796
0
  TPA.Revert();
2797
149
  return !ErrorFound;
2798
149
}
2799
2800
/// ParseParenExpression - This parses the unit that starts with a '(' token,
2801
/// based on what is allowed by ExprType.  The actual thing parsed is returned
2802
/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2803
/// not the parsed cast-expression.
2804
///
2805
/// \verbatim
2806
///       primary-expression: [C99 6.5.1]
2807
///         '(' expression ')'
2808
/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
2809
///       postfix-expression: [C99 6.5.2]
2810
///         '(' type-name ')' '{' initializer-list '}'
2811
///         '(' type-name ')' '{' initializer-list ',' '}'
2812
///       cast-expression: [C99 6.5.4]
2813
///         '(' type-name ')' cast-expression
2814
/// [ARC]   bridged-cast-expression
2815
/// [ARC] bridged-cast-expression:
2816
///         (__bridge type-name) cast-expression
2817
///         (__bridge_transfer type-name) cast-expression
2818
///         (__bridge_retained type-name) cast-expression
2819
///       fold-expression: [C++1z]
2820
///         '(' cast-expression fold-operator '...' ')'
2821
///         '(' '...' fold-operator cast-expression ')'
2822
///         '(' cast-expression fold-operator '...'
2823
///                 fold-operator cast-expression ')'
2824
/// [OPENMP] Array shaping operation
2825
///       '(' '[' expression ']' { '[' expression ']' } cast-expression
2826
/// \endverbatim
2827
ExprResult
2828
Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2829
                             bool isTypeCast, ParsedType &CastTy,
2830
5.79M
                             SourceLocation &RParenLoc) {
2831
5.79M
  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2832
0
  ColonProtectionRAIIObject ColonProtection(*this, false);
2833
5.79M
  BalancedDelimiterTracker T(*this, tok::l_paren);
2834
5.79M
  if (T.consumeOpen())
2835
0
    return ExprError();
2836
5.79M
  SourceLocation OpenLoc = T.getOpenLocation();
2837
2838
5.79M
  PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2839
2840
5.79M
  ExprResult Result(true);
2841
5.79M
  bool isAmbiguousTypeId;
2842
5.79M
  CastTy = nullptr;
2843
2844
5.79M
  if (Tok.is(tok::code_completion)) {
2845
30
    cutOffParsing();
2846
30
    Actions.CodeCompleteExpression(
2847
30
        getCurScope(), PreferredType.get(Tok.getLocation()),
2848
30
        /*IsParenthesized=*/ExprType >= CompoundLiteral);
2849
30
    return ExprError();
2850
30
  }
2851
2852
  // Diagnose use of bridge casts in non-arc mode.
2853
5.79M
  bool BridgeCast = (getLangOpts().ObjC &&
2854
5.79M
                     Tok.isOneOf(tok::kw___bridge,
2855
718k
                                 tok::kw___bridge_transfer,
2856
718k
                                 tok::kw___bridge_retained,
2857
718k
                                 tok::kw___bridge_retain));
2858
5.79M
  if (BridgeCast && 
!getLangOpts().ObjCAutoRefCount425
) {
2859
86
    if (!TryConsumeToken(tok::kw___bridge)) {
2860
8
      StringRef BridgeCastName = Tok.getName();
2861
8
      SourceLocation BridgeKeywordLoc = ConsumeToken();
2862
8
      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2863
8
        Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2864
8
          << BridgeCastName
2865
8
          << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2866
8
    }
2867
86
    BridgeCast = false;
2868
86
  }
2869
2870
  // None of these cases should fall through with an invalid Result
2871
  // unless they've already reported an error.
2872
5.79M
  if (ExprType >= CompoundStmt && 
Tok.is(tok::l_brace)5.79M
) {
2873
8.94k
    Diag(Tok, diag::ext_gnu_statement_expr);
2874
2875
8.94k
    checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
2876
2877
8.94k
    if (!getCurScope()->getFnParent() && 
!getCurScope()->getBlockParent()2
) {
2878
2
      Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2879
8.94k
    } else {
2880
      // Find the nearest non-record decl context. Variables declared in a
2881
      // statement expression behave as if they were declared in the enclosing
2882
      // function, block, or other code construct.
2883
8.94k
      DeclContext *CodeDC = Actions.CurContext;
2884
8.95k
      while (CodeDC->isRecord() || 
isa<EnumDecl>(CodeDC)8.94k
) {
2885
3
        CodeDC = CodeDC->getParent();
2886
3
        assert(CodeDC && !CodeDC->isFileContext() &&
2887
3
               "statement expr not in code context");
2888
3
      }
2889
8.94k
      Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2890
2891
8.94k
      Actions.ActOnStartStmtExpr();
2892
2893
8.94k
      StmtResult Stmt(ParseCompoundStatement(true));
2894
8.94k
      ExprType = CompoundStmt;
2895
2896
      // If the substmt parsed correctly, build the AST node.
2897
8.94k
      if (!Stmt.isInvalid()) {
2898
8.94k
        Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2899
8.94k
                                       Tok.getLocation());
2900
8.94k
      } else {
2901
0
        Actions.ActOnStmtExprError();
2902
0
      }
2903
8.94k
    }
2904
5.78M
  } else if (ExprType >= CompoundLiteral && 
BridgeCast5.78M
) {
2905
339
    tok::TokenKind tokenKind = Tok.getKind();
2906
339
    SourceLocation BridgeKeywordLoc = ConsumeToken();
2907
2908
    // Parse an Objective-C ARC ownership cast expression.
2909
339
    ObjCBridgeCastKind Kind;
2910
339
    if (tokenKind == tok::kw___bridge)
2911
128
      Kind = OBC_Bridge;
2912
211
    else if (tokenKind == tok::kw___bridge_transfer)
2913
107
      Kind = OBC_BridgeTransfer;
2914
104
    else if (tokenKind == tok::kw___bridge_retained)
2915
100
      Kind = OBC_BridgeRetained;
2916
4
    else {
2917
      // As a hopefully temporary workaround, allow __bridge_retain as
2918
      // a synonym for __bridge_retained, but only in system headers.
2919
4
      assert(tokenKind == tok::kw___bridge_retain);
2920
0
      Kind = OBC_BridgeRetained;
2921
4
      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2922
2
        Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2923
2
          << FixItHint::CreateReplacement(BridgeKeywordLoc,
2924
2
                                          "__bridge_retained");
2925
4
    }
2926
2927
0
    TypeResult Ty = ParseTypeName();
2928
339
    T.consumeClose();
2929
339
    ColonProtection.restore();
2930
339
    RParenLoc = T.getCloseLocation();
2931
2932
339
    PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2933
339
    ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2934
2935
339
    if (Ty.isInvalid() || SubExpr.isInvalid())
2936
0
      return ExprError();
2937
2938
339
    return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2939
339
                                        BridgeKeywordLoc, Ty.get(),
2940
339
                                        RParenLoc, SubExpr.get());
2941
5.78M
  } else if (ExprType >= CompoundLiteral &&
2942
5.78M
             
isTypeIdInParens(isAmbiguousTypeId)5.78M
) {
2943
2944
    // Otherwise, this is a compound literal expression or cast expression.
2945
2946
    // In C++, if the type-id is ambiguous we disambiguate based on context.
2947
    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2948
    // in which case we should treat it as type-id.
2949
    // if stopIfCastExpr is false, we need to determine the context past the
2950
    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2951
4.75M
    if (isAmbiguousTypeId && 
!stopIfCastExpr1.72k
) {
2952
1.64k
      ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2953
1.64k
                                                        ColonProtection);
2954
1.64k
      RParenLoc = T.getCloseLocation();
2955
1.64k
      return res;
2956
1.64k
    }
2957
2958
    // Parse the type declarator.
2959
4.75M
    DeclSpec DS(AttrFactory);
2960
4.75M
    ParseSpecifierQualifierList(DS);
2961
4.75M
    Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
2962
4.75M
    ParseDeclarator(DeclaratorInfo);
2963
2964
    // If our type is followed by an identifier and either ':' or ']', then
2965
    // this is probably an Objective-C message send where the leading '[' is
2966
    // missing. Recover as if that were the case.
2967
4.75M
    if (!DeclaratorInfo.isInvalidType() && 
Tok.is(tok::identifier)4.75M
&&
2968
4.75M
        
!InMessageExpression77
&&
getLangOpts().ObjC77
&&
2969
4.75M
        
(75
NextToken().is(tok::colon)75
||
NextToken().is(tok::r_square)0
)) {
2970
75
      TypeResult Ty;
2971
75
      {
2972
75
        InMessageExpressionRAIIObject InMessage(*this, false);
2973
75
        Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2974
75
      }
2975
75
      Result = ParseObjCMessageExpressionBody(SourceLocation(),
2976
75
                                              SourceLocation(),
2977
75
                                              Ty.get(), nullptr);
2978
4.75M
    } else {
2979
      // Match the ')'.
2980
4.75M
      T.consumeClose();
2981
4.75M
      ColonProtection.restore();
2982
4.75M
      RParenLoc = T.getCloseLocation();
2983
4.75M
      if (Tok.is(tok::l_brace)) {
2984
53.3k
        ExprType = CompoundLiteral;
2985
53.3k
        TypeResult Ty;
2986
53.3k
        {
2987
53.3k
          InMessageExpressionRAIIObject InMessage(*this, false);
2988
53.3k
          Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2989
53.3k
        }
2990
53.3k
        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2991
53.3k
      }
2992
2993
4.70M
      if (Tok.is(tok::l_paren)) {
2994
        // This could be OpenCL vector Literals
2995
393k
        if (getLangOpts().OpenCL)
2996
477
        {
2997
477
          TypeResult Ty;
2998
477
          {
2999
477
            InMessageExpressionRAIIObject InMessage(*this, false);
3000
477
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3001
477
          }
3002
477
          if(Ty.isInvalid())
3003
0
          {
3004
0
             return ExprError();
3005
0
          }
3006
477
          QualType QT = Ty.get().get().getCanonicalType();
3007
477
          if (QT->isVectorType())
3008
167
          {
3009
            // We parsed '(' vector-type-name ')' followed by '('
3010
3011
            // Parse the cast-expression that follows it next.
3012
            // isVectorLiteral = true will make sure we don't parse any
3013
            // Postfix expression yet
3014
167
            Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3015
167
                                         /*isAddressOfOperand=*/false,
3016
167
                                         /*isTypeCast=*/IsTypeCast,
3017
167
                                         /*isVectorLiteral=*/true);
3018
3019
167
            if (!Result.isInvalid()) {
3020
167
              Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3021
167
                                             DeclaratorInfo, CastTy,
3022
167
                                             RParenLoc, Result.get());
3023
167
            }
3024
3025
            // After we performed the cast we can check for postfix-expr pieces.
3026
167
            if (!Result.isInvalid()) {
3027
164
              Result = ParsePostfixExpressionSuffix(Result);
3028
164
            }
3029
3030
167
            return Result;
3031
167
          }
3032
477
        }
3033
393k
      }
3034
3035
4.70M
      if (ExprType == CastExpr) {
3036
        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3037
3038
4.70M
        if (DeclaratorInfo.isInvalidType())
3039
7
          return ExprError();
3040
3041
        // Note that this doesn't parse the subsequent cast-expression, it just
3042
        // returns the parsed type to the callee.
3043
4.70M
        if (stopIfCastExpr) {
3044
65.9k
          TypeResult Ty;
3045
65.9k
          {
3046
65.9k
            InMessageExpressionRAIIObject InMessage(*this, false);
3047
65.9k
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3048
65.9k
          }
3049
65.9k
          CastTy = Ty.get();
3050
65.9k
          return ExprResult();
3051
65.9k
        }
3052
3053
        // Reject the cast of super idiom in ObjC.
3054
4.63M
        if (Tok.is(tok::identifier) && 
getLangOpts().ObjC4.10M
&&
3055
4.63M
            
Tok.getIdentifierInfo() == Ident_super278k
&&
3056
4.63M
            
getCurScope()->isInObjcMethodScope()10
&&
3057
4.63M
            
GetLookAheadToken(1).isNot(tok::period)8
) {
3058
7
          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3059
7
            << SourceRange(OpenLoc, RParenLoc);
3060
7
          return ExprError();
3061
7
        }
3062
3063
4.63M
        PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3064
        // Parse the cast-expression that follows it next.
3065
        // TODO: For cast expression with CastTy.
3066
4.63M
        Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3067
4.63M
                                     /*isAddressOfOperand=*/false,
3068
4.63M
                                     /*isTypeCast=*/IsTypeCast);
3069
4.63M
        if (!Result.isInvalid()) {
3070
4.63M
          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3071
4.63M
                                         DeclaratorInfo, CastTy,
3072
4.63M
                                         RParenLoc, Result.get());
3073
4.63M
        }
3074
4.63M
        return Result;
3075
4.63M
      }
3076
3077
0
      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3078
0
      return ExprError();
3079
4.70M
    }
3080
4.75M
  } else 
if (1.02M
ExprType >= FoldExpr1.02M
&&
Tok.is(tok::ellipsis)1.02M
&&
3081
1.02M
             
isFoldOperator(NextToken().getKind())28
) {
3082
24
    ExprType = FoldExpr;
3083
24
    return ParseFoldExpression(ExprResult(), T);
3084
1.02M
  } else if (isTypeCast) {
3085
    // Parse the expression-list.
3086
321k
    InMessageExpressionRAIIObject InMessage(*this, false);
3087
3088
321k
    ExprVector ArgExprs;
3089
321k
    CommaLocsTy CommaLocs;
3090
3091
321k
    if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
3092
      // FIXME: If we ever support comma expressions as operands to
3093
      // fold-expressions, we'll need to allow multiple ArgExprs here.
3094
321k
      if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3095
321k
          
isFoldOperator(Tok.getKind())319k
&&
NextToken().is(tok::ellipsis)30
) {
3096
30
        ExprType = FoldExpr;
3097
30
        return ParseFoldExpression(ArgExprs[0], T);
3098
30
      }
3099
3100
321k
      ExprType = SimpleExpr;
3101
321k
      Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3102
321k
                                          ArgExprs);
3103
321k
    }
3104
707k
  } else if (getLangOpts().OpenMP >= 50 && 
OpenMPDirectiveParsing3.70k
&&
3105
707k
             
ExprType == CastExpr1.21k
&&
Tok.is(tok::l_square)1.21k
&&
3106
707k
             
tryParseOpenMPArrayShapingCastPart()149
) {
3107
137
    bool ErrorFound = false;
3108
137
    SmallVector<Expr *, 4> OMPDimensions;
3109
137
    SmallVector<SourceRange, 4> OMPBracketsRanges;
3110
283
    do {
3111
283
      BalancedDelimiterTracker TS(*this, tok::l_square);
3112
283
      TS.consumeOpen();
3113
283
      ExprResult NumElements =
3114
283
          Actions.CorrectDelayedTyposInExpr(ParseExpression());
3115
283
      if (!NumElements.isUsable()) {
3116
18
        ErrorFound = true;
3117
18
        while (!SkipUntil(tok::r_square, tok::r_paren,
3118
18
                          StopAtSemi | StopBeforeMatch))
3119
0
          ;
3120
18
      }
3121
283
      TS.consumeClose();
3122
283
      OMPDimensions.push_back(NumElements.get());
3123
283
      OMPBracketsRanges.push_back(TS.getRange());
3124
283
    } while (Tok.isNot(tok::r_paren));
3125
    // Match the ')'.
3126
137
    T.consumeClose();
3127
137
    RParenLoc = T.getCloseLocation();
3128
137
    Result = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3129
137
    if (ErrorFound) {
3130
18
      Result = ExprError();
3131
119
    } else if (!Result.isInvalid()) {
3132
119
      Result = Actions.ActOnOMPArrayShapingExpr(
3133
119
          Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3134
119
    }
3135
137
    return Result;
3136
707k
  } else {
3137
707k
    InMessageExpressionRAIIObject InMessage(*this, false);
3138
3139
707k
    Result = ParseExpression(MaybeTypeCast);
3140
707k
    if (!getLangOpts().CPlusPlus && 
MaybeTypeCast310k
&&
Result.isUsable()310k
) {
3141
      // Correct typos in non-C++ code earlier so that implicit-cast-like
3142
      // expressions are parsed correctly.
3143
310k
      Result = Actions.CorrectDelayedTyposInExpr(Result);
3144
310k
    }
3145
3146
707k
    if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3147
707k
        
NextToken().is(tok::ellipsis)199
) {
3148
187
      ExprType = FoldExpr;
3149
187
      return ParseFoldExpression(Result, T);
3150
187
    }
3151
707k
    ExprType = SimpleExpr;
3152
3153
    // Don't build a paren expression unless we actually match a ')'.
3154
707k
    if (!Result.isInvalid() && 
Tok.is(tok::r_paren)706k
)
3155
706k
      Result =
3156
706k
          Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3157
707k
  }
3158
3159
  // Match the ')'.
3160
1.03M
  if (Result.isInvalid()) {
3161
476
    SkipUntil(tok::r_paren, StopAtSemi);
3162
476
    return ExprError();
3163
476
  }
3164
3165
1.03M
  T.consumeClose();
3166
1.03M
  RParenLoc = T.getCloseLocation();
3167
1.03M
  return Result;
3168
1.03M
}
3169
3170
/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3171
/// and we are at the left brace.
3172
///
3173
/// \verbatim
3174
///       postfix-expression: [C99 6.5.2]
3175
///         '(' type-name ')' '{' initializer-list '}'
3176
///         '(' type-name ')' '{' initializer-list ',' '}'
3177
/// \endverbatim
3178
ExprResult
3179
Parser::ParseCompoundLiteralExpression(ParsedType Ty,
3180
                                       SourceLocation LParenLoc,
3181
53.3k
                                       SourceLocation RParenLoc) {
3182
53.3k
  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3183
53.3k
  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
3184
6.81k
    Diag(LParenLoc, diag::ext_c99_compound_literal);
3185
53.3k
  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
3186
53.3k
  ExprResult Result = ParseInitializer();
3187
53.3k
  if (!Result.isInvalid() && 
Ty53.3k
)
3188
53.3k
    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3189
6
  return Result;
3190
53.3k
}
3191
3192
/// ParseStringLiteralExpression - This handles the various token types that
3193
/// form string literals, and also handles string concatenation [C99 5.1.1.2,
3194
/// translation phase #6].
3195
///
3196
/// \verbatim
3197
///       primary-expression: [C99 6.5.1]
3198
///         string-literal
3199
/// \verbatim
3200
3.97M
ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3201
3.97M
  assert(isTokenStringLiteral() && "Not a string literal!");
3202
3203
  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
3204
  // considered to be strings for concatenation purposes.
3205
0
  SmallVector<Token, 4> StringToks;
3206
3207
4.14M
  do {
3208
4.14M
    StringToks.push_back(Tok);
3209
4.14M
    ConsumeStringToken();
3210
4.14M
  } while (isTokenStringLiteral());
3211
3212
  // Pass the set of string tokens, ready for concatenation, to the actions.
3213
3.97M
  return Actions.ActOnStringLiteral(StringToks,
3214
3.97M
                                    AllowUserDefinedLiteral ? 
getCurScope()3.08M
3215
3.97M
                                                            : 
nullptr893k
);
3216
3.97M
}
3217
3218
/// ParseGenericSelectionExpression - Parse a C11 generic-selection
3219
/// [C11 6.5.1.1].
3220
///
3221
/// \verbatim
3222
///    generic-selection:
3223
///           _Generic ( assignment-expression , generic-assoc-list )
3224
///    generic-assoc-list:
3225
///           generic-association
3226
///           generic-assoc-list , generic-association
3227
///    generic-association:
3228
///           type-name : assignment-expression
3229
///           default : assignment-expression
3230
/// \endverbatim
3231
215
ExprResult Parser::ParseGenericSelectionExpression() {
3232
215
  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3233
215
  if (!getLangOpts().C11)
3234
68
    Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3235
3236
215
  SourceLocation KeyLoc = ConsumeToken();
3237
215
  BalancedDelimiterTracker T(*this, tok::l_paren);
3238
215
  if (T.expectAndConsume())
3239
1
    return ExprError();
3240
3241
214
  ExprResult ControllingExpr;
3242
214
  {
3243
    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3244
    // not evaluated."
3245
214
    EnterExpressionEvaluationContext Unevaluated(
3246
214
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3247
214
    ControllingExpr =
3248
214
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3249
214
    if (ControllingExpr.isInvalid()) {
3250
1
      SkipUntil(tok::r_paren, StopAtSemi);
3251
1
      return ExprError();
3252
1
    }
3253
214
  }
3254
3255
213
  if (ExpectAndConsume(tok::comma)) {
3256
1
    SkipUntil(tok::r_paren, StopAtSemi);
3257
1
    return ExprError();
3258
1
  }
3259
3260
212
  SourceLocation DefaultLoc;
3261
212
  TypeVector Types;
3262
212
  ExprVector Exprs;
3263
458
  do {
3264
458
    ParsedType Ty;
3265
458
    if (Tok.is(tok::kw_default)) {
3266
      // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3267
      // generic association."
3268
102
      if (!DefaultLoc.isInvalid()) {
3269
1
        Diag(Tok, diag::err_duplicate_default_assoc);
3270
1
        Diag(DefaultLoc, diag::note_previous_default_assoc);
3271
1
        SkipUntil(tok::r_paren, StopAtSemi);
3272
1
        return ExprError();
3273
1
      }
3274
101
      DefaultLoc = ConsumeToken();
3275
101
      Ty = nullptr;
3276
356
    } else {
3277
356
      ColonProtectionRAIIObject X(*this);
3278
356
      TypeResult TR = ParseTypeName();
3279
356
      if (TR.isInvalid()) {
3280
0
        SkipUntil(tok::r_paren, StopAtSemi);
3281
0
        return ExprError();
3282
0
      }
3283
356
      Ty = TR.get();
3284
356
    }
3285
457
    Types.push_back(Ty);
3286
3287
457
    if (ExpectAndConsume(tok::colon)) {
3288
1
      SkipUntil(tok::r_paren, StopAtSemi);
3289
1
      return ExprError();
3290
1
    }
3291
3292
    // FIXME: These expressions should be parsed in a potentially potentially
3293
    // evaluated context.
3294
456
    ExprResult ER(
3295
456
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3296
456
    if (ER.isInvalid()) {
3297
0
      SkipUntil(tok::r_paren, StopAtSemi);
3298
0
      return ExprError();
3299
0
    }
3300
456
    Exprs.push_back(ER.get());
3301
456
  } while (TryConsumeToken(tok::comma));
3302
3303
210
  T.consumeClose();
3304
210
  if (T.getCloseLocation().isInvalid())
3305
0
    return ExprError();
3306
3307
210
  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3308
210
                                           T.getCloseLocation(),
3309
210
                                           ControllingExpr.get(),
3310
210
                                           Types, Exprs);
3311
210
}
3312
3313
/// Parse A C++1z fold-expression after the opening paren and optional
3314
/// left-hand-side expression.
3315
///
3316
/// \verbatim
3317
///   fold-expression:
3318
///       ( cast-expression fold-operator ... )
3319
///       ( ... fold-operator cast-expression )
3320
///       ( cast-expression fold-operator ... fold-operator cast-expression )
3321
ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3322
241
                                       BalancedDelimiterTracker &T) {
3323
241
  if (LHS.isInvalid()) {
3324
1
    T.skipToEnd();
3325
1
    return true;
3326
1
  }
3327
3328
240
  tok::TokenKind Kind = tok::unknown;
3329
240
  SourceLocation FirstOpLoc;
3330
240
  if (LHS.isUsable()) {
3331
216
    Kind = Tok.getKind();
3332
216
    assert(isFoldOperator(Kind) && "missing fold-operator");
3333
0
    FirstOpLoc = ConsumeToken();
3334
216
  }
3335
3336
0
  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3337
0
  SourceLocation EllipsisLoc = ConsumeToken();
3338
3339
240
  ExprResult RHS;
3340
240
  if (Tok.isNot(tok::r_paren)) {
3341
84
    if (!isFoldOperator(Tok.getKind()))
3342
1
      return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3343
3344
83
    if (Kind != tok::unknown && 
Tok.getKind() != Kind59
)
3345
2
      Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3346
2
        << SourceRange(FirstOpLoc);
3347
83
    Kind = Tok.getKind();
3348
83
    ConsumeToken();
3349
3350
83
    RHS = ParseExpression();
3351
83
    if (RHS.isInvalid()) {
3352
0
      T.skipToEnd();
3353
0
      return true;
3354
0
    }
3355
83
  }
3356
3357
239
  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3358
239
                        ? 
diag::warn_cxx14_compat_fold_expression201
3359
239
                        : 
diag::ext_fold_expression38
);
3360
3361
239
  T.consumeClose();
3362
239
  return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3363
239
                                  Kind, EllipsisLoc, RHS.get(),
3364
239
                                  T.getCloseLocation());
3365
240
}
3366
3367
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3368
///
3369
/// \verbatim
3370
///       argument-expression-list:
3371
///         assignment-expression
3372
///         argument-expression-list , assignment-expression
3373
///
3374
/// [C++] expression-list:
3375
/// [C++]   assignment-expression
3376
/// [C++]   expression-list , assignment-expression
3377
///
3378
/// [C++0x] expression-list:
3379
/// [C++0x]   initializer-list
3380
///
3381
/// [C++0x] initializer-list
3382
/// [C++0x]   initializer-clause ...[opt]
3383
/// [C++0x]   initializer-list , initializer-clause ...[opt]
3384
///
3385
/// [C++0x] initializer-clause:
3386
/// [C++0x]   assignment-expression
3387
/// [C++0x]   braced-init-list
3388
/// \endverbatim
3389
bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3390
                                 SmallVectorImpl<SourceLocation> &CommaLocs,
3391
                                 llvm::function_ref<void()> ExpressionStarts,
3392
                                 bool FailImmediatelyOnInvalidExpr,
3393
8.29M
                                 bool EarlyTypoCorrection) {
3394
8.29M
  bool SawError = false;
3395
13.5M
  while (true) {
3396
13.5M
    if (ExpressionStarts)
3397
9.14M
      ExpressionStarts();
3398
3399
13.5M
    ExprResult Expr;
3400
13.5M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)5.20M
) {
3401
1.86k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3402
1.86k
      Expr = ParseBraceInitializer();
3403
1.86k
    } else
3404
13.5M
      Expr = ParseAssignmentExpression();
3405
3406
13.5M
    if (EarlyTypoCorrection)
3407
4.37M
      Expr = Actions.CorrectDelayedTyposInExpr(Expr);
3408
3409
13.5M
    if (Tok.is(tok::ellipsis))
3410
33.7k
      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3411
13.4M
    else if (Tok.is(tok::code_completion)) {
3412
      // There's nothing to suggest in here as we parsed a full expression.
3413
      // Instead fail and propogate the error since caller might have something
3414
      // the suggest, e.g. signature help in function call. Note that this is
3415
      // performed before pushing the \p Expr, so that signature help can report
3416
      // current argument correctly.
3417
1
      SawError = true;
3418
1
      cutOffParsing();
3419
1
      break;
3420
1
    }
3421
13.5M
    if (Expr.isInvalid()) {
3422
3.43k
      SawError = true;
3423
3.43k
      if (FailImmediatelyOnInvalidExpr)
3424
45
        break;
3425
3.39k
      SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3426
13.5M
    } else {
3427
13.5M
      Exprs.push_back(Expr.get());
3428
13.5M
    }
3429
3430
13.5M
    if (Tok.isNot(tok::comma))
3431
8.29M
      break;
3432
    // Move to the next argument, remember where the comma was.
3433
5.23M
    Token Comma = Tok;
3434
5.23M
    CommaLocs.push_back(ConsumeToken());
3435
3436
5.23M
    checkPotentialAngleBracketDelimiter(Comma);
3437
5.23M
  }
3438
8.29M
  if (SawError) {
3439
    // Ensure typos get diagnosed when errors were encountered while parsing the
3440
    // expression list.
3441
3.43k
    for (auto &E : Exprs) {
3442
3.10k
      ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
3443
3.10k
      if (Expr.isUsable()) 
E = Expr.get()2.36k
;
3444
3.10k
    }
3445
3.43k
  }
3446
8.29M
  return SawError;
3447
8.29M
}
3448
3449
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3450
/// used for misc language extensions.
3451
///
3452
/// \verbatim
3453
///       simple-expression-list:
3454
///         assignment-expression
3455
///         simple-expression-list , assignment-expression
3456
/// \endverbatim
3457
bool
3458
Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
3459
321k
                                  SmallVectorImpl<SourceLocation> &CommaLocs) {
3460
344k
  while (true) {
3461
344k
    ExprResult Expr = ParseAssignmentExpression();
3462
344k
    if (Expr.isInvalid())
3463
9
      return true;
3464
3465
344k
    Exprs.push_back(Expr.get());
3466
3467
344k
    if (Tok.isNot(tok::comma))
3468
321k
      return false;
3469
3470
    // Move to the next argument, remember where the comma was.
3471
23.1k
    Token Comma = Tok;
3472
23.1k
    CommaLocs.push_back(ConsumeToken());
3473
3474
23.1k
    checkPotentialAngleBracketDelimiter(Comma);
3475
23.1k
  }
3476
321k
}
3477
3478
/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3479
///
3480
/// \verbatim
3481
/// [clang] block-id:
3482
/// [clang]   specifier-qualifier-list block-declarator
3483
/// \endverbatim
3484
347
void Parser::ParseBlockId(SourceLocation CaretLoc) {
3485
347
  if (Tok.is(tok::code_completion)) {
3486
1
    cutOffParsing();
3487
1
    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
3488
1
    return;
3489
1
  }
3490
3491
  // Parse the specifier-qualifier-list piece.
3492
346
  DeclSpec DS(AttrFactory);
3493
346
  ParseSpecifierQualifierList(DS);
3494
3495
  // Parse the block-declarator.
3496
346
  Declarator DeclaratorInfo(DS, DeclaratorContext::BlockLiteral);
3497
346
  DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3498
346
  ParseDeclarator(DeclaratorInfo);
3499
3500
346
  MaybeParseGNUAttributes(DeclaratorInfo);
3501
3502
  // Inform sema that we are starting a block.
3503
346
  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3504
346
}
3505
3506
/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3507
/// like ^(int x){ return x+1; }
3508
///
3509
/// \verbatim
3510
///         block-literal:
3511
/// [clang]   '^' block-args[opt] compound-statement
3512
/// [clang]   '^' block-id compound-statement
3513
/// [clang] block-args:
3514
/// [clang]   '(' parameter-list ')'
3515
/// \endverbatim
3516
3.33k
ExprResult Parser::ParseBlockLiteralExpression() {
3517
3.33k
  assert(Tok.is(tok::caret) && "block literal starts with ^");
3518
0
  SourceLocation CaretLoc = ConsumeToken();
3519
3520
3.33k
  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3521
3.33k
                                "block literal parsing");
3522
3523
  // Enter a scope to hold everything within the block.  This includes the
3524
  // argument decls, decls within the compound expression, etc.  This also
3525
  // allows determining whether a variable reference inside the block is
3526
  // within or outside of the block.
3527
3.33k
  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3528
3.33k
                                  Scope::CompoundStmtScope | Scope::DeclScope);
3529
3530
  // Inform sema that we are starting a block.
3531
3.33k
  Actions.ActOnBlockStart(CaretLoc, getCurScope());
3532
3533
  // Parse the return type if present.
3534
3.33k
  DeclSpec DS(AttrFactory);
3535
3.33k
  Declarator ParamInfo(DS, DeclaratorContext::BlockLiteral);
3536
3.33k
  ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3537
  // FIXME: Since the return type isn't actually parsed, it can't be used to
3538
  // fill ParamInfo with an initial valid range, so do it manually.
3539
3.33k
  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3540
3541
  // If this block has arguments, parse them.  There is no ambiguity here with
3542
  // the expression case, because the expression case requires a parameter list.
3543
3.33k
  if (Tok.is(tok::l_paren)) {
3544
1.28k
    ParseParenDeclarator(ParamInfo);
3545
    // Parse the pieces after the identifier as if we had "int(...)".
3546
    // SetIdentifier sets the source range end, but in this case we're past
3547
    // that location.
3548
1.28k
    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3549
1.28k
    ParamInfo.SetIdentifier(nullptr, CaretLoc);
3550
1.28k
    ParamInfo.SetRangeEnd(Tmp);
3551
1.28k
    if (ParamInfo.isInvalidType()) {
3552
      // If there was an error parsing the arguments, they may have
3553
      // tried to use ^(x+y) which requires an argument list.  Just
3554
      // skip the whole block literal.
3555
0
      Actions.ActOnBlockError(CaretLoc, getCurScope());
3556
0
      return ExprError();
3557
0
    }
3558
3559
1.28k
    MaybeParseGNUAttributes(ParamInfo);
3560
3561
    // Inform sema that we are starting a block.
3562
1.28k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3563
2.04k
  } else if (!Tok.is(tok::l_brace)) {
3564
347
    ParseBlockId(CaretLoc);
3565
1.69k
  } else {
3566
    // Otherwise, pretend we saw (void).
3567
1.69k
    SourceLocation NoLoc;
3568
1.69k
    ParamInfo.AddTypeInfo(
3569
1.69k
        DeclaratorChunk::getFunction(/*HasProto=*/true,
3570
1.69k
                                     /*IsAmbiguous=*/false,
3571
1.69k
                                     /*RParenLoc=*/NoLoc,
3572
1.69k
                                     /*ArgInfo=*/nullptr,
3573
1.69k
                                     /*NumParams=*/0,
3574
1.69k
                                     /*EllipsisLoc=*/NoLoc,
3575
1.69k
                                     /*RParenLoc=*/NoLoc,
3576
1.69k
                                     /*RefQualifierIsLvalueRef=*/true,
3577
1.69k
                                     /*RefQualifierLoc=*/NoLoc,
3578
1.69k
                                     /*MutableLoc=*/NoLoc, EST_None,
3579
1.69k
                                     /*ESpecRange=*/SourceRange(),
3580
1.69k
                                     /*Exceptions=*/nullptr,
3581
1.69k
                                     /*ExceptionRanges=*/nullptr,
3582
1.69k
                                     /*NumExceptions=*/0,
3583
1.69k
                                     /*NoexceptExpr=*/nullptr,
3584
1.69k
                                     /*ExceptionSpecTokens=*/nullptr,
3585
1.69k
                                     /*DeclsInPrototype=*/None, CaretLoc,
3586
1.69k
                                     CaretLoc, ParamInfo),
3587
1.69k
        CaretLoc);
3588
3589
1.69k
    MaybeParseGNUAttributes(ParamInfo);
3590
3591
    // Inform sema that we are starting a block.
3592
1.69k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3593
1.69k
  }
3594
3595
3596
3.33k
  ExprResult Result(true);
3597
3.33k
  if (!Tok.is(tok::l_brace)) {
3598
    // Saw something like: ^expr
3599
131
    Diag(Tok, diag::err_expected_expression);
3600
131
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3601
131
    return ExprError();
3602
131
  }
3603
3604
3.20k
  StmtResult Stmt(ParseCompoundStatementBody());
3605
3.20k
  BlockScope.Exit();
3606
3.20k
  if (!Stmt.isInvalid())
3607
3.20k
    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3608
0
  else
3609
0
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3610
3.20k
  return Result;
3611
3.33k
}
3612
3613
/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3614
///
3615
///         '__objc_yes'
3616
///         '__objc_no'
3617
923
ExprResult Parser::ParseObjCBoolLiteral() {
3618
923
  tok::TokenKind Kind = Tok.getKind();
3619
923
  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3620
923
}
3621
3622
/// Validate availability spec list, emitting diagnostics if necessary. Returns
3623
/// true if invalid.
3624
static bool CheckAvailabilitySpecList(Parser &P,
3625
109
                                      ArrayRef<AvailabilitySpec> AvailSpecs) {
3626
109
  llvm::SmallSet<StringRef, 4> Platforms;
3627
109
  bool HasOtherPlatformSpec = false;
3628
109
  bool Valid = true;
3629
226
  for (const auto &Spec : AvailSpecs) {
3630
226
    if (Spec.isOtherPlatformSpec()) {
3631
108
      if (HasOtherPlatformSpec) {
3632
0
        P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3633
0
        Valid = false;
3634
0
      }
3635
3636
108
      HasOtherPlatformSpec = true;
3637
108
      continue;
3638
108
    }
3639
3640
118
    bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3641
118
    if (!Inserted) {
3642
      // Rule out multiple version specs referring to the same platform.
3643
      // For example, we emit an error for:
3644
      // @available(macos 10.10, macos 10.11, *)
3645
1
      StringRef Platform = Spec.getPlatform();
3646
1
      P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3647
1
          << Spec.getEndLoc() << Platform;
3648
1
      Valid = false;
3649
1
    }
3650
118
  }
3651
3652
109
  if (!HasOtherPlatformSpec) {
3653
1
    SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3654
1
    P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3655
1
        << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3656
1
    return true;
3657
1
  }
3658
3659
108
  return !Valid;
3660
109
}
3661
3662
/// Parse availability query specification.
3663
///
3664
///  availability-spec:
3665
///     '*'
3666
///     identifier version-tuple
3667
237
Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3668
237
  if (Tok.is(tok::star)) {
3669
110
    return AvailabilitySpec(ConsumeToken());
3670
127
  } else {
3671
    // Parse the platform name.
3672
127
    if (Tok.is(tok::code_completion)) {
3673
2
      cutOffParsing();
3674
2
      Actions.CodeCompleteAvailabilityPlatformName();
3675
2
      return None;
3676
2
    }
3677
125
    if (Tok.isNot(tok::identifier)) {
3678
2
      Diag(Tok, diag::err_avail_query_expected_platform_name);
3679
2
      return None;
3680
2
    }
3681
3682
123
    IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3683
123
    SourceRange VersionRange;
3684
123
    VersionTuple Version = ParseVersionTuple(VersionRange);
3685
3686
123
    if (Version.empty())
3687
1
      return None;
3688
3689
122
    StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3690
122
    StringRef Platform =
3691
122
        AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3692
3693
122
    if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3694
3
      Diag(PlatformIdentifier->Loc,
3695
3
           diag::err_avail_query_unrecognized_platform_name)
3696
3
          << GivenPlatform;
3697
3
      return None;
3698
3
    }
3699
3700
119
    return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3701
119
                            VersionRange.getEnd());
3702
122
  }
3703
237
}
3704
3705
117
ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3706
117
  assert(Tok.is(tok::kw___builtin_available) ||
3707
117
         Tok.isObjCAtKeyword(tok::objc_available));
3708
3709
  // Eat the available or __builtin_available.
3710
0
  ConsumeToken();
3711
3712
117
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3713
117
  if (Parens.expectAndConsume())
3714
1
    return ExprError();
3715
3716
116
  SmallVector<AvailabilitySpec, 4> AvailSpecs;
3717
116
  bool HasError = false;
3718
237
  while (true) {
3719
237
    Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3720
237
    if (!Spec)
3721
8
      HasError = true;
3722
229
    else
3723
229
      AvailSpecs.push_back(*Spec);
3724
3725
237
    if (!TryConsumeToken(tok::comma))
3726
116
      break;
3727
237
  }
3728
3729
116
  if (HasError) {
3730
7
    SkipUntil(tok::r_paren, StopAtSemi);
3731
7
    return ExprError();
3732
7
  }
3733
3734
109
  CheckAvailabilitySpecList(*this, AvailSpecs);
3735
3736
109
  if (Parens.consumeClose())
3737
0
    return ExprError();
3738
3739
109
  return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3740
109
                                                Parens.getCloseLocation());
3741
109
}