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