1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===// 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 contains code to emit Stmt nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/StmtVisitor.h" 19 #include "clang/Basic/PrettyStackTrace.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/InlineAsm.h" 23 #include "llvm/Intrinsics.h" 24 #include "llvm/DataLayout.h" 25 using namespace clang; 26 using namespace CodeGen; 27 28 //===----------------------------------------------------------------------===// 29 // Statement Emission 30 //===----------------------------------------------------------------------===// 31 32 void CodeGenFunction::EmitStopPoint(const Stmt *S) { 33 if (CGDebugInfo *DI = getDebugInfo()) { 34 SourceLocation Loc; 35 if (isa<DeclStmt>(S)) 36 Loc = S->getLocEnd(); 37 else 38 Loc = S->getLocStart(); 39 DI->EmitLocation(Builder, Loc); 40 } 41 } 42 43 void CodeGenFunction::EmitStmt(const Stmt *S) { 44 assert(S && "Null statement?"); 45 46 // These statements have their own debug info handling. 47 if (EmitSimpleStmt(S)) 48 return; 49 50 // Check if we are generating unreachable code. 51 if (!HaveInsertPoint()) { 52 // If so, and the statement doesn't contain a label, then we do not need to 53 // generate actual code. This is safe because (1) the current point is 54 // unreachable, so we don't need to execute the code, and (2) we've already 55 // handled the statements which update internal data structures (like the 56 // local variable map) which could be used by subsequent statements. 57 if (!ContainsLabel(S)) { 58 // Verify that any decl statements were handled as simple, they may be in 59 // scope of subsequent reachable statements. 60 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 61 return; 62 } 63 64 // Otherwise, make a new block to hold the code. 65 EnsureInsertPoint(); 66 } 67 68 // Generate a stoppoint if we are emitting debug info. 69 EmitStopPoint(S); 70 71 switch (S->getStmtClass()) { 72 case Stmt::NoStmtClass: 73 case Stmt::CXXCatchStmtClass: 74 case Stmt::SEHExceptStmtClass: 75 case Stmt::SEHFinallyStmtClass: 76 case Stmt::MSDependentExistsStmtClass: 77 llvm_unreachable("invalid statement class to emit generically"); 78 case Stmt::NullStmtClass: 79 case Stmt::CompoundStmtClass: 80 case Stmt::DeclStmtClass: 81 case Stmt::LabelStmtClass: 82 case Stmt::AttributedStmtClass: 83 case Stmt::GotoStmtClass: 84 case Stmt::BreakStmtClass: 85 case Stmt::ContinueStmtClass: 86 case Stmt::DefaultStmtClass: 87 case Stmt::CaseStmtClass: 88 llvm_unreachable("should have emitted these statements as simple"); 89 90 #define STMT(Type, Base) 91 #define ABSTRACT_STMT(Op) 92 #define EXPR(Type, Base) \ 93 case Stmt::Type##Class: 94 #include "clang/AST/StmtNodes.inc" 95 { 96 // Remember the block we came in on. 97 llvm::BasicBlock *incoming = Builder.GetInsertBlock(); 98 assert(incoming && "expression emission must have an insertion point"); 99 100 EmitIgnoredExpr(cast<Expr>(S)); 101 102 llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); 103 assert(outgoing && "expression emission cleared block!"); 104 105 // The expression emitters assume (reasonably!) that the insertion 106 // point is always set. To maintain that, the call-emission code 107 // for noreturn functions has to enter a new block with no 108 // predecessors. We want to kill that block and mark the current 109 // insertion point unreachable in the common case of a call like 110 // "exit();". Since expression emission doesn't otherwise create 111 // blocks with no predecessors, we can just test for that. 112 // However, we must be careful not to do this to our incoming 113 // block, because *statement* emission does sometimes create 114 // reachable blocks which will have no predecessors until later in 115 // the function. This occurs with, e.g., labels that are not 116 // reachable by fallthrough. 117 if (incoming != outgoing && outgoing->use_empty()) { 118 outgoing->eraseFromParent(); 119 Builder.ClearInsertionPoint(); 120 } 121 break; 122 } 123 124 case Stmt::IndirectGotoStmtClass: 125 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 126 127 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 128 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break; 129 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break; 130 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break; 131 132 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 133 134 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 135 case Stmt::GCCAsmStmtClass: // Intentional fall-through. 136 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 137 138 case Stmt::ObjCAtTryStmtClass: 139 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 140 break; 141 case Stmt::ObjCAtCatchStmtClass: 142 llvm_unreachable( 143 "@catch statements should be handled by EmitObjCAtTryStmt"); 144 case Stmt::ObjCAtFinallyStmtClass: 145 llvm_unreachable( 146 "@finally statements should be handled by EmitObjCAtTryStmt"); 147 case Stmt::ObjCAtThrowStmtClass: 148 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 149 break; 150 case Stmt::ObjCAtSynchronizedStmtClass: 151 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 152 break; 153 case Stmt::ObjCForCollectionStmtClass: 154 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 155 break; 156 case Stmt::ObjCAutoreleasePoolStmtClass: 157 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S)); 158 break; 159 160 case Stmt::CXXTryStmtClass: 161 EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 162 break; 163 case Stmt::CXXForRangeStmtClass: 164 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S)); 165 case Stmt::SEHTryStmtClass: 166 // FIXME Not yet implemented 167 break; 168 } 169 } 170 171 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) { 172 switch (S->getStmtClass()) { 173 default: return false; 174 case Stmt::NullStmtClass: break; 175 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break; 176 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break; 177 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break; 178 case Stmt::AttributedStmtClass: 179 EmitAttributedStmt(cast<AttributedStmt>(*S)); break; 180 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break; 181 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break; 182 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break; 183 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break; 184 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break; 185 } 186 187 return true; 188 } 189 190 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 191 /// this captures the expression result of the last sub-statement and returns it 192 /// (for use by the statement expression extension). 193 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 194 AggValueSlot AggSlot) { 195 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 196 "LLVM IR generation of compound statement ('{}')"); 197 198 // Keep track of the current cleanup stack depth, including debug scopes. 199 LexicalScope Scope(*this, S.getSourceRange()); 200 201 for (CompoundStmt::const_body_iterator I = S.body_begin(), 202 E = S.body_end()-GetLast; I != E; ++I) 203 EmitStmt(*I); 204 205 RValue RV; 206 if (!GetLast) 207 RV = RValue::get(0); 208 else { 209 // We have to special case labels here. They are statements, but when put 210 // at the end of a statement expression, they yield the value of their 211 // subexpression. Handle this by walking through all labels we encounter, 212 // emitting them before we evaluate the subexpr. 213 const Stmt *LastStmt = S.body_back(); 214 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) { 215 EmitLabel(LS->getDecl()); 216 LastStmt = LS->getSubStmt(); 217 } 218 219 EnsureInsertPoint(); 220 221 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot); 222 } 223 224 return RV; 225 } 226 227 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 228 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 229 230 // If there is a cleanup stack, then we it isn't worth trying to 231 // simplify this block (we would need to remove it from the scope map 232 // and cleanup entry). 233 if (!EHStack.empty()) 234 return; 235 236 // Can only simplify direct branches. 237 if (!BI || !BI->isUnconditional()) 238 return; 239 240 // Can only simplify empty blocks. 241 if (BI != BB->begin()) 242 return; 243 244 BB->replaceAllUsesWith(BI->getSuccessor(0)); 245 BI->eraseFromParent(); 246 BB->eraseFromParent(); 247 } 248 249 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 250 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 251 252 // Fall out of the current block (if necessary). 253 EmitBranch(BB); 254 255 if (IsFinished && BB->use_empty()) { 256 delete BB; 257 return; 258 } 259 260 // Place the block after the current block, if possible, or else at 261 // the end of the function. 262 if (CurBB && CurBB->getParent()) 263 CurFn->getBasicBlockList().insertAfter(CurBB, BB); 264 else 265 CurFn->getBasicBlockList().push_back(BB); 266 Builder.SetInsertPoint(BB); 267 } 268 269 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 270 // Emit a branch from the current block to the target one if this 271 // was a real block. If this was just a fall-through block after a 272 // terminator, don't emit it. 273 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 274 275 if (!CurBB || CurBB->getTerminator()) { 276 // If there is no insert point or the previous block is already 277 // terminated, don't touch it. 278 } else { 279 // Otherwise, create a fall-through branch. 280 Builder.CreateBr(Target); 281 } 282 283 Builder.ClearInsertionPoint(); 284 } 285 286 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) { 287 bool inserted = false; 288 for (llvm::BasicBlock::use_iterator 289 i = block->use_begin(), e = block->use_end(); i != e; ++i) { 290 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) { 291 CurFn->getBasicBlockList().insertAfter(insn->getParent(), block); 292 inserted = true; 293 break; 294 } 295 } 296 297 if (!inserted) 298 CurFn->getBasicBlockList().push_back(block); 299 300 Builder.SetInsertPoint(block); 301 } 302 303 CodeGenFunction::JumpDest 304 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) { 305 JumpDest &Dest = LabelMap[D]; 306 if (Dest.isValid()) return Dest; 307 308 // Create, but don't insert, the new block. 309 Dest = JumpDest(createBasicBlock(D->getName()), 310 EHScopeStack::stable_iterator::invalid(), 311 NextCleanupDestIndex++); 312 return Dest; 313 } 314 315 void CodeGenFunction::EmitLabel(const LabelDecl *D) { 316 JumpDest &Dest = LabelMap[D]; 317 318 // If we didn't need a forward reference to this label, just go 319 // ahead and create a destination at the current scope. 320 if (!Dest.isValid()) { 321 Dest = getJumpDestInCurrentScope(D->getName()); 322 323 // Otherwise, we need to give this label a target depth and remove 324 // it from the branch-fixups list. 325 } else { 326 assert(!Dest.getScopeDepth().isValid() && "already emitted label!"); 327 Dest = JumpDest(Dest.getBlock(), 328 EHStack.stable_begin(), 329 Dest.getDestIndex()); 330 331 ResolveBranchFixups(Dest.getBlock()); 332 } 333 334 EmitBlock(Dest.getBlock()); 335 } 336 337 338 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 339 EmitLabel(S.getDecl()); 340 EmitStmt(S.getSubStmt()); 341 } 342 343 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) { 344 EmitStmt(S.getSubStmt()); 345 } 346 347 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 348 // If this code is reachable then emit a stop point (if generating 349 // debug info). We have to do this ourselves because we are on the 350 // "simple" statement path. 351 if (HaveInsertPoint()) 352 EmitStopPoint(&S); 353 354 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel())); 355 } 356 357 358 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 359 if (const LabelDecl *Target = S.getConstantTarget()) { 360 EmitBranchThroughCleanup(getJumpDestForLabel(Target)); 361 return; 362 } 363 364 // Ensure that we have an i8* for our PHI node. 365 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 366 Int8PtrTy, "addr"); 367 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 368 369 // Get the basic block for the indirect goto. 370 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 371 372 // The first instruction in the block has to be the PHI for the switch dest, 373 // add an entry for this branch. 374 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 375 376 EmitBranch(IndGotoBB); 377 } 378 379 void CodeGenFunction::EmitIfStmt(const IfStmt &S) { 380 // C99 6.8.4.1: The first substatement is executed if the expression compares 381 // unequal to 0. The condition must be a scalar type. 382 RunCleanupsScope ConditionScope(*this); 383 384 if (S.getConditionVariable()) 385 EmitAutoVarDecl(*S.getConditionVariable()); 386 387 // If the condition constant folds and can be elided, try to avoid emitting 388 // the condition and the dead arm of the if/else. 389 bool CondConstant; 390 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) { 391 // Figure out which block (then or else) is executed. 392 const Stmt *Executed = S.getThen(); 393 const Stmt *Skipped = S.getElse(); 394 if (!CondConstant) // Condition false? 395 std::swap(Executed, Skipped); 396 397 // If the skipped block has no labels in it, just emit the executed block. 398 // This avoids emitting dead code and simplifies the CFG substantially. 399 if (!ContainsLabel(Skipped)) { 400 if (Executed) { 401 RunCleanupsScope ExecutedScope(*this); 402 EmitStmt(Executed); 403 } 404 return; 405 } 406 } 407 408 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 409 // the conditional branch. 410 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 411 llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 412 llvm::BasicBlock *ElseBlock = ContBlock; 413 if (S.getElse()) 414 ElseBlock = createBasicBlock("if.else"); 415 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock); 416 417 // Emit the 'then' code. 418 EmitBlock(ThenBlock); 419 { 420 RunCleanupsScope ThenScope(*this); 421 EmitStmt(S.getThen()); 422 } 423 EmitBranch(ContBlock); 424 425 // Emit the 'else' code if present. 426 if (const Stmt *Else = S.getElse()) { 427 // There is no need to emit line number for unconditional branch. 428 if (getDebugInfo()) 429 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 430 EmitBlock(ElseBlock); 431 { 432 RunCleanupsScope ElseScope(*this); 433 EmitStmt(Else); 434 } 435 // There is no need to emit line number for unconditional branch. 436 if (getDebugInfo()) 437 Builder.SetCurrentDebugLocation(llvm::DebugLoc()); 438 EmitBranch(ContBlock); 439 } 440 441 // Emit the continuation block for code after the if. 442 EmitBlock(ContBlock, true); 443 } 444 445 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { 446 // Emit the header for the loop, which will also become 447 // the continue target. 448 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond"); 449 EmitBlock(LoopHeader.getBlock()); 450 451 // Create an exit block for when the condition fails, which will 452 // also become the break target. 453 JumpDest LoopExit = getJumpDestInCurrentScope("while.end"); 454 455 // Store the blocks to use for break and continue. 456 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader)); 457 458 // C++ [stmt.while]p2: 459 // When the condition of a while statement is a declaration, the 460 // scope of the variable that is declared extends from its point 461 // of declaration (3.3.2) to the end of the while statement. 462 // [...] 463 // The object created in a condition is destroyed and created 464 // with each iteration of the loop. 465 RunCleanupsScope ConditionScope(*this); 466 467 if (S.getConditionVariable()) 468 EmitAutoVarDecl(*S.getConditionVariable()); 469 470 // Evaluate the conditional in the while header. C99 6.8.5.1: The 471 // evaluation of the controlling expression takes place before each 472 // execution of the loop body. 473 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 474 475 // while(1) is common, avoid extra exit blocks. Be sure 476 // to correctly handle break/continue though. 477 bool EmitBoolCondBranch = true; 478 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 479 if (C->isOne()) 480 EmitBoolCondBranch = false; 481 482 // As long as the condition is true, go to the loop body. 483 llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 484 if (EmitBoolCondBranch) { 485 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 486 if (ConditionScope.requiresCleanups()) 487 ExitBlock = createBasicBlock("while.exit"); 488 489 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 490 491 if (ExitBlock != LoopExit.getBlock()) { 492 EmitBlock(ExitBlock); 493 EmitBranchThroughCleanup(LoopExit); 494 } 495 } 496 497 // Emit the loop body. We have to emit this in a cleanup scope 498 // because it might be a singleton DeclStmt. 499 { 500 RunCleanupsScope BodyScope(*this); 501 EmitBlock(LoopBody); 502 EmitStmt(S.getBody()); 503 } 504 505 BreakContinueStack.pop_back(); 506 507 // Immediately force cleanup. 508 ConditionScope.ForceCleanup(); 509 510 // Branch to the loop header again. 511 EmitBranch(LoopHeader.getBlock()); 512 513 // Emit the exit block. 514 EmitBlock(LoopExit.getBlock(), true); 515 516 // The LoopHeader typically is just a branch if we skipped emitting 517 // a branch, try to erase it. 518 if (!EmitBoolCondBranch) 519 SimplifyForwardingBlocks(LoopHeader.getBlock()); 520 } 521 522 void CodeGenFunction::EmitDoStmt(const DoStmt &S) { 523 JumpDest LoopExit = getJumpDestInCurrentScope("do.end"); 524 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond"); 525 526 // Store the blocks to use for break and continue. 527 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond)); 528 529 // Emit the body of the loop. 530 llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 531 EmitBlock(LoopBody); 532 { 533 RunCleanupsScope BodyScope(*this); 534 EmitStmt(S.getBody()); 535 } 536 537 BreakContinueStack.pop_back(); 538 539 EmitBlock(LoopCond.getBlock()); 540 541 // C99 6.8.5.2: "The evaluation of the controlling expression takes place 542 // after each execution of the loop body." 543 544 // Evaluate the conditional in the while header. 545 // C99 6.8.5p2/p4: The first substatement is executed if the expression 546 // compares unequal to 0. The condition must be a scalar type. 547 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 548 549 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 550 // to correctly handle break/continue though. 551 bool EmitBoolCondBranch = true; 552 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 553 if (C->isZero()) 554 EmitBoolCondBranch = false; 555 556 // As long as the condition is true, iterate the loop. 557 if (EmitBoolCondBranch) 558 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock()); 559 560 // Emit the exit block. 561 EmitBlock(LoopExit.getBlock()); 562 563 // The DoCond block typically is just a branch if we skipped 564 // emitting a branch, try to erase it. 565 if (!EmitBoolCondBranch) 566 SimplifyForwardingBlocks(LoopCond.getBlock()); 567 } 568 569 void CodeGenFunction::EmitForStmt(const ForStmt &S) { 570 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 571 572 RunCleanupsScope ForScope(*this); 573 574 CGDebugInfo *DI = getDebugInfo(); 575 if (DI) 576 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 577 578 // Evaluate the first part before the loop. 579 if (S.getInit()) 580 EmitStmt(S.getInit()); 581 582 // Start the loop with a block that tests the condition. 583 // If there's an increment, the continue scope will be overwritten 584 // later. 585 JumpDest Continue = getJumpDestInCurrentScope("for.cond"); 586 llvm::BasicBlock *CondBlock = Continue.getBlock(); 587 EmitBlock(CondBlock); 588 589 // Create a cleanup scope for the condition variable cleanups. 590 RunCleanupsScope ConditionScope(*this); 591 592 llvm::Value *BoolCondVal = 0; 593 if (S.getCond()) { 594 // If the for statement has a condition scope, emit the local variable 595 // declaration. 596 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 597 if (S.getConditionVariable()) { 598 EmitAutoVarDecl(*S.getConditionVariable()); 599 } 600 601 // If there are any cleanups between here and the loop-exit scope, 602 // create a block to stage a loop exit along. 603 if (ForScope.requiresCleanups()) 604 ExitBlock = createBasicBlock("for.cond.cleanup"); 605 606 // As long as the condition is true, iterate the loop. 607 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 608 609 // C99 6.8.5p2/p4: The first substatement is executed if the expression 610 // compares unequal to 0. The condition must be a scalar type. 611 BoolCondVal = EvaluateExprAsBool(S.getCond()); 612 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock); 613 614 if (ExitBlock != LoopExit.getBlock()) { 615 EmitBlock(ExitBlock); 616 EmitBranchThroughCleanup(LoopExit); 617 } 618 619 EmitBlock(ForBody); 620 } else { 621 // Treat it as a non-zero constant. Don't even create a new block for the 622 // body, just fall into it. 623 } 624 625 // If the for loop doesn't have an increment we can just use the 626 // condition as the continue block. Otherwise we'll need to create 627 // a block for it (in the current scope, i.e. in the scope of the 628 // condition), and that we will become our continue block. 629 if (S.getInc()) 630 Continue = getJumpDestInCurrentScope("for.inc"); 631 632 // Store the blocks to use for break and continue. 633 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 634 635 { 636 // Create a separate cleanup scope for the body, in case it is not 637 // a compound statement. 638 RunCleanupsScope BodyScope(*this); 639 EmitStmt(S.getBody()); 640 } 641 642 // If there is an increment, emit it next. 643 if (S.getInc()) { 644 EmitBlock(Continue.getBlock()); 645 EmitStmt(S.getInc()); 646 } 647 648 BreakContinueStack.pop_back(); 649 650 ConditionScope.ForceCleanup(); 651 EmitBranch(CondBlock); 652 653 ForScope.ForceCleanup(); 654 655 if (DI) 656 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 657 658 // Emit the fall-through block. 659 EmitBlock(LoopExit.getBlock(), true); 660 } 661 662 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) { 663 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 664 665 RunCleanupsScope ForScope(*this); 666 667 CGDebugInfo *DI = getDebugInfo(); 668 if (DI) 669 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin()); 670 671 // Evaluate the first pieces before the loop. 672 EmitStmt(S.getRangeStmt()); 673 EmitStmt(S.getBeginEndStmt()); 674 675 // Start the loop with a block that tests the condition. 676 // If there's an increment, the continue scope will be overwritten 677 // later. 678 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 679 EmitBlock(CondBlock); 680 681 // If there are any cleanups between here and the loop-exit scope, 682 // create a block to stage a loop exit along. 683 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 684 if (ForScope.requiresCleanups()) 685 ExitBlock = createBasicBlock("for.cond.cleanup"); 686 687 // The loop body, consisting of the specified body and the loop variable. 688 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 689 690 // The body is executed if the expression, contextually converted 691 // to bool, is true. 692 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 693 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock); 694 695 if (ExitBlock != LoopExit.getBlock()) { 696 EmitBlock(ExitBlock); 697 EmitBranchThroughCleanup(LoopExit); 698 } 699 700 EmitBlock(ForBody); 701 702 // Create a block for the increment. In case of a 'continue', we jump there. 703 JumpDest Continue = getJumpDestInCurrentScope("for.inc"); 704 705 // Store the blocks to use for break and continue. 706 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 707 708 { 709 // Create a separate cleanup scope for the loop variable and body. 710 RunCleanupsScope BodyScope(*this); 711 EmitStmt(S.getLoopVarStmt()); 712 EmitStmt(S.getBody()); 713 } 714 715 // If there is an increment, emit it next. 716 EmitBlock(Continue.getBlock()); 717 EmitStmt(S.getInc()); 718 719 BreakContinueStack.pop_back(); 720 721 EmitBranch(CondBlock); 722 723 ForScope.ForceCleanup(); 724 725 if (DI) 726 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd()); 727 728 // Emit the fall-through block. 729 EmitBlock(LoopExit.getBlock(), true); 730 } 731 732 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 733 if (RV.isScalar()) { 734 Builder.CreateStore(RV.getScalarVal(), ReturnValue); 735 } else if (RV.isAggregate()) { 736 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty); 737 } else { 738 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false); 739 } 740 EmitBranchThroughCleanup(ReturnBlock); 741 } 742 743 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 744 /// if the function returns void, or may be missing one if the function returns 745 /// non-void. Fun stuff :). 746 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 747 // Emit the result value, even if unused, to evalute the side effects. 748 const Expr *RV = S.getRetValue(); 749 750 // Treat block literals in a return expression as if they appeared 751 // in their own scope. This permits a small, easily-implemented 752 // exception to our over-conservative rules about not jumping to 753 // statements following block literals with non-trivial cleanups. 754 RunCleanupsScope cleanupScope(*this); 755 if (const ExprWithCleanups *cleanups = 756 dyn_cast_or_null<ExprWithCleanups>(RV)) { 757 enterFullExpression(cleanups); 758 RV = cleanups->getSubExpr(); 759 } 760 761 // FIXME: Clean this up by using an LValue for ReturnTemp, 762 // EmitStoreThroughLValue, and EmitAnyExpr. 763 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() && 764 !Target.useGlobalsForAutomaticVariables()) { 765 // Apply the named return value optimization for this return statement, 766 // which means doing nothing: the appropriate result has already been 767 // constructed into the NRVO variable. 768 769 // If there is an NRVO flag for this variable, set it to 1 into indicate 770 // that the cleanup code should not destroy the variable. 771 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) 772 Builder.CreateStore(Builder.getTrue(), NRVOFlag); 773 } else if (!ReturnValue) { 774 // Make sure not to return anything, but evaluate the expression 775 // for side effects. 776 if (RV) 777 EmitAnyExpr(RV); 778 } else if (RV == 0) { 779 // Do nothing (return value is left uninitialized) 780 } else if (FnRetTy->isReferenceType()) { 781 // If this function returns a reference, take the address of the expression 782 // rather than the value. 783 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0); 784 Builder.CreateStore(Result.getScalarVal(), ReturnValue); 785 } else if (!hasAggregateLLVMType(RV->getType())) { 786 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 787 } else if (RV->getType()->isAnyComplexType()) { 788 EmitComplexExprIntoAddr(RV, ReturnValue, false); 789 } else { 790 CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType()); 791 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment, Qualifiers(), 792 AggValueSlot::IsDestructed, 793 AggValueSlot::DoesNotNeedGCBarriers, 794 AggValueSlot::IsNotAliased)); 795 } 796 797 cleanupScope.ForceCleanup(); 798 EmitBranchThroughCleanup(ReturnBlock); 799 } 800 801 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 802 // As long as debug info is modeled with instructions, we have to ensure we 803 // have a place to insert here and write the stop point here. 804 if (HaveInsertPoint()) 805 EmitStopPoint(&S); 806 807 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end(); 808 I != E; ++I) 809 EmitDecl(**I); 810 } 811 812 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 813 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 814 815 // If this code is reachable then emit a stop point (if generating 816 // debug info). We have to do this ourselves because we are on the 817 // "simple" statement path. 818 if (HaveInsertPoint()) 819 EmitStopPoint(&S); 820 821 JumpDest Block = BreakContinueStack.back().BreakBlock; 822 EmitBranchThroughCleanup(Block); 823 } 824 825 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 826 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 827 828 // If this code is reachable then emit a stop point (if generating 829 // debug info). We have to do this ourselves because we are on the 830 // "simple" statement path. 831 if (HaveInsertPoint()) 832 EmitStopPoint(&S); 833 834 JumpDest Block = BreakContinueStack.back().ContinueBlock; 835 EmitBranchThroughCleanup(Block); 836 } 837 838 /// EmitCaseStmtRange - If case statement range is not too big then 839 /// add multiple cases to switch instruction, one for each value within 840 /// the range. If range is too big then emit "if" condition check. 841 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { 842 assert(S.getRHS() && "Expected RHS value in CaseStmt"); 843 844 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext()); 845 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext()); 846 847 // Emit the code for this case. We do this first to make sure it is 848 // properly chained from our predecessor before generating the 849 // switch machinery to enter this block. 850 EmitBlock(createBasicBlock("sw.bb")); 851 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 852 EmitStmt(S.getSubStmt()); 853 854 // If range is empty, do nothing. 855 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 856 return; 857 858 llvm::APInt Range = RHS - LHS; 859 // FIXME: parameters such as this should not be hardcoded. 860 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 861 // Range is small enough to add multiple switch instruction cases. 862 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) { 863 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest); 864 LHS++; 865 } 866 return; 867 } 868 869 // The range is too big. Emit "if" condition into a new block, 870 // making sure to save and restore the current insertion point. 871 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 872 873 // Push this test onto the chain of range checks (which terminates 874 // in the default basic block). The switch's default will be changed 875 // to the top of this chain after switch emission is complete. 876 llvm::BasicBlock *FalseDest = CaseRangeBlock; 877 CaseRangeBlock = createBasicBlock("sw.caserange"); 878 879 CurFn->getBasicBlockList().push_back(CaseRangeBlock); 880 Builder.SetInsertPoint(CaseRangeBlock); 881 882 // Emit range check. 883 llvm::Value *Diff = 884 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS)); 885 llvm::Value *Cond = 886 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds"); 887 Builder.CreateCondBr(Cond, CaseDest, FalseDest); 888 889 // Restore the appropriate insertion point. 890 if (RestoreBB) 891 Builder.SetInsertPoint(RestoreBB); 892 else 893 Builder.ClearInsertionPoint(); 894 } 895 896 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { 897 // If there is no enclosing switch instance that we're aware of, then this 898 // case statement and its block can be elided. This situation only happens 899 // when we've constant-folded the switch, are emitting the constant case, 900 // and part of the constant case includes another case statement. For 901 // instance: switch (4) { case 4: do { case 5: } while (1); } 902 if (!SwitchInsn) { 903 EmitStmt(S.getSubStmt()); 904 return; 905 } 906 907 // Handle case ranges. 908 if (S.getRHS()) { 909 EmitCaseStmtRange(S); 910 return; 911 } 912 913 llvm::ConstantInt *CaseVal = 914 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext())); 915 916 // If the body of the case is just a 'break', and if there was no fallthrough, 917 // try to not emit an empty block. 918 if ((CGM.getCodeGenOpts().OptimizationLevel > 0) && 919 isa<BreakStmt>(S.getSubStmt())) { 920 JumpDest Block = BreakContinueStack.back().BreakBlock; 921 922 // Only do this optimization if there are no cleanups that need emitting. 923 if (isObviouslyBranchWithoutCleanups(Block)) { 924 SwitchInsn->addCase(CaseVal, Block.getBlock()); 925 926 // If there was a fallthrough into this case, make sure to redirect it to 927 // the end of the switch as well. 928 if (Builder.GetInsertBlock()) { 929 Builder.CreateBr(Block.getBlock()); 930 Builder.ClearInsertionPoint(); 931 } 932 return; 933 } 934 } 935 936 EmitBlock(createBasicBlock("sw.bb")); 937 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 938 SwitchInsn->addCase(CaseVal, CaseDest); 939 940 // Recursively emitting the statement is acceptable, but is not wonderful for 941 // code where we have many case statements nested together, i.e.: 942 // case 1: 943 // case 2: 944 // case 3: etc. 945 // Handling this recursively will create a new block for each case statement 946 // that falls through to the next case which is IR intensive. It also causes 947 // deep recursion which can run into stack depth limitations. Handle 948 // sequential non-range case statements specially. 949 const CaseStmt *CurCase = &S; 950 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 951 952 // Otherwise, iteratively add consecutive cases to this switch stmt. 953 while (NextCase && NextCase->getRHS() == 0) { 954 CurCase = NextCase; 955 llvm::ConstantInt *CaseVal = 956 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext())); 957 SwitchInsn->addCase(CaseVal, CaseDest); 958 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 959 } 960 961 // Normal default recursion for non-cases. 962 EmitStmt(CurCase->getSubStmt()); 963 } 964 965 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) { 966 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 967 assert(DefaultBlock->empty() && 968 "EmitDefaultStmt: Default block already defined?"); 969 EmitBlock(DefaultBlock); 970 EmitStmt(S.getSubStmt()); 971 } 972 973 /// CollectStatementsForCase - Given the body of a 'switch' statement and a 974 /// constant value that is being switched on, see if we can dead code eliminate 975 /// the body of the switch to a simple series of statements to emit. Basically, 976 /// on a switch (5) we want to find these statements: 977 /// case 5: 978 /// printf(...); <-- 979 /// ++i; <-- 980 /// break; 981 /// 982 /// and add them to the ResultStmts vector. If it is unsafe to do this 983 /// transformation (for example, one of the elided statements contains a label 984 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S' 985 /// should include statements after it (e.g. the printf() line is a substmt of 986 /// the case) then return CSFC_FallThrough. If we handled it and found a break 987 /// statement, then return CSFC_Success. 988 /// 989 /// If Case is non-null, then we are looking for the specified case, checking 990 /// that nothing we jump over contains labels. If Case is null, then we found 991 /// the case and are looking for the break. 992 /// 993 /// If the recursive walk actually finds our Case, then we set FoundCase to 994 /// true. 995 /// 996 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success }; 997 static CSFC_Result CollectStatementsForCase(const Stmt *S, 998 const SwitchCase *Case, 999 bool &FoundCase, 1000 SmallVectorImpl<const Stmt*> &ResultStmts) { 1001 // If this is a null statement, just succeed. 1002 if (S == 0) 1003 return Case ? CSFC_Success : CSFC_FallThrough; 1004 1005 // If this is the switchcase (case 4: or default) that we're looking for, then 1006 // we're in business. Just add the substatement. 1007 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) { 1008 if (S == Case) { 1009 FoundCase = true; 1010 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase, 1011 ResultStmts); 1012 } 1013 1014 // Otherwise, this is some other case or default statement, just ignore it. 1015 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase, 1016 ResultStmts); 1017 } 1018 1019 // If we are in the live part of the code and we found our break statement, 1020 // return a success! 1021 if (Case == 0 && isa<BreakStmt>(S)) 1022 return CSFC_Success; 1023 1024 // If this is a switch statement, then it might contain the SwitchCase, the 1025 // break, or neither. 1026 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1027 // Handle this as two cases: we might be looking for the SwitchCase (if so 1028 // the skipped statements must be skippable) or we might already have it. 1029 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end(); 1030 if (Case) { 1031 // Keep track of whether we see a skipped declaration. The code could be 1032 // using the declaration even if it is skipped, so we can't optimize out 1033 // the decl if the kept statements might refer to it. 1034 bool HadSkippedDecl = false; 1035 1036 // If we're looking for the case, just see if we can skip each of the 1037 // substatements. 1038 for (; Case && I != E; ++I) { 1039 HadSkippedDecl |= isa<DeclStmt>(*I); 1040 1041 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) { 1042 case CSFC_Failure: return CSFC_Failure; 1043 case CSFC_Success: 1044 // A successful result means that either 1) that the statement doesn't 1045 // have the case and is skippable, or 2) does contain the case value 1046 // and also contains the break to exit the switch. In the later case, 1047 // we just verify the rest of the statements are elidable. 1048 if (FoundCase) { 1049 // If we found the case and skipped declarations, we can't do the 1050 // optimization. 1051 if (HadSkippedDecl) 1052 return CSFC_Failure; 1053 1054 for (++I; I != E; ++I) 1055 if (CodeGenFunction::ContainsLabel(*I, true)) 1056 return CSFC_Failure; 1057 return CSFC_Success; 1058 } 1059 break; 1060 case CSFC_FallThrough: 1061 // If we have a fallthrough condition, then we must have found the 1062 // case started to include statements. Consider the rest of the 1063 // statements in the compound statement as candidates for inclusion. 1064 assert(FoundCase && "Didn't find case but returned fallthrough?"); 1065 // We recursively found Case, so we're not looking for it anymore. 1066 Case = 0; 1067 1068 // If we found the case and skipped declarations, we can't do the 1069 // optimization. 1070 if (HadSkippedDecl) 1071 return CSFC_Failure; 1072 break; 1073 } 1074 } 1075 } 1076 1077 // If we have statements in our range, then we know that the statements are 1078 // live and need to be added to the set of statements we're tracking. 1079 for (; I != E; ++I) { 1080 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) { 1081 case CSFC_Failure: return CSFC_Failure; 1082 case CSFC_FallThrough: 1083 // A fallthrough result means that the statement was simple and just 1084 // included in ResultStmt, keep adding them afterwards. 1085 break; 1086 case CSFC_Success: 1087 // A successful result means that we found the break statement and 1088 // stopped statement inclusion. We just ensure that any leftover stmts 1089 // are skippable and return success ourselves. 1090 for (++I; I != E; ++I) 1091 if (CodeGenFunction::ContainsLabel(*I, true)) 1092 return CSFC_Failure; 1093 return CSFC_Success; 1094 } 1095 } 1096 1097 return Case ? CSFC_Success : CSFC_FallThrough; 1098 } 1099 1100 // Okay, this is some other statement that we don't handle explicitly, like a 1101 // for statement or increment etc. If we are skipping over this statement, 1102 // just verify it doesn't have labels, which would make it invalid to elide. 1103 if (Case) { 1104 if (CodeGenFunction::ContainsLabel(S, true)) 1105 return CSFC_Failure; 1106 return CSFC_Success; 1107 } 1108 1109 // Otherwise, we want to include this statement. Everything is cool with that 1110 // so long as it doesn't contain a break out of the switch we're in. 1111 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure; 1112 1113 // Otherwise, everything is great. Include the statement and tell the caller 1114 // that we fall through and include the next statement as well. 1115 ResultStmts.push_back(S); 1116 return CSFC_FallThrough; 1117 } 1118 1119 /// FindCaseStatementsForValue - Find the case statement being jumped to and 1120 /// then invoke CollectStatementsForCase to find the list of statements to emit 1121 /// for a switch on constant. See the comment above CollectStatementsForCase 1122 /// for more details. 1123 static bool FindCaseStatementsForValue(const SwitchStmt &S, 1124 const llvm::APSInt &ConstantCondValue, 1125 SmallVectorImpl<const Stmt*> &ResultStmts, 1126 ASTContext &C) { 1127 // First step, find the switch case that is being branched to. We can do this 1128 // efficiently by scanning the SwitchCase list. 1129 const SwitchCase *Case = S.getSwitchCaseList(); 1130 const DefaultStmt *DefaultCase = 0; 1131 1132 for (; Case; Case = Case->getNextSwitchCase()) { 1133 // It's either a default or case. Just remember the default statement in 1134 // case we're not jumping to any numbered cases. 1135 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) { 1136 DefaultCase = DS; 1137 continue; 1138 } 1139 1140 // Check to see if this case is the one we're looking for. 1141 const CaseStmt *CS = cast<CaseStmt>(Case); 1142 // Don't handle case ranges yet. 1143 if (CS->getRHS()) return false; 1144 1145 // If we found our case, remember it as 'case'. 1146 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue) 1147 break; 1148 } 1149 1150 // If we didn't find a matching case, we use a default if it exists, or we 1151 // elide the whole switch body! 1152 if (Case == 0) { 1153 // It is safe to elide the body of the switch if it doesn't contain labels 1154 // etc. If it is safe, return successfully with an empty ResultStmts list. 1155 if (DefaultCase == 0) 1156 return !CodeGenFunction::ContainsLabel(&S); 1157 Case = DefaultCase; 1158 } 1159 1160 // Ok, we know which case is being jumped to, try to collect all the 1161 // statements that follow it. This can fail for a variety of reasons. Also, 1162 // check to see that the recursive walk actually found our case statement. 1163 // Insane cases like this can fail to find it in the recursive walk since we 1164 // don't handle every stmt kind: 1165 // switch (4) { 1166 // while (1) { 1167 // case 4: ... 1168 bool FoundCase = false; 1169 return CollectStatementsForCase(S.getBody(), Case, FoundCase, 1170 ResultStmts) != CSFC_Failure && 1171 FoundCase; 1172 } 1173 1174 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 1175 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog"); 1176 1177 RunCleanupsScope ConditionScope(*this); 1178 1179 if (S.getConditionVariable()) 1180 EmitAutoVarDecl(*S.getConditionVariable()); 1181 1182 // Handle nested switch statements. 1183 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 1184 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 1185 1186 // See if we can constant fold the condition of the switch and therefore only 1187 // emit the live case statement (if any) of the switch. 1188 llvm::APSInt ConstantCondValue; 1189 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) { 1190 SmallVector<const Stmt*, 4> CaseStmts; 1191 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts, 1192 getContext())) { 1193 RunCleanupsScope ExecutedScope(*this); 1194 1195 // At this point, we are no longer "within" a switch instance, so 1196 // we can temporarily enforce this to ensure that any embedded case 1197 // statements are not emitted. 1198 SwitchInsn = 0; 1199 1200 // Okay, we can dead code eliminate everything except this case. Emit the 1201 // specified series of statements and we're good. 1202 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i) 1203 EmitStmt(CaseStmts[i]); 1204 1205 // Now we want to restore the saved switch instance so that nested 1206 // switches continue to function properly 1207 SwitchInsn = SavedSwitchInsn; 1208 1209 return; 1210 } 1211 } 1212 1213 llvm::Value *CondV = EmitScalarExpr(S.getCond()); 1214 1215 // Create basic block to hold stuff that comes after switch 1216 // statement. We also need to create a default block now so that 1217 // explicit case ranges tests can have a place to jump to on 1218 // failure. 1219 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 1220 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 1221 CaseRangeBlock = DefaultBlock; 1222 1223 // Clear the insertion point to indicate we are in unreachable code. 1224 Builder.ClearInsertionPoint(); 1225 1226 // All break statements jump to NextBlock. If BreakContinueStack is non empty 1227 // then reuse last ContinueBlock. 1228 JumpDest OuterContinue; 1229 if (!BreakContinueStack.empty()) 1230 OuterContinue = BreakContinueStack.back().ContinueBlock; 1231 1232 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue)); 1233 1234 // Emit switch body. 1235 EmitStmt(S.getBody()); 1236 1237 BreakContinueStack.pop_back(); 1238 1239 // Update the default block in case explicit case range tests have 1240 // been chained on top. 1241 SwitchInsn->setDefaultDest(CaseRangeBlock); 1242 1243 // If a default was never emitted: 1244 if (!DefaultBlock->getParent()) { 1245 // If we have cleanups, emit the default block so that there's a 1246 // place to jump through the cleanups from. 1247 if (ConditionScope.requiresCleanups()) { 1248 EmitBlock(DefaultBlock); 1249 1250 // Otherwise, just forward the default block to the switch end. 1251 } else { 1252 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock()); 1253 delete DefaultBlock; 1254 } 1255 } 1256 1257 ConditionScope.ForceCleanup(); 1258 1259 // Emit continuation. 1260 EmitBlock(SwitchExit.getBlock(), true); 1261 1262 SwitchInsn = SavedSwitchInsn; 1263 CaseRangeBlock = SavedCRBlock; 1264 } 1265 1266 static std::string 1267 SimplifyConstraint(const char *Constraint, const TargetInfo &Target, 1268 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) { 1269 std::string Result; 1270 1271 while (*Constraint) { 1272 switch (*Constraint) { 1273 default: 1274 Result += Target.convertConstraint(Constraint); 1275 break; 1276 // Ignore these 1277 case '*': 1278 case '?': 1279 case '!': 1280 case '=': // Will see this and the following in mult-alt constraints. 1281 case '+': 1282 break; 1283 case '#': // Ignore the rest of the constraint alternative. 1284 while (Constraint[1] && Constraint[1] != ',') 1285 Constraint++; 1286 break; 1287 case ',': 1288 Result += "|"; 1289 break; 1290 case 'g': 1291 Result += "imr"; 1292 break; 1293 case '[': { 1294 assert(OutCons && 1295 "Must pass output names to constraints with a symbolic name"); 1296 unsigned Index; 1297 bool result = Target.resolveSymbolicName(Constraint, 1298 &(*OutCons)[0], 1299 OutCons->size(), Index); 1300 assert(result && "Could not resolve symbolic name"); (void)result; 1301 Result += llvm::utostr(Index); 1302 break; 1303 } 1304 } 1305 1306 Constraint++; 1307 } 1308 1309 return Result; 1310 } 1311 1312 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared 1313 /// as using a particular register add that as a constraint that will be used 1314 /// in this asm stmt. 1315 static std::string 1316 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr, 1317 const TargetInfo &Target, CodeGenModule &CGM, 1318 const AsmStmt &Stmt) { 1319 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr); 1320 if (!AsmDeclRef) 1321 return Constraint; 1322 const ValueDecl &Value = *AsmDeclRef->getDecl(); 1323 const VarDecl *Variable = dyn_cast<VarDecl>(&Value); 1324 if (!Variable) 1325 return Constraint; 1326 if (Variable->getStorageClass() != SC_Register) 1327 return Constraint; 1328 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>(); 1329 if (!Attr) 1330 return Constraint; 1331 StringRef Register = Attr->getLabel(); 1332 assert(Target.isValidGCCRegisterName(Register)); 1333 // We're using validateOutputConstraint here because we only care if 1334 // this is a register constraint. 1335 TargetInfo::ConstraintInfo Info(Constraint, ""); 1336 if (Target.validateOutputConstraint(Info) && 1337 !Info.allowsRegister()) { 1338 CGM.ErrorUnsupported(&Stmt, "__asm__"); 1339 return Constraint; 1340 } 1341 // Canonicalize the register here before returning it. 1342 Register = Target.getNormalizedGCCRegisterName(Register); 1343 return "{" + Register.str() + "}"; 1344 } 1345 1346 llvm::Value* 1347 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 1348 LValue InputValue, QualType InputType, 1349 std::string &ConstraintStr) { 1350 llvm::Value *Arg; 1351 if (Info.allowsRegister() || !Info.allowsMemory()) { 1352 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) { 1353 Arg = EmitLoadOfLValue(InputValue).getScalarVal(); 1354 } else { 1355 llvm::Type *Ty = ConvertType(InputType); 1356 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty); 1357 if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 1358 Ty = llvm::IntegerType::get(getLLVMContext(), Size); 1359 Ty = llvm::PointerType::getUnqual(Ty); 1360 1361 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(), 1362 Ty)); 1363 } else { 1364 Arg = InputValue.getAddress(); 1365 ConstraintStr += '*'; 1366 } 1367 } 1368 } else { 1369 Arg = InputValue.getAddress(); 1370 ConstraintStr += '*'; 1371 } 1372 1373 return Arg; 1374 } 1375 1376 llvm::Value* CodeGenFunction::EmitAsmInput( 1377 const TargetInfo::ConstraintInfo &Info, 1378 const Expr *InputExpr, 1379 std::string &ConstraintStr) { 1380 if (Info.allowsRegister() || !Info.allowsMemory()) 1381 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) 1382 return EmitScalarExpr(InputExpr); 1383 1384 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 1385 LValue Dest = EmitLValue(InputExpr); 1386 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr); 1387 } 1388 1389 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline 1390 /// asm call instruction. The !srcloc MDNode contains a list of constant 1391 /// integers which are the source locations of the start of each line in the 1392 /// asm. 1393 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str, 1394 CodeGenFunction &CGF) { 1395 SmallVector<llvm::Value *, 8> Locs; 1396 // Add the location of the first line to the MDNode. 1397 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1398 Str->getLocStart().getRawEncoding())); 1399 StringRef StrVal = Str->getString(); 1400 if (!StrVal.empty()) { 1401 const SourceManager &SM = CGF.CGM.getContext().getSourceManager(); 1402 const LangOptions &LangOpts = CGF.CGM.getLangOpts(); 1403 1404 // Add the location of the start of each subsequent line of the asm to the 1405 // MDNode. 1406 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) { 1407 if (StrVal[i] != '\n') continue; 1408 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts, 1409 CGF.Target); 1410 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1411 LineLoc.getRawEncoding())); 1412 } 1413 } 1414 1415 return llvm::MDNode::get(CGF.getLLVMContext(), Locs); 1416 } 1417 1418 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 1419 // Assemble the final asm string. 1420 std::string AsmString = S.generateAsmString(getContext()); 1421 1422 // Get all the output and input constraints together. 1423 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1424 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1425 1426 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 1427 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), 1428 S.getOutputName(i)); 1429 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid; 1430 assert(IsValid && "Failed to parse output constraint"); 1431 OutputConstraintInfos.push_back(Info); 1432 } 1433 1434 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1435 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), 1436 S.getInputName(i)); 1437 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(), 1438 S.getNumOutputs(), Info); 1439 assert(IsValid && "Failed to parse input constraint"); (void)IsValid; 1440 InputConstraintInfos.push_back(Info); 1441 } 1442 1443 std::string Constraints; 1444 1445 std::vector<LValue> ResultRegDests; 1446 std::vector<QualType> ResultRegQualTys; 1447 std::vector<llvm::Type *> ResultRegTypes; 1448 std::vector<llvm::Type *> ResultTruncRegTypes; 1449 std::vector<llvm::Type *> ArgTypes; 1450 std::vector<llvm::Value*> Args; 1451 1452 // Keep track of inout constraints. 1453 std::string InOutConstraints; 1454 std::vector<llvm::Value*> InOutArgs; 1455 std::vector<llvm::Type*> InOutArgTypes; 1456 1457 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 1458 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 1459 1460 // Simplify the output constraint. 1461 std::string OutputConstraint(S.getOutputConstraint(i)); 1462 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target); 1463 1464 const Expr *OutExpr = S.getOutputExpr(i); 1465 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 1466 1467 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, 1468 Target, CGM, S); 1469 1470 LValue Dest = EmitLValue(OutExpr); 1471 if (!Constraints.empty()) 1472 Constraints += ','; 1473 1474 // If this is a register output, then make the inline asm return it 1475 // by-value. If this is a memory result, return the value by-reference. 1476 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) { 1477 Constraints += "=" + OutputConstraint; 1478 ResultRegQualTys.push_back(OutExpr->getType()); 1479 ResultRegDests.push_back(Dest); 1480 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 1481 ResultTruncRegTypes.push_back(ResultRegTypes.back()); 1482 1483 // If this output is tied to an input, and if the input is larger, then 1484 // we need to set the actual result type of the inline asm node to be the 1485 // same as the input type. 1486 if (Info.hasMatchingInput()) { 1487 unsigned InputNo; 1488 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 1489 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 1490 if (Input.hasTiedOperand() && Input.getTiedOperand() == i) 1491 break; 1492 } 1493 assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 1494 1495 QualType InputTy = S.getInputExpr(InputNo)->getType(); 1496 QualType OutputType = OutExpr->getType(); 1497 1498 uint64_t InputSize = getContext().getTypeSize(InputTy); 1499 if (getContext().getTypeSize(OutputType) < InputSize) { 1500 // Form the asm to return the value as a larger integer or fp type. 1501 ResultRegTypes.back() = ConvertType(InputTy); 1502 } 1503 } 1504 if (llvm::Type* AdjTy = 1505 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 1506 ResultRegTypes.back())) 1507 ResultRegTypes.back() = AdjTy; 1508 } else { 1509 ArgTypes.push_back(Dest.getAddress()->getType()); 1510 Args.push_back(Dest.getAddress()); 1511 Constraints += "=*"; 1512 Constraints += OutputConstraint; 1513 } 1514 1515 if (Info.isReadWrite()) { 1516 InOutConstraints += ','; 1517 1518 const Expr *InputExpr = S.getOutputExpr(i); 1519 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(), 1520 InOutConstraints); 1521 1522 if (llvm::Type* AdjTy = 1523 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 1524 Arg->getType())) 1525 Arg = Builder.CreateBitCast(Arg, AdjTy); 1526 1527 if (Info.allowsRegister()) 1528 InOutConstraints += llvm::utostr(i); 1529 else 1530 InOutConstraints += OutputConstraint; 1531 1532 InOutArgTypes.push_back(Arg->getType()); 1533 InOutArgs.push_back(Arg); 1534 } 1535 } 1536 1537 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs(); 1538 1539 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1540 const Expr *InputExpr = S.getInputExpr(i); 1541 1542 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1543 1544 if (!Constraints.empty()) 1545 Constraints += ','; 1546 1547 // Simplify the input constraint. 1548 std::string InputConstraint(S.getInputConstraint(i)); 1549 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target, 1550 &OutputConstraintInfos); 1551 1552 InputConstraint = 1553 AddVariableConstraints(InputConstraint, 1554 *InputExpr->IgnoreParenNoopCasts(getContext()), 1555 Target, CGM, S); 1556 1557 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints); 1558 1559 // If this input argument is tied to a larger output result, extend the 1560 // input to be the same size as the output. The LLVM backend wants to see 1561 // the input and output of a matching constraint be the same size. Note 1562 // that GCC does not define what the top bits are here. We use zext because 1563 // that is usually cheaper, but LLVM IR should really get an anyext someday. 1564 if (Info.hasTiedOperand()) { 1565 unsigned Output = Info.getTiedOperand(); 1566 QualType OutputType = S.getOutputExpr(Output)->getType(); 1567 QualType InputTy = InputExpr->getType(); 1568 1569 if (getContext().getTypeSize(OutputType) > 1570 getContext().getTypeSize(InputTy)) { 1571 // Use ptrtoint as appropriate so that we can do our extension. 1572 if (isa<llvm::PointerType>(Arg->getType())) 1573 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy); 1574 llvm::Type *OutputTy = ConvertType(OutputType); 1575 if (isa<llvm::IntegerType>(OutputTy)) 1576 Arg = Builder.CreateZExt(Arg, OutputTy); 1577 else if (isa<llvm::PointerType>(OutputTy)) 1578 Arg = Builder.CreateZExt(Arg, IntPtrTy); 1579 else { 1580 assert(OutputTy->isFloatingPointTy() && "Unexpected output type"); 1581 Arg = Builder.CreateFPExt(Arg, OutputTy); 1582 } 1583 } 1584 } 1585 if (llvm::Type* AdjTy = 1586 getTargetHooks().adjustInlineAsmType(*this, InputConstraint, 1587 Arg->getType())) 1588 Arg = Builder.CreateBitCast(Arg, AdjTy); 1589 1590 ArgTypes.push_back(Arg->getType()); 1591 Args.push_back(Arg); 1592 Constraints += InputConstraint; 1593 } 1594 1595 // Append the "input" part of inout constraints last. 1596 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 1597 ArgTypes.push_back(InOutArgTypes[i]); 1598 Args.push_back(InOutArgs[i]); 1599 } 1600 Constraints += InOutConstraints; 1601 1602 // Clobbers 1603 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 1604 StringRef Clobber = S.getClobber(i); 1605 1606 if (Clobber != "memory" && Clobber != "cc") 1607 Clobber = Target.getNormalizedGCCRegisterName(Clobber); 1608 1609 if (i != 0 || NumConstraints != 0) 1610 Constraints += ','; 1611 1612 Constraints += "~{"; 1613 Constraints += Clobber; 1614 Constraints += '}'; 1615 } 1616 1617 // Add machine specific clobbers 1618 std::string MachineClobbers = Target.getClobbers(); 1619 if (!MachineClobbers.empty()) { 1620 if (!Constraints.empty()) 1621 Constraints += ','; 1622 Constraints += MachineClobbers; 1623 } 1624 1625 llvm::Type *ResultType; 1626 if (ResultRegTypes.empty()) 1627 ResultType = VoidTy; 1628 else if (ResultRegTypes.size() == 1) 1629 ResultType = ResultRegTypes[0]; 1630 else 1631 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes); 1632 1633 llvm::FunctionType *FTy = 1634 llvm::FunctionType::get(ResultType, ArgTypes, false); 1635 1636 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0; 1637 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ? 1638 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT; 1639 llvm::InlineAsm *IA = 1640 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect, 1641 /* IsAlignStack */ false, AsmDialect); 1642 llvm::CallInst *Result = Builder.CreateCall(IA, Args); 1643 Result->addAttribute(llvm::AttrListPtr::FunctionIndex, 1644 llvm::Attributes::get(getLLVMContext(), 1645 llvm::Attributes::NoUnwind)); 1646 1647 // Slap the source location of the inline asm into a !srcloc metadata on the 1648 // call. FIXME: Handle metadata for MS-style inline asms. 1649 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) 1650 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(), 1651 *this)); 1652 1653 // Extract all of the register value results from the asm. 1654 std::vector<llvm::Value*> RegResults; 1655 if (ResultRegTypes.size() == 1) { 1656 RegResults.push_back(Result); 1657 } else { 1658 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 1659 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult"); 1660 RegResults.push_back(Tmp); 1661 } 1662 } 1663 1664 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 1665 llvm::Value *Tmp = RegResults[i]; 1666 1667 // If the result type of the LLVM IR asm doesn't match the result type of 1668 // the expression, do the conversion. 1669 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 1670 llvm::Type *TruncTy = ResultTruncRegTypes[i]; 1671 1672 // Truncate the integer result to the right size, note that TruncTy can be 1673 // a pointer. 1674 if (TruncTy->isFloatingPointTy()) 1675 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 1676 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 1677 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy); 1678 Tmp = Builder.CreateTrunc(Tmp, 1679 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize)); 1680 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 1681 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 1682 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType()); 1683 Tmp = Builder.CreatePtrToInt(Tmp, 1684 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize)); 1685 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1686 } else if (TruncTy->isIntegerTy()) { 1687 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1688 } else if (TruncTy->isVectorTy()) { 1689 Tmp = Builder.CreateBitCast(Tmp, TruncTy); 1690 } 1691 } 1692 1693 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]); 1694 } 1695 } 1696