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