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