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