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