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