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