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