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/AST/ASTContext.h" 18 #include "clang/Basic/Diagnostic.h" 19 #include "clang/Basic/PrettyStackTrace.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Basic/TargetInfo.h" 22 #include "clang/Sema/DeclSpec.h" 23 #include "clang/Sema/PrettyDeclStackTrace.h" 24 #include "clang/Sema/Scope.h" 25 #include "clang/Sema/TypoCorrection.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCContext.h" 28 #include "llvm/MC/MCObjectFileInfo.h" 29 #include "llvm/MC/MCParser/MCAsmParser.h" 30 #include "llvm/MC/MCRegisterInfo.h" 31 #include "llvm/MC/MCStreamer.h" 32 #include "llvm/MC/MCSubtargetInfo.h" 33 #include "llvm/MC/MCTargetAsmParser.h" 34 #include "llvm/Support/SourceMgr.h" 35 #include "llvm/Support/TargetRegistry.h" 36 #include "llvm/Support/TargetSelect.h" 37 #include "llvm/ADT/SmallString.h" 38 using namespace clang; 39 40 //===----------------------------------------------------------------------===// 41 // C99 6.8: Statements and Blocks. 42 //===----------------------------------------------------------------------===// 43 44 /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'. 45 /// StatementOrDeclaration: 46 /// statement 47 /// declaration 48 /// 49 /// statement: 50 /// labeled-statement 51 /// compound-statement 52 /// expression-statement 53 /// selection-statement 54 /// iteration-statement 55 /// jump-statement 56 /// [C++] declaration-statement 57 /// [C++] try-block 58 /// [MS] seh-try-block 59 /// [OBC] objc-throw-statement 60 /// [OBC] objc-try-catch-statement 61 /// [OBC] objc-synchronized-statement 62 /// [GNU] asm-statement 63 /// [OMP] openmp-construct [TODO] 64 /// 65 /// labeled-statement: 66 /// identifier ':' statement 67 /// 'case' constant-expression ':' statement 68 /// 'default' ':' statement 69 /// 70 /// selection-statement: 71 /// if-statement 72 /// switch-statement 73 /// 74 /// iteration-statement: 75 /// while-statement 76 /// do-statement 77 /// for-statement 78 /// 79 /// expression-statement: 80 /// expression[opt] ';' 81 /// 82 /// jump-statement: 83 /// 'goto' identifier ';' 84 /// 'continue' ';' 85 /// 'break' ';' 86 /// 'return' expression[opt] ';' 87 /// [GNU] 'goto' '*' expression ';' 88 /// 89 /// [OBC] objc-throw-statement: 90 /// [OBC] '@' 'throw' expression ';' 91 /// [OBC] '@' 'throw' ';' 92 /// 93 StmtResult 94 Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement, 95 SourceLocation *TrailingElseLoc) { 96 97 ParenBraceBracketBalancer BalancerRAIIObj(*this); 98 99 ParsedAttributesWithRange Attrs(AttrFactory); 100 MaybeParseCXX11Attributes(Attrs, 0, /*MightBeObjCMessageSend*/ true); 101 102 StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts, 103 OnlyStatement, TrailingElseLoc, Attrs); 104 105 assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) && 106 "attributes on empty statement"); 107 108 if (Attrs.empty() || Res.isInvalid()) 109 return Res; 110 111 return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range); 112 } 113 114 StmtResult 115 Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts, 116 bool OnlyStatement, SourceLocation *TrailingElseLoc, 117 ParsedAttributesWithRange &Attrs) { 118 const char *SemiError = 0; 119 StmtResult Res; 120 121 // Cases in this switch statement should fall through if the parser expects 122 // the token to end in a semicolon (in which case SemiError should be set), 123 // or they directly 'return;' if not. 124 Retry: 125 tok::TokenKind Kind = Tok.getKind(); 126 SourceLocation AtLoc; 127 switch (Kind) { 128 case tok::at: // May be a @try or @throw statement 129 { 130 ProhibitAttributes(Attrs); // TODO: is it correct? 131 AtLoc = ConsumeToken(); // consume @ 132 return ParseObjCAtStatement(AtLoc); 133 } 134 135 case tok::code_completion: 136 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement); 137 cutOffParsing(); 138 return StmtError(); 139 140 case tok::identifier: { 141 Token Next = NextToken(); 142 if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement 143 // identifier ':' statement 144 return ParseLabeledStatement(Attrs); 145 } 146 147 // Look up the identifier, and typo-correct it to a keyword if it's not 148 // found. 149 if (Next.isNot(tok::coloncolon)) { 150 // Try to limit which sets of keywords should be included in typo 151 // correction based on what the next token is. 152 // FIXME: Pass the next token into the CorrectionCandidateCallback and 153 // do this filtering in a more fine-grained manner. 154 CorrectionCandidateCallback DefaultValidator; 155 DefaultValidator.WantTypeSpecifiers = 156 Next.is(tok::l_paren) || Next.is(tok::less) || 157 Next.is(tok::identifier) || Next.is(tok::star) || 158 Next.is(tok::amp) || Next.is(tok::l_square); 159 DefaultValidator.WantExpressionKeywords = 160 Next.is(tok::l_paren) || Next.is(tok::identifier) || 161 Next.is(tok::arrow) || Next.is(tok::period); 162 DefaultValidator.WantRemainingKeywords = 163 Next.is(tok::l_paren) || Next.is(tok::semi) || 164 Next.is(tok::identifier) || Next.is(tok::l_brace); 165 DefaultValidator.WantCXXNamedCasts = false; 166 if (TryAnnotateName(/*IsAddressOfOperand*/false, &DefaultValidator) 167 == ANK_Error) { 168 // Handle errors here by skipping up to the next semicolon or '}', and 169 // eat the semicolon if that's what stopped us. 170 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true); 171 if (Tok.is(tok::semi)) 172 ConsumeToken(); 173 return StmtError(); 174 } 175 176 // If the identifier was typo-corrected, try again. 177 if (Tok.isNot(tok::identifier)) 178 goto Retry; 179 } 180 181 // Fall through 182 } 183 184 default: { 185 if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) { 186 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 187 DeclGroupPtrTy Decl = ParseDeclaration(Stmts, Declarator::BlockContext, 188 DeclEnd, Attrs); 189 return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd); 190 } 191 192 if (Tok.is(tok::r_brace)) { 193 Diag(Tok, diag::err_expected_statement); 194 return StmtError(); 195 } 196 197 return ParseExprStatement(); 198 } 199 200 case tok::kw_case: // C99 6.8.1: labeled-statement 201 return ParseCaseStatement(); 202 case tok::kw_default: // C99 6.8.1: labeled-statement 203 return ParseDefaultStatement(); 204 205 case tok::l_brace: // C99 6.8.2: compound-statement 206 return ParseCompoundStatement(); 207 case tok::semi: { // C99 6.8.3p3: expression[opt] ';' 208 bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro(); 209 return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro); 210 } 211 212 case tok::kw_if: // C99 6.8.4.1: if-statement 213 return ParseIfStatement(TrailingElseLoc); 214 case tok::kw_switch: // C99 6.8.4.2: switch-statement 215 return ParseSwitchStatement(TrailingElseLoc); 216 217 case tok::kw_while: // C99 6.8.5.1: while-statement 218 return ParseWhileStatement(TrailingElseLoc); 219 case tok::kw_do: // C99 6.8.5.2: do-statement 220 Res = ParseDoStatement(); 221 SemiError = "do/while"; 222 break; 223 case tok::kw_for: // C99 6.8.5.3: for-statement 224 return ParseForStatement(TrailingElseLoc); 225 226 case tok::kw_goto: // C99 6.8.6.1: goto-statement 227 Res = ParseGotoStatement(); 228 SemiError = "goto"; 229 break; 230 case tok::kw_continue: // C99 6.8.6.2: continue-statement 231 Res = ParseContinueStatement(); 232 SemiError = "continue"; 233 break; 234 case tok::kw_break: // C99 6.8.6.3: break-statement 235 Res = ParseBreakStatement(); 236 SemiError = "break"; 237 break; 238 case tok::kw_return: // C99 6.8.6.4: return-statement 239 Res = ParseReturnStatement(); 240 SemiError = "return"; 241 break; 242 243 case tok::kw_asm: { 244 ProhibitAttributes(Attrs); 245 bool msAsm = false; 246 Res = ParseAsmStatement(msAsm); 247 Res = Actions.ActOnFinishFullStmt(Res.get()); 248 if (msAsm) return Res; 249 SemiError = "asm"; 250 break; 251 } 252 253 case tok::kw_try: // C++ 15: try-block 254 return ParseCXXTryBlock(); 255 256 case tok::kw___try: 257 ProhibitAttributes(Attrs); // TODO: is it correct? 258 return ParseSEHTryBlock(); 259 260 case tok::annot_pragma_vis: 261 ProhibitAttributes(Attrs); 262 HandlePragmaVisibility(); 263 return StmtEmpty(); 264 265 case tok::annot_pragma_pack: 266 ProhibitAttributes(Attrs); 267 HandlePragmaPack(); 268 return StmtEmpty(); 269 270 case tok::annot_pragma_msstruct: 271 ProhibitAttributes(Attrs); 272 HandlePragmaMSStruct(); 273 return StmtEmpty(); 274 275 case tok::annot_pragma_align: 276 ProhibitAttributes(Attrs); 277 HandlePragmaAlign(); 278 return StmtEmpty(); 279 280 case tok::annot_pragma_weak: 281 ProhibitAttributes(Attrs); 282 HandlePragmaWeak(); 283 return StmtEmpty(); 284 285 case tok::annot_pragma_weakalias: 286 ProhibitAttributes(Attrs); 287 HandlePragmaWeakAlias(); 288 return StmtEmpty(); 289 290 case tok::annot_pragma_redefine_extname: 291 ProhibitAttributes(Attrs); 292 HandlePragmaRedefineExtname(); 293 return StmtEmpty(); 294 295 case tok::annot_pragma_fp_contract: 296 Diag(Tok, diag::err_pragma_fp_contract_scope); 297 ConsumeToken(); 298 return StmtError(); 299 300 case tok::annot_pragma_opencl_extension: 301 ProhibitAttributes(Attrs); 302 HandlePragmaOpenCLExtension(); 303 return StmtEmpty(); 304 305 case tok::annot_pragma_captured: 306 return HandlePragmaCaptured(); 307 308 case tok::annot_pragma_openmp: 309 return ParseOpenMPDeclarativeOrExecutableDirective(); 310 311 } 312 313 // If we reached this code, the statement must end in a semicolon. 314 if (Tok.is(tok::semi)) { 315 ConsumeToken(); 316 } else if (!Res.isInvalid()) { 317 // If the result was valid, then we do want to diagnose this. Use 318 // ExpectAndConsume to emit the diagnostic, even though we know it won't 319 // succeed. 320 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError); 321 // Skip until we see a } or ;, but don't eat it. 322 SkipUntil(tok::r_brace, true, true); 323 } 324 325 return Res; 326 } 327 328 /// \brief Parse an expression statement. 329 StmtResult Parser::ParseExprStatement() { 330 // If a case keyword is missing, this is where it should be inserted. 331 Token OldToken = Tok; 332 333 // expression[opt] ';' 334 ExprResult Expr(ParseExpression()); 335 if (Expr.isInvalid()) { 336 // If the expression is invalid, skip ahead to the next semicolon or '}'. 337 // Not doing this opens us up to the possibility of infinite loops if 338 // ParseExpression does not consume any tokens. 339 SkipUntil(tok::r_brace, /*StopAtSemi=*/true, /*DontConsume=*/true); 340 if (Tok.is(tok::semi)) 341 ConsumeToken(); 342 return Actions.ActOnExprStmtError(); 343 } 344 345 if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() && 346 Actions.CheckCaseExpression(Expr.get())) { 347 // If a constant expression is followed by a colon inside a switch block, 348 // suggest a missing case keyword. 349 Diag(OldToken, diag::err_expected_case_before_expression) 350 << FixItHint::CreateInsertion(OldToken.getLocation(), "case "); 351 352 // Recover parsing as a case statement. 353 return ParseCaseStatement(/*MissingCase=*/true, Expr); 354 } 355 356 // Otherwise, eat the semicolon. 357 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 358 return Actions.ActOnExprStmt(Expr); 359 } 360 361 StmtResult Parser::ParseSEHTryBlock() { 362 assert(Tok.is(tok::kw___try) && "Expected '__try'"); 363 SourceLocation Loc = ConsumeToken(); 364 return ParseSEHTryBlockCommon(Loc); 365 } 366 367 /// ParseSEHTryBlockCommon 368 /// 369 /// seh-try-block: 370 /// '__try' compound-statement seh-handler 371 /// 372 /// seh-handler: 373 /// seh-except-block 374 /// seh-finally-block 375 /// 376 StmtResult Parser::ParseSEHTryBlockCommon(SourceLocation TryLoc) { 377 if(Tok.isNot(tok::l_brace)) 378 return StmtError(Diag(Tok,diag::err_expected_lbrace)); 379 380 StmtResult TryBlock(ParseCompoundStatement()); 381 if(TryBlock.isInvalid()) 382 return TryBlock; 383 384 StmtResult Handler; 385 if (Tok.is(tok::identifier) && 386 Tok.getIdentifierInfo() == getSEHExceptKeyword()) { 387 SourceLocation Loc = ConsumeToken(); 388 Handler = ParseSEHExceptBlock(Loc); 389 } else if (Tok.is(tok::kw___finally)) { 390 SourceLocation Loc = ConsumeToken(); 391 Handler = ParseSEHFinallyBlock(Loc); 392 } else { 393 return StmtError(Diag(Tok,diag::err_seh_expected_handler)); 394 } 395 396 if(Handler.isInvalid()) 397 return Handler; 398 399 return Actions.ActOnSEHTryBlock(false /* IsCXXTry */, 400 TryLoc, 401 TryBlock.take(), 402 Handler.take()); 403 } 404 405 /// ParseSEHExceptBlock - Handle __except 406 /// 407 /// seh-except-block: 408 /// '__except' '(' seh-filter-expression ')' compound-statement 409 /// 410 StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) { 411 PoisonIdentifierRAIIObject raii(Ident__exception_code, false), 412 raii2(Ident___exception_code, false), 413 raii3(Ident_GetExceptionCode, false); 414 415 if(ExpectAndConsume(tok::l_paren,diag::err_expected_lparen)) 416 return StmtError(); 417 418 ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope); 419 420 if (getLangOpts().Borland) { 421 Ident__exception_info->setIsPoisoned(false); 422 Ident___exception_info->setIsPoisoned(false); 423 Ident_GetExceptionInfo->setIsPoisoned(false); 424 } 425 ExprResult FilterExpr(ParseExpression()); 426 427 if (getLangOpts().Borland) { 428 Ident__exception_info->setIsPoisoned(true); 429 Ident___exception_info->setIsPoisoned(true); 430 Ident_GetExceptionInfo->setIsPoisoned(true); 431 } 432 433 if(FilterExpr.isInvalid()) 434 return StmtError(); 435 436 if(ExpectAndConsume(tok::r_paren,diag::err_expected_rparen)) 437 return StmtError(); 438 439 StmtResult Block(ParseCompoundStatement()); 440 441 if(Block.isInvalid()) 442 return Block; 443 444 return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.take(), Block.take()); 445 } 446 447 /// ParseSEHFinallyBlock - Handle __finally 448 /// 449 /// seh-finally-block: 450 /// '__finally' compound-statement 451 /// 452 StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyBlock) { 453 PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false), 454 raii2(Ident___abnormal_termination, false), 455 raii3(Ident_AbnormalTermination, false); 456 457 StmtResult Block(ParseCompoundStatement()); 458 if(Block.isInvalid()) 459 return Block; 460 461 return Actions.ActOnSEHFinallyBlock(FinallyBlock,Block.take()); 462 } 463 464 /// ParseLabeledStatement - We have an identifier and a ':' after it. 465 /// 466 /// labeled-statement: 467 /// identifier ':' statement 468 /// [GNU] identifier ':' attributes[opt] statement 469 /// 470 StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) { 471 assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() && 472 "Not an identifier!"); 473 474 Token IdentTok = Tok; // Save the whole token. 475 ConsumeToken(); // eat the identifier. 476 477 assert(Tok.is(tok::colon) && "Not a label!"); 478 479 // identifier ':' statement 480 SourceLocation ColonLoc = ConsumeToken(); 481 482 // Read label attributes, if present. attrs will contain both C++11 and GNU 483 // attributes (if present) after this point. 484 MaybeParseGNUAttributes(attrs); 485 486 StmtResult SubStmt(ParseStatement()); 487 488 // Broken substmt shouldn't prevent the label from being added to the AST. 489 if (SubStmt.isInvalid()) 490 SubStmt = Actions.ActOnNullStmt(ColonLoc); 491 492 LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(), 493 IdentTok.getLocation()); 494 if (AttributeList *Attrs = attrs.getList()) { 495 Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs); 496 attrs.clear(); 497 } 498 499 return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc, 500 SubStmt.get()); 501 } 502 503 /// ParseCaseStatement 504 /// labeled-statement: 505 /// 'case' constant-expression ':' statement 506 /// [GNU] 'case' constant-expression '...' constant-expression ':' statement 507 /// 508 StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) { 509 assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!"); 510 511 // It is very very common for code to contain many case statements recursively 512 // nested, as in (but usually without indentation): 513 // case 1: 514 // case 2: 515 // case 3: 516 // case 4: 517 // case 5: etc. 518 // 519 // Parsing this naively works, but is both inefficient and can cause us to run 520 // out of stack space in our recursive descent parser. As a special case, 521 // flatten this recursion into an iterative loop. This is complex and gross, 522 // but all the grossness is constrained to ParseCaseStatement (and some 523 // wierdness in the actions), so this is just local grossness :). 524 525 // TopLevelCase - This is the highest level we have parsed. 'case 1' in the 526 // example above. 527 StmtResult TopLevelCase(true); 528 529 // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which 530 // gets updated each time a new case is parsed, and whose body is unset so 531 // far. When parsing 'case 4', this is the 'case 3' node. 532 Stmt *DeepestParsedCaseStmt = 0; 533 534 // While we have case statements, eat and stack them. 535 SourceLocation ColonLoc; 536 do { 537 SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() : 538 ConsumeToken(); // eat the 'case'. 539 540 if (Tok.is(tok::code_completion)) { 541 Actions.CodeCompleteCase(getCurScope()); 542 cutOffParsing(); 543 return StmtError(); 544 } 545 546 /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'. 547 /// Disable this form of error recovery while we're parsing the case 548 /// expression. 549 ColonProtectionRAIIObject ColonProtection(*this); 550 551 ExprResult LHS(MissingCase ? Expr : ParseConstantExpression()); 552 MissingCase = false; 553 if (LHS.isInvalid()) { 554 SkipUntil(tok::colon); 555 return StmtError(); 556 } 557 558 // GNU case range extension. 559 SourceLocation DotDotDotLoc; 560 ExprResult RHS; 561 if (Tok.is(tok::ellipsis)) { 562 Diag(Tok, diag::ext_gnu_case_range); 563 DotDotDotLoc = ConsumeToken(); 564 565 RHS = ParseConstantExpression(); 566 if (RHS.isInvalid()) { 567 SkipUntil(tok::colon); 568 return StmtError(); 569 } 570 } 571 572 ColonProtection.restore(); 573 574 if (Tok.is(tok::colon)) { 575 ColonLoc = ConsumeToken(); 576 577 // Treat "case blah;" as a typo for "case blah:". 578 } else if (Tok.is(tok::semi)) { 579 ColonLoc = ConsumeToken(); 580 Diag(ColonLoc, diag::err_expected_colon_after) << "'case'" 581 << FixItHint::CreateReplacement(ColonLoc, ":"); 582 } else { 583 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation); 584 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'case'" 585 << FixItHint::CreateInsertion(ExpectedLoc, ":"); 586 ColonLoc = ExpectedLoc; 587 } 588 589 StmtResult Case = 590 Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc, 591 RHS.get(), ColonLoc); 592 593 // If we had a sema error parsing this case, then just ignore it and 594 // continue parsing the sub-stmt. 595 if (Case.isInvalid()) { 596 if (TopLevelCase.isInvalid()) // No parsed case stmts. 597 return ParseStatement(); 598 // Otherwise, just don't add it as a nested case. 599 } else { 600 // If this is the first case statement we parsed, it becomes TopLevelCase. 601 // Otherwise we link it into the current chain. 602 Stmt *NextDeepest = Case.get(); 603 if (TopLevelCase.isInvalid()) 604 TopLevelCase = Case; 605 else 606 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get()); 607 DeepestParsedCaseStmt = NextDeepest; 608 } 609 610 // Handle all case statements. 611 } while (Tok.is(tok::kw_case)); 612 613 assert(!TopLevelCase.isInvalid() && "Should have parsed at least one case!"); 614 615 // If we found a non-case statement, start by parsing it. 616 StmtResult SubStmt; 617 618 if (Tok.isNot(tok::r_brace)) { 619 SubStmt = ParseStatement(); 620 } else { 621 // Nicely diagnose the common error "switch (X) { case 4: }", which is 622 // not valid. 623 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc); 624 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement) 625 << FixItHint::CreateInsertion(AfterColonLoc, " ;"); 626 SubStmt = true; 627 } 628 629 // Broken sub-stmt shouldn't prevent forming the case statement properly. 630 if (SubStmt.isInvalid()) 631 SubStmt = Actions.ActOnNullStmt(SourceLocation()); 632 633 // Install the body into the most deeply-nested case. 634 Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get()); 635 636 // Return the top level parsed statement tree. 637 return TopLevelCase; 638 } 639 640 /// ParseDefaultStatement 641 /// labeled-statement: 642 /// 'default' ':' statement 643 /// Note that this does not parse the 'statement' at the end. 644 /// 645 StmtResult Parser::ParseDefaultStatement() { 646 assert(Tok.is(tok::kw_default) && "Not a default stmt!"); 647 SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'. 648 649 SourceLocation ColonLoc; 650 if (Tok.is(tok::colon)) { 651 ColonLoc = ConsumeToken(); 652 653 // Treat "default;" as a typo for "default:". 654 } else if (Tok.is(tok::semi)) { 655 ColonLoc = ConsumeToken(); 656 Diag(ColonLoc, diag::err_expected_colon_after) << "'default'" 657 << FixItHint::CreateReplacement(ColonLoc, ":"); 658 } else { 659 SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation); 660 Diag(ExpectedLoc, diag::err_expected_colon_after) << "'default'" 661 << FixItHint::CreateInsertion(ExpectedLoc, ":"); 662 ColonLoc = ExpectedLoc; 663 } 664 665 StmtResult SubStmt; 666 667 if (Tok.isNot(tok::r_brace)) { 668 SubStmt = ParseStatement(); 669 } else { 670 // Diagnose the common error "switch (X) {... default: }", which is 671 // not valid. 672 SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc); 673 Diag(AfterColonLoc, diag::err_label_end_of_compound_statement) 674 << FixItHint::CreateInsertion(AfterColonLoc, " ;"); 675 SubStmt = true; 676 } 677 678 // Broken sub-stmt shouldn't prevent forming the case statement properly. 679 if (SubStmt.isInvalid()) 680 SubStmt = Actions.ActOnNullStmt(ColonLoc); 681 682 return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc, 683 SubStmt.get(), getCurScope()); 684 } 685 686 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) { 687 return ParseCompoundStatement(isStmtExpr, Scope::DeclScope); 688 } 689 690 /// ParseCompoundStatement - Parse a "{}" block. 691 /// 692 /// compound-statement: [C99 6.8.2] 693 /// { block-item-list[opt] } 694 /// [GNU] { label-declarations block-item-list } [TODO] 695 /// 696 /// block-item-list: 697 /// block-item 698 /// block-item-list block-item 699 /// 700 /// block-item: 701 /// declaration 702 /// [GNU] '__extension__' declaration 703 /// statement 704 /// [OMP] openmp-directive [TODO] 705 /// 706 /// [GNU] label-declarations: 707 /// [GNU] label-declaration 708 /// [GNU] label-declarations label-declaration 709 /// 710 /// [GNU] label-declaration: 711 /// [GNU] '__label__' identifier-list ';' 712 /// 713 /// [OMP] openmp-directive: [TODO] 714 /// [OMP] barrier-directive 715 /// [OMP] flush-directive 716 /// 717 StmtResult Parser::ParseCompoundStatement(bool isStmtExpr, 718 unsigned ScopeFlags) { 719 assert(Tok.is(tok::l_brace) && "Not a compount stmt!"); 720 721 // Enter a scope to hold everything within the compound stmt. Compound 722 // statements can always hold declarations. 723 ParseScope CompoundScope(this, ScopeFlags); 724 725 // Parse the statements in the body. 726 return ParseCompoundStatementBody(isStmtExpr); 727 } 728 729 /// Parse any pragmas at the start of the compound expression. We handle these 730 /// separately since some pragmas (FP_CONTRACT) must appear before any C 731 /// statement in the compound, but may be intermingled with other pragmas. 732 void Parser::ParseCompoundStatementLeadingPragmas() { 733 bool checkForPragmas = true; 734 while (checkForPragmas) { 735 switch (Tok.getKind()) { 736 case tok::annot_pragma_vis: 737 HandlePragmaVisibility(); 738 break; 739 case tok::annot_pragma_pack: 740 HandlePragmaPack(); 741 break; 742 case tok::annot_pragma_msstruct: 743 HandlePragmaMSStruct(); 744 break; 745 case tok::annot_pragma_align: 746 HandlePragmaAlign(); 747 break; 748 case tok::annot_pragma_weak: 749 HandlePragmaWeak(); 750 break; 751 case tok::annot_pragma_weakalias: 752 HandlePragmaWeakAlias(); 753 break; 754 case tok::annot_pragma_redefine_extname: 755 HandlePragmaRedefineExtname(); 756 break; 757 case tok::annot_pragma_opencl_extension: 758 HandlePragmaOpenCLExtension(); 759 break; 760 case tok::annot_pragma_fp_contract: 761 HandlePragmaFPContract(); 762 break; 763 default: 764 checkForPragmas = false; 765 break; 766 } 767 } 768 769 } 770 771 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the 772 /// ActOnCompoundStmt action. This expects the '{' to be the current token, and 773 /// consume the '}' at the end of the block. It does not manipulate the scope 774 /// stack. 775 StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) { 776 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), 777 Tok.getLocation(), 778 "in compound statement ('{}')"); 779 780 // Record the state of the FP_CONTRACT pragma, restore on leaving the 781 // compound statement. 782 Sema::FPContractStateRAII SaveFPContractState(Actions); 783 784 InMessageExpressionRAIIObject InMessage(*this, false); 785 BalancedDelimiterTracker T(*this, tok::l_brace); 786 if (T.consumeOpen()) 787 return StmtError(); 788 789 Sema::CompoundScopeRAII CompoundScope(Actions); 790 791 // Parse any pragmas at the beginning of the compound statement. 792 ParseCompoundStatementLeadingPragmas(); 793 794 StmtVector Stmts; 795 796 // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are 797 // only allowed at the start of a compound stmt regardless of the language. 798 while (Tok.is(tok::kw___label__)) { 799 SourceLocation LabelLoc = ConsumeToken(); 800 Diag(LabelLoc, diag::ext_gnu_local_label); 801 802 SmallVector<Decl *, 8> DeclsInGroup; 803 while (1) { 804 if (Tok.isNot(tok::identifier)) { 805 Diag(Tok, diag::err_expected_ident); 806 break; 807 } 808 809 IdentifierInfo *II = Tok.getIdentifierInfo(); 810 SourceLocation IdLoc = ConsumeToken(); 811 DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc)); 812 813 if (!Tok.is(tok::comma)) 814 break; 815 ConsumeToken(); 816 } 817 818 DeclSpec DS(AttrFactory); 819 DeclGroupPtrTy Res = 820 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); 821 StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation()); 822 823 ExpectAndConsumeSemi(diag::err_expected_semi_declaration); 824 if (R.isUsable()) 825 Stmts.push_back(R.release()); 826 } 827 828 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 829 if (Tok.is(tok::annot_pragma_unused)) { 830 HandlePragmaUnused(); 831 continue; 832 } 833 834 if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || 835 Tok.is(tok::kw___if_not_exists))) { 836 ParseMicrosoftIfExistsStatement(Stmts); 837 continue; 838 } 839 840 StmtResult R; 841 if (Tok.isNot(tok::kw___extension__)) { 842 R = ParseStatementOrDeclaration(Stmts, false); 843 } else { 844 // __extension__ can start declarations and it can also be a unary 845 // operator for expressions. Consume multiple __extension__ markers here 846 // until we can determine which is which. 847 // FIXME: This loses extension expressions in the AST! 848 SourceLocation ExtLoc = ConsumeToken(); 849 while (Tok.is(tok::kw___extension__)) 850 ConsumeToken(); 851 852 ParsedAttributesWithRange attrs(AttrFactory); 853 MaybeParseCXX11Attributes(attrs, 0, /*MightBeObjCMessageSend*/ true); 854 855 // If this is the start of a declaration, parse it as such. 856 if (isDeclarationStatement()) { 857 // __extension__ silences extension warnings in the subdeclaration. 858 // FIXME: Save the __extension__ on the decl as a node somehow? 859 ExtensionRAIIObject O(Diags); 860 861 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 862 DeclGroupPtrTy Res = ParseDeclaration(Stmts, 863 Declarator::BlockContext, DeclEnd, 864 attrs); 865 R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd); 866 } else { 867 // Otherwise this was a unary __extension__ marker. 868 ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc)); 869 870 if (Res.isInvalid()) { 871 SkipUntil(tok::semi); 872 continue; 873 } 874 875 // FIXME: Use attributes? 876 // Eat the semicolon at the end of stmt and convert the expr into a 877 // statement. 878 ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); 879 R = Actions.ActOnExprStmt(Res); 880 } 881 } 882 883 if (R.isUsable()) 884 Stmts.push_back(R.release()); 885 } 886 887 SourceLocation CloseLoc = Tok.getLocation(); 888 889 // We broke out of the while loop because we found a '}' or EOF. 890 if (!T.consumeClose()) 891 // Recover by creating a compound statement with what we parsed so far, 892 // instead of dropping everything and returning StmtError(); 893 CloseLoc = T.getCloseLocation(); 894 895 return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc, 896 Stmts, isStmtExpr); 897 } 898 899 /// ParseParenExprOrCondition: 900 /// [C ] '(' expression ')' 901 /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true] 902 /// 903 /// This function parses and performs error recovery on the specified condition 904 /// or expression (depending on whether we're in C++ or C mode). This function 905 /// goes out of its way to recover well. It returns true if there was a parser 906 /// error (the right paren couldn't be found), which indicates that the caller 907 /// should try to recover harder. It returns false if the condition is 908 /// successfully parsed. Note that a successful parse can still have semantic 909 /// errors in the condition. 910 bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult, 911 Decl *&DeclResult, 912 SourceLocation Loc, 913 bool ConvertToBoolean) { 914 BalancedDelimiterTracker T(*this, tok::l_paren); 915 T.consumeOpen(); 916 917 if (getLangOpts().CPlusPlus) 918 ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean); 919 else { 920 ExprResult = ParseExpression(); 921 DeclResult = 0; 922 923 // If required, convert to a boolean value. 924 if (!ExprResult.isInvalid() && ConvertToBoolean) 925 ExprResult 926 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get()); 927 } 928 929 // If the parser was confused by the condition and we don't have a ')', try to 930 // recover by skipping ahead to a semi and bailing out. If condexp is 931 // semantically invalid but we have well formed code, keep going. 932 if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) { 933 SkipUntil(tok::semi); 934 // Skipping may have stopped if it found the containing ')'. If so, we can 935 // continue parsing the if statement. 936 if (Tok.isNot(tok::r_paren)) 937 return true; 938 } 939 940 // Otherwise the condition is valid or the rparen is present. 941 T.consumeClose(); 942 943 // Check for extraneous ')'s to catch things like "if (foo())) {". We know 944 // that all callers are looking for a statement after the condition, so ")" 945 // isn't valid. 946 while (Tok.is(tok::r_paren)) { 947 Diag(Tok, diag::err_extraneous_rparen_in_condition) 948 << FixItHint::CreateRemoval(Tok.getLocation()); 949 ConsumeParen(); 950 } 951 952 return false; 953 } 954 955 956 /// ParseIfStatement 957 /// if-statement: [C99 6.8.4.1] 958 /// 'if' '(' expression ')' statement 959 /// 'if' '(' expression ')' statement 'else' statement 960 /// [C++] 'if' '(' condition ')' statement 961 /// [C++] 'if' '(' condition ')' statement 'else' statement 962 /// 963 StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) { 964 assert(Tok.is(tok::kw_if) && "Not an if stmt!"); 965 SourceLocation IfLoc = ConsumeToken(); // eat the 'if'. 966 967 if (Tok.isNot(tok::l_paren)) { 968 Diag(Tok, diag::err_expected_lparen_after) << "if"; 969 SkipUntil(tok::semi); 970 return StmtError(); 971 } 972 973 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 974 975 // C99 6.8.4p3 - In C99, the if statement is a block. This is not 976 // the case for C90. 977 // 978 // C++ 6.4p3: 979 // A name introduced by a declaration in a condition is in scope from its 980 // point of declaration until the end of the substatements controlled by the 981 // condition. 982 // C++ 3.3.2p4: 983 // Names declared in the for-init-statement, and in the condition of if, 984 // while, for, and switch statements are local to the if, while, for, or 985 // switch statement (including the controlled statement). 986 // 987 ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX); 988 989 // Parse the condition. 990 ExprResult CondExp; 991 Decl *CondVar = 0; 992 if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true)) 993 return StmtError(); 994 995 FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc)); 996 997 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if 998 // there is no compound stmt. C90 does not have this clause. We only do this 999 // if the body isn't a compound statement to avoid push/pop in common cases. 1000 // 1001 // C++ 6.4p1: 1002 // The substatement in a selection-statement (each substatement, in the else 1003 // form of the if statement) implicitly defines a local scope. 1004 // 1005 // For C++ we create a scope for the condition and a new scope for 1006 // substatements because: 1007 // -When the 'then' scope exits, we want the condition declaration to still be 1008 // active for the 'else' scope too. 1009 // -Sema will detect name clashes by considering declarations of a 1010 // 'ControlScope' as part of its direct subscope. 1011 // -If we wanted the condition and substatement to be in the same scope, we 1012 // would have to notify ParseStatement not to create a new scope. It's 1013 // simpler to let it create a new scope. 1014 // 1015 ParseScope InnerScope(this, Scope::DeclScope, 1016 C99orCXX && Tok.isNot(tok::l_brace)); 1017 1018 // Read the 'then' stmt. 1019 SourceLocation ThenStmtLoc = Tok.getLocation(); 1020 1021 SourceLocation InnerStatementTrailingElseLoc; 1022 StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc)); 1023 1024 // Pop the 'if' scope if needed. 1025 InnerScope.Exit(); 1026 1027 // If it has an else, parse it. 1028 SourceLocation ElseLoc; 1029 SourceLocation ElseStmtLoc; 1030 StmtResult ElseStmt; 1031 1032 if (Tok.is(tok::kw_else)) { 1033 if (TrailingElseLoc) 1034 *TrailingElseLoc = Tok.getLocation(); 1035 1036 ElseLoc = ConsumeToken(); 1037 ElseStmtLoc = Tok.getLocation(); 1038 1039 // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if 1040 // there is no compound stmt. C90 does not have this clause. We only do 1041 // this if the body isn't a compound statement to avoid push/pop in common 1042 // cases. 1043 // 1044 // C++ 6.4p1: 1045 // The substatement in a selection-statement (each substatement, in the else 1046 // form of the if statement) implicitly defines a local scope. 1047 // 1048 ParseScope InnerScope(this, Scope::DeclScope, 1049 C99orCXX && Tok.isNot(tok::l_brace)); 1050 1051 ElseStmt = ParseStatement(); 1052 1053 // Pop the 'else' scope if needed. 1054 InnerScope.Exit(); 1055 } else if (Tok.is(tok::code_completion)) { 1056 Actions.CodeCompleteAfterIf(getCurScope()); 1057 cutOffParsing(); 1058 return StmtError(); 1059 } else if (InnerStatementTrailingElseLoc.isValid()) { 1060 Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else); 1061 } 1062 1063 IfScope.Exit(); 1064 1065 // If the then or else stmt is invalid and the other is valid (and present), 1066 // make turn the invalid one into a null stmt to avoid dropping the other 1067 // part. If both are invalid, return error. 1068 if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) || 1069 (ThenStmt.isInvalid() && ElseStmt.get() == 0) || 1070 (ThenStmt.get() == 0 && ElseStmt.isInvalid())) { 1071 // Both invalid, or one is invalid and other is non-present: return error. 1072 return StmtError(); 1073 } 1074 1075 // Now if either are invalid, replace with a ';'. 1076 if (ThenStmt.isInvalid()) 1077 ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc); 1078 if (ElseStmt.isInvalid()) 1079 ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc); 1080 1081 return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(), 1082 ElseLoc, ElseStmt.get()); 1083 } 1084 1085 /// ParseSwitchStatement 1086 /// switch-statement: 1087 /// 'switch' '(' expression ')' statement 1088 /// [C++] 'switch' '(' condition ')' statement 1089 StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) { 1090 assert(Tok.is(tok::kw_switch) && "Not a switch stmt!"); 1091 SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'. 1092 1093 if (Tok.isNot(tok::l_paren)) { 1094 Diag(Tok, diag::err_expected_lparen_after) << "switch"; 1095 SkipUntil(tok::semi); 1096 return StmtError(); 1097 } 1098 1099 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 1100 1101 // C99 6.8.4p3 - In C99, the switch statement is a block. This is 1102 // not the case for C90. Start the switch scope. 1103 // 1104 // C++ 6.4p3: 1105 // A name introduced by a declaration in a condition is in scope from its 1106 // point of declaration until the end of the substatements controlled by the 1107 // condition. 1108 // C++ 3.3.2p4: 1109 // Names declared in the for-init-statement, and in the condition of if, 1110 // while, for, and switch statements are local to the if, while, for, or 1111 // switch statement (including the controlled statement). 1112 // 1113 unsigned ScopeFlags = Scope::BreakScope | Scope::SwitchScope; 1114 if (C99orCXX) 1115 ScopeFlags |= Scope::DeclScope | Scope::ControlScope; 1116 ParseScope SwitchScope(this, ScopeFlags); 1117 1118 // Parse the condition. 1119 ExprResult Cond; 1120 Decl *CondVar = 0; 1121 if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false)) 1122 return StmtError(); 1123 1124 StmtResult Switch 1125 = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar); 1126 1127 if (Switch.isInvalid()) { 1128 // Skip the switch body. 1129 // FIXME: This is not optimal recovery, but parsing the body is more 1130 // dangerous due to the presence of case and default statements, which 1131 // will have no place to connect back with the switch. 1132 if (Tok.is(tok::l_brace)) { 1133 ConsumeBrace(); 1134 SkipUntil(tok::r_brace, false, false); 1135 } else 1136 SkipUntil(tok::semi); 1137 return Switch; 1138 } 1139 1140 // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if 1141 // there is no compound stmt. C90 does not have this clause. We only do this 1142 // if the body isn't a compound statement to avoid push/pop in common cases. 1143 // 1144 // C++ 6.4p1: 1145 // The substatement in a selection-statement (each substatement, in the else 1146 // form of the if statement) implicitly defines a local scope. 1147 // 1148 // See comments in ParseIfStatement for why we create a scope for the 1149 // condition and a new scope for substatement in C++. 1150 // 1151 ParseScope InnerScope(this, Scope::DeclScope, 1152 C99orCXX && Tok.isNot(tok::l_brace)); 1153 1154 // Read the body statement. 1155 StmtResult Body(ParseStatement(TrailingElseLoc)); 1156 1157 // Pop the scopes. 1158 InnerScope.Exit(); 1159 SwitchScope.Exit(); 1160 1161 if (Body.isInvalid()) { 1162 // FIXME: Remove the case statement list from the Switch statement. 1163 1164 // Put the synthesized null statement on the same line as the end of switch 1165 // condition. 1166 SourceLocation SynthesizedNullStmtLocation = Cond.get()->getLocEnd(); 1167 Body = Actions.ActOnNullStmt(SynthesizedNullStmtLocation); 1168 } 1169 1170 return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get()); 1171 } 1172 1173 /// ParseWhileStatement 1174 /// while-statement: [C99 6.8.5.1] 1175 /// 'while' '(' expression ')' statement 1176 /// [C++] 'while' '(' condition ')' statement 1177 StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) { 1178 assert(Tok.is(tok::kw_while) && "Not a while stmt!"); 1179 SourceLocation WhileLoc = Tok.getLocation(); 1180 ConsumeToken(); // eat the 'while'. 1181 1182 if (Tok.isNot(tok::l_paren)) { 1183 Diag(Tok, diag::err_expected_lparen_after) << "while"; 1184 SkipUntil(tok::semi); 1185 return StmtError(); 1186 } 1187 1188 bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; 1189 1190 // C99 6.8.5p5 - In C99, the while statement is a block. This is not 1191 // the case for C90. Start the loop scope. 1192 // 1193 // C++ 6.4p3: 1194 // A name introduced by a declaration in a condition is in scope from its 1195 // point of declaration until the end of the substatements controlled by the 1196 // condition. 1197 // C++ 3.3.2p4: 1198 // Names declared in the for-init-statement, and in the condition of if, 1199 // while, for, and switch statements are local to the if, while, for, or 1200 // switch statement (including the controlled statement). 1201 // 1202 unsigned ScopeFlags; 1203 if (C99orCXX) 1204 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | 1205 Scope::DeclScope | Scope::ControlScope; 1206 else 1207 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 1208 ParseScope WhileScope(this, ScopeFlags); 1209 1210 // Parse the condition. 1211 ExprResult Cond; 1212 Decl *CondVar = 0; 1213 if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true)) 1214 return StmtError(); 1215 1216 FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc)); 1217 1218 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if 1219 // there is no compound stmt. C90 does not have this clause. We only do this 1220 // if the body isn't a compound statement to avoid push/pop in common cases. 1221 // 1222 // C++ 6.5p2: 1223 // The substatement in an iteration-statement implicitly defines a local scope 1224 // which is entered and exited each time through the loop. 1225 // 1226 // See comments in ParseIfStatement for why we create a scope for the 1227 // condition and a new scope for substatement in C++. 1228 // 1229 ParseScope InnerScope(this, Scope::DeclScope, 1230 C99orCXX && Tok.isNot(tok::l_brace)); 1231 1232 // Read the body statement. 1233 StmtResult Body(ParseStatement(TrailingElseLoc)); 1234 1235 // Pop the body scope if needed. 1236 InnerScope.Exit(); 1237 WhileScope.Exit(); 1238 1239 if ((Cond.isInvalid() && !CondVar) || Body.isInvalid()) 1240 return StmtError(); 1241 1242 return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get()); 1243 } 1244 1245 /// ParseDoStatement 1246 /// do-statement: [C99 6.8.5.2] 1247 /// 'do' statement 'while' '(' expression ')' ';' 1248 /// Note: this lets the caller parse the end ';'. 1249 StmtResult Parser::ParseDoStatement() { 1250 assert(Tok.is(tok::kw_do) && "Not a do stmt!"); 1251 SourceLocation DoLoc = ConsumeToken(); // eat the 'do'. 1252 1253 // C99 6.8.5p5 - In C99, the do statement is a block. This is not 1254 // the case for C90. Start the loop scope. 1255 unsigned ScopeFlags; 1256 if (getLangOpts().C99) 1257 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope; 1258 else 1259 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 1260 1261 ParseScope DoScope(this, ScopeFlags); 1262 1263 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if 1264 // there is no compound stmt. C90 does not have this clause. We only do this 1265 // if the body isn't a compound statement to avoid push/pop in common cases. 1266 // 1267 // C++ 6.5p2: 1268 // The substatement in an iteration-statement implicitly defines a local scope 1269 // which is entered and exited each time through the loop. 1270 // 1271 ParseScope InnerScope(this, Scope::DeclScope, 1272 (getLangOpts().C99 || getLangOpts().CPlusPlus) && 1273 Tok.isNot(tok::l_brace)); 1274 1275 // Read the body statement. 1276 StmtResult Body(ParseStatement()); 1277 1278 // Pop the body scope if needed. 1279 InnerScope.Exit(); 1280 1281 if (Tok.isNot(tok::kw_while)) { 1282 if (!Body.isInvalid()) { 1283 Diag(Tok, diag::err_expected_while); 1284 Diag(DoLoc, diag::note_matching) << "do"; 1285 SkipUntil(tok::semi, false, true); 1286 } 1287 return StmtError(); 1288 } 1289 SourceLocation WhileLoc = ConsumeToken(); 1290 1291 if (Tok.isNot(tok::l_paren)) { 1292 Diag(Tok, diag::err_expected_lparen_after) << "do/while"; 1293 SkipUntil(tok::semi, false, true); 1294 return StmtError(); 1295 } 1296 1297 // Parse the parenthesized condition. 1298 BalancedDelimiterTracker T(*this, tok::l_paren); 1299 T.consumeOpen(); 1300 1301 // FIXME: Do not just parse the attribute contents and throw them away 1302 ParsedAttributesWithRange attrs(AttrFactory); 1303 MaybeParseCXX11Attributes(attrs); 1304 ProhibitAttributes(attrs); 1305 1306 ExprResult Cond = ParseExpression(); 1307 T.consumeClose(); 1308 DoScope.Exit(); 1309 1310 if (Cond.isInvalid() || Body.isInvalid()) 1311 return StmtError(); 1312 1313 return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(), 1314 Cond.get(), T.getCloseLocation()); 1315 } 1316 1317 /// ParseForStatement 1318 /// for-statement: [C99 6.8.5.3] 1319 /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement 1320 /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement 1321 /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')' 1322 /// [C++] statement 1323 /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement 1324 /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement 1325 /// [OBJC2] 'for' '(' expr 'in' expr ')' statement 1326 /// 1327 /// [C++] for-init-statement: 1328 /// [C++] expression-statement 1329 /// [C++] simple-declaration 1330 /// 1331 /// [C++0x] for-range-declaration: 1332 /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator 1333 /// [C++0x] for-range-initializer: 1334 /// [C++0x] expression 1335 /// [C++0x] braced-init-list [TODO] 1336 StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) { 1337 assert(Tok.is(tok::kw_for) && "Not a for stmt!"); 1338 SourceLocation ForLoc = ConsumeToken(); // eat the 'for'. 1339 1340 if (Tok.isNot(tok::l_paren)) { 1341 Diag(Tok, diag::err_expected_lparen_after) << "for"; 1342 SkipUntil(tok::semi); 1343 return StmtError(); 1344 } 1345 1346 bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || 1347 getLangOpts().ObjC1; 1348 1349 // C99 6.8.5p5 - In C99, the for statement is a block. This is not 1350 // the case for C90. Start the loop scope. 1351 // 1352 // C++ 6.4p3: 1353 // A name introduced by a declaration in a condition is in scope from its 1354 // point of declaration until the end of the substatements controlled by the 1355 // condition. 1356 // C++ 3.3.2p4: 1357 // Names declared in the for-init-statement, and in the condition of if, 1358 // while, for, and switch statements are local to the if, while, for, or 1359 // switch statement (including the controlled statement). 1360 // C++ 6.5.3p1: 1361 // Names declared in the for-init-statement are in the same declarative-region 1362 // as those declared in the condition. 1363 // 1364 unsigned ScopeFlags; 1365 if (C99orCXXorObjC) 1366 ScopeFlags = Scope::BreakScope | Scope::ContinueScope | 1367 Scope::DeclScope | Scope::ControlScope; 1368 else 1369 ScopeFlags = Scope::BreakScope | Scope::ContinueScope; 1370 1371 ParseScope ForScope(this, ScopeFlags); 1372 1373 BalancedDelimiterTracker T(*this, tok::l_paren); 1374 T.consumeOpen(); 1375 1376 ExprResult Value; 1377 1378 bool ForEach = false, ForRange = false; 1379 StmtResult FirstPart; 1380 bool SecondPartIsInvalid = false; 1381 FullExprArg SecondPart(Actions); 1382 ExprResult Collection; 1383 ForRangeInit ForRangeInit; 1384 FullExprArg ThirdPart(Actions); 1385 Decl *SecondVar = 0; 1386 1387 if (Tok.is(tok::code_completion)) { 1388 Actions.CodeCompleteOrdinaryName(getCurScope(), 1389 C99orCXXorObjC? Sema::PCC_ForInit 1390 : Sema::PCC_Expression); 1391 cutOffParsing(); 1392 return StmtError(); 1393 } 1394 1395 ParsedAttributesWithRange attrs(AttrFactory); 1396 MaybeParseCXX11Attributes(attrs); 1397 1398 // Parse the first part of the for specifier. 1399 if (Tok.is(tok::semi)) { // for (; 1400 ProhibitAttributes(attrs); 1401 // no first part, eat the ';'. 1402 ConsumeToken(); 1403 } else if (isForInitDeclaration()) { // for (int X = 4; 1404 // Parse declaration, which eats the ';'. 1405 if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode? 1406 Diag(Tok, diag::ext_c99_variable_decl_in_for_loop); 1407 1408 // In C++0x, "for (T NS:a" might not be a typo for :: 1409 bool MightBeForRangeStmt = getLangOpts().CPlusPlus; 1410 ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt); 1411 1412 SourceLocation DeclStart = Tok.getLocation(), DeclEnd; 1413 StmtVector Stmts; 1414 DeclGroupPtrTy DG = ParseSimpleDeclaration(Stmts, Declarator::ForContext, 1415 DeclEnd, attrs, false, 1416 MightBeForRangeStmt ? 1417 &ForRangeInit : 0); 1418 FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); 1419 1420 if (ForRangeInit.ParsedForRangeDecl()) { 1421 Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ? 1422 diag::warn_cxx98_compat_for_range : diag::ext_for_range); 1423 1424 ForRange = true; 1425 } else if (Tok.is(tok::semi)) { // for (int x = 4; 1426 ConsumeToken(); 1427 } else if ((ForEach = isTokIdentifier_in())) { 1428 Actions.ActOnForEachDeclStmt(DG); 1429 // ObjC: for (id x in expr) 1430 ConsumeToken(); // consume 'in' 1431 1432 if (Tok.is(tok::code_completion)) { 1433 Actions.CodeCompleteObjCForCollection(getCurScope(), DG); 1434 cutOffParsing(); 1435 return StmtError(); 1436 } 1437 Collection = ParseExpression(); 1438 } else { 1439 Diag(Tok, diag::err_expected_semi_for); 1440 } 1441 } else { 1442 ProhibitAttributes(attrs); 1443 Value = ParseExpression(); 1444 1445 ForEach = isTokIdentifier_in(); 1446 1447 // Turn the expression into a stmt. 1448 if (!Value.isInvalid()) { 1449 if (ForEach) 1450 FirstPart = Actions.ActOnForEachLValueExpr(Value.get()); 1451 else 1452 FirstPart = Actions.ActOnExprStmt(Value); 1453 } 1454 1455 if (Tok.is(tok::semi)) { 1456 ConsumeToken(); 1457 } else if (ForEach) { 1458 ConsumeToken(); // consume 'in' 1459 1460 if (Tok.is(tok::code_completion)) { 1461 Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy()); 1462 cutOffParsing(); 1463 return StmtError(); 1464 } 1465 Collection = ParseExpression(); 1466 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) { 1467 // User tried to write the reasonable, but ill-formed, for-range-statement 1468 // for (expr : expr) { ... } 1469 Diag(Tok, diag::err_for_range_expected_decl) 1470 << FirstPart.get()->getSourceRange(); 1471 SkipUntil(tok::r_paren, false, true); 1472 SecondPartIsInvalid = true; 1473 } else { 1474 if (!Value.isInvalid()) { 1475 Diag(Tok, diag::err_expected_semi_for); 1476 } else { 1477 // Skip until semicolon or rparen, don't consume it. 1478 SkipUntil(tok::r_paren, true, true); 1479 if (Tok.is(tok::semi)) 1480 ConsumeToken(); 1481 } 1482 } 1483 } 1484 if (!ForEach && !ForRange) { 1485 assert(!SecondPart.get() && "Shouldn't have a second expression yet."); 1486 // Parse the second part of the for specifier. 1487 if (Tok.is(tok::semi)) { // for (...;; 1488 // no second part. 1489 } else if (Tok.is(tok::r_paren)) { 1490 // missing both semicolons. 1491 } else { 1492 ExprResult Second; 1493 if (getLangOpts().CPlusPlus) 1494 ParseCXXCondition(Second, SecondVar, ForLoc, true); 1495 else { 1496 Second = ParseExpression(); 1497 if (!Second.isInvalid()) 1498 Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc, 1499 Second.get()); 1500 } 1501 SecondPartIsInvalid = Second.isInvalid(); 1502 SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc); 1503 } 1504 1505 if (Tok.isNot(tok::semi)) { 1506 if (!SecondPartIsInvalid || SecondVar) 1507 Diag(Tok, diag::err_expected_semi_for); 1508 else 1509 // Skip until semicolon or rparen, don't consume it. 1510 SkipUntil(tok::r_paren, true, true); 1511 } 1512 1513 if (Tok.is(tok::semi)) { 1514 ConsumeToken(); 1515 } 1516 1517 // Parse the third part of the for specifier. 1518 if (Tok.isNot(tok::r_paren)) { // for (...;...;) 1519 ExprResult Third = ParseExpression(); 1520 // FIXME: The C++11 standard doesn't actually say that this is a 1521 // discarded-value expression, but it clearly should be. 1522 ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.take()); 1523 } 1524 } 1525 // Match the ')'. 1526 T.consumeClose(); 1527 1528 // We need to perform most of the semantic analysis for a C++0x for-range 1529 // statememt before parsing the body, in order to be able to deduce the type 1530 // of an auto-typed loop variable. 1531 StmtResult ForRangeStmt; 1532 StmtResult ForEachStmt; 1533 1534 if (ForRange) { 1535 ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.take(), 1536 ForRangeInit.ColonLoc, 1537 ForRangeInit.RangeExpr.get(), 1538 T.getCloseLocation(), 1539 Sema::BFRK_Build); 1540 1541 1542 // Similarly, we need to do the semantic analysis for a for-range 1543 // statement immediately in order to close over temporaries correctly. 1544 } else if (ForEach) { 1545 ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc, 1546 FirstPart.take(), 1547 Collection.take(), 1548 T.getCloseLocation()); 1549 } 1550 1551 // C99 6.8.5p5 - In C99, the body of the if statement is a scope, even if 1552 // there is no compound stmt. C90 does not have this clause. We only do this 1553 // if the body isn't a compound statement to avoid push/pop in common cases. 1554 // 1555 // C++ 6.5p2: 1556 // The substatement in an iteration-statement implicitly defines a local scope 1557 // which is entered and exited each time through the loop. 1558 // 1559 // See comments in ParseIfStatement for why we create a scope for 1560 // for-init-statement/condition and a new scope for substatement in C++. 1561 // 1562 ParseScope InnerScope(this, Scope::DeclScope, 1563 C99orCXXorObjC && Tok.isNot(tok::l_brace)); 1564 1565 // Read the body statement. 1566 StmtResult Body(ParseStatement(TrailingElseLoc)); 1567 1568 // Pop the body scope if needed. 1569 InnerScope.Exit(); 1570 1571 // Leave the for-scope. 1572 ForScope.Exit(); 1573 1574 if (Body.isInvalid()) 1575 return StmtError(); 1576 1577 if (ForEach) 1578 return Actions.FinishObjCForCollectionStmt(ForEachStmt.take(), 1579 Body.take()); 1580 1581 if (ForRange) 1582 return Actions.FinishCXXForRangeStmt(ForRangeStmt.take(), Body.take()); 1583 1584 return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.take(), 1585 SecondPart, SecondVar, ThirdPart, 1586 T.getCloseLocation(), Body.take()); 1587 } 1588 1589 /// ParseGotoStatement 1590 /// jump-statement: 1591 /// 'goto' identifier ';' 1592 /// [GNU] 'goto' '*' expression ';' 1593 /// 1594 /// Note: this lets the caller parse the end ';'. 1595 /// 1596 StmtResult Parser::ParseGotoStatement() { 1597 assert(Tok.is(tok::kw_goto) && "Not a goto stmt!"); 1598 SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'. 1599 1600 StmtResult Res; 1601 if (Tok.is(tok::identifier)) { 1602 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 1603 Tok.getLocation()); 1604 Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD); 1605 ConsumeToken(); 1606 } else if (Tok.is(tok::star)) { 1607 // GNU indirect goto extension. 1608 Diag(Tok, diag::ext_gnu_indirect_goto); 1609 SourceLocation StarLoc = ConsumeToken(); 1610 ExprResult R(ParseExpression()); 1611 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it. 1612 SkipUntil(tok::semi, false, true); 1613 return StmtError(); 1614 } 1615 Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.take()); 1616 } else { 1617 Diag(Tok, diag::err_expected_ident); 1618 return StmtError(); 1619 } 1620 1621 return Res; 1622 } 1623 1624 /// ParseContinueStatement 1625 /// jump-statement: 1626 /// 'continue' ';' 1627 /// 1628 /// Note: this lets the caller parse the end ';'. 1629 /// 1630 StmtResult Parser::ParseContinueStatement() { 1631 SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'. 1632 return Actions.ActOnContinueStmt(ContinueLoc, getCurScope()); 1633 } 1634 1635 /// ParseBreakStatement 1636 /// jump-statement: 1637 /// 'break' ';' 1638 /// 1639 /// Note: this lets the caller parse the end ';'. 1640 /// 1641 StmtResult Parser::ParseBreakStatement() { 1642 SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'. 1643 return Actions.ActOnBreakStmt(BreakLoc, getCurScope()); 1644 } 1645 1646 /// ParseReturnStatement 1647 /// jump-statement: 1648 /// 'return' expression[opt] ';' 1649 StmtResult Parser::ParseReturnStatement() { 1650 assert(Tok.is(tok::kw_return) && "Not a return stmt!"); 1651 SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'. 1652 1653 ExprResult R; 1654 if (Tok.isNot(tok::semi)) { 1655 if (Tok.is(tok::code_completion)) { 1656 Actions.CodeCompleteReturn(getCurScope()); 1657 cutOffParsing(); 1658 return StmtError(); 1659 } 1660 1661 if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) { 1662 R = ParseInitializer(); 1663 if (R.isUsable()) 1664 Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus11 ? 1665 diag::warn_cxx98_compat_generalized_initializer_lists : 1666 diag::ext_generalized_initializer_lists) 1667 << R.get()->getSourceRange(); 1668 } else 1669 R = ParseExpression(); 1670 if (R.isInvalid()) { // Skip to the semicolon, but don't consume it. 1671 SkipUntil(tok::semi, false, true); 1672 return StmtError(); 1673 } 1674 } 1675 return Actions.ActOnReturnStmt(ReturnLoc, R.take()); 1676 } 1677 1678 namespace { 1679 class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback { 1680 Parser &TheParser; 1681 SourceLocation AsmLoc; 1682 StringRef AsmString; 1683 1684 /// The tokens we streamed into AsmString and handed off to MC. 1685 ArrayRef<Token> AsmToks; 1686 1687 /// The offset of each token in AsmToks within AsmString. 1688 ArrayRef<unsigned> AsmTokOffsets; 1689 1690 public: 1691 ClangAsmParserCallback(Parser &P, SourceLocation Loc, 1692 StringRef AsmString, 1693 ArrayRef<Token> Toks, 1694 ArrayRef<unsigned> Offsets) 1695 : TheParser(P), AsmLoc(Loc), AsmString(AsmString), 1696 AsmToks(Toks), AsmTokOffsets(Offsets) { 1697 assert(AsmToks.size() == AsmTokOffsets.size()); 1698 } 1699 1700 void *LookupInlineAsmIdentifier(StringRef &LineBuf, 1701 InlineAsmIdentifierInfo &Info, 1702 bool IsUnevaluatedContext) { 1703 // Collect the desired tokens. 1704 SmallVector<Token, 16> LineToks; 1705 const Token *FirstOrigToken = 0; 1706 findTokensForString(LineBuf, LineToks, FirstOrigToken); 1707 1708 unsigned NumConsumedToks; 1709 ExprResult Result = 1710 TheParser.ParseMSAsmIdentifier(LineToks, NumConsumedToks, &Info, 1711 IsUnevaluatedContext); 1712 1713 // If we consumed the entire line, tell MC that. 1714 // Also do this if we consumed nothing as a way of reporting failure. 1715 if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) { 1716 // By not modifying LineBuf, we're implicitly consuming it all. 1717 1718 // Otherwise, consume up to the original tokens. 1719 } else { 1720 assert(FirstOrigToken && "not using original tokens?"); 1721 1722 // Since we're using original tokens, apply that offset. 1723 assert(FirstOrigToken[NumConsumedToks].getLocation() 1724 == LineToks[NumConsumedToks].getLocation()); 1725 unsigned FirstIndex = FirstOrigToken - AsmToks.begin(); 1726 unsigned LastIndex = FirstIndex + NumConsumedToks - 1; 1727 1728 // The total length we've consumed is the relative offset 1729 // of the last token we consumed plus its length. 1730 unsigned TotalOffset = (AsmTokOffsets[LastIndex] 1731 + AsmToks[LastIndex].getLength() 1732 - AsmTokOffsets[FirstIndex]); 1733 LineBuf = LineBuf.substr(0, TotalOffset); 1734 } 1735 1736 // Initialize the "decl" with the lookup result. 1737 Info.OpDecl = static_cast<void*>(Result.take()); 1738 return Info.OpDecl; 1739 } 1740 1741 bool LookupInlineAsmField(StringRef Base, StringRef Member, 1742 unsigned &Offset) { 1743 return TheParser.getActions().LookupInlineAsmField(Base, Member, 1744 Offset, AsmLoc); 1745 } 1746 1747 static void DiagHandlerCallback(const llvm::SMDiagnostic &D, 1748 void *Context) { 1749 ((ClangAsmParserCallback*) Context)->handleDiagnostic(D); 1750 } 1751 1752 private: 1753 /// Collect the appropriate tokens for the given string. 1754 void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks, 1755 const Token *&FirstOrigToken) const { 1756 // For now, assert that the string we're working with is a substring 1757 // of what we gave to MC. This lets us use the original tokens. 1758 assert(!std::less<const char*>()(Str.begin(), AsmString.begin()) && 1759 !std::less<const char*>()(AsmString.end(), Str.end())); 1760 1761 // Try to find a token whose offset matches the first token. 1762 unsigned FirstCharOffset = Str.begin() - AsmString.begin(); 1763 const unsigned *FirstTokOffset 1764 = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), 1765 FirstCharOffset); 1766 1767 // For now, assert that the start of the string exactly 1768 // corresponds to the start of a token. 1769 assert(*FirstTokOffset == FirstCharOffset); 1770 1771 // Use all the original tokens for this line. (We assume the 1772 // end of the line corresponds cleanly to a token break.) 1773 unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin(); 1774 FirstOrigToken = &AsmToks[FirstTokIndex]; 1775 unsigned LastCharOffset = Str.end() - AsmString.begin(); 1776 for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) { 1777 if (AsmTokOffsets[i] >= LastCharOffset) break; 1778 TempToks.push_back(AsmToks[i]); 1779 } 1780 } 1781 1782 void handleDiagnostic(const llvm::SMDiagnostic &D) { 1783 // Compute an offset into the inline asm buffer. 1784 // FIXME: This isn't right if .macro is involved (but hopefully, no 1785 // real-world code does that). 1786 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 1787 const llvm::MemoryBuffer *LBuf = 1788 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 1789 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 1790 1791 // Figure out which token that offset points into. 1792 const unsigned *TokOffsetPtr = 1793 std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset); 1794 unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin(); 1795 unsigned TokOffset = *TokOffsetPtr; 1796 1797 // If we come up with an answer which seems sane, use it; otherwise, 1798 // just point at the __asm keyword. 1799 // FIXME: Assert the answer is sane once we handle .macro correctly. 1800 SourceLocation Loc = AsmLoc; 1801 if (TokIndex < AsmToks.size()) { 1802 const Token &Tok = AsmToks[TokIndex]; 1803 Loc = Tok.getLocation(); 1804 Loc = Loc.getLocWithOffset(Offset - TokOffset); 1805 } 1806 TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) 1807 << D.getMessage(); 1808 } 1809 }; 1810 } 1811 1812 /// Parse an identifier in an MS-style inline assembly block. 1813 /// 1814 /// \param CastInfo - a void* so that we don't have to teach Parser.h 1815 /// about the actual type. 1816 ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, 1817 unsigned &NumLineToksConsumed, 1818 void *CastInfo, 1819 bool IsUnevaluatedContext) { 1820 llvm::InlineAsmIdentifierInfo &Info = 1821 *(llvm::InlineAsmIdentifierInfo *) CastInfo; 1822 1823 // Push a fake token on the end so that we don't overrun the token 1824 // stream. We use ';' because it expression-parsing should never 1825 // overrun it. 1826 const tok::TokenKind EndOfStream = tok::semi; 1827 Token EndOfStreamTok; 1828 EndOfStreamTok.startToken(); 1829 EndOfStreamTok.setKind(EndOfStream); 1830 LineToks.push_back(EndOfStreamTok); 1831 1832 // Also copy the current token over. 1833 LineToks.push_back(Tok); 1834 1835 PP.EnterTokenStream(LineToks.begin(), 1836 LineToks.size(), 1837 /*disable macros*/ true, 1838 /*owns tokens*/ false); 1839 1840 // Clear the current token and advance to the first token in LineToks. 1841 ConsumeAnyToken(); 1842 1843 // Parse an optional scope-specifier if we're in C++. 1844 CXXScopeSpec SS; 1845 if (getLangOpts().CPlusPlus) { 1846 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); 1847 } 1848 1849 // Require an identifier here. 1850 SourceLocation TemplateKWLoc; 1851 UnqualifiedId Id; 1852 bool Invalid = ParseUnqualifiedId(SS, 1853 /*EnteringContext=*/false, 1854 /*AllowDestructorName=*/false, 1855 /*AllowConstructorName=*/false, 1856 /*ObjectType=*/ ParsedType(), 1857 TemplateKWLoc, 1858 Id); 1859 1860 // If we've run into the poison token we inserted before, or there 1861 // was a parsing error, then claim the entire line. 1862 if (Invalid || Tok.is(EndOfStream)) { 1863 NumLineToksConsumed = LineToks.size() - 2; 1864 1865 // Otherwise, claim up to the start of the next token. 1866 } else { 1867 // Figure out how many tokens we are into LineToks. 1868 unsigned LineIndex = 0; 1869 while (LineToks[LineIndex].getLocation() != Tok.getLocation()) { 1870 LineIndex++; 1871 assert(LineIndex < LineToks.size() - 2); // we added two extra tokens 1872 } 1873 1874 NumLineToksConsumed = LineIndex; 1875 } 1876 1877 // Finally, restore the old parsing state by consuming all the 1878 // tokens we staged before, implicitly killing off the 1879 // token-lexer we pushed. 1880 for (unsigned n = LineToks.size() - 2 - NumLineToksConsumed; n != 0; --n) { 1881 ConsumeAnyToken(); 1882 } 1883 ConsumeToken(EndOfStream); 1884 1885 // Leave LineToks in its original state. 1886 LineToks.pop_back(); 1887 LineToks.pop_back(); 1888 1889 // Perform the lookup. 1890 return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info, 1891 IsUnevaluatedContext); 1892 } 1893 1894 /// Turn a sequence of our tokens back into a string that we can hand 1895 /// to the MC asm parser. 1896 static bool buildMSAsmString(Preprocessor &PP, 1897 SourceLocation AsmLoc, 1898 ArrayRef<Token> AsmToks, 1899 SmallVectorImpl<unsigned> &TokOffsets, 1900 SmallString<512> &Asm) { 1901 assert (!AsmToks.empty() && "Didn't expect an empty AsmToks!"); 1902 1903 // Is this the start of a new assembly statement? 1904 bool isNewStatement = true; 1905 1906 for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) { 1907 const Token &Tok = AsmToks[i]; 1908 1909 // Start each new statement with a newline and a tab. 1910 if (!isNewStatement && 1911 (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) { 1912 Asm += "\n\t"; 1913 isNewStatement = true; 1914 } 1915 1916 // Preserve the existence of leading whitespace except at the 1917 // start of a statement. 1918 if (!isNewStatement && Tok.hasLeadingSpace()) 1919 Asm += ' '; 1920 1921 // Remember the offset of this token. 1922 TokOffsets.push_back(Asm.size()); 1923 1924 // Don't actually write '__asm' into the assembly stream. 1925 if (Tok.is(tok::kw_asm)) { 1926 // Complain about __asm at the end of the stream. 1927 if (i + 1 == e) { 1928 PP.Diag(AsmLoc, diag::err_asm_empty); 1929 return true; 1930 } 1931 1932 continue; 1933 } 1934 1935 // Append the spelling of the token. 1936 SmallString<32> SpellingBuffer; 1937 bool SpellingInvalid = false; 1938 Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid); 1939 assert(!SpellingInvalid && "spelling was invalid after correct parse?"); 1940 1941 // We are no longer at the start of a statement. 1942 isNewStatement = false; 1943 } 1944 1945 // Ensure that the buffer is null-terminated. 1946 Asm.push_back('\0'); 1947 Asm.pop_back(); 1948 1949 assert(TokOffsets.size() == AsmToks.size()); 1950 return false; 1951 } 1952 1953 /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled, 1954 /// this routine is called to collect the tokens for an MS asm statement. 1955 /// 1956 /// [MS] ms-asm-statement: 1957 /// ms-asm-block 1958 /// ms-asm-block ms-asm-statement 1959 /// 1960 /// [MS] ms-asm-block: 1961 /// '__asm' ms-asm-line '\n' 1962 /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt] 1963 /// 1964 /// [MS] ms-asm-instruction-block 1965 /// ms-asm-line 1966 /// ms-asm-line '\n' ms-asm-instruction-block 1967 /// 1968 StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) { 1969 SourceManager &SrcMgr = PP.getSourceManager(); 1970 SourceLocation EndLoc = AsmLoc; 1971 SmallVector<Token, 4> AsmToks; 1972 1973 bool InBraces = false; 1974 unsigned short savedBraceCount = 0; 1975 bool InAsmComment = false; 1976 FileID FID; 1977 unsigned LineNo = 0; 1978 unsigned NumTokensRead = 0; 1979 SourceLocation LBraceLoc; 1980 1981 if (Tok.is(tok::l_brace)) { 1982 // Braced inline asm: consume the opening brace. 1983 InBraces = true; 1984 savedBraceCount = BraceCount; 1985 EndLoc = LBraceLoc = ConsumeBrace(); 1986 ++NumTokensRead; 1987 } else { 1988 // Single-line inline asm; compute which line it is on. 1989 std::pair<FileID, unsigned> ExpAsmLoc = 1990 SrcMgr.getDecomposedExpansionLoc(EndLoc); 1991 FID = ExpAsmLoc.first; 1992 LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second); 1993 } 1994 1995 SourceLocation TokLoc = Tok.getLocation(); 1996 do { 1997 // If we hit EOF, we're done, period. 1998 if (Tok.is(tok::eof)) 1999 break; 2000 2001 if (!InAsmComment && Tok.is(tok::semi)) { 2002 // A semicolon in an asm is the start of a comment. 2003 InAsmComment = true; 2004 if (InBraces) { 2005 // Compute which line the comment is on. 2006 std::pair<FileID, unsigned> ExpSemiLoc = 2007 SrcMgr.getDecomposedExpansionLoc(TokLoc); 2008 FID = ExpSemiLoc.first; 2009 LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second); 2010 } 2011 } else if (!InBraces || InAsmComment) { 2012 // If end-of-line is significant, check whether this token is on a 2013 // new line. 2014 std::pair<FileID, unsigned> ExpLoc = 2015 SrcMgr.getDecomposedExpansionLoc(TokLoc); 2016 if (ExpLoc.first != FID || 2017 SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) { 2018 // If this is a single-line __asm, we're done. 2019 if (!InBraces) 2020 break; 2021 // We're no longer in a comment. 2022 InAsmComment = false; 2023 } else if (!InAsmComment && Tok.is(tok::r_brace)) { 2024 // Single-line asm always ends when a closing brace is seen. 2025 // FIXME: This is compatible with Apple gcc's -fasm-blocks; what 2026 // does MSVC do here? 2027 break; 2028 } 2029 } 2030 if (!InAsmComment && InBraces && Tok.is(tok::r_brace) && 2031 BraceCount == (savedBraceCount + 1)) { 2032 // Consume the closing brace, and finish 2033 EndLoc = ConsumeBrace(); 2034 break; 2035 } 2036 2037 // Consume the next token; make sure we don't modify the brace count etc. 2038 // if we are in a comment. 2039 EndLoc = TokLoc; 2040 if (InAsmComment) 2041 PP.Lex(Tok); 2042 else { 2043 AsmToks.push_back(Tok); 2044 ConsumeAnyToken(); 2045 } 2046 TokLoc = Tok.getLocation(); 2047 ++NumTokensRead; 2048 } while (1); 2049 2050 if (InBraces && BraceCount != savedBraceCount) { 2051 // __asm without closing brace (this can happen at EOF). 2052 Diag(Tok, diag::err_expected_rbrace); 2053 Diag(LBraceLoc, diag::note_matching) << "{"; 2054 return StmtError(); 2055 } else if (NumTokensRead == 0) { 2056 // Empty __asm. 2057 Diag(Tok, diag::err_expected_lbrace); 2058 return StmtError(); 2059 } 2060 2061 // Okay, prepare to use MC to parse the assembly. 2062 SmallVector<StringRef, 4> ConstraintRefs; 2063 SmallVector<Expr*, 4> Exprs; 2064 SmallVector<StringRef, 4> ClobberRefs; 2065 2066 // We need an actual supported target. 2067 llvm::Triple TheTriple = Actions.Context.getTargetInfo().getTriple(); 2068 llvm::Triple::ArchType ArchTy = TheTriple.getArch(); 2069 bool UnsupportedArch = (ArchTy != llvm::Triple::x86 && 2070 ArchTy != llvm::Triple::x86_64); 2071 if (UnsupportedArch) 2072 Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName(); 2073 2074 // If we don't support assembly, or the assembly is empty, we don't 2075 // need to instantiate the AsmParser, etc. 2076 if (UnsupportedArch || AsmToks.empty()) { 2077 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, StringRef(), 2078 /*NumOutputs*/ 0, /*NumInputs*/ 0, 2079 ConstraintRefs, ClobberRefs, Exprs, EndLoc); 2080 } 2081 2082 // Expand the tokens into a string buffer. 2083 SmallString<512> AsmString; 2084 SmallVector<unsigned, 8> TokOffsets; 2085 if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString)) 2086 return StmtError(); 2087 2088 // Find the target and create the target specific parser. 2089 std::string Error; 2090 const std::string &TT = TheTriple.getTriple(); 2091 const llvm::Target *TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error); 2092 2093 OwningPtr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT)); 2094 OwningPtr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT)); 2095 OwningPtr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo()); 2096 OwningPtr<llvm::MCSubtargetInfo> 2097 STI(TheTarget->createMCSubtargetInfo(TT, "", "")); 2098 2099 llvm::SourceMgr TempSrcMgr; 2100 llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr); 2101 llvm::MemoryBuffer *Buffer = 2102 llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>"); 2103 2104 // Tell SrcMgr about this buffer, which is what the parser will pick up. 2105 TempSrcMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc()); 2106 2107 OwningPtr<llvm::MCStreamer> Str(createNullStreamer(Ctx)); 2108 OwningPtr<llvm::MCAsmParser> 2109 Parser(createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI)); 2110 OwningPtr<llvm::MCTargetAsmParser> 2111 TargetParser(TheTarget->createMCAsmParser(*STI, *Parser)); 2112 2113 // Get the instruction descriptor. 2114 const llvm::MCInstrInfo *MII = TheTarget->createMCInstrInfo(); 2115 llvm::MCInstPrinter *IP = 2116 TheTarget->createMCInstPrinter(1, *MAI, *MII, *MRI, *STI); 2117 2118 // Change to the Intel dialect. 2119 Parser->setAssemblerDialect(1); 2120 Parser->setTargetParser(*TargetParser.get()); 2121 Parser->setParsingInlineAsm(true); 2122 TargetParser->setParsingInlineAsm(true); 2123 2124 ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, 2125 AsmToks, TokOffsets); 2126 TargetParser->setSemaCallback(&Callback); 2127 TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback, 2128 &Callback); 2129 2130 unsigned NumOutputs; 2131 unsigned NumInputs; 2132 std::string AsmStringIR; 2133 SmallVector<std::pair<void *, bool>, 4> OpExprs; 2134 SmallVector<std::string, 4> Constraints; 2135 SmallVector<std::string, 4> Clobbers; 2136 if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, 2137 NumOutputs, NumInputs, OpExprs, Constraints, 2138 Clobbers, MII, IP, Callback)) 2139 return StmtError(); 2140 2141 // Build the vector of clobber StringRefs. 2142 unsigned NumClobbers = Clobbers.size(); 2143 ClobberRefs.resize(NumClobbers); 2144 for (unsigned i = 0; i != NumClobbers; ++i) 2145 ClobberRefs[i] = StringRef(Clobbers[i]); 2146 2147 // Recast the void pointers and build the vector of constraint StringRefs. 2148 unsigned NumExprs = NumOutputs + NumInputs; 2149 ConstraintRefs.resize(NumExprs); 2150 Exprs.resize(NumExprs); 2151 for (unsigned i = 0, e = NumExprs; i != e; ++i) { 2152 Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first); 2153 if (!OpExpr) 2154 return StmtError(); 2155 2156 // Need address of variable. 2157 if (OpExprs[i].second) 2158 OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr) 2159 .take(); 2160 2161 ConstraintRefs[i] = StringRef(Constraints[i]); 2162 Exprs[i] = OpExpr; 2163 } 2164 2165 // FIXME: We should be passing source locations for better diagnostics. 2166 return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmStringIR, 2167 NumOutputs, NumInputs, 2168 ConstraintRefs, ClobberRefs, Exprs, EndLoc); 2169 } 2170 2171 /// ParseAsmStatement - Parse a GNU extended asm statement. 2172 /// asm-statement: 2173 /// gnu-asm-statement 2174 /// ms-asm-statement 2175 /// 2176 /// [GNU] gnu-asm-statement: 2177 /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';' 2178 /// 2179 /// [GNU] asm-argument: 2180 /// asm-string-literal 2181 /// asm-string-literal ':' asm-operands[opt] 2182 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt] 2183 /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt] 2184 /// ':' asm-clobbers 2185 /// 2186 /// [GNU] asm-clobbers: 2187 /// asm-string-literal 2188 /// asm-clobbers ',' asm-string-literal 2189 /// 2190 StmtResult Parser::ParseAsmStatement(bool &msAsm) { 2191 assert(Tok.is(tok::kw_asm) && "Not an asm stmt"); 2192 SourceLocation AsmLoc = ConsumeToken(); 2193 2194 if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) && 2195 !isTypeQualifier()) { 2196 msAsm = true; 2197 return ParseMicrosoftAsmStatement(AsmLoc); 2198 } 2199 DeclSpec DS(AttrFactory); 2200 SourceLocation Loc = Tok.getLocation(); 2201 ParseTypeQualifierListOpt(DS, true, false); 2202 2203 // GNU asms accept, but warn, about type-qualifiers other than volatile. 2204 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2205 Diag(Loc, diag::w_asm_qualifier_ignored) << "const"; 2206 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2207 Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict"; 2208 // FIXME: Once GCC supports _Atomic, check whether it permits it here. 2209 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 2210 Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic"; 2211 2212 // Remember if this was a volatile asm. 2213 bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile; 2214 if (Tok.isNot(tok::l_paren)) { 2215 Diag(Tok, diag::err_expected_lparen_after) << "asm"; 2216 SkipUntil(tok::r_paren); 2217 return StmtError(); 2218 } 2219 BalancedDelimiterTracker T(*this, tok::l_paren); 2220 T.consumeOpen(); 2221 2222 ExprResult AsmString(ParseAsmStringLiteral()); 2223 if (AsmString.isInvalid()) { 2224 // Consume up to and including the closing paren. 2225 T.skipToEnd(); 2226 return StmtError(); 2227 } 2228 2229 SmallVector<IdentifierInfo *, 4> Names; 2230 ExprVector Constraints; 2231 ExprVector Exprs; 2232 ExprVector Clobbers; 2233 2234 if (Tok.is(tok::r_paren)) { 2235 // We have a simple asm expression like 'asm("foo")'. 2236 T.consumeClose(); 2237 return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile, 2238 /*NumOutputs*/ 0, /*NumInputs*/ 0, 0, 2239 Constraints, Exprs, AsmString.take(), 2240 Clobbers, T.getCloseLocation()); 2241 } 2242 2243 // Parse Outputs, if present. 2244 bool AteExtraColon = false; 2245 if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) { 2246 // In C++ mode, parse "::" like ": :". 2247 AteExtraColon = Tok.is(tok::coloncolon); 2248 ConsumeToken(); 2249 2250 if (!AteExtraColon && 2251 ParseAsmOperandsOpt(Names, Constraints, Exprs)) 2252 return StmtError(); 2253 } 2254 2255 unsigned NumOutputs = Names.size(); 2256 2257 // Parse Inputs, if present. 2258 if (AteExtraColon || 2259 Tok.is(tok::colon) || Tok.is(tok::coloncolon)) { 2260 // In C++ mode, parse "::" like ": :". 2261 if (AteExtraColon) 2262 AteExtraColon = false; 2263 else { 2264 AteExtraColon = Tok.is(tok::coloncolon); 2265 ConsumeToken(); 2266 } 2267 2268 if (!AteExtraColon && 2269 ParseAsmOperandsOpt(Names, Constraints, Exprs)) 2270 return StmtError(); 2271 } 2272 2273 assert(Names.size() == Constraints.size() && 2274 Constraints.size() == Exprs.size() && 2275 "Input operand size mismatch!"); 2276 2277 unsigned NumInputs = Names.size() - NumOutputs; 2278 2279 // Parse the clobbers, if present. 2280 if (AteExtraColon || Tok.is(tok::colon)) { 2281 if (!AteExtraColon) 2282 ConsumeToken(); 2283 2284 // Parse the asm-string list for clobbers if present. 2285 if (Tok.isNot(tok::r_paren)) { 2286 while (1) { 2287 ExprResult Clobber(ParseAsmStringLiteral()); 2288 2289 if (Clobber.isInvalid()) 2290 break; 2291 2292 Clobbers.push_back(Clobber.release()); 2293 2294 if (Tok.isNot(tok::comma)) break; 2295 ConsumeToken(); 2296 } 2297 } 2298 } 2299 2300 T.consumeClose(); 2301 return Actions.ActOnGCCAsmStmt(AsmLoc, false, isVolatile, NumOutputs, 2302 NumInputs, Names.data(), Constraints, Exprs, 2303 AsmString.take(), Clobbers, 2304 T.getCloseLocation()); 2305 } 2306 2307 /// ParseAsmOperands - Parse the asm-operands production as used by 2308 /// asm-statement, assuming the leading ':' token was eaten. 2309 /// 2310 /// [GNU] asm-operands: 2311 /// asm-operand 2312 /// asm-operands ',' asm-operand 2313 /// 2314 /// [GNU] asm-operand: 2315 /// asm-string-literal '(' expression ')' 2316 /// '[' identifier ']' asm-string-literal '(' expression ')' 2317 /// 2318 // 2319 // FIXME: Avoid unnecessary std::string trashing. 2320 bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, 2321 SmallVectorImpl<Expr *> &Constraints, 2322 SmallVectorImpl<Expr *> &Exprs) { 2323 // 'asm-operands' isn't present? 2324 if (!isTokenStringLiteral() && Tok.isNot(tok::l_square)) 2325 return false; 2326 2327 while (1) { 2328 // Read the [id] if present. 2329 if (Tok.is(tok::l_square)) { 2330 BalancedDelimiterTracker T(*this, tok::l_square); 2331 T.consumeOpen(); 2332 2333 if (Tok.isNot(tok::identifier)) { 2334 Diag(Tok, diag::err_expected_ident); 2335 SkipUntil(tok::r_paren); 2336 return true; 2337 } 2338 2339 IdentifierInfo *II = Tok.getIdentifierInfo(); 2340 ConsumeToken(); 2341 2342 Names.push_back(II); 2343 T.consumeClose(); 2344 } else 2345 Names.push_back(0); 2346 2347 ExprResult Constraint(ParseAsmStringLiteral()); 2348 if (Constraint.isInvalid()) { 2349 SkipUntil(tok::r_paren); 2350 return true; 2351 } 2352 Constraints.push_back(Constraint.release()); 2353 2354 if (Tok.isNot(tok::l_paren)) { 2355 Diag(Tok, diag::err_expected_lparen_after) << "asm operand"; 2356 SkipUntil(tok::r_paren); 2357 return true; 2358 } 2359 2360 // Read the parenthesized expression. 2361 BalancedDelimiterTracker T(*this, tok::l_paren); 2362 T.consumeOpen(); 2363 ExprResult Res(ParseExpression()); 2364 T.consumeClose(); 2365 if (Res.isInvalid()) { 2366 SkipUntil(tok::r_paren); 2367 return true; 2368 } 2369 Exprs.push_back(Res.release()); 2370 // Eat the comma and continue parsing if it exists. 2371 if (Tok.isNot(tok::comma)) return false; 2372 ConsumeToken(); 2373 } 2374 } 2375 2376 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) { 2377 assert(Tok.is(tok::l_brace)); 2378 SourceLocation LBraceLoc = Tok.getLocation(); 2379 2380 if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) && 2381 trySkippingFunctionBody()) { 2382 BodyScope.Exit(); 2383 return Actions.ActOnSkippedFunctionBody(Decl); 2384 } 2385 2386 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc, 2387 "parsing function body"); 2388 2389 // Do not enter a scope for the brace, as the arguments are in the same scope 2390 // (the function body) as the body itself. Instead, just read the statement 2391 // list and put it into a CompoundStmt for safe keeping. 2392 StmtResult FnBody(ParseCompoundStatementBody()); 2393 2394 // If the function body could not be parsed, make a bogus compoundstmt. 2395 if (FnBody.isInvalid()) { 2396 Sema::CompoundScopeRAII CompoundScope(Actions); 2397 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, 2398 MultiStmtArg(), false); 2399 } 2400 2401 BodyScope.Exit(); 2402 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take()); 2403 } 2404 2405 /// ParseFunctionTryBlock - Parse a C++ function-try-block. 2406 /// 2407 /// function-try-block: 2408 /// 'try' ctor-initializer[opt] compound-statement handler-seq 2409 /// 2410 Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) { 2411 assert(Tok.is(tok::kw_try) && "Expected 'try'"); 2412 SourceLocation TryLoc = ConsumeToken(); 2413 2414 PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc, 2415 "parsing function try block"); 2416 2417 // Constructor initializer list? 2418 if (Tok.is(tok::colon)) 2419 ParseConstructorInitializer(Decl); 2420 else 2421 Actions.ActOnDefaultCtorInitializers(Decl); 2422 2423 if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) && 2424 trySkippingFunctionBody()) { 2425 BodyScope.Exit(); 2426 return Actions.ActOnSkippedFunctionBody(Decl); 2427 } 2428 2429 SourceLocation LBraceLoc = Tok.getLocation(); 2430 StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true)); 2431 // If we failed to parse the try-catch, we just give the function an empty 2432 // compound statement as the body. 2433 if (FnBody.isInvalid()) { 2434 Sema::CompoundScopeRAII CompoundScope(Actions); 2435 FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, 2436 MultiStmtArg(), false); 2437 } 2438 2439 BodyScope.Exit(); 2440 return Actions.ActOnFinishFunctionBody(Decl, FnBody.take()); 2441 } 2442 2443 bool Parser::trySkippingFunctionBody() { 2444 assert(Tok.is(tok::l_brace)); 2445 assert(SkipFunctionBodies && 2446 "Should only be called when SkipFunctionBodies is enabled"); 2447 2448 if (!PP.isCodeCompletionEnabled()) { 2449 ConsumeBrace(); 2450 SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false); 2451 return true; 2452 } 2453 2454 // We're in code-completion mode. Skip parsing for all function bodies unless 2455 // the body contains the code-completion point. 2456 TentativeParsingAction PA(*this); 2457 ConsumeBrace(); 2458 if (SkipUntil(tok::r_brace, /*StopAtSemi=*/false, /*DontConsume=*/false, 2459 /*StopAtCodeCompletion=*/true)) { 2460 PA.Commit(); 2461 return true; 2462 } 2463 2464 PA.Revert(); 2465 return false; 2466 } 2467 2468 /// ParseCXXTryBlock - Parse a C++ try-block. 2469 /// 2470 /// try-block: 2471 /// 'try' compound-statement handler-seq 2472 /// 2473 StmtResult Parser::ParseCXXTryBlock() { 2474 assert(Tok.is(tok::kw_try) && "Expected 'try'"); 2475 2476 SourceLocation TryLoc = ConsumeToken(); 2477 return ParseCXXTryBlockCommon(TryLoc); 2478 } 2479 2480 /// ParseCXXTryBlockCommon - Parse the common part of try-block and 2481 /// function-try-block. 2482 /// 2483 /// try-block: 2484 /// 'try' compound-statement handler-seq 2485 /// 2486 /// function-try-block: 2487 /// 'try' ctor-initializer[opt] compound-statement handler-seq 2488 /// 2489 /// handler-seq: 2490 /// handler handler-seq[opt] 2491 /// 2492 /// [Borland] try-block: 2493 /// 'try' compound-statement seh-except-block 2494 /// 'try' compound-statment seh-finally-block 2495 /// 2496 StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) { 2497 if (Tok.isNot(tok::l_brace)) 2498 return StmtError(Diag(Tok, diag::err_expected_lbrace)); 2499 // FIXME: Possible draft standard bug: attribute-specifier should be allowed? 2500 2501 StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false, 2502 Scope::DeclScope | Scope::TryScope | 2503 (FnTry ? Scope::FnTryCatchScope : 0))); 2504 if (TryBlock.isInvalid()) 2505 return TryBlock; 2506 2507 // Borland allows SEH-handlers with 'try' 2508 2509 if ((Tok.is(tok::identifier) && 2510 Tok.getIdentifierInfo() == getSEHExceptKeyword()) || 2511 Tok.is(tok::kw___finally)) { 2512 // TODO: Factor into common return ParseSEHHandlerCommon(...) 2513 StmtResult Handler; 2514 if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) { 2515 SourceLocation Loc = ConsumeToken(); 2516 Handler = ParseSEHExceptBlock(Loc); 2517 } 2518 else { 2519 SourceLocation Loc = ConsumeToken(); 2520 Handler = ParseSEHFinallyBlock(Loc); 2521 } 2522 if(Handler.isInvalid()) 2523 return Handler; 2524 2525 return Actions.ActOnSEHTryBlock(true /* IsCXXTry */, 2526 TryLoc, 2527 TryBlock.take(), 2528 Handler.take()); 2529 } 2530 else { 2531 StmtVector Handlers; 2532 ParsedAttributesWithRange attrs(AttrFactory); 2533 MaybeParseCXX11Attributes(attrs); 2534 ProhibitAttributes(attrs); 2535 2536 if (Tok.isNot(tok::kw_catch)) 2537 return StmtError(Diag(Tok, diag::err_expected_catch)); 2538 while (Tok.is(tok::kw_catch)) { 2539 StmtResult Handler(ParseCXXCatchBlock(FnTry)); 2540 if (!Handler.isInvalid()) 2541 Handlers.push_back(Handler.release()); 2542 } 2543 // Don't bother creating the full statement if we don't have any usable 2544 // handlers. 2545 if (Handlers.empty()) 2546 return StmtError(); 2547 2548 return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.take(),Handlers); 2549 } 2550 } 2551 2552 /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard 2553 /// 2554 /// handler: 2555 /// 'catch' '(' exception-declaration ')' compound-statement 2556 /// 2557 /// exception-declaration: 2558 /// attribute-specifier-seq[opt] type-specifier-seq declarator 2559 /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt] 2560 /// '...' 2561 /// 2562 StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) { 2563 assert(Tok.is(tok::kw_catch) && "Expected 'catch'"); 2564 2565 SourceLocation CatchLoc = ConsumeToken(); 2566 2567 BalancedDelimiterTracker T(*this, tok::l_paren); 2568 if (T.expectAndConsume(diag::err_expected_lparen)) 2569 return StmtError(); 2570 2571 // C++ 3.3.2p3: 2572 // The name in a catch exception-declaration is local to the handler and 2573 // shall not be redeclared in the outermost block of the handler. 2574 ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope | 2575 (FnCatch ? Scope::FnTryCatchScope : 0)); 2576 2577 // exception-declaration is equivalent to '...' or a parameter-declaration 2578 // without default arguments. 2579 Decl *ExceptionDecl = 0; 2580 if (Tok.isNot(tok::ellipsis)) { 2581 ParsedAttributesWithRange Attributes(AttrFactory); 2582 MaybeParseCXX11Attributes(Attributes); 2583 2584 DeclSpec DS(AttrFactory); 2585 DS.takeAttributesFrom(Attributes); 2586 2587 if (ParseCXXTypeSpecifierSeq(DS)) 2588 return StmtError(); 2589 2590 Declarator ExDecl(DS, Declarator::CXXCatchContext); 2591 ParseDeclarator(ExDecl); 2592 ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl); 2593 } else 2594 ConsumeToken(); 2595 2596 T.consumeClose(); 2597 if (T.getCloseLocation().isInvalid()) 2598 return StmtError(); 2599 2600 if (Tok.isNot(tok::l_brace)) 2601 return StmtError(Diag(Tok, diag::err_expected_lbrace)); 2602 2603 // FIXME: Possible draft standard bug: attribute-specifier should be allowed? 2604 StmtResult Block(ParseCompoundStatement()); 2605 if (Block.isInvalid()) 2606 return Block; 2607 2608 return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.take()); 2609 } 2610 2611 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) { 2612 IfExistsCondition Result; 2613 if (ParseMicrosoftIfExistsCondition(Result)) 2614 return; 2615 2616 // Handle dependent statements by parsing the braces as a compound statement. 2617 // This is not the same behavior as Visual C++, which don't treat this as a 2618 // compound statement, but for Clang's type checking we can't have anything 2619 // inside these braces escaping to the surrounding code. 2620 if (Result.Behavior == IEB_Dependent) { 2621 if (!Tok.is(tok::l_brace)) { 2622 Diag(Tok, diag::err_expected_lbrace); 2623 return; 2624 } 2625 2626 StmtResult Compound = ParseCompoundStatement(); 2627 if (Compound.isInvalid()) 2628 return; 2629 2630 StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc, 2631 Result.IsIfExists, 2632 Result.SS, 2633 Result.Name, 2634 Compound.get()); 2635 if (DepResult.isUsable()) 2636 Stmts.push_back(DepResult.get()); 2637 return; 2638 } 2639 2640 BalancedDelimiterTracker Braces(*this, tok::l_brace); 2641 if (Braces.consumeOpen()) { 2642 Diag(Tok, diag::err_expected_lbrace); 2643 return; 2644 } 2645 2646 switch (Result.Behavior) { 2647 case IEB_Parse: 2648 // Parse the statements below. 2649 break; 2650 2651 case IEB_Dependent: 2652 llvm_unreachable("Dependent case handled above"); 2653 2654 case IEB_Skip: 2655 Braces.skipToEnd(); 2656 return; 2657 } 2658 2659 // Condition is true, parse the statements. 2660 while (Tok.isNot(tok::r_brace)) { 2661 StmtResult R = ParseStatementOrDeclaration(Stmts, false); 2662 if (R.isUsable()) 2663 Stmts.push_back(R.release()); 2664 } 2665 Braces.consumeClose(); 2666 } 2667