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