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