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