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