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