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