Coverage Report

Created: 2021-08-24 07:12

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