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