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