CGStmt.cpp revision 01234bbc1cb94946df8046ad95e17537082b4f71
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 "clang/AST/StmtVisitor.h" 18#include "clang/Basic/PrettyStackTrace.h" 19#include "clang/Basic/TargetInfo.h" 20#include "llvm/ADT/StringExtras.h" 21#include "llvm/InlineAsm.h" 22#include "llvm/Intrinsics.h" 23#include "llvm/Target/TargetData.h" 24using namespace clang; 25using namespace CodeGen; 26 27//===----------------------------------------------------------------------===// 28// Statement Emission 29//===----------------------------------------------------------------------===// 30 31void CodeGenFunction::EmitStopPoint(const Stmt *S) { 32 if (CGDebugInfo *DI = getDebugInfo()) { 33 DI->setLocation(S->getLocStart()); 34 DI->EmitStopPoint(CurFn, Builder); 35 } 36} 37 38void CodeGenFunction::EmitStmt(const Stmt *S) { 39 assert(S && "Null statement?"); 40 41 // Check if we can handle this without bothering to generate an 42 // insert point or debug info. 43 if (EmitSimpleStmt(S)) 44 return; 45 46 // Check if we are generating unreachable code. 47 if (!HaveInsertPoint()) { 48 // If so, and the statement doesn't contain a label, then we do not need to 49 // generate actual code. This is safe because (1) the current point is 50 // unreachable, so we don't need to execute the code, and (2) we've already 51 // handled the statements which update internal data structures (like the 52 // local variable map) which could be used by subsequent statements. 53 if (!ContainsLabel(S)) { 54 // Verify that any decl statements were handled as simple, they may be in 55 // scope of subsequent reachable statements. 56 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 57 return; 58 } 59 60 // Otherwise, make a new block to hold the code. 61 EnsureInsertPoint(); 62 } 63 64 // Generate a stoppoint if we are emitting debug info. 65 EmitStopPoint(S); 66 67 switch (S->getStmtClass()) { 68 default: 69 // Must be an expression in a stmt context. Emit the value (to get 70 // side-effects) and ignore the result. 71 if (!isa<Expr>(S)) 72 ErrorUnsupported(S, "statement"); 73 74 EmitAnyExpr(cast<Expr>(S), 0, false, true); 75 76 // Expression emitters don't handle unreachable blocks yet, so look for one 77 // explicitly here. This handles the common case of a call to a noreturn 78 // function. 79 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) { 80 if (CurBB->empty() && CurBB->use_empty()) { 81 CurBB->eraseFromParent(); 82 Builder.ClearInsertionPoint(); 83 } 84 } 85 break; 86 case Stmt::IndirectGotoStmtClass: 87 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 88 89 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 90 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break; 91 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break; 92 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break; 93 94 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 95 96 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 97 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 98 99 case Stmt::ObjCAtTryStmtClass: 100 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 101 break; 102 case Stmt::ObjCAtCatchStmtClass: 103 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt"); 104 break; 105 case Stmt::ObjCAtFinallyStmtClass: 106 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt"); 107 break; 108 case Stmt::ObjCAtThrowStmtClass: 109 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 110 break; 111 case Stmt::ObjCAtSynchronizedStmtClass: 112 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 113 break; 114 case Stmt::ObjCForCollectionStmtClass: 115 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 116 break; 117 118 case Stmt::CXXTryStmtClass: 119 EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 120 break; 121 } 122} 123 124bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) { 125 switch (S->getStmtClass()) { 126 default: return false; 127 case Stmt::NullStmtClass: break; 128 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break; 129 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break; 130 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break; 131 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break; 132 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break; 133 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break; 134 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break; 135 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break; 136 } 137 138 return true; 139} 140 141/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 142/// this captures the expression result of the last sub-statement and returns it 143/// (for use by the statement expression extension). 144RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 145 llvm::Value *AggLoc, bool isAggVol) { 146 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 147 "LLVM IR generation of compound statement ('{}')"); 148 149 CGDebugInfo *DI = getDebugInfo(); 150 if (DI) { 151 DI->setLocation(S.getLBracLoc()); 152 DI->EmitRegionStart(CurFn, Builder); 153 } 154 155 // Keep track of the current cleanup stack depth. 156 CleanupScope Scope(*this); 157 158 for (CompoundStmt::const_body_iterator I = S.body_begin(), 159 E = S.body_end()-GetLast; I != E; ++I) 160 EmitStmt(*I); 161 162 if (DI) { 163 DI->setLocation(S.getLBracLoc()); 164 DI->EmitRegionEnd(CurFn, Builder); 165 } 166 167 RValue RV; 168 if (!GetLast) 169 RV = RValue::get(0); 170 else { 171 // We have to special case labels here. They are statements, but when put 172 // at the end of a statement expression, they yield the value of their 173 // subexpression. Handle this by walking through all labels we encounter, 174 // emitting them before we evaluate the subexpr. 175 const Stmt *LastStmt = S.body_back(); 176 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) { 177 EmitLabel(*LS); 178 LastStmt = LS->getSubStmt(); 179 } 180 181 EnsureInsertPoint(); 182 183 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc); 184 } 185 186 return RV; 187} 188 189void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 190 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 191 192 // If there is a cleanup stack, then we it isn't worth trying to 193 // simplify this block (we would need to remove it from the scope map 194 // and cleanup entry). 195 if (!CleanupEntries.empty()) 196 return; 197 198 // Can only simplify direct branches. 199 if (!BI || !BI->isUnconditional()) 200 return; 201 202 BB->replaceAllUsesWith(BI->getSuccessor(0)); 203 BI->eraseFromParent(); 204 BB->eraseFromParent(); 205} 206 207void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 208 // Fall out of the current block (if necessary). 209 EmitBranch(BB); 210 211 if (IsFinished && BB->use_empty()) { 212 delete BB; 213 return; 214 } 215 216 // If necessary, associate the block with the cleanup stack size. 217 if (!CleanupEntries.empty()) { 218 // Check if the basic block has already been inserted. 219 BlockScopeMap::iterator I = BlockScopes.find(BB); 220 if (I != BlockScopes.end()) { 221 assert(I->second == CleanupEntries.size() - 1); 222 } else { 223 BlockScopes[BB] = CleanupEntries.size() - 1; 224 CleanupEntries.back().Blocks.push_back(BB); 225 } 226 } 227 228 CurFn->getBasicBlockList().push_back(BB); 229 Builder.SetInsertPoint(BB); 230} 231 232void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 233 // Emit a branch from the current block to the target one if this 234 // was a real block. If this was just a fall-through block after a 235 // terminator, don't emit it. 236 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 237 238 if (!CurBB || CurBB->getTerminator()) { 239 // If there is no insert point or the previous block is already 240 // terminated, don't touch it. 241 } else { 242 // Otherwise, create a fall-through branch. 243 Builder.CreateBr(Target); 244 } 245 246 Builder.ClearInsertionPoint(); 247} 248 249void CodeGenFunction::EmitLabel(const LabelStmt &S) { 250 EmitBlock(getBasicBlockForLabel(&S)); 251} 252 253 254void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 255 EmitLabel(S); 256 EmitStmt(S.getSubStmt()); 257} 258 259void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 260 // If this code is reachable then emit a stop point (if generating 261 // debug info). We have to do this ourselves because we are on the 262 // "simple" statement path. 263 if (HaveInsertPoint()) 264 EmitStopPoint(&S); 265 266 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel())); 267} 268 269 270void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 271 // Ensure that we have an i8* for our PHI node. 272 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 273 llvm::Type::getInt8PtrTy(VMContext), 274 "addr"); 275 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 276 277 278 // Get the basic block for the indirect goto. 279 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 280 281 // The first instruction in the block has to be the PHI for the switch dest, 282 // add an entry for this branch. 283 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 284 285 EmitBranch(IndGotoBB); 286} 287 288void CodeGenFunction::EmitIfStmt(const IfStmt &S) { 289 // C99 6.8.4.1: The first substatement is executed if the expression compares 290 // unequal to 0. The condition must be a scalar type. 291 CleanupScope ConditionScope(*this); 292 293 if (S.getConditionVariable()) 294 EmitLocalBlockVarDecl(*S.getConditionVariable()); 295 296 // If the condition constant folds and can be elided, try to avoid emitting 297 // the condition and the dead arm of the if/else. 298 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) { 299 // Figure out which block (then or else) is executed. 300 const Stmt *Executed = S.getThen(), *Skipped = S.getElse(); 301 if (Cond == -1) // Condition false? 302 std::swap(Executed, Skipped); 303 304 // If the skipped block has no labels in it, just emit the executed block. 305 // This avoids emitting dead code and simplifies the CFG substantially. 306 if (!ContainsLabel(Skipped)) { 307 if (Executed) { 308 CleanupScope ExecutedScope(*this); 309 EmitStmt(Executed); 310 } 311 return; 312 } 313 } 314 315 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 316 // the conditional branch. 317 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 318 llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 319 llvm::BasicBlock *ElseBlock = ContBlock; 320 if (S.getElse()) 321 ElseBlock = createBasicBlock("if.else"); 322 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock); 323 324 // Emit the 'then' code. 325 EmitBlock(ThenBlock); 326 { 327 CleanupScope ThenScope(*this); 328 EmitStmt(S.getThen()); 329 } 330 EmitBranch(ContBlock); 331 332 // Emit the 'else' code if present. 333 if (const Stmt *Else = S.getElse()) { 334 EmitBlock(ElseBlock); 335 { 336 CleanupScope ElseScope(*this); 337 EmitStmt(Else); 338 } 339 EmitBranch(ContBlock); 340 } 341 342 // Emit the continuation block for code after the if. 343 EmitBlock(ContBlock, true); 344} 345 346void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { 347 // Emit the header for the loop, insert it, which will create an uncond br to 348 // it. 349 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond"); 350 EmitBlock(LoopHeader); 351 352 // Create an exit block for when the condition fails, create a block for the 353 // body of the loop. 354 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end"); 355 llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 356 357 // Store the blocks to use for break and continue. 358 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader)); 359 360 // Evaluate the conditional in the while header. C99 6.8.5.1: The 361 // evaluation of the controlling expression takes place before each 362 // execution of the loop body. 363 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 364 365 // while(1) is common, avoid extra exit blocks. Be sure 366 // to correctly handle break/continue though. 367 bool EmitBoolCondBranch = true; 368 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 369 if (C->isOne()) 370 EmitBoolCondBranch = false; 371 372 // As long as the condition is true, go to the loop body. 373 if (EmitBoolCondBranch) 374 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 375 376 // Emit the loop body. 377 EmitBlock(LoopBody); 378 EmitStmt(S.getBody()); 379 380 BreakContinueStack.pop_back(); 381 382 // Cycle to the condition. 383 EmitBranch(LoopHeader); 384 385 // Emit the exit block. 386 EmitBlock(ExitBlock, true); 387 388 // The LoopHeader typically is just a branch if we skipped emitting 389 // a branch, try to erase it. 390 if (!EmitBoolCondBranch) 391 SimplifyForwardingBlocks(LoopHeader); 392} 393 394void CodeGenFunction::EmitDoStmt(const DoStmt &S) { 395 // Emit the body for the loop, insert it, which will create an uncond br to 396 // it. 397 llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 398 llvm::BasicBlock *AfterDo = createBasicBlock("do.end"); 399 EmitBlock(LoopBody); 400 401 llvm::BasicBlock *DoCond = createBasicBlock("do.cond"); 402 403 // Store the blocks to use for break and continue. 404 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond)); 405 406 // Emit the body of the loop into the block. 407 EmitStmt(S.getBody()); 408 409 BreakContinueStack.pop_back(); 410 411 EmitBlock(DoCond); 412 413 // C99 6.8.5.2: "The evaluation of the controlling expression takes place 414 // after each execution of the loop body." 415 416 // Evaluate the conditional in the while header. 417 // C99 6.8.5p2/p4: The first substatement is executed if the expression 418 // compares unequal to 0. The condition must be a scalar type. 419 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 420 421 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 422 // to correctly handle break/continue though. 423 bool EmitBoolCondBranch = true; 424 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 425 if (C->isZero()) 426 EmitBoolCondBranch = false; 427 428 // As long as the condition is true, iterate the loop. 429 if (EmitBoolCondBranch) 430 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo); 431 432 // Emit the exit block. 433 EmitBlock(AfterDo); 434 435 // The DoCond block typically is just a branch if we skipped 436 // emitting a branch, try to erase it. 437 if (!EmitBoolCondBranch) 438 SimplifyForwardingBlocks(DoCond); 439} 440 441void CodeGenFunction::EmitForStmt(const ForStmt &S) { 442 // FIXME: What do we do if the increment (f.e.) contains a stmt expression, 443 // which contains a continue/break? 444 445 // Evaluate the first part before the loop. 446 if (S.getInit()) 447 EmitStmt(S.getInit()); 448 449 // Start the loop with a block that tests the condition. 450 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 451 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 452 453 EmitBlock(CondBlock); 454 455 // Evaluate the condition if present. If not, treat it as a 456 // non-zero-constant according to 6.8.5.3p2, aka, true. 457 if (S.getCond()) { 458 // As long as the condition is true, iterate the loop. 459 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 460 461 // C99 6.8.5p2/p4: The first substatement is executed if the expression 462 // compares unequal to 0. The condition must be a scalar type. 463 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor); 464 465 EmitBlock(ForBody); 466 } else { 467 // Treat it as a non-zero constant. Don't even create a new block for the 468 // body, just fall into it. 469 } 470 471 // If the for loop doesn't have an increment we can just use the 472 // condition as the continue block. 473 llvm::BasicBlock *ContinueBlock; 474 if (S.getInc()) 475 ContinueBlock = createBasicBlock("for.inc"); 476 else 477 ContinueBlock = CondBlock; 478 479 // Store the blocks to use for break and continue. 480 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock)); 481 482 // If the condition is true, execute the body of the for stmt. 483 CGDebugInfo *DI = getDebugInfo(); 484 if (DI) { 485 DI->setLocation(S.getSourceRange().getBegin()); 486 DI->EmitRegionStart(CurFn, Builder); 487 } 488 EmitStmt(S.getBody()); 489 490 BreakContinueStack.pop_back(); 491 492 // If there is an increment, emit it next. 493 if (S.getInc()) { 494 EmitBlock(ContinueBlock); 495 EmitStmt(S.getInc()); 496 } 497 498 // Finally, branch back up to the condition for the next iteration. 499 EmitBranch(CondBlock); 500 if (DI) { 501 DI->setLocation(S.getSourceRange().getEnd()); 502 DI->EmitRegionEnd(CurFn, Builder); 503 } 504 505 // Emit the fall-through block. 506 EmitBlock(AfterFor, true); 507} 508 509void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 510 if (RV.isScalar()) { 511 Builder.CreateStore(RV.getScalarVal(), ReturnValue); 512 } else if (RV.isAggregate()) { 513 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty); 514 } else { 515 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false); 516 } 517 EmitBranchThroughCleanup(ReturnBlock); 518} 519 520/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 521/// if the function returns void, or may be missing one if the function returns 522/// non-void. Fun stuff :). 523void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 524 // Emit the result value, even if unused, to evalute the side effects. 525 const Expr *RV = S.getRetValue(); 526 527 // FIXME: Clean this up by using an LValue for ReturnTemp, 528 // EmitStoreThroughLValue, and EmitAnyExpr. 529 if (!ReturnValue) { 530 // Make sure not to return anything, but evaluate the expression 531 // for side effects. 532 if (RV) 533 EmitAnyExpr(RV); 534 } else if (RV == 0) { 535 // Do nothing (return value is left uninitialized) 536 } else if (FnRetTy->isReferenceType()) { 537 // If this function returns a reference, take the address of the expression 538 // rather than the value. 539 Builder.CreateStore(EmitLValue(RV).getAddress(), ReturnValue); 540 } else if (!hasAggregateLLVMType(RV->getType())) { 541 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 542 } else if (RV->getType()->isAnyComplexType()) { 543 EmitComplexExprIntoAddr(RV, ReturnValue, false); 544 } else { 545 EmitAggExpr(RV, ReturnValue, false); 546 } 547 548 EmitBranchThroughCleanup(ReturnBlock); 549} 550 551void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 552 // As long as debug info is modeled with instructions, we have to ensure we 553 // have a place to insert here and write the stop point here. 554 if (getDebugInfo()) { 555 EnsureInsertPoint(); 556 EmitStopPoint(&S); 557 } 558 559 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end(); 560 I != E; ++I) 561 EmitDecl(**I); 562} 563 564void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 565 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 566 567 // If this code is reachable then emit a stop point (if generating 568 // debug info). We have to do this ourselves because we are on the 569 // "simple" statement path. 570 if (HaveInsertPoint()) 571 EmitStopPoint(&S); 572 573 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock; 574 EmitBranchThroughCleanup(Block); 575} 576 577void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 578 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 579 580 // If this code is reachable then emit a stop point (if generating 581 // debug info). We have to do this ourselves because we are on the 582 // "simple" statement path. 583 if (HaveInsertPoint()) 584 EmitStopPoint(&S); 585 586 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock; 587 EmitBranchThroughCleanup(Block); 588} 589 590/// EmitCaseStmtRange - If case statement range is not too big then 591/// add multiple cases to switch instruction, one for each value within 592/// the range. If range is too big then emit "if" condition check. 593void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { 594 assert(S.getRHS() && "Expected RHS value in CaseStmt"); 595 596 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext()); 597 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext()); 598 599 // Emit the code for this case. We do this first to make sure it is 600 // properly chained from our predecessor before generating the 601 // switch machinery to enter this block. 602 EmitBlock(createBasicBlock("sw.bb")); 603 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 604 EmitStmt(S.getSubStmt()); 605 606 // If range is empty, do nothing. 607 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 608 return; 609 610 llvm::APInt Range = RHS - LHS; 611 // FIXME: parameters such as this should not be hardcoded. 612 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 613 // Range is small enough to add multiple switch instruction cases. 614 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) { 615 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest); 616 LHS++; 617 } 618 return; 619 } 620 621 // The range is too big. Emit "if" condition into a new block, 622 // making sure to save and restore the current insertion point. 623 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 624 625 // Push this test onto the chain of range checks (which terminates 626 // in the default basic block). The switch's default will be changed 627 // to the top of this chain after switch emission is complete. 628 llvm::BasicBlock *FalseDest = CaseRangeBlock; 629 CaseRangeBlock = createBasicBlock("sw.caserange"); 630 631 CurFn->getBasicBlockList().push_back(CaseRangeBlock); 632 Builder.SetInsertPoint(CaseRangeBlock); 633 634 // Emit range check. 635 llvm::Value *Diff = 636 Builder.CreateSub(SwitchInsn->getCondition(), 637 llvm::ConstantInt::get(VMContext, LHS), "tmp"); 638 llvm::Value *Cond = 639 Builder.CreateICmpULE(Diff, 640 llvm::ConstantInt::get(VMContext, Range), "tmp"); 641 Builder.CreateCondBr(Cond, CaseDest, FalseDest); 642 643 // Restore the appropriate insertion point. 644 if (RestoreBB) 645 Builder.SetInsertPoint(RestoreBB); 646 else 647 Builder.ClearInsertionPoint(); 648} 649 650void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { 651 if (S.getRHS()) { 652 EmitCaseStmtRange(S); 653 return; 654 } 655 656 EmitBlock(createBasicBlock("sw.bb")); 657 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 658 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext()); 659 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); 660 661 // Recursively emitting the statement is acceptable, but is not wonderful for 662 // code where we have many case statements nested together, i.e.: 663 // case 1: 664 // case 2: 665 // case 3: etc. 666 // Handling this recursively will create a new block for each case statement 667 // that falls through to the next case which is IR intensive. It also causes 668 // deep recursion which can run into stack depth limitations. Handle 669 // sequential non-range case statements specially. 670 const CaseStmt *CurCase = &S; 671 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 672 673 // Otherwise, iteratively add consequtive cases to this switch stmt. 674 while (NextCase && NextCase->getRHS() == 0) { 675 CurCase = NextCase; 676 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext()); 677 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); 678 679 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 680 } 681 682 // Normal default recursion for non-cases. 683 EmitStmt(CurCase->getSubStmt()); 684} 685 686void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) { 687 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 688 assert(DefaultBlock->empty() && 689 "EmitDefaultStmt: Default block already defined?"); 690 EmitBlock(DefaultBlock); 691 EmitStmt(S.getSubStmt()); 692} 693 694void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 695 llvm::Value *CondV = EmitScalarExpr(S.getCond()); 696 697 // Handle nested switch statements. 698 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 699 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 700 701 // Create basic block to hold stuff that comes after switch 702 // statement. We also need to create a default block now so that 703 // explicit case ranges tests can have a place to jump to on 704 // failure. 705 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog"); 706 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 707 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 708 CaseRangeBlock = DefaultBlock; 709 710 // Clear the insertion point to indicate we are in unreachable code. 711 Builder.ClearInsertionPoint(); 712 713 // All break statements jump to NextBlock. If BreakContinueStack is non empty 714 // then reuse last ContinueBlock. 715 llvm::BasicBlock *ContinueBlock = 0; 716 if (!BreakContinueStack.empty()) 717 ContinueBlock = BreakContinueStack.back().ContinueBlock; 718 719 // Ensure any vlas created between there and here, are undone 720 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock)); 721 722 // Emit switch body. 723 EmitStmt(S.getBody()); 724 725 BreakContinueStack.pop_back(); 726 727 // Update the default block in case explicit case range tests have 728 // been chained on top. 729 SwitchInsn->setSuccessor(0, CaseRangeBlock); 730 731 // If a default was never emitted then reroute any jumps to it and 732 // discard. 733 if (!DefaultBlock->getParent()) { 734 DefaultBlock->replaceAllUsesWith(NextBlock); 735 delete DefaultBlock; 736 } 737 738 // Emit continuation. 739 EmitBlock(NextBlock, true); 740 741 SwitchInsn = SavedSwitchInsn; 742 CaseRangeBlock = SavedCRBlock; 743} 744 745static std::string 746SimplifyConstraint(const char *Constraint, const TargetInfo &Target, 747 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) { 748 std::string Result; 749 750 while (*Constraint) { 751 switch (*Constraint) { 752 default: 753 Result += Target.convertConstraint(*Constraint); 754 break; 755 // Ignore these 756 case '*': 757 case '?': 758 case '!': 759 break; 760 case 'g': 761 Result += "imr"; 762 break; 763 case '[': { 764 assert(OutCons && 765 "Must pass output names to constraints with a symbolic name"); 766 unsigned Index; 767 bool result = Target.resolveSymbolicName(Constraint, 768 &(*OutCons)[0], 769 OutCons->size(), Index); 770 assert(result && "Could not resolve symbolic name"); result=result; 771 Result += llvm::utostr(Index); 772 break; 773 } 774 } 775 776 Constraint++; 777 } 778 779 return Result; 780} 781 782llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S, 783 const TargetInfo::ConstraintInfo &Info, 784 const Expr *InputExpr, 785 std::string &ConstraintStr) { 786 llvm::Value *Arg; 787 if (Info.allowsRegister() || !Info.allowsMemory()) { 788 const llvm::Type *Ty = ConvertType(InputExpr->getType()); 789 790 if (Ty->isSingleValueType()) { 791 Arg = EmitScalarExpr(InputExpr); 792 } else { 793 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 794 LValue Dest = EmitLValue(InputExpr); 795 796 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty); 797 if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 798 Ty = llvm::IntegerType::get(VMContext, Size); 799 Ty = llvm::PointerType::getUnqual(Ty); 800 801 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty)); 802 } else { 803 Arg = Dest.getAddress(); 804 ConstraintStr += '*'; 805 } 806 } 807 } else { 808 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 809 LValue Dest = EmitLValue(InputExpr); 810 Arg = Dest.getAddress(); 811 ConstraintStr += '*'; 812 } 813 814 return Arg; 815} 816 817void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 818 // Analyze the asm string to decompose it into its pieces. We know that Sema 819 // has already done this, so it is guaranteed to be successful. 820 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces; 821 unsigned DiagOffs; 822 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs); 823 824 // Assemble the pieces into the final asm string. 825 std::string AsmString; 826 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { 827 if (Pieces[i].isString()) 828 AsmString += Pieces[i].getString(); 829 else if (Pieces[i].getModifier() == '\0') 830 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo()); 831 else 832 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' + 833 Pieces[i].getModifier() + '}'; 834 } 835 836 // Get all the output and input constraints together. 837 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 838 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 839 840 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 841 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), 842 S.getOutputName(i)); 843 bool result = Target.validateOutputConstraint(Info); 844 assert(result && "Failed to parse output constraint"); result=result; 845 OutputConstraintInfos.push_back(Info); 846 } 847 848 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 849 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), 850 S.getInputName(i)); 851 bool result = Target.validateInputConstraint(OutputConstraintInfos.data(), 852 S.getNumOutputs(), 853 Info); result=result; 854 assert(result && "Failed to parse input constraint"); 855 InputConstraintInfos.push_back(Info); 856 } 857 858 std::string Constraints; 859 860 std::vector<LValue> ResultRegDests; 861 std::vector<QualType> ResultRegQualTys; 862 std::vector<const llvm::Type *> ResultRegTypes; 863 std::vector<const llvm::Type *> ResultTruncRegTypes; 864 std::vector<const llvm::Type*> ArgTypes; 865 std::vector<llvm::Value*> Args; 866 867 // Keep track of inout constraints. 868 std::string InOutConstraints; 869 std::vector<llvm::Value*> InOutArgs; 870 std::vector<const llvm::Type*> InOutArgTypes; 871 872 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 873 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 874 875 // Simplify the output constraint. 876 std::string OutputConstraint(S.getOutputConstraint(i)); 877 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target); 878 879 const Expr *OutExpr = S.getOutputExpr(i); 880 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 881 882 LValue Dest = EmitLValue(OutExpr); 883 if (!Constraints.empty()) 884 Constraints += ','; 885 886 // If this is a register output, then make the inline asm return it 887 // by-value. If this is a memory result, return the value by-reference. 888 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) { 889 Constraints += "=" + OutputConstraint; 890 ResultRegQualTys.push_back(OutExpr->getType()); 891 ResultRegDests.push_back(Dest); 892 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 893 ResultTruncRegTypes.push_back(ResultRegTypes.back()); 894 895 // If this output is tied to an input, and if the input is larger, then 896 // we need to set the actual result type of the inline asm node to be the 897 // same as the input type. 898 if (Info.hasMatchingInput()) { 899 unsigned InputNo; 900 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 901 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 902 if (Input.hasTiedOperand() && 903 Input.getTiedOperand() == i) 904 break; 905 } 906 assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 907 908 QualType InputTy = S.getInputExpr(InputNo)->getType(); 909 QualType OutputTy = OutExpr->getType(); 910 911 uint64_t InputSize = getContext().getTypeSize(InputTy); 912 if (getContext().getTypeSize(OutputTy) < InputSize) { 913 // Form the asm to return the value as a larger integer type. 914 ResultRegTypes.back() = llvm::IntegerType::get(VMContext, (unsigned)InputSize); 915 } 916 } 917 } else { 918 ArgTypes.push_back(Dest.getAddress()->getType()); 919 Args.push_back(Dest.getAddress()); 920 Constraints += "=*"; 921 Constraints += OutputConstraint; 922 } 923 924 if (Info.isReadWrite()) { 925 InOutConstraints += ','; 926 927 const Expr *InputExpr = S.getOutputExpr(i); 928 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints); 929 930 if (Info.allowsRegister()) 931 InOutConstraints += llvm::utostr(i); 932 else 933 InOutConstraints += OutputConstraint; 934 935 InOutArgTypes.push_back(Arg->getType()); 936 InOutArgs.push_back(Arg); 937 } 938 } 939 940 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs(); 941 942 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 943 const Expr *InputExpr = S.getInputExpr(i); 944 945 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 946 947 if (!Constraints.empty()) 948 Constraints += ','; 949 950 // Simplify the input constraint. 951 std::string InputConstraint(S.getInputConstraint(i)); 952 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target, 953 &OutputConstraintInfos); 954 955 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints); 956 957 // If this input argument is tied to a larger output result, extend the 958 // input to be the same size as the output. The LLVM backend wants to see 959 // the input and output of a matching constraint be the same size. Note 960 // that GCC does not define what the top bits are here. We use zext because 961 // that is usually cheaper, but LLVM IR should really get an anyext someday. 962 if (Info.hasTiedOperand()) { 963 unsigned Output = Info.getTiedOperand(); 964 QualType OutputTy = S.getOutputExpr(Output)->getType(); 965 QualType InputTy = InputExpr->getType(); 966 967 if (getContext().getTypeSize(OutputTy) > 968 getContext().getTypeSize(InputTy)) { 969 // Use ptrtoint as appropriate so that we can do our extension. 970 if (isa<llvm::PointerType>(Arg->getType())) 971 Arg = Builder.CreatePtrToInt(Arg, 972 llvm::IntegerType::get(VMContext, LLVMPointerWidth)); 973 unsigned OutputSize = (unsigned)getContext().getTypeSize(OutputTy); 974 Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(VMContext, OutputSize)); 975 } 976 } 977 978 979 ArgTypes.push_back(Arg->getType()); 980 Args.push_back(Arg); 981 Constraints += InputConstraint; 982 } 983 984 // Append the "input" part of inout constraints last. 985 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 986 ArgTypes.push_back(InOutArgTypes[i]); 987 Args.push_back(InOutArgs[i]); 988 } 989 Constraints += InOutConstraints; 990 991 // Clobbers 992 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 993 std::string Clobber(S.getClobber(i)->getStrData(), 994 S.getClobber(i)->getByteLength()); 995 996 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str()); 997 998 if (i != 0 || NumConstraints != 0) 999 Constraints += ','; 1000 1001 Constraints += "~{"; 1002 Constraints += Clobber; 1003 Constraints += '}'; 1004 } 1005 1006 // Add machine specific clobbers 1007 std::string MachineClobbers = Target.getClobbers(); 1008 if (!MachineClobbers.empty()) { 1009 if (!Constraints.empty()) 1010 Constraints += ','; 1011 Constraints += MachineClobbers; 1012 } 1013 1014 const llvm::Type *ResultType; 1015 if (ResultRegTypes.empty()) 1016 ResultType = llvm::Type::getVoidTy(VMContext); 1017 else if (ResultRegTypes.size() == 1) 1018 ResultType = ResultRegTypes[0]; 1019 else 1020 ResultType = llvm::StructType::get(VMContext, ResultRegTypes); 1021 1022 const llvm::FunctionType *FTy = 1023 llvm::FunctionType::get(ResultType, ArgTypes, false); 1024 1025 llvm::InlineAsm *IA = 1026 llvm::InlineAsm::get(FTy, AsmString, Constraints, 1027 S.isVolatile() || S.getNumOutputs() == 0); 1028 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end()); 1029 Result->addAttribute(~0, llvm::Attribute::NoUnwind); 1030 1031 1032 // Extract all of the register value results from the asm. 1033 std::vector<llvm::Value*> RegResults; 1034 if (ResultRegTypes.size() == 1) { 1035 RegResults.push_back(Result); 1036 } else { 1037 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 1038 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult"); 1039 RegResults.push_back(Tmp); 1040 } 1041 } 1042 1043 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 1044 llvm::Value *Tmp = RegResults[i]; 1045 1046 // If the result type of the LLVM IR asm doesn't match the result type of 1047 // the expression, do the conversion. 1048 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 1049 const llvm::Type *TruncTy = ResultTruncRegTypes[i]; 1050 // Truncate the integer result to the right size, note that 1051 // ResultTruncRegTypes can be a pointer. 1052 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy); 1053 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, (unsigned)ResSize)); 1054 1055 if (Tmp->getType() != TruncTy) { 1056 assert(isa<llvm::PointerType>(TruncTy)); 1057 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 1058 } 1059 } 1060 1061 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i], 1062 ResultRegQualTys[i]); 1063 } 1064} 1065