Coverage Report

Created: 2022-07-16 07:03

/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
8.40M
ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
124
8.40M
  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
125
8.40M
  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
126
8.40M
}
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
27.9M
ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
161
27.9M
  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
27.9M
  if (Tok.is(tok::kw_throw))
169
17.9k
    return ParseThrowExpression();
170
27.9M
  if (Tok.is(tok::kw_co_yield))
171
293
    return ParseCoyieldExpression();
172
173
27.9M
  ExprResult LHS = ParseCastExpression(AnyCastExpr,
174
27.9M
                                       /*isAddressOfOperand=*/false,
175
27.9M
                                       isTypeCast);
176
27.9M
  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
177
27.9M
}
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.78M
Parser::ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast) {
202
4.78M
  assert(Actions.ExprEvalContexts.back().Context ==
203
4.78M
             Sema::ExpressionEvaluationContext::ConstantEvaluated &&
204
4.78M
         "Call this function only if your ExpressionEvaluationContext is "
205
4.78M
         "already ConstantEvaluated");
206
0
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
207
4.78M
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
208
4.78M
  return Actions.ActOnConstantExpression(Res);
209
4.78M
}
210
211
194k
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
194k
  EnterExpressionEvaluationContext ConstantEvaluated(
217
194k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
218
194k
  return ParseConstantExpressionInExprEvalContext(isTypeCast);
219
194k
}
220
221
23.6k
ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
222
23.6k
  EnterExpressionEvaluationContext ConstantEvaluated(
223
23.6k
      Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
224
23.6k
  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
225
23.6k
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
226
23.6k
  return Actions.ActOnCaseExpr(CaseLoc, Res);
227
23.6k
}
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
1.18k
ExprResult Parser::ParseConstraintExpression() {
236
1.18k
  EnterExpressionEvaluationContext ConstantEvaluated(
237
1.18k
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
238
1.18k
  ExprResult LHS(ParseCastExpression(AnyCastExpr));
239
1.18k
  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
240
1.18k
  if (Res.isUsable() && 
!Actions.CheckConstraintExpression(Res.get())1.18k
) {
241
6
    Actions.CorrectDelayedTyposInExpr(Res);
242
6
    return ExprError();
243
6
  }
244
1.17k
  return Res;
245
1.18k
}
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
2.09k
Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
258
2.09k
  EnterExpressionEvaluationContext ConstantEvaluated(
259
2.09k
      Actions, Sema::ExpressionEvaluationContext::Unevaluated);
260
2.09k
  bool NotPrimaryExpression = false;
261
2.45k
  auto ParsePrimary = [&] () {
262
2.45k
    ExprResult E = ParseCastExpression(PrimaryExprOnly,
263
2.45k
                                       /*isAddressOfOperand=*/false,
264
2.45k
                                       /*isTypeCast=*/NotTypeCast,
265
2.45k
                                       /*isVectorLiteral=*/false,
266
2.45k
                                       &NotPrimaryExpression);
267
2.45k
    if (E.isInvalid())
268
8
      return ExprError();
269
2.45k
    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
2.45k
    if (NotPrimaryExpression ||
287
        // Check if the following tokens must be a part of a non-primary
288
        // expression
289
2.45k
        getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
290
2.44k
                           /*CPlusPlus11=*/true) > prec::LogicalAnd ||
291
        // Postfix operators other than '(' (which will be checked for in
292
        // CheckConstraintExpression).
293
2.45k
        
Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus)2.43k
||
294
2.45k
        
(2.43k
Tok.is(tok::l_square)2.43k
&&
!NextToken().is(tok::l_square)134
)) {
295
12
      E = RecoverFromNonPrimary(E, /*Note=*/false);
296
12
      if (E.isInvalid())
297
0
        return ExprError();
298
12
      NotPrimaryExpression = false;
299
12
    }
300
2.45k
    bool PossibleNonPrimary;
301
2.45k
    bool IsConstraintExpr =
302
2.45k
        Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
303
2.45k
                                          IsTrailingRequiresClause);
304
2.45k
    if (!IsConstraintExpr || 
PossibleNonPrimary2.44k
) {
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
2.43k
    return E;
315
2.45k
  };
316
2.09k
  ExprResult LHS = ParsePrimary();
317
2.09k
  if (LHS.isInvalid())
318
20
    return ExprError();
319
2.43k
  
while (2.07k
Tok.is(tok::ampamp)) {
320
367
    SourceLocation LogicalAndLoc = ConsumeToken();
321
367
    ExprResult RHS = ParsePrimary();
322
367
    if (RHS.isInvalid()) {
323
0
      Actions.CorrectDelayedTyposInExpr(LHS);
324
0
      return ExprError();
325
0
    }
326
367
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
327
367
                                       tok::ampamp, LHS.get(), RHS.get());
328
367
    if (!Op.isUsable()) {
329
0
      Actions.CorrectDelayedTyposInExpr(RHS);
330
0
      Actions.CorrectDelayedTyposInExpr(LHS);
331
0
      return ExprError();
332
0
    }
333
367
    LHS = Op;
334
367
  }
335
2.07k
  return LHS;
336
2.07k
}
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
2.07k
Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
350
2.07k
  ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
351
2.07k
  if (!LHS.isUsable())
352
20
    return ExprError();
353
2.07k
  
while (2.05k
Tok.is(tok::pipepipe)) {
354
15
    SourceLocation LogicalOrLoc = ConsumeToken();
355
15
    ExprResult RHS =
356
15
        ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
357
15
    if (!RHS.isUsable()) {
358
0
      Actions.CorrectDelayedTyposInExpr(LHS);
359
0
      return ExprError();
360
0
    }
361
15
    ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
362
15
                                       tok::pipepipe, LHS.get(), RHS.get());
363
15
    if (!Op.isUsable()) {
364
0
      Actions.CorrectDelayedTyposInExpr(RHS);
365
0
      Actions.CorrectDelayedTyposInExpr(LHS);
366
0
      return ExprError();
367
0
    }
368
15
    LHS = Op;
369
15
  }
370
2.05k
  return LHS;
371
2.05k
}
372
373
44.6k
bool Parser::isNotExpressionStart() {
374
44.6k
  tok::TokenKind K = Tok.getKind();
375
44.6k
  if (K == tok::l_brace || 
K == tok::r_brace44.6k
||
376
44.6k
      
K == tok::kw_for44.6k
||
K == tok::kw_while44.6k
||
377
44.6k
      
K == tok::kw_if44.6k
||
K == tok::kw_else44.6k
||
378
44.6k
      
K == tok::kw_goto44.6k
||
K == tok::kw_try44.6k
)
379
5
    return true;
380
  // If this is a decl-specifier, we can't be at the start of an expression.
381
44.6k
  return isKnownToBeDeclarationSpecifier();
382
44.6k
}
383
384
5.32M
bool Parser::isFoldOperator(prec::Level Level) const {
385
5.32M
  return Level > prec::Unknown && 
Level != prec::Conditional4.17M
&&
386
5.32M
         
Level != prec::Spaceship4.11M
;
387
5.32M
}
388
389
1.14M
bool Parser::isFoldOperator(tok::TokenKind Kind) const {
390
1.14M
  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
391
1.14M
}
392
393
/// Parse a binary expression that starts with \p LHS and has a
394
/// precedence of at least \p MinPrec.
395
ExprResult
396
41.3M
Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
397
41.3M
  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
398
41.3M
                                               GreaterThanIsOperator,
399
41.3M
                                               getLangOpts().CPlusPlus11);
400
41.3M
  SourceLocation ColonLoc;
401
402
41.3M
  auto SavedType = PreferredType;
403
45.5M
  while (true) {
404
    // Every iteration may rely on a preferred type for the whole expression.
405
45.5M
    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
45.5M
    if (NextTokPrec < MinPrec)
410
41.3M
      return LHS;
411
412
    // Consume the operator, saving the operator token for error reporting.
413
4.17M
    Token OpToken = Tok;
414
4.17M
    ConsumeToken();
415
416
4.17M
    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
4.17M
    if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
423
4.17M
                        tok::greatergreatergreater) &&
424
4.17M
        
checkPotentialAngleBracketDelimiter(OpToken)209k
)
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
4.17M
    if (OpToken.is(tok::comma) && 
isNotExpressionStart()44.6k
) {
433
9
      PP.EnterToken(Tok, /*IsReinject*/true);
434
9
      Tok = OpToken;
435
9
      return LHS;
436
9
    }
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
4.17M
    if (isFoldOperator(NextTokPrec) && 
Tok.is(tok::ellipsis)4.11M
) {
441
      // FIXME: We can't check this via lookahead before we consume the token
442
      // because that tickles a lexer bug.
443
402
      PP.EnterToken(Tok, /*IsReinject*/true);
444
402
      Tok = OpToken;
445
402
      return LHS;
446
402
    }
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
4.17M
    if (getLangOpts().ObjC && 
getLangOpts().CPlusPlus673k
&&
454
4.17M
        
Tok.isOneOf(tok::colon, tok::r_square)232k
&&
455
4.17M
        
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
4.17M
    ExprResult TernaryMiddle(true);
463
4.17M
    if (NextTokPrec == prec::Conditional) {
464
60.3k
      if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)50.2k
) {
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
60.3k
      } else if (Tok.isNot(tok::colon)) {
475
        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
476
60.1k
        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
60.1k
        TernaryMiddle = ParseExpression();
483
60.1k
      } else {
484
        // Special case handling of "X ? Y : Z" where Y is empty:
485
        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
486
276
        TernaryMiddle = nullptr;
487
276
        Diag(Tok, diag::ext_gnu_conditional_expr);
488
276
      }
489
490
60.3k
      if (TernaryMiddle.isInvalid()) {
491
26
        Actions.CorrectDelayedTyposInExpr(LHS);
492
26
        LHS = ExprError();
493
26
        TernaryMiddle = nullptr;
494
26
      }
495
496
60.3k
      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
60.3k
    }
525
526
0
    PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
527
4.17M
                              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
4.17M
    ExprResult RHS;
539
4.17M
    bool RHSIsInitList = false;
540
4.17M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)2.97M
) {
541
87
      RHS = ParseBraceInitializer();
542
87
      RHSIsInitList = true;
543
4.17M
    } else if (getLangOpts().CPlusPlus && 
NextTokPrec <= prec::Conditional3.01M
)
544
867k
      RHS = ParseAssignmentExpression();
545
3.30M
    else
546
3.30M
      RHS = ParseCastExpression(AnyCastExpr);
547
548
4.17M
    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
796
      Actions.CorrectDelayedTyposInExpr(LHS);
552
796
      if (TernaryMiddle.isUsable())
553
4
        TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
554
796
      LHS = ExprError();
555
796
    }
556
557
    // Remember the precedence of this operator and get the precedence of the
558
    // operator immediately to the right of the RHS.
559
4.17M
    prec::Level ThisPrec = NextTokPrec;
560
4.17M
    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
561
4.17M
                                     getLangOpts().CPlusPlus11);
562
563
    // Assignment and conditional expressions are right-associative.
564
4.17M
    bool isRightAssoc = ThisPrec == prec::Conditional ||
565
4.17M
                        
ThisPrec == prec::Assignment4.11M
;
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
4.17M
    if (ThisPrec < NextTokPrec ||
570
4.17M
        
(3.99M
ThisPrec == NextTokPrec3.99M
&&
isRightAssoc142k
)) {
571
178k
      if (!RHS.isInvalid() && 
RHSIsInitList178k
) {
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
178k
      RHS = ParseRHSOfBinaryExpression(RHS,
582
178k
                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
583
178k
      RHSIsInitList = false;
584
585
178k
      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
178k
      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
595
178k
                                       getLangOpts().CPlusPlus11);
596
178k
    }
597
598
4.17M
    if (!RHS.isInvalid() && 
RHSIsInitList4.17M
) {
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
4.17M
    ExprResult OrigLHS = LHS;
616
4.17M
    if (!LHS.isInvalid()) {
617
      // Combine the LHS and RHS into the LHS (e.g. build AST).
618
4.17M
      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
4.11M
        if (!GreaterThanIsOperator && 
OpToken.is(tok::greatergreater)136k
)
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
4.11M
        ExprResult BinOp =
629
4.11M
            Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
630
4.11M
                               OpToken.getKind(), LHS.get(), RHS.get());
631
4.11M
        if (BinOp.isInvalid())
632
5.46k
          BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
633
5.46k
                                             RHS.get()->getEndLoc(),
634
5.46k
                                             {LHS.get(), RHS.get()});
635
636
4.11M
        LHS = BinOp;
637
4.11M
      } else {
638
60.2k
        ExprResult CondOp = Actions.ActOnConditionalOp(
639
60.2k
            OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
640
60.2k
            RHS.get());
641
60.2k
        if (CondOp.isInvalid()) {
642
362
          std::vector<clang::Expr *> Args;
643
          // TernaryMiddle can be null for the GNU conditional expr extension.
644
362
          if (TernaryMiddle.get())
645
351
            Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
646
11
          else
647
11
            Args = {LHS.get(), RHS.get()};
648
362
          CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
649
362
                                              RHS.get()->getEndLoc(), Args);
650
362
        }
651
652
60.2k
        LHS = CondOp;
653
60.2k
      }
654
      // In this case, ActOnBinOp or ActOnConditionalOp performed the
655
      // CorrectDelayedTyposInExpr check.
656
4.17M
      if (!getLangOpts().CPlusPlus)
657
1.16M
        continue;
658
4.17M
    }
659
660
    // Ensure potential typos aren't left undiagnosed.
661
3.01M
    if (LHS.isInvalid()) {
662
1.34k
      Actions.CorrectDelayedTyposInExpr(OrigLHS);
663
1.34k
      Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
664
1.34k
      Actions.CorrectDelayedTyposInExpr(RHS);
665
1.34k
    }
666
3.01M
  }
667
41.3M
}
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
42.9M
                                       bool *NotPrimaryExpression) {
680
42.9M
  bool NotCastExpr;
681
42.9M
  ExprResult Res = ParseCastExpression(ParseKind,
682
42.9M
                                       isAddressOfOperand,
683
42.9M
                                       NotCastExpr,
684
42.9M
                                       isTypeCast,
685
42.9M
                                       isVectorLiteral,
686
42.9M
                                       NotPrimaryExpression);
687
42.9M
  if (NotCastExpr)
688
16.2k
    Diag(Tok, diag::err_expected_expression);
689
42.9M
  return Res;
690
42.9M
}
691
692
namespace {
693
class CastExpressionIdValidator final : public CorrectionCandidateCallback {
694
 public:
695
  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
696
15.1M
      : NextToken(Next), AllowNonTypes(AllowNonTypes) {
697
15.1M
    WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
698
15.1M
  }
699
700
446
  bool ValidateCandidate(const TypoCorrection &candidate) override {
701
446
    NamedDecl *ND = candidate.getCorrectionDecl();
702
446
    if (!ND)
703
11
      return candidate.isKeyword();
704
705
435
    if (isa<TypeDecl>(ND))
706
58
      return WantTypeSpecifiers;
707
708
377
    if (!AllowNonTypes || 
!CorrectionCandidateCallback::ValidateCandidate(candidate)365
)
709
12
      return false;
710
711
365
    if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
712
312
      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.23k
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
723
3.23k
    return std::make_unique<CastExpressionIdValidator>(*this);
724
3.23k
  }
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
44.8M
                                       bool *NotPrimaryExpression) {
919
44.8M
  ExprResult Res;
920
44.8M
  tok::TokenKind SavedKind = Tok.getKind();
921
44.8M
  auto SavedType = PreferredType;
922
44.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
44.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
44.8M
  switch (SavedKind) {
940
5.91M
  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.91M
    ParenParseOption ParenExprType;
944
5.91M
    switch (ParseKind) {
945
5.28k
      case CastParseKind::UnaryExprOnly:
946
5.28k
        if (!getLangOpts().CPlusPlus)
947
0
          ParenExprType = CompoundLiteral;
948
5.28k
        LLVM_FALLTHROUGH;
949
5.91M
      case CastParseKind::AnyCastExpr:
950
5.91M
        ParenExprType = ParenParseOption::CastExpr;
951
5.91M
        break;
952
350
      case CastParseKind::PrimaryExprOnly:
953
350
        ParenExprType = FoldExpr;
954
350
        break;
955
5.91M
    }
956
5.91M
    ParsedType CastTy;
957
5.91M
    SourceLocation RParenLoc;
958
5.91M
    Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
959
5.91M
                               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.91M
    if (isVectorLiteral)
965
167
      return Res;
966
967
5.91M
    switch (ParenExprType) {
968
1.13M
    case SimpleExpr:   break;    // Nothing else to do.
969
8.96k
    case CompoundStmt: break;  // Nothing else to do.
970
53.6k
    case CompoundLiteral:
971
      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
972
      // postfix-expression exist, parse them now.
973
53.6k
      break;
974
4.72M
    case CastExpr:
975
      // We have parsed the cast-expression and no postfix-expr pieces are
976
      // following.
977
4.72M
      return Res;
978
264
    case FoldExpr:
979
      // We only parsed a fold-expression. There might be postfix-expr pieces
980
      // afterwards; parse them now.
981
264
      break;
982
5.91M
    }
983
984
1.19M
    break;
985
5.91M
  }
986
987
    // primary-expression
988
7.97M
  case tok::numeric_constant:
989
    // constant: integer-constant
990
    // constant: floating-constant
991
992
7.97M
    Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
993
7.97M
    ConsumeToken();
994
7.97M
    break;
995
996
176k
  case tok::kw_true:
997
347k
  case tok::kw_false:
998
347k
    Res = ParseCXXBoolLiteral();
999
347k
    break;
1000
1001
516
  case tok::kw___objc_yes:
1002
919
  case tok::kw___objc_no:
1003
919
    Res = ParseObjCBoolLiteral();
1004
919
    break;
1005
1006
156k
  case tok::kw_nullptr:
1007
156k
    Diag(Tok, diag::warn_cxx98_compat_nullptr);
1008
156k
    Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
1009
156k
    break;
1010
1011
16
  case tok::annot_primary_expr:
1012
957k
  case tok::annot_overload_set:
1013
957k
    Res = getExprAnnotation(Tok);
1014
957k
    if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1015
957k
      Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1016
957k
    ConsumeAnnotationToken();
1017
957k
    if (!Res.isInvalid() && 
Tok.is(tok::less)957k
)
1018
22
      checkPotentialAngleBracket(Res);
1019
957k
    break;
1020
1021
2.22M
  case tok::annot_non_type:
1022
2.22M
  case tok::annot_non_type_dependent:
1023
2.22M
  case tok::annot_non_type_undeclared: {
1024
2.22M
    CXXScopeSpec SS;
1025
2.22M
    Token Replacement;
1026
2.22M
    Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1027
2.22M
    assert(!Res.isUnset() &&
1028
2.22M
           "should not perform typo correction on annotation token");
1029
0
    break;
1030
2.22M
  }
1031
1032
3
  case tok::kw___super:
1033
3.67k
  case tok::kw_decltype:
1034
    // Annotate the token and tail recurse.
1035
3.67k
    if (TryAnnotateTypeOrScopeToken())
1036
0
      return ExprError();
1037
3.67k
    assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1038
0
    return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1039
3.67k
                               isVectorLiteral, NotPrimaryExpression);
1040
1041
16.7M
  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
16.7M
    if (getLangOpts().CPlusPlus) {
1047
      // Avoid the unnecessary parse-time lookup in the common case
1048
      // where the syntax forbids a type.
1049
9.42M
      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
9.42M
      if (Next.is(tok::l_paren) &&
1055
9.42M
          
Tok.is(tok::identifier)1.29M
&&
1056
9.42M
          
Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()1.29M
) {
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
9.42M
      if ((!ColonIsSacred && 
Next.is(tok::colon)9.06M
) ||
1134
9.42M
          Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1135
9.42M
                       tok::l_brace)) {
1136
        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1137
2.77M
        if (TryAnnotateTypeOrScopeToken())
1138
9
          return ExprError();
1139
2.77M
        if (!Tok.is(tok::identifier))
1140
1.53M
          return ParseCastExpression(ParseKind, isAddressOfOperand,
1141
1.53M
                                     NotCastExpr, isTypeCast,
1142
1.53M
                                     isVectorLiteral,
1143
1.53M
                                     NotPrimaryExpression);
1144
2.77M
      }
1145
9.42M
    }
1146
1147
    // Consume the identifier so that we can see if it is followed by a '(' or
1148
    // '.'.
1149
15.1M
    IdentifierInfo &II = *Tok.getIdentifierInfo();
1150
15.1M
    SourceLocation ILoc = ConsumeToken();
1151
1152
    // Support 'Class.property' and 'super.property' notation.
1153
15.1M
    if (getLangOpts().ObjC && 
Tok.is(tok::period)1.26M
&&
1154
15.1M
        
(34.1k
Actions.getTypeName(II, ILoc, getCurScope())34.1k
||
1155
         // Allow the base to be 'super' if in an objc-method.
1156
34.1k
         
(33.9k
&II == Ident_super33.9k
&&
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
15.1M
    if (getLangOpts().ObjC && 
&II == Ident_super1.26M
&&
!InMessageExpression256
&&
1184
15.1M
        
getCurScope()->isInObjcMethodScope()34
&&
1185
15.1M
        
(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
15.1M
    if (getLangOpts().ObjC &&
1199
15.1M
        
(1.26M
(1.26M
Tok.is(tok::identifier)1.26M
&&
!InMessageExpression11.5k
) ||
1200
1.26M
         
Tok.is(tok::code_completion)1.26M
)) {
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, ParsedAttributesView::none(),
1216
74
                                      DeclaratorContext::TypeName);
1217
74
            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
1218
74
                                                  DeclaratorInfo);
1219
74
            if (Ty.isInvalid())
1220
0
              break;
1221
1222
74
            Res = ParseObjCMessageExpressionBody(SourceLocation(),
1223
74
                                                 SourceLocation(),
1224
74
                                                 Ty.get(), nullptr);
1225
74
            break;
1226
74
          }
1227
161
    }
1228
1229
    // Make sure to pass down the right value for isAddressOfOperand.
1230
15.1M
    if (isAddressOfOperand && 
isPostfixExpressionSuffixStart()117k
)
1231
31.3k
      isAddressOfOperand = false;
1232
1233
    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1234
    // need to know whether or not this identifier is a function designator or
1235
    // not.
1236
15.1M
    UnqualifiedId Name;
1237
15.1M
    CXXScopeSpec ScopeSpec;
1238
15.1M
    SourceLocation TemplateKWLoc;
1239
15.1M
    Token Replacement;
1240
15.1M
    CastExpressionIdValidator Validator(
1241
15.1M
        /*Next=*/Tok,
1242
15.1M
        /*AllowTypes=*/isTypeCast != NotTypeCast,
1243
15.1M
        /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1244
15.1M
    Validator.IsAddressOfOperand = isAddressOfOperand;
1245
15.1M
    if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1246
126
      Validator.WantExpressionKeywords = false;
1247
126
      Validator.WantRemainingKeywords = false;
1248
15.1M
    } else {
1249
15.1M
      Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1250
15.1M
    }
1251
15.1M
    Name.setIdentifier(&II, ILoc);
1252
15.1M
    Res = Actions.ActOnIdExpression(
1253
15.1M
        getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1254
15.1M
        isAddressOfOperand, &Validator,
1255
15.1M
        /*IsInlineAsmIdentifier=*/false,
1256
15.1M
        Tok.is(tok::r_paren) ? 
nullptr3.89M
:
&Replacement11.2M
);
1257
15.1M
    if (!Res.isInvalid() && 
Res.isUnset()15.1M
) {
1258
2
      UnconsumeToken(Replacement);
1259
2
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1260
2
                                 NotCastExpr, isTypeCast,
1261
2
                                 /*isVectorLiteral=*/false,
1262
2
                                 NotPrimaryExpression);
1263
2
    }
1264
15.1M
    if (!Res.isInvalid() && 
Tok.is(tok::less)15.1M
)
1265
232k
      checkPotentialAngleBracket(Res);
1266
15.1M
    break;
1267
15.1M
  }
1268
565k
  case tok::char_constant:     // constant: character-constant
1269
566k
  case tok::wide_char_constant:
1270
567k
  case tok::utf8_char_constant:
1271
567k
  case tok::utf16_char_constant:
1272
567k
  case tok::utf32_char_constant:
1273
567k
    Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1274
567k
    ConsumeToken();
1275
567k
    break;
1276
365
  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
1277
566
  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
1278
575
  case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
1279
588
  case tok::kw___FUNCSIG__:     // primary-expression: __FUNCSIG__ [MS]
1280
596
  case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
1281
602
  case tok::kw_L__FUNCSIG__:    // primary-expression: L__FUNCSIG__ [MS]
1282
821
  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
1283
821
    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1284
821
    ConsumeToken();
1285
821
    break;
1286
4.49M
  case tok::string_literal:    // primary-expression: string-literal
1287
4.49M
  case tok::wide_string_literal:
1288
4.49M
  case tok::utf8_string_literal:
1289
4.49M
  case tok::utf16_string_literal:
1290
4.49M
  case tok::utf32_string_literal:
1291
4.49M
    Res = ParseStringLiteralExpression(true);
1292
4.49M
    break;
1293
316
  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
1294
316
    Res = ParseGenericSelectionExpression();
1295
316
    break;
1296
16
  case tok::kw___builtin_available:
1297
16
    Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1298
16
    break;
1299
1.11k
  case tok::kw___builtin_va_arg:
1300
1.48k
  case tok::kw___builtin_offsetof:
1301
1.54k
  case tok::kw___builtin_choose_expr:
1302
1.59k
  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1303
23.4k
  case tok::kw___builtin_convertvector:
1304
23.4k
  case tok::kw___builtin_COLUMN:
1305
23.4k
  case tok::kw___builtin_FILE:
1306
23.5k
  case tok::kw___builtin_FUNCTION:
1307
23.5k
  case tok::kw___builtin_LINE:
1308
23.5k
  case tok::kw___builtin_source_location:
1309
23.5k
    if (NotPrimaryExpression)
1310
0
      *NotPrimaryExpression = true;
1311
    // This parses the complete suffix; we can return early.
1312
23.5k
    return ParseBuiltinPrimaryExpression();
1313
3.55k
  case tok::kw___null:
1314
3.55k
    Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1315
3.55k
    break;
1316
1317
338k
  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
1318
400k
  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
1319
400k
    if (NotPrimaryExpression)
1320
0
      *NotPrimaryExpression = true;
1321
    // C++ [expr.unary] has:
1322
    //   unary-expression:
1323
    //     ++ cast-expression
1324
    //     -- cast-expression
1325
400k
    Token SavedTok = Tok;
1326
400k
    ConsumeToken();
1327
1328
400k
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1329
400k
                             SavedTok.getLocation());
1330
    // One special case is implicitly handled here: if the preceding tokens are
1331
    // an ambiguous cast expression, such as "(T())++", then we recurse to
1332
    // determine whether the '++' is prefix or postfix.
1333
400k
    Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1334
391k
                                  UnaryExprOnly : 
AnyCastExpr9.55k
,
1335
400k
                              /*isAddressOfOperand*/false, NotCastExpr,
1336
400k
                              NotTypeCast);
1337
400k
    if (NotCastExpr) {
1338
      // If we return with NotCastExpr = true, we must not consume any tokens,
1339
      // so put the token back where we found it.
1340
7
      assert(Res.isInvalid());
1341
0
      UnconsumeToken(SavedTok);
1342
7
      return ExprError();
1343
7
    }
1344
400k
    if (!Res.isInvalid()) {
1345
400k
      Expr *Arg = Res.get();
1346
400k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1347
400k
                                 SavedKind, Arg);
1348
400k
      if (Res.isInvalid())
1349
101
        Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1350
101
                                         Arg->getEndLoc(), Arg);
1351
400k
    }
1352
400k
    return Res;
1353
400k
  }
1354
132k
  case tok::amp: {         // unary-expression: '&' cast-expression
1355
132k
    if (NotPrimaryExpression)
1356
0
      *NotPrimaryExpression = true;
1357
    // Special treatment because of member pointers
1358
132k
    SourceLocation SavedLoc = ConsumeToken();
1359
132k
    PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1360
132k
    Res = ParseCastExpression(AnyCastExpr, true);
1361
132k
    if (!Res.isInvalid()) {
1362
132k
      Expr *Arg = Res.get();
1363
132k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1364
132k
      if (Res.isInvalid())
1365
213
        Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1366
213
                                         Arg);
1367
132k
    }
1368
132k
    return Res;
1369
400k
  }
1370
1371
613k
  case tok::star:          // unary-expression: '*' cast-expression
1372
613k
  case tok::plus:          // unary-expression: '+' cast-expression
1373
1.57M
  case tok::minus:         // unary-expression: '-' cast-expression
1374
1.65M
  case tok::tilde:         // unary-expression: '~' cast-expression
1375
1.85M
  case tok::exclaim:       // unary-expression: '!' cast-expression
1376
1.85M
  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
1377
1.85M
  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
1378
1.85M
    if (NotPrimaryExpression)
1379
0
      *NotPrimaryExpression = true;
1380
1.85M
    SourceLocation SavedLoc = ConsumeToken();
1381
1.85M
    PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1382
1.85M
    Res = ParseCastExpression(AnyCastExpr);
1383
1.85M
    if (!Res.isInvalid()) {
1384
1.85M
      Expr *Arg = Res.get();
1385
1.85M
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1386
1.85M
      if (Res.isInvalid())
1387
193
        Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1388
1.85M
    }
1389
1.85M
    return Res;
1390
1.85M
  }
1391
1392
475
  case tok::kw_co_await: {  // unary-expression: 'co_await' cast-expression
1393
475
    if (NotPrimaryExpression)
1394
0
      *NotPrimaryExpression = true;
1395
475
    SourceLocation CoawaitLoc = ConsumeToken();
1396
475
    Res = ParseCastExpression(AnyCastExpr);
1397
475
    if (!Res.isInvalid())
1398
475
      Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1399
475
    return Res;
1400
1.85M
  }
1401
1402
32.6k
  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1403
    // __extension__ silences extension warnings in the subexpression.
1404
32.6k
    if (NotPrimaryExpression)
1405
0
      *NotPrimaryExpression = true;
1406
32.6k
    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
1407
32.6k
    SourceLocation SavedLoc = ConsumeToken();
1408
32.6k
    Res = ParseCastExpression(AnyCastExpr);
1409
32.6k
    if (!Res.isInvalid())
1410
32.6k
      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1411
32.6k
    return Res;
1412
1.85M
  }
1413
142
  case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
1414
142
    if (!getLangOpts().C11)
1415
76
      Diag(Tok, diag::ext_c11_feature) << Tok.getName();
1416
142
    LLVM_FALLTHROUGH;
1417
6.70k
  case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
1418
9.92k
  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
1419
                           // unary-expression: '__alignof' '(' type-name ')'
1420
136k
  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
1421
                           // unary-expression: 'sizeof' '(' type-name ')'
1422
136k
  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
1423
  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1424
136k
  case tok::kw___builtin_omp_required_simd_align:
1425
136k
    if (NotPrimaryExpression)
1426
4
      *NotPrimaryExpression = true;
1427
136k
    AllowSuffix = false;
1428
136k
    Res = ParseUnaryExprOrTypeTraitExpression();
1429
136k
    break;
1430
321
  case tok::ampamp: {      // unary-expression: '&&' identifier
1431
321
    if (NotPrimaryExpression)
1432
0
      *NotPrimaryExpression = true;
1433
321
    SourceLocation AmpAmpLoc = ConsumeToken();
1434
321
    if (Tok.isNot(tok::identifier))
1435
0
      return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1436
1437
321
    if (getCurScope()->getFnParent() == nullptr)
1438
1
      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1439
1440
320
    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1441
320
    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1442
320
                                                Tok.getLocation());
1443
320
    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1444
320
    ConsumeToken();
1445
320
    AllowSuffix = false;
1446
320
    break;
1447
321
  }
1448
6.36k
  case tok::kw_const_cast:
1449
7.70k
  case tok::kw_dynamic_cast:
1450
16.5k
  case tok::kw_reinterpret_cast:
1451
214k
  case tok::kw_static_cast:
1452
214k
  case tok::kw_addrspace_cast:
1453
214k
    if (NotPrimaryExpression)
1454
0
      *NotPrimaryExpression = true;
1455
214k
    Res = ParseCXXCasts();
1456
214k
    break;
1457
718
  case tok::kw___builtin_bit_cast:
1458
718
    if (NotPrimaryExpression)
1459
0
      *NotPrimaryExpression = true;
1460
718
    Res = ParseBuiltinBitCast();
1461
718
    break;
1462
5.27k
  case tok::kw_typeid:
1463
5.27k
    if (NotPrimaryExpression)
1464
0
      *NotPrimaryExpression = true;
1465
5.27k
    Res = ParseCXXTypeid();
1466
5.27k
    break;
1467
178
  case tok::kw___uuidof:
1468
178
    if (NotPrimaryExpression)
1469
0
      *NotPrimaryExpression = true;
1470
178
    Res = ParseCXXUuidof();
1471
178
    break;
1472
346k
  case tok::kw_this:
1473
346k
    Res = ParseCXXThis();
1474
346k
    break;
1475
74
  case tok::kw___builtin_sycl_unique_stable_name:
1476
74
    Res = ParseSYCLUniqueStableNameExpression();
1477
74
    break;
1478
1479
402k
  case tok::annot_typename:
1480
402k
    if (isStartOfObjCClassMessageMissingOpenBracket()) {
1481
81
      TypeResult Type = getTypeAnnotation(Tok);
1482
1483
      // Fake up a Declarator to use with ActOnTypeName.
1484
81
      DeclSpec DS(AttrFactory);
1485
81
      DS.SetRangeStart(Tok.getLocation());
1486
81
      DS.SetRangeEnd(Tok.getLastLoc());
1487
1488
81
      const char *PrevSpec = nullptr;
1489
81
      unsigned DiagID;
1490
81
      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1491
81
                         PrevSpec, DiagID, Type,
1492
81
                         Actions.getASTContext().getPrintingPolicy());
1493
1494
81
      Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1495
81
                                DeclaratorContext::TypeName);
1496
81
      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1497
81
      if (Ty.isInvalid())
1498
0
        break;
1499
1500
81
      ConsumeAnnotationToken();
1501
81
      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1502
81
                                           Ty.get(), nullptr);
1503
81
      break;
1504
81
    }
1505
402k
    
LLVM_FALLTHROUGH402k
;402k
1506
1507
402k
  case tok::annot_decltype:
1508
403k
  case tok::kw_char:
1509
403k
  case tok::kw_wchar_t:
1510
403k
  case tok::kw_char8_t:
1511
403k
  case tok::kw_char16_t:
1512
403k
  case tok::kw_char32_t:
1513
407k
  case tok::kw_bool:
1514
407k
  case tok::kw_short:
1515
408k
  case tok::kw_int:
1516
408k
  case tok::kw_long:
1517
408k
  case tok::kw___int64:
1518
408k
  case tok::kw___int128:
1519
408k
  case tok::kw__ExtInt:
1520
408k
  case tok::kw__BitInt:
1521
408k
  case tok::kw_signed:
1522
408k
  case tok::kw_unsigned:
1523
408k
  case tok::kw_half:
1524
411k
  case tok::kw_float:
1525
411k
  case tok::kw_double:
1526
411k
  case tok::kw___bf16:
1527
411k
  case tok::kw__Float16:
1528
411k
  case tok::kw___float128:
1529
411k
  case tok::kw___ibm128:
1530
413k
  case tok::kw_void:
1531
413k
  case tok::kw_auto:
1532
444k
  case tok::kw_typename:
1533
444k
  case tok::kw_typeof:
1534
444k
  case tok::kw___vector:
1535
5.33M
#define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1536
5.33M
#include 
"clang/Basic/OpenCLImageTypes.def"444k
1537
5.33M
  {
1538
5.33M
    if (
!getLangOpts().CPlusPlus444k
) {
1539
296
      Diag(Tok, diag::err_expected_expression);
1540
296
      return ExprError();
1541
296
    }
1542
1543
    // Everything henceforth is a postfix-expression.
1544
444k
    if (NotPrimaryExpression)
1545
4
      *NotPrimaryExpression = true;
1546
1547
444k
    if (SavedKind == tok::kw_typename) {
1548
      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1549
      //                     typename-specifier braced-init-list
1550
31.3k
      if (TryAnnotateTypeOrScopeToken())
1551
7
        return ExprError();
1552
1553
31.2k
      if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1554
        // We are trying to parse a simple-type-specifier but might not get such
1555
        // a token after error recovery.
1556
0
        return ExprError();
1557
31.2k
    }
1558
1559
    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1560
    //                     simple-type-specifier braced-init-list
1561
    //
1562
444k
    DeclSpec DS(AttrFactory);
1563
1564
444k
    ParseCXXSimpleTypeSpecifier(DS);
1565
444k
    if (Tok.isNot(tok::l_paren) &&
1566
444k
        
(8.92k
!getLangOpts().CPlusPlus118.92k
||
Tok.isNot(tok::l_brace)8.91k
))
1567
54
      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1568
54
                         << DS.getSourceRange());
1569
1570
444k
    if (Tok.is(tok::l_brace))
1571
8.87k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1572
1573
444k
    Res = ParseCXXTypeConstructExpression(DS);
1574
444k
    break;
1575
444k
  }
1576
1577
1.55M
  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1578
    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1579
    // (We can end up in this situation after tentative parsing.)
1580
1.55M
    if (TryAnnotateTypeOrScopeToken())
1581
0
      return ExprError();
1582
1.55M
    if (!Tok.is(tok::annot_cxxscope))
1583
4
      return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1584
4
                                 isTypeCast, isVectorLiteral,
1585
4
                                 NotPrimaryExpression);
1586
1587
1.55M
    Token Next = NextToken();
1588
1.55M
    if (Next.is(tok::annot_template_id)) {
1589
177k
      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1590
177k
      if (TemplateId->Kind == TNK_Type_template) {
1591
        // We have a qualified template-id that we know refers to a
1592
        // type, translate it into a type and continue parsing as a
1593
        // cast expression.
1594
0
        CXXScopeSpec SS;
1595
0
        ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1596
0
                                       /*ObjectHasErrors=*/false,
1597
0
                                       /*EnteringContext=*/false);
1598
0
        AnnotateTemplateIdTokenAsType(SS);
1599
0
        return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1600
0
                                   isTypeCast, isVectorLiteral,
1601
0
                                   NotPrimaryExpression);
1602
0
      }
1603
177k
    }
1604
1605
    // Parse as an id-expression.
1606
1.55M
    Res = ParseCXXIdExpression(isAddressOfOperand);
1607
1.55M
    break;
1608
1.55M
  }
1609
1610
104k
  case tok::annot_template_id: { // [C++]          template-id
1611
104k
    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1612
104k
    if (TemplateId->Kind == TNK_Type_template) {
1613
      // We have a template-id that we know refers to a type,
1614
      // translate it into a type and continue parsing as a cast
1615
      // expression.
1616
49
      CXXScopeSpec SS;
1617
49
      AnnotateTemplateIdTokenAsType(SS);
1618
49
      return ParseCastExpression(ParseKind, isAddressOfOperand,
1619
49
                                 NotCastExpr, isTypeCast, isVectorLiteral,
1620
49
                                 NotPrimaryExpression);
1621
49
    }
1622
1623
    // Fall through to treat the template-id as an id-expression.
1624
104k
    
LLVM_FALLTHROUGH104k
;
1625
104k
  }
1626
1627
107k
  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1628
107k
    Res = ParseCXXIdExpression(isAddressOfOperand);
1629
107k
    break;
1630
1631
93.2k
  case tok::coloncolon: {
1632
    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1633
    // annotates the token, tail recurse.
1634
93.2k
    if (TryAnnotateTypeOrScopeToken())
1635
4
      return ExprError();
1636
93.2k
    if (!Tok.is(tok::coloncolon))
1637
73.7k
      return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1638
73.7k
                                 isVectorLiteral, NotPrimaryExpression);
1639
1640
    // ::new -> [C++] new-expression
1641
    // ::delete -> [C++] delete-expression
1642
19.4k
    SourceLocation CCLoc = ConsumeToken();
1643
19.4k
    if (Tok.is(tok::kw_new)) {
1644
19.4k
      if (NotPrimaryExpression)
1645
0
        *NotPrimaryExpression = true;
1646
19.4k
      Res = ParseCXXNewExpression(true, CCLoc);
1647
19.4k
      AllowSuffix = false;
1648
19.4k
      break;
1649
19.4k
    }
1650
52
    if (Tok.is(tok::kw_delete)) {
1651
52
      if (NotPrimaryExpression)
1652
0
        *NotPrimaryExpression = true;
1653
52
      Res = ParseCXXDeleteExpression(true, CCLoc);
1654
52
      AllowSuffix = false;
1655
52
      break;
1656
52
    }
1657
1658
    // This is not a type name or scope specifier, it is an invalid expression.
1659
0
    Diag(CCLoc, diag::err_expected_expression);
1660
0
    return ExprError();
1661
52
  }
1662
1663
9.26k
  case tok::kw_new: // [C++] new-expression
1664
9.26k
    if (NotPrimaryExpression)
1665
0
      *NotPrimaryExpression = true;
1666
9.26k
    Res = ParseCXXNewExpression(false, Tok.getLocation());
1667
9.26k
    AllowSuffix = false;
1668
9.26k
    break;
1669
1670
5.16k
  case tok::kw_delete: // [C++] delete-expression
1671
5.16k
    if (NotPrimaryExpression)
1672
0
      *NotPrimaryExpression = true;
1673
5.16k
    Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1674
5.16k
    AllowSuffix = false;
1675
5.16k
    break;
1676
1677
771
  case tok::kw_requires: // [C++2a] requires-expression
1678
771
    Res = ParseRequiresExpression();
1679
771
    AllowSuffix = false;
1680
771
    break;
1681
1682
12.3k
  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1683
12.3k
    if (NotPrimaryExpression)
1684
0
      *NotPrimaryExpression = true;
1685
12.3k
    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1686
12.3k
    SourceLocation KeyLoc = ConsumeToken();
1687
12.3k
    BalancedDelimiterTracker T(*this, tok::l_paren);
1688
1689
12.3k
    if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1690
0
      return ExprError();
1691
    // C++11 [expr.unary.noexcept]p1:
1692
    //   The noexcept operator determines whether the evaluation of its operand,
1693
    //   which is an unevaluated operand, can throw an exception.
1694
12.3k
    EnterExpressionEvaluationContext Unevaluated(
1695
12.3k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1696
12.3k
    Res = ParseExpression();
1697
1698
12.3k
    T.consumeClose();
1699
1700
12.3k
    if (!Res.isInvalid())
1701
12.3k
      Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1702
12.3k
                                      T.getCloseLocation());
1703
12.3k
    AllowSuffix = false;
1704
12.3k
    break;
1705
12.3k
  }
1706
1707
0
#define TYPE_TRAIT(N,Spelling,K) \
1708
807k
  case tok::kw_##Spelling:
1709
30.0k
#include 
"clang/Basic/TokenKinds.def"12.3k
1710
30.0k
    Res = ParseTypeTrait();
1711
30.0k
    break;
1712
1713
10
  case tok::kw___array_rank:
1714
542
  case tok::kw___array_extent:
1715
542
    if (NotPrimaryExpression)
1716
0
      *NotPrimaryExpression = true;
1717
542
    Res = ParseArrayTypeTrait();
1718
542
    break;
1719
1720
224
  case tok::kw___is_lvalue_expr:
1721
439
  case tok::kw___is_rvalue_expr:
1722
439
    if (NotPrimaryExpression)
1723
0
      *NotPrimaryExpression = true;
1724
439
    Res = ParseExpressionTrait();
1725
439
    break;
1726
1727
8.46k
  case tok::at: {
1728
8.46k
    if (NotPrimaryExpression)
1729
0
      *NotPrimaryExpression = true;
1730
8.46k
    SourceLocation AtLoc = ConsumeToken();
1731
8.46k
    return ParseObjCAtExpression(AtLoc);
1732
224
  }
1733
3.33k
  case tok::caret:
1734
3.33k
    Res = ParseBlockLiteralExpression();
1735
3.33k
    break;
1736
98
  case tok::code_completion: {
1737
98
    cutOffParsing();
1738
98
    Actions.CodeCompleteExpression(getCurScope(),
1739
98
                                   PreferredType.get(Tok.getLocation()));
1740
98
    return ExprError();
1741
224
  }
1742
31.1k
  case tok::l_square:
1743
31.1k
    if (getLangOpts().CPlusPlus11) {
1744
11.3k
      if (getLangOpts().ObjC) {
1745
        // C++11 lambda expressions and Objective-C message sends both start with a
1746
        // square bracket.  There are three possibilities here:
1747
        // we have a valid lambda expression, we have an invalid lambda
1748
        // expression, or we have something that doesn't appear to be a lambda.
1749
        // If we're in the last case, we fall back to ParseObjCMessageExpression.
1750
2.97k
        Res = TryParseLambdaExpression();
1751
2.97k
        if (!Res.isInvalid() && 
!Res.get()2.96k
) {
1752
          // We assume Objective-C++ message expressions are not
1753
          // primary-expressions.
1754
2.76k
          if (NotPrimaryExpression)
1755
0
            *NotPrimaryExpression = true;
1756
2.76k
          Res = ParseObjCMessageExpression();
1757
2.76k
        }
1758
2.97k
        break;
1759
2.97k
      }
1760
8.40k
      Res = ParseLambdaExpression();
1761
8.40k
      break;
1762
11.3k
    }
1763
19.8k
    if (getLangOpts().ObjC) {
1764
19.7k
      Res = ParseObjCMessageExpression();
1765
19.7k
      break;
1766
19.7k
    }
1767
19.8k
    
LLVM_FALLTHROUGH13
;13
1768
16.9k
  default:
1769
16.9k
    NotCastExpr = true;
1770
16.9k
    return ExprError();
1771
44.8M
  }
1772
1773
  // Check to see whether Res is a function designator only. If it is and we
1774
  // are compiling for OpenCL, we need to return an error as this implies
1775
  // that the address of the function is being taken, which is illegal in CL.
1776
1777
36.0M
  if (ParseKind == PrimaryExprOnly)
1778
    // This is strictly a primary-expression - no postfix-expr pieces should be
1779
    // parsed.
1780
2.45k
    return Res;
1781
1782
36.0M
  if (!AllowSuffix) {
1783
    // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1784
    // error already.
1785
184k
    if (Res.isInvalid())
1786
777
      return Res;
1787
1788
183k
    switch (Tok.getKind()) {
1789
5
    case tok::l_square:
1790
6
    case tok::l_paren:
1791
6
    case tok::plusplus:
1792
6
    case tok::minusminus:
1793
      // "expected ';'" or similar is probably the right diagnostic here. Let
1794
      // the caller decide what to do.
1795
6
      if (Tok.isAtStartOfLine())
1796
1
        return Res;
1797
1798
6
      
LLVM_FALLTHROUGH5
;5
1799
5
    case tok::period:
1800
7
    case tok::arrow:
1801
7
      break;
1802
1803
183k
    default:
1804
183k
      return Res;
1805
183k
    }
1806
1807
    // This was a unary-expression for which a postfix-expression suffix is
1808
    // not permitted by the grammar (eg, a sizeof expression or
1809
    // new-expression or similar). Diagnose but parse the suffix anyway.
1810
7
    Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1811
7
        << Tok.getKind() << Res.get()->getSourceRange()
1812
7
        << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1813
7
        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1814
7
                                      ")");
1815
7
  }
1816
1817
  // These can be followed by postfix-expr pieces.
1818
35.8M
  PreferredType = SavedType;
1819
35.8M
  Res = ParsePostfixExpressionSuffix(Res);
1820
35.8M
  if (getLangOpts().OpenCL &&
1821
35.8M
      !getActions().getOpenCLOptions().isAvailableOption(
1822
92.6k
          "__cl_clang_function_pointers", getLangOpts()))
1823
92.6k
    if (Expr *PostfixExpr = Res.get()) {
1824
92.5k
      QualType Ty = PostfixExpr->getType();
1825
92.5k
      if (!Ty.isNull() && 
Ty->isFunctionType()92.3k
) {
1826
10
        Diag(PostfixExpr->getExprLoc(),
1827
10
             diag::err_opencl_taking_function_address_parser);
1828
10
        return ExprError();
1829
10
      }
1830
92.5k
    }
1831
1832
35.8M
  return Res;
1833
35.8M
}
1834
1835
/// Once the leading part of a postfix-expression is parsed, this
1836
/// method parses any suffixes that apply.
1837
///
1838
/// \verbatim
1839
///       postfix-expression: [C99 6.5.2]
1840
///         primary-expression
1841
///         postfix-expression '[' expression ']'
1842
///         postfix-expression '[' braced-init-list ']'
1843
///         postfix-expression '[' expression-list [opt] ']'  [C++2b 12.4.5]
1844
///         postfix-expression '(' argument-expression-list[opt] ')'
1845
///         postfix-expression '.' identifier
1846
///         postfix-expression '->' identifier
1847
///         postfix-expression '++'
1848
///         postfix-expression '--'
1849
///         '(' type-name ')' '{' initializer-list '}'
1850
///         '(' type-name ')' '{' initializer-list ',' '}'
1851
///
1852
///       argument-expression-list: [C99 6.5.2]
1853
///         argument-expression ...[opt]
1854
///         argument-expression-list ',' assignment-expression ...[opt]
1855
/// \endverbatim
1856
ExprResult
1857
35.8M
Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1858
  // Now that the primary-expression piece of the postfix-expression has been
1859
  // parsed, see if there are any postfix-expression pieces here.
1860
35.8M
  SourceLocation Loc;
1861
35.8M
  auto SavedType = PreferredType;
1862
43.8M
  while (true) {
1863
    // Each iteration relies on preferred type for the whole expression.
1864
43.8M
    PreferredType = SavedType;
1865
43.8M
    switch (Tok.getKind()) {
1866
69
    case tok::code_completion:
1867
69
      if (InMessageExpression)
1868
58
        return LHS;
1869
1870
11
      cutOffParsing();
1871
11
      Actions.CodeCompletePostfixExpression(
1872
11
          getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
1873
11
      return ExprError();
1874
1875
20.7k
    case tok::identifier:
1876
      // If we see identifier: after an expression, and we're not already in a
1877
      // message send, then this is probably a message send with a missing
1878
      // opening bracket '['.
1879
20.7k
      if (getLangOpts().ObjC && 
!InMessageExpression18.9k
&&
1880
20.7k
          
(282
NextToken().is(tok::colon)282
||
NextToken().is(tok::r_square)196
)) {
1881
174
        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1882
174
                                             nullptr, LHS.get());
1883
174
        break;
1884
174
      }
1885
      // Fall through; this isn't a message send.
1886
20.7k
      
LLVM_FALLTHROUGH20.6k
;20.6k
1887
1888
35.8M
    default:  // Not a postfix-expression suffix.
1889
35.8M
      return LHS;
1890
308k
    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1891
      // If we have a array postfix expression that starts on a new line and
1892
      // Objective-C is enabled, it is highly likely that the user forgot a
1893
      // semicolon after the base expression and that the array postfix-expr is
1894
      // actually another message send.  In this case, do some look-ahead to see
1895
      // if the contents of the square brackets are obviously not a valid
1896
      // expression and recover by pretending there is no suffix.
1897
308k
      if (getLangOpts().ObjC && 
Tok.isAtStartOfLine()59.8k
&&
1898
308k
          
isSimpleObjCMessageExpression()5
)
1899
4
        return LHS;
1900
1901
      // Reject array indices starting with a lambda-expression. '[[' is
1902
      // reserved for attributes.
1903
308k
      if (CheckProhibitedCXX11Attribute()) {
1904
2
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
1905
2
        return ExprError();
1906
2
      }
1907
308k
      BalancedDelimiterTracker T(*this, tok::l_square);
1908
308k
      T.consumeOpen();
1909
308k
      Loc = T.getOpenLocation();
1910
308k
      ExprResult Length, Stride;
1911
308k
      SourceLocation ColonLocFirst, ColonLocSecond;
1912
308k
      ExprVector ArgExprs;
1913
308k
      bool HasError = false;
1914
308k
      PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
1915
1916
      // We try to parse a list of indexes in all language mode first
1917
      // and, in we find 0 or one index, we try to parse an OpenMP array
1918
      // section. This allow us to support C++2b multi dimensional subscript and
1919
      // OpenMp sections in the same language mode.
1920
308k
      if (!getLangOpts().OpenMP || 
Tok.isNot(tok::colon)115k
) {
1921
300k
        if (!getLangOpts().CPlusPlus2b) {
1922
300k
          ExprResult Idx;
1923
300k
          if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)205k
) {
1924
4
            Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1925
4
            Idx = ParseBraceInitializer();
1926
300k
          } else {
1927
300k
            Idx = ParseExpression(); // May be a comma expression
1928
300k
          }
1929
300k
          LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1930
300k
          Idx = Actions.CorrectDelayedTyposInExpr(Idx);
1931
300k
          if (Idx.isInvalid()) {
1932
130
            HasError = true;
1933
300k
          } else {
1934
300k
            ArgExprs.push_back(Idx.get());
1935
300k
          }
1936
300k
        } else 
if (320
Tok.isNot(tok::r_square)320
) {
1937
308
          CommaLocsTy CommaLocs;
1938
308
          if (ParseExpressionList(ArgExprs, CommaLocs)) {
1939
0
            LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1940
0
            HasError = true;
1941
0
          }
1942
308
          assert(
1943
308
              (ArgExprs.empty() || ArgExprs.size() == CommaLocs.size() + 1) &&
1944
308
              "Unexpected number of commas!");
1945
308
        }
1946
300k
      }
1947
1948
308k
      if (ArgExprs.size() <= 1 && 
getLangOpts().OpenMP308k
) {
1949
115k
        ColonProtectionRAIIObject RAII(*this);
1950
115k
        if (Tok.is(tok::colon)) {
1951
          // Consume ':'
1952
13.0k
          ColonLocFirst = ConsumeToken();
1953
13.0k
          if (Tok.isNot(tok::r_square) &&
1954
13.0k
              
(9.83k
getLangOpts().OpenMP < 509.83k
||
1955
9.83k
               
((7.06k
Tok.isNot(tok::colon)7.06k
&&
getLangOpts().OpenMP >= 507.04k
)))) {
1956
9.82k
            Length = ParseExpression();
1957
9.82k
            Length = Actions.CorrectDelayedTyposInExpr(Length);
1958
9.82k
          }
1959
13.0k
        }
1960
115k
        if (getLangOpts().OpenMP >= 50 &&
1961
115k
            
(93.1k
OMPClauseKind == llvm::omp::Clause::OMPC_to93.1k
||
1962
93.1k
             
OMPClauseKind == llvm::omp::Clause::OMPC_from92.2k
) &&
1963
115k
            
Tok.is(tok::colon)1.53k
) {
1964
          // Consume ':'
1965
215
          ColonLocSecond = ConsumeToken();
1966
215
          if (Tok.isNot(tok::r_square)) {
1967
167
            Stride = ParseExpression();
1968
167
          }
1969
215
        }
1970
115k
      }
1971
1972
308k
      SourceLocation RLoc = Tok.getLocation();
1973
308k
      LHS = Actions.CorrectDelayedTyposInExpr(LHS);
1974
1975
308k
      if (!LHS.isInvalid() && 
!HasError308k
&&
!Length.isInvalid()307k
&&
1976
308k
          
!Stride.isInvalid()307k
&&
Tok.is(tok::r_square)307k
) {
1977
307k
        if (ColonLocFirst.isValid() || 
ColonLocSecond.isValid()295k
) {
1978
12.3k
          LHS = Actions.ActOnOMPArraySectionExpr(
1979
12.3k
              LHS.get(), Loc, ArgExprs.empty() ? 
nullptr7.27k
:
ArgExprs[0]5.11k
,
1980
12.3k
              ColonLocFirst, ColonLocSecond, Length.get(), Stride.get(), RLoc);
1981
295k
        } else {
1982
295k
          LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1983
295k
                                                ArgExprs, RLoc);
1984
295k
        }
1985
307k
      } else {
1986
773
        LHS = ExprError();
1987
773
      }
1988
1989
      // Match the ']'.
1990
308k
      T.consumeClose();
1991
308k
      break;
1992
308k
    }
1993
1994
5.84M
    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1995
5.84M
    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1996
                               //   '(' argument-expression-list[opt] ')'
1997
5.84M
      tok::TokenKind OpKind = Tok.getKind();
1998
5.84M
      InMessageExpressionRAIIObject InMessage(*this, false);
1999
2000
5.84M
      Expr *ExecConfig = nullptr;
2001
2002
5.84M
      BalancedDelimiterTracker PT(*this, tok::l_paren);
2003
2004
5.84M
      if (OpKind == tok::lesslessless) {
2005
184
        ExprVector ExecConfigExprs;
2006
184
        CommaLocsTy ExecConfigCommaLocs;
2007
184
        SourceLocation OpenLoc = ConsumeToken();
2008
2009
184
        if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
2010
1
          (void)Actions.CorrectDelayedTyposInExpr(LHS);
2011
1
          LHS = ExprError();
2012
1
        }
2013
2014
184
        SourceLocation CloseLoc;
2015
184
        if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
2016
183
        } else 
if (1
LHS.isInvalid()1
) {
2017
0
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
2018
1
        } else {
2019
          // There was an error closing the brackets
2020
1
          Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
2021
1
          Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
2022
1
          SkipUntil(tok::greatergreatergreater, StopAtSemi);
2023
1
          LHS = ExprError();
2024
1
        }
2025
2026
184
        if (!LHS.isInvalid()) {
2027
180
          if (ExpectAndConsume(tok::l_paren))
2028
1
            LHS = ExprError();
2029
179
          else
2030
179
            Loc = PrevTokLocation;
2031
180
        }
2032
2033
184
        if (!LHS.isInvalid()) {
2034
179
          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
2035
179
                                    OpenLoc,
2036
179
                                    ExecConfigExprs,
2037
179
                                    CloseLoc);
2038
179
          if (ECResult.isInvalid())
2039
2
            LHS = ExprError();
2040
177
          else
2041
177
            ExecConfig = ECResult.get();
2042
179
        }
2043
5.84M
      } else {
2044
5.84M
        PT.consumeOpen();
2045
5.84M
        Loc = PT.getOpenLocation();
2046
5.84M
      }
2047
2048
5.84M
      ExprVector ArgExprs;
2049
5.84M
      CommaLocsTy CommaLocs;
2050
5.84M
      auto RunSignatureHelp = [&]() -> QualType {
2051
189
        QualType PreferredType = Actions.ProduceCallSignatureHelp(
2052
189
            LHS.get(), ArgExprs, PT.getOpenLocation());
2053
189
        CalledSignatureHelp = true;
2054
189
        return PreferredType;
2055
189
      };
2056
5.84M
      if (OpKind == tok::l_paren || 
!LHS.isInvalid()184
) {
2057
5.84M
        if (Tok.isNot(tok::r_paren)) {
2058
9.89M
          if (
ParseExpressionList(ArgExprs, CommaLocs, [&] 4.28M
{
2059
9.89M
                PreferredType.enterFunctionArgument(Tok.getLocation(),
2060
9.89M
                                                    RunSignatureHelp);
2061
9.89M
              })) {
2062
3.47k
            (void)Actions.CorrectDelayedTyposInExpr(LHS);
2063
            // If we got an error when parsing expression list, we don't call
2064
            // the CodeCompleteCall handler inside the parser. So call it here
2065
            // to make sure we get overload suggestions even when we are in the
2066
            // middle of a parameter.
2067
3.47k
            if (PP.isCodeCompletionReached() && 
!CalledSignatureHelp184
)
2068
4
              RunSignatureHelp();
2069
3.47k
            LHS = ExprError();
2070
4.28M
          } else if (LHS.isInvalid()) {
2071
238
            for (auto &E : ArgExprs)
2072
375
              Actions.CorrectDelayedTyposInExpr(E);
2073
238
          }
2074
4.28M
        }
2075
5.84M
      }
2076
2077
      // Match the ')'.
2078
5.84M
      if (LHS.isInvalid()) {
2079
3.88k
        SkipUntil(tok::r_paren, StopAtSemi);
2080
5.84M
      } else if (Tok.isNot(tok::r_paren)) {
2081
1.29k
        bool HadDelayedTypo = false;
2082
1.29k
        if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2083
0
          HadDelayedTypo = true;
2084
1.29k
        for (auto &E : ArgExprs)
2085
1.29k
          if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2086
11
            HadDelayedTypo = true;
2087
        // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2088
        // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2089
        // the unmatched l_paren.
2090
1.29k
        if (HadDelayedTypo)
2091
11
          SkipUntil(tok::r_paren, StopAtSemi);
2092
1.28k
        else
2093
1.28k
          PT.consumeClose();
2094
1.29k
        LHS = ExprError();
2095
5.83M
      } else {
2096
5.83M
        assert(
2097
5.83M
            (ArgExprs.size() == 0 || ArgExprs.size() - 1 == CommaLocs.size()) &&
2098
5.83M
            "Unexpected number of commas!");
2099
0
        Expr *Fn = LHS.get();
2100
5.83M
        SourceLocation RParLoc = Tok.getLocation();
2101
5.83M
        LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2102
5.83M
                                    ExecConfig);
2103
5.83M
        if (LHS.isInvalid()) {
2104
7.63k
          ArgExprs.insert(ArgExprs.begin(), Fn);
2105
7.63k
          LHS =
2106
7.63k
              Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2107
7.63k
        }
2108
5.83M
        PT.consumeClose();
2109
5.83M
      }
2110
2111
0
      break;
2112
5.84M
    }
2113
460k
    case tok::arrow:
2114
1.75M
    case tok::period: {
2115
      // postfix-expression: p-e '->' template[opt] id-expression
2116
      // postfix-expression: p-e '.' template[opt] id-expression
2117
1.75M
      tok::TokenKind OpKind = Tok.getKind();
2118
1.75M
      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
2119
2120
1.75M
      CXXScopeSpec SS;
2121
1.75M
      ParsedType ObjectType;
2122
1.75M
      bool MayBePseudoDestructor = false;
2123
1.75M
      Expr* OrigLHS = !LHS.isInvalid() ? 
LHS.get()1.75M
:
nullptr44
;
2124
2125
1.75M
      PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2126
2127
1.75M
      if (getLangOpts().CPlusPlus && 
!LHS.isInvalid()1.62M
) {
2128
1.62M
        Expr *Base = OrigLHS;
2129
1.62M
        const Type* BaseType = Base->getType().getTypePtrOrNull();
2130
1.62M
        if (BaseType && 
Tok.is(tok::l_paren)1.62M
&&
2131
1.62M
            
(13
BaseType->isFunctionType()13
||
2132
13
             
BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember)8
)) {
2133
10
          Diag(OpLoc, diag::err_function_is_not_record)
2134
10
              << OpKind << Base->getSourceRange()
2135
10
              << FixItHint::CreateRemoval(OpLoc);
2136
10
          return ParsePostfixExpressionSuffix(Base);
2137
10
        }
2138
2139
1.62M
        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2140
1.62M
                                                   OpKind, ObjectType,
2141
1.62M
                                                   MayBePseudoDestructor);
2142
1.62M
        if (LHS.isInvalid()) {
2143
          // Clang will try to perform expression based completion as a
2144
          // fallback, which is confusing in case of member references. So we
2145
          // stop here without any completions.
2146
176
          if (Tok.is(tok::code_completion)) {
2147
0
            cutOffParsing();
2148
0
            return ExprError();
2149
0
          }
2150
176
          break;
2151
176
        }
2152
1.62M
        ParseOptionalCXXScopeSpecifier(
2153
1.62M
            SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2154
1.62M
            /*EnteringContext=*/false, &MayBePseudoDestructor);
2155
1.62M
        if (SS.isNotEmpty())
2156
720
          ObjectType = nullptr;
2157
1.62M
      }
2158
2159
1.75M
      if (Tok.is(tok::code_completion)) {
2160
162
        tok::TokenKind CorrectedOpKind =
2161
162
            OpKind == tok::arrow ? 
tok::period44
:
tok::arrow118
;
2162
162
        ExprResult CorrectedLHS(/*Invalid=*/true);
2163
162
        if (getLangOpts().CPlusPlus && 
OrigLHS113
) {
2164
          // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2165
          // hack.
2166
112
          Sema::TentativeAnalysisScope Trap(Actions);
2167
112
          CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2168
112
              getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2169
112
              MayBePseudoDestructor);
2170
112
        }
2171
2172
162
        Expr *Base = LHS.get();
2173
162
        Expr *CorrectedBase = CorrectedLHS.get();
2174
162
        if (!CorrectedBase && 
!getLangOpts().CPlusPlus50
)
2175
49
          CorrectedBase = Base;
2176
2177
        // Code completion for a member access expression.
2178
162
        cutOffParsing();
2179
162
        Actions.CodeCompleteMemberReferenceExpr(
2180
162
            getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2181
162
            Base && 
ExprStatementTokLoc == Base->getBeginLoc()161
,
2182
162
            PreferredType.get(Tok.getLocation()));
2183
2184
162
        return ExprError();
2185
162
      }
2186
2187
1.75M
      if (MayBePseudoDestructor && 
!LHS.isInvalid()7.25k
) {
2188
7.25k
        LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2189
7.25k
                                       ObjectType);
2190
7.25k
        break;
2191
7.25k
      }
2192
2193
      // Either the action has told us that this cannot be a
2194
      // pseudo-destructor expression (based on the type of base
2195
      // expression), or we didn't see a '~' in the right place. We
2196
      // can still parse a destructor name here, but in that case it
2197
      // names a real destructor.
2198
      // Allow explicit constructor calls in Microsoft mode.
2199
      // FIXME: Add support for explicit call of template constructor.
2200
1.74M
      SourceLocation TemplateKWLoc;
2201
1.74M
      UnqualifiedId Name;
2202
1.74M
      if (getLangOpts().ObjC && 
OpKind == tok::period197k
&&
2203
1.74M
          
Tok.is(tok::kw_class)105k
) {
2204
        // Objective-C++:
2205
        //   After a '.' in a member access expression, treat the keyword
2206
        //   'class' as if it were an identifier.
2207
        //
2208
        // This hack allows property access to the 'class' method because it is
2209
        // such a common method name. For other C++ keywords that are
2210
        // Objective-C method names, one must use the message send syntax.
2211
2
        IdentifierInfo *Id = Tok.getIdentifierInfo();
2212
2
        SourceLocation Loc = ConsumeToken();
2213
2
        Name.setIdentifier(Id, Loc);
2214
1.74M
      } else if (ParseUnqualifiedId(
2215
1.74M
                     SS, ObjectType, LHS.get() && 
LHS.get()->containsErrors()1.74M
,
2216
1.74M
                     /*EnteringContext=*/false,
2217
1.74M
                     /*AllowDestructorName=*/true,
2218
                     /*AllowConstructorName=*/
2219
1.74M
                     getLangOpts().MicrosoftExt && 
SS.isNotEmpty()3.71k
,
2220
1.74M
                     /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2221
324
        (void)Actions.CorrectDelayedTyposInExpr(LHS);
2222
324
        LHS = ExprError();
2223
324
      }
2224
2225
1.74M
      if (!LHS.isInvalid())
2226
1.74M
        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2227
1.74M
                                            OpKind, SS, TemplateKWLoc, Name,
2228
1.74M
                                 CurParsedObjCImpl ? 
CurParsedObjCImpl->Dcl2.21k
2229
1.74M
                                                   : 
nullptr1.74M
);
2230
1.74M
      if (!LHS.isInvalid()) {
2231
1.74M
        if (Tok.is(tok::less))
2232
5.21k
          checkPotentialAngleBracket(LHS);
2233
1.74M
      } else 
if (814
OrigLHS814
&&
Name.isValid()771
) {
2234
        // Preserve the LHS if the RHS is an invalid member.
2235
460
        LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2236
460
                                         Name.getEndLoc(), {OrigLHS});
2237
460
      }
2238
1.74M
      break;
2239
1.75M
    }
2240
47.2k
    case tok::plusplus:    // postfix-expression: postfix-expression '++'
2241
48.8k
    case tok::minusminus:  // postfix-expression: postfix-expression '--'
2242
48.8k
      if (!LHS.isInvalid()) {
2243
48.8k
        Expr *Arg = LHS.get();
2244
48.8k
        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2245
48.8k
                                          Tok.getKind(), Arg);
2246
48.8k
        if (LHS.isInvalid())
2247
114
          LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2248
114
                                           Tok.getLocation(), Arg);
2249
48.8k
      }
2250
48.8k
      ConsumeToken();
2251
48.8k
      break;
2252
43.8M
    }
2253
43.8M
  }
2254
35.8M
}
2255
2256
/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2257
/// vec_step and we are at the start of an expression or a parenthesized
2258
/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2259
/// expression (isCastExpr == false) or the type (isCastExpr == true).
2260
///
2261
/// \verbatim
2262
///       unary-expression:  [C99 6.5.3]
2263
///         'sizeof' unary-expression
2264
///         'sizeof' '(' type-name ')'
2265
/// [GNU]   '__alignof' unary-expression
2266
/// [GNU]   '__alignof' '(' type-name ')'
2267
/// [C11]   '_Alignof' '(' type-name ')'
2268
/// [C++0x] 'alignof' '(' type-id ')'
2269
///
2270
/// [GNU]   typeof-specifier:
2271
///           typeof ( expressions )
2272
///           typeof ( type-name )
2273
/// [GNU/C++] typeof unary-expression
2274
///
2275
/// [OpenCL 1.1 6.11.12] vec_step built-in function:
2276
///           vec_step ( expressions )
2277
///           vec_step ( type-name )
2278
/// \endverbatim
2279
ExprResult
2280
Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2281
                                           bool &isCastExpr,
2282
                                           ParsedType &CastTy,
2283
101k
                                           SourceRange &CastRange) {
2284
2285
101k
  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
2286
101k
                       tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2287
101k
                       tok::kw___builtin_omp_required_simd_align) &&
2288
101k
         "Not a typeof/sizeof/alignof/vec_step expression!");
2289
2290
0
  ExprResult Operand;
2291
2292
  // If the operand doesn't start with an '(', it must be an expression.
2293
101k
  if (Tok.isNot(tok::l_paren)) {
2294
    // If construct allows a form without parenthesis, user may forget to put
2295
    // pathenthesis around type name.
2296
828
    if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2297
828
                      tok::kw__Alignof)) {
2298
822
      if (isTypeIdUnambiguously()) {
2299
9
        DeclSpec DS(AttrFactory);
2300
9
        ParseSpecifierQualifierList(DS);
2301
9
        Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2302
9
                                  DeclaratorContext::TypeName);
2303
9
        ParseDeclarator(DeclaratorInfo);
2304
2305
9
        SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2306
9
        SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2307
9
        if (LParenLoc.isInvalid() || 
RParenLoc.isInvalid()8
) {
2308
1
          Diag(OpTok.getLocation(),
2309
1
               diag::err_expected_parentheses_around_typename)
2310
1
              << OpTok.getName();
2311
8
        } else {
2312
8
          Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2313
8
              << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
2314
8
              << FixItHint::CreateInsertion(RParenLoc, ")");
2315
8
        }
2316
9
        isCastExpr = true;
2317
9
        return ExprEmpty();
2318
9
      }
2319
822
    }
2320
2321
819
    isCastExpr = false;
2322
819
    if (OpTok.is(tok::kw_typeof) && 
!getLangOpts().CPlusPlus6
) {
2323
0
      Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2324
0
                                          << tok::l_paren;
2325
0
      return ExprError();
2326
0
    }
2327
2328
819
    Operand = ParseCastExpression(UnaryExprOnly);
2329
100k
  } else {
2330
    // If it starts with a '(', we know that it is either a parenthesized
2331
    // type-name, or it is a unary-expression that starts with a compound
2332
    // literal, or starts with a primary-expression that is a parenthesized
2333
    // expression.
2334
100k
    ParenParseOption ExprType = CastExpr;
2335
100k
    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2336
2337
100k
    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2338
100k
                                   false, CastTy, RParenLoc);
2339
100k
    CastRange = SourceRange(LParenLoc, RParenLoc);
2340
2341
    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2342
    // a type.
2343
100k
    if (ExprType == CastExpr) {
2344
85.2k
      isCastExpr = true;
2345
85.2k
      return ExprEmpty();
2346
85.2k
    }
2347
2348
15.6k
    if (getLangOpts().CPlusPlus || 
OpTok.isNot(tok::kw_typeof)1.81k
) {
2349
      // GNU typeof in C requires the expression to be parenthesized. Not so for
2350
      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2351
      // the start of a unary-expression, but doesn't include any postfix
2352
      // pieces. Parse these now if present.
2353
14.9k
      if (!Operand.isInvalid())
2354
14.9k
        Operand = ParsePostfixExpressionSuffix(Operand.get());
2355
14.9k
    }
2356
15.6k
  }
2357
2358
  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2359
16.4k
  isCastExpr = false;
2360
16.4k
  return Operand;
2361
101k
}
2362
2363
/// Parse a __builtin_sycl_unique_stable_name expression.  Accepts a type-id as
2364
/// a parameter.
2365
74
ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
2366
74
  assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
2367
74
         "Not __builtin_sycl_unique_stable_name");
2368
2369
0
  SourceLocation OpLoc = ConsumeToken();
2370
74
  BalancedDelimiterTracker T(*this, tok::l_paren);
2371
2372
  // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2373
74
  if (T.expectAndConsume(diag::err_expected_lparen_after,
2374
74
                         "__builtin_sycl_unique_stable_name"))
2375
2
    return ExprError();
2376
2377
72
  TypeResult Ty = ParseTypeName();
2378
2379
72
  if (Ty.isInvalid()) {
2380
8
    T.skipToEnd();
2381
8
    return ExprError();
2382
8
  }
2383
2384
64
  if (T.consumeClose())
2385
2
    return ExprError();
2386
2387
62
  return Actions.ActOnSYCLUniqueStableNameExpr(OpLoc, T.getOpenLocation(),
2388
62
                                               T.getCloseLocation(), Ty.get());
2389
64
}
2390
2391
/// Parse a sizeof or alignof expression.
2392
///
2393
/// \verbatim
2394
///       unary-expression:  [C99 6.5.3]
2395
///         'sizeof' unary-expression
2396
///         'sizeof' '(' type-name ')'
2397
/// [C++11] 'sizeof' '...' '(' identifier ')'
2398
/// [GNU]   '__alignof' unary-expression
2399
/// [GNU]   '__alignof' '(' type-name ')'
2400
/// [C11]   '_Alignof' '(' type-name ')'
2401
/// [C++11] 'alignof' '(' type-id ')'
2402
/// \endverbatim
2403
136k
ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2404
136k
  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
2405
136k
                     tok::kw__Alignof, tok::kw_vec_step,
2406
136k
                     tok::kw___builtin_omp_required_simd_align) &&
2407
136k
         "Not a sizeof/alignof/vec_step expression!");
2408
0
  Token OpTok = Tok;
2409
136k
  ConsumeToken();
2410
2411
  // [C++11] 'sizeof' '...' '(' identifier ')'
2412
136k
  if (Tok.is(tok::ellipsis) && 
OpTok.is(tok::kw_sizeof)38.2k
) {
2413
38.2k
    SourceLocation EllipsisLoc = ConsumeToken();
2414
38.2k
    SourceLocation LParenLoc, RParenLoc;
2415
38.2k
    IdentifierInfo *Name = nullptr;
2416
38.2k
    SourceLocation NameLoc;
2417
38.2k
    if (Tok.is(tok::l_paren)) {
2418
38.2k
      BalancedDelimiterTracker T(*this, tok::l_paren);
2419
38.2k
      T.consumeOpen();
2420
38.2k
      LParenLoc = T.getOpenLocation();
2421
38.2k
      if (Tok.is(tok::identifier)) {
2422
38.2k
        Name = Tok.getIdentifierInfo();
2423
38.2k
        NameLoc = ConsumeToken();
2424
38.2k
        T.consumeClose();
2425
38.2k
        RParenLoc = T.getCloseLocation();
2426
38.2k
        if (RParenLoc.isInvalid())
2427
0
          RParenLoc = PP.getLocForEndOfToken(NameLoc);
2428
38.2k
      } else {
2429
0
        Diag(Tok, diag::err_expected_parameter_pack);
2430
0
        SkipUntil(tok::r_paren, StopAtSemi);
2431
0
      }
2432
38.2k
    } else 
if (1
Tok.is(tok::identifier)1
) {
2433
1
      Name = Tok.getIdentifierInfo();
2434
1
      NameLoc = ConsumeToken();
2435
1
      LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2436
1
      RParenLoc = PP.getLocForEndOfToken(NameLoc);
2437
1
      Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2438
1
        << Name
2439
1
        << FixItHint::CreateInsertion(LParenLoc, "(")
2440
1
        << FixItHint::CreateInsertion(RParenLoc, ")");
2441
1
    } else {
2442
0
      Diag(Tok, diag::err_sizeof_parameter_pack);
2443
0
    }
2444
2445
38.2k
    if (!Name)
2446
0
      return ExprError();
2447
2448
38.2k
    EnterExpressionEvaluationContext Unevaluated(
2449
38.2k
        Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2450
38.2k
        Sema::ReuseLambdaContextDecl);
2451
2452
38.2k
    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2453
38.2k
                                                OpTok.getLocation(),
2454
38.2k
                                                *Name, NameLoc,
2455
38.2k
                                                RParenLoc);
2456
38.2k
  }
2457
2458
98.7k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2459
6.70k
    Diag(OpTok, diag::warn_cxx98_compat_alignof);
2460
2461
98.7k
  EnterExpressionEvaluationContext Unevaluated(
2462
98.7k
      Actions, Sema::ExpressionEvaluationContext::Unevaluated,
2463
98.7k
      Sema::ReuseLambdaContextDecl);
2464
2465
98.7k
  bool isCastExpr;
2466
98.7k
  ParsedType CastTy;
2467
98.7k
  SourceRange CastRange;
2468
98.7k
  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2469
98.7k
                                                          isCastExpr,
2470
98.7k
                                                          CastTy,
2471
98.7k
                                                          CastRange);
2472
2473
98.7k
  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2474
98.7k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2475
6.70k
    ExprKind = UETT_AlignOf;
2476
92.0k
  else if (OpTok.is(tok::kw___alignof))
2477
3.22k
    ExprKind = UETT_PreferredAlignOf;
2478
88.8k
  else if (OpTok.is(tok::kw_vec_step))
2479
45
    ExprKind = UETT_VecStep;
2480
88.7k
  else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
2481
29
    ExprKind = UETT_OpenMPRequiredSimdAlign;
2482
2483
98.7k
  if (isCastExpr)
2484
85.1k
    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2485
85.1k
                                                 ExprKind,
2486
85.1k
                                                 /*IsType=*/true,
2487
85.1k
                                                 CastTy.getAsOpaquePtr(),
2488
85.1k
                                                 CastRange);
2489
2490
13.5k
  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2491
39
    Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2492
2493
  // If we get here, the operand to the sizeof/alignof was an expression.
2494
13.5k
  if (!Operand.isInvalid())
2495
13.5k
    Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2496
13.5k
                                                    ExprKind,
2497
13.5k
                                                    /*IsType=*/false,
2498
13.5k
                                                    Operand.get(),
2499
13.5k
                                                    CastRange);
2500
13.5k
  return Operand;
2501
98.7k
}
2502
2503
/// ParseBuiltinPrimaryExpression
2504
///
2505
/// \verbatim
2506
///       primary-expression: [C99 6.5.1]
2507
/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2508
/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2509
/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2510
///                                     assign-expr ')'
2511
/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2512
/// [GNU]   '__builtin_FILE' '(' ')'
2513
/// [GNU]   '__builtin_FUNCTION' '(' ')'
2514
/// [GNU]   '__builtin_LINE' '(' ')'
2515
/// [CLANG] '__builtin_COLUMN' '(' ')'
2516
/// [GNU]   '__builtin_source_location' '(' ')'
2517
/// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
2518
///
2519
/// [GNU] offsetof-member-designator:
2520
/// [GNU]   identifier
2521
/// [GNU]   offsetof-member-designator '.' identifier
2522
/// [GNU]   offsetof-member-designator '[' expression ']'
2523
/// \endverbatim
2524
23.5k
ExprResult Parser::ParseBuiltinPrimaryExpression() {
2525
23.5k
  ExprResult Res;
2526
23.5k
  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2527
2528
23.5k
  tok::TokenKind T = Tok.getKind();
2529
23.5k
  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
2530
2531
  // All of these start with an open paren.
2532
23.5k
  if (Tok.isNot(tok::l_paren))
2533
0
    return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2534
0
                                                         << tok::l_paren);
2535
2536
23.5k
  BalancedDelimiterTracker PT(*this, tok::l_paren);
2537
23.5k
  PT.consumeOpen();
2538
2539
  // TODO: Build AST.
2540
2541
23.5k
  switch (T) {
2542
0
  default: llvm_unreachable("Not a builtin primary expression!");
2543
1.11k
  case tok::kw___builtin_va_arg: {
2544
1.11k
    ExprResult Expr(ParseAssignmentExpression());
2545
2546
1.11k
    if (ExpectAndConsume(tok::comma)) {
2547
0
      SkipUntil(tok::r_paren, StopAtSemi);
2548
0
      Expr = ExprError();
2549
0
    }
2550
2551
1.11k
    TypeResult Ty = ParseTypeName();
2552
2553
1.11k
    if (Tok.isNot(tok::r_paren)) {
2554
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2555
0
      Expr = ExprError();
2556
0
    }
2557
2558
1.11k
    if (Expr.isInvalid() || Ty.isInvalid())
2559
0
      Res = ExprError();
2560
1.11k
    else
2561
1.11k
      Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2562
1.11k
    break;
2563
0
  }
2564
368
  case tok::kw___builtin_offsetof: {
2565
368
    SourceLocation TypeLoc = Tok.getLocation();
2566
368
    TypeResult Ty = ParseTypeName();
2567
368
    if (Ty.isInvalid()) {
2568
1
      SkipUntil(tok::r_paren, StopAtSemi);
2569
1
      return ExprError();
2570
1
    }
2571
2572
367
    if (ExpectAndConsume(tok::comma)) {
2573
0
      SkipUntil(tok::r_paren, StopAtSemi);
2574
0
      return ExprError();
2575
0
    }
2576
2577
    // We must have at least one identifier here.
2578
367
    if (Tok.isNot(tok::identifier)) {
2579
0
      Diag(Tok, diag::err_expected) << tok::identifier;
2580
0
      SkipUntil(tok::r_paren, StopAtSemi);
2581
0
      return ExprError();
2582
0
    }
2583
2584
    // Keep track of the various subcomponents we see.
2585
367
    SmallVector<Sema::OffsetOfComponent, 4> Comps;
2586
2587
367
    Comps.push_back(Sema::OffsetOfComponent());
2588
367
    Comps.back().isBrackets = false;
2589
367
    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2590
367
    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2591
2592
    // FIXME: This loop leaks the index expressions on error.
2593
428
    while (true) {
2594
428
      if (Tok.is(tok::period)) {
2595
        // offsetof-member-designator: offsetof-member-designator '.' identifier
2596
19
        Comps.push_back(Sema::OffsetOfComponent());
2597
19
        Comps.back().isBrackets = false;
2598
19
        Comps.back().LocStart = ConsumeToken();
2599
2600
19
        if (Tok.isNot(tok::identifier)) {
2601
0
          Diag(Tok, diag::err_expected) << tok::identifier;
2602
0
          SkipUntil(tok::r_paren, StopAtSemi);
2603
0
          return ExprError();
2604
0
        }
2605
19
        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2606
19
        Comps.back().LocEnd = ConsumeToken();
2607
2608
409
      } else if (Tok.is(tok::l_square)) {
2609
42
        if (CheckProhibitedCXX11Attribute())
2610
0
          return ExprError();
2611
2612
        // offsetof-member-designator: offsetof-member-design '[' expression ']'
2613
42
        Comps.push_back(Sema::OffsetOfComponent());
2614
42
        Comps.back().isBrackets = true;
2615
42
        BalancedDelimiterTracker ST(*this, tok::l_square);
2616
42
        ST.consumeOpen();
2617
42
        Comps.back().LocStart = ST.getOpenLocation();
2618
42
        Res = ParseExpression();
2619
42
        if (Res.isInvalid()) {
2620
0
          SkipUntil(tok::r_paren, StopAtSemi);
2621
0
          return Res;
2622
0
        }
2623
42
        Comps.back().U.E = Res.get();
2624
2625
42
        ST.consumeClose();
2626
42
        Comps.back().LocEnd = ST.getCloseLocation();
2627
367
      } else {
2628
367
        if (Tok.isNot(tok::r_paren)) {
2629
2
          PT.consumeClose();
2630
2
          Res = ExprError();
2631
365
        } else if (Ty.isInvalid()) {
2632
0
          Res = ExprError();
2633
365
        } else {
2634
365
          PT.consumeClose();
2635
365
          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2636
365
                                             Ty.get(), Comps,
2637
365
                                             PT.getCloseLocation());
2638
365
        }
2639
367
        break;
2640
367
      }
2641
428
    }
2642
367
    break;
2643
367
  }
2644
367
  case tok::kw___builtin_choose_expr: {
2645
61
    ExprResult Cond(ParseAssignmentExpression());
2646
61
    if (Cond.isInvalid()) {
2647
0
      SkipUntil(tok::r_paren, StopAtSemi);
2648
0
      return Cond;
2649
0
    }
2650
61
    if (ExpectAndConsume(tok::comma)) {
2651
0
      SkipUntil(tok::r_paren, StopAtSemi);
2652
0
      return ExprError();
2653
0
    }
2654
2655
61
    ExprResult Expr1(ParseAssignmentExpression());
2656
61
    if (Expr1.isInvalid()) {
2657
0
      SkipUntil(tok::r_paren, StopAtSemi);
2658
0
      return Expr1;
2659
0
    }
2660
61
    if (ExpectAndConsume(tok::comma)) {
2661
0
      SkipUntil(tok::r_paren, StopAtSemi);
2662
0
      return ExprError();
2663
0
    }
2664
2665
61
    ExprResult Expr2(ParseAssignmentExpression());
2666
61
    if (Expr2.isInvalid()) {
2667
0
      SkipUntil(tok::r_paren, StopAtSemi);
2668
0
      return Expr2;
2669
0
    }
2670
61
    if (Tok.isNot(tok::r_paren)) {
2671
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2672
0
      return ExprError();
2673
0
    }
2674
61
    Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2675
61
                                  Expr2.get(), ConsumeParen());
2676
61
    break;
2677
61
  }
2678
45
  case tok::kw___builtin_astype: {
2679
    // The first argument is an expression to be converted, followed by a comma.
2680
45
    ExprResult Expr(ParseAssignmentExpression());
2681
45
    if (Expr.isInvalid()) {
2682
0
      SkipUntil(tok::r_paren, StopAtSemi);
2683
0
      return ExprError();
2684
0
    }
2685
2686
45
    if (ExpectAndConsume(tok::comma)) {
2687
0
      SkipUntil(tok::r_paren, StopAtSemi);
2688
0
      return ExprError();
2689
0
    }
2690
2691
    // Second argument is the type to bitcast to.
2692
45
    TypeResult DestTy = ParseTypeName();
2693
45
    if (DestTy.isInvalid())
2694
0
      return ExprError();
2695
2696
    // Attempt to consume the r-paren.
2697
45
    if (Tok.isNot(tok::r_paren)) {
2698
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2699
0
      SkipUntil(tok::r_paren, StopAtSemi);
2700
0
      return ExprError();
2701
0
    }
2702
2703
45
    Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2704
45
                                  ConsumeParen());
2705
45
    break;
2706
45
  }
2707
21.8k
  case tok::kw___builtin_convertvector: {
2708
    // The first argument is an expression to be converted, followed by a comma.
2709
21.8k
    ExprResult Expr(ParseAssignmentExpression());
2710
21.8k
    if (Expr.isInvalid()) {
2711
0
      SkipUntil(tok::r_paren, StopAtSemi);
2712
0
      return ExprError();
2713
0
    }
2714
2715
21.8k
    if (ExpectAndConsume(tok::comma)) {
2716
0
      SkipUntil(tok::r_paren, StopAtSemi);
2717
0
      return ExprError();
2718
0
    }
2719
2720
    // Second argument is the type to bitcast to.
2721
21.8k
    TypeResult DestTy = ParseTypeName();
2722
21.8k
    if (DestTy.isInvalid())
2723
0
      return ExprError();
2724
2725
    // Attempt to consume the r-paren.
2726
21.8k
    if (Tok.isNot(tok::r_paren)) {
2727
0
      Diag(Tok, diag::err_expected) << tok::r_paren;
2728
0
      SkipUntil(tok::r_paren, StopAtSemi);
2729
0
      return ExprError();
2730
0
    }
2731
2732
21.8k
    Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2733
21.8k
                                         ConsumeParen());
2734
21.8k
    break;
2735
21.8k
  }
2736
17
  case tok::kw___builtin_COLUMN:
2737
39
  case tok::kw___builtin_FILE:
2738
57
  case tok::kw___builtin_FUNCTION:
2739
108
  case tok::kw___builtin_LINE:
2740
128
  case tok::kw___builtin_source_location: {
2741
    // Attempt to consume the r-paren.
2742
128
    if (Tok.isNot(tok::r_paren)) {
2743
8
      Diag(Tok, diag::err_expected) << tok::r_paren;
2744
8
      SkipUntil(tok::r_paren, StopAtSemi);
2745
8
      return ExprError();
2746
8
    }
2747
120
    SourceLocExpr::IdentKind Kind = [&] {
2748
120
      switch (T) {
2749
20
      case tok::kw___builtin_FILE:
2750
20
        return SourceLocExpr::File;
2751
16
      case tok::kw___builtin_FUNCTION:
2752
16
        return SourceLocExpr::Function;
2753
49
      case tok::kw___builtin_LINE:
2754
49
        return SourceLocExpr::Line;
2755
15
      case tok::kw___builtin_COLUMN:
2756
15
        return SourceLocExpr::Column;
2757
20
      case tok::kw___builtin_source_location:
2758
20
        return SourceLocExpr::SourceLocStruct;
2759
0
      default:
2760
0
        llvm_unreachable("invalid keyword");
2761
120
      }
2762
120
    }();
2763
120
    Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
2764
120
    break;
2765
128
  }
2766
23.5k
  }
2767
2768
23.5k
  if (Res.isInvalid())
2769
49
    return ExprError();
2770
2771
  // These can be followed by postfix-expr pieces because they are
2772
  // primary-expressions.
2773
23.5k
  return ParsePostfixExpressionSuffix(Res.get());
2774
23.5k
}
2775
2776
149
bool Parser::tryParseOpenMPArrayShapingCastPart() {
2777
149
  assert(Tok.is(tok::l_square) && "Expected open bracket");
2778
0
  bool ErrorFound = true;
2779
149
  TentativeParsingAction TPA(*this);
2780
295
  do {
2781
295
    if (Tok.isNot(tok::l_square))
2782
0
      break;
2783
    // Consume '['
2784
295
    ConsumeBracket();
2785
    // Skip inner expression.
2786
295
    while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
2787
295
                      StopAtSemi | StopBeforeMatch))
2788
0
      ;
2789
295
    if (Tok.isNot(tok::r_square))
2790
6
      break;
2791
    // Consume ']'
2792
289
    ConsumeBracket();
2793
    // Found ')' - done.
2794
289
    if (Tok.is(tok::r_paren)) {
2795
137
      ErrorFound = false;
2796
137
      break;
2797
137
    }
2798
289
  } while (
Tok.isNot(tok::annot_pragma_openmp_end)152
);
2799
0
  TPA.Revert();
2800
149
  return !ErrorFound;
2801
149
}
2802
2803
/// ParseParenExpression - This parses the unit that starts with a '(' token,
2804
/// based on what is allowed by ExprType.  The actual thing parsed is returned
2805
/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2806
/// not the parsed cast-expression.
2807
///
2808
/// \verbatim
2809
///       primary-expression: [C99 6.5.1]
2810
///         '(' expression ')'
2811
/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
2812
///       postfix-expression: [C99 6.5.2]
2813
///         '(' type-name ')' '{' initializer-list '}'
2814
///         '(' type-name ')' '{' initializer-list ',' '}'
2815
///       cast-expression: [C99 6.5.4]
2816
///         '(' type-name ')' cast-expression
2817
/// [ARC]   bridged-cast-expression
2818
/// [ARC] bridged-cast-expression:
2819
///         (__bridge type-name) cast-expression
2820
///         (__bridge_transfer type-name) cast-expression
2821
///         (__bridge_retained type-name) cast-expression
2822
///       fold-expression: [C++1z]
2823
///         '(' cast-expression fold-operator '...' ')'
2824
///         '(' '...' fold-operator cast-expression ')'
2825
///         '(' cast-expression fold-operator '...'
2826
///                 fold-operator cast-expression ')'
2827
/// [OPENMP] Array shaping operation
2828
///       '(' '[' expression ']' { '[' expression ']' } cast-expression
2829
/// \endverbatim
2830
ExprResult
2831
Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2832
                             bool isTypeCast, ParsedType &CastTy,
2833
6.02M
                             SourceLocation &RParenLoc) {
2834
6.02M
  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2835
0
  ColonProtectionRAIIObject ColonProtection(*this, false);
2836
6.02M
  BalancedDelimiterTracker T(*this, tok::l_paren);
2837
6.02M
  if (T.consumeOpen())
2838
0
    return ExprError();
2839
6.02M
  SourceLocation OpenLoc = T.getOpenLocation();
2840
2841
6.02M
  PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
2842
2843
6.02M
  ExprResult Result(true);
2844
6.02M
  bool isAmbiguousTypeId;
2845
6.02M
  CastTy = nullptr;
2846
2847
6.02M
  if (Tok.is(tok::code_completion)) {
2848
30
    cutOffParsing();
2849
30
    Actions.CodeCompleteExpression(
2850
30
        getCurScope(), PreferredType.get(Tok.getLocation()),
2851
30
        /*IsParenthesized=*/ExprType >= CompoundLiteral);
2852
30
    return ExprError();
2853
30
  }
2854
2855
  // Diagnose use of bridge casts in non-arc mode.
2856
6.02M
  bool BridgeCast = (getLangOpts().ObjC &&
2857
6.02M
                     Tok.isOneOf(tok::kw___bridge,
2858
716k
                                 tok::kw___bridge_transfer,
2859
716k
                                 tok::kw___bridge_retained,
2860
716k
                                 tok::kw___bridge_retain));
2861
6.02M
  if (BridgeCast && 
!getLangOpts().ObjCAutoRefCount425
) {
2862
86
    if (!TryConsumeToken(tok::kw___bridge)) {
2863
8
      StringRef BridgeCastName = Tok.getName();
2864
8
      SourceLocation BridgeKeywordLoc = ConsumeToken();
2865
8
      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2866
8
        Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2867
8
          << BridgeCastName
2868
8
          << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2869
8
    }
2870
86
    BridgeCast = false;
2871
86
  }
2872
2873
  // None of these cases should fall through with an invalid Result
2874
  // unless they've already reported an error.
2875
6.02M
  if (ExprType >= CompoundStmt && 
Tok.is(tok::l_brace)6.02M
) {
2876
8.96k
    Diag(Tok, OpenLoc.isMacroID() ? 
diag::ext_gnu_statement_expr_macro8.52k
2877
8.96k
                                  : 
diag::ext_gnu_statement_expr437
);
2878
2879
8.96k
    checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
2880
2881
8.96k
    if (!getCurScope()->getFnParent() && 
!getCurScope()->getBlockParent()3
) {
2882
3
      Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2883
8.96k
    } else {
2884
      // Find the nearest non-record decl context. Variables declared in a
2885
      // statement expression behave as if they were declared in the enclosing
2886
      // function, block, or other code construct.
2887
8.96k
      DeclContext *CodeDC = Actions.CurContext;
2888
8.96k
      while (CodeDC->isRecord() || 
isa<EnumDecl>(CodeDC)8.96k
) {
2889
3
        CodeDC = CodeDC->getParent();
2890
3
        assert(CodeDC && !CodeDC->isFileContext() &&
2891
3
               "statement expr not in code context");
2892
3
      }
2893
8.96k
      Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2894
2895
8.96k
      Actions.ActOnStartStmtExpr();
2896
2897
8.96k
      StmtResult Stmt(ParseCompoundStatement(true));
2898
8.96k
      ExprType = CompoundStmt;
2899
2900
      // If the substmt parsed correctly, build the AST node.
2901
8.96k
      if (!Stmt.isInvalid()) {
2902
8.96k
        Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
2903
8.96k
                                       Tok.getLocation());
2904
8.96k
      } else {
2905
0
        Actions.ActOnStmtExprError();
2906
0
      }
2907
8.96k
    }
2908
6.01M
  } else if (ExprType >= CompoundLiteral && 
BridgeCast6.01M
) {
2909
339
    tok::TokenKind tokenKind = Tok.getKind();
2910
339
    SourceLocation BridgeKeywordLoc = ConsumeToken();
2911
2912
    // Parse an Objective-C ARC ownership cast expression.
2913
339
    ObjCBridgeCastKind Kind;
2914
339
    if (tokenKind == tok::kw___bridge)
2915
128
      Kind = OBC_Bridge;
2916
211
    else if (tokenKind == tok::kw___bridge_transfer)
2917
107
      Kind = OBC_BridgeTransfer;
2918
104
    else if (tokenKind == tok::kw___bridge_retained)
2919
100
      Kind = OBC_BridgeRetained;
2920
4
    else {
2921
      // As a hopefully temporary workaround, allow __bridge_retain as
2922
      // a synonym for __bridge_retained, but only in system headers.
2923
4
      assert(tokenKind == tok::kw___bridge_retain);
2924
0
      Kind = OBC_BridgeRetained;
2925
4
      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2926
2
        Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2927
2
          << FixItHint::CreateReplacement(BridgeKeywordLoc,
2928
2
                                          "__bridge_retained");
2929
4
    }
2930
2931
0
    TypeResult Ty = ParseTypeName();
2932
339
    T.consumeClose();
2933
339
    ColonProtection.restore();
2934
339
    RParenLoc = T.getCloseLocation();
2935
2936
339
    PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
2937
339
    ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
2938
2939
339
    if (Ty.isInvalid() || SubExpr.isInvalid())
2940
0
      return ExprError();
2941
2942
339
    return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2943
339
                                        BridgeKeywordLoc, Ty.get(),
2944
339
                                        RParenLoc, SubExpr.get());
2945
6.01M
  } else if (ExprType >= CompoundLiteral &&
2946
6.01M
             
isTypeIdInParens(isAmbiguousTypeId)6.01M
) {
2947
2948
    // Otherwise, this is a compound literal expression or cast expression.
2949
2950
    // In C++, if the type-id is ambiguous we disambiguate based on context.
2951
    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2952
    // in which case we should treat it as type-id.
2953
    // if stopIfCastExpr is false, we need to determine the context past the
2954
    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2955
4.86M
    if (isAmbiguousTypeId && 
!stopIfCastExpr1.71k
) {
2956
1.63k
      ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2957
1.63k
                                                        ColonProtection);
2958
1.63k
      RParenLoc = T.getCloseLocation();
2959
1.63k
      return res;
2960
1.63k
    }
2961
2962
    // Parse the type declarator.
2963
4.86M
    DeclSpec DS(AttrFactory);
2964
4.86M
    ParseSpecifierQualifierList(DS);
2965
4.86M
    Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2966
4.86M
                              DeclaratorContext::TypeName);
2967
4.86M
    ParseDeclarator(DeclaratorInfo);
2968
2969
    // If our type is followed by an identifier and either ':' or ']', then
2970
    // this is probably an Objective-C message send where the leading '[' is
2971
    // missing. Recover as if that were the case.
2972
4.86M
    if (!DeclaratorInfo.isInvalidType() && 
Tok.is(tok::identifier)4.86M
&&
2973
4.86M
        
!InMessageExpression77
&&
getLangOpts().ObjC77
&&
2974
4.86M
        
(75
NextToken().is(tok::colon)75
||
NextToken().is(tok::r_square)0
)) {
2975
75
      TypeResult Ty;
2976
75
      {
2977
75
        InMessageExpressionRAIIObject InMessage(*this, false);
2978
75
        Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2979
75
      }
2980
75
      Result = ParseObjCMessageExpressionBody(SourceLocation(),
2981
75
                                              SourceLocation(),
2982
75
                                              Ty.get(), nullptr);
2983
4.86M
    } else {
2984
      // Match the ')'.
2985
4.86M
      T.consumeClose();
2986
4.86M
      ColonProtection.restore();
2987
4.86M
      RParenLoc = T.getCloseLocation();
2988
4.86M
      if (Tok.is(tok::l_brace)) {
2989
53.6k
        ExprType = CompoundLiteral;
2990
53.6k
        TypeResult Ty;
2991
53.6k
        {
2992
53.6k
          InMessageExpressionRAIIObject InMessage(*this, false);
2993
53.6k
          Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2994
53.6k
        }
2995
53.6k
        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2996
53.6k
      }
2997
2998
4.80M
      if (Tok.is(tok::l_paren)) {
2999
        // This could be OpenCL vector Literals
3000
396k
        if (getLangOpts().OpenCL)
3001
477
        {
3002
477
          TypeResult Ty;
3003
477
          {
3004
477
            InMessageExpressionRAIIObject InMessage(*this, false);
3005
477
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3006
477
          }
3007
477
          if(Ty.isInvalid())
3008
0
          {
3009
0
             return ExprError();
3010
0
          }
3011
477
          QualType QT = Ty.get().get().getCanonicalType();
3012
477
          if (QT->isVectorType())
3013
167
          {
3014
            // We parsed '(' vector-type-name ')' followed by '('
3015
3016
            // Parse the cast-expression that follows it next.
3017
            // isVectorLiteral = true will make sure we don't parse any
3018
            // Postfix expression yet
3019
167
            Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3020
167
                                         /*isAddressOfOperand=*/false,
3021
167
                                         /*isTypeCast=*/IsTypeCast,
3022
167
                                         /*isVectorLiteral=*/true);
3023
3024
167
            if (!Result.isInvalid()) {
3025
167
              Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3026
167
                                             DeclaratorInfo, CastTy,
3027
167
                                             RParenLoc, Result.get());
3028
167
            }
3029
3030
            // After we performed the cast we can check for postfix-expr pieces.
3031
167
            if (!Result.isInvalid()) {
3032
164
              Result = ParsePostfixExpressionSuffix(Result);
3033
164
            }
3034
3035
167
            return Result;
3036
167
          }
3037
477
        }
3038
396k
      }
3039
3040
4.80M
      if (ExprType == CastExpr) {
3041
        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3042
3043
4.80M
        if (DeclaratorInfo.isInvalidType())
3044
7
          return ExprError();
3045
3046
        // Note that this doesn't parse the subsequent cast-expression, it just
3047
        // returns the parsed type to the callee.
3048
4.80M
        if (stopIfCastExpr) {
3049
85.2k
          TypeResult Ty;
3050
85.2k
          {
3051
85.2k
            InMessageExpressionRAIIObject InMessage(*this, false);
3052
85.2k
            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3053
85.2k
          }
3054
85.2k
          CastTy = Ty.get();
3055
85.2k
          return ExprResult();
3056
85.2k
        }
3057
3058
        // Reject the cast of super idiom in ObjC.
3059
4.72M
        if (Tok.is(tok::identifier) && 
getLangOpts().ObjC4.16M
&&
3060
4.72M
            
Tok.getIdentifierInfo() == Ident_super277k
&&
3061
4.72M
            
getCurScope()->isInObjcMethodScope()10
&&
3062
4.72M
            
GetLookAheadToken(1).isNot(tok::period)8
) {
3063
7
          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3064
7
            << SourceRange(OpenLoc, RParenLoc);
3065
7
          return ExprError();
3066
7
        }
3067
3068
4.72M
        PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3069
        // Parse the cast-expression that follows it next.
3070
        // TODO: For cast expression with CastTy.
3071
4.72M
        Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3072
4.72M
                                     /*isAddressOfOperand=*/false,
3073
4.72M
                                     /*isTypeCast=*/IsTypeCast);
3074
4.72M
        if (!Result.isInvalid()) {
3075
4.72M
          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3076
4.72M
                                         DeclaratorInfo, CastTy,
3077
4.72M
                                         RParenLoc, Result.get());
3078
4.72M
        }
3079
4.72M
        return Result;
3080
4.72M
      }
3081
3082
0
      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3083
0
      return ExprError();
3084
4.80M
    }
3085
4.86M
  } else 
if (1.14M
ExprType >= FoldExpr1.14M
&&
Tok.is(tok::ellipsis)1.14M
&&
3086
1.14M
             
isFoldOperator(NextToken().getKind())33
) {
3087
29
    ExprType = FoldExpr;
3088
29
    return ParseFoldExpression(ExprResult(), T);
3089
1.14M
  } else if (isTypeCast) {
3090
    // Parse the expression-list.
3091
323k
    InMessageExpressionRAIIObject InMessage(*this, false);
3092
3093
323k
    ExprVector ArgExprs;
3094
323k
    CommaLocsTy CommaLocs;
3095
3096
323k
    if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
3097
      // FIXME: If we ever support comma expressions as operands to
3098
      // fold-expressions, we'll need to allow multiple ArgExprs here.
3099
323k
      if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3100
323k
          
isFoldOperator(Tok.getKind())322k
&&
NextToken().is(tok::ellipsis)30
) {
3101
30
        ExprType = FoldExpr;
3102
30
        return ParseFoldExpression(ArgExprs[0], T);
3103
30
      }
3104
3105
323k
      ExprType = SimpleExpr;
3106
323k
      Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3107
323k
                                          ArgExprs);
3108
323k
    }
3109
823k
  } else if (getLangOpts().OpenMP >= 50 && 
OpenMPDirectiveParsing3.95k
&&
3110
823k
             
ExprType == CastExpr1.26k
&&
Tok.is(tok::l_square)1.26k
&&
3111
823k
             
tryParseOpenMPArrayShapingCastPart()149
) {
3112
137
    bool ErrorFound = false;
3113
137
    SmallVector<Expr *, 4> OMPDimensions;
3114
137
    SmallVector<SourceRange, 4> OMPBracketsRanges;
3115
283
    do {
3116
283
      BalancedDelimiterTracker TS(*this, tok::l_square);
3117
283
      TS.consumeOpen();
3118
283
      ExprResult NumElements =
3119
283
          Actions.CorrectDelayedTyposInExpr(ParseExpression());
3120
283
      if (!NumElements.isUsable()) {
3121
18
        ErrorFound = true;
3122
18
        while (!SkipUntil(tok::r_square, tok::r_paren,
3123
18
                          StopAtSemi | StopBeforeMatch))
3124
0
          ;
3125
18
      }
3126
283
      TS.consumeClose();
3127
283
      OMPDimensions.push_back(NumElements.get());
3128
283
      OMPBracketsRanges.push_back(TS.getRange());
3129
283
    } while (Tok.isNot(tok::r_paren));
3130
    // Match the ')'.
3131
137
    T.consumeClose();
3132
137
    RParenLoc = T.getCloseLocation();
3133
137
    Result = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3134
137
    if (ErrorFound) {
3135
18
      Result = ExprError();
3136
119
    } else if (!Result.isInvalid()) {
3137
119
      Result = Actions.ActOnOMPArrayShapingExpr(
3138
119
          Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3139
119
    }
3140
137
    return Result;
3141
823k
  } else {
3142
823k
    InMessageExpressionRAIIObject InMessage(*this, false);
3143
3144
823k
    Result = ParseExpression(MaybeTypeCast);
3145
823k
    if (!getLangOpts().CPlusPlus && 
MaybeTypeCast310k
&&
Result.isUsable()310k
) {
3146
      // Correct typos in non-C++ code earlier so that implicit-cast-like
3147
      // expressions are parsed correctly.
3148
310k
      Result = Actions.CorrectDelayedTyposInExpr(Result);
3149
310k
    }
3150
3151
823k
    if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3152
823k
        
NextToken().is(tok::ellipsis)205
) {
3153
205
      ExprType = FoldExpr;
3154
205
      return ParseFoldExpression(Result, T);
3155
205
    }
3156
823k
    ExprType = SimpleExpr;
3157
3158
    // Don't build a paren expression unless we actually match a ')'.
3159
823k
    if (!Result.isInvalid() && 
Tok.is(tok::r_paren)822k
)
3160
822k
      Result =
3161
822k
          Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3162
823k
  }
3163
3164
  // Match the ')'.
3165
1.15M
  if (Result.isInvalid()) {
3166
488
    SkipUntil(tok::r_paren, StopAtSemi);
3167
488
    return ExprError();
3168
488
  }
3169
3170
1.15M
  T.consumeClose();
3171
1.15M
  RParenLoc = T.getCloseLocation();
3172
1.15M
  return Result;
3173
1.15M
}
3174
3175
/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3176
/// and we are at the left brace.
3177
///
3178
/// \verbatim
3179
///       postfix-expression: [C99 6.5.2]
3180
///         '(' type-name ')' '{' initializer-list '}'
3181
///         '(' type-name ')' '{' initializer-list ',' '}'
3182
/// \endverbatim
3183
ExprResult
3184
Parser::ParseCompoundLiteralExpression(ParsedType Ty,
3185
                                       SourceLocation LParenLoc,
3186
53.6k
                                       SourceLocation RParenLoc) {
3187
53.6k
  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3188
53.6k
  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
3189
6.81k
    Diag(LParenLoc, diag::ext_c99_compound_literal);
3190
53.6k
  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
3191
53.6k
  ExprResult Result = ParseInitializer();
3192
53.6k
  if (!Result.isInvalid() && 
Ty53.6k
)
3193
53.6k
    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3194
6
  return Result;
3195
53.6k
}
3196
3197
/// ParseStringLiteralExpression - This handles the various token types that
3198
/// form string literals, and also handles string concatenation [C99 5.1.1.2,
3199
/// translation phase #6].
3200
///
3201
/// \verbatim
3202
///       primary-expression: [C99 6.5.1]
3203
///         string-literal
3204
/// \verbatim
3205
5.40M
ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3206
5.40M
  assert(isTokenStringLiteral() && "Not a string literal!");
3207
3208
  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
3209
  // considered to be strings for concatenation purposes.
3210
0
  SmallVector<Token, 4> StringToks;
3211
3212
5.57M
  do {
3213
5.57M
    StringToks.push_back(Tok);
3214
5.57M
    ConsumeStringToken();
3215
5.57M
  } while (isTokenStringLiteral());
3216
3217
  // Pass the set of string tokens, ready for concatenation, to the actions.
3218
5.40M
  return Actions.ActOnStringLiteral(StringToks,
3219
5.40M
                                    AllowUserDefinedLiteral ? 
getCurScope()4.49M
3220
5.40M
                                                            : 
nullptr911k
);
3221
5.40M
}
3222
3223
/// ParseGenericSelectionExpression - Parse a C11 generic-selection
3224
/// [C11 6.5.1.1].
3225
///
3226
/// \verbatim
3227
///    generic-selection:
3228
///           _Generic ( assignment-expression , generic-assoc-list )
3229
///    generic-assoc-list:
3230
///           generic-association
3231
///           generic-assoc-list , generic-association
3232
///    generic-association:
3233
///           type-name : assignment-expression
3234
///           default : assignment-expression
3235
/// \endverbatim
3236
316
ExprResult Parser::ParseGenericSelectionExpression() {
3237
316
  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3238
316
  if (!getLangOpts().C11)
3239
117
    Diag(Tok, diag::ext_c11_feature) << Tok.getName();
3240
3241
316
  SourceLocation KeyLoc = ConsumeToken();
3242
316
  BalancedDelimiterTracker T(*this, tok::l_paren);
3243
316
  if (T.expectAndConsume())
3244
1
    return ExprError();
3245
3246
315
  ExprResult ControllingExpr;
3247
315
  {
3248
    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3249
    // not evaluated."
3250
315
    EnterExpressionEvaluationContext Unevaluated(
3251
315
        Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3252
315
    ControllingExpr =
3253
315
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3254
315
    if (ControllingExpr.isInvalid()) {
3255
1
      SkipUntil(tok::r_paren, StopAtSemi);
3256
1
      return ExprError();
3257
1
    }
3258
315
  }
3259
3260
314
  if (ExpectAndConsume(tok::comma)) {
3261
1
    SkipUntil(tok::r_paren, StopAtSemi);
3262
1
    return ExprError();
3263
1
  }
3264
3265
313
  SourceLocation DefaultLoc;
3266
313
  TypeVector Types;
3267
313
  ExprVector Exprs;
3268
600
  do {
3269
600
    ParsedType Ty;
3270
600
    if (Tok.is(tok::kw_default)) {
3271
      // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3272
      // generic association."
3273
110
      if (!DefaultLoc.isInvalid()) {
3274
1
        Diag(Tok, diag::err_duplicate_default_assoc);
3275
1
        Diag(DefaultLoc, diag::note_previous_default_assoc);
3276
1
        SkipUntil(tok::r_paren, StopAtSemi);
3277
1
        return ExprError();
3278
1
      }
3279
109
      DefaultLoc = ConsumeToken();
3280
109
      Ty = nullptr;
3281
490
    } else {
3282
490
      ColonProtectionRAIIObject X(*this);
3283
490
      TypeResult TR = ParseTypeName(nullptr, DeclaratorContext::Association);
3284
490
      if (TR.isInvalid()) {
3285
1
        SkipUntil(tok::r_paren, StopAtSemi);
3286
1
        return ExprError();
3287
1
      }
3288
489
      Ty = TR.get();
3289
489
    }
3290
598
    Types.push_back(Ty);
3291
3292
598
    if (ExpectAndConsume(tok::colon)) {
3293
1
      SkipUntil(tok::r_paren, StopAtSemi);
3294
1
      return ExprError();
3295
1
    }
3296
3297
    // FIXME: These expressions should be parsed in a potentially potentially
3298
    // evaluated context.
3299
597
    ExprResult ER(
3300
597
        Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
3301
597
    if (ER.isInvalid()) {
3302
2
      SkipUntil(tok::r_paren, StopAtSemi);
3303
2
      return ExprError();
3304
2
    }
3305
595
    Exprs.push_back(ER.get());
3306
595
  } while (TryConsumeToken(tok::comma));
3307
3308
308
  T.consumeClose();
3309
308
  if (T.getCloseLocation().isInvalid())
3310
0
    return ExprError();
3311
3312
308
  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
3313
308
                                           T.getCloseLocation(),
3314
308
                                           ControllingExpr.get(),
3315
308
                                           Types, Exprs);
3316
308
}
3317
3318
/// Parse A C++1z fold-expression after the opening paren and optional
3319
/// left-hand-side expression.
3320
///
3321
/// \verbatim
3322
///   fold-expression:
3323
///       ( cast-expression fold-operator ... )
3324
///       ( ... fold-operator cast-expression )
3325
///       ( cast-expression fold-operator ... fold-operator cast-expression )
3326
ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3327
264
                                       BalancedDelimiterTracker &T) {
3328
264
  if (LHS.isInvalid()) {
3329
1
    T.skipToEnd();
3330
1
    return true;
3331
1
  }
3332
3333
263
  tok::TokenKind Kind = tok::unknown;
3334
263
  SourceLocation FirstOpLoc;
3335
263
  if (LHS.isUsable()) {
3336
234
    Kind = Tok.getKind();
3337
234
    assert(isFoldOperator(Kind) && "missing fold-operator");
3338
0
    FirstOpLoc = ConsumeToken();
3339
234
  }
3340
3341
0
  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3342
0
  SourceLocation EllipsisLoc = ConsumeToken();
3343
3344
263
  ExprResult RHS;
3345
263
  if (Tok.isNot(tok::r_paren)) {
3346
89
    if (!isFoldOperator(Tok.getKind()))
3347
1
      return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3348
3349
88
    if (Kind != tok::unknown && 
Tok.getKind() != Kind59
)
3350
2
      Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3351
2
        << SourceRange(FirstOpLoc);
3352
88
    Kind = Tok.getKind();
3353
88
    ConsumeToken();
3354
3355
88
    RHS = ParseExpression();
3356
88
    if (RHS.isInvalid()) {
3357
0
      T.skipToEnd();
3358
0
      return true;
3359
0
    }
3360
88
  }
3361
3362
262
  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3363
262
                        ? 
diag::warn_cxx14_compat_fold_expression224
3364
262
                        : 
diag::ext_fold_expression38
);
3365
3366
262
  T.consumeClose();
3367
262
  return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3368
262
                                  Kind, EllipsisLoc, RHS.get(),
3369
262
                                  T.getCloseLocation());
3370
263
}
3371
3372
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3373
///
3374
/// \verbatim
3375
///       argument-expression-list:
3376
///         assignment-expression
3377
///         argument-expression-list , assignment-expression
3378
///
3379
/// [C++] expression-list:
3380
/// [C++]   assignment-expression
3381
/// [C++]   expression-list , assignment-expression
3382
///
3383
/// [C++0x] expression-list:
3384
/// [C++0x]   initializer-list
3385
///
3386
/// [C++0x] initializer-list
3387
/// [C++0x]   initializer-clause ...[opt]
3388
/// [C++0x]   initializer-list , initializer-clause ...[opt]
3389
///
3390
/// [C++0x] initializer-clause:
3391
/// [C++0x]   assignment-expression
3392
/// [C++0x]   braced-init-list
3393
/// \endverbatim
3394
bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3395
                                 SmallVectorImpl<SourceLocation> &CommaLocs,
3396
                                 llvm::function_ref<void()> ExpressionStarts,
3397
                                 bool FailImmediatelyOnInvalidExpr,
3398
10.6M
                                 bool EarlyTypoCorrection) {
3399
10.6M
  bool SawError = false;
3400
16.5M
  while (true) {
3401
16.5M
    if (ExpressionStarts)
3402
10.7M
      ExpressionStarts();
3403
3404
16.5M
    ExprResult Expr;
3405
16.5M
    if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::l_brace)8.16M
) {
3406
2.01k
      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3407
2.01k
      Expr = ParseBraceInitializer();
3408
2.01k
    } else
3409
16.5M
      Expr = ParseAssignmentExpression();
3410
3411
16.5M
    if (EarlyTypoCorrection)
3412
5.79M
      Expr = Actions.CorrectDelayedTyposInExpr(Expr);
3413
3414
16.5M
    if (Tok.is(tok::ellipsis))
3415
49.2k
      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3416
16.5M
    else if (Tok.is(tok::code_completion)) {
3417
      // There's nothing to suggest in here as we parsed a full expression.
3418
      // Instead fail and propogate the error since caller might have something
3419
      // the suggest, e.g. signature help in function call. Note that this is
3420
      // performed before pushing the \p Expr, so that signature help can report
3421
      // current argument correctly.
3422
1
      SawError = true;
3423
1
      cutOffParsing();
3424
1
      break;
3425
1
    }
3426
16.5M
    if (Expr.isInvalid()) {
3427
3.66k
      SawError = true;
3428
3.66k
      if (FailImmediatelyOnInvalidExpr)
3429
46
        break;
3430
3.62k
      SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3431
16.5M
    } else {
3432
16.5M
      Exprs.push_back(Expr.get());
3433
16.5M
    }
3434
3435
16.5M
    if (Tok.isNot(tok::comma))
3436
10.6M
      break;
3437
    // Move to the next argument, remember where the comma was.
3438
5.90M
    Token Comma = Tok;
3439
5.90M
    CommaLocs.push_back(ConsumeToken());
3440
3441
5.90M
    checkPotentialAngleBracketDelimiter(Comma);
3442
5.90M
  }
3443
10.6M
  if (SawError) {
3444
    // Ensure typos get diagnosed when errors were encountered while parsing the
3445
    // expression list.
3446
3.66k
    for (auto &E : Exprs) {
3447
3.35k
      ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
3448
3.35k
      if (Expr.isUsable()) 
E = Expr.get()2.52k
;
3449
3.35k
    }
3450
3.66k
  }
3451
10.6M
  return SawError;
3452
10.6M
}
3453
3454
/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3455
/// used for misc language extensions.
3456
///
3457
/// \verbatim
3458
///       simple-expression-list:
3459
///         assignment-expression
3460
///         simple-expression-list , assignment-expression
3461
/// \endverbatim
3462
bool
3463
Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
3464
324k
                                  SmallVectorImpl<SourceLocation> &CommaLocs) {
3465
347k
  while (true) {
3466
347k
    ExprResult Expr = ParseAssignmentExpression();
3467
347k
    if (Expr.isInvalid())
3468
9
      return true;
3469
3470
347k
    Exprs.push_back(Expr.get());
3471
3472
347k
    if (Tok.isNot(tok::comma))
3473
324k
      return false;
3474
3475
    // Move to the next argument, remember where the comma was.
3476
23.2k
    Token Comma = Tok;
3477
23.2k
    CommaLocs.push_back(ConsumeToken());
3478
3479
23.2k
    checkPotentialAngleBracketDelimiter(Comma);
3480
23.2k
  }
3481
324k
}
3482
3483
/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3484
///
3485
/// \verbatim
3486
/// [clang] block-id:
3487
/// [clang]   specifier-qualifier-list block-declarator
3488
/// \endverbatim
3489
347
void Parser::ParseBlockId(SourceLocation CaretLoc) {
3490
347
  if (Tok.is(tok::code_completion)) {
3491
1
    cutOffParsing();
3492
1
    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
3493
1
    return;
3494
1
  }
3495
3496
  // Parse the specifier-qualifier-list piece.
3497
346
  DeclSpec DS(AttrFactory);
3498
346
  ParseSpecifierQualifierList(DS);
3499
3500
  // Parse the block-declarator.
3501
346
  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3502
346
                            DeclaratorContext::BlockLiteral);
3503
346
  DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3504
346
  ParseDeclarator(DeclaratorInfo);
3505
3506
346
  MaybeParseGNUAttributes(DeclaratorInfo);
3507
3508
  // Inform sema that we are starting a block.
3509
346
  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3510
346
}
3511
3512
/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3513
/// like ^(int x){ return x+1; }
3514
///
3515
/// \verbatim
3516
///         block-literal:
3517
/// [clang]   '^' block-args[opt] compound-statement
3518
/// [clang]   '^' block-id compound-statement
3519
/// [clang] block-args:
3520
/// [clang]   '(' parameter-list ')'
3521
/// \endverbatim
3522
3.33k
ExprResult Parser::ParseBlockLiteralExpression() {
3523
3.33k
  assert(Tok.is(tok::caret) && "block literal starts with ^");
3524
0
  SourceLocation CaretLoc = ConsumeToken();
3525
3526
3.33k
  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3527
3.33k
                                "block literal parsing");
3528
3529
  // Enter a scope to hold everything within the block.  This includes the
3530
  // argument decls, decls within the compound expression, etc.  This also
3531
  // allows determining whether a variable reference inside the block is
3532
  // within or outside of the block.
3533
3.33k
  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3534
3.33k
                                  Scope::CompoundStmtScope | Scope::DeclScope);
3535
3536
  // Inform sema that we are starting a block.
3537
3.33k
  Actions.ActOnBlockStart(CaretLoc, getCurScope());
3538
3539
  // Parse the return type if present.
3540
3.33k
  DeclSpec DS(AttrFactory);
3541
3.33k
  Declarator ParamInfo(DS, ParsedAttributesView::none(),
3542
3.33k
                       DeclaratorContext::BlockLiteral);
3543
3.33k
  ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3544
  // FIXME: Since the return type isn't actually parsed, it can't be used to
3545
  // fill ParamInfo with an initial valid range, so do it manually.
3546
3.33k
  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3547
3548
  // If this block has arguments, parse them.  There is no ambiguity here with
3549
  // the expression case, because the expression case requires a parameter list.
3550
3.33k
  if (Tok.is(tok::l_paren)) {
3551
1.28k
    ParseParenDeclarator(ParamInfo);
3552
    // Parse the pieces after the identifier as if we had "int(...)".
3553
    // SetIdentifier sets the source range end, but in this case we're past
3554
    // that location.
3555
1.28k
    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3556
1.28k
    ParamInfo.SetIdentifier(nullptr, CaretLoc);
3557
1.28k
    ParamInfo.SetRangeEnd(Tmp);
3558
1.28k
    if (ParamInfo.isInvalidType()) {
3559
      // If there was an error parsing the arguments, they may have
3560
      // tried to use ^(x+y) which requires an argument list.  Just
3561
      // skip the whole block literal.
3562
0
      Actions.ActOnBlockError(CaretLoc, getCurScope());
3563
0
      return ExprError();
3564
0
    }
3565
3566
1.28k
    MaybeParseGNUAttributes(ParamInfo);
3567
3568
    // Inform sema that we are starting a block.
3569
1.28k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3570
2.04k
  } else if (!Tok.is(tok::l_brace)) {
3571
347
    ParseBlockId(CaretLoc);
3572
1.69k
  } else {
3573
    // Otherwise, pretend we saw (void).
3574
1.69k
    SourceLocation NoLoc;
3575
1.69k
    ParamInfo.AddTypeInfo(
3576
1.69k
        DeclaratorChunk::getFunction(/*HasProto=*/true,
3577
1.69k
                                     /*IsAmbiguous=*/false,
3578
1.69k
                                     /*RParenLoc=*/NoLoc,
3579
1.69k
                                     /*ArgInfo=*/nullptr,
3580
1.69k
                                     /*NumParams=*/0,
3581
1.69k
                                     /*EllipsisLoc=*/NoLoc,
3582
1.69k
                                     /*RParenLoc=*/NoLoc,
3583
1.69k
                                     /*RefQualifierIsLvalueRef=*/true,
3584
1.69k
                                     /*RefQualifierLoc=*/NoLoc,
3585
1.69k
                                     /*MutableLoc=*/NoLoc, EST_None,
3586
1.69k
                                     /*ESpecRange=*/SourceRange(),
3587
1.69k
                                     /*Exceptions=*/nullptr,
3588
1.69k
                                     /*ExceptionRanges=*/nullptr,
3589
1.69k
                                     /*NumExceptions=*/0,
3590
1.69k
                                     /*NoexceptExpr=*/nullptr,
3591
1.69k
                                     /*ExceptionSpecTokens=*/nullptr,
3592
1.69k
                                     /*DeclsInPrototype=*/None, CaretLoc,
3593
1.69k
                                     CaretLoc, ParamInfo),
3594
1.69k
        CaretLoc);
3595
3596
1.69k
    MaybeParseGNUAttributes(ParamInfo);
3597
3598
    // Inform sema that we are starting a block.
3599
1.69k
    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3600
1.69k
  }
3601
3602
3603
3.33k
  ExprResult Result(true);
3604
3.33k
  if (!Tok.is(tok::l_brace)) {
3605
    // Saw something like: ^expr
3606
131
    Diag(Tok, diag::err_expected_expression);
3607
131
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3608
131
    return ExprError();
3609
131
  }
3610
3611
3.20k
  StmtResult Stmt(ParseCompoundStatementBody());
3612
3.20k
  BlockScope.Exit();
3613
3.20k
  if (!Stmt.isInvalid())
3614
3.20k
    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3615
0
  else
3616
0
    Actions.ActOnBlockError(CaretLoc, getCurScope());
3617
3.20k
  return Result;
3618
3.33k
}
3619
3620
/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3621
///
3622
///         '__objc_yes'
3623
///         '__objc_no'
3624
919
ExprResult Parser::ParseObjCBoolLiteral() {
3625
919
  tok::TokenKind Kind = Tok.getKind();
3626
919
  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3627
919
}
3628
3629
/// Validate availability spec list, emitting diagnostics if necessary. Returns
3630
/// true if invalid.
3631
static bool CheckAvailabilitySpecList(Parser &P,
3632
110
                                      ArrayRef<AvailabilitySpec> AvailSpecs) {
3633
110
  llvm::SmallSet<StringRef, 4> Platforms;
3634
110
  bool HasOtherPlatformSpec = false;
3635
110
  bool Valid = true;
3636
228
  for (const auto &Spec : AvailSpecs) {
3637
228
    if (Spec.isOtherPlatformSpec()) {
3638
109
      if (HasOtherPlatformSpec) {
3639
0
        P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
3640
0
        Valid = false;
3641
0
      }
3642
3643
109
      HasOtherPlatformSpec = true;
3644
109
      continue;
3645
109
    }
3646
3647
119
    bool Inserted = Platforms.insert(Spec.getPlatform()).second;
3648
119
    if (!Inserted) {
3649
      // Rule out multiple version specs referring to the same platform.
3650
      // For example, we emit an error for:
3651
      // @available(macos 10.10, macos 10.11, *)
3652
1
      StringRef Platform = Spec.getPlatform();
3653
1
      P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
3654
1
          << Spec.getEndLoc() << Platform;
3655
1
      Valid = false;
3656
1
    }
3657
119
  }
3658
3659
110
  if (!HasOtherPlatformSpec) {
3660
1
    SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
3661
1
    P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
3662
1
        << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
3663
1
    return true;
3664
1
  }
3665
3666
109
  return !Valid;
3667
110
}
3668
3669
/// Parse availability query specification.
3670
///
3671
///  availability-spec:
3672
///     '*'
3673
///     identifier version-tuple
3674
239
Optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
3675
239
  if (Tok.is(tok::star)) {
3676
111
    return AvailabilitySpec(ConsumeToken());
3677
128
  } else {
3678
    // Parse the platform name.
3679
128
    if (Tok.is(tok::code_completion)) {
3680
2
      cutOffParsing();
3681
2
      Actions.CodeCompleteAvailabilityPlatformName();
3682
2
      return None;
3683
2
    }
3684
126
    if (Tok.isNot(tok::identifier)) {
3685
2
      Diag(Tok, diag::err_avail_query_expected_platform_name);
3686
2
      return None;
3687
2
    }
3688
3689
124
    IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
3690
124
    SourceRange VersionRange;
3691
124
    VersionTuple Version = ParseVersionTuple(VersionRange);
3692
3693
124
    if (Version.empty())
3694
1
      return None;
3695
3696
123
    StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
3697
123
    StringRef Platform =
3698
123
        AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
3699
3700
123
    if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) {
3701
3
      Diag(PlatformIdentifier->Loc,
3702
3
           diag::err_avail_query_unrecognized_platform_name)
3703
3
          << GivenPlatform;
3704
3
      return None;
3705
3
    }
3706
3707
120
    return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
3708
120
                            VersionRange.getEnd());
3709
123
  }
3710
239
}
3711
3712
118
ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
3713
118
  assert(Tok.is(tok::kw___builtin_available) ||
3714
118
         Tok.isObjCAtKeyword(tok::objc_available));
3715
3716
  // Eat the available or __builtin_available.
3717
0
  ConsumeToken();
3718
3719
118
  BalancedDelimiterTracker Parens(*this, tok::l_paren);
3720
118
  if (Parens.expectAndConsume())
3721
1
    return ExprError();
3722
3723
117
  SmallVector<AvailabilitySpec, 4> AvailSpecs;
3724
117
  bool HasError = false;
3725
239
  while (true) {
3726
239
    Optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
3727
239
    if (!Spec)
3728
8
      HasError = true;
3729
231
    else
3730
231
      AvailSpecs.push_back(*Spec);
3731
3732
239
    if (!TryConsumeToken(tok::comma))
3733
117
      break;
3734
239
  }
3735
3736
117
  if (HasError) {
3737
7
    SkipUntil(tok::r_paren, StopAtSemi);
3738
7
    return ExprError();
3739
7
  }
3740
3741
110
  CheckAvailabilitySpecList(*this, AvailSpecs);
3742
3743
110
  if (Parens.consumeClose())
3744
0
    return ExprError();
3745
3746
110
  return Actions.ActOnObjCAvailabilityCheckExpr(AvailSpecs, BeginLoc,
3747
110
                                                Parens.getCloseLocation());
3748
110
}