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