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