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