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