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