]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp
Merge clang 7.0.1 and several follow-up changes
[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/AST/PrettyDeclStackTrace.h"
16 #include "clang/Basic/Attributes.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/Parse/Parser.h"
19 #include "clang/Parse/RAIIObjectsForParser.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/LoopHint.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 /// 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, 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     LLVM_FALLTHROUGH;
207   }
208
209   default: {
210     if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
211          Allowed == ACK_Any) &&
212         isDeclarationStatement()) {
213       SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
214       DeclGroupPtrTy Decl = ParseDeclaration(DeclaratorContext::BlockContext,
215                                              DeclEnd, Attrs);
216       return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
217     }
218
219     if (Tok.is(tok::r_brace)) {
220       Diag(Tok, diag::err_expected_statement);
221       return StmtError();
222     }
223
224     return ParseExprStatement();
225   }
226
227   case tok::kw_case:                // C99 6.8.1: labeled-statement
228     return ParseCaseStatement();
229   case tok::kw_default:             // C99 6.8.1: labeled-statement
230     return ParseDefaultStatement();
231
232   case tok::l_brace:                // C99 6.8.2: compound-statement
233     return ParseCompoundStatement();
234   case tok::semi: {                 // C99 6.8.3p3: expression[opt] ';'
235     bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
236     return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
237   }
238
239   case tok::kw_if:                  // C99 6.8.4.1: if-statement
240     return ParseIfStatement(TrailingElseLoc);
241   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
242     return ParseSwitchStatement(TrailingElseLoc);
243
244   case tok::kw_while:               // C99 6.8.5.1: while-statement
245     return ParseWhileStatement(TrailingElseLoc);
246   case tok::kw_do:                  // C99 6.8.5.2: do-statement
247     Res = ParseDoStatement();
248     SemiError = "do/while";
249     break;
250   case tok::kw_for:                 // C99 6.8.5.3: for-statement
251     return ParseForStatement(TrailingElseLoc);
252
253   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
254     Res = ParseGotoStatement();
255     SemiError = "goto";
256     break;
257   case tok::kw_continue:            // C99 6.8.6.2: continue-statement
258     Res = ParseContinueStatement();
259     SemiError = "continue";
260     break;
261   case tok::kw_break:               // C99 6.8.6.3: break-statement
262     Res = ParseBreakStatement();
263     SemiError = "break";
264     break;
265   case tok::kw_return:              // C99 6.8.6.4: return-statement
266     Res = ParseReturnStatement();
267     SemiError = "return";
268     break;
269   case tok::kw_co_return:            // C++ Coroutines: co_return statement
270     Res = ParseReturnStatement();
271     SemiError = "co_return";
272     break;
273
274   case tok::kw_asm: {
275     ProhibitAttributes(Attrs);
276     bool msAsm = false;
277     Res = ParseAsmStatement(msAsm);
278     Res = Actions.ActOnFinishFullStmt(Res.get());
279     if (msAsm) return Res;
280     SemiError = "asm";
281     break;
282   }
283
284   case tok::kw___if_exists:
285   case tok::kw___if_not_exists:
286     ProhibitAttributes(Attrs);
287     ParseMicrosoftIfExistsStatement(Stmts);
288     // An __if_exists block is like a compound statement, but it doesn't create
289     // a new scope.
290     return StmtEmpty();
291
292   case tok::kw_try:                 // C++ 15: try-block
293     return ParseCXXTryBlock();
294
295   case tok::kw___try:
296     ProhibitAttributes(Attrs); // TODO: is it correct?
297     return ParseSEHTryBlock();
298
299   case tok::kw___leave:
300     Res = ParseSEHLeaveStatement();
301     SemiError = "__leave";
302     break;
303
304   case tok::annot_pragma_vis:
305     ProhibitAttributes(Attrs);
306     HandlePragmaVisibility();
307     return StmtEmpty();
308
309   case tok::annot_pragma_pack:
310     ProhibitAttributes(Attrs);
311     HandlePragmaPack();
312     return StmtEmpty();
313
314   case tok::annot_pragma_msstruct:
315     ProhibitAttributes(Attrs);
316     HandlePragmaMSStruct();
317     return StmtEmpty();
318
319   case tok::annot_pragma_align:
320     ProhibitAttributes(Attrs);
321     HandlePragmaAlign();
322     return StmtEmpty();
323
324   case tok::annot_pragma_weak:
325     ProhibitAttributes(Attrs);
326     HandlePragmaWeak();
327     return StmtEmpty();
328
329   case tok::annot_pragma_weakalias:
330     ProhibitAttributes(Attrs);
331     HandlePragmaWeakAlias();
332     return StmtEmpty();
333
334   case tok::annot_pragma_redefine_extname:
335     ProhibitAttributes(Attrs);
336     HandlePragmaRedefineExtname();
337     return StmtEmpty();
338
339   case tok::annot_pragma_fp_contract:
340     ProhibitAttributes(Attrs);
341     Diag(Tok, diag::err_pragma_fp_contract_scope);
342     ConsumeAnnotationToken();
343     return StmtError();
344
345   case tok::annot_pragma_fp:
346     ProhibitAttributes(Attrs);
347     Diag(Tok, diag::err_pragma_fp_scope);
348     ConsumeAnnotationToken();
349     return StmtError();
350
351   case tok::annot_pragma_opencl_extension:
352     ProhibitAttributes(Attrs);
353     HandlePragmaOpenCLExtension();
354     return StmtEmpty();
355
356   case tok::annot_pragma_captured:
357     ProhibitAttributes(Attrs);
358     return HandlePragmaCaptured();
359
360   case tok::annot_pragma_openmp:
361     ProhibitAttributes(Attrs);
362     return ParseOpenMPDeclarativeOrExecutableDirective(Allowed);
363
364   case tok::annot_pragma_ms_pointers_to_members:
365     ProhibitAttributes(Attrs);
366     HandlePragmaMSPointersToMembers();
367     return StmtEmpty();
368
369   case tok::annot_pragma_ms_pragma:
370     ProhibitAttributes(Attrs);
371     HandlePragmaMSPragma();
372     return StmtEmpty();
373
374   case tok::annot_pragma_ms_vtordisp:
375     ProhibitAttributes(Attrs);
376     HandlePragmaMSVtorDisp();
377     return StmtEmpty();
378
379   case tok::annot_pragma_loop_hint:
380     ProhibitAttributes(Attrs);
381     return ParsePragmaLoopHint(Stmts, Allowed, TrailingElseLoc, Attrs);
382
383   case tok::annot_pragma_dump:
384     HandlePragmaDump();
385     return StmtEmpty();
386
387   case tok::annot_pragma_attribute:
388     HandlePragmaAttribute();
389     return StmtEmpty();
390   }
391
392   // If we reached this code, the statement must end in a semicolon.
393   if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
394     // If the result was valid, then we do want to diagnose this.  Use
395     // ExpectAndConsume to emit the diagnostic, even though we know it won't
396     // succeed.
397     ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
398     // Skip until we see a } or ;, but don't eat it.
399     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
400   }
401
402   return Res;
403 }
404
405 /// Parse an expression statement.
406 StmtResult Parser::ParseExprStatement() {
407   // If a case keyword is missing, this is where it should be inserted.
408   Token OldToken = Tok;
409
410   ExprStatementTokLoc = Tok.getLocation();
411
412   // expression[opt] ';'
413   ExprResult Expr(ParseExpression());
414   if (Expr.isInvalid()) {
415     // If the expression is invalid, skip ahead to the next semicolon or '}'.
416     // Not doing this opens us up to the possibility of infinite loops if
417     // ParseExpression does not consume any tokens.
418     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
419     if (Tok.is(tok::semi))
420       ConsumeToken();
421     return Actions.ActOnExprStmtError();
422   }
423
424   if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
425       Actions.CheckCaseExpression(Expr.get())) {
426     // If a constant expression is followed by a colon inside a switch block,
427     // suggest a missing case keyword.
428     Diag(OldToken, diag::err_expected_case_before_expression)
429       << FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
430
431     // Recover parsing as a case statement.
432     return ParseCaseStatement(/*MissingCase=*/true, Expr);
433   }
434
435   // Otherwise, eat the semicolon.
436   ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
437   return Actions.ActOnExprStmt(Expr);
438 }
439
440 /// ParseSEHTryBlockCommon
441 ///
442 /// seh-try-block:
443 ///   '__try' compound-statement seh-handler
444 ///
445 /// seh-handler:
446 ///   seh-except-block
447 ///   seh-finally-block
448 ///
449 StmtResult Parser::ParseSEHTryBlock() {
450   assert(Tok.is(tok::kw___try) && "Expected '__try'");
451   SourceLocation TryLoc = ConsumeToken();
452
453   if (Tok.isNot(tok::l_brace))
454     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
455
456   StmtResult TryBlock(ParseCompoundStatement(
457       /*isStmtExpr=*/false,
458       Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
459   if (TryBlock.isInvalid())
460     return TryBlock;
461
462   StmtResult Handler;
463   if (Tok.is(tok::identifier) &&
464       Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
465     SourceLocation Loc = ConsumeToken();
466     Handler = ParseSEHExceptBlock(Loc);
467   } else if (Tok.is(tok::kw___finally)) {
468     SourceLocation Loc = ConsumeToken();
469     Handler = ParseSEHFinallyBlock(Loc);
470   } else {
471     return StmtError(Diag(Tok, diag::err_seh_expected_handler));
472   }
473
474   if(Handler.isInvalid())
475     return Handler;
476
477   return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
478                                   TryLoc,
479                                   TryBlock.get(),
480                                   Handler.get());
481 }
482
483 /// ParseSEHExceptBlock - Handle __except
484 ///
485 /// seh-except-block:
486 ///   '__except' '(' seh-filter-expression ')' compound-statement
487 ///
488 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
489   PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
490     raii2(Ident___exception_code, false),
491     raii3(Ident_GetExceptionCode, false);
492
493   if (ExpectAndConsume(tok::l_paren))
494     return StmtError();
495
496   ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
497                                    Scope::SEHExceptScope);
498
499   if (getLangOpts().Borland) {
500     Ident__exception_info->setIsPoisoned(false);
501     Ident___exception_info->setIsPoisoned(false);
502     Ident_GetExceptionInfo->setIsPoisoned(false);
503   }
504
505   ExprResult FilterExpr;
506   {
507     ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
508                                           Scope::SEHFilterScope);
509     FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
510   }
511
512   if (getLangOpts().Borland) {
513     Ident__exception_info->setIsPoisoned(true);
514     Ident___exception_info->setIsPoisoned(true);
515     Ident_GetExceptionInfo->setIsPoisoned(true);
516   }
517
518   if(FilterExpr.isInvalid())
519     return StmtError();
520
521   if (ExpectAndConsume(tok::r_paren))
522     return StmtError();
523
524   if (Tok.isNot(tok::l_brace))
525     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
526
527   StmtResult Block(ParseCompoundStatement());
528
529   if(Block.isInvalid())
530     return Block;
531
532   return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
533 }
534
535 /// ParseSEHFinallyBlock - Handle __finally
536 ///
537 /// seh-finally-block:
538 ///   '__finally' compound-statement
539 ///
540 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
541   PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
542     raii2(Ident___abnormal_termination, false),
543     raii3(Ident_AbnormalTermination, false);
544
545   if (Tok.isNot(tok::l_brace))
546     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
547
548   ParseScope FinallyScope(this, 0);
549   Actions.ActOnStartSEHFinallyBlock();
550
551   StmtResult Block(ParseCompoundStatement());
552   if(Block.isInvalid()) {
553     Actions.ActOnAbortSEHFinallyBlock();
554     return Block;
555   }
556
557   return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
558 }
559
560 /// Handle __leave
561 ///
562 /// seh-leave-statement:
563 ///   '__leave' ';'
564 ///
565 StmtResult Parser::ParseSEHLeaveStatement() {
566   SourceLocation LeaveLoc = ConsumeToken();  // eat the '__leave'.
567   return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
568 }
569
570 /// ParseLabeledStatement - We have an identifier and a ':' after it.
571 ///
572 ///       labeled-statement:
573 ///         identifier ':' statement
574 /// [GNU]   identifier ':' attributes[opt] statement
575 ///
576 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) {
577   assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
578          "Not an identifier!");
579
580   Token IdentTok = Tok;  // Save the whole token.
581   ConsumeToken();  // eat the identifier.
582
583   assert(Tok.is(tok::colon) && "Not a label!");
584
585   // identifier ':' statement
586   SourceLocation ColonLoc = ConsumeToken();
587
588   // Read label attributes, if present.
589   StmtResult SubStmt;
590   if (Tok.is(tok::kw___attribute)) {
591     ParsedAttributesWithRange TempAttrs(AttrFactory);
592     ParseGNUAttributes(TempAttrs);
593
594     // In C++, GNU attributes only apply to the label if they are followed by a
595     // semicolon, to disambiguate label attributes from attributes on a labeled
596     // declaration.
597     //
598     // This doesn't quite match what GCC does; if the attribute list is empty
599     // and followed by a semicolon, GCC will reject (it appears to parse the
600     // attributes as part of a statement in that case). That looks like a bug.
601     if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
602       attrs.takeAllFrom(TempAttrs);
603     else if (isDeclarationStatement()) {
604       StmtVector Stmts;
605       // FIXME: We should do this whether or not we have a declaration
606       // statement, but that doesn't work correctly (because ProhibitAttributes
607       // can't handle GNU attributes), so only call it in the one case where
608       // GNU attributes are allowed.
609       SubStmt = ParseStatementOrDeclarationAfterAttributes(
610           Stmts, /*Allowed=*/ACK_StatementsOpenMPNonStandalone, nullptr,
611           TempAttrs);
612       if (!TempAttrs.empty() && !SubStmt.isInvalid())
613         SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
614                                                 TempAttrs.Range);
615     } else {
616       Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
617     }
618   }
619
620   // If we've not parsed a statement yet, parse one now.
621   if (!SubStmt.isInvalid() && !SubStmt.isUsable())
622     SubStmt = ParseStatement();
623
624   // Broken substmt shouldn't prevent the label from being added to the AST.
625   if (SubStmt.isInvalid())
626     SubStmt = Actions.ActOnNullStmt(ColonLoc);
627
628   LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
629                                               IdentTok.getLocation());
630   Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
631   attrs.clear();
632
633   return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
634                                 SubStmt.get());
635 }
636
637 /// ParseCaseStatement
638 ///       labeled-statement:
639 ///         'case' constant-expression ':' statement
640 /// [GNU]   'case' constant-expression '...' constant-expression ':' statement
641 ///
642 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) {
643   assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
644
645   // It is very very common for code to contain many case statements recursively
646   // nested, as in (but usually without indentation):
647   //  case 1:
648   //    case 2:
649   //      case 3:
650   //         case 4:
651   //           case 5: etc.
652   //
653   // Parsing this naively works, but is both inefficient and can cause us to run
654   // out of stack space in our recursive descent parser.  As a special case,
655   // flatten this recursion into an iterative loop.  This is complex and gross,
656   // but all the grossness is constrained to ParseCaseStatement (and some
657   // weirdness in the actions), so this is just local grossness :).
658
659   // TopLevelCase - This is the highest level we have parsed.  'case 1' in the
660   // example above.
661   StmtResult TopLevelCase(true);
662
663   // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
664   // gets updated each time a new case is parsed, and whose body is unset so
665   // far.  When parsing 'case 4', this is the 'case 3' node.
666   Stmt *DeepestParsedCaseStmt = nullptr;
667
668   // While we have case statements, eat and stack them.
669   SourceLocation ColonLoc;
670   do {
671     SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
672                                            ConsumeToken();  // eat the 'case'.
673     ColonLoc = SourceLocation();
674
675     if (Tok.is(tok::code_completion)) {
676       Actions.CodeCompleteCase(getCurScope());
677       cutOffParsing();
678       return StmtError();
679     }
680
681     /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
682     /// Disable this form of error recovery while we're parsing the case
683     /// expression.
684     ColonProtectionRAIIObject ColonProtection(*this);
685
686     ExprResult LHS;
687     if (!MissingCase) {
688       LHS = ParseCaseExpression(CaseLoc);
689       if (LHS.isInvalid()) {
690         // If constant-expression is parsed unsuccessfully, recover by skipping
691         // current case statement (moving to the colon that ends it).
692         if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
693           return StmtError();
694       }
695     } else {
696       LHS = Expr;
697       MissingCase = false;
698     }
699
700     // GNU case range extension.
701     SourceLocation DotDotDotLoc;
702     ExprResult RHS;
703     if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
704       Diag(DotDotDotLoc, diag::ext_gnu_case_range);
705       RHS = ParseCaseExpression(CaseLoc);
706       if (RHS.isInvalid()) {
707         if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
708           return StmtError();
709       }
710     }
711
712     ColonProtection.restore();
713
714     if (TryConsumeToken(tok::colon, ColonLoc)) {
715     } else if (TryConsumeToken(tok::semi, ColonLoc) ||
716                TryConsumeToken(tok::coloncolon, ColonLoc)) {
717       // Treat "case blah;" or "case blah::" as a typo for "case blah:".
718       Diag(ColonLoc, diag::err_expected_after)
719           << "'case'" << tok::colon
720           << FixItHint::CreateReplacement(ColonLoc, ":");
721     } else {
722       SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
723       Diag(ExpectedLoc, diag::err_expected_after)
724           << "'case'" << tok::colon
725           << FixItHint::CreateInsertion(ExpectedLoc, ":");
726       ColonLoc = ExpectedLoc;
727     }
728
729     StmtResult Case =
730         Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
731
732     // If we had a sema error parsing this case, then just ignore it and
733     // continue parsing the sub-stmt.
734     if (Case.isInvalid()) {
735       if (TopLevelCase.isInvalid())  // No parsed case stmts.
736         return ParseStatement(/*TrailingElseLoc=*/nullptr,
737                               /*AllowOpenMPStandalone=*/true);
738       // Otherwise, just don't add it as a nested case.
739     } else {
740       // If this is the first case statement we parsed, it becomes TopLevelCase.
741       // Otherwise we link it into the current chain.
742       Stmt *NextDeepest = Case.get();
743       if (TopLevelCase.isInvalid())
744         TopLevelCase = Case;
745       else
746         Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
747       DeepestParsedCaseStmt = NextDeepest;
748     }
749
750     // Handle all case statements.
751   } while (Tok.is(tok::kw_case));
752
753   // If we found a non-case statement, start by parsing it.
754   StmtResult SubStmt;
755
756   if (Tok.isNot(tok::r_brace)) {
757     SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
758                              /*AllowOpenMPStandalone=*/true);
759   } else {
760     // Nicely diagnose the common error "switch (X) { case 4: }", which is
761     // not valid.  If ColonLoc doesn't point to a valid text location, there was
762     // another parsing error, so avoid producing extra diagnostics.
763     if (ColonLoc.isValid()) {
764       SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
765       Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
766         << FixItHint::CreateInsertion(AfterColonLoc, " ;");
767     }
768     SubStmt = StmtError();
769   }
770
771   // Install the body into the most deeply-nested case.
772   if (DeepestParsedCaseStmt) {
773     // Broken sub-stmt shouldn't prevent forming the case statement properly.
774     if (SubStmt.isInvalid())
775       SubStmt = Actions.ActOnNullStmt(SourceLocation());
776     Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
777   }
778
779   // Return the top level parsed statement tree.
780   return TopLevelCase;
781 }
782
783 /// ParseDefaultStatement
784 ///       labeled-statement:
785 ///         'default' ':' statement
786 /// Note that this does not parse the 'statement' at the end.
787 ///
788 StmtResult Parser::ParseDefaultStatement() {
789   assert(Tok.is(tok::kw_default) && "Not a default stmt!");
790   SourceLocation DefaultLoc = ConsumeToken();  // eat the 'default'.
791
792   SourceLocation ColonLoc;
793   if (TryConsumeToken(tok::colon, ColonLoc)) {
794   } else if (TryConsumeToken(tok::semi, ColonLoc)) {
795     // Treat "default;" as a typo for "default:".
796     Diag(ColonLoc, diag::err_expected_after)
797         << "'default'" << tok::colon
798         << FixItHint::CreateReplacement(ColonLoc, ":");
799   } else {
800     SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
801     Diag(ExpectedLoc, diag::err_expected_after)
802         << "'default'" << tok::colon
803         << FixItHint::CreateInsertion(ExpectedLoc, ":");
804     ColonLoc = ExpectedLoc;
805   }
806
807   StmtResult SubStmt;
808
809   if (Tok.isNot(tok::r_brace)) {
810     SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr,
811                              /*AllowOpenMPStandalone=*/true);
812   } else {
813     // Diagnose the common error "switch (X) {... default: }", which is
814     // not valid.
815     SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
816     Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
817       << FixItHint::CreateInsertion(AfterColonLoc, " ;");
818     SubStmt = true;
819   }
820
821   // Broken sub-stmt shouldn't prevent forming the case statement properly.
822   if (SubStmt.isInvalid())
823     SubStmt = Actions.ActOnNullStmt(ColonLoc);
824
825   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
826                                   SubStmt.get(), getCurScope());
827 }
828
829 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
830   return ParseCompoundStatement(isStmtExpr,
831                                 Scope::DeclScope | Scope::CompoundStmtScope);
832 }
833
834 /// ParseCompoundStatement - Parse a "{}" block.
835 ///
836 ///       compound-statement: [C99 6.8.2]
837 ///         { block-item-list[opt] }
838 /// [GNU]   { label-declarations block-item-list } [TODO]
839 ///
840 ///       block-item-list:
841 ///         block-item
842 ///         block-item-list block-item
843 ///
844 ///       block-item:
845 ///         declaration
846 /// [GNU]   '__extension__' declaration
847 ///         statement
848 ///
849 /// [GNU] label-declarations:
850 /// [GNU]   label-declaration
851 /// [GNU]   label-declarations label-declaration
852 ///
853 /// [GNU] label-declaration:
854 /// [GNU]   '__label__' identifier-list ';'
855 ///
856 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
857                                           unsigned ScopeFlags) {
858   assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
859
860   // Enter a scope to hold everything within the compound stmt.  Compound
861   // statements can always hold declarations.
862   ParseScope CompoundScope(this, ScopeFlags);
863
864   // Parse the statements in the body.
865   return ParseCompoundStatementBody(isStmtExpr);
866 }
867
868 /// Parse any pragmas at the start of the compound expression. We handle these
869 /// separately since some pragmas (FP_CONTRACT) must appear before any C
870 /// statement in the compound, but may be intermingled with other pragmas.
871 void Parser::ParseCompoundStatementLeadingPragmas() {
872   bool checkForPragmas = true;
873   while (checkForPragmas) {
874     switch (Tok.getKind()) {
875     case tok::annot_pragma_vis:
876       HandlePragmaVisibility();
877       break;
878     case tok::annot_pragma_pack:
879       HandlePragmaPack();
880       break;
881     case tok::annot_pragma_msstruct:
882       HandlePragmaMSStruct();
883       break;
884     case tok::annot_pragma_align:
885       HandlePragmaAlign();
886       break;
887     case tok::annot_pragma_weak:
888       HandlePragmaWeak();
889       break;
890     case tok::annot_pragma_weakalias:
891       HandlePragmaWeakAlias();
892       break;
893     case tok::annot_pragma_redefine_extname:
894       HandlePragmaRedefineExtname();
895       break;
896     case tok::annot_pragma_opencl_extension:
897       HandlePragmaOpenCLExtension();
898       break;
899     case tok::annot_pragma_fp_contract:
900       HandlePragmaFPContract();
901       break;
902     case tok::annot_pragma_fp:
903       HandlePragmaFP();
904       break;
905     case tok::annot_pragma_ms_pointers_to_members:
906       HandlePragmaMSPointersToMembers();
907       break;
908     case tok::annot_pragma_ms_pragma:
909       HandlePragmaMSPragma();
910       break;
911     case tok::annot_pragma_ms_vtordisp:
912       HandlePragmaMSVtorDisp();
913       break;
914     case tok::annot_pragma_dump:
915       HandlePragmaDump();
916       break;
917     default:
918       checkForPragmas = false;
919       break;
920     }
921   }
922
923 }
924
925 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
926 /// ActOnCompoundStmt action.  This expects the '{' to be the current token, and
927 /// consume the '}' at the end of the block.  It does not manipulate the scope
928 /// stack.
929 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
930   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
931                                 Tok.getLocation(),
932                                 "in compound statement ('{}')");
933
934   // Record the state of the FP_CONTRACT pragma, restore on leaving the
935   // compound statement.
936   Sema::FPContractStateRAII SaveFPContractState(Actions);
937
938   InMessageExpressionRAIIObject InMessage(*this, false);
939   BalancedDelimiterTracker T(*this, tok::l_brace);
940   if (T.consumeOpen())
941     return StmtError();
942
943   Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
944
945   // Parse any pragmas at the beginning of the compound statement.
946   ParseCompoundStatementLeadingPragmas();
947
948   StmtVector Stmts;
949
950   // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
951   // only allowed at the start of a compound stmt regardless of the language.
952   while (Tok.is(tok::kw___label__)) {
953     SourceLocation LabelLoc = ConsumeToken();
954
955     SmallVector<Decl *, 8> DeclsInGroup;
956     while (1) {
957       if (Tok.isNot(tok::identifier)) {
958         Diag(Tok, diag::err_expected) << tok::identifier;
959         break;
960       }
961
962       IdentifierInfo *II = Tok.getIdentifierInfo();
963       SourceLocation IdLoc = ConsumeToken();
964       DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
965
966       if (!TryConsumeToken(tok::comma))
967         break;
968     }
969
970     DeclSpec DS(AttrFactory);
971     DeclGroupPtrTy Res =
972         Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
973     StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
974
975     ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
976     if (R.isUsable())
977       Stmts.push_back(R.get());
978   }
979
980   while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
981          Tok.isNot(tok::eof)) {
982     if (Tok.is(tok::annot_pragma_unused)) {
983       HandlePragmaUnused();
984       continue;
985     }
986
987     StmtResult R;
988     if (Tok.isNot(tok::kw___extension__)) {
989       R = ParseStatementOrDeclaration(Stmts, ACK_Any);
990     } else {
991       // __extension__ can start declarations and it can also be a unary
992       // operator for expressions.  Consume multiple __extension__ markers here
993       // until we can determine which is which.
994       // FIXME: This loses extension expressions in the AST!
995       SourceLocation ExtLoc = ConsumeToken();
996       while (Tok.is(tok::kw___extension__))
997         ConsumeToken();
998
999       ParsedAttributesWithRange attrs(AttrFactory);
1000       MaybeParseCXX11Attributes(attrs, nullptr,
1001                                 /*MightBeObjCMessageSend*/ true);
1002
1003       // If this is the start of a declaration, parse it as such.
1004       if (isDeclarationStatement()) {
1005         // __extension__ silences extension warnings in the subdeclaration.
1006         // FIXME: Save the __extension__ on the decl as a node somehow?
1007         ExtensionRAIIObject O(Diags);
1008
1009         SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1010         DeclGroupPtrTy Res =
1011             ParseDeclaration(DeclaratorContext::BlockContext, DeclEnd, attrs);
1012         R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
1013       } else {
1014         // Otherwise this was a unary __extension__ marker.
1015         ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
1016
1017         if (Res.isInvalid()) {
1018           SkipUntil(tok::semi);
1019           continue;
1020         }
1021
1022         // FIXME: Use attributes?
1023         // Eat the semicolon at the end of stmt and convert the expr into a
1024         // statement.
1025         ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
1026         R = Actions.ActOnExprStmt(Res);
1027       }
1028     }
1029
1030     if (R.isUsable())
1031       Stmts.push_back(R.get());
1032   }
1033
1034   SourceLocation CloseLoc = Tok.getLocation();
1035
1036   // We broke out of the while loop because we found a '}' or EOF.
1037   if (!T.consumeClose())
1038     // Recover by creating a compound statement with what we parsed so far,
1039     // instead of dropping everything and returning StmtError();
1040     CloseLoc = T.getCloseLocation();
1041
1042   return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
1043                                    Stmts, isStmtExpr);
1044 }
1045
1046 /// ParseParenExprOrCondition:
1047 /// [C  ]     '(' expression ')'
1048 /// [C++]     '(' condition ')'
1049 /// [C++1z]   '(' init-statement[opt] condition ')'
1050 ///
1051 /// This function parses and performs error recovery on the specified condition
1052 /// or expression (depending on whether we're in C++ or C mode).  This function
1053 /// goes out of its way to recover well.  It returns true if there was a parser
1054 /// error (the right paren couldn't be found), which indicates that the caller
1055 /// should try to recover harder.  It returns false if the condition is
1056 /// successfully parsed.  Note that a successful parse can still have semantic
1057 /// errors in the condition.
1058 bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
1059                                        Sema::ConditionResult &Cond,
1060                                        SourceLocation Loc,
1061                                        Sema::ConditionKind CK) {
1062   BalancedDelimiterTracker T(*this, tok::l_paren);
1063   T.consumeOpen();
1064
1065   if (getLangOpts().CPlusPlus)
1066     Cond = ParseCXXCondition(InitStmt, Loc, CK);
1067   else {
1068     ExprResult CondExpr = ParseExpression();
1069
1070     // If required, convert to a boolean value.
1071     if (CondExpr.isInvalid())
1072       Cond = Sema::ConditionError();
1073     else
1074       Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
1075   }
1076
1077   // If the parser was confused by the condition and we don't have a ')', try to
1078   // recover by skipping ahead to a semi and bailing out.  If condexp is
1079   // semantically invalid but we have well formed code, keep going.
1080   if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
1081     SkipUntil(tok::semi);
1082     // Skipping may have stopped if it found the containing ')'.  If so, we can
1083     // continue parsing the if statement.
1084     if (Tok.isNot(tok::r_paren))
1085       return true;
1086   }
1087
1088   // Otherwise the condition is valid or the rparen is present.
1089   T.consumeClose();
1090
1091   // Check for extraneous ')'s to catch things like "if (foo())) {".  We know
1092   // that all callers are looking for a statement after the condition, so ")"
1093   // isn't valid.
1094   while (Tok.is(tok::r_paren)) {
1095     Diag(Tok, diag::err_extraneous_rparen_in_condition)
1096       << FixItHint::CreateRemoval(Tok.getLocation());
1097     ConsumeParen();
1098   }
1099
1100   return false;
1101 }
1102
1103
1104 /// ParseIfStatement
1105 ///       if-statement: [C99 6.8.4.1]
1106 ///         'if' '(' expression ')' statement
1107 ///         'if' '(' expression ')' statement 'else' statement
1108 /// [C++]   'if' '(' condition ')' statement
1109 /// [C++]   'if' '(' condition ')' statement 'else' statement
1110 ///
1111 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
1112   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
1113   SourceLocation IfLoc = ConsumeToken();  // eat the 'if'.
1114
1115   bool IsConstexpr = false;
1116   if (Tok.is(tok::kw_constexpr)) {
1117     Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
1118                                         : diag::ext_constexpr_if);
1119     IsConstexpr = true;
1120     ConsumeToken();
1121   }
1122
1123   if (Tok.isNot(tok::l_paren)) {
1124     Diag(Tok, diag::err_expected_lparen_after) << "if";
1125     SkipUntil(tok::semi);
1126     return StmtError();
1127   }
1128
1129   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1130
1131   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
1132   // the case for C90.
1133   //
1134   // C++ 6.4p3:
1135   // A name introduced by a declaration in a condition is in scope from its
1136   // point of declaration until the end of the substatements controlled by the
1137   // condition.
1138   // C++ 3.3.2p4:
1139   // Names declared in the for-init-statement, and in the condition of if,
1140   // while, for, and switch statements are local to the if, while, for, or
1141   // switch statement (including the controlled statement).
1142   //
1143   ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
1144
1145   // Parse the condition.
1146   StmtResult InitStmt;
1147   Sema::ConditionResult Cond;
1148   if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
1149                                 IsConstexpr ? Sema::ConditionKind::ConstexprIf
1150                                             : Sema::ConditionKind::Boolean))
1151     return StmtError();
1152
1153   llvm::Optional<bool> ConstexprCondition;
1154   if (IsConstexpr)
1155     ConstexprCondition = Cond.getKnownValue();
1156
1157   // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1158   // there is no compound stmt.  C90 does not have this clause.  We only do this
1159   // if the body isn't a compound statement to avoid push/pop in common cases.
1160   //
1161   // C++ 6.4p1:
1162   // The substatement in a selection-statement (each substatement, in the else
1163   // form of the if statement) implicitly defines a local scope.
1164   //
1165   // For C++ we create a scope for the condition and a new scope for
1166   // substatements because:
1167   // -When the 'then' scope exits, we want the condition declaration to still be
1168   //    active for the 'else' scope too.
1169   // -Sema will detect name clashes by considering declarations of a
1170   //    'ControlScope' as part of its direct subscope.
1171   // -If we wanted the condition and substatement to be in the same scope, we
1172   //    would have to notify ParseStatement not to create a new scope. It's
1173   //    simpler to let it create a new scope.
1174   //
1175   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1176
1177   // Read the 'then' stmt.
1178   SourceLocation ThenStmtLoc = Tok.getLocation();
1179
1180   SourceLocation InnerStatementTrailingElseLoc;
1181   StmtResult ThenStmt;
1182   {
1183     EnterExpressionEvaluationContext PotentiallyDiscarded(
1184         Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1185         Sema::ExpressionEvaluationContextRecord::EK_Other,
1186         /*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
1187     ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
1188   }
1189
1190   // Pop the 'if' scope if needed.
1191   InnerScope.Exit();
1192
1193   // If it has an else, parse it.
1194   SourceLocation ElseLoc;
1195   SourceLocation ElseStmtLoc;
1196   StmtResult ElseStmt;
1197
1198   if (Tok.is(tok::kw_else)) {
1199     if (TrailingElseLoc)
1200       *TrailingElseLoc = Tok.getLocation();
1201
1202     ElseLoc = ConsumeToken();
1203     ElseStmtLoc = Tok.getLocation();
1204
1205     // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
1206     // there is no compound stmt.  C90 does not have this clause.  We only do
1207     // this if the body isn't a compound statement to avoid push/pop in common
1208     // cases.
1209     //
1210     // C++ 6.4p1:
1211     // The substatement in a selection-statement (each substatement, in the else
1212     // form of the if statement) implicitly defines a local scope.
1213     //
1214     ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
1215                           Tok.is(tok::l_brace));
1216
1217     EnterExpressionEvaluationContext PotentiallyDiscarded(
1218         Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
1219         Sema::ExpressionEvaluationContextRecord::EK_Other,
1220         /*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
1221     ElseStmt = ParseStatement();
1222
1223     // Pop the 'else' scope if needed.
1224     InnerScope.Exit();
1225   } else if (Tok.is(tok::code_completion)) {
1226     Actions.CodeCompleteAfterIf(getCurScope());
1227     cutOffParsing();
1228     return StmtError();
1229   } else if (InnerStatementTrailingElseLoc.isValid()) {
1230     Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
1231   }
1232
1233   IfScope.Exit();
1234
1235   // If the then or else stmt is invalid and the other is valid (and present),
1236   // make turn the invalid one into a null stmt to avoid dropping the other
1237   // part.  If both are invalid, return error.
1238   if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
1239       (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
1240       (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
1241     // Both invalid, or one is invalid and other is non-present: return error.
1242     return StmtError();
1243   }
1244
1245   // Now if either are invalid, replace with a ';'.
1246   if (ThenStmt.isInvalid())
1247     ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
1248   if (ElseStmt.isInvalid())
1249     ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
1250
1251   return Actions.ActOnIfStmt(IfLoc, IsConstexpr, InitStmt.get(), Cond,
1252                              ThenStmt.get(), ElseLoc, ElseStmt.get());
1253 }
1254
1255 /// ParseSwitchStatement
1256 ///       switch-statement:
1257 ///         'switch' '(' expression ')' statement
1258 /// [C++]   'switch' '(' condition ')' statement
1259 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
1260   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
1261   SourceLocation SwitchLoc = ConsumeToken();  // eat the 'switch'.
1262
1263   if (Tok.isNot(tok::l_paren)) {
1264     Diag(Tok, diag::err_expected_lparen_after) << "switch";
1265     SkipUntil(tok::semi);
1266     return StmtError();
1267   }
1268
1269   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1270
1271   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
1272   // not the case for C90.  Start the switch scope.
1273   //
1274   // C++ 6.4p3:
1275   // A name introduced by a declaration in a condition is in scope from its
1276   // point of declaration until the end of the substatements controlled by the
1277   // condition.
1278   // C++ 3.3.2p4:
1279   // Names declared in the for-init-statement, and in the condition of if,
1280   // while, for, and switch statements are local to the if, while, for, or
1281   // switch statement (including the controlled statement).
1282   //
1283   unsigned ScopeFlags = Scope::SwitchScope;
1284   if (C99orCXX)
1285     ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
1286   ParseScope SwitchScope(this, ScopeFlags);
1287
1288   // Parse the condition.
1289   StmtResult InitStmt;
1290   Sema::ConditionResult Cond;
1291   if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
1292                                 Sema::ConditionKind::Switch))
1293     return StmtError();
1294
1295   StmtResult Switch =
1296       Actions.ActOnStartOfSwitchStmt(SwitchLoc, InitStmt.get(), Cond);
1297
1298   if (Switch.isInvalid()) {
1299     // Skip the switch body.
1300     // FIXME: This is not optimal recovery, but parsing the body is more
1301     // dangerous due to the presence of case and default statements, which
1302     // will have no place to connect back with the switch.
1303     if (Tok.is(tok::l_brace)) {
1304       ConsumeBrace();
1305       SkipUntil(tok::r_brace);
1306     } else
1307       SkipUntil(tok::semi);
1308     return Switch;
1309   }
1310
1311   // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
1312   // there is no compound stmt.  C90 does not have this clause.  We only do this
1313   // if the body isn't a compound statement to avoid push/pop in common cases.
1314   //
1315   // C++ 6.4p1:
1316   // The substatement in a selection-statement (each substatement, in the else
1317   // form of the if statement) implicitly defines a local scope.
1318   //
1319   // See comments in ParseIfStatement for why we create a scope for the
1320   // condition and a new scope for substatement in C++.
1321   //
1322   getCurScope()->AddFlags(Scope::BreakScope);
1323   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1324
1325   // We have incremented the mangling number for the SwitchScope and the
1326   // InnerScope, which is one too many.
1327   if (C99orCXX)
1328     getCurScope()->decrementMSManglingNumber();
1329
1330   // Read the body statement.
1331   StmtResult Body(ParseStatement(TrailingElseLoc));
1332
1333   // Pop the scopes.
1334   InnerScope.Exit();
1335   SwitchScope.Exit();
1336
1337   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
1338 }
1339
1340 /// ParseWhileStatement
1341 ///       while-statement: [C99 6.8.5.1]
1342 ///         'while' '(' expression ')' statement
1343 /// [C++]   'while' '(' condition ')' statement
1344 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
1345   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
1346   SourceLocation WhileLoc = Tok.getLocation();
1347   ConsumeToken();  // eat the 'while'.
1348
1349   if (Tok.isNot(tok::l_paren)) {
1350     Diag(Tok, diag::err_expected_lparen_after) << "while";
1351     SkipUntil(tok::semi);
1352     return StmtError();
1353   }
1354
1355   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1356
1357   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
1358   // the case for C90.  Start the loop scope.
1359   //
1360   // C++ 6.4p3:
1361   // A name introduced by a declaration in a condition is in scope from its
1362   // point of declaration until the end of the substatements controlled by the
1363   // condition.
1364   // C++ 3.3.2p4:
1365   // Names declared in the for-init-statement, and in the condition of if,
1366   // while, for, and switch statements are local to the if, while, for, or
1367   // switch statement (including the controlled statement).
1368   //
1369   unsigned ScopeFlags;
1370   if (C99orCXX)
1371     ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
1372                  Scope::DeclScope  | Scope::ControlScope;
1373   else
1374     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1375   ParseScope WhileScope(this, ScopeFlags);
1376
1377   // Parse the condition.
1378   Sema::ConditionResult Cond;
1379   if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
1380                                 Sema::ConditionKind::Boolean))
1381     return StmtError();
1382
1383   // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
1384   // there is no compound stmt.  C90 does not have this clause.  We only do this
1385   // if the body isn't a compound statement to avoid push/pop in common cases.
1386   //
1387   // C++ 6.5p2:
1388   // The substatement in an iteration-statement implicitly defines a local scope
1389   // which is entered and exited each time through the loop.
1390   //
1391   // See comments in ParseIfStatement for why we create a scope for the
1392   // condition and a new scope for substatement in C++.
1393   //
1394   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1395
1396   // Read the body statement.
1397   StmtResult Body(ParseStatement(TrailingElseLoc));
1398
1399   // Pop the body scope if needed.
1400   InnerScope.Exit();
1401   WhileScope.Exit();
1402
1403   if (Cond.isInvalid() || Body.isInvalid())
1404     return StmtError();
1405
1406   return Actions.ActOnWhileStmt(WhileLoc, Cond, Body.get());
1407 }
1408
1409 /// ParseDoStatement
1410 ///       do-statement: [C99 6.8.5.2]
1411 ///         'do' statement 'while' '(' expression ')' ';'
1412 /// Note: this lets the caller parse the end ';'.
1413 StmtResult Parser::ParseDoStatement() {
1414   assert(Tok.is(tok::kw_do) && "Not a do stmt!");
1415   SourceLocation DoLoc = ConsumeToken();  // eat the 'do'.
1416
1417   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
1418   // the case for C90.  Start the loop scope.
1419   unsigned ScopeFlags;
1420   if (getLangOpts().C99)
1421     ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
1422   else
1423     ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
1424
1425   ParseScope DoScope(this, ScopeFlags);
1426
1427   // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
1428   // there is no compound stmt.  C90 does not have this clause. We only do this
1429   // if the body isn't a compound statement to avoid push/pop in common cases.
1430   //
1431   // C++ 6.5p2:
1432   // The substatement in an iteration-statement implicitly defines a local scope
1433   // which is entered and exited each time through the loop.
1434   //
1435   bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
1436   ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
1437
1438   // Read the body statement.
1439   StmtResult Body(ParseStatement());
1440
1441   // Pop the body scope if needed.
1442   InnerScope.Exit();
1443
1444   if (Tok.isNot(tok::kw_while)) {
1445     if (!Body.isInvalid()) {
1446       Diag(Tok, diag::err_expected_while);
1447       Diag(DoLoc, diag::note_matching) << "'do'";
1448       SkipUntil(tok::semi, StopBeforeMatch);
1449     }
1450     return StmtError();
1451   }
1452   SourceLocation WhileLoc = ConsumeToken();
1453
1454   if (Tok.isNot(tok::l_paren)) {
1455     Diag(Tok, diag::err_expected_lparen_after) << "do/while";
1456     SkipUntil(tok::semi, StopBeforeMatch);
1457     return StmtError();
1458   }
1459
1460   // Parse the parenthesized expression.
1461   BalancedDelimiterTracker T(*this, tok::l_paren);
1462   T.consumeOpen();
1463
1464   // A do-while expression is not a condition, so can't have attributes.
1465   DiagnoseAndSkipCXX11Attributes();
1466
1467   ExprResult Cond = ParseExpression();
1468   // Correct the typos in condition before closing the scope.
1469   if (Cond.isUsable())
1470     Cond = Actions.CorrectDelayedTyposInExpr(Cond);
1471   T.consumeClose();
1472   DoScope.Exit();
1473
1474   if (Cond.isInvalid() || Body.isInvalid())
1475     return StmtError();
1476
1477   return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
1478                              Cond.get(), T.getCloseLocation());
1479 }
1480
1481 bool Parser::isForRangeIdentifier() {
1482   assert(Tok.is(tok::identifier));
1483
1484   const Token &Next = NextToken();
1485   if (Next.is(tok::colon))
1486     return true;
1487
1488   if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
1489     TentativeParsingAction PA(*this);
1490     ConsumeToken();
1491     SkipCXX11Attributes();
1492     bool Result = Tok.is(tok::colon);
1493     PA.Revert();
1494     return Result;
1495   }
1496
1497   return false;
1498 }
1499
1500 /// ParseForStatement
1501 ///       for-statement: [C99 6.8.5.3]
1502 ///         'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
1503 ///         'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
1504 /// [C++]   'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
1505 /// [C++]       statement
1506 /// [C++0x] 'for'
1507 ///             'co_await'[opt]    [Coroutines]
1508 ///             '(' for-range-declaration ':' for-range-initializer ')'
1509 ///             statement
1510 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
1511 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement
1512 ///
1513 /// [C++] for-init-statement:
1514 /// [C++]   expression-statement
1515 /// [C++]   simple-declaration
1516 ///
1517 /// [C++0x] for-range-declaration:
1518 /// [C++0x]   attribute-specifier-seq[opt] type-specifier-seq declarator
1519 /// [C++0x] for-range-initializer:
1520 /// [C++0x]   expression
1521 /// [C++0x]   braced-init-list            [TODO]
1522 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
1523   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
1524   SourceLocation ForLoc = ConsumeToken();  // eat the 'for'.
1525
1526   SourceLocation CoawaitLoc;
1527   if (Tok.is(tok::kw_co_await))
1528     CoawaitLoc = ConsumeToken();
1529
1530   if (Tok.isNot(tok::l_paren)) {
1531     Diag(Tok, diag::err_expected_lparen_after) << "for";
1532     SkipUntil(tok::semi);
1533     return StmtError();
1534   }
1535
1536   bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
1537     getLangOpts().ObjC1;
1538
1539   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
1540   // the case for C90.  Start the loop scope.
1541   //
1542   // C++ 6.4p3:
1543   // A name introduced by a declaration in a condition is in scope from its
1544   // point of declaration until the end of the substatements controlled by the
1545   // condition.
1546   // C++ 3.3.2p4:
1547   // Names declared in the for-init-statement, and in the condition of if,
1548   // while, for, and switch statements are local to the if, while, for, or
1549   // switch statement (including the controlled statement).
1550   // C++ 6.5.3p1:
1551   // Names declared in the for-init-statement are in the same declarative-region
1552   // as those declared in the condition.
1553   //
1554   unsigned ScopeFlags = 0;
1555   if (C99orCXXorObjC)
1556     ScopeFlags = Scope::DeclScope | Scope::ControlScope;
1557
1558   ParseScope ForScope(this, ScopeFlags);
1559
1560   BalancedDelimiterTracker T(*this, tok::l_paren);
1561   T.consumeOpen();
1562
1563   ExprResult Value;
1564
1565   bool ForEach = false, ForRange = false;
1566   StmtResult FirstPart;
1567   Sema::ConditionResult SecondPart;
1568   ExprResult Collection;
1569   ForRangeInit ForRangeInit;
1570   FullExprArg ThirdPart(Actions);
1571
1572   if (Tok.is(tok::code_completion)) {
1573     Actions.CodeCompleteOrdinaryName(getCurScope(),
1574                                      C99orCXXorObjC? Sema::PCC_ForInit
1575                                                    : Sema::PCC_Expression);
1576     cutOffParsing();
1577     return StmtError();
1578   }
1579
1580   ParsedAttributesWithRange attrs(AttrFactory);
1581   MaybeParseCXX11Attributes(attrs);
1582
1583   // Parse the first part of the for specifier.
1584   if (Tok.is(tok::semi)) {  // for (;
1585     ProhibitAttributes(attrs);
1586     // no first part, eat the ';'.
1587     ConsumeToken();
1588   } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
1589              isForRangeIdentifier()) {
1590     ProhibitAttributes(attrs);
1591     IdentifierInfo *Name = Tok.getIdentifierInfo();
1592     SourceLocation Loc = ConsumeToken();
1593     MaybeParseCXX11Attributes(attrs);
1594
1595     ForRangeInit.ColonLoc = ConsumeToken();
1596     if (Tok.is(tok::l_brace))
1597       ForRangeInit.RangeExpr = ParseBraceInitializer();
1598     else
1599       ForRangeInit.RangeExpr = ParseExpression();
1600
1601     Diag(Loc, diag::err_for_range_identifier)
1602       << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
1603               ? FixItHint::CreateInsertion(Loc, "auto &&")
1604               : FixItHint());
1605
1606     FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name,
1607                                                    attrs, attrs.Range.getEnd());
1608     ForRange = true;
1609   } else if (isForInitDeclaration()) {  // for (int X = 4;
1610     ParenBraceBracketBalancer BalancerRAIIObj(*this);
1611
1612     // Parse declaration, which eats the ';'.
1613     if (!C99orCXXorObjC) {   // Use of C99-style for loops in C90 mode?
1614       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
1615       Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
1616     }
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         DeclaratorContext::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                      ParsedAttr::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.Context, 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.Context, 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(
2084       /*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
2085                                 Scope::CompoundStmtScope |
2086                                 (FnTry ? Scope::FnTryCatchScope : 0)));
2087   if (TryBlock.isInvalid())
2088     return TryBlock;
2089
2090   // Borland allows SEH-handlers with 'try'
2091
2092   if ((Tok.is(tok::identifier) &&
2093        Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
2094       Tok.is(tok::kw___finally)) {
2095     // TODO: Factor into common return ParseSEHHandlerCommon(...)
2096     StmtResult Handler;
2097     if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
2098       SourceLocation Loc = ConsumeToken();
2099       Handler = ParseSEHExceptBlock(Loc);
2100     }
2101     else {
2102       SourceLocation Loc = ConsumeToken();
2103       Handler = ParseSEHFinallyBlock(Loc);
2104     }
2105     if(Handler.isInvalid())
2106       return Handler;
2107
2108     return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
2109                                     TryLoc,
2110                                     TryBlock.get(),
2111                                     Handler.get());
2112   }
2113   else {
2114     StmtVector Handlers;
2115
2116     // C++11 attributes can't appear here, despite this context seeming
2117     // statement-like.
2118     DiagnoseAndSkipCXX11Attributes();
2119
2120     if (Tok.isNot(tok::kw_catch))
2121       return StmtError(Diag(Tok, diag::err_expected_catch));
2122     while (Tok.is(tok::kw_catch)) {
2123       StmtResult Handler(ParseCXXCatchBlock(FnTry));
2124       if (!Handler.isInvalid())
2125         Handlers.push_back(Handler.get());
2126     }
2127     // Don't bother creating the full statement if we don't have any usable
2128     // handlers.
2129     if (Handlers.empty())
2130       return StmtError();
2131
2132     return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
2133   }
2134 }
2135
2136 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
2137 ///
2138 ///   handler:
2139 ///     'catch' '(' exception-declaration ')' compound-statement
2140 ///
2141 ///   exception-declaration:
2142 ///     attribute-specifier-seq[opt] type-specifier-seq declarator
2143 ///     attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
2144 ///     '...'
2145 ///
2146 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
2147   assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
2148
2149   SourceLocation CatchLoc = ConsumeToken();
2150
2151   BalancedDelimiterTracker T(*this, tok::l_paren);
2152   if (T.expectAndConsume())
2153     return StmtError();
2154
2155   // C++ 3.3.2p3:
2156   // The name in a catch exception-declaration is local to the handler and
2157   // shall not be redeclared in the outermost block of the handler.
2158   ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
2159                           (FnCatch ? Scope::FnTryCatchScope : 0));
2160
2161   // exception-declaration is equivalent to '...' or a parameter-declaration
2162   // without default arguments.
2163   Decl *ExceptionDecl = nullptr;
2164   if (Tok.isNot(tok::ellipsis)) {
2165     ParsedAttributesWithRange Attributes(AttrFactory);
2166     MaybeParseCXX11Attributes(Attributes);
2167
2168     DeclSpec DS(AttrFactory);
2169     DS.takeAttributesFrom(Attributes);
2170
2171     if (ParseCXXTypeSpecifierSeq(DS))
2172       return StmtError();
2173
2174     Declarator ExDecl(DS, DeclaratorContext::CXXCatchContext);
2175     ParseDeclarator(ExDecl);
2176     ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
2177   } else
2178     ConsumeToken();
2179
2180   T.consumeClose();
2181   if (T.getCloseLocation().isInvalid())
2182     return StmtError();
2183
2184   if (Tok.isNot(tok::l_brace))
2185     return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
2186
2187   // FIXME: Possible draft standard bug: attribute-specifier should be allowed?
2188   StmtResult Block(ParseCompoundStatement());
2189   if (Block.isInvalid())
2190     return Block;
2191
2192   return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
2193 }
2194
2195 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
2196   IfExistsCondition Result;
2197   if (ParseMicrosoftIfExistsCondition(Result))
2198     return;
2199
2200   // Handle dependent statements by parsing the braces as a compound statement.
2201   // This is not the same behavior as Visual C++, which don't treat this as a
2202   // compound statement, but for Clang's type checking we can't have anything
2203   // inside these braces escaping to the surrounding code.
2204   if (Result.Behavior == IEB_Dependent) {
2205     if (!Tok.is(tok::l_brace)) {
2206       Diag(Tok, diag::err_expected) << tok::l_brace;
2207       return;
2208     }
2209
2210     StmtResult Compound = ParseCompoundStatement();
2211     if (Compound.isInvalid())
2212       return;
2213
2214     StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
2215                                                               Result.IsIfExists,
2216                                                               Result.SS,
2217                                                               Result.Name,
2218                                                               Compound.get());
2219     if (DepResult.isUsable())
2220       Stmts.push_back(DepResult.get());
2221     return;
2222   }
2223
2224   BalancedDelimiterTracker Braces(*this, tok::l_brace);
2225   if (Braces.consumeOpen()) {
2226     Diag(Tok, diag::err_expected) << tok::l_brace;
2227     return;
2228   }
2229
2230   switch (Result.Behavior) {
2231   case IEB_Parse:
2232     // Parse the statements below.
2233     break;
2234
2235   case IEB_Dependent:
2236     llvm_unreachable("Dependent case handled above");
2237
2238   case IEB_Skip:
2239     Braces.skipToEnd();
2240     return;
2241   }
2242
2243   // Condition is true, parse the statements.
2244   while (Tok.isNot(tok::r_brace)) {
2245     StmtResult R = ParseStatementOrDeclaration(Stmts, ACK_Any);
2246     if (R.isUsable())
2247       Stmts.push_back(R.get());
2248   }
2249   Braces.consumeClose();
2250 }
2251
2252 bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
2253   MaybeParseGNUAttributes(Attrs);
2254
2255   if (Attrs.empty())
2256     return true;
2257
2258   if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
2259     return true;
2260
2261   if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
2262     Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
2263     return false;
2264   }
2265   return true;
2266 }