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" 24 using namespace clang; 25 using namespace CodeGen; 26 27 //===----------------------------------------------------------------------===// 28 // Statement Emission 29 //===----------------------------------------------------------------------===// 30 31 void CodeGenFunction::EmitStopPoint(const Stmt *S) { 32 if (CGDebugInfo *DI = getDebugInfo()) { 33 DI->setLocation(S->getLocStart()); 34 DI->EmitStopPoint(CurFn, Builder); 35 } 36 } 37 38 void 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 124 bool 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). 144 RValue 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.getRBracLoc()); 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 189 void 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 207 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 208 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 209 210 // Fall out of the current block (if necessary). 211 EmitBranch(BB); 212 213 if (IsFinished && BB->use_empty()) { 214 delete BB; 215 return; 216 } 217 218 // If necessary, associate the block with the cleanup stack size. 219 if (!CleanupEntries.empty()) { 220 // Check if the basic block has already been inserted. 221 BlockScopeMap::iterator I = BlockScopes.find(BB); 222 if (I != BlockScopes.end()) { 223 assert(I->second == CleanupEntries.size() - 1); 224 } else { 225 BlockScopes[BB] = CleanupEntries.size() - 1; 226 CleanupEntries.back().Blocks.push_back(BB); 227 } 228 } 229 230 // Place the block after the current block, if possible, or else at 231 // the end of the function. 232 if (CurBB && CurBB->getParent()) 233 CurFn->getBasicBlockList().insertAfter(CurBB, BB); 234 else 235 CurFn->getBasicBlockList().push_back(BB); 236 Builder.SetInsertPoint(BB); 237 } 238 239 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 240 // Emit a branch from the current block to the target one if this 241 // was a real block. If this was just a fall-through block after a 242 // terminator, don't emit it. 243 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 244 245 if (!CurBB || CurBB->getTerminator()) { 246 // If there is no insert point or the previous block is already 247 // terminated, don't touch it. 248 } else { 249 // Otherwise, create a fall-through branch. 250 Builder.CreateBr(Target); 251 } 252 253 Builder.ClearInsertionPoint(); 254 } 255 256 void CodeGenFunction::EmitLabel(const LabelStmt &S) { 257 EmitBlock(getBasicBlockForLabel(&S)); 258 } 259 260 261 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 262 EmitLabel(S); 263 EmitStmt(S.getSubStmt()); 264 } 265 266 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 267 // If this code is reachable then emit a stop point (if generating 268 // debug info). We have to do this ourselves because we are on the 269 // "simple" statement path. 270 if (HaveInsertPoint()) 271 EmitStopPoint(&S); 272 273 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel())); 274 } 275 276 277 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 278 // Ensure that we have an i8* for our PHI node. 279 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 280 llvm::Type::getInt8PtrTy(VMContext), 281 "addr"); 282 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 283 284 285 // Get the basic block for the indirect goto. 286 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 287 288 // The first instruction in the block has to be the PHI for the switch dest, 289 // add an entry for this branch. 290 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 291 292 EmitBranch(IndGotoBB); 293 } 294 295 void CodeGenFunction::EmitIfStmt(const IfStmt &S) { 296 // C99 6.8.4.1: The first substatement is executed if the expression compares 297 // unequal to 0. The condition must be a scalar type. 298 CleanupScope ConditionScope(*this); 299 300 if (S.getConditionVariable()) 301 EmitLocalBlockVarDecl(*S.getConditionVariable()); 302 303 // If the condition constant folds and can be elided, try to avoid emitting 304 // the condition and the dead arm of the if/else. 305 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) { 306 // Figure out which block (then or else) is executed. 307 const Stmt *Executed = S.getThen(), *Skipped = S.getElse(); 308 if (Cond == -1) // Condition false? 309 std::swap(Executed, Skipped); 310 311 // If the skipped block has no labels in it, just emit the executed block. 312 // This avoids emitting dead code and simplifies the CFG substantially. 313 if (!ContainsLabel(Skipped)) { 314 if (Executed) { 315 CleanupScope ExecutedScope(*this); 316 EmitStmt(Executed); 317 } 318 return; 319 } 320 } 321 322 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 323 // the conditional branch. 324 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 325 llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 326 llvm::BasicBlock *ElseBlock = ContBlock; 327 if (S.getElse()) 328 ElseBlock = createBasicBlock("if.else"); 329 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock); 330 331 // Emit the 'then' code. 332 EmitBlock(ThenBlock); 333 { 334 CleanupScope ThenScope(*this); 335 EmitStmt(S.getThen()); 336 } 337 EmitBranch(ContBlock); 338 339 // Emit the 'else' code if present. 340 if (const Stmt *Else = S.getElse()) { 341 EmitBlock(ElseBlock); 342 { 343 CleanupScope ElseScope(*this); 344 EmitStmt(Else); 345 } 346 EmitBranch(ContBlock); 347 } 348 349 // Emit the continuation block for code after the if. 350 EmitBlock(ContBlock, true); 351 } 352 353 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) { 354 // Emit the header for the loop, insert it, which will create an uncond br to 355 // it. 356 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond"); 357 EmitBlock(LoopHeader); 358 359 // Create an exit block for when the condition fails, create a block for the 360 // body of the loop. 361 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end"); 362 llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 363 llvm::BasicBlock *CleanupBlock = 0; 364 llvm::BasicBlock *EffectiveExitBlock = ExitBlock; 365 366 // Store the blocks to use for break and continue. 367 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader)); 368 369 // C++ [stmt.while]p2: 370 // When the condition of a while statement is a declaration, the 371 // scope of the variable that is declared extends from its point 372 // of declaration (3.3.2) to the end of the while statement. 373 // [...] 374 // The object created in a condition is destroyed and created 375 // with each iteration of the loop. 376 CleanupScope ConditionScope(*this); 377 378 if (S.getConditionVariable()) { 379 EmitLocalBlockVarDecl(*S.getConditionVariable()); 380 381 // If this condition variable requires cleanups, create a basic 382 // block to handle those cleanups. 383 if (ConditionScope.requiresCleanups()) { 384 CleanupBlock = createBasicBlock("while.cleanup"); 385 EffectiveExitBlock = CleanupBlock; 386 } 387 } 388 389 // Evaluate the conditional in the while header. C99 6.8.5.1: The 390 // evaluation of the controlling expression takes place before each 391 // execution of the loop body. 392 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 393 394 // while(1) is common, avoid extra exit blocks. Be sure 395 // to correctly handle break/continue though. 396 bool EmitBoolCondBranch = true; 397 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 398 if (C->isOne()) 399 EmitBoolCondBranch = false; 400 401 // As long as the condition is true, go to the loop body. 402 if (EmitBoolCondBranch) 403 Builder.CreateCondBr(BoolCondVal, LoopBody, EffectiveExitBlock); 404 405 // Emit the loop body. 406 { 407 CleanupScope BodyScope(*this); 408 EmitBlock(LoopBody); 409 EmitStmt(S.getBody()); 410 } 411 412 BreakContinueStack.pop_back(); 413 414 if (CleanupBlock) { 415 // If we have a cleanup block, jump there to perform cleanups 416 // before looping. 417 EmitBranch(CleanupBlock); 418 419 // Emit the cleanup block, performing cleanups for the condition 420 // and then jumping to either the loop header or the exit block. 421 EmitBlock(CleanupBlock); 422 ConditionScope.ForceCleanup(); 423 Builder.CreateCondBr(BoolCondVal, LoopHeader, ExitBlock); 424 } else { 425 // Cycle to the condition. 426 EmitBranch(LoopHeader); 427 } 428 429 // Emit the exit block. 430 EmitBlock(ExitBlock, true); 431 432 433 // The LoopHeader typically is just a branch if we skipped emitting 434 // a branch, try to erase it. 435 if (!EmitBoolCondBranch && !CleanupBlock) 436 SimplifyForwardingBlocks(LoopHeader); 437 } 438 439 void CodeGenFunction::EmitDoStmt(const DoStmt &S) { 440 // Emit the body for the loop, insert it, which will create an uncond br to 441 // it. 442 llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 443 llvm::BasicBlock *AfterDo = createBasicBlock("do.end"); 444 EmitBlock(LoopBody); 445 446 llvm::BasicBlock *DoCond = createBasicBlock("do.cond"); 447 448 // Store the blocks to use for break and continue. 449 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond)); 450 451 // Emit the body of the loop into the block. 452 EmitStmt(S.getBody()); 453 454 BreakContinueStack.pop_back(); 455 456 EmitBlock(DoCond); 457 458 // C99 6.8.5.2: "The evaluation of the controlling expression takes place 459 // after each execution of the loop body." 460 461 // Evaluate the conditional in the while header. 462 // C99 6.8.5p2/p4: The first substatement is executed if the expression 463 // compares unequal to 0. The condition must be a scalar type. 464 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 465 466 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 467 // to correctly handle break/continue though. 468 bool EmitBoolCondBranch = true; 469 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 470 if (C->isZero()) 471 EmitBoolCondBranch = false; 472 473 // As long as the condition is true, iterate the loop. 474 if (EmitBoolCondBranch) 475 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo); 476 477 // Emit the exit block. 478 EmitBlock(AfterDo); 479 480 // The DoCond block typically is just a branch if we skipped 481 // emitting a branch, try to erase it. 482 if (!EmitBoolCondBranch) 483 SimplifyForwardingBlocks(DoCond); 484 } 485 486 void CodeGenFunction::EmitForStmt(const ForStmt &S) { 487 // FIXME: What do we do if the increment (f.e.) contains a stmt expression, 488 // which contains a continue/break? 489 CleanupScope ForScope(*this); 490 491 // Evaluate the first part before the loop. 492 if (S.getInit()) 493 EmitStmt(S.getInit()); 494 495 // Start the loop with a block that tests the condition. 496 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 497 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 498 llvm::BasicBlock *IncBlock = 0; 499 llvm::BasicBlock *CondCleanup = 0; 500 llvm::BasicBlock *EffectiveExitBlock = AfterFor; 501 EmitBlock(CondBlock); 502 503 // Create a cleanup scope for the condition variable cleanups. 504 CleanupScope ConditionScope(*this); 505 506 llvm::Value *BoolCondVal = 0; 507 if (S.getCond()) { 508 // If the for statement has a condition scope, emit the local variable 509 // declaration. 510 if (S.getConditionVariable()) { 511 EmitLocalBlockVarDecl(*S.getConditionVariable()); 512 513 if (ConditionScope.requiresCleanups()) { 514 CondCleanup = createBasicBlock("for.cond.cleanup"); 515 EffectiveExitBlock = CondCleanup; 516 } 517 } 518 519 // As long as the condition is true, iterate the loop. 520 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 521 522 // C99 6.8.5p2/p4: The first substatement is executed if the expression 523 // compares unequal to 0. The condition must be a scalar type. 524 BoolCondVal = EvaluateExprAsBool(S.getCond()); 525 Builder.CreateCondBr(BoolCondVal, ForBody, EffectiveExitBlock); 526 527 EmitBlock(ForBody); 528 } else { 529 // Treat it as a non-zero constant. Don't even create a new block for the 530 // body, just fall into it. 531 } 532 533 // If the for loop doesn't have an increment we can just use the 534 // condition as the continue block. 535 llvm::BasicBlock *ContinueBlock; 536 if (S.getInc()) 537 ContinueBlock = IncBlock = createBasicBlock("for.inc"); 538 else 539 ContinueBlock = CondBlock; 540 541 // Store the blocks to use for break and continue. 542 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock)); 543 544 // If the condition is true, execute the body of the for stmt. 545 CGDebugInfo *DI = getDebugInfo(); 546 if (DI) { 547 DI->setLocation(S.getSourceRange().getBegin()); 548 DI->EmitRegionStart(CurFn, Builder); 549 } 550 551 { 552 // Create a separate cleanup scope for the body, in case it is not 553 // a compound statement. 554 CleanupScope BodyScope(*this); 555 EmitStmt(S.getBody()); 556 } 557 558 BreakContinueStack.pop_back(); 559 560 // If there is an increment, emit it next. 561 if (S.getInc()) { 562 EmitBlock(IncBlock); 563 EmitStmt(S.getInc()); 564 } 565 566 // Finally, branch back up to the condition for the next iteration. 567 if (CondCleanup) { 568 // Branch to the cleanup block. 569 EmitBranch(CondCleanup); 570 571 // Emit the cleanup block, which branches back to the loop body or 572 // outside of the for statement once it is done. 573 EmitBlock(CondCleanup); 574 ConditionScope.ForceCleanup(); 575 Builder.CreateCondBr(BoolCondVal, CondBlock, AfterFor); 576 } else 577 EmitBranch(CondBlock); 578 if (DI) { 579 DI->setLocation(S.getSourceRange().getEnd()); 580 DI->EmitRegionEnd(CurFn, Builder); 581 } 582 583 // Emit the fall-through block. 584 EmitBlock(AfterFor, true); 585 } 586 587 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 588 if (RV.isScalar()) { 589 Builder.CreateStore(RV.getScalarVal(), ReturnValue); 590 } else if (RV.isAggregate()) { 591 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty); 592 } else { 593 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false); 594 } 595 EmitBranchThroughCleanup(ReturnBlock); 596 } 597 598 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 599 /// if the function returns void, or may be missing one if the function returns 600 /// non-void. Fun stuff :). 601 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 602 // Emit the result value, even if unused, to evalute the side effects. 603 const Expr *RV = S.getRetValue(); 604 605 // FIXME: Clean this up by using an LValue for ReturnTemp, 606 // EmitStoreThroughLValue, and EmitAnyExpr. 607 if (!ReturnValue) { 608 // Make sure not to return anything, but evaluate the expression 609 // for side effects. 610 if (RV) 611 EmitAnyExpr(RV); 612 } else if (RV == 0) { 613 // Do nothing (return value is left uninitialized) 614 } else if (FnRetTy->isReferenceType()) { 615 // If this function returns a reference, take the address of the expression 616 // rather than the value. 617 RValue Result = EmitReferenceBindingToExpr(RV, false); 618 Builder.CreateStore(Result.getScalarVal(), ReturnValue); 619 } else if (!hasAggregateLLVMType(RV->getType())) { 620 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 621 } else if (RV->getType()->isAnyComplexType()) { 622 EmitComplexExprIntoAddr(RV, ReturnValue, false); 623 } else { 624 EmitAggExpr(RV, ReturnValue, false); 625 } 626 627 EmitBranchThroughCleanup(ReturnBlock); 628 } 629 630 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 631 // As long as debug info is modeled with instructions, we have to ensure we 632 // have a place to insert here and write the stop point here. 633 if (getDebugInfo()) { 634 EnsureInsertPoint(); 635 EmitStopPoint(&S); 636 } 637 638 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end(); 639 I != E; ++I) 640 EmitDecl(**I); 641 } 642 643 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 644 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 645 646 // If this code is reachable then emit a stop point (if generating 647 // debug info). We have to do this ourselves because we are on the 648 // "simple" statement path. 649 if (HaveInsertPoint()) 650 EmitStopPoint(&S); 651 652 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock; 653 EmitBranchThroughCleanup(Block); 654 } 655 656 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 657 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 658 659 // If this code is reachable then emit a stop point (if generating 660 // debug info). We have to do this ourselves because we are on the 661 // "simple" statement path. 662 if (HaveInsertPoint()) 663 EmitStopPoint(&S); 664 665 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock; 666 EmitBranchThroughCleanup(Block); 667 } 668 669 /// EmitCaseStmtRange - If case statement range is not too big then 670 /// add multiple cases to switch instruction, one for each value within 671 /// the range. If range is too big then emit "if" condition check. 672 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) { 673 assert(S.getRHS() && "Expected RHS value in CaseStmt"); 674 675 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext()); 676 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext()); 677 678 // Emit the code for this case. We do this first to make sure it is 679 // properly chained from our predecessor before generating the 680 // switch machinery to enter this block. 681 EmitBlock(createBasicBlock("sw.bb")); 682 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 683 EmitStmt(S.getSubStmt()); 684 685 // If range is empty, do nothing. 686 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 687 return; 688 689 llvm::APInt Range = RHS - LHS; 690 // FIXME: parameters such as this should not be hardcoded. 691 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 692 // Range is small enough to add multiple switch instruction cases. 693 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) { 694 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest); 695 LHS++; 696 } 697 return; 698 } 699 700 // The range is too big. Emit "if" condition into a new block, 701 // making sure to save and restore the current insertion point. 702 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 703 704 // Push this test onto the chain of range checks (which terminates 705 // in the default basic block). The switch's default will be changed 706 // to the top of this chain after switch emission is complete. 707 llvm::BasicBlock *FalseDest = CaseRangeBlock; 708 CaseRangeBlock = createBasicBlock("sw.caserange"); 709 710 CurFn->getBasicBlockList().push_back(CaseRangeBlock); 711 Builder.SetInsertPoint(CaseRangeBlock); 712 713 // Emit range check. 714 llvm::Value *Diff = 715 Builder.CreateSub(SwitchInsn->getCondition(), 716 llvm::ConstantInt::get(VMContext, LHS), "tmp"); 717 llvm::Value *Cond = 718 Builder.CreateICmpULE(Diff, 719 llvm::ConstantInt::get(VMContext, Range), "tmp"); 720 Builder.CreateCondBr(Cond, CaseDest, FalseDest); 721 722 // Restore the appropriate insertion point. 723 if (RestoreBB) 724 Builder.SetInsertPoint(RestoreBB); 725 else 726 Builder.ClearInsertionPoint(); 727 } 728 729 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) { 730 if (S.getRHS()) { 731 EmitCaseStmtRange(S); 732 return; 733 } 734 735 EmitBlock(createBasicBlock("sw.bb")); 736 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock(); 737 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext()); 738 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); 739 740 // Recursively emitting the statement is acceptable, but is not wonderful for 741 // code where we have many case statements nested together, i.e.: 742 // case 1: 743 // case 2: 744 // case 3: etc. 745 // Handling this recursively will create a new block for each case statement 746 // that falls through to the next case which is IR intensive. It also causes 747 // deep recursion which can run into stack depth limitations. Handle 748 // sequential non-range case statements specially. 749 const CaseStmt *CurCase = &S; 750 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 751 752 // Otherwise, iteratively add consequtive cases to this switch stmt. 753 while (NextCase && NextCase->getRHS() == 0) { 754 CurCase = NextCase; 755 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext()); 756 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest); 757 758 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 759 } 760 761 // Normal default recursion for non-cases. 762 EmitStmt(CurCase->getSubStmt()); 763 } 764 765 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) { 766 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 767 assert(DefaultBlock->empty() && 768 "EmitDefaultStmt: Default block already defined?"); 769 EmitBlock(DefaultBlock); 770 EmitStmt(S.getSubStmt()); 771 } 772 773 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 774 CleanupScope ConditionScope(*this); 775 776 if (S.getConditionVariable()) 777 EmitLocalBlockVarDecl(*S.getConditionVariable()); 778 779 llvm::Value *CondV = EmitScalarExpr(S.getCond()); 780 781 // Handle nested switch statements. 782 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 783 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 784 785 // Create basic block to hold stuff that comes after switch 786 // statement. We also need to create a default block now so that 787 // explicit case ranges tests can have a place to jump to on 788 // failure. 789 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog"); 790 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 791 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 792 CaseRangeBlock = DefaultBlock; 793 794 // Clear the insertion point to indicate we are in unreachable code. 795 Builder.ClearInsertionPoint(); 796 797 // All break statements jump to NextBlock. If BreakContinueStack is non empty 798 // then reuse last ContinueBlock. 799 llvm::BasicBlock *ContinueBlock = 0; 800 if (!BreakContinueStack.empty()) 801 ContinueBlock = BreakContinueStack.back().ContinueBlock; 802 803 // Ensure any vlas created between there and here, are undone 804 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock)); 805 806 // Emit switch body. 807 EmitStmt(S.getBody()); 808 809 BreakContinueStack.pop_back(); 810 811 // Update the default block in case explicit case range tests have 812 // been chained on top. 813 SwitchInsn->setSuccessor(0, CaseRangeBlock); 814 815 // If a default was never emitted then reroute any jumps to it and 816 // discard. 817 if (!DefaultBlock->getParent()) { 818 DefaultBlock->replaceAllUsesWith(NextBlock); 819 delete DefaultBlock; 820 } 821 822 // Emit continuation. 823 EmitBlock(NextBlock, true); 824 825 SwitchInsn = SavedSwitchInsn; 826 CaseRangeBlock = SavedCRBlock; 827 } 828 829 static std::string 830 SimplifyConstraint(const char *Constraint, const TargetInfo &Target, 831 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) { 832 std::string Result; 833 834 while (*Constraint) { 835 switch (*Constraint) { 836 default: 837 Result += Target.convertConstraint(*Constraint); 838 break; 839 // Ignore these 840 case '*': 841 case '?': 842 case '!': 843 break; 844 case 'g': 845 Result += "imr"; 846 break; 847 case '[': { 848 assert(OutCons && 849 "Must pass output names to constraints with a symbolic name"); 850 unsigned Index; 851 bool result = Target.resolveSymbolicName(Constraint, 852 &(*OutCons)[0], 853 OutCons->size(), Index); 854 assert(result && "Could not resolve symbolic name"); result=result; 855 Result += llvm::utostr(Index); 856 break; 857 } 858 } 859 860 Constraint++; 861 } 862 863 return Result; 864 } 865 866 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S, 867 const TargetInfo::ConstraintInfo &Info, 868 const Expr *InputExpr, 869 std::string &ConstraintStr) { 870 llvm::Value *Arg; 871 if (Info.allowsRegister() || !Info.allowsMemory()) { 872 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) { 873 Arg = EmitScalarExpr(InputExpr); 874 } else { 875 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 876 LValue Dest = EmitLValue(InputExpr); 877 878 const llvm::Type *Ty = ConvertType(InputExpr->getType()); 879 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty); 880 if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 881 Ty = llvm::IntegerType::get(VMContext, Size); 882 Ty = llvm::PointerType::getUnqual(Ty); 883 884 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty)); 885 } else { 886 Arg = Dest.getAddress(); 887 ConstraintStr += '*'; 888 } 889 } 890 } else { 891 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 892 LValue Dest = EmitLValue(InputExpr); 893 Arg = Dest.getAddress(); 894 ConstraintStr += '*'; 895 } 896 897 return Arg; 898 } 899 900 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 901 // Analyze the asm string to decompose it into its pieces. We know that Sema 902 // has already done this, so it is guaranteed to be successful. 903 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces; 904 unsigned DiagOffs; 905 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs); 906 907 // Assemble the pieces into the final asm string. 908 std::string AsmString; 909 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { 910 if (Pieces[i].isString()) 911 AsmString += Pieces[i].getString(); 912 else if (Pieces[i].getModifier() == '\0') 913 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo()); 914 else 915 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' + 916 Pieces[i].getModifier() + '}'; 917 } 918 919 // Get all the output and input constraints together. 920 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 921 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 922 923 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 924 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), 925 S.getOutputName(i)); 926 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid; 927 assert(IsValid && "Failed to parse output constraint"); 928 OutputConstraintInfos.push_back(Info); 929 } 930 931 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 932 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), 933 S.getInputName(i)); 934 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(), 935 S.getNumOutputs(), Info); 936 assert(IsValid && "Failed to parse input constraint"); (void)IsValid; 937 InputConstraintInfos.push_back(Info); 938 } 939 940 std::string Constraints; 941 942 std::vector<LValue> ResultRegDests; 943 std::vector<QualType> ResultRegQualTys; 944 std::vector<const llvm::Type *> ResultRegTypes; 945 std::vector<const llvm::Type *> ResultTruncRegTypes; 946 std::vector<const llvm::Type*> ArgTypes; 947 std::vector<llvm::Value*> Args; 948 949 // Keep track of inout constraints. 950 std::string InOutConstraints; 951 std::vector<llvm::Value*> InOutArgs; 952 std::vector<const llvm::Type*> InOutArgTypes; 953 954 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 955 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 956 957 // Simplify the output constraint. 958 std::string OutputConstraint(S.getOutputConstraint(i)); 959 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target); 960 961 const Expr *OutExpr = S.getOutputExpr(i); 962 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 963 964 LValue Dest = EmitLValue(OutExpr); 965 if (!Constraints.empty()) 966 Constraints += ','; 967 968 // If this is a register output, then make the inline asm return it 969 // by-value. If this is a memory result, return the value by-reference. 970 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) { 971 Constraints += "=" + OutputConstraint; 972 ResultRegQualTys.push_back(OutExpr->getType()); 973 ResultRegDests.push_back(Dest); 974 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 975 ResultTruncRegTypes.push_back(ResultRegTypes.back()); 976 977 // If this output is tied to an input, and if the input is larger, then 978 // we need to set the actual result type of the inline asm node to be the 979 // same as the input type. 980 if (Info.hasMatchingInput()) { 981 unsigned InputNo; 982 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 983 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 984 if (Input.hasTiedOperand() && Input.getTiedOperand() == i) 985 break; 986 } 987 assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 988 989 QualType InputTy = S.getInputExpr(InputNo)->getType(); 990 QualType OutputType = OutExpr->getType(); 991 992 uint64_t InputSize = getContext().getTypeSize(InputTy); 993 if (getContext().getTypeSize(OutputType) < InputSize) { 994 // Form the asm to return the value as a larger integer or fp type. 995 ResultRegTypes.back() = ConvertType(InputTy); 996 } 997 } 998 } else { 999 ArgTypes.push_back(Dest.getAddress()->getType()); 1000 Args.push_back(Dest.getAddress()); 1001 Constraints += "=*"; 1002 Constraints += OutputConstraint; 1003 } 1004 1005 if (Info.isReadWrite()) { 1006 InOutConstraints += ','; 1007 1008 const Expr *InputExpr = S.getOutputExpr(i); 1009 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints); 1010 1011 if (Info.allowsRegister()) 1012 InOutConstraints += llvm::utostr(i); 1013 else 1014 InOutConstraints += OutputConstraint; 1015 1016 InOutArgTypes.push_back(Arg->getType()); 1017 InOutArgs.push_back(Arg); 1018 } 1019 } 1020 1021 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs(); 1022 1023 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 1024 const Expr *InputExpr = S.getInputExpr(i); 1025 1026 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1027 1028 if (!Constraints.empty()) 1029 Constraints += ','; 1030 1031 // Simplify the input constraint. 1032 std::string InputConstraint(S.getInputConstraint(i)); 1033 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target, 1034 &OutputConstraintInfos); 1035 1036 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints); 1037 1038 // If this input argument is tied to a larger output result, extend the 1039 // input to be the same size as the output. The LLVM backend wants to see 1040 // the input and output of a matching constraint be the same size. Note 1041 // that GCC does not define what the top bits are here. We use zext because 1042 // that is usually cheaper, but LLVM IR should really get an anyext someday. 1043 if (Info.hasTiedOperand()) { 1044 unsigned Output = Info.getTiedOperand(); 1045 QualType OutputType = S.getOutputExpr(Output)->getType(); 1046 QualType InputTy = InputExpr->getType(); 1047 1048 if (getContext().getTypeSize(OutputType) > 1049 getContext().getTypeSize(InputTy)) { 1050 // Use ptrtoint as appropriate so that we can do our extension. 1051 if (isa<llvm::PointerType>(Arg->getType())) 1052 Arg = Builder.CreatePtrToInt(Arg, 1053 llvm::IntegerType::get(VMContext, LLVMPointerWidth)); 1054 const llvm::Type *OutputTy = ConvertType(OutputType); 1055 if (isa<llvm::IntegerType>(OutputTy)) 1056 Arg = Builder.CreateZExt(Arg, OutputTy); 1057 else 1058 Arg = Builder.CreateFPExt(Arg, OutputTy); 1059 } 1060 } 1061 1062 1063 ArgTypes.push_back(Arg->getType()); 1064 Args.push_back(Arg); 1065 Constraints += InputConstraint; 1066 } 1067 1068 // Append the "input" part of inout constraints last. 1069 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 1070 ArgTypes.push_back(InOutArgTypes[i]); 1071 Args.push_back(InOutArgs[i]); 1072 } 1073 Constraints += InOutConstraints; 1074 1075 // Clobbers 1076 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 1077 llvm::StringRef Clobber = S.getClobber(i)->getString(); 1078 1079 Clobber = Target.getNormalizedGCCRegisterName(Clobber); 1080 1081 if (i != 0 || NumConstraints != 0) 1082 Constraints += ','; 1083 1084 Constraints += "~{"; 1085 Constraints += Clobber; 1086 Constraints += '}'; 1087 } 1088 1089 // Add machine specific clobbers 1090 std::string MachineClobbers = Target.getClobbers(); 1091 if (!MachineClobbers.empty()) { 1092 if (!Constraints.empty()) 1093 Constraints += ','; 1094 Constraints += MachineClobbers; 1095 } 1096 1097 const llvm::Type *ResultType; 1098 if (ResultRegTypes.empty()) 1099 ResultType = llvm::Type::getVoidTy(VMContext); 1100 else if (ResultRegTypes.size() == 1) 1101 ResultType = ResultRegTypes[0]; 1102 else 1103 ResultType = llvm::StructType::get(VMContext, ResultRegTypes); 1104 1105 const llvm::FunctionType *FTy = 1106 llvm::FunctionType::get(ResultType, ArgTypes, false); 1107 1108 llvm::InlineAsm *IA = 1109 llvm::InlineAsm::get(FTy, AsmString, Constraints, 1110 S.isVolatile() || S.getNumOutputs() == 0); 1111 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end()); 1112 Result->addAttribute(~0, llvm::Attribute::NoUnwind); 1113 1114 // Slap the source location of the inline asm into a !srcloc metadata on the 1115 // call. 1116 unsigned LocID = S.getAsmString()->getLocStart().getRawEncoding(); 1117 llvm::Value *LocIDC = 1118 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LocID); 1119 Result->setMetadata("srcloc", llvm::MDNode::get(VMContext, &LocIDC, 1)); 1120 1121 // Extract all of the register value results from the asm. 1122 std::vector<llvm::Value*> RegResults; 1123 if (ResultRegTypes.size() == 1) { 1124 RegResults.push_back(Result); 1125 } else { 1126 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 1127 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult"); 1128 RegResults.push_back(Tmp); 1129 } 1130 } 1131 1132 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 1133 llvm::Value *Tmp = RegResults[i]; 1134 1135 // If the result type of the LLVM IR asm doesn't match the result type of 1136 // the expression, do the conversion. 1137 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 1138 const llvm::Type *TruncTy = ResultTruncRegTypes[i]; 1139 1140 // Truncate the integer result to the right size, note that TruncTy can be 1141 // a pointer. 1142 if (TruncTy->isFloatingPointTy()) 1143 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 1144 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 1145 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy); 1146 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, 1147 (unsigned)ResSize)); 1148 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 1149 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 1150 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType()); 1151 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext, 1152 (unsigned)TmpSize)); 1153 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1154 } else if (TruncTy->isIntegerTy()) { 1155 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 1156 } 1157 } 1158 1159 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i], 1160 ResultRegQualTys[i]); 1161 } 1162 } 1163