Coverage Report

Created: 2021-01-19 06:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Parse/ParseStmt.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the Statement and Block portions of the Parser
10
// interface.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/AST/PrettyDeclStackTrace.h"
15
#include "clang/Basic/Attributes.h"
16
#include "clang/Basic/PrettyStackTrace.h"
17
#include "clang/Parse/LoopHint.h"
18
#include "clang/Parse/Parser.h"
19
#include "clang/Parse/RAIIObjectsForParser.h"
20
#include "clang/Sema/DeclSpec.h"
21
#include "clang/Sema/Scope.h"
22
#include "clang/Sema/TypoCorrection.h"
23
using namespace clang;
24
25
//===----------------------------------------------------------------------===//
26
// C99 6.8: Statements and Blocks.
27
//===----------------------------------------------------------------------===//
28
29
/// Parse a standalone statement (for instance, as the body of an 'if',
30
/// 'while', or 'for').
31
StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
32
992k
                                  ParsedStmtContext StmtCtx) {
33
992k
  StmtResult Res;
34
35
  // We may get back a null statement if we found a #pragma. Keep going until
36
  // we get an actual statement.
37
992k
  do {
38
992k
    StmtVector Stmts;
39
992k
    Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
40
992k
  } while (!Res.isInvalid() && 
!Res.get()986k
);
41
42
992k
  return Res;
43
992k
}
44
45
/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
46
///       StatementOrDeclaration:
47
///         statement
48
///         declaration
49
///
50
///       statement:
51
///         labeled-statement
52
///         compound-statement
53
///         expression-statement
54
///         selection-statement
55
///         iteration-statement
56
///         jump-statement
57
/// [C++]   declaration-statement
58
/// [C++]   try-block
59
/// [MS]    seh-try-block
60
/// [OBC]   objc-throw-statement
61
/// [OBC]   objc-try-catch-statement
62
/// [OBC]   objc-synchronized-statement
63
/// [GNU]   asm-statement
64
/// [OMP]   openmp-construct             [TODO]
65
///
66
///       labeled-statement:
67
///         identifier ':' statement
68
///         'case' constant-expression ':' statement
69
///         'default' ':' statement
70
///
71
///       selection-statement:
72
///         if-statement
73
///         switch-statement
74
///
75
///       iteration-statement:
76
///         while-statement
77
///         do-statement
78
///         for-statement
79
///
80
///       expression-statement:
81
///         expression[opt] ';'
82
///
83
///       jump-statement:
84
///         'goto' identifier ';'
85
///         'continue' ';'
86
///         'break' ';'
87
///         'return' expression[opt] ';'
88
/// [GNU]   'goto' '*' expression ';'
89
///
90
/// [OBC] objc-throw-statement:
91
/// [OBC]   '@' 'throw' expression ';'
92
/// [OBC]   '@' 'throw' ';'
93
///
94
StmtResult
95
Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
96
                                    ParsedStmtContext StmtCtx,
97
7.25M
                                    SourceLocation *TrailingElseLoc) {
98
99
7.25M
  ParenBraceBracketBalancer BalancerRAIIObj(*this);
100
101
7.25M
  ParsedAttributesWithRange Attrs(AttrFactory);
102
7.25M
  MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
103
7.25M
  if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
104
1
    return StmtError();
105
106
7.25M
  StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
107
7.25M
      Stmts, StmtCtx, TrailingElseLoc, Attrs);
108
7.25M
  MaybeDestroyTemplateIds();
109
110
7.25M
  assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
111
7.25M
         "attributes on empty statement");
112
113
7.25M
  if (Attrs.empty() || 
Res.isInvalid()1.36k
)
114
7.25M
    return Res;
115
116
1.36k
  return Actions.ProcessStmtAttributes(Res.get(), Attrs, Attrs.Range);
117
1.36k
}
118
119
namespace {
120
class StatementFilterCCC final : public CorrectionCandidateCallback {
121
public:
122
2.18M
  StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
123
2.18M
    WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
124
2.18M
                                         tok::identifier, tok::star, tok::amp);
125
2.18M
    WantExpressionKeywords =
126
2.18M
        nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
127
2.18M
    WantRemainingKeywords =
128
2.18M
        nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
129
2.18M
    WantCXXNamedCasts = false;
130
2.18M
  }
131
132
190
  bool ValidateCandidate(const TypoCorrection &candidate) override {
133
190
    if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
134
17
      return !candidate.getCorrectionSpecifier() || 
isa<ObjCIvarDecl>(FD)2
;
135
173
    if (NextToken.is(tok::equal))
136
46
      return candidate.getCorrectionDeclAs<VarDecl>();
137
127
    if (NextToken.is(tok::period) &&
138
16
        candidate.getCorrectionDeclAs<NamespaceDecl>())
139
2
      return false;
140
125
    return CorrectionCandidateCallback::ValidateCandidate(candidate);
141
125
  }
142
143
211
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
144
211
    return std::make_unique<StatementFilterCCC>(*this);
145
211
  }
146
147
private:
148
  Token NextToken;
149
};
150
}
151
152
StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
153
    StmtVector &Stmts, ParsedStmtContext StmtCtx,
154
7.25M
    SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) {
155
7.25M
  const char *SemiError = nullptr;
156
7.25M
  StmtResult Res;
157
7.25M
  SourceLocation GNUAttributeLoc;
158
159
  // Cases in this switch statement should fall through if the parser expects
160
  // the token to end in a semicolon (in which case SemiError should be set),
161
  // or they directly 'return;' if not.
162
9.43M
Retry:
163
9.43M
  tok::TokenKind Kind  = Tok.getKind();
164
9.43M
  SourceLocation AtLoc;
165
9.43M
  switch (Kind) {
166
974
  case tok::at: // May be a @try or @throw statement
167
974
    {
168
974
      ProhibitAttributes(Attrs); // TODO: is it correct?
169
974
      AtLoc = ConsumeToken();  // consume @
170
974
      return ParseObjCAtStatement(AtLoc, StmtCtx);
171
0
    }
172
173
135
  case tok::code_completion:
174
135
    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
175
135
    cutOffParsing();
176
135
    return StmtError();
177
178
2.31M
  case tok::identifier: {
179
2.31M
    Token Next = NextToken();
180
2.31M
    if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
181
      // identifier ':' statement
182
3.99k
      return ParseLabeledStatement(Attrs, StmtCtx);
183
3.99k
    }
184
185
    // Look up the identifier, and typo-correct it to a keyword if it's not
186
    // found.
187
2.31M
    if (Next.isNot(tok::coloncolon)) {
188
      // Try to limit which sets of keywords should be included in typo
189
      // correction based on what the next token is.
190
2.18M
      StatementFilterCCC CCC(Next);
191
2.18M
      if (TryAnnotateName(&CCC) == ANK_Error) {
192
        // Handle errors here by skipping up to the next semicolon or '}', and
193
        // eat the semicolon if that's what stopped us.
194
44
        SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
195
44
        if (Tok.is(tok::semi))
196
37
          ConsumeToken();
197
44
        return StmtError();
198
44
      }
199
200
      // If the identifier was typo-corrected, try again.
201
2.18M
      if (Tok.isNot(tok::identifier))
202
2.17M
        goto Retry;
203
132k
    }
204
205
    // Fall through
206
132k
    LLVM_FALLTHROUGH;
207
132k
  }
208
209
3.05M
  default: {
210
3.05M
    if ((getLangOpts().CPlusPlus || 
getLangOpts().MicrosoftExt1.04M
||
211
1.03M
         (StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
212
1.03M
             ParsedStmtContext()) &&
213
3.04M
        (GNUAttributeLoc.isValid() || 
isDeclarationStatement()3.04M
)) {
214
1.18M
      SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
215
1.18M
      DeclGroupPtrTy Decl;
216
1.18M
      if (GNUAttributeLoc.isValid()) {
217
2.28k
        DeclStart = GNUAttributeLoc;
218
2.28k
        Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, Attrs,
219
2.28k
                                &GNUAttributeLoc);
220
1.18M
      } else {
221
1.18M
        Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, Attrs);
222
1.18M
      }
223
1.18M
      if (Attrs.Range.getBegin().isValid())
224
107
        DeclStart = Attrs.Range.getBegin();
225
1.18M
      return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
226
1.18M
    }
227
228
1.86M
    if (Tok.is(tok::r_brace)) {
229
30
      Diag(Tok, diag::err_expected_statement);
230
30
      return StmtError();
231
30
    }
232
233
1.86M
    return ParseExprStatement(StmtCtx);
234
1.86M
  }
235
236
2.28k
  case tok::kw___attribute: {
237
2.28k
    GNUAttributeLoc = Tok.getLocation();
238
2.28k
    ParseGNUAttributes(Attrs);
239
2.28k
    goto Retry;
240
1.86M
  }
241
242
17.8k
  case tok::kw_case:                // C99 6.8.1: labeled-statement
243
17.8k
    return ParseCaseStatement(StmtCtx);
244
2.12k
  case tok::kw_default:             // C99 6.8.1: labeled-statement
245
2.12k
    return ParseDefaultStatement(StmtCtx);
246
247
365k
  case tok::l_brace:                // C99 6.8.2: compound-statement
248
365k
    return ParseCompoundStatement();
249
36.2k
  case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
250
36.2k
    bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
251
36.2k
    return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
252
1.86M
  }
253
254
427k
  case tok::kw_if:                  // C99 6.8.4.1: if-statement
255
427k
    return ParseIfStatement(TrailingElseLoc);
256
6.08k
  case tok::kw_switch:              // C99 6.8.4.2: switch-statement
257
6.08k
    return ParseSwitchStatement(TrailingElseLoc);
258
259
42.4k
  case tok::kw_while:               // C99 6.8.5.1: while-statement
260
42.4k
    return ParseWhileStatement(TrailingElseLoc);
261
7.63k
  case tok::kw_do:                  // C99 6.8.5.2: do-statement
262
7.63k
    Res = ParseDoStatement();
263
7.63k
    SemiError = "do/while";
264
7.63k
    break;
265
184k
  case tok::kw_for:                 // C99 6.8.5.3: for-statement
266
184k
    return ParseForStatement(TrailingElseLoc);
267
268
7.36k
  case tok::kw_goto:                // C99 6.8.6.1: goto-statement
269
7.36k
    Res = ParseGotoStatement();
270
7.36k
    SemiError = "goto";
271
7.36k
    break;
272
5.99k
  case tok::kw_continue:            // C99 6.8.6.2: continue-statement
273
5.99k
    Res = ParseContinueStatement();
274
5.99k
    SemiError = "continue";
275
5.99k
    break;
276
32.6k
  case tok::kw_break:               // C99 6.8.6.3: break-statement
277
32.6k
    Res = ParseBreakStatement();
278
32.6k
    SemiError = "break";
279
32.6k
    break;
280
2.81M
  case tok::kw_return:              // C99 6.8.6.4: return-statement
281
2.81M
    Res = ParseReturnStatement();
282
2.81M
    SemiError = "return";
283
2.81M
    break;
284
103
  case tok::kw_co_return:            // C++ Coroutines: co_return statement
285
103
    Res = ParseReturnStatement();
286
103
    SemiError = "co_return";
287
103
    break;
288
289
6.59k
  case tok::kw_asm: {
290
6.59k
    ProhibitAttributes(Attrs);
291
6.59k
    bool msAsm = false;
292
6.59k
    Res = ParseAsmStatement(msAsm);
293
6.59k
    Res = Actions.ActOnFinishFullStmt(Res.get());
294
6.59k
    if (msAsm) 
return Res245
;
295
6.35k
    SemiError = "asm";
296
6.35k
    break;
297
6.35k
  }
298
299
15
  case tok::kw___if_exists:
300
29
  case tok::kw___if_not_exists:
301
29
    ProhibitAttributes(Attrs);
302
29
    ParseMicrosoftIfExistsStatement(Stmts);
303
    // An __if_exists block is like a compound statement, but it doesn't create
304
    // a new scope.
305
29
    return StmtEmpty();
306
307
10.3k
  case tok::kw_try:                 // C++ 15: try-block
308
10.3k
    return ParseCXXTryBlock();
309
310
272
  case tok::kw___try:
311
272
    ProhibitAttributes(Attrs); // TODO: is it correct?
312
272
    return ParseSEHTryBlock();
313
314
34
  case tok::kw___leave:
315
34
    Res = ParseSEHLeaveStatement();
316
34
    SemiError = "__leave";
317
34
    break;
318
319
0
  case tok::annot_pragma_vis:
320
0
    ProhibitAttributes(Attrs);
321
0
    HandlePragmaVisibility();
322
0
    return StmtEmpty();
323
324
22
  case tok::annot_pragma_pack:
325
22
    ProhibitAttributes(Attrs);
326
22
    HandlePragmaPack();
327
22
    return StmtEmpty();
328
329
0
  case tok::annot_pragma_msstruct:
330
0
    ProhibitAttributes(Attrs);
331
0
    HandlePragmaMSStruct();
332
0
    return StmtEmpty();
333
334
1
  case tok::annot_pragma_align:
335
1
    ProhibitAttributes(Attrs);
336
1
    HandlePragmaAlign();
337
1
    return StmtEmpty();
338
339
9
  case tok::annot_pragma_weak:
340
9
    ProhibitAttributes(Attrs);
341
9
    HandlePragmaWeak();
342
9
    return StmtEmpty();
343
344
0
  case tok::annot_pragma_weakalias:
345
0
    ProhibitAttributes(Attrs);
346
0
    HandlePragmaWeakAlias();
347
0
    return StmtEmpty();
348
349
0
  case tok::annot_pragma_redefine_extname:
350
0
    ProhibitAttributes(Attrs);
351
0
    HandlePragmaRedefineExtname();
352
0
    return StmtEmpty();
353
354
3
  case tok::annot_pragma_fp_contract:
355
3
    ProhibitAttributes(Attrs);
356
3
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "fp_contract";
357
3
    ConsumeAnnotationToken();
358
3
    return StmtError();
359
360
3
  case tok::annot_pragma_fp:
361
3
    ProhibitAttributes(Attrs);
362
3
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "clang fp";
363
3
    ConsumeAnnotationToken();
364
3
    return StmtError();
365
366
3
  case tok::annot_pragma_fenv_access:
367
3
    ProhibitAttributes(Attrs);
368
3
    Diag(Tok, diag::err_pragma_stdc_fenv_access_scope);
369
3
    ConsumeAnnotationToken();
370
3
    return StmtEmpty();
371
372
1
  case tok::annot_pragma_fenv_round:
373
1
    ProhibitAttributes(Attrs);
374
1
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";
375
1
    ConsumeAnnotationToken();
376
1
    return StmtError();
377
378
0
  case tok::annot_pragma_float_control:
379
0
    ProhibitAttributes(Attrs);
380
0
    Diag(Tok, diag::err_pragma_file_or_compound_scope) << "float_control";
381
0
    ConsumeAnnotationToken();
382
0
    return StmtError();
383
384
7
  case tok::annot_pragma_opencl_extension:
385
7
    ProhibitAttributes(Attrs);
386
7
    HandlePragmaOpenCLExtension();
387
7
    return StmtEmpty();
388
389
57
  case tok::annot_pragma_captured:
390
57
    ProhibitAttributes(Attrs);
391
57
    return HandlePragmaCaptured();
392
393
224k
  case tok::annot_pragma_openmp:
394
224k
    ProhibitAttributes(Attrs);
395
224k
    return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
396
397
0
  case tok::annot_pragma_ms_pointers_to_members:
398
0
    ProhibitAttributes(Attrs);
399
0
    HandlePragmaMSPointersToMembers();
400
0
    return StmtEmpty();
401
402
0
  case tok::annot_pragma_ms_pragma:
403
0
    ProhibitAttributes(Attrs);
404
0
    HandlePragmaMSPragma();
405
0
    return StmtEmpty();
406
407
1
  case tok::annot_pragma_ms_vtordisp:
408
1
    ProhibitAttributes(Attrs);
409
1
    HandlePragmaMSVtorDisp();
410
1
    return StmtEmpty();
411
412
187
  case tok::annot_pragma_loop_hint:
413
187
    ProhibitAttributes(Attrs);
414
187
    return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs);
415
416
2
  case tok::annot_pragma_dump:
417
2
    HandlePragmaDump();
418
2
    return StmtEmpty();
419
420
7
  case tok::annot_pragma_attribute:
421
7
    HandlePragmaAttribute();
422
7
    return StmtEmpty();
423
2.87M
  }
424
425
  // If we reached this code, the statement must end in a semicolon.
426
2.87M
  if (!TryConsumeToken(tok::semi) && 
!Res.isInvalid()84
) {
427
    // If the result was valid, then we do want to diagnose this.  Use
428
    // ExpectAndConsume to emit the diagnostic, even though we know it won't
429
    // succeed.
430
6
    ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
431
    // Skip until we see a } or ;, but don't eat it.
432
6
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
433
6
  }
434
435
2.87M
  return Res;
436
2.87M
}
437
438
/// Parse an expression statement.
439
1.86M
StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
440
  // If a case keyword is missing, this is where it should be inserted.
441
1.86M
  Token OldToken = Tok;
442
443
1.86M
  ExprStatementTokLoc = Tok.getLocation();
444
445
  // expression[opt] ';'
446
1.86M
  ExprResult Expr(ParseExpression());
447
1.86M
  if (Expr.isInvalid()) {
448
    // If the expression is invalid, skip ahead to the next semicolon or '}'.
449
    // Not doing this opens us up to the possibility of infinite loops if
450
    // ParseExpression does not consume any tokens.
451
7.18k
    SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
452
7.18k
    if (Tok.is(tok::semi))
453
6.57k
      ConsumeToken();
454
7.18k
    return Actions.ActOnExprStmtError();
455
7.18k
  }
456
457
1.86M
  if (Tok.is(tok::colon) && 
getCurScope()->isSwitchScope()19
&&
458
18
      Actions.CheckCaseExpression(Expr.get())) {
459
    // If a constant expression is followed by a colon inside a switch block,
460
    // suggest a missing case keyword.
461
18
    Diag(OldToken, diag::err_expected_case_before_expression)
462
18
      << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
463
464
    // Recover parsing as a case statement.
465
18
    return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
466
18
  }
467
468
  // Otherwise, eat the semicolon.
469
1.86M
  ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
470
1.86M
  return handleExprStmt(Expr, StmtCtx);
471
1.86M
}
472
473
/// ParseSEHTryBlockCommon
474
///
475
/// seh-try-block:
476
///   '__try' compound-statement seh-handler
477
///
478
/// seh-handler:
479
///   seh-except-block
480
///   seh-finally-block
481
///
482
272
StmtResult Parser::ParseSEHTryBlock() {
483
272
  assert(Tok.is(tok::kw___try) && "Expected '__try'");
484
272
  SourceLocation TryLoc = ConsumeToken();
485
486
272
  if (Tok.isNot(tok::l_brace))
487
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
488
489
271
  StmtResult TryBlock(ParseCompoundStatement(
490
271
      /*isStmtExpr=*/false,
491
271
      Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
492
271
  if (TryBlock.isInvalid())
493
0
    return TryBlock;
494
495
271
  StmtResult Handler;
496
271
  if (Tok.is(tok::identifier) &&
497
127
      Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
498
127
    SourceLocation Loc = ConsumeToken();
499
127
    Handler = ParseSEHExceptBlock(Loc);
500
144
  } else if (Tok.is(tok::kw___finally)) {
501
141
    SourceLocation Loc = ConsumeToken();
502
141
    Handler = ParseSEHFinallyBlock(Loc);
503
3
  } else {
504
3
    return StmtError(Diag(Tok, diag::err_seh_expected_handler));
505
3
  }
506
507
268
  if(Handler.isInvalid())
508
10
    return Handler;
509
510
258
  return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
511
258
                                  TryLoc,
512
258
                                  TryBlock.get(),
513
258
                                  Handler.get());
514
258
}
515
516
/// ParseSEHExceptBlock - Handle __except
517
///
518
/// seh-except-block:
519
///   '__except' '(' seh-filter-expression ')' compound-statement
520
///
521
128
StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
522
128
  PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
523
128
    raii2(Ident___exception_code, false),
524
128
    raii3(Ident_GetExceptionCode, false);
525
526
128
  if (ExpectAndConsume(tok::l_paren))
527
0
    return StmtError();
528
529
128
  ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
530
128
                                   Scope::SEHExceptScope);
531
532
128
  if (getLangOpts().Borland) {
533
15
    Ident__exception_info->setIsPoisoned(false);
534
15
    Ident___exception_info->setIsPoisoned(false);
535
15
    Ident_GetExceptionInfo->setIsPoisoned(false);
536
15
  }
537
538
128
  ExprResult FilterExpr;
539
128
  {
540
128
    ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
541
128
                                          Scope::SEHFilterScope);
542
128
    FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
543
128
  }
544
545
128
  if (getLangOpts().Borland) {
546
15
    Ident__exception_info->setIsPoisoned(true);
547
15
    Ident___exception_info->setIsPoisoned(true);
548
15
    Ident_GetExceptionInfo->setIsPoisoned(true);
549
15
  }
550
551
128
  if(FilterExpr.isInvalid())
552
6
    return StmtError();
553
554
122
  if (ExpectAndConsume(tok::r_paren))
555
0
    return StmtError();
556
557
122
  if (Tok.isNot(tok::l_brace))
558
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
559
560
121
  StmtResult Block(ParseCompoundStatement());
561
562
121
  if(Block.isInvalid())
563
0
    return Block;
564
565
121
  return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
566
121
}
567
568
/// ParseSEHFinallyBlock - Handle __finally
569
///
570
/// seh-finally-block:
571
///   '__finally' compound-statement
572
///
573
143
StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
574
143
  PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
575
143
    raii2(Ident___abnormal_termination, false),
576
143
    raii3(Ident_AbnormalTermination, false);
577
578
143
  if (Tok.isNot(tok::l_brace))
579
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
580
581
142
  ParseScope FinallyScope(this, 0);
582
142
  Actions.ActOnStartSEHFinallyBlock();
583
584
142
  StmtResult Block(ParseCompoundStatement());
585
142
  if(Block.isInvalid()) {
586
0
    Actions.ActOnAbortSEHFinallyBlock();
587
0
    return Block;
588
0
  }
589
590
142
  return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
591
142
}
592
593
/// Handle __leave
594
///
595
/// seh-leave-statement:
596
///   '__leave' ';'
597
///
598
34
StmtResult Parser::ParseSEHLeaveStatement() {
599
34
  SourceLocation LeaveLoc = ConsumeToken();  // eat the '__leave'.
600
34
  return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
601
34
}
602
603
/// ParseLabeledStatement - We have an identifier and a ':' after it.
604
///
605
///       labeled-statement:
606
///         identifier ':' statement
607
/// [GNU]   identifier ':' attributes[opt] statement
608
///
609
StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs,
610
3.99k
                                         ParsedStmtContext StmtCtx) {
611
3.99k
  assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
612
3.99k
         "Not an identifier!");
613
614
  // The substatement is always a 'statement', not a 'declaration', but is
615
  // otherwise in the same context as the labeled-statement.
616
3.99k
  StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
617
618
3.99k
  Token IdentTok = Tok;  // Save the whole token.
619
3.99k
  ConsumeToken();  // eat the identifier.
620
621
3.99k
  assert(Tok.is(tok::colon) && "Not a label!");
622
623
  // identifier ':' statement
624
3.99k
  SourceLocation ColonLoc = ConsumeToken();
625
626
  // Read label attributes, if present.
627
3.99k
  StmtResult SubStmt;
628
3.99k
  if (Tok.is(tok::kw___attribute)) {
629
12
    ParsedAttributesWithRange TempAttrs(AttrFactory);
630
12
    ParseGNUAttributes(TempAttrs);
631
632
    // In C++, GNU attributes only apply to the label if they are followed by a
633
    // semicolon, to disambiguate label attributes from attributes on a labeled
634
    // declaration.
635
    //
636
    // This doesn't quite match what GCC does; if the attribute list is empty
637
    // and followed by a semicolon, GCC will reject (it appears to parse the
638
    // attributes as part of a statement in that case). That looks like a bug.
639
12
    if (!getLangOpts().CPlusPlus || 
Tok.is(tok::semi)9
)
640
6
      attrs.takeAllFrom(TempAttrs);
641
6
    else if (isDeclarationStatement()) {
642
5
      StmtVector Stmts;
643
      // FIXME: We should do this whether or not we have a declaration
644
      // statement, but that doesn't work correctly (because ProhibitAttributes
645
      // can't handle GNU attributes), so only call it in the one case where
646
      // GNU attributes are allowed.
647
5
      SubStmt = ParseStatementOrDeclarationAfterAttributes(Stmts, StmtCtx,
648
5
                                                           nullptr, TempAttrs);
649
5
      if (!TempAttrs.empty() && 
!SubStmt.isInvalid()0
)
650
0
        SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
651
0
                                                TempAttrs.Range);
652
1
    } else {
653
1
      Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
654
1
    }
655
12
  }
656
657
  // If we've not parsed a statement yet, parse one now.
658
3.99k
  if (!SubStmt.isInvalid() && !SubStmt.isUsable())
659
3.99k
    SubStmt = ParseStatement(nullptr, StmtCtx);
660
661
  // Broken substmt shouldn't prevent the label from being added to the AST.
662
3.99k
  if (SubStmt.isInvalid())
663
7
    SubStmt = Actions.ActOnNullStmt(ColonLoc);
664
665
3.99k
  LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
666
3.99k
                                              IdentTok.getLocation());
667
3.99k
  Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
668
3.99k
  attrs.clear();
669
670
3.99k
  return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
671
3.99k
                                SubStmt.get());
672
3.99k
}
673
674
/// ParseCaseStatement
675
///       labeled-statement:
676
///         'case' constant-expression ':' statement
677
/// [GNU]   'case' constant-expression '...' constant-expression ':' statement
678
///
679
StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
680
17.8k
                                      bool MissingCase, ExprResult Expr) {
681
17.8k
  assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
682
683
  // The substatement is always a 'statement', not a 'declaration', but is
684
  // otherwise in the same context as the labeled-statement.
685
17.8k
  StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
686
687
  // It is very very common for code to contain many case statements recursively
688
  // nested, as in (but usually without indentation):
689
  //  case 1:
690
  //    case 2:
691
  //      case 3:
692
  //         case 4:
693
  //           case 5: etc.
694
  //
695
  // Parsing this naively works, but is both inefficient and can cause us to run
696
  // out of stack space in our recursive descent parser.  As a special case,
697
  // flatten this recursion into an iterative loop.  This is complex and gross,
698
  // but all the grossness is constrained to ParseCaseStatement (and some
699
  // weirdness in the actions), so this is just local grossness :).
700
701
  // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
702
  // example above.
703
17.8k
  StmtResult TopLevelCase(true);
704
705
  // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
706
  // gets updated each time a new case is parsed, and whose body is unset so
707
  // far.  When parsing 'case 4', this is the 'case 3' node.
708
17.8k
  Stmt *DeepestParsedCaseStmt = nullptr;
709
710
  // While we have case statements, eat and stack them.
711
17.8k
  SourceLocation ColonLoc;
712
21.6k
  do {
713
18
    SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
714
21.6k
                                           ConsumeToken();  // eat the 'case'.
715
21.6k
    ColonLoc = SourceLocation();
716
717
21.6k
    if (Tok.is(tok::code_completion)) {
718
10
      Actions.CodeCompleteCase(getCurScope());
719
10
      cutOffParsing();
720
10
      return StmtError();
721
10
    }
722
723
    /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
724
    /// Disable this form of error recovery while we're parsing the case
725
    /// expression.
726
21.6k
    ColonProtectionRAIIObject ColonProtection(*this);
727
728
21.6k
    ExprResult LHS;
729
21.6k
    if (!MissingCase) {
730
21.6k
      LHS = ParseCaseExpression(CaseLoc);
731
21.6k
      if (LHS.isInvalid()) {
732
        // If constant-expression is parsed unsuccessfully, recover by skipping
733
        // current case statement (moving to the colon that ends it).
734
66
        if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
735
2
          return StmtError();
736
18
      }
737
18
    } else {
738
18
      LHS = Expr;
739
18
      MissingCase = false;
740
18
    }
741
742
    // GNU case range extension.
743
21.6k
    SourceLocation DotDotDotLoc;
744
21.6k
    ExprResult RHS;
745
21.6k
    if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
746
104
      Diag(DotDotDotLoc, diag::ext_gnu_case_range);
747
104
      RHS = ParseCaseExpression(CaseLoc);
748
104
      if (RHS.isInvalid()) {
749
2
        if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
750
0
          return StmtError();
751
21.6k
      }
752
104
    }
753
754
21.6k
    ColonProtection.restore();
755
756
21.6k
    if (TryConsumeToken(tok::colon, ColonLoc)) {
757
10
    } else if (TryConsumeToken(tok::semi, ColonLoc) ||
758
5
               TryConsumeToken(tok::coloncolon, ColonLoc)) {
759
      // Treat "case blah;" or "case blah::" as a typo for "case blah:".
760
5
      Diag(ColonLoc, diag::err_expected_after)
761
5
          << "'case'" << tok::colon
762
5
          << FixItHint::CreateReplacement(ColonLoc, ":");
763
5
    } else {
764
5
      SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
765
5
      Diag(ExpectedLoc, diag::err_expected_after)
766
5
          << "'case'" << tok::colon
767
5
          << FixItHint::CreateInsertion(ExpectedLoc, ":");
768
5
      ColonLoc = ExpectedLoc;
769
5
    }
770
771
21.6k
    StmtResult Case =
772
21.6k
        Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
773
774
    // If we had a sema error parsing this case, then just ignore it and
775
    // continue parsing the sub-stmt.
776
21.6k
    if (Case.isInvalid()) {
777
69
      if (TopLevelCase.isInvalid())  // No parsed case stmts.
778
58
        return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
779
      // Otherwise, just don't add it as a nested case.
780
21.5k
    } else {
781
      // If this is the first case statement we parsed, it becomes TopLevelCase.
782
      // Otherwise we link it into the current chain.
783
21.5k
      Stmt *NextDeepest = Case.get();
784
21.5k
      if (TopLevelCase.isInvalid())
785
17.7k
        TopLevelCase = Case;
786
3.79k
      else
787
3.79k
        Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
788
21.5k
      DeepestParsedCaseStmt = NextDeepest;
789
21.5k
    }
790
791
    // Handle all case statements.
792
21.5k
  } while (Tok.is(tok::kw_case));
793
794
  // If we found a non-case statement, start by parsing it.
795
17.7k
  StmtResult SubStmt;
796
797
17.7k
  if (Tok.isNot(tok::r_brace)) {
798
17.7k
    SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
799
9
  } else {
800
    // Nicely diagnose the common error "switch (X) { case 4: }", which is
801
    // not valid.  If ColonLoc doesn't point to a valid text location, there was
802
    // another parsing error, so avoid producing extra diagnostics.
803
9
    if (ColonLoc.isValid()) {
804
9
      SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
805
9
      Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
806
9
        << FixItHint::CreateInsertion(AfterColonLoc, " ;");
807
9
    }
808
9
    SubStmt = StmtError();
809
9
  }
810
811
  // Install the body into the most deeply-nested case.
812
17.7k
  if (DeepestParsedCaseStmt) {
813
    // Broken sub-stmt shouldn't prevent forming the case statement properly.
814
17.7k
    if (SubStmt.isInvalid())
815
28
      SubStmt = Actions.ActOnNullStmt(SourceLocation());
816
17.7k
    Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
817
17.7k
  }
818
819
  // Return the top level parsed statement tree.
820
17.7k
  return TopLevelCase;
821
17.8k
}
822
823
/// ParseDefaultStatement
824
///       labeled-statement:
825
///         'default' ':' statement
826
/// Note that this does not parse the 'statement' at the end.
827
///
828
2.12k
StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
829
2.12k
  assert(Tok.is(tok::kw_default) && "Not a default stmt!");
830
831
  // The substatement is always a 'statement', not a 'declaration', but is
832
  // otherwise in the same context as the labeled-statement.
833
2.12k
  StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
834
835
2.12k
  SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
836
837
2.12k
  SourceLocation ColonLoc;
838
2.12k
  if (TryConsumeToken(tok::colon, ColonLoc)) {
839
2
  } else if (TryConsumeToken(tok::semi, ColonLoc)) {
840
    // Treat "default;" as a typo for "default:".
841
1
    Diag(ColonLoc, diag::err_expected_after)
842
1
        << "'default'" << tok::colon
843
1
        << FixItHint::CreateReplacement(ColonLoc, ":");
844
1
  } else {
845
1
    SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
846
1
    Diag(ExpectedLoc, diag::err_expected_after)
847
1
        << "'default'" << tok::colon
848
1
        << FixItHint::CreateInsertion(ExpectedLoc, ":");
849
1
    ColonLoc = ExpectedLoc;
850
1
  }
851
852
2.12k
  StmtResult SubStmt;
853
854
2.12k
  if (Tok.isNot(tok::r_brace)) {
855
2.12k
    SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
856
3
  } else {
857
    // Diagnose the common error "switch (X) {... default: }", which is
858
    // not valid.
859
3
    SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
860
3
    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
861
3
      << FixItHint::CreateInsertion(AfterColonLoc, " ;");
862
3
    SubStmt = true;
863
3
  }
864
865
  // Broken sub-stmt shouldn't prevent forming the case statement properly.
866
2.12k
  if (SubStmt.isInvalid())
867
6
    SubStmt = Actions.ActOnNullStmt(ColonLoc);
868
869
2.12k
  return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
870
2.12k
                                  SubStmt.get(), getCurScope());
871
2.12k
}
872
873
384k
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
874
384k
  return ParseCompoundStatement(isStmtExpr,
875
384k
                                Scope::DeclScope | Scope::CompoundStmtScope);
876
384k
}
877
878
/// ParseCompoundStatement - Parse a "{}" block.
879
///
880
///       compound-statement: [C99 6.8.2]
881
///         { block-item-list[opt] }
882
/// [GNU]   { label-declarations block-item-list } [TODO]
883
///
884
///       block-item-list:
885
///         block-item
886
///         block-item-list block-item
887
///
888
///       block-item:
889
///         declaration
890
/// [GNU]   '__extension__' declaration
891
///         statement
892
///
893
/// [GNU] label-declarations:
894
/// [GNU]   label-declaration
895
/// [GNU]   label-declarations label-declaration
896
///
897
/// [GNU] label-declaration:
898
/// [GNU]   '__label__' identifier-list ';'
899
///
900
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
901
395k
                                          unsigned ScopeFlags) {
902
395k
  assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
903
904
  // Enter a scope to hold everything within the compound stmt.  Compound
905
  // statements can always hold declarations.
906
395k
  ParseScope CompoundScope(this, ScopeFlags);
907
908
  // Parse the statements in the body.
909
395k
  return ParseCompoundStatementBody(isStmtExpr);
910
395k
}
911
912
/// Parse any pragmas at the start of the compound expression. We handle these
913
/// separately since some pragmas (FP_CONTRACT) must appear before any C
914
/// statement in the compound, but may be intermingled with other pragmas.
915
3.63M
void Parser::ParseCompoundStatementLeadingPragmas() {
916
3.63M
  bool checkForPragmas = true;
917
7.26M
  while (checkForPragmas) {
918
3.63M
    switch (Tok.getKind()) {
919
2
    case tok::annot_pragma_vis:
920
2
      HandlePragmaVisibility();
921
2
      break;
922
5
    case tok::annot_pragma_pack:
923
5
      HandlePragmaPack();
924
5
      break;
925
0
    case tok::annot_pragma_msstruct:
926
0
      HandlePragmaMSStruct();
927
0
      break;
928
1
    case tok::annot_pragma_align:
929
1
      HandlePragmaAlign();
930
1
      break;
931
1
    case tok::annot_pragma_weak:
932
1
      HandlePragmaWeak();
933
1
      break;
934
0
    case tok::annot_pragma_weakalias:
935
0
      HandlePragmaWeakAlias();
936
0
      break;
937
0
    case tok::annot_pragma_redefine_extname:
938
0
      HandlePragmaRedefineExtname();
939
0
      break;
940
0
    case tok::annot_pragma_opencl_extension:
941
0
      HandlePragmaOpenCLExtension();
942
0
      break;
943
24
    case tok::annot_pragma_fp_contract:
944
24
      HandlePragmaFPContract();
945
24
      break;
946
44
    case tok::annot_pragma_fp:
947
44
      HandlePragmaFP();
948
44
      break;
949
3
    case tok::annot_pragma_fenv_access:
950
3
      HandlePragmaFEnvAccess();
951
3
      break;
952
16
    case tok::annot_pragma_fenv_round:
953
16
      HandlePragmaFEnvRound();
954
16
      break;
955
70
    case tok::annot_pragma_float_control:
956
70
      HandlePragmaFloatControl();
957
70
      break;
958
0
    case tok::annot_pragma_ms_pointers_to_members:
959
0
      HandlePragmaMSPointersToMembers();
960
0
      break;
961
8
    case tok::annot_pragma_ms_pragma:
962
8
      HandlePragmaMSPragma();
963
8
      break;
964
4
    case tok::annot_pragma_ms_vtordisp:
965
4
      HandlePragmaMSVtorDisp();
966
4
      break;
967
0
    case tok::annot_pragma_dump:
968
0
      HandlePragmaDump();
969
0
      break;
970
3.63M
    default:
971
3.63M
      checkForPragmas = false;
972
3.63M
      break;
973
3.63M
    }
974
3.63M
  }
975
976
3.63M
}
977
978
/// Consume any extra semi-colons resulting in null statements,
979
/// returning true if any tok::semi were consumed.
980
6.26M
bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
981
6.26M
  if (!Tok.is(tok::semi))
982
6.25M
    return false;
983
984
10.6k
  SourceLocation StartLoc = Tok.getLocation();
985
10.6k
  SourceLocation EndLoc;
986
987
21.0k
  while (Tok.is(tok::semi) && 
!Tok.hasLeadingEmptyMacro()10.7k
&&
988
10.4k
         Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
989
10.4k
    EndLoc = Tok.getLocation();
990
991
    // Don't just ConsumeToken() this tok::semi, do store it in AST.
992
10.4k
    StmtResult R =
993
10.4k
        ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
994
10.4k
    if (R.isUsable())
995
10.4k
      Stmts.push_back(R.get());
996
10.4k
  }
997
998
  // Did not consume any extra semi.
999
10.6k
  if (EndLoc.isInvalid())
1000
321
    return false;
1001
1002
10.3k
  Diag(StartLoc, diag::warn_null_statement)
1003
10.3k
      << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
1004
10.3k
  return true;
1005
10.3k
}
1006
1007
1.86M
StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
1008
1.86M
  bool IsStmtExprResult = false;
1009
1.86M
  if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
1010
    // For GCC compatibility we skip past NullStmts.
1011
13.0k
    unsigned LookAhead = 0;
1012
13.0k
    while (GetLookAheadToken(LookAhead).is(tok::semi)) {
1013
10
      ++LookAhead;
1014
10
    }
1015
    // Then look to see if the next two tokens close the statement expression;
1016
    // if so, this expression statement is the last statement in a statment
1017
    // expression.
1018
13.0k
    IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&
1019
7.68k
                       GetLookAheadToken(LookAhead + 1).is(tok::r_paren);
1020
13.0k
  }
1021
1022
1.86M
  if (IsStmtExprResult)
1023
7.68k
    E = Actions.ActOnStmtExprResult(E);
1024
1.86M
  return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
1025
1.86M
}
1026
1027
/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
1028
/// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
1029
/// consume the '}' at the end of the block.  It does not manipulate the scope
1030
/// stack.
1031
3.63M
StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
1032
3.63M
  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
1033
3.63M
                                Tok.getLocation(),
1034
3.63M
                                "in compound statement ('{}')");
1035
1036
  // Record the current FPFeatures, restore on leaving the
1037
  // compound statement.
1038
3.63M
  Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
1039
1040
3.63M
  InMessageExpressionRAIIObject InMessage(*this, false);
1041
3.63M
  BalancedDelimiterTracker T(*this, tok::l_brace);
1042
3.63M
  if (T.consumeOpen())
1043
4
    return StmtError();
1044
1045
3.63M
  Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
1046
1047
  // Parse any pragmas at the beginning of the compound statement.
1048
3.63M
  ParseCompoundStatementLeadingPragmas();
1049
3.63M
  Actions.ActOnAfterCompoundStatementLeadingPragmas();
1050
1051
3.63M
  StmtVector Stmts;
1052
1053
  // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
1054
  // only allowed at the start of a compound stmt regardless of the language.
1055
3.63M
  while (Tok.is(tok::kw___label__)) {
1056
11
    SourceLocation LabelLoc = ConsumeToken();
1057
1058
11
    SmallVector<Decl *, 8> DeclsInGroup;
1059
11
    while (1) {
1060
11
      if (Tok.isNot(tok::identifier)) {
1061
0
        Diag(Tok, diag::err_expected) << tok::identifier;
1062
0
        break;
1063
0
      }
1064
1065
11
      IdentifierInfo *II = Tok.getIdentifierInfo();
1066
11
      SourceLocation IdLoc = ConsumeToken();
1067
11
      DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
1068
1069
11
      if (!TryConsumeToken(tok::comma))
1070
11
        break;
1071
11
    }
1072
1073
11
    DeclSpec DS(AttrFactory);
1074
11
    DeclGroupPtrTy Res =
1075
11
        Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
1076
11
    StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
1077
1078
11
    ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
1079
11
    if (R.isUsable())
1080
11
      Stmts.push_back(R.get());
1081
11
  }
1082
1083
3.63M
  ParsedStmtContext SubStmtCtx =
1084
3.63M
      ParsedStmtContext::Compound |
1085
3.62M
      (isStmtExpr ? 
ParsedStmtContext::InStmtExpr8.86k
: ParsedStmtContext());
1086
1087
9.89M
  while (!tryParseMisplacedModuleImport() && 
Tok.isNot(tok::r_brace)9.89M
&&
1088
6.26M
         Tok.isNot(tok::eof)) {
1089
6.26M
    if (Tok.is(tok::annot_pragma_unused)) {
1090
24
      HandlePragmaUnused();
1091
24
      continue;
1092
24
    }
1093
1094
6.26M
    if (ConsumeNullStmt(Stmts))
1095
10.3k
      continue;
1096
1097
6.25M
    StmtResult R;
1098
6.25M
    if (Tok.isNot(tok::kw___extension__)) {
1099
6.25M
      R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
1100
3.60k
    } else {
1101
      // __extension__ can start declarations and it can also be a unary
1102
      // operator for expressions.  Consume multiple __extension__ markers here
1103
      // until we can determine which is which.
1104
      // FIXME: This loses extension expressions in the AST!
1105
3.60k
      SourceLocation ExtLoc = ConsumeToken();
1106
3.60k
      while (Tok.is(tok::kw___extension__))
1107
0
        ConsumeToken();
1108
1109
3.60k
      ParsedAttributesWithRange attrs(AttrFactory);
1110
3.60k
      MaybeParseCXX11Attributes(attrs, nullptr,
1111
3.60k
                                /*MightBeObjCMessageSend*/ true);
1112
1113
      // If this is the start of a declaration, parse it as such.
1114
3.60k
      if (isDeclarationStatement()) {
1115
        // __extension__ silences extension warnings in the subdeclaration.
1116
        // FIXME: Save the __extension__ on the decl as a node somehow?
1117
15
        ExtensionRAIIObject O(Diags);
1118
1119
15
        SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1120
15
        DeclGroupPtrTy Res =
1121
15
            ParseDeclaration(DeclaratorContext::Block, DeclEnd, attrs);
1122
15
        R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1123
3.58k
      } else {
1124
        // Otherwise this was a unary __extension__ marker.
1125
3.58k
        ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1126
1127
3.58k
        if (Res.isInvalid()) {
1128
1
          SkipUntil(tok::semi);
1129
1
          continue;
1130
1
        }
1131
1132
        // Eat the semicolon at the end of stmt and convert the expr into a
1133
        // statement.
1134
3.58k
        ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1135
3.58k
        R = handleExprStmt(Res, SubStmtCtx);
1136
3.58k
        if (R.isUsable())
1137
3.58k
          R = Actions.ProcessStmtAttributes(R.get(), attrs, attrs.Range);
1138
3.58k
      }
1139
3.60k
    }
1140
1141
6.25M
    if (R.isUsable())
1142
6.21M
      Stmts.push_back(R.get());
1143
6.25M
  }
1144
1145
3.63M
  SourceLocation CloseLoc = Tok.getLocation();
1146
1147
  // We broke out of the while loop because we found a '}' or EOF.
1148
3.63M
  if (!T.consumeClose()) {
1149
    // If this is the '})' of a statement expression, check that it's written
1150
    // in a sensible way.
1151
3.63M
    if (isStmtExpr && 
Tok.is(tok::r_paren)8.86k
)
1152
8.86k
      checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd);
1153
2.06k
  } else {
1154
    // Recover by creating a compound statement with what we parsed so far,
1155
    // instead of dropping everything and returning StmtError().
1156
2.06k
  }
1157
1158
3.63M
  if (T.getCloseLocation().isValid())
1159
3.63M
    CloseLoc = T.getCloseLocation();
1160
1161
3.63M
  return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1162
3.63M
                                   Stmts, isStmtExpr);
1163
3.63M
}
1164
1165
/// ParseParenExprOrCondition:
1166
/// [C  ]     '(' expression ')'
1167
/// [C++]     '(' condition ')'
1168
/// [C++1z]   '(' init-statement[opt] condition ')'
1169
///
1170
/// This function parses and performs error recovery on the specified condition
1171
/// or expression (depending on whether we're in C++ or C mode).  This function
1172
/// goes out of its way to recover well.  It returns true if there was a parser
1173
/// error (the right paren couldn't be found), which indicates that the caller
1174
/// should try to recover harder.  It returns false if the condition is
1175
/// successfully parsed.  Note that a successful parse can still have semantic
1176
/// errors in the condition.
1177
/// Additionally, if LParenLoc and RParenLoc are non-null, it will assign
1178
/// the location of the outer-most '(' and ')', respectively, to them.
1179
bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1180
                                       Sema::ConditionResult &Cond,
1181
                                       SourceLocation Loc,
1182
                                       Sema::ConditionKind CK,
1183
                                       SourceLocation *LParenLoc,
1184
475k
                                       SourceLocation *RParenLoc) {
1185
475k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1186
475k
  T.consumeOpen();
1187
1188
475k
  if (getLangOpts().CPlusPlus)
1189
456k
    Cond = ParseCXXCondition(InitStmt, Loc, CK);
1190
19.5k
  else {
1191
19.5k
    ExprResult CondExpr = ParseExpression();
1192
1193
    // If required, convert to a boolean value.
1194
19.5k
    if (CondExpr.isInvalid())
1195
7
      Cond = Sema::ConditionError();
1196
19.5k
    else
1197
19.5k
      Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1198
19.5k
  }
1199
1200
  // If the parser was confused by the condition and we don't have a ')', try to
1201
  // recover by skipping ahead to a semi and bailing out.  If condexp is
1202
  // semantically invalid but we have well formed code, keep going.
1203
475k
  if (Cond.isInvalid() && 
Tok.isNot(tok::r_paren)105
) {
1204
22
    SkipUntil(tok::semi);
1205
    // Skipping may have stopped if it found the containing ')'.  If so, we can
1206
    // continue parsing the if statement.
1207
22
    if (Tok.isNot(tok::r_paren))
1208
15
      return true;
1209
475k
  }
1210
1211
  // Otherwise the condition is valid or the rparen is present.
1212
475k
  T.consumeClose();
1213
1214
475k
  if (LParenLoc != nullptr) {
1215
475k
    *LParenLoc = T.getOpenLocation();
1216
475k
  }
1217
475k
  if (RParenLoc != nullptr) {
1218
475k
    *RParenLoc = T.getCloseLocation();
1219
475k
  }
1220
1221
  // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
1222
  // that all callers are looking for a statement after the condition, so ")"
1223
  // isn't valid.
1224
475k
  while (Tok.is(tok::r_paren)) {
1225
1
    Diag(Tok, diag::err_extraneous_rparen_in_condition)
1226
1
      << FixItHint::CreateRemoval(Tok.getLocation());
1227
1
    ConsumeParen();
1228
1
  }
1229
1230
475k
  return false;
1231
475k
}
1232
1233
namespace {
1234
1235
enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
1236
1237
struct MisleadingIndentationChecker {
1238
  Parser &P;
1239
  SourceLocation StmtLoc;
1240
  SourceLocation PrevLoc;
1241
  unsigned NumDirectives;
1242
  MisleadingStatementKind Kind;
1243
  bool ShouldSkip;
1244
  MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
1245
                               SourceLocation SL)
1246
      : P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
1247
        NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
1248
741k
        ShouldSkip(P.getCurToken().is(tok::l_brace)) {
1249
741k
    if (!P.MisleadingIndentationElseLoc.isInvalid()) {
1250
18.8k
      StmtLoc = P.MisleadingIndentationElseLoc;
1251
18.8k
      P.MisleadingIndentationElseLoc = SourceLocation();
1252
18.8k
    }
1253
741k
    if (Kind == MSK_else && 
!ShouldSkip87.0k
)
1254
43.3k
      P.MisleadingIndentationElseLoc = SL;
1255
741k
  }
1256
1257
  /// Compute the column number will aligning tabs on TabStop (-ftabstop), this
1258
  /// gives the visual indentation of the SourceLocation.
1259
1.15k
  static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
1260
1.15k
    unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
1261
1262
1.15k
    unsigned ColNo = SM.getSpellingColumnNumber(Loc);
1263
1.15k
    if (ColNo == 0 || TabStop == 1)
1264
66
      return ColNo;
1265
1266
1.08k
    std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc);
1267
1268
1.08k
    bool Invalid;
1269
1.08k
    StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);
1270
1.08k
    if (Invalid)
1271
0
      return 0;
1272
1273
1.08k
    const char *EndPos = BufData.data() + FIDAndOffset.second;
1274
    // FileOffset are 0-based and Column numbers are 1-based
1275
1.08k
    assert(FIDAndOffset.second + 1 >= ColNo &&
1276
1.08k
           "Column number smaller than file offset?");
1277
1278
1.08k
    unsigned VisualColumn = 0; // Stored as 0-based column, here.
1279
    // Loop from beginning of line up to Loc's file position, counting columns,
1280
    // expanding tabs.
1281
5.02k
    for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
1282
3.93k
         ++CurPos) {
1283
3.93k
      if (*CurPos == '\t')
1284
        // Advance visual column to next tabstop.
1285
42
        VisualColumn += (TabStop - VisualColumn % TabStop);
1286
3.89k
      else
1287
3.89k
        VisualColumn++;
1288
3.93k
    }
1289
1.08k
    return VisualColumn + 1;
1290
1.08k
  }
1291
1292
654k
  void Check() {
1293
654k
    Token Tok = P.getCurToken();
1294
654k
    if (P.getActions().getDiagnostics().isIgnored(
1295
654k
            diag::warn_misleading_indentation, Tok.getLocation()) ||
1296
918
        ShouldSkip || 
NumDirectives != P.getPreprocessor().getNumDirectives()472
||
1297
447
        Tok.isOneOf(tok::semi, tok::r_brace) || 
Tok.isAnnotation()404
||
1298
404
        Tok.getLocation().isMacroID() || 
PrevLoc.isMacroID()400
||
1299
396
        StmtLoc.isMacroID() ||
1300
653k
        
(396
Kind == MSK_else396
&&
P.MisleadingIndentationElseLoc.isInvalid()24
)) {
1301
653k
      P.MisleadingIndentationElseLoc = SourceLocation();
1302
653k
      return;
1303
653k
    }
1304
384
    if (Kind == MSK_else)
1305
12
      P.MisleadingIndentationElseLoc = SourceLocation();
1306
1307
384
    SourceManager &SM = P.getPreprocessor().getSourceManager();
1308
384
    unsigned PrevColNum = getVisualIndentation(SM, PrevLoc);
1309
384
    unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation());
1310
384
    unsigned StmtColNum = getVisualIndentation(SM, StmtLoc);
1311
1312
384
    if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
1313
384
        ((PrevColNum > StmtColNum && 
PrevColNum == CurColNum376
) ||
1314
338
         !Tok.isAtStartOfLine()) &&
1315
59
        SM.getPresumedLineNumber(StmtLoc) !=
1316
59
            SM.getPresumedLineNumber(Tok.getLocation()) &&
1317
50
        (Tok.isNot(tok::identifier) ||
1318
46
         
P.getPreprocessor().LookAhead(0).isNot(tok::colon)26
)) {
1319
46
      P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind;
1320
46
      P.Diag(StmtLoc, diag::note_previous_statement);
1321
46
    }
1322
384
  }
1323
};
1324
1325
}
1326
1327
/// ParseIfStatement
1328
///       if-statement: [C99 6.8.4.1]
1329
///         'if' '(' expression ')' statement
1330
///         'if' '(' expression ')' statement 'else' statement
1331
/// [C++]   'if' '(' condition ')' statement
1332
/// [C++]   'if' '(' condition ')' statement 'else' statement
1333
///
1334
427k
StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1335
427k
  assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1336
427k
  SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
1337
1338
427k
  bool IsConstexpr = false;
1339
427k
  if (Tok.is(tok::kw_constexpr)) {
1340
106
    Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1341
1
                                        : diag::ext_constexpr_if);
1342
107
    IsConstexpr = true;
1343
107
    ConsumeToken();
1344
107
  }
1345
1346
427k
  if (Tok.isNot(tok::l_paren)) {
1347
0
    Diag(Tok, diag::err_expected_lparen_after) << "if";
1348
0
    SkipUntil(tok::semi);
1349
0
    return StmtError();
1350
0
  }
1351
1352
427k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus408k
;
1353
1354
  // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
1355
  // the case for C90.
1356
  //
1357
  // C++ 6.4p3:
1358
  // A name introduced by a declaration in a condition is in scope from its
1359
  // point of declaration until the end of the substatements controlled by the
1360
  // condition.
1361
  // C++ 3.3.2p4:
1362
  // Names declared in the for-init-statement, and in the condition of if,
1363
  // while, for, and switch statements are local to the if, while, for, or
1364
  // switch statement (including the controlled statement).
1365
  //
1366
427k
  ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1367
1368
  // Parse the condition.
1369
427k
  StmtResult InitStmt;
1370
427k
  Sema::ConditionResult Cond;
1371
427k
  SourceLocation LParen;
1372
427k
  SourceLocation RParen;
1373
427k
  if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1374
107
                                IsConstexpr ? Sema::ConditionKind::ConstexprIf
1375
427k
                                            : Sema::ConditionKind::Boolean,
1376
427k
                                &LParen, &RParen))
1377
8
    return StmtError();
1378
1379
427k
  llvm::Optional<bool> ConstexprCondition;
1380
427k
  if (IsConstexpr)
1381
107
    ConstexprCondition = Cond.getKnownValue();
1382
1383
427k
  bool IsBracedThen = Tok.is(tok::l_brace);
1384
1385
  // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1386
  // there is no compound stmt.  C90 does not have this clause.  We only do this
1387
  // if the body isn't a compound statement to avoid push/pop in common cases.
1388
  //
1389
  // C++ 6.4p1:
1390
  // The substatement in a selection-statement (each substatement, in the else
1391
  // form of the if statement) implicitly defines a local scope.
1392
  //
1393
  // For C++ we create a scope for the condition and a new scope for
1394
  // substatements because:
1395
  // -When the 'then' scope exits, we want the condition declaration to still be
1396
  //    active for the 'else' scope too.
1397
  // -Sema will detect name clashes by considering declarations of a
1398
  //    'ControlScope' as part of its direct subscope.
1399
  // -If we wanted the condition and substatement to be in the same scope, we
1400
  //    would have to notify ParseStatement not to create a new scope. It's
1401
  //    simpler to let it create a new scope.
1402
  //
1403
427k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
1404
1405
427k
  MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
1406
1407
  // Read the 'then' stmt.
1408
427k
  SourceLocation ThenStmtLoc = Tok.getLocation();
1409
1410
427k
  SourceLocation InnerStatementTrailingElseLoc;
1411
427k
  StmtResult ThenStmt;
1412
427k
  {
1413
427k
    EnterExpressionEvaluationContext PotentiallyDiscarded(
1414
427k
        Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1415
427k
        Sema::ExpressionEvaluationContextRecord::EK_Other,
1416
427k
        /*ShouldEnter=*/ConstexprCondition && 
!*ConstexprCondition77
);
1417
427k
    ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1418
427k
  }
1419
1420
427k
  if (Tok.isNot(tok::kw_else))
1421
340k
    MIChecker.Check();
1422
1423
  // Pop the 'if' scope if needed.
1424
427k
  InnerScope.Exit();
1425
1426
  // If it has an else, parse it.
1427
427k
  SourceLocation ElseLoc;
1428
427k
  SourceLocation ElseStmtLoc;
1429
427k
  StmtResult ElseStmt;
1430
1431
427k
  if (Tok.is(tok::kw_else)) {
1432
87.0k
    if (TrailingElseLoc)
1433
14
      *TrailingElseLoc = Tok.getLocation();
1434
1435
87.0k
    ElseLoc = ConsumeToken();
1436
87.0k
    ElseStmtLoc = Tok.getLocation();
1437
1438
    // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1439
    // there is no compound stmt.  C90 does not have this clause.  We only do
1440
    // this if the body isn't a compound statement to avoid push/pop in common
1441
    // cases.
1442
    //
1443
    // C++ 6.4p1:
1444
    // The substatement in a selection-statement (each substatement, in the else
1445
    // form of the if statement) implicitly defines a local scope.
1446
    //
1447
87.0k
    ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1448
87.0k
                          Tok.is(tok::l_brace));
1449
1450
87.0k
    MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
1451
1452
87.0k
    EnterExpressionEvaluationContext PotentiallyDiscarded(
1453
87.0k
        Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1454
87.0k
        Sema::ExpressionEvaluationContextRecord::EK_Other,
1455
87.0k
        /*ShouldEnter=*/ConstexprCondition && 
*ConstexprCondition43
);
1456
87.0k
    ElseStmt = ParseStatement();
1457
1458
87.0k
    if (ElseStmt.isUsable())
1459
87.0k
      MIChecker.Check();
1460
1461
    // Pop the 'else' scope if needed.
1462
87.0k
    InnerScope.Exit();
1463
340k
  } else if (Tok.is(tok::code_completion)) {
1464
4
    Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen);
1465
4
    cutOffParsing();
1466
4
    return StmtError();
1467
340k
  } else if (InnerStatementTrailingElseLoc.isValid()) {
1468
6
    Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1469
6
  }
1470
1471
427k
  IfScope.Exit();
1472
1473
  // If the then or else stmt is invalid and the other is valid (and present),
1474
  // make turn the invalid one into a null stmt to avoid dropping the other
1475
  // part.  If both are invalid, return error.
1476
427k
  if ((ThenStmt.isInvalid() && 
ElseStmt.isInvalid()310
) ||
1477
427k
      (ThenStmt.isInvalid() && 
ElseStmt.get() == nullptr293
) ||
1478
426k
      (ThenStmt.get() == nullptr && 
ElseStmt.isInvalid()75
)) {
1479
    // Both invalid, or one is invalid and other is non-present: return error.
1480
235
    return StmtError();
1481
235
  }
1482
1483
  // Now if either are invalid, replace with a ';'.
1484
426k
  if (ThenStmt.isInvalid())
1485
75
    ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1486
426k
  if (ElseStmt.isInvalid())
1487
3
    ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1488
1489
426k
  return Actions.ActOnIfStmt(IfLoc, IsConstexpr, LParen, InitStmt.get(), Cond,
1490
426k
                             RParen, ThenStmt.get(), ElseLoc, ElseStmt.get());
1491
426k
}
1492
1493
/// ParseSwitchStatement
1494
///       switch-statement:
1495
///         'switch' '(' expression ')' statement
1496
/// [C++]   'switch' '(' condition ')' statement
1497
6.08k
StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1498
6.08k
  assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1499
6.08k
  SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
1500
1501
6.08k
  if (Tok.isNot(tok::l_paren)) {
1502
0
    Diag(Tok, diag::err_expected_lparen_after) << "switch";
1503
0
    SkipUntil(tok::semi);
1504
0
    return StmtError();
1505
0
  }
1506
1507
6.08k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus5.32k
;
1508
1509
  // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1510
  // not the case for C90.  Start the switch scope.
1511
  //
1512
  // C++ 6.4p3:
1513
  // A name introduced by a declaration in a condition is in scope from its
1514
  // point of declaration until the end of the substatements controlled by the
1515
  // condition.
1516
  // C++ 3.3.2p4:
1517
  // Names declared in the for-init-statement, and in the condition of if,
1518
  // while, for, and switch statements are local to the if, while, for, or
1519
  // switch statement (including the controlled statement).
1520
  //
1521
6.08k
  unsigned ScopeFlags = Scope::SwitchScope;
1522
6.08k
  if (C99orCXX)
1523
6.06k
    ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1524
6.08k
  ParseScope SwitchScope(this, ScopeFlags);
1525
1526
  // Parse the condition.
1527
6.08k
  StmtResult InitStmt;
1528
6.08k
  Sema::ConditionResult Cond;
1529
6.08k
  SourceLocation LParen;
1530
6.08k
  SourceLocation RParen;
1531
6.08k
  if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1532
6.08k
                                Sema::ConditionKind::Switch, &LParen, &RParen))
1533
2
    return StmtError();
1534
1535
6.08k
  StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
1536
6.08k
      SwitchLoc, LParen, InitStmt.get(), Cond, RParen);
1537
1538
6.08k
  if (Switch.isInvalid()) {
1539
    // Skip the switch body.
1540
    // FIXME: This is not optimal recovery, but parsing the body is more
1541
    // dangerous due to the presence of case and default statements, which
1542
    // will have no place to connect back with the switch.
1543
1
    if (Tok.is(tok::l_brace)) {
1544
1
      ConsumeBrace();
1545
1
      SkipUntil(tok::r_brace);
1546
1
    } else
1547
0
      SkipUntil(tok::semi);
1548
1
    return Switch;
1549
1
  }
1550
1551
  // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1552
  // there is no compound stmt.  C90 does not have this clause.  We only do this
1553
  // if the body isn't a compound statement to avoid push/pop in common cases.
1554
  //
1555
  // C++ 6.4p1:
1556
  // The substatement in a selection-statement (each substatement, in the else
1557
  // form of the if statement) implicitly defines a local scope.
1558
  //
1559
  // See comments in ParseIfStatement for why we create a scope for the
1560
  // condition and a new scope for substatement in C++.
1561
  //
1562
6.08k
  getCurScope()->AddFlags(Scope::BreakScope);
1563
6.08k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1564
1565
  // We have incremented the mangling number for the SwitchScope and the
1566
  // InnerScope, which is one too many.
1567
6.08k
  if (C99orCXX)
1568
6.06k
    getCurScope()->decrementMSManglingNumber();
1569
1570
  // Read the body statement.
1571
6.08k
  StmtResult Body(ParseStatement(TrailingElseLoc));
1572
1573
  // Pop the scopes.
1574
6.08k
  InnerScope.Exit();
1575
6.08k
  SwitchScope.Exit();
1576
1577
6.08k
  return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1578
6.08k
}
1579
1580
/// ParseWhileStatement
1581
///       while-statement: [C99 6.8.5.1]
1582
///         'while' '(' expression ')' statement
1583
/// [C++]   'while' '(' condition ')' statement
1584
42.4k
StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1585
42.4k
  assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1586
42.4k
  SourceLocation WhileLoc = Tok.getLocation();
1587
42.4k
  ConsumeToken();  // eat the 'while'.
1588
1589
42.4k
  if (Tok.isNot(tok::l_paren)) {
1590
0
    Diag(Tok, diag::err_expected_lparen_after) << "while";
1591
0
    SkipUntil(tok::semi);
1592
0
    return StmtError();
1593
0
  }
1594
1595
42.4k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus41.8k
;
1596
1597
  // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1598
  // the case for C90.  Start the loop scope.
1599
  //
1600
  // C++ 6.4p3:
1601
  // A name introduced by a declaration in a condition is in scope from its
1602
  // point of declaration until the end of the substatements controlled by the
1603
  // condition.
1604
  // C++ 3.3.2p4:
1605
  // Names declared in the for-init-statement, and in the condition of if,
1606
  // while, for, and switch statements are local to the if, while, for, or
1607
  // switch statement (including the controlled statement).
1608
  //
1609
42.4k
  unsigned ScopeFlags;
1610
42.4k
  if (C99orCXX)
1611
42.4k
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1612
42.4k
                 Scope::DeclScope  | Scope::ControlScope;
1613
17
  else
1614
17
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1615
42.4k
  ParseScope WhileScope(this, ScopeFlags);
1616
1617
  // Parse the condition.
1618
42.4k
  Sema::ConditionResult Cond;
1619
42.4k
  SourceLocation LParen;
1620
42.4k
  SourceLocation RParen;
1621
42.4k
  if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1622
42.4k
                                Sema::ConditionKind::Boolean, &LParen, &RParen))
1623
5
    return StmtError();
1624
1625
  // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1626
  // there is no compound stmt.  C90 does not have this clause.  We only do this
1627
  // if the body isn't a compound statement to avoid push/pop in common cases.
1628
  //
1629
  // C++ 6.5p2:
1630
  // The substatement in an iteration-statement implicitly defines a local scope
1631
  // which is entered and exited each time through the loop.
1632
  //
1633
  // See comments in ParseIfStatement for why we create a scope for the
1634
  // condition and a new scope for substatement in C++.
1635
  //
1636
42.4k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1637
1638
42.4k
  MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
1639
1640
  // Read the body statement.
1641
42.4k
  StmtResult Body(ParseStatement(TrailingElseLoc));
1642
1643
42.4k
  if (Body.isUsable())
1644
42.4k
    MIChecker.Check();
1645
  // Pop the body scope if needed.
1646
42.4k
  InnerScope.Exit();
1647
42.4k
  WhileScope.Exit();
1648
1649
42.4k
  if (Cond.isInvalid() || 
Body.isInvalid()42.4k
)
1650
29
    return StmtError();
1651
1652
42.4k
  return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());
1653
42.4k
}
1654
1655
/// ParseDoStatement
1656
///       do-statement: [C99 6.8.5.2]
1657
///         'do' statement 'while' '(' expression ')' ';'
1658
/// Note: this lets the caller parse the end ';'.
1659
7.63k
StmtResult Parser::ParseDoStatement() {
1660
7.63k
  assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1661
7.63k
  SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1662
1663
  // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1664
  // the case for C90.  Start the loop scope.
1665
7.63k
  unsigned ScopeFlags;
1666
7.63k
  if (getLangOpts().C99)
1667
244
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1668
7.38k
  else
1669
7.38k
    ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1670
1671
7.63k
  ParseScope DoScope(this, ScopeFlags);
1672
1673
  // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1674
  // there is no compound stmt.  C90 does not have this clause. We only do this
1675
  // if the body isn't a compound statement to avoid push/pop in common cases.
1676
  //
1677
  // C++ 6.5p2:
1678
  // The substatement in an iteration-statement implicitly defines a local scope
1679
  // which is entered and exited each time through the loop.
1680
  //
1681
7.63k
  bool C99orCXX = getLangOpts().C99 || 
getLangOpts().CPlusPlus7.38k
;
1682
7.63k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1683
1684
  // Read the body statement.
1685
7.63k
  StmtResult Body(ParseStatement());
1686
1687
  // Pop the body scope if needed.
1688
7.63k
  InnerScope.Exit();
1689
1690
7.63k
  if (Tok.isNot(tok::kw_while)) {
1691
6
    if (!Body.isInvalid()) {
1692
5
      Diag(Tok, diag::err_expected_while);
1693
5
      Diag(DoLoc, diag::note_matching) << "'do'";
1694
5
      SkipUntil(tok::semi, StopBeforeMatch);
1695
5
    }
1696
6
    return StmtError();
1697
6
  }
1698
7.62k
  SourceLocation WhileLoc = ConsumeToken();
1699
1700
7.62k
  if (Tok.isNot(tok::l_paren)) {
1701
0
    Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1702
0
    SkipUntil(tok::semi, StopBeforeMatch);
1703
0
    return StmtError();
1704
0
  }
1705
1706
  // Parse the parenthesized expression.
1707
7.62k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1708
7.62k
  T.consumeOpen();
1709
1710
  // A do-while expression is not a condition, so can't have attributes.
1711
7.62k
  DiagnoseAndSkipCXX11Attributes();
1712
1713
7.62k
  ExprResult Cond = ParseExpression();
1714
  // Correct the typos in condition before closing the scope.
1715
7.62k
  if (Cond.isUsable())
1716
7.62k
    Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1717
7.62k
  T.consumeClose();
1718
7.62k
  DoScope.Exit();
1719
1720
7.62k
  if (Cond.isInvalid() || 
Body.isInvalid()7.62k
)
1721
11
    return StmtError();
1722
1723
7.61k
  return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1724
7.61k
                             Cond.get(), T.getCloseLocation());
1725
7.61k
}
1726
1727
38.6k
bool Parser::isForRangeIdentifier() {
1728
38.6k
  assert(Tok.is(tok::identifier));
1729
1730
38.6k
  const Token &Next = NextToken();
1731
38.6k
  if (Next.is(tok::colon))
1732
3
    return true;
1733
1734
38.6k
  if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1735
102
    TentativeParsingAction PA(*this);
1736
102
    ConsumeToken();
1737
102
    SkipCXX11Attributes();
1738
102
    bool Result = Tok.is(tok::colon);
1739
102
    PA.Revert();
1740
102
    return Result;
1741
102
  }
1742
1743
38.5k
  return false;
1744
38.5k
}
1745
1746
/// ParseForStatement
1747
///       for-statement: [C99 6.8.5.3]
1748
///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1749
///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1750
/// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1751
/// [C++]       statement
1752
/// [C++0x] 'for'
1753
///             'co_await'[opt]    [Coroutines]
1754
///             '(' for-range-declaration ':' for-range-initializer ')'
1755
///             statement
1756
/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1757
/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1758
///
1759
/// [C++] for-init-statement:
1760
/// [C++]   expression-statement
1761
/// [C++]   simple-declaration
1762
///
1763
/// [C++0x] for-range-declaration:
1764
/// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1765
/// [C++0x] for-range-initializer:
1766
/// [C++0x]   expression
1767
/// [C++0x]   braced-init-list            [TODO]
1768
184k
StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1769
184k
  assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1770
184k
  SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1771
1772
184k
  SourceLocation CoawaitLoc;
1773
184k
  if (Tok.is(tok::kw_co_await))
1774
9
    CoawaitLoc = ConsumeToken();
1775
1776
184k
  if (Tok.isNot(tok::l_paren)) {
1777
0
    Diag(Tok, diag::err_expected_lparen_after) << "for";
1778
0
    SkipUntil(tok::semi);
1779
0
    return StmtError();
1780
0
  }
1781
1782
184k
  bool C99orCXXorObjC = getLangOpts().C99 || 
getLangOpts().CPlusPlus175k
||
1783
43
    getLangOpts().ObjC;
1784
1785
  // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1786
  // the case for C90.  Start the loop scope.
1787
  //
1788
  // C++ 6.4p3:
1789
  // A name introduced by a declaration in a condition is in scope from its
1790
  // point of declaration until the end of the substatements controlled by the
1791
  // condition.
1792
  // C++ 3.3.2p4:
1793
  // Names declared in the for-init-statement, and in the condition of if,
1794
  // while, for, and switch statements are local to the if, while, for, or
1795
  // switch statement (including the controlled statement).
1796
  // C++ 6.5.3p1:
1797
  // Names declared in the for-init-statement are in the same declarative-region
1798
  // as those declared in the condition.
1799
  //
1800
184k
  unsigned ScopeFlags = 0;
1801
184k
  if (C99orCXXorObjC)
1802
184k
    ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1803
1804
184k
  ParseScope ForScope(this, ScopeFlags);
1805
1806
184k
  BalancedDelimiterTracker T(*this, tok::l_paren);
1807
184k
  T.consumeOpen();
1808
1809
184k
  ExprResult Value;
1810
1811
184k
  bool ForEach = false;
1812
184k
  StmtResult FirstPart;
1813
184k
  Sema::ConditionResult SecondPart;
1814
184k
  ExprResult Collection;
1815
184k
  ForRangeInfo ForRangeInfo;
1816
184k
  FullExprArg ThirdPart(Actions);
1817
1818
184k
  if (Tok.is(tok::code_completion)) {
1819
6
    Actions.CodeCompleteOrdinaryName(getCurScope(),
1820
6
                                     C99orCXXorObjC? Sema::PCC_ForInit
1821
0
                                                   : Sema::PCC_Expression);
1822
6
    cutOffParsing();
1823
6
    return StmtError();
1824
6
  }
1825
1826
184k
  ParsedAttributesWithRange attrs(AttrFactory);
1827
184k
  MaybeParseCXX11Attributes(attrs);
1828
1829
184k
  SourceLocation EmptyInitStmtSemiLoc;
1830
1831
  // Parse the first part of the for specifier.
1832
184k
  if (Tok.is(tok::semi)) {  // for (;
1833
43.2k
    ProhibitAttributes(attrs);
1834
    // no first part, eat the ';'.
1835
43.2k
    SourceLocation SemiLoc = Tok.getLocation();
1836
43.2k
    if (!Tok.hasLeadingEmptyMacro() && 
!SemiLoc.isMacroID()43.2k
)
1837
43.2k
      EmptyInitStmtSemiLoc = SemiLoc;
1838
43.2k
    ConsumeToken();
1839
141k
  } else if (getLangOpts().CPlusPlus && 
Tok.is(tok::identifier)132k
&&
1840
38.6k
             isForRangeIdentifier()) {
1841
6
    ProhibitAttributes(attrs);
1842
6
    IdentifierInfo *Name = Tok.getIdentifierInfo();
1843
6
    SourceLocation Loc = ConsumeToken();
1844
6
    MaybeParseCXX11Attributes(attrs);
1845
1846
6
    ForRangeInfo.ColonLoc = ConsumeToken();
1847
6
    if (Tok.is(tok::l_brace))
1848
0
      ForRangeInfo.RangeExpr = ParseBraceInitializer();
1849
6
    else
1850
6
      ForRangeInfo.RangeExpr = ParseExpression();
1851
1852
6
    Diag(Loc, diag::err_for_range_identifier)
1853
6
      << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1854
6
              ? FixItHint::CreateInsertion(Loc, "auto &&")
1855
0
              : FixItHint());
1856
1857
6
    ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier(
1858
6
        getCurScope(), Loc, Name, attrs, attrs.Range.getEnd());
1859
141k
  } else if (isForInitDeclaration()) {  // for (int X = 4;
1860
111k
    ParenBraceBracketBalancer BalancerRAIIObj(*this);
1861
1862
    // Parse declaration, which eats the ';'.
1863
111k
    if (!C99orCXXorObjC) {   // Use of C99-style for loops in C90 mode?
1864
4
      Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1865
4
      Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1866
4
    }
1867
1868
    // In C++0x, "for (T NS:a" might not be a typo for ::
1869
111k
    bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
1870
111k
    ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1871
1872
111k
    SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1873
111k
    DeclGroupPtrTy DG = ParseSimpleDeclaration(
1874
111k
        DeclaratorContext::ForInit, DeclEnd, attrs, false,
1875
109k
        MightBeForRangeStmt ? &ForRangeInfo : 
nullptr1.83k
);
1876
111k
    FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1877
111k
    if (ForRangeInfo.ParsedForRangeDecl()) {
1878
1.28k
      Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 ?
1879
1.27k
           diag::warn_cxx98_compat_for_range : 
diag::ext_for_range9
);
1880
1.28k
      ForRangeInfo.LoopVar = FirstPart;
1881
1.28k
      FirstPart = StmtResult();
1882
109k
    } else if (Tok.is(tok::semi)) {  // for (int x = 4;
1883
109k
      ConsumeToken();
1884
240
    } else if ((ForEach = isTokIdentifier_in())) {
1885
235
      Actions.ActOnForEachDeclStmt(DG);
1886
      // ObjC: for (id x in expr)
1887
235
      ConsumeToken(); // consume 'in'
1888
1889
235
      if (Tok.is(tok::code_completion)) {
1890
2
        Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
1891
2
        cutOffParsing();
1892
2
        return StmtError();
1893
2
      }
1894
233
      Collection = ParseExpression();
1895
5
    } else {
1896
5
      Diag(Tok, diag::err_expected_semi_for);
1897
5
    }
1898
30.3k
  } else {
1899
30.3k
    ProhibitAttributes(attrs);
1900
30.3k
    Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
1901
1902
30.3k
    ForEach = isTokIdentifier_in();
1903
1904
    // Turn the expression into a stmt.
1905
30.3k
    if (!Value.isInvalid()) {
1906
30.3k
      if (ForEach)
1907
49
        FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
1908
30.3k
      else {
1909
        // We already know this is not an init-statement within a for loop, so
1910
        // if we are parsing a C++11 range-based for loop, we should treat this
1911
        // expression statement as being a discarded value expression because
1912
        // we will err below. This way we do not warn on an unused expression
1913
        // that was an error in the first place, like with: for (expr : expr);
1914
30.3k
        bool IsRangeBasedFor =
1915
30.3k
            getLangOpts().CPlusPlus11 && 
!ForEach23.6k
&&
Tok.is(tok::colon)23.6k
;
1916
30.3k
        FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
1917
30.3k
      }
1918
30.3k
    }
1919
1920
30.3k
    if (Tok.is(tok::semi)) {
1921
30.3k
      ConsumeToken();
1922
62
    } else if (ForEach) {
1923
49
      ConsumeToken(); // consume 'in'
1924
1925
49
      if (Tok.is(tok::code_completion)) {
1926
0
        Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
1927
0
        cutOffParsing();
1928
0
        return StmtError();
1929
0
      }
1930
49
      Collection = ParseExpression();
1931
13
    } else if (getLangOpts().CPlusPlus11 && 
Tok.is(tok::colon)11
&&
FirstPart.get()8
) {
1932
      // User tried to write the reasonable, but ill-formed, for-range-statement
1933
      //   for (expr : expr) { ... }
1934
6
      Diag(Tok, diag::err_for_range_expected_decl)
1935
6
        << FirstPart.get()->getSourceRange();
1936
6
      SkipUntil(tok::r_paren, StopBeforeMatch);
1937
6
      SecondPart = Sema::ConditionError();
1938
7
    } else {
1939
7
      if (!Value.isInvalid()) {
1940
3
        Diag(Tok, diag::err_expected_semi_for);
1941
4
      } else {
1942
        // Skip until semicolon or rparen, don't consume it.
1943
4
        SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
1944
4
        if (Tok.is(tok::semi))
1945
2
          ConsumeToken();
1946
4
      }
1947
7
    }
1948
30.3k
  }
1949
1950
  // Parse the second part of the for specifier.
1951
184k
  getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
1952
184k
  if (!ForEach && 
!ForRangeInfo.ParsedForRangeDecl()184k
&&
1953
183k
      !SecondPart.isInvalid()) {
1954
    // Parse the second part of the for specifier.
1955
183k
    if (Tok.is(tok::semi)) {  // for (...;;
1956
      // no second part.
1957
182k
    } else if (Tok.is(tok::r_paren)) {
1958
      // missing both semicolons.
1959
182k
    } else {
1960
182k
      if (getLangOpts().CPlusPlus) {
1961
        // C++2a: We've parsed an init-statement; we might have a
1962
        // for-range-declaration next.
1963
173k
        bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
1964
173k
        ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
1965
173k
        SecondPart =
1966
173k
            ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean,
1967
173k
                              MightBeForRangeStmt ? &ForRangeInfo : 
nullptr0
);
1968
1969
173k
        if (ForRangeInfo.ParsedForRangeDecl()) {
1970
33
          Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
1971
19
                               : ForRangeInfo.ColonLoc,
1972
52
               getLangOpts().CPlusPlus20
1973
47
                   ? diag::warn_cxx17_compat_for_range_init_stmt
1974
5
                   : diag::ext_for_range_init_stmt)
1975
33
              << (FirstPart.get() ? FirstPart.get()->getSourceRange()
1976
19
                                  : SourceRange());
1977
52
          if (EmptyInitStmtSemiLoc.isValid()) {
1978
4
            Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
1979
4
                << /*for-loop*/ 2
1980
4
                << FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
1981
4
          }
1982
52
        }
1983
8.44k
      } else {
1984
8.44k
        ExprResult SecondExpr = ParseExpression();
1985
8.44k
        if (SecondExpr.isInvalid())
1986
1
          SecondPart = Sema::ConditionError();
1987
8.43k
        else
1988
8.43k
          SecondPart =
1989
8.43k
              Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
1990
8.43k
                                     Sema::ConditionKind::Boolean);
1991
8.44k
      }
1992
182k
    }
1993
183k
  }
1994
1995
  // Parse the third part of the for statement.
1996
184k
  if (!ForEach && 
!ForRangeInfo.ParsedForRangeDecl()184k
) {
1997
183k
    if (Tok.isNot(tok::semi)) {
1998
21
      if (!SecondPart.isInvalid())
1999
8
        Diag(Tok, diag::err_expected_semi_for);
2000
13
      else
2001
        // Skip until semicolon or rparen, don't consume it.
2002
13
        SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
2003
21
    }
2004
2005
183k
    if (Tok.is(tok::semi)) {
2006
183k
      ConsumeToken();
2007
183k
    }
2008
2009
183k
    if (Tok.isNot(tok::r_paren)) {   // for (...;...;)
2010
178k
      ExprResult Third = ParseExpression();
2011
      // FIXME: The C++11 standard doesn't actually say that this is a
2012
      // discarded-value expression, but it clearly should be.
2013
178k
      ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
2014
178k
    }
2015
183k
  }
2016
  // Match the ')'.
2017
184k
  T.consumeClose();
2018
2019
  // C++ Coroutines [stmt.iter]:
2020
  //   'co_await' can only be used for a range-based for statement.
2021
184k
  if (CoawaitLoc.isValid() && 
!ForRangeInfo.ParsedForRangeDecl()9
) {
2022
1
    Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
2023
1
    CoawaitLoc = SourceLocation();
2024
1
  }
2025
2026
  // We need to perform most of the semantic analysis for a C++0x for-range
2027
  // statememt before parsing the body, in order to be able to deduce the type
2028
  // of an auto-typed loop variable.
2029
184k
  StmtResult ForRangeStmt;
2030
184k
  StmtResult ForEachStmt;
2031
2032
184k
  if (ForRangeInfo.ParsedForRangeDecl()) {
2033
1.34k
    ExprResult CorrectedRange =
2034
1.34k
        Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
2035
1.34k
    ForRangeStmt = Actions.ActOnCXXForRangeStmt(
2036
1.34k
        getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
2037
1.34k
        ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
2038
1.34k
        T.getCloseLocation(), Sema::BFRK_Build);
2039
2040
  // Similarly, we need to do the semantic analysis for a for-range
2041
  // statement immediately in order to close over temporaries correctly.
2042
183k
  } else if (ForEach) {
2043
282
    ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
2044
282
                                                     FirstPart.get(),
2045
282
                                                     Collection.get(),
2046
282
                                                     T.getCloseLocation());
2047
183k
  } else {
2048
    // In OpenMP loop region loop control variable must be captured and be
2049
    // private. Perform analysis of first part (if any).
2050
183k
    if (getLangOpts().OpenMP && 
FirstPart.isUsable()110k
) {
2051
110k
      Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
2052
110k
    }
2053
183k
  }
2054
2055
  // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
2056
  // there is no compound stmt.  C90 does not have this clause.  We only do this
2057
  // if the body isn't a compound statement to avoid push/pop in common cases.
2058
  //
2059
  // C++ 6.5p2:
2060
  // The substatement in an iteration-statement implicitly defines a local scope
2061
  // which is entered and exited each time through the loop.
2062
  //
2063
  // See comments in ParseIfStatement for why we create a scope for
2064
  // for-init-statement/condition and a new scope for substatement in C++.
2065
  //
2066
184k
  ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
2067
184k
                        Tok.is(tok::l_brace));
2068
2069
  // The body of the for loop has the same local mangling number as the
2070
  // for-init-statement.
2071
  // It will only be incremented if the body contains other things that would
2072
  // normally increment the mangling number (like a compound statement).
2073
184k
  if (C99orCXXorObjC)
2074
184k
    getCurScope()->decrementMSManglingNumber();
2075
2076
184k
  MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
2077
2078
  // Read the body statement.
2079
184k
  StmtResult Body(ParseStatement(TrailingElseLoc));
2080
2081
184k
  if (Body.isUsable())
2082
184k
    MIChecker.Check();
2083
2084
  // Pop the body scope if needed.
2085
184k
  InnerScope.Exit();
2086
2087
  // Leave the for-scope.
2088
184k
  ForScope.Exit();
2089
2090
184k
  if (Body.isInvalid())
2091
145
    return StmtError();
2092
2093
184k
  if (ForEach)
2094
282
   return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
2095
282
                                              Body.get());
2096
2097
184k
  if (ForRangeInfo.ParsedForRangeDecl())
2098
1.33k
    return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
2099
2100
182k
  return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
2101
182k
                              SecondPart, ThirdPart, T.getCloseLocation(),
2102
182k
                              Body.get());
2103
182k
}
2104
2105
/// ParseGotoStatement
2106
///       jump-statement:
2107
///         'goto' identifier ';'
2108
/// [GNU]   'goto' '*' expression ';'
2109
///
2110
/// Note: this lets the caller parse the end ';'.
2111
///
2112
7.36k
StmtResult Parser::ParseGotoStatement() {
2113
7.36k
  assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
2114
7.36k
  SourceLocation GotoLoc = ConsumeToken();  // eat the 'goto'.
2115
2116
7.36k
  StmtResult Res;
2117
7.36k
  if (Tok.is(tok::identifier)) {
2118
7.23k
    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
2119
7.23k
                                                Tok.getLocation());
2120
7.23k
    Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
2121
7.23k
    ConsumeToken();
2122
129
  } else if (Tok.is(tok::star)) {
2123
    // GNU indirect goto extension.
2124
128
    Diag(Tok, diag::ext_gnu_indirect_goto);
2125
128
    SourceLocation StarLoc = ConsumeToken();
2126
128
    ExprResult R(ParseExpression());
2127
128
    if (R.isInvalid()) {  // Skip to the semicolon, but don't consume it.
2128
0
      SkipUntil(tok::semi, StopBeforeMatch);
2129
0
      return StmtError();
2130
0
    }
2131
128
    Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
2132
1
  } else {
2133
1
    Diag(Tok, diag::err_expected) << tok::identifier;
2134
1
    return StmtError();
2135
1
  }
2136
2137
7.36k
  return Res;
2138
7.36k
}
2139
2140
/// ParseContinueStatement
2141
///       jump-statement:
2142
///         'continue' ';'
2143
///
2144
/// Note: this lets the caller parse the end ';'.
2145
///
2146
5.99k
StmtResult Parser::ParseContinueStatement() {
2147
5.99k
  SourceLocation ContinueLoc = ConsumeToken();  // eat the 'continue'.
2148
5.99k
  return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
2149
5.99k
}
2150
2151
/// ParseBreakStatement
2152
///       jump-statement:
2153
///         'break' ';'
2154
///
2155
/// Note: this lets the caller parse the end ';'.
2156
///
2157
32.6k
StmtResult Parser::ParseBreakStatement() {
2158
32.6k
  SourceLocation BreakLoc = ConsumeToken();  // eat the 'break'.
2159
32.6k
  return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
2160
32.6k
}
2161
2162
/// ParseReturnStatement
2163
///       jump-statement:
2164
///         'return' expression[opt] ';'
2165
///         'return' braced-init-list ';'
2166
///         'co_return' expression[opt] ';'
2167
///         'co_return' braced-init-list ';'
2168
2.81M
StmtResult Parser::ParseReturnStatement() {
2169
2.81M
  assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
2170
2.81M
         "Not a return stmt!");
2171
2.81M
  bool IsCoreturn = Tok.is(tok::kw_co_return);
2172
2.81M
  SourceLocation ReturnLoc = ConsumeToken();  // eat the 'return'.
2173
2174
2.81M
  ExprResult R;
2175
2.81M
  if (Tok.isNot(tok::semi)) {
2176
2.79M
    if (!IsCoreturn)
2177
2.79M
      PreferredType.enterReturn(Actions, Tok.getLocation());
2178
    // FIXME: Code completion for co_return.
2179
2.79M
    if (Tok.is(tok::code_completion) && 
!IsCoreturn15
) {
2180
15
      Actions.CodeCompleteExpression(getCurScope(),
2181
15
                                     PreferredType.get(Tok.getLocation()));
2182
15
      cutOffParsing();
2183
15
      return StmtError();
2184
15
    }
2185
2186
2.79M
    if (Tok.is(tok::l_brace) && 
getLangOpts().CPlusPlus503
) {
2187
503
      R = ParseInitializer();
2188
503
      if (R.isUsable())
2189
503
        Diag(R.get()->getBeginLoc(),
2190
503
             getLangOpts().CPlusPlus11
2191
501
                 ? diag::warn_cxx98_compat_generalized_initializer_lists
2192
2
                 : diag::ext_generalized_initializer_lists)
2193
503
            << R.get()->getSourceRange();
2194
503
    } else
2195
2.79M
      R = ParseExpression();
2196
2.79M
    if (R.isInvalid()) {
2197
221
      SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
2198
221
      return StmtError();
2199
221
    }
2200
2.81M
  }
2201
2.81M
  if (IsCoreturn)
2202
103
    return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
2203
2.81M
  return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
2204
2.81M
}
2205
2206
StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
2207
                                       ParsedStmtContext StmtCtx,
2208
                                       SourceLocation *TrailingElseLoc,
2209
187
                                       ParsedAttributesWithRange &Attrs) {
2210
  // Create temporary attribute list.
2211
187
  ParsedAttributesWithRange TempAttrs(AttrFactory);
2212
2213
187
  SourceLocation StartLoc = Tok.getLocation();
2214
2215
  // Get loop hints and consume annotated token.
2216
564
  while (Tok.is(tok::annot_pragma_loop_hint)) {
2217
377
    LoopHint Hint;
2218
377
    if (!HandlePragmaLoopHint(Hint))
2219
48
      continue;
2220
2221
329
    ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
2222
329
                            ArgsUnion(Hint.ValueExpr)};
2223
329
    TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
2224
329
                     Hint.PragmaNameLoc->Loc, ArgHints, 4,
2225
329
                     ParsedAttr::AS_Pragma);
2226
329
  }
2227
2228
  // Get the next statement.
2229
187
  MaybeParseCXX11Attributes(Attrs);
2230
2231
187
  StmtResult S = ParseStatementOrDeclarationAfterAttributes(
2232
187
      Stmts, StmtCtx, TrailingElseLoc, Attrs);
2233
2234
187
  Attrs.takeAllFrom(TempAttrs);
2235
2236
  // Start of attribute range may already be set for some invalid input.
2237
  // See PR46336.
2238
187
  if (Attrs.Range.getBegin().isInvalid())
2239
186
    Attrs.Range.setBegin(StartLoc);
2240
2241
187
  return S;
2242
187
}
2243
2244
3.22M
Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
2245
3.22M
  assert(Tok.is(tok::l_brace));
2246
3.22M
  SourceLocation LBraceLoc = Tok.getLocation();
2247
2248
3.22M
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
2249
3.22M
                                      "parsing function body");
2250
2251
  // Save and reset current vtordisp stack if we have entered a C++ method body.
2252
3.22M
  bool IsCXXMethod =
2253
3.22M
      getLangOpts().CPlusPlus && 
Decl1.44M
&&
isa<CXXMethodDecl>(Decl)1.44M
;
2254
3.22M
  Sema::PragmaStackSentinelRAII
2255
3.22M
    PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2256
2257
  // Do not enter a scope for the brace, as the arguments are in the same scope
2258
  // (the function body) as the body itself.  Instead, just read the statement
2259
  // list and put it into a CompoundStmt for safe keeping.
2260
3.22M
  StmtResult FnBody(ParseCompoundStatementBody());
2261
2262
  // If the function body could not be parsed, make a bogus compoundstmt.
2263
3.22M
  if (FnBody.isInvalid()) {
2264
0
    Sema::CompoundScopeRAII CompoundScope(Actions);
2265
0
    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2266
0
  }
2267
2268
3.22M
  BodyScope.Exit();
2269
3.22M
  return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2270
3.22M
}
2271
2272
/// ParseFunctionTryBlock - Parse a C++ function-try-block.
2273
///
2274
///       function-try-block:
2275
///         'try' ctor-initializer[opt] compound-statement handler-seq
2276
///
2277
209
Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
2278
209
  assert(Tok.is(tok::kw_try) && "Expected 'try'");
2279
209
  SourceLocation TryLoc = ConsumeToken();
2280
2281
209
  PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
2282
209
                                      "parsing function try block");
2283
2284
  // Constructor initializer list?
2285
209
  if (Tok.is(tok::colon))
2286
10
    ParseConstructorInitializer(Decl);
2287
199
  else
2288
199
    Actions.ActOnDefaultCtorInitializers(Decl);
2289
2290
  // Save and reset current vtordisp stack if we have entered a C++ method body.
2291
209
  bool IsCXXMethod =
2292
209
      getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
2293
209
  Sema::PragmaStackSentinelRAII
2294
209
    PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
2295
2296
209
  SourceLocation LBraceLoc = Tok.getLocation();
2297
209
  StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
2298
  // If we failed to parse the try-catch, we just give the function an empty
2299
  // compound statement as the body.
2300
209
  if (FnBody.isInvalid()) {
2301
4
    Sema::CompoundScopeRAII CompoundScope(Actions);
2302
4
    FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
2303
4
  }
2304
2305
209
  BodyScope.Exit();
2306
209
  return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
2307
209
}
2308
2309
2.41k
bool Parser::trySkippingFunctionBody() {
2310
2.41k
  assert(SkipFunctionBodies &&
2311
2.41k
         "Should only be called when SkipFunctionBodies is enabled");
2312
2.41k
  if (!PP.isCodeCompletionEnabled()) {
2313
30
    SkipFunctionBody();
2314
30
    return true;
2315
30
  }
2316
2317
  // We're in code-completion mode. Skip parsing for all function bodies unless
2318
  // the body contains the code-completion point.
2319
2.38k
  TentativeParsingAction PA(*this);
2320
2.38k
  bool IsTryCatch = Tok.is(tok::kw_try);
2321
2.38k
  CachedTokens Toks;
2322
2.38k
  bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
2323
3.03k
  if (
llvm::any_of(Toks, [](const Token &Tok) 2.38k
{
2324
3.03k
        return Tok.is(tok::code_completion);
2325
34
      })) {
2326
34
    PA.Revert();
2327
34
    return false;
2328
34
  }
2329
2.35k
  if (ErrorInPrologue) {
2330
0
    PA.Commit();
2331
0
    SkipMalformedDecl();
2332
0
    return true;
2333
0
  }
2334
2.35k
  if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2335
870
    PA.Revert();
2336
870
    return false;
2337
870
  }
2338
1.51k
  
while (1.48k
IsTryCatch &&
Tok.is(tok::kw_catch)68
) {
2339
34
    if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
2340
34
        !SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
2341
0
      PA.Revert();
2342
0
      return false;
2343
0
    }
2344
34
  }
2345
1.48k
  PA.Commit();
2346
1.48k
  return true;
2347
1.48k
}
2348
2349
/// ParseCXXTryBlock - Parse a C++ try-block.
2350
///
2351
///       try-block:
2352
///         'try' compound-statement handler-seq
2353
///
2354
10.3k
StmtResult Parser::ParseCXXTryBlock() {
2355
10.3k
  assert(Tok.is(tok::kw_try) && "Expected 'try'");
2356
2357
10.3k
  SourceLocation TryLoc = ConsumeToken();
2358
10.3k
  return ParseCXXTryBlockCommon(TryLoc);
2359
10.3k
}
2360
2361
/// ParseCXXTryBlockCommon - Parse the common part of try-block and
2362
/// function-try-block.
2363
///
2364
///       try-block:
2365
///         'try' compound-statement handler-seq
2366
///
2367
///       function-try-block:
2368
///         'try' ctor-initializer[opt] compound-statement handler-seq
2369
///
2370
///       handler-seq:
2371
///         handler handler-seq[opt]
2372
///
2373
///       [Borland] try-block:
2374
///         'try' compound-statement seh-except-block
2375
///         'try' compound-statement seh-finally-block
2376
///
2377
10.5k
StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
2378
10.5k
  if (Tok.isNot(tok::l_brace))
2379
6
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2380
2381
10.5k
  StmtResult TryBlock(ParseCompoundStatement(
2382
10.5k
      /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2383
10.5k
                                Scope::CompoundStmtScope |
2384
10.3k
                                (FnTry ? 
Scope::FnTryCatchScope205
: 0)));
2385
10.5k
  if (TryBlock.isInvalid())
2386
0
    return TryBlock;
2387
2388
  // Borland allows SEH-handlers with 'try'
2389
2390
10.5k
  if ((Tok.is(tok::identifier) &&
2391
1
       Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2392
10.5k
      Tok.is(tok::kw___finally)) {
2393
    // TODO: Factor into common return ParseSEHHandlerCommon(...)
2394
3
    StmtResult Handler;
2395
3
    if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2396
1
      SourceLocation Loc = ConsumeToken();
2397
1
      Handler = ParseSEHExceptBlock(Loc);
2398
1
    }
2399
2
    else {
2400
2
      SourceLocation Loc = ConsumeToken();
2401
2
      Handler = ParseSEHFinallyBlock(Loc);
2402
2
    }
2403
3
    if(Handler.isInvalid())
2404
0
      return Handler;
2405
2406
3
    return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2407
3
                                    TryLoc,
2408
3
                                    TryBlock.get(),
2409
3
                                    Handler.get());
2410
3
  }
2411
10.5k
  else {
2412
10.5k
    StmtVector Handlers;
2413
2414
    // C++11 attributes can't appear here, despite this context seeming
2415
    // statement-like.
2416
10.5k
    DiagnoseAndSkipCXX11Attributes();
2417
2418
10.5k
    if (Tok.isNot(tok::kw_catch))
2419
0
      return StmtError(Diag(Tok, diag::err_expected_catch));
2420
21.1k
    
while (10.5k
Tok.is(tok::kw_catch)) {
2421
10.6k
      StmtResult Handler(ParseCXXCatchBlock(FnTry));
2422
10.6k
      if (!Handler.isInvalid())
2423
10.6k
        Handlers.push_back(Handler.get());
2424
10.6k
    }
2425
    // Don't bother creating the full statement if we don't have any usable
2426
    // handlers.
2427
10.5k
    if (Handlers.empty())
2428
3
      return StmtError();
2429
2430
10.5k
    return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2431
10.5k
  }
2432
10.5k
}
2433
2434
/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2435
///
2436
///   handler:
2437
///     'catch' '(' exception-declaration ')' compound-statement
2438
///
2439
///   exception-declaration:
2440
///     attribute-specifier-seq[opt] type-specifier-seq declarator
2441
///     attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2442
///     '...'
2443
///
2444
10.6k
StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2445
10.6k
  assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2446
2447
10.6k
  SourceLocation CatchLoc = ConsumeToken();
2448
2449
10.6k
  BalancedDelimiterTracker T(*this, tok::l_paren);
2450
10.6k
  if (T.expectAndConsume())
2451
2
    return StmtError();
2452
2453
  // C++ 3.3.2p3:
2454
  // The name in a catch exception-declaration is local to the handler and
2455
  // shall not be redeclared in the outermost block of the handler.
2456
10.6k
  ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2457
10.6k
                                  Scope::CatchScope |
2458
10.4k
                                  (FnCatch ? 
Scope::FnTryCatchScope217
: 0));
2459
2460
  // exception-declaration is equivalent to '...' or a parameter-declaration
2461
  // without default arguments.
2462
10.6k
  Decl *ExceptionDecl = nullptr;
2463
10.6k
  if (Tok.isNot(tok::ellipsis)) {
2464
774
    ParsedAttributesWithRange Attributes(AttrFactory);
2465
774
    MaybeParseCXX11Attributes(Attributes);
2466
2467
774
    DeclSpec DS(AttrFactory);
2468
774
    DS.takeAttributesFrom(Attributes);
2469
2470
774
    if (ParseCXXTypeSpecifierSeq(DS))
2471
0
      return StmtError();
2472
2473
774
    Declarator ExDecl(DS, DeclaratorContext::CXXCatch);
2474
774
    ParseDeclarator(ExDecl);
2475
774
    ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2476
774
  } else
2477
9.87k
    ConsumeToken();
2478
2479
10.6k
  T.consumeClose();
2480
10.6k
  if (T.getCloseLocation().isInvalid())
2481
0
    return StmtError();
2482
2483
10.6k
  if (Tok.isNot(tok::l_brace))
2484
1
    return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2485
2486
  // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2487
10.6k
  StmtResult Block(ParseCompoundStatement());
2488
10.6k
  if (Block.isInvalid())
2489
0
    return Block;
2490
2491
10.6k
  return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2492
10.6k
}
2493
2494
29
void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2495
29
  IfExistsCondition Result;
2496
29
  if (ParseMicrosoftIfExistsCondition(Result))
2497
2
    return;
2498
2499
  // Handle dependent statements by parsing the braces as a compound statement.
2500
  // This is not the same behavior as Visual C++, which don't treat this as a
2501
  // compound statement, but for Clang's type checking we can't have anything
2502
  // inside these braces escaping to the surrounding code.
2503
27
  if (Result.Behavior == IEB_Dependent) {
2504
8
    if (!Tok.is(tok::l_brace)) {
2505
0
      Diag(Tok, diag::err_expected) << tok::l_brace;
2506
0
      return;
2507
0
    }
2508
2509
8
    StmtResult Compound = ParseCompoundStatement();
2510
8
    if (Compound.isInvalid())
2511
0
      return;
2512
2513
8
    StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2514
8
                                                              Result.IsIfExists,
2515
8
                                                              Result.SS,
2516
8
                                                              Result.Name,
2517
8
                                                              Compound.get());
2518
8
    if (DepResult.isUsable())
2519
8
      Stmts.push_back(DepResult.get());
2520
8
    return;
2521
8
  }
2522
2523
19
  BalancedDelimiterTracker Braces(*this, tok::l_brace);
2524
19
  if (Braces.consumeOpen()) {
2525
0
    Diag(Tok, diag::err_expected) << tok::l_brace;
2526
0
    return;
2527
0
  }
2528
2529
19
  switch (Result.Behavior) {
2530
14
  case IEB_Parse:
2531
    // Parse the statements below.
2532
14
    break;
2533
2534
0
  case IEB_Dependent:
2535
0
    llvm_unreachable("Dependent case handled above");
2536
2537
5
  case IEB_Skip:
2538
5
    Braces.skipToEnd();
2539
5
    return;
2540
14
  }
2541
2542
  // Condition is true, parse the statements.
2543
34
  
while (14
Tok.isNot(tok::r_brace)) {
2544
20
    StmtResult R =
2545
20
        ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
2546
20
    if (R.isUsable())
2547
18
      Stmts.push_back(R.get());
2548
20
  }
2549
14
  Braces.consumeClose();
2550
14
}
2551
2552
7.23k
bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2553
7.23k
  MaybeParseGNUAttributes(Attrs);
2554
2555
7.23k
  if (Attrs.empty())
2556
7.18k
    return true;
2557
2558
45
  if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
2559
23
    return true;
2560
2561
22
  if (!(Tok.is(tok::kw_for) || 
Tok.is(tok::kw_while)14
||
Tok.is(tok::kw_do)7
)) {
2562
1
    Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
2563
1
    return false;
2564
1
  }
2565
21
  return true;
2566
21
}