Coverage Report

Created: 2021-08-24 07:12

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