1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Stmt nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGDebugInfo.h" 14 #include "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/Attr.h" 19 #include "clang/AST/StmtVisitor.h" 20 #include "clang/Basic/Builtins.h" 21 #include "clang/Basic/DiagnosticSema.h" 22 #include "clang/Basic/PrettyStackTrace.h" 23 #include "clang/Basic/SourceManager.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "llvm/ADT/SmallSet.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/InlineAsm.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/Support/SaveAndRestore.h" 32 33 using namespace clang; 34 using namespace CodeGen; 35 36 //===----------------------------------------------------------------------===// 37 // Statement Emission 38 //===----------------------------------------------------------------------===// 39 40 void CodeGenFunction::EmitStopPoint(const Stmt *S) { 41 if (CGDebugInfo *DI = getDebugInfo()) { 42 SourceLocation Loc; 43 Loc = S->getBeginLoc(); 44 DI->EmitLocation(Builder, Loc); 45 46 LastStopPoint = Loc; 47 } 48 } 49 50 void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) { 51 assert(S && "Null statement?"); 52 PGO.setCurrentStmt(S); 53 54 // These statements have their own debug info handling. 55 if (EmitSimpleStmt(S, Attrs)) 56 return; 57 58 // Check if we are generating unreachable code. 59 if (!HaveInsertPoint()) { 60 // If so, and the statement doesn't contain a label, then we do not need to 61 // generate actual code. This is safe because (1) the current point is 62 // unreachable, so we don't need to execute the code, and (2) we've already 63 // handled the statements which update internal data structures (like the 64 // local variable map) which could be used by subsequent statements. 65 if (!ContainsLabel(S)) { 66 // Verify that any decl statements were handled as simple, they may be in 67 // scope of subsequent reachable statements. 68 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!"); 69 return; 70 } 71 72 // Otherwise, make a new block to hold the code. 73 EnsureInsertPoint(); 74 } 75 76 // Generate a stoppoint if we are emitting debug info. 77 EmitStopPoint(S); 78 79 // Ignore all OpenMP directives except for simd if OpenMP with Simd is 80 // enabled. 81 if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) { 82 if (const auto *D = dyn_cast<OMPExecutableDirective>(S)) { 83 EmitSimpleOMPExecutableDirective(*D); 84 return; 85 } 86 } 87 88 switch (S->getStmtClass()) { 89 case Stmt::NoStmtClass: 90 case Stmt::CXXCatchStmtClass: 91 case Stmt::SEHExceptStmtClass: 92 case Stmt::SEHFinallyStmtClass: 93 case Stmt::MSDependentExistsStmtClass: 94 llvm_unreachable("invalid statement class to emit generically"); 95 case Stmt::NullStmtClass: 96 case Stmt::CompoundStmtClass: 97 case Stmt::DeclStmtClass: 98 case Stmt::LabelStmtClass: 99 case Stmt::AttributedStmtClass: 100 case Stmt::GotoStmtClass: 101 case Stmt::BreakStmtClass: 102 case Stmt::ContinueStmtClass: 103 case Stmt::DefaultStmtClass: 104 case Stmt::CaseStmtClass: 105 case Stmt::SEHLeaveStmtClass: 106 llvm_unreachable("should have emitted these statements as simple"); 107 108 #define STMT(Type, Base) 109 #define ABSTRACT_STMT(Op) 110 #define EXPR(Type, Base) \ 111 case Stmt::Type##Class: 112 #include "clang/AST/StmtNodes.inc" 113 { 114 // Remember the block we came in on. 115 llvm::BasicBlock *incoming = Builder.GetInsertBlock(); 116 assert(incoming && "expression emission must have an insertion point"); 117 118 EmitIgnoredExpr(cast<Expr>(S)); 119 120 llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); 121 assert(outgoing && "expression emission cleared block!"); 122 123 // The expression emitters assume (reasonably!) that the insertion 124 // point is always set. To maintain that, the call-emission code 125 // for noreturn functions has to enter a new block with no 126 // predecessors. We want to kill that block and mark the current 127 // insertion point unreachable in the common case of a call like 128 // "exit();". Since expression emission doesn't otherwise create 129 // blocks with no predecessors, we can just test for that. 130 // However, we must be careful not to do this to our incoming 131 // block, because *statement* emission does sometimes create 132 // reachable blocks which will have no predecessors until later in 133 // the function. This occurs with, e.g., labels that are not 134 // reachable by fallthrough. 135 if (incoming != outgoing && outgoing->use_empty()) { 136 outgoing->eraseFromParent(); 137 Builder.ClearInsertionPoint(); 138 } 139 break; 140 } 141 142 case Stmt::IndirectGotoStmtClass: 143 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break; 144 145 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break; 146 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S), Attrs); break; 147 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S), Attrs); break; 148 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S), Attrs); break; 149 150 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break; 151 152 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break; 153 case Stmt::GCCAsmStmtClass: // Intentional fall-through. 154 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break; 155 case Stmt::CoroutineBodyStmtClass: 156 EmitCoroutineBody(cast<CoroutineBodyStmt>(*S)); 157 break; 158 case Stmt::CoreturnStmtClass: 159 EmitCoreturnStmt(cast<CoreturnStmt>(*S)); 160 break; 161 case Stmt::CapturedStmtClass: { 162 const CapturedStmt *CS = cast<CapturedStmt>(S); 163 EmitCapturedStmt(*CS, CS->getCapturedRegionKind()); 164 } 165 break; 166 case Stmt::ObjCAtTryStmtClass: 167 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S)); 168 break; 169 case Stmt::ObjCAtCatchStmtClass: 170 llvm_unreachable( 171 "@catch statements should be handled by EmitObjCAtTryStmt"); 172 case Stmt::ObjCAtFinallyStmtClass: 173 llvm_unreachable( 174 "@finally statements should be handled by EmitObjCAtTryStmt"); 175 case Stmt::ObjCAtThrowStmtClass: 176 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S)); 177 break; 178 case Stmt::ObjCAtSynchronizedStmtClass: 179 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S)); 180 break; 181 case Stmt::ObjCForCollectionStmtClass: 182 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S)); 183 break; 184 case Stmt::ObjCAutoreleasePoolStmtClass: 185 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S)); 186 break; 187 188 case Stmt::CXXTryStmtClass: 189 EmitCXXTryStmt(cast<CXXTryStmt>(*S)); 190 break; 191 case Stmt::CXXForRangeStmtClass: 192 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S), Attrs); 193 break; 194 case Stmt::SEHTryStmtClass: 195 EmitSEHTryStmt(cast<SEHTryStmt>(*S)); 196 break; 197 case Stmt::OMPCanonicalLoopClass: 198 EmitOMPCanonicalLoop(cast<OMPCanonicalLoop>(S)); 199 break; 200 case Stmt::OMPParallelDirectiveClass: 201 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S)); 202 break; 203 case Stmt::OMPSimdDirectiveClass: 204 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S)); 205 break; 206 case Stmt::OMPTileDirectiveClass: 207 EmitOMPTileDirective(cast<OMPTileDirective>(*S)); 208 break; 209 case Stmt::OMPForDirectiveClass: 210 EmitOMPForDirective(cast<OMPForDirective>(*S)); 211 break; 212 case Stmt::OMPForSimdDirectiveClass: 213 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S)); 214 break; 215 case Stmt::OMPSectionsDirectiveClass: 216 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S)); 217 break; 218 case Stmt::OMPSectionDirectiveClass: 219 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S)); 220 break; 221 case Stmt::OMPSingleDirectiveClass: 222 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S)); 223 break; 224 case Stmt::OMPMasterDirectiveClass: 225 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S)); 226 break; 227 case Stmt::OMPCriticalDirectiveClass: 228 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S)); 229 break; 230 case Stmt::OMPParallelForDirectiveClass: 231 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S)); 232 break; 233 case Stmt::OMPParallelForSimdDirectiveClass: 234 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S)); 235 break; 236 case Stmt::OMPParallelMasterDirectiveClass: 237 EmitOMPParallelMasterDirective(cast<OMPParallelMasterDirective>(*S)); 238 break; 239 case Stmt::OMPParallelSectionsDirectiveClass: 240 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S)); 241 break; 242 case Stmt::OMPTaskDirectiveClass: 243 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S)); 244 break; 245 case Stmt::OMPTaskyieldDirectiveClass: 246 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S)); 247 break; 248 case Stmt::OMPBarrierDirectiveClass: 249 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S)); 250 break; 251 case Stmt::OMPTaskwaitDirectiveClass: 252 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S)); 253 break; 254 case Stmt::OMPTaskgroupDirectiveClass: 255 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S)); 256 break; 257 case Stmt::OMPFlushDirectiveClass: 258 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S)); 259 break; 260 case Stmt::OMPDepobjDirectiveClass: 261 EmitOMPDepobjDirective(cast<OMPDepobjDirective>(*S)); 262 break; 263 case Stmt::OMPScanDirectiveClass: 264 EmitOMPScanDirective(cast<OMPScanDirective>(*S)); 265 break; 266 case Stmt::OMPOrderedDirectiveClass: 267 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S)); 268 break; 269 case Stmt::OMPAtomicDirectiveClass: 270 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S)); 271 break; 272 case Stmt::OMPTargetDirectiveClass: 273 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S)); 274 break; 275 case Stmt::OMPTeamsDirectiveClass: 276 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S)); 277 break; 278 case Stmt::OMPCancellationPointDirectiveClass: 279 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S)); 280 break; 281 case Stmt::OMPCancelDirectiveClass: 282 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S)); 283 break; 284 case Stmt::OMPTargetDataDirectiveClass: 285 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S)); 286 break; 287 case Stmt::OMPTargetEnterDataDirectiveClass: 288 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S)); 289 break; 290 case Stmt::OMPTargetExitDataDirectiveClass: 291 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S)); 292 break; 293 case Stmt::OMPTargetParallelDirectiveClass: 294 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S)); 295 break; 296 case Stmt::OMPTargetParallelForDirectiveClass: 297 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S)); 298 break; 299 case Stmt::OMPTaskLoopDirectiveClass: 300 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S)); 301 break; 302 case Stmt::OMPTaskLoopSimdDirectiveClass: 303 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S)); 304 break; 305 case Stmt::OMPMasterTaskLoopDirectiveClass: 306 EmitOMPMasterTaskLoopDirective(cast<OMPMasterTaskLoopDirective>(*S)); 307 break; 308 case Stmt::OMPMasterTaskLoopSimdDirectiveClass: 309 EmitOMPMasterTaskLoopSimdDirective( 310 cast<OMPMasterTaskLoopSimdDirective>(*S)); 311 break; 312 case Stmt::OMPParallelMasterTaskLoopDirectiveClass: 313 EmitOMPParallelMasterTaskLoopDirective( 314 cast<OMPParallelMasterTaskLoopDirective>(*S)); 315 break; 316 case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: 317 EmitOMPParallelMasterTaskLoopSimdDirective( 318 cast<OMPParallelMasterTaskLoopSimdDirective>(*S)); 319 break; 320 case Stmt::OMPDistributeDirectiveClass: 321 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S)); 322 break; 323 case Stmt::OMPTargetUpdateDirectiveClass: 324 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S)); 325 break; 326 case Stmt::OMPDistributeParallelForDirectiveClass: 327 EmitOMPDistributeParallelForDirective( 328 cast<OMPDistributeParallelForDirective>(*S)); 329 break; 330 case Stmt::OMPDistributeParallelForSimdDirectiveClass: 331 EmitOMPDistributeParallelForSimdDirective( 332 cast<OMPDistributeParallelForSimdDirective>(*S)); 333 break; 334 case Stmt::OMPDistributeSimdDirectiveClass: 335 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S)); 336 break; 337 case Stmt::OMPTargetParallelForSimdDirectiveClass: 338 EmitOMPTargetParallelForSimdDirective( 339 cast<OMPTargetParallelForSimdDirective>(*S)); 340 break; 341 case Stmt::OMPTargetSimdDirectiveClass: 342 EmitOMPTargetSimdDirective(cast<OMPTargetSimdDirective>(*S)); 343 break; 344 case Stmt::OMPTeamsDistributeDirectiveClass: 345 EmitOMPTeamsDistributeDirective(cast<OMPTeamsDistributeDirective>(*S)); 346 break; 347 case Stmt::OMPTeamsDistributeSimdDirectiveClass: 348 EmitOMPTeamsDistributeSimdDirective( 349 cast<OMPTeamsDistributeSimdDirective>(*S)); 350 break; 351 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: 352 EmitOMPTeamsDistributeParallelForSimdDirective( 353 cast<OMPTeamsDistributeParallelForSimdDirective>(*S)); 354 break; 355 case Stmt::OMPTeamsDistributeParallelForDirectiveClass: 356 EmitOMPTeamsDistributeParallelForDirective( 357 cast<OMPTeamsDistributeParallelForDirective>(*S)); 358 break; 359 case Stmt::OMPTargetTeamsDirectiveClass: 360 EmitOMPTargetTeamsDirective(cast<OMPTargetTeamsDirective>(*S)); 361 break; 362 case Stmt::OMPTargetTeamsDistributeDirectiveClass: 363 EmitOMPTargetTeamsDistributeDirective( 364 cast<OMPTargetTeamsDistributeDirective>(*S)); 365 break; 366 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: 367 EmitOMPTargetTeamsDistributeParallelForDirective( 368 cast<OMPTargetTeamsDistributeParallelForDirective>(*S)); 369 break; 370 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: 371 EmitOMPTargetTeamsDistributeParallelForSimdDirective( 372 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S)); 373 break; 374 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: 375 EmitOMPTargetTeamsDistributeSimdDirective( 376 cast<OMPTargetTeamsDistributeSimdDirective>(*S)); 377 break; 378 case Stmt::OMPInteropDirectiveClass: 379 llvm_unreachable("Interop directive not supported yet."); 380 break; 381 case Stmt::OMPDispatchDirectiveClass: 382 llvm_unreachable("Dispatch directive not supported yet."); 383 break; 384 case Stmt::OMPMaskedDirectiveClass: 385 llvm_unreachable("Masked directive not supported yet."); 386 break; 387 } 388 } 389 390 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S, 391 ArrayRef<const Attr *> Attrs) { 392 switch (S->getStmtClass()) { 393 default: 394 return false; 395 case Stmt::NullStmtClass: 396 break; 397 case Stmt::CompoundStmtClass: 398 EmitCompoundStmt(cast<CompoundStmt>(*S)); 399 break; 400 case Stmt::DeclStmtClass: 401 EmitDeclStmt(cast<DeclStmt>(*S)); 402 break; 403 case Stmt::LabelStmtClass: 404 EmitLabelStmt(cast<LabelStmt>(*S)); 405 break; 406 case Stmt::AttributedStmtClass: 407 EmitAttributedStmt(cast<AttributedStmt>(*S)); 408 break; 409 case Stmt::GotoStmtClass: 410 EmitGotoStmt(cast<GotoStmt>(*S)); 411 break; 412 case Stmt::BreakStmtClass: 413 EmitBreakStmt(cast<BreakStmt>(*S)); 414 break; 415 case Stmt::ContinueStmtClass: 416 EmitContinueStmt(cast<ContinueStmt>(*S)); 417 break; 418 case Stmt::DefaultStmtClass: 419 EmitDefaultStmt(cast<DefaultStmt>(*S), Attrs); 420 break; 421 case Stmt::CaseStmtClass: 422 EmitCaseStmt(cast<CaseStmt>(*S), Attrs); 423 break; 424 case Stmt::SEHLeaveStmtClass: 425 EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); 426 break; 427 } 428 return true; 429 } 430 431 /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, 432 /// this captures the expression result of the last sub-statement and returns it 433 /// (for use by the statement expression extension). 434 Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, 435 AggValueSlot AggSlot) { 436 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), 437 "LLVM IR generation of compound statement ('{}')"); 438 439 // Keep track of the current cleanup stack depth, including debug scopes. 440 LexicalScope Scope(*this, S.getSourceRange()); 441 442 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot); 443 } 444 445 Address 446 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, 447 bool GetLast, 448 AggValueSlot AggSlot) { 449 450 const Stmt *ExprResult = S.getStmtExprResult(); 451 assert((!GetLast || (GetLast && ExprResult)) && 452 "If GetLast is true then the CompoundStmt must have a StmtExprResult"); 453 454 Address RetAlloca = Address::invalid(); 455 456 for (auto *CurStmt : S.body()) { 457 if (GetLast && ExprResult == CurStmt) { 458 // We have to special case labels here. They are statements, but when put 459 // at the end of a statement expression, they yield the value of their 460 // subexpression. Handle this by walking through all labels we encounter, 461 // emitting them before we evaluate the subexpr. 462 // Similar issues arise for attributed statements. 463 while (!isa<Expr>(ExprResult)) { 464 if (const auto *LS = dyn_cast<LabelStmt>(ExprResult)) { 465 EmitLabel(LS->getDecl()); 466 ExprResult = LS->getSubStmt(); 467 } else if (const auto *AS = dyn_cast<AttributedStmt>(ExprResult)) { 468 // FIXME: Update this if we ever have attributes that affect the 469 // semantics of an expression. 470 ExprResult = AS->getSubStmt(); 471 } else { 472 llvm_unreachable("unknown value statement"); 473 } 474 } 475 476 EnsureInsertPoint(); 477 478 const Expr *E = cast<Expr>(ExprResult); 479 QualType ExprTy = E->getType(); 480 if (hasAggregateEvaluationKind(ExprTy)) { 481 EmitAggExpr(E, AggSlot); 482 } else { 483 // We can't return an RValue here because there might be cleanups at 484 // the end of the StmtExpr. Because of that, we have to emit the result 485 // here into a temporary alloca. 486 RetAlloca = CreateMemTemp(ExprTy); 487 EmitAnyExprToMem(E, RetAlloca, Qualifiers(), 488 /*IsInit*/ false); 489 } 490 } else { 491 EmitStmt(CurStmt); 492 } 493 } 494 495 return RetAlloca; 496 } 497 498 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { 499 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator()); 500 501 // If there is a cleanup stack, then we it isn't worth trying to 502 // simplify this block (we would need to remove it from the scope map 503 // and cleanup entry). 504 if (!EHStack.empty()) 505 return; 506 507 // Can only simplify direct branches. 508 if (!BI || !BI->isUnconditional()) 509 return; 510 511 // Can only simplify empty blocks. 512 if (BI->getIterator() != BB->begin()) 513 return; 514 515 BB->replaceAllUsesWith(BI->getSuccessor(0)); 516 BI->eraseFromParent(); 517 BB->eraseFromParent(); 518 } 519 520 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { 521 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 522 523 // Fall out of the current block (if necessary). 524 EmitBranch(BB); 525 526 if (IsFinished && BB->use_empty()) { 527 delete BB; 528 return; 529 } 530 531 // Place the block after the current block, if possible, or else at 532 // the end of the function. 533 if (CurBB && CurBB->getParent()) 534 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB); 535 else 536 CurFn->getBasicBlockList().push_back(BB); 537 Builder.SetInsertPoint(BB); 538 } 539 540 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { 541 // Emit a branch from the current block to the target one if this 542 // was a real block. If this was just a fall-through block after a 543 // terminator, don't emit it. 544 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 545 546 if (!CurBB || CurBB->getTerminator()) { 547 // If there is no insert point or the previous block is already 548 // terminated, don't touch it. 549 } else { 550 // Otherwise, create a fall-through branch. 551 Builder.CreateBr(Target); 552 } 553 554 Builder.ClearInsertionPoint(); 555 } 556 557 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) { 558 bool inserted = false; 559 for (llvm::User *u : block->users()) { 560 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) { 561 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(), 562 block); 563 inserted = true; 564 break; 565 } 566 } 567 568 if (!inserted) 569 CurFn->getBasicBlockList().push_back(block); 570 571 Builder.SetInsertPoint(block); 572 } 573 574 CodeGenFunction::JumpDest 575 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) { 576 JumpDest &Dest = LabelMap[D]; 577 if (Dest.isValid()) return Dest; 578 579 // Create, but don't insert, the new block. 580 Dest = JumpDest(createBasicBlock(D->getName()), 581 EHScopeStack::stable_iterator::invalid(), 582 NextCleanupDestIndex++); 583 return Dest; 584 } 585 586 void CodeGenFunction::EmitLabel(const LabelDecl *D) { 587 // Add this label to the current lexical scope if we're within any 588 // normal cleanups. Jumps "in" to this label --- when permitted by 589 // the language --- may need to be routed around such cleanups. 590 if (EHStack.hasNormalCleanups() && CurLexicalScope) 591 CurLexicalScope->addLabel(D); 592 593 JumpDest &Dest = LabelMap[D]; 594 595 // If we didn't need a forward reference to this label, just go 596 // ahead and create a destination at the current scope. 597 if (!Dest.isValid()) { 598 Dest = getJumpDestInCurrentScope(D->getName()); 599 600 // Otherwise, we need to give this label a target depth and remove 601 // it from the branch-fixups list. 602 } else { 603 assert(!Dest.getScopeDepth().isValid() && "already emitted label!"); 604 Dest.setScopeDepth(EHStack.stable_begin()); 605 ResolveBranchFixups(Dest.getBlock()); 606 } 607 608 EmitBlock(Dest.getBlock()); 609 610 // Emit debug info for labels. 611 if (CGDebugInfo *DI = getDebugInfo()) { 612 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { 613 DI->setLocation(D->getLocation()); 614 DI->EmitLabel(D, Builder); 615 } 616 } 617 618 incrementProfileCounter(D->getStmt()); 619 } 620 621 /// Change the cleanup scope of the labels in this lexical scope to 622 /// match the scope of the enclosing context. 623 void CodeGenFunction::LexicalScope::rescopeLabels() { 624 assert(!Labels.empty()); 625 EHScopeStack::stable_iterator innermostScope 626 = CGF.EHStack.getInnermostNormalCleanup(); 627 628 // Change the scope depth of all the labels. 629 for (SmallVectorImpl<const LabelDecl*>::const_iterator 630 i = Labels.begin(), e = Labels.end(); i != e; ++i) { 631 assert(CGF.LabelMap.count(*i)); 632 JumpDest &dest = CGF.LabelMap.find(*i)->second; 633 assert(dest.getScopeDepth().isValid()); 634 assert(innermostScope.encloses(dest.getScopeDepth())); 635 dest.setScopeDepth(innermostScope); 636 } 637 638 // Reparent the labels if the new scope also has cleanups. 639 if (innermostScope != EHScopeStack::stable_end() && ParentScope) { 640 ParentScope->Labels.append(Labels.begin(), Labels.end()); 641 } 642 } 643 644 645 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { 646 EmitLabel(S.getDecl()); 647 EmitStmt(S.getSubStmt()); 648 } 649 650 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) { 651 bool nomerge = false; 652 for (const auto *A : S.getAttrs()) 653 if (A->getKind() == attr::NoMerge) { 654 nomerge = true; 655 break; 656 } 657 SaveAndRestore<bool> save_nomerge(InNoMergeAttributedStmt, nomerge); 658 EmitStmt(S.getSubStmt(), S.getAttrs()); 659 } 660 661 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { 662 // If this code is reachable then emit a stop point (if generating 663 // debug info). We have to do this ourselves because we are on the 664 // "simple" statement path. 665 if (HaveInsertPoint()) 666 EmitStopPoint(&S); 667 668 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel())); 669 } 670 671 672 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { 673 if (const LabelDecl *Target = S.getConstantTarget()) { 674 EmitBranchThroughCleanup(getJumpDestForLabel(Target)); 675 return; 676 } 677 678 // Ensure that we have an i8* for our PHI node. 679 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()), 680 Int8PtrTy, "addr"); 681 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 682 683 // Get the basic block for the indirect goto. 684 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); 685 686 // The first instruction in the block has to be the PHI for the switch dest, 687 // add an entry for this branch. 688 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB); 689 690 EmitBranch(IndGotoBB); 691 } 692 693 void CodeGenFunction::EmitIfStmt(const IfStmt &S) { 694 // C99 6.8.4.1: The first substatement is executed if the expression compares 695 // unequal to 0. The condition must be a scalar type. 696 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange()); 697 698 if (S.getInit()) 699 EmitStmt(S.getInit()); 700 701 if (S.getConditionVariable()) 702 EmitDecl(*S.getConditionVariable()); 703 704 // If the condition constant folds and can be elided, try to avoid emitting 705 // the condition and the dead arm of the if/else. 706 bool CondConstant; 707 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant, 708 S.isConstexpr())) { 709 // Figure out which block (then or else) is executed. 710 const Stmt *Executed = S.getThen(); 711 const Stmt *Skipped = S.getElse(); 712 if (!CondConstant) // Condition false? 713 std::swap(Executed, Skipped); 714 715 // If the skipped block has no labels in it, just emit the executed block. 716 // This avoids emitting dead code and simplifies the CFG substantially. 717 if (S.isConstexpr() || !ContainsLabel(Skipped)) { 718 if (CondConstant) 719 incrementProfileCounter(&S); 720 if (Executed) { 721 RunCleanupsScope ExecutedScope(*this); 722 EmitStmt(Executed); 723 } 724 return; 725 } 726 } 727 728 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit 729 // the conditional branch. 730 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then"); 731 llvm::BasicBlock *ContBlock = createBasicBlock("if.end"); 732 llvm::BasicBlock *ElseBlock = ContBlock; 733 if (S.getElse()) 734 ElseBlock = createBasicBlock("if.else"); 735 736 // Prefer the PGO based weights over the likelihood attribute. 737 // When the build isn't optimized the metadata isn't used, so don't generate 738 // it. 739 Stmt::Likelihood LH = Stmt::LH_None; 740 uint64_t Count = getProfileCount(S.getThen()); 741 if (!Count && CGM.getCodeGenOpts().OptimizationLevel) 742 LH = Stmt::getLikelihood(S.getThen(), S.getElse()); 743 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Count, LH); 744 745 // Emit the 'then' code. 746 EmitBlock(ThenBlock); 747 incrementProfileCounter(&S); 748 { 749 RunCleanupsScope ThenScope(*this); 750 EmitStmt(S.getThen()); 751 } 752 EmitBranch(ContBlock); 753 754 // Emit the 'else' code if present. 755 if (const Stmt *Else = S.getElse()) { 756 { 757 // There is no need to emit line number for an unconditional branch. 758 auto NL = ApplyDebugLocation::CreateEmpty(*this); 759 EmitBlock(ElseBlock); 760 } 761 { 762 RunCleanupsScope ElseScope(*this); 763 EmitStmt(Else); 764 } 765 { 766 // There is no need to emit line number for an unconditional branch. 767 auto NL = ApplyDebugLocation::CreateEmpty(*this); 768 EmitBranch(ContBlock); 769 } 770 } 771 772 // Emit the continuation block for code after the if. 773 EmitBlock(ContBlock, true); 774 } 775 776 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S, 777 ArrayRef<const Attr *> WhileAttrs) { 778 // Emit the header for the loop, which will also become 779 // the continue target. 780 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond"); 781 EmitBlock(LoopHeader.getBlock()); 782 783 // Create an exit block for when the condition fails, which will 784 // also become the break target. 785 JumpDest LoopExit = getJumpDestInCurrentScope("while.end"); 786 787 // Store the blocks to use for break and continue. 788 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader)); 789 790 // C++ [stmt.while]p2: 791 // When the condition of a while statement is a declaration, the 792 // scope of the variable that is declared extends from its point 793 // of declaration (3.3.2) to the end of the while statement. 794 // [...] 795 // The object created in a condition is destroyed and created 796 // with each iteration of the loop. 797 RunCleanupsScope ConditionScope(*this); 798 799 if (S.getConditionVariable()) 800 EmitDecl(*S.getConditionVariable()); 801 802 // Evaluate the conditional in the while header. C99 6.8.5.1: The 803 // evaluation of the controlling expression takes place before each 804 // execution of the loop body. 805 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 806 807 // while(1) is common, avoid extra exit blocks. Be sure 808 // to correctly handle break/continue though. 809 bool EmitBoolCondBranch = true; 810 bool LoopMustProgress = false; 811 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) { 812 if (C->isOne()) { 813 EmitBoolCondBranch = false; 814 FnIsMustProgress = false; 815 } 816 } else if (LanguageRequiresProgress()) 817 LoopMustProgress = true; 818 819 const SourceRange &R = S.getSourceRange(); 820 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), CGM.getCodeGenOpts(), 821 WhileAttrs, SourceLocToDebugLoc(R.getBegin()), 822 SourceLocToDebugLoc(R.getEnd()), LoopMustProgress); 823 824 // As long as the condition is true, go to the loop body. 825 llvm::BasicBlock *LoopBody = createBasicBlock("while.body"); 826 if (EmitBoolCondBranch) { 827 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 828 if (ConditionScope.requiresCleanups()) 829 ExitBlock = createBasicBlock("while.exit"); 830 llvm::MDNode *Weights = 831 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())); 832 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel) 833 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic( 834 BoolCondVal, Stmt::getLikelihood(S.getBody())); 835 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock, Weights); 836 837 if (ExitBlock != LoopExit.getBlock()) { 838 EmitBlock(ExitBlock); 839 EmitBranchThroughCleanup(LoopExit); 840 } 841 } else if (const Attr *A = Stmt::getLikelihoodAttr(S.getBody())) { 842 CGM.getDiags().Report(A->getLocation(), 843 diag::warn_attribute_has_no_effect_on_infinite_loop) 844 << A << A->getRange(); 845 CGM.getDiags().Report( 846 S.getWhileLoc(), 847 diag::note_attribute_has_no_effect_on_infinite_loop_here) 848 << SourceRange(S.getWhileLoc(), S.getRParenLoc()); 849 } 850 851 // Emit the loop body. We have to emit this in a cleanup scope 852 // because it might be a singleton DeclStmt. 853 { 854 RunCleanupsScope BodyScope(*this); 855 EmitBlock(LoopBody); 856 incrementProfileCounter(&S); 857 EmitStmt(S.getBody()); 858 } 859 860 BreakContinueStack.pop_back(); 861 862 // Immediately force cleanup. 863 ConditionScope.ForceCleanup(); 864 865 EmitStopPoint(&S); 866 // Branch to the loop header again. 867 EmitBranch(LoopHeader.getBlock()); 868 869 LoopStack.pop(); 870 871 // Emit the exit block. 872 EmitBlock(LoopExit.getBlock(), true); 873 874 // The LoopHeader typically is just a branch if we skipped emitting 875 // a branch, try to erase it. 876 if (!EmitBoolCondBranch) 877 SimplifyForwardingBlocks(LoopHeader.getBlock()); 878 } 879 880 void CodeGenFunction::EmitDoStmt(const DoStmt &S, 881 ArrayRef<const Attr *> DoAttrs) { 882 JumpDest LoopExit = getJumpDestInCurrentScope("do.end"); 883 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond"); 884 885 uint64_t ParentCount = getCurrentProfileCount(); 886 887 // Store the blocks to use for break and continue. 888 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond)); 889 890 // Emit the body of the loop. 891 llvm::BasicBlock *LoopBody = createBasicBlock("do.body"); 892 893 EmitBlockWithFallThrough(LoopBody, &S); 894 { 895 RunCleanupsScope BodyScope(*this); 896 EmitStmt(S.getBody()); 897 } 898 899 EmitBlock(LoopCond.getBlock()); 900 901 // C99 6.8.5.2: "The evaluation of the controlling expression takes place 902 // after each execution of the loop body." 903 904 // Evaluate the conditional in the while header. 905 // C99 6.8.5p2/p4: The first substatement is executed if the expression 906 // compares unequal to 0. The condition must be a scalar type. 907 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 908 909 BreakContinueStack.pop_back(); 910 911 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure 912 // to correctly handle break/continue though. 913 bool EmitBoolCondBranch = true; 914 bool LoopMustProgress = false; 915 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) { 916 if (C->isZero()) 917 EmitBoolCondBranch = false; 918 else if (C->isOne()) 919 FnIsMustProgress = false; 920 } else if (LanguageRequiresProgress()) 921 LoopMustProgress = true; 922 923 const SourceRange &R = S.getSourceRange(); 924 LoopStack.push(LoopBody, CGM.getContext(), CGM.getCodeGenOpts(), DoAttrs, 925 SourceLocToDebugLoc(R.getBegin()), 926 SourceLocToDebugLoc(R.getEnd()), LoopMustProgress); 927 928 // As long as the condition is true, iterate the loop. 929 if (EmitBoolCondBranch) { 930 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount; 931 Builder.CreateCondBr( 932 BoolCondVal, LoopBody, LoopExit.getBlock(), 933 createProfileWeightsForLoop(S.getCond(), BackedgeCount)); 934 } 935 936 LoopStack.pop(); 937 938 // Emit the exit block. 939 EmitBlock(LoopExit.getBlock()); 940 941 // The DoCond block typically is just a branch if we skipped 942 // emitting a branch, try to erase it. 943 if (!EmitBoolCondBranch) 944 SimplifyForwardingBlocks(LoopCond.getBlock()); 945 } 946 947 void CodeGenFunction::EmitForStmt(const ForStmt &S, 948 ArrayRef<const Attr *> ForAttrs) { 949 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 950 951 LexicalScope ForScope(*this, S.getSourceRange()); 952 953 // Evaluate the first part before the loop. 954 if (S.getInit()) 955 EmitStmt(S.getInit()); 956 957 // Start the loop with a block that tests the condition. 958 // If there's an increment, the continue scope will be overwritten 959 // later. 960 JumpDest CondDest = getJumpDestInCurrentScope("for.cond"); 961 llvm::BasicBlock *CondBlock = CondDest.getBlock(); 962 EmitBlock(CondBlock); 963 964 bool LoopMustProgress = false; 965 Expr::EvalResult Result; 966 if (LanguageRequiresProgress()) { 967 if (!S.getCond()) { 968 FnIsMustProgress = false; 969 } else if (!S.getCond()->EvaluateAsInt(Result, getContext())) { 970 LoopMustProgress = true; 971 } 972 } 973 974 const SourceRange &R = S.getSourceRange(); 975 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs, 976 SourceLocToDebugLoc(R.getBegin()), 977 SourceLocToDebugLoc(R.getEnd()), LoopMustProgress); 978 979 // Create a cleanup scope for the condition variable cleanups. 980 LexicalScope ConditionScope(*this, S.getSourceRange()); 981 982 // If the for loop doesn't have an increment we can just use the condition as 983 // the continue block. Otherwise, if there is no condition variable, we can 984 // form the continue block now. If there is a condition variable, we can't 985 // form the continue block until after we've emitted the condition, because 986 // the condition is in scope in the increment, but Sema's jump diagnostics 987 // ensure that there are no continues from the condition variable that jump 988 // to the loop increment. 989 JumpDest Continue; 990 if (!S.getInc()) 991 Continue = CondDest; 992 else if (!S.getConditionVariable()) 993 Continue = getJumpDestInCurrentScope("for.inc"); 994 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 995 996 if (S.getCond()) { 997 // If the for statement has a condition scope, emit the local variable 998 // declaration. 999 if (S.getConditionVariable()) { 1000 EmitDecl(*S.getConditionVariable()); 1001 1002 // We have entered the condition variable's scope, so we're now able to 1003 // jump to the continue block. 1004 Continue = S.getInc() ? getJumpDestInCurrentScope("for.inc") : CondDest; 1005 BreakContinueStack.back().ContinueBlock = Continue; 1006 } 1007 1008 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 1009 // If there are any cleanups between here and the loop-exit scope, 1010 // create a block to stage a loop exit along. 1011 if (ForScope.requiresCleanups()) 1012 ExitBlock = createBasicBlock("for.cond.cleanup"); 1013 1014 // As long as the condition is true, iterate the loop. 1015 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1016 1017 // C99 6.8.5p2/p4: The first substatement is executed if the expression 1018 // compares unequal to 0. The condition must be a scalar type. 1019 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 1020 llvm::MDNode *Weights = 1021 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())); 1022 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel) 1023 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic( 1024 BoolCondVal, Stmt::getLikelihood(S.getBody())); 1025 1026 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal)) 1027 if (C->isOne()) 1028 FnIsMustProgress = false; 1029 1030 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights); 1031 1032 if (ExitBlock != LoopExit.getBlock()) { 1033 EmitBlock(ExitBlock); 1034 EmitBranchThroughCleanup(LoopExit); 1035 } 1036 1037 EmitBlock(ForBody); 1038 } else { 1039 // Treat it as a non-zero constant. Don't even create a new block for the 1040 // body, just fall into it. 1041 } 1042 incrementProfileCounter(&S); 1043 1044 { 1045 // Create a separate cleanup scope for the body, in case it is not 1046 // a compound statement. 1047 RunCleanupsScope BodyScope(*this); 1048 EmitStmt(S.getBody()); 1049 } 1050 1051 // If there is an increment, emit it next. 1052 if (S.getInc()) { 1053 EmitBlock(Continue.getBlock()); 1054 EmitStmt(S.getInc()); 1055 } 1056 1057 BreakContinueStack.pop_back(); 1058 1059 ConditionScope.ForceCleanup(); 1060 1061 EmitStopPoint(&S); 1062 EmitBranch(CondBlock); 1063 1064 ForScope.ForceCleanup(); 1065 1066 LoopStack.pop(); 1067 1068 // Emit the fall-through block. 1069 EmitBlock(LoopExit.getBlock(), true); 1070 } 1071 1072 void 1073 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S, 1074 ArrayRef<const Attr *> ForAttrs) { 1075 JumpDest LoopExit = getJumpDestInCurrentScope("for.end"); 1076 1077 LexicalScope ForScope(*this, S.getSourceRange()); 1078 1079 // Evaluate the first pieces before the loop. 1080 if (S.getInit()) 1081 EmitStmt(S.getInit()); 1082 EmitStmt(S.getRangeStmt()); 1083 EmitStmt(S.getBeginStmt()); 1084 EmitStmt(S.getEndStmt()); 1085 1086 // Start the loop with a block that tests the condition. 1087 // If there's an increment, the continue scope will be overwritten 1088 // later. 1089 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1090 EmitBlock(CondBlock); 1091 1092 const SourceRange &R = S.getSourceRange(); 1093 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), ForAttrs, 1094 SourceLocToDebugLoc(R.getBegin()), 1095 SourceLocToDebugLoc(R.getEnd())); 1096 1097 // If there are any cleanups between here and the loop-exit scope, 1098 // create a block to stage a loop exit along. 1099 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 1100 if (ForScope.requiresCleanups()) 1101 ExitBlock = createBasicBlock("for.cond.cleanup"); 1102 1103 // The loop body, consisting of the specified body and the loop variable. 1104 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1105 1106 // The body is executed if the expression, contextually converted 1107 // to bool, is true. 1108 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond()); 1109 llvm::MDNode *Weights = 1110 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())); 1111 if (!Weights && CGM.getCodeGenOpts().OptimizationLevel) 1112 BoolCondVal = emitCondLikelihoodViaExpectIntrinsic( 1113 BoolCondVal, Stmt::getLikelihood(S.getBody())); 1114 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock, Weights); 1115 1116 if (ExitBlock != LoopExit.getBlock()) { 1117 EmitBlock(ExitBlock); 1118 EmitBranchThroughCleanup(LoopExit); 1119 } 1120 1121 EmitBlock(ForBody); 1122 incrementProfileCounter(&S); 1123 1124 // Create a block for the increment. In case of a 'continue', we jump there. 1125 JumpDest Continue = getJumpDestInCurrentScope("for.inc"); 1126 1127 // Store the blocks to use for break and continue. 1128 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1129 1130 { 1131 // Create a separate cleanup scope for the loop variable and body. 1132 LexicalScope BodyScope(*this, S.getSourceRange()); 1133 EmitStmt(S.getLoopVarStmt()); 1134 EmitStmt(S.getBody()); 1135 } 1136 1137 EmitStopPoint(&S); 1138 // If there is an increment, emit it next. 1139 EmitBlock(Continue.getBlock()); 1140 EmitStmt(S.getInc()); 1141 1142 BreakContinueStack.pop_back(); 1143 1144 EmitBranch(CondBlock); 1145 1146 ForScope.ForceCleanup(); 1147 1148 LoopStack.pop(); 1149 1150 // Emit the fall-through block. 1151 EmitBlock(LoopExit.getBlock(), true); 1152 } 1153 1154 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { 1155 if (RV.isScalar()) { 1156 Builder.CreateStore(RV.getScalarVal(), ReturnValue); 1157 } else if (RV.isAggregate()) { 1158 LValue Dest = MakeAddrLValue(ReturnValue, Ty); 1159 LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty); 1160 EmitAggregateCopy(Dest, Src, Ty, getOverlapForReturnValue()); 1161 } else { 1162 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty), 1163 /*init*/ true); 1164 } 1165 EmitBranchThroughCleanup(ReturnBlock); 1166 } 1167 1168 namespace { 1169 // RAII struct used to save and restore a return statment's result expression. 1170 struct SaveRetExprRAII { 1171 SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF) 1172 : OldRetExpr(CGF.RetExpr), CGF(CGF) { 1173 CGF.RetExpr = RetExpr; 1174 } 1175 ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; } 1176 const Expr *OldRetExpr; 1177 CodeGenFunction &CGF; 1178 }; 1179 } // namespace 1180 1181 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand 1182 /// if the function returns void, or may be missing one if the function returns 1183 /// non-void. Fun stuff :). 1184 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { 1185 if (requiresReturnValueCheck()) { 1186 llvm::Constant *SLoc = EmitCheckSourceLocation(S.getBeginLoc()); 1187 auto *SLocPtr = 1188 new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false, 1189 llvm::GlobalVariable::PrivateLinkage, SLoc); 1190 SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1191 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(SLocPtr); 1192 assert(ReturnLocation.isValid() && "No valid return location"); 1193 Builder.CreateStore(Builder.CreateBitCast(SLocPtr, Int8PtrTy), 1194 ReturnLocation); 1195 } 1196 1197 // Returning from an outlined SEH helper is UB, and we already warn on it. 1198 if (IsOutlinedSEHHelper) { 1199 Builder.CreateUnreachable(); 1200 Builder.ClearInsertionPoint(); 1201 } 1202 1203 // Emit the result value, even if unused, to evaluate the side effects. 1204 const Expr *RV = S.getRetValue(); 1205 1206 // Record the result expression of the return statement. The recorded 1207 // expression is used to determine whether a block capture's lifetime should 1208 // end at the end of the full expression as opposed to the end of the scope 1209 // enclosing the block expression. 1210 // 1211 // This permits a small, easily-implemented exception to our over-conservative 1212 // rules about not jumping to statements following block literals with 1213 // non-trivial cleanups. 1214 SaveRetExprRAII SaveRetExpr(RV, *this); 1215 1216 RunCleanupsScope cleanupScope(*this); 1217 if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(RV)) 1218 RV = EWC->getSubExpr(); 1219 // FIXME: Clean this up by using an LValue for ReturnTemp, 1220 // EmitStoreThroughLValue, and EmitAnyExpr. 1221 // Check if the NRVO candidate was not globalized in OpenMP mode. 1222 if (getLangOpts().ElideConstructors && S.getNRVOCandidate() && 1223 S.getNRVOCandidate()->isNRVOVariable() && 1224 (!getLangOpts().OpenMP || 1225 !CGM.getOpenMPRuntime() 1226 .getAddressOfLocalVariable(*this, S.getNRVOCandidate()) 1227 .isValid())) { 1228 // Apply the named return value optimization for this return statement, 1229 // which means doing nothing: the appropriate result has already been 1230 // constructed into the NRVO variable. 1231 1232 // If there is an NRVO flag for this variable, set it to 1 into indicate 1233 // that the cleanup code should not destroy the variable. 1234 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) 1235 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag); 1236 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) { 1237 // Make sure not to return anything, but evaluate the expression 1238 // for side effects. 1239 if (RV) 1240 EmitAnyExpr(RV); 1241 } else if (!RV) { 1242 // Do nothing (return value is left uninitialized) 1243 } else if (FnRetTy->isReferenceType()) { 1244 // If this function returns a reference, take the address of the expression 1245 // rather than the value. 1246 RValue Result = EmitReferenceBindingToExpr(RV); 1247 Builder.CreateStore(Result.getScalarVal(), ReturnValue); 1248 } else { 1249 switch (getEvaluationKind(RV->getType())) { 1250 case TEK_Scalar: 1251 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue); 1252 break; 1253 case TEK_Complex: 1254 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()), 1255 /*isInit*/ true); 1256 break; 1257 case TEK_Aggregate: 1258 EmitAggExpr(RV, AggValueSlot::forAddr( 1259 ReturnValue, Qualifiers(), 1260 AggValueSlot::IsDestructed, 1261 AggValueSlot::DoesNotNeedGCBarriers, 1262 AggValueSlot::IsNotAliased, 1263 getOverlapForReturnValue())); 1264 break; 1265 } 1266 } 1267 1268 ++NumReturnExprs; 1269 if (!RV || RV->isEvaluatable(getContext())) 1270 ++NumSimpleReturnExprs; 1271 1272 cleanupScope.ForceCleanup(); 1273 EmitBranchThroughCleanup(ReturnBlock); 1274 } 1275 1276 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { 1277 // As long as debug info is modeled with instructions, we have to ensure we 1278 // have a place to insert here and write the stop point here. 1279 if (HaveInsertPoint()) 1280 EmitStopPoint(&S); 1281 1282 for (const auto *I : S.decls()) 1283 EmitDecl(*I); 1284 } 1285 1286 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { 1287 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!"); 1288 1289 // If this code is reachable then emit a stop point (if generating 1290 // debug info). We have to do this ourselves because we are on the 1291 // "simple" statement path. 1292 if (HaveInsertPoint()) 1293 EmitStopPoint(&S); 1294 1295 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock); 1296 } 1297 1298 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { 1299 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 1300 1301 // If this code is reachable then emit a stop point (if generating 1302 // debug info). We have to do this ourselves because we are on the 1303 // "simple" statement path. 1304 if (HaveInsertPoint()) 1305 EmitStopPoint(&S); 1306 1307 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock); 1308 } 1309 1310 /// EmitCaseStmtRange - If case statement range is not too big then 1311 /// add multiple cases to switch instruction, one for each value within 1312 /// the range. If range is too big then emit "if" condition check. 1313 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S, 1314 ArrayRef<const Attr *> Attrs) { 1315 assert(S.getRHS() && "Expected RHS value in CaseStmt"); 1316 1317 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext()); 1318 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext()); 1319 1320 // Emit the code for this case. We do this first to make sure it is 1321 // properly chained from our predecessor before generating the 1322 // switch machinery to enter this block. 1323 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb"); 1324 EmitBlockWithFallThrough(CaseDest, &S); 1325 EmitStmt(S.getSubStmt()); 1326 1327 // If range is empty, do nothing. 1328 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS)) 1329 return; 1330 1331 Stmt::Likelihood LH = Stmt::getLikelihood(Attrs); 1332 llvm::APInt Range = RHS - LHS; 1333 // FIXME: parameters such as this should not be hardcoded. 1334 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) { 1335 // Range is small enough to add multiple switch instruction cases. 1336 uint64_t Total = getProfileCount(&S); 1337 unsigned NCases = Range.getZExtValue() + 1; 1338 // We only have one region counter for the entire set of cases here, so we 1339 // need to divide the weights evenly between the generated cases, ensuring 1340 // that the total weight is preserved. E.g., a weight of 5 over three cases 1341 // will be distributed as weights of 2, 2, and 1. 1342 uint64_t Weight = Total / NCases, Rem = Total % NCases; 1343 for (unsigned I = 0; I != NCases; ++I) { 1344 if (SwitchWeights) 1345 SwitchWeights->push_back(Weight + (Rem ? 1 : 0)); 1346 else if (SwitchLikelihood) 1347 SwitchLikelihood->push_back(LH); 1348 1349 if (Rem) 1350 Rem--; 1351 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest); 1352 ++LHS; 1353 } 1354 return; 1355 } 1356 1357 // The range is too big. Emit "if" condition into a new block, 1358 // making sure to save and restore the current insertion point. 1359 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); 1360 1361 // Push this test onto the chain of range checks (which terminates 1362 // in the default basic block). The switch's default will be changed 1363 // to the top of this chain after switch emission is complete. 1364 llvm::BasicBlock *FalseDest = CaseRangeBlock; 1365 CaseRangeBlock = createBasicBlock("sw.caserange"); 1366 1367 CurFn->getBasicBlockList().push_back(CaseRangeBlock); 1368 Builder.SetInsertPoint(CaseRangeBlock); 1369 1370 // Emit range check. 1371 llvm::Value *Diff = 1372 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS)); 1373 llvm::Value *Cond = 1374 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds"); 1375 1376 llvm::MDNode *Weights = nullptr; 1377 if (SwitchWeights) { 1378 uint64_t ThisCount = getProfileCount(&S); 1379 uint64_t DefaultCount = (*SwitchWeights)[0]; 1380 Weights = createProfileWeights(ThisCount, DefaultCount); 1381 1382 // Since we're chaining the switch default through each large case range, we 1383 // need to update the weight for the default, ie, the first case, to include 1384 // this case. 1385 (*SwitchWeights)[0] += ThisCount; 1386 } else if (SwitchLikelihood) 1387 Cond = emitCondLikelihoodViaExpectIntrinsic(Cond, LH); 1388 1389 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights); 1390 1391 // Restore the appropriate insertion point. 1392 if (RestoreBB) 1393 Builder.SetInsertPoint(RestoreBB); 1394 else 1395 Builder.ClearInsertionPoint(); 1396 } 1397 1398 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S, 1399 ArrayRef<const Attr *> Attrs) { 1400 // If there is no enclosing switch instance that we're aware of, then this 1401 // case statement and its block can be elided. This situation only happens 1402 // when we've constant-folded the switch, are emitting the constant case, 1403 // and part of the constant case includes another case statement. For 1404 // instance: switch (4) { case 4: do { case 5: } while (1); } 1405 if (!SwitchInsn) { 1406 EmitStmt(S.getSubStmt()); 1407 return; 1408 } 1409 1410 // Handle case ranges. 1411 if (S.getRHS()) { 1412 EmitCaseStmtRange(S, Attrs); 1413 return; 1414 } 1415 1416 llvm::ConstantInt *CaseVal = 1417 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext())); 1418 if (SwitchLikelihood) 1419 SwitchLikelihood->push_back(Stmt::getLikelihood(Attrs)); 1420 1421 // If the body of the case is just a 'break', try to not emit an empty block. 1422 // If we're profiling or we're not optimizing, leave the block in for better 1423 // debug and coverage analysis. 1424 if (!CGM.getCodeGenOpts().hasProfileClangInstr() && 1425 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1426 isa<BreakStmt>(S.getSubStmt())) { 1427 JumpDest Block = BreakContinueStack.back().BreakBlock; 1428 1429 // Only do this optimization if there are no cleanups that need emitting. 1430 if (isObviouslyBranchWithoutCleanups(Block)) { 1431 if (SwitchWeights) 1432 SwitchWeights->push_back(getProfileCount(&S)); 1433 SwitchInsn->addCase(CaseVal, Block.getBlock()); 1434 1435 // If there was a fallthrough into this case, make sure to redirect it to 1436 // the end of the switch as well. 1437 if (Builder.GetInsertBlock()) { 1438 Builder.CreateBr(Block.getBlock()); 1439 Builder.ClearInsertionPoint(); 1440 } 1441 return; 1442 } 1443 } 1444 1445 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb"); 1446 EmitBlockWithFallThrough(CaseDest, &S); 1447 if (SwitchWeights) 1448 SwitchWeights->push_back(getProfileCount(&S)); 1449 SwitchInsn->addCase(CaseVal, CaseDest); 1450 1451 // Recursively emitting the statement is acceptable, but is not wonderful for 1452 // code where we have many case statements nested together, i.e.: 1453 // case 1: 1454 // case 2: 1455 // case 3: etc. 1456 // Handling this recursively will create a new block for each case statement 1457 // that falls through to the next case which is IR intensive. It also causes 1458 // deep recursion which can run into stack depth limitations. Handle 1459 // sequential non-range case statements specially. 1460 // 1461 // TODO When the next case has a likelihood attribute the code returns to the 1462 // recursive algorithm. Maybe improve this case if it becomes common practice 1463 // to use a lot of attributes. 1464 const CaseStmt *CurCase = &S; 1465 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt()); 1466 1467 // Otherwise, iteratively add consecutive cases to this switch stmt. 1468 while (NextCase && NextCase->getRHS() == nullptr) { 1469 CurCase = NextCase; 1470 llvm::ConstantInt *CaseVal = 1471 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext())); 1472 1473 if (SwitchWeights) 1474 SwitchWeights->push_back(getProfileCount(NextCase)); 1475 if (CGM.getCodeGenOpts().hasProfileClangInstr()) { 1476 CaseDest = createBasicBlock("sw.bb"); 1477 EmitBlockWithFallThrough(CaseDest, CurCase); 1478 } 1479 // Since this loop is only executed when the CaseStmt has no attributes 1480 // use a hard-coded value. 1481 if (SwitchLikelihood) 1482 SwitchLikelihood->push_back(Stmt::LH_None); 1483 1484 SwitchInsn->addCase(CaseVal, CaseDest); 1485 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt()); 1486 } 1487 1488 // Normal default recursion for non-cases. 1489 EmitStmt(CurCase->getSubStmt()); 1490 } 1491 1492 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S, 1493 ArrayRef<const Attr *> Attrs) { 1494 // If there is no enclosing switch instance that we're aware of, then this 1495 // default statement can be elided. This situation only happens when we've 1496 // constant-folded the switch. 1497 if (!SwitchInsn) { 1498 EmitStmt(S.getSubStmt()); 1499 return; 1500 } 1501 1502 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); 1503 assert(DefaultBlock->empty() && 1504 "EmitDefaultStmt: Default block already defined?"); 1505 1506 if (SwitchLikelihood) 1507 SwitchLikelihood->front() = Stmt::getLikelihood(Attrs); 1508 1509 EmitBlockWithFallThrough(DefaultBlock, &S); 1510 1511 EmitStmt(S.getSubStmt()); 1512 } 1513 1514 /// CollectStatementsForCase - Given the body of a 'switch' statement and a 1515 /// constant value that is being switched on, see if we can dead code eliminate 1516 /// the body of the switch to a simple series of statements to emit. Basically, 1517 /// on a switch (5) we want to find these statements: 1518 /// case 5: 1519 /// printf(...); <-- 1520 /// ++i; <-- 1521 /// break; 1522 /// 1523 /// and add them to the ResultStmts vector. If it is unsafe to do this 1524 /// transformation (for example, one of the elided statements contains a label 1525 /// that might be jumped to), return CSFC_Failure. If we handled it and 'S' 1526 /// should include statements after it (e.g. the printf() line is a substmt of 1527 /// the case) then return CSFC_FallThrough. If we handled it and found a break 1528 /// statement, then return CSFC_Success. 1529 /// 1530 /// If Case is non-null, then we are looking for the specified case, checking 1531 /// that nothing we jump over contains labels. If Case is null, then we found 1532 /// the case and are looking for the break. 1533 /// 1534 /// If the recursive walk actually finds our Case, then we set FoundCase to 1535 /// true. 1536 /// 1537 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success }; 1538 static CSFC_Result CollectStatementsForCase(const Stmt *S, 1539 const SwitchCase *Case, 1540 bool &FoundCase, 1541 SmallVectorImpl<const Stmt*> &ResultStmts) { 1542 // If this is a null statement, just succeed. 1543 if (!S) 1544 return Case ? CSFC_Success : CSFC_FallThrough; 1545 1546 // If this is the switchcase (case 4: or default) that we're looking for, then 1547 // we're in business. Just add the substatement. 1548 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) { 1549 if (S == Case) { 1550 FoundCase = true; 1551 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase, 1552 ResultStmts); 1553 } 1554 1555 // Otherwise, this is some other case or default statement, just ignore it. 1556 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase, 1557 ResultStmts); 1558 } 1559 1560 // If we are in the live part of the code and we found our break statement, 1561 // return a success! 1562 if (!Case && isa<BreakStmt>(S)) 1563 return CSFC_Success; 1564 1565 // If this is a switch statement, then it might contain the SwitchCase, the 1566 // break, or neither. 1567 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1568 // Handle this as two cases: we might be looking for the SwitchCase (if so 1569 // the skipped statements must be skippable) or we might already have it. 1570 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end(); 1571 bool StartedInLiveCode = FoundCase; 1572 unsigned StartSize = ResultStmts.size(); 1573 1574 // If we've not found the case yet, scan through looking for it. 1575 if (Case) { 1576 // Keep track of whether we see a skipped declaration. The code could be 1577 // using the declaration even if it is skipped, so we can't optimize out 1578 // the decl if the kept statements might refer to it. 1579 bool HadSkippedDecl = false; 1580 1581 // If we're looking for the case, just see if we can skip each of the 1582 // substatements. 1583 for (; Case && I != E; ++I) { 1584 HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(*I); 1585 1586 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) { 1587 case CSFC_Failure: return CSFC_Failure; 1588 case CSFC_Success: 1589 // A successful result means that either 1) that the statement doesn't 1590 // have the case and is skippable, or 2) does contain the case value 1591 // and also contains the break to exit the switch. In the later case, 1592 // we just verify the rest of the statements are elidable. 1593 if (FoundCase) { 1594 // If we found the case and skipped declarations, we can't do the 1595 // optimization. 1596 if (HadSkippedDecl) 1597 return CSFC_Failure; 1598 1599 for (++I; I != E; ++I) 1600 if (CodeGenFunction::ContainsLabel(*I, true)) 1601 return CSFC_Failure; 1602 return CSFC_Success; 1603 } 1604 break; 1605 case CSFC_FallThrough: 1606 // If we have a fallthrough condition, then we must have found the 1607 // case started to include statements. Consider the rest of the 1608 // statements in the compound statement as candidates for inclusion. 1609 assert(FoundCase && "Didn't find case but returned fallthrough?"); 1610 // We recursively found Case, so we're not looking for it anymore. 1611 Case = nullptr; 1612 1613 // If we found the case and skipped declarations, we can't do the 1614 // optimization. 1615 if (HadSkippedDecl) 1616 return CSFC_Failure; 1617 break; 1618 } 1619 } 1620 1621 if (!FoundCase) 1622 return CSFC_Success; 1623 1624 assert(!HadSkippedDecl && "fallthrough after skipping decl"); 1625 } 1626 1627 // If we have statements in our range, then we know that the statements are 1628 // live and need to be added to the set of statements we're tracking. 1629 bool AnyDecls = false; 1630 for (; I != E; ++I) { 1631 AnyDecls |= CodeGenFunction::mightAddDeclToScope(*I); 1632 1633 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) { 1634 case CSFC_Failure: return CSFC_Failure; 1635 case CSFC_FallThrough: 1636 // A fallthrough result means that the statement was simple and just 1637 // included in ResultStmt, keep adding them afterwards. 1638 break; 1639 case CSFC_Success: 1640 // A successful result means that we found the break statement and 1641 // stopped statement inclusion. We just ensure that any leftover stmts 1642 // are skippable and return success ourselves. 1643 for (++I; I != E; ++I) 1644 if (CodeGenFunction::ContainsLabel(*I, true)) 1645 return CSFC_Failure; 1646 return CSFC_Success; 1647 } 1648 } 1649 1650 // If we're about to fall out of a scope without hitting a 'break;', we 1651 // can't perform the optimization if there were any decls in that scope 1652 // (we'd lose their end-of-lifetime). 1653 if (AnyDecls) { 1654 // If the entire compound statement was live, there's one more thing we 1655 // can try before giving up: emit the whole thing as a single statement. 1656 // We can do that unless the statement contains a 'break;'. 1657 // FIXME: Such a break must be at the end of a construct within this one. 1658 // We could emit this by just ignoring the BreakStmts entirely. 1659 if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) { 1660 ResultStmts.resize(StartSize); 1661 ResultStmts.push_back(S); 1662 } else { 1663 return CSFC_Failure; 1664 } 1665 } 1666 1667 return CSFC_FallThrough; 1668 } 1669 1670 // Okay, this is some other statement that we don't handle explicitly, like a 1671 // for statement or increment etc. If we are skipping over this statement, 1672 // just verify it doesn't have labels, which would make it invalid to elide. 1673 if (Case) { 1674 if (CodeGenFunction::ContainsLabel(S, true)) 1675 return CSFC_Failure; 1676 return CSFC_Success; 1677 } 1678 1679 // Otherwise, we want to include this statement. Everything is cool with that 1680 // so long as it doesn't contain a break out of the switch we're in. 1681 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure; 1682 1683 // Otherwise, everything is great. Include the statement and tell the caller 1684 // that we fall through and include the next statement as well. 1685 ResultStmts.push_back(S); 1686 return CSFC_FallThrough; 1687 } 1688 1689 /// FindCaseStatementsForValue - Find the case statement being jumped to and 1690 /// then invoke CollectStatementsForCase to find the list of statements to emit 1691 /// for a switch on constant. See the comment above CollectStatementsForCase 1692 /// for more details. 1693 static bool FindCaseStatementsForValue(const SwitchStmt &S, 1694 const llvm::APSInt &ConstantCondValue, 1695 SmallVectorImpl<const Stmt*> &ResultStmts, 1696 ASTContext &C, 1697 const SwitchCase *&ResultCase) { 1698 // First step, find the switch case that is being branched to. We can do this 1699 // efficiently by scanning the SwitchCase list. 1700 const SwitchCase *Case = S.getSwitchCaseList(); 1701 const DefaultStmt *DefaultCase = nullptr; 1702 1703 for (; Case; Case = Case->getNextSwitchCase()) { 1704 // It's either a default or case. Just remember the default statement in 1705 // case we're not jumping to any numbered cases. 1706 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) { 1707 DefaultCase = DS; 1708 continue; 1709 } 1710 1711 // Check to see if this case is the one we're looking for. 1712 const CaseStmt *CS = cast<CaseStmt>(Case); 1713 // Don't handle case ranges yet. 1714 if (CS->getRHS()) return false; 1715 1716 // If we found our case, remember it as 'case'. 1717 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue) 1718 break; 1719 } 1720 1721 // If we didn't find a matching case, we use a default if it exists, or we 1722 // elide the whole switch body! 1723 if (!Case) { 1724 // It is safe to elide the body of the switch if it doesn't contain labels 1725 // etc. If it is safe, return successfully with an empty ResultStmts list. 1726 if (!DefaultCase) 1727 return !CodeGenFunction::ContainsLabel(&S); 1728 Case = DefaultCase; 1729 } 1730 1731 // Ok, we know which case is being jumped to, try to collect all the 1732 // statements that follow it. This can fail for a variety of reasons. Also, 1733 // check to see that the recursive walk actually found our case statement. 1734 // Insane cases like this can fail to find it in the recursive walk since we 1735 // don't handle every stmt kind: 1736 // switch (4) { 1737 // while (1) { 1738 // case 4: ... 1739 bool FoundCase = false; 1740 ResultCase = Case; 1741 return CollectStatementsForCase(S.getBody(), Case, FoundCase, 1742 ResultStmts) != CSFC_Failure && 1743 FoundCase; 1744 } 1745 1746 static Optional<SmallVector<uint64_t, 16>> 1747 getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) { 1748 // Are there enough branches to weight them? 1749 if (Likelihoods.size() <= 1) 1750 return None; 1751 1752 uint64_t NumUnlikely = 0; 1753 uint64_t NumNone = 0; 1754 uint64_t NumLikely = 0; 1755 for (const auto LH : Likelihoods) { 1756 switch (LH) { 1757 case Stmt::LH_Unlikely: 1758 ++NumUnlikely; 1759 break; 1760 case Stmt::LH_None: 1761 ++NumNone; 1762 break; 1763 case Stmt::LH_Likely: 1764 ++NumLikely; 1765 break; 1766 } 1767 } 1768 1769 // Is there a likelihood attribute used? 1770 if (NumUnlikely == 0 && NumLikely == 0) 1771 return None; 1772 1773 // When multiple cases share the same code they can be combined during 1774 // optimization. In that case the weights of the branch will be the sum of 1775 // the individual weights. Make sure the combined sum of all neutral cases 1776 // doesn't exceed the value of a single likely attribute. 1777 // The additions both avoid divisions by 0 and make sure the weights of None 1778 // don't exceed the weight of Likely. 1779 const uint64_t Likely = INT32_MAX / (NumLikely + 2); 1780 const uint64_t None = Likely / (NumNone + 1); 1781 const uint64_t Unlikely = 0; 1782 1783 SmallVector<uint64_t, 16> Result; 1784 Result.reserve(Likelihoods.size()); 1785 for (const auto LH : Likelihoods) { 1786 switch (LH) { 1787 case Stmt::LH_Unlikely: 1788 Result.push_back(Unlikely); 1789 break; 1790 case Stmt::LH_None: 1791 Result.push_back(None); 1792 break; 1793 case Stmt::LH_Likely: 1794 Result.push_back(Likely); 1795 break; 1796 } 1797 } 1798 1799 return Result; 1800 } 1801 1802 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { 1803 // Handle nested switch statements. 1804 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; 1805 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights; 1806 SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood; 1807 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; 1808 1809 // See if we can constant fold the condition of the switch and therefore only 1810 // emit the live case statement (if any) of the switch. 1811 llvm::APSInt ConstantCondValue; 1812 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) { 1813 SmallVector<const Stmt*, 4> CaseStmts; 1814 const SwitchCase *Case = nullptr; 1815 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts, 1816 getContext(), Case)) { 1817 if (Case) 1818 incrementProfileCounter(Case); 1819 RunCleanupsScope ExecutedScope(*this); 1820 1821 if (S.getInit()) 1822 EmitStmt(S.getInit()); 1823 1824 // Emit the condition variable if needed inside the entire cleanup scope 1825 // used by this special case for constant folded switches. 1826 if (S.getConditionVariable()) 1827 EmitDecl(*S.getConditionVariable()); 1828 1829 // At this point, we are no longer "within" a switch instance, so 1830 // we can temporarily enforce this to ensure that any embedded case 1831 // statements are not emitted. 1832 SwitchInsn = nullptr; 1833 1834 // Okay, we can dead code eliminate everything except this case. Emit the 1835 // specified series of statements and we're good. 1836 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i) 1837 EmitStmt(CaseStmts[i]); 1838 incrementProfileCounter(&S); 1839 1840 // Now we want to restore the saved switch instance so that nested 1841 // switches continue to function properly 1842 SwitchInsn = SavedSwitchInsn; 1843 1844 return; 1845 } 1846 } 1847 1848 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog"); 1849 1850 RunCleanupsScope ConditionScope(*this); 1851 1852 if (S.getInit()) 1853 EmitStmt(S.getInit()); 1854 1855 if (S.getConditionVariable()) 1856 EmitDecl(*S.getConditionVariable()); 1857 llvm::Value *CondV = EmitScalarExpr(S.getCond()); 1858 1859 // Create basic block to hold stuff that comes after switch 1860 // statement. We also need to create a default block now so that 1861 // explicit case ranges tests can have a place to jump to on 1862 // failure. 1863 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default"); 1864 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock); 1865 if (PGO.haveRegionCounts()) { 1866 // Walk the SwitchCase list to find how many there are. 1867 uint64_t DefaultCount = 0; 1868 unsigned NumCases = 0; 1869 for (const SwitchCase *Case = S.getSwitchCaseList(); 1870 Case; 1871 Case = Case->getNextSwitchCase()) { 1872 if (isa<DefaultStmt>(Case)) 1873 DefaultCount = getProfileCount(Case); 1874 NumCases += 1; 1875 } 1876 SwitchWeights = new SmallVector<uint64_t, 16>(); 1877 SwitchWeights->reserve(NumCases); 1878 // The default needs to be first. We store the edge count, so we already 1879 // know the right weight. 1880 SwitchWeights->push_back(DefaultCount); 1881 } else if (CGM.getCodeGenOpts().OptimizationLevel) { 1882 SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>(); 1883 // Initialize the default case. 1884 SwitchLikelihood->push_back(Stmt::LH_None); 1885 } 1886 1887 CaseRangeBlock = DefaultBlock; 1888 1889 // Clear the insertion point to indicate we are in unreachable code. 1890 Builder.ClearInsertionPoint(); 1891 1892 // All break statements jump to NextBlock. If BreakContinueStack is non-empty 1893 // then reuse last ContinueBlock. 1894 JumpDest OuterContinue; 1895 if (!BreakContinueStack.empty()) 1896 OuterContinue = BreakContinueStack.back().ContinueBlock; 1897 1898 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue)); 1899 1900 // Emit switch body. 1901 EmitStmt(S.getBody()); 1902 1903 BreakContinueStack.pop_back(); 1904 1905 // Update the default block in case explicit case range tests have 1906 // been chained on top. 1907 SwitchInsn->setDefaultDest(CaseRangeBlock); 1908 1909 // If a default was never emitted: 1910 if (!DefaultBlock->getParent()) { 1911 // If we have cleanups, emit the default block so that there's a 1912 // place to jump through the cleanups from. 1913 if (ConditionScope.requiresCleanups()) { 1914 EmitBlock(DefaultBlock); 1915 1916 // Otherwise, just forward the default block to the switch end. 1917 } else { 1918 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock()); 1919 delete DefaultBlock; 1920 } 1921 } 1922 1923 ConditionScope.ForceCleanup(); 1924 1925 // Emit continuation. 1926 EmitBlock(SwitchExit.getBlock(), true); 1927 incrementProfileCounter(&S); 1928 1929 // If the switch has a condition wrapped by __builtin_unpredictable, 1930 // create metadata that specifies that the switch is unpredictable. 1931 // Don't bother if not optimizing because that metadata would not be used. 1932 auto *Call = dyn_cast<CallExpr>(S.getCond()); 1933 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 1934 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 1935 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1936 llvm::MDBuilder MDHelper(getLLVMContext()); 1937 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable, 1938 MDHelper.createUnpredictable()); 1939 } 1940 } 1941 1942 if (SwitchWeights) { 1943 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() && 1944 "switch weights do not match switch cases"); 1945 // If there's only one jump destination there's no sense weighting it. 1946 if (SwitchWeights->size() > 1) 1947 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof, 1948 createProfileWeights(*SwitchWeights)); 1949 delete SwitchWeights; 1950 } else if (SwitchLikelihood) { 1951 assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() && 1952 "switch likelihoods do not match switch cases"); 1953 Optional<SmallVector<uint64_t, 16>> LHW = 1954 getLikelihoodWeights(*SwitchLikelihood); 1955 if (LHW) { 1956 llvm::MDBuilder MDHelper(CGM.getLLVMContext()); 1957 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof, 1958 createProfileWeights(*LHW)); 1959 } 1960 delete SwitchLikelihood; 1961 } 1962 SwitchInsn = SavedSwitchInsn; 1963 SwitchWeights = SavedSwitchWeights; 1964 SwitchLikelihood = SavedSwitchLikelihood; 1965 CaseRangeBlock = SavedCRBlock; 1966 } 1967 1968 static std::string 1969 SimplifyConstraint(const char *Constraint, const TargetInfo &Target, 1970 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) { 1971 std::string Result; 1972 1973 while (*Constraint) { 1974 switch (*Constraint) { 1975 default: 1976 Result += Target.convertConstraint(Constraint); 1977 break; 1978 // Ignore these 1979 case '*': 1980 case '?': 1981 case '!': 1982 case '=': // Will see this and the following in mult-alt constraints. 1983 case '+': 1984 break; 1985 case '#': // Ignore the rest of the constraint alternative. 1986 while (Constraint[1] && Constraint[1] != ',') 1987 Constraint++; 1988 break; 1989 case '&': 1990 case '%': 1991 Result += *Constraint; 1992 while (Constraint[1] && Constraint[1] == *Constraint) 1993 Constraint++; 1994 break; 1995 case ',': 1996 Result += "|"; 1997 break; 1998 case 'g': 1999 Result += "imr"; 2000 break; 2001 case '[': { 2002 assert(OutCons && 2003 "Must pass output names to constraints with a symbolic name"); 2004 unsigned Index; 2005 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index); 2006 assert(result && "Could not resolve symbolic name"); (void)result; 2007 Result += llvm::utostr(Index); 2008 break; 2009 } 2010 } 2011 2012 Constraint++; 2013 } 2014 2015 return Result; 2016 } 2017 2018 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared 2019 /// as using a particular register add that as a constraint that will be used 2020 /// in this asm stmt. 2021 static std::string 2022 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr, 2023 const TargetInfo &Target, CodeGenModule &CGM, 2024 const AsmStmt &Stmt, const bool EarlyClobber, 2025 std::string *GCCReg = nullptr) { 2026 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr); 2027 if (!AsmDeclRef) 2028 return Constraint; 2029 const ValueDecl &Value = *AsmDeclRef->getDecl(); 2030 const VarDecl *Variable = dyn_cast<VarDecl>(&Value); 2031 if (!Variable) 2032 return Constraint; 2033 if (Variable->getStorageClass() != SC_Register) 2034 return Constraint; 2035 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>(); 2036 if (!Attr) 2037 return Constraint; 2038 StringRef Register = Attr->getLabel(); 2039 assert(Target.isValidGCCRegisterName(Register)); 2040 // We're using validateOutputConstraint here because we only care if 2041 // this is a register constraint. 2042 TargetInfo::ConstraintInfo Info(Constraint, ""); 2043 if (Target.validateOutputConstraint(Info) && 2044 !Info.allowsRegister()) { 2045 CGM.ErrorUnsupported(&Stmt, "__asm__"); 2046 return Constraint; 2047 } 2048 // Canonicalize the register here before returning it. 2049 Register = Target.getNormalizedGCCRegisterName(Register); 2050 if (GCCReg != nullptr) 2051 *GCCReg = Register.str(); 2052 return (EarlyClobber ? "&{" : "{") + Register.str() + "}"; 2053 } 2054 2055 llvm::Value* 2056 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 2057 LValue InputValue, QualType InputType, 2058 std::string &ConstraintStr, 2059 SourceLocation Loc) { 2060 llvm::Value *Arg; 2061 if (Info.allowsRegister() || !Info.allowsMemory()) { 2062 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) { 2063 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal(); 2064 } else { 2065 llvm::Type *Ty = ConvertType(InputType); 2066 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty); 2067 if (Size <= 64 && llvm::isPowerOf2_64(Size)) { 2068 Ty = llvm::IntegerType::get(getLLVMContext(), Size); 2069 Ty = llvm::PointerType::getUnqual(Ty); 2070 2071 Arg = Builder.CreateLoad( 2072 Builder.CreateBitCast(InputValue.getAddress(*this), Ty)); 2073 } else { 2074 Arg = InputValue.getPointer(*this); 2075 ConstraintStr += '*'; 2076 } 2077 } 2078 } else { 2079 Arg = InputValue.getPointer(*this); 2080 ConstraintStr += '*'; 2081 } 2082 2083 return Arg; 2084 } 2085 2086 llvm::Value* CodeGenFunction::EmitAsmInput( 2087 const TargetInfo::ConstraintInfo &Info, 2088 const Expr *InputExpr, 2089 std::string &ConstraintStr) { 2090 // If this can't be a register or memory, i.e., has to be a constant 2091 // (immediate or symbolic), try to emit it as such. 2092 if (!Info.allowsRegister() && !Info.allowsMemory()) { 2093 if (Info.requiresImmediateConstant()) { 2094 Expr::EvalResult EVResult; 2095 InputExpr->EvaluateAsRValue(EVResult, getContext(), true); 2096 2097 llvm::APSInt IntResult; 2098 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(), 2099 getContext())) 2100 return llvm::ConstantInt::get(getLLVMContext(), IntResult); 2101 } 2102 2103 Expr::EvalResult Result; 2104 if (InputExpr->EvaluateAsInt(Result, getContext())) 2105 return llvm::ConstantInt::get(getLLVMContext(), Result.Val.getInt()); 2106 } 2107 2108 if (Info.allowsRegister() || !Info.allowsMemory()) 2109 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType())) 2110 return EmitScalarExpr(InputExpr); 2111 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass) 2112 return EmitScalarExpr(InputExpr); 2113 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext()); 2114 LValue Dest = EmitLValue(InputExpr); 2115 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr, 2116 InputExpr->getExprLoc()); 2117 } 2118 2119 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline 2120 /// asm call instruction. The !srcloc MDNode contains a list of constant 2121 /// integers which are the source locations of the start of each line in the 2122 /// asm. 2123 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str, 2124 CodeGenFunction &CGF) { 2125 SmallVector<llvm::Metadata *, 8> Locs; 2126 // Add the location of the first line to the MDNode. 2127 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 2128 CGF.Int32Ty, Str->getBeginLoc().getRawEncoding()))); 2129 StringRef StrVal = Str->getString(); 2130 if (!StrVal.empty()) { 2131 const SourceManager &SM = CGF.CGM.getContext().getSourceManager(); 2132 const LangOptions &LangOpts = CGF.CGM.getLangOpts(); 2133 unsigned StartToken = 0; 2134 unsigned ByteOffset = 0; 2135 2136 // Add the location of the start of each subsequent line of the asm to the 2137 // MDNode. 2138 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) { 2139 if (StrVal[i] != '\n') continue; 2140 SourceLocation LineLoc = Str->getLocationOfByte( 2141 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset); 2142 Locs.push_back(llvm::ConstantAsMetadata::get( 2143 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding()))); 2144 } 2145 } 2146 2147 return llvm::MDNode::get(CGF.getLLVMContext(), Locs); 2148 } 2149 2150 static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect, 2151 bool ReadOnly, bool ReadNone, bool NoMerge, 2152 const AsmStmt &S, 2153 const std::vector<llvm::Type *> &ResultRegTypes, 2154 CodeGenFunction &CGF, 2155 std::vector<llvm::Value *> &RegResults) { 2156 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2157 llvm::Attribute::NoUnwind); 2158 if (NoMerge) 2159 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2160 llvm::Attribute::NoMerge); 2161 // Attach readnone and readonly attributes. 2162 if (!HasSideEffect) { 2163 if (ReadNone) 2164 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2165 llvm::Attribute::ReadNone); 2166 else if (ReadOnly) 2167 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2168 llvm::Attribute::ReadOnly); 2169 } 2170 2171 // Slap the source location of the inline asm into a !srcloc metadata on the 2172 // call. 2173 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) 2174 Result.setMetadata("srcloc", 2175 getAsmSrcLocInfo(gccAsmStmt->getAsmString(), CGF)); 2176 else { 2177 // At least put the line number on MS inline asm blobs. 2178 llvm::Constant *Loc = llvm::ConstantInt::get(CGF.Int32Ty, 2179 S.getAsmLoc().getRawEncoding()); 2180 Result.setMetadata("srcloc", 2181 llvm::MDNode::get(CGF.getLLVMContext(), 2182 llvm::ConstantAsMetadata::get(Loc))); 2183 } 2184 2185 if (CGF.getLangOpts().assumeFunctionsAreConvergent()) 2186 // Conservatively, mark all inline asm blocks in CUDA or OpenCL as 2187 // convergent (meaning, they may call an intrinsically convergent op, such 2188 // as bar.sync, and so can't have certain optimizations applied around 2189 // them). 2190 Result.addAttribute(llvm::AttributeList::FunctionIndex, 2191 llvm::Attribute::Convergent); 2192 // Extract all of the register value results from the asm. 2193 if (ResultRegTypes.size() == 1) { 2194 RegResults.push_back(&Result); 2195 } else { 2196 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { 2197 llvm::Value *Tmp = CGF.Builder.CreateExtractValue(&Result, i, "asmresult"); 2198 RegResults.push_back(Tmp); 2199 } 2200 } 2201 } 2202 2203 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { 2204 // Assemble the final asm string. 2205 std::string AsmString = S.generateAsmString(getContext()); 2206 2207 // Get all the output and input constraints together. 2208 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 2209 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 2210 2211 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 2212 StringRef Name; 2213 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S)) 2214 Name = GAS->getOutputName(i); 2215 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name); 2216 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid; 2217 assert(IsValid && "Failed to parse output constraint"); 2218 OutputConstraintInfos.push_back(Info); 2219 } 2220 2221 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 2222 StringRef Name; 2223 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S)) 2224 Name = GAS->getInputName(i); 2225 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name); 2226 bool IsValid = 2227 getTarget().validateInputConstraint(OutputConstraintInfos, Info); 2228 assert(IsValid && "Failed to parse input constraint"); (void)IsValid; 2229 InputConstraintInfos.push_back(Info); 2230 } 2231 2232 std::string Constraints; 2233 2234 std::vector<LValue> ResultRegDests; 2235 std::vector<QualType> ResultRegQualTys; 2236 std::vector<llvm::Type *> ResultRegTypes; 2237 std::vector<llvm::Type *> ResultTruncRegTypes; 2238 std::vector<llvm::Type *> ArgTypes; 2239 std::vector<llvm::Value*> Args; 2240 llvm::BitVector ResultTypeRequiresCast; 2241 2242 // Keep track of inout constraints. 2243 std::string InOutConstraints; 2244 std::vector<llvm::Value*> InOutArgs; 2245 std::vector<llvm::Type*> InOutArgTypes; 2246 2247 // Keep track of out constraints for tied input operand. 2248 std::vector<std::string> OutputConstraints; 2249 2250 // Keep track of defined physregs. 2251 llvm::SmallSet<std::string, 8> PhysRegOutputs; 2252 2253 // An inline asm can be marked readonly if it meets the following conditions: 2254 // - it doesn't have any sideeffects 2255 // - it doesn't clobber memory 2256 // - it doesn't return a value by-reference 2257 // It can be marked readnone if it doesn't have any input memory constraints 2258 // in addition to meeting the conditions listed above. 2259 bool ReadOnly = true, ReadNone = true; 2260 2261 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { 2262 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; 2263 2264 // Simplify the output constraint. 2265 std::string OutputConstraint(S.getOutputConstraint(i)); 2266 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, 2267 getTarget(), &OutputConstraintInfos); 2268 2269 const Expr *OutExpr = S.getOutputExpr(i); 2270 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext()); 2271 2272 std::string GCCReg; 2273 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, 2274 getTarget(), CGM, S, 2275 Info.earlyClobber(), 2276 &GCCReg); 2277 // Give an error on multiple outputs to same physreg. 2278 if (!GCCReg.empty() && !PhysRegOutputs.insert(GCCReg).second) 2279 CGM.Error(S.getAsmLoc(), "multiple outputs to hard register: " + GCCReg); 2280 2281 OutputConstraints.push_back(OutputConstraint); 2282 LValue Dest = EmitLValue(OutExpr); 2283 if (!Constraints.empty()) 2284 Constraints += ','; 2285 2286 // If this is a register output, then make the inline asm return it 2287 // by-value. If this is a memory result, return the value by-reference. 2288 bool isScalarizableAggregate = 2289 hasAggregateEvaluationKind(OutExpr->getType()); 2290 if (!Info.allowsMemory() && (hasScalarEvaluationKind(OutExpr->getType()) || 2291 isScalarizableAggregate)) { 2292 Constraints += "=" + OutputConstraint; 2293 ResultRegQualTys.push_back(OutExpr->getType()); 2294 ResultRegDests.push_back(Dest); 2295 ResultTruncRegTypes.push_back(ConvertTypeForMem(OutExpr->getType())); 2296 if (Info.allowsRegister() && isScalarizableAggregate) { 2297 ResultTypeRequiresCast.push_back(true); 2298 unsigned Size = getContext().getTypeSize(OutExpr->getType()); 2299 llvm::Type *ConvTy = llvm::IntegerType::get(getLLVMContext(), Size); 2300 ResultRegTypes.push_back(ConvTy); 2301 } else { 2302 ResultTypeRequiresCast.push_back(false); 2303 ResultRegTypes.push_back(ResultTruncRegTypes.back()); 2304 } 2305 // If this output is tied to an input, and if the input is larger, then 2306 // we need to set the actual result type of the inline asm node to be the 2307 // same as the input type. 2308 if (Info.hasMatchingInput()) { 2309 unsigned InputNo; 2310 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { 2311 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; 2312 if (Input.hasTiedOperand() && Input.getTiedOperand() == i) 2313 break; 2314 } 2315 assert(InputNo != S.getNumInputs() && "Didn't find matching input!"); 2316 2317 QualType InputTy = S.getInputExpr(InputNo)->getType(); 2318 QualType OutputType = OutExpr->getType(); 2319 2320 uint64_t InputSize = getContext().getTypeSize(InputTy); 2321 if (getContext().getTypeSize(OutputType) < InputSize) { 2322 // Form the asm to return the value as a larger integer or fp type. 2323 ResultRegTypes.back() = ConvertType(InputTy); 2324 } 2325 } 2326 if (llvm::Type* AdjTy = 2327 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 2328 ResultRegTypes.back())) 2329 ResultRegTypes.back() = AdjTy; 2330 else { 2331 CGM.getDiags().Report(S.getAsmLoc(), 2332 diag::err_asm_invalid_type_in_input) 2333 << OutExpr->getType() << OutputConstraint; 2334 } 2335 2336 // Update largest vector width for any vector types. 2337 if (auto *VT = dyn_cast<llvm::VectorType>(ResultRegTypes.back())) 2338 LargestVectorWidth = 2339 std::max((uint64_t)LargestVectorWidth, 2340 VT->getPrimitiveSizeInBits().getKnownMinSize()); 2341 } else { 2342 llvm::Type *DestAddrTy = Dest.getAddress(*this).getType(); 2343 llvm::Value *DestPtr = Dest.getPointer(*this); 2344 // Matrix types in memory are represented by arrays, but accessed through 2345 // vector pointers, with the alignment specified on the access operation. 2346 // For inline assembly, update pointer arguments to use vector pointers. 2347 // Otherwise there will be a mis-match if the matrix is also an 2348 // input-argument which is represented as vector. 2349 if (isa<MatrixType>(OutExpr->getType().getCanonicalType())) { 2350 DestAddrTy = llvm::PointerType::get( 2351 ConvertType(OutExpr->getType()), 2352 cast<llvm::PointerType>(DestAddrTy)->getAddressSpace()); 2353 DestPtr = Builder.CreateBitCast(DestPtr, DestAddrTy); 2354 } 2355 ArgTypes.push_back(DestAddrTy); 2356 Args.push_back(DestPtr); 2357 Constraints += "=*"; 2358 Constraints += OutputConstraint; 2359 ReadOnly = ReadNone = false; 2360 } 2361 2362 if (Info.isReadWrite()) { 2363 InOutConstraints += ','; 2364 2365 const Expr *InputExpr = S.getOutputExpr(i); 2366 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(), 2367 InOutConstraints, 2368 InputExpr->getExprLoc()); 2369 2370 if (llvm::Type* AdjTy = 2371 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint, 2372 Arg->getType())) 2373 Arg = Builder.CreateBitCast(Arg, AdjTy); 2374 2375 // Update largest vector width for any vector types. 2376 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType())) 2377 LargestVectorWidth = 2378 std::max((uint64_t)LargestVectorWidth, 2379 VT->getPrimitiveSizeInBits().getKnownMinSize()); 2380 // Only tie earlyclobber physregs. 2381 if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber())) 2382 InOutConstraints += llvm::utostr(i); 2383 else 2384 InOutConstraints += OutputConstraint; 2385 2386 InOutArgTypes.push_back(Arg->getType()); 2387 InOutArgs.push_back(Arg); 2388 } 2389 } 2390 2391 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX) 2392 // to the return value slot. Only do this when returning in registers. 2393 if (isa<MSAsmStmt>(&S)) { 2394 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo(); 2395 if (RetAI.isDirect() || RetAI.isExtend()) { 2396 // Make a fake lvalue for the return value slot. 2397 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy); 2398 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs( 2399 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes, 2400 ResultRegDests, AsmString, S.getNumOutputs()); 2401 SawAsmBlock = true; 2402 } 2403 } 2404 2405 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { 2406 const Expr *InputExpr = S.getInputExpr(i); 2407 2408 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 2409 2410 if (Info.allowsMemory()) 2411 ReadNone = false; 2412 2413 if (!Constraints.empty()) 2414 Constraints += ','; 2415 2416 // Simplify the input constraint. 2417 std::string InputConstraint(S.getInputConstraint(i)); 2418 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(), 2419 &OutputConstraintInfos); 2420 2421 InputConstraint = AddVariableConstraints( 2422 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()), 2423 getTarget(), CGM, S, false /* No EarlyClobber */); 2424 2425 std::string ReplaceConstraint (InputConstraint); 2426 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints); 2427 2428 // If this input argument is tied to a larger output result, extend the 2429 // input to be the same size as the output. The LLVM backend wants to see 2430 // the input and output of a matching constraint be the same size. Note 2431 // that GCC does not define what the top bits are here. We use zext because 2432 // that is usually cheaper, but LLVM IR should really get an anyext someday. 2433 if (Info.hasTiedOperand()) { 2434 unsigned Output = Info.getTiedOperand(); 2435 QualType OutputType = S.getOutputExpr(Output)->getType(); 2436 QualType InputTy = InputExpr->getType(); 2437 2438 if (getContext().getTypeSize(OutputType) > 2439 getContext().getTypeSize(InputTy)) { 2440 // Use ptrtoint as appropriate so that we can do our extension. 2441 if (isa<llvm::PointerType>(Arg->getType())) 2442 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy); 2443 llvm::Type *OutputTy = ConvertType(OutputType); 2444 if (isa<llvm::IntegerType>(OutputTy)) 2445 Arg = Builder.CreateZExt(Arg, OutputTy); 2446 else if (isa<llvm::PointerType>(OutputTy)) 2447 Arg = Builder.CreateZExt(Arg, IntPtrTy); 2448 else { 2449 assert(OutputTy->isFloatingPointTy() && "Unexpected output type"); 2450 Arg = Builder.CreateFPExt(Arg, OutputTy); 2451 } 2452 } 2453 // Deal with the tied operands' constraint code in adjustInlineAsmType. 2454 ReplaceConstraint = OutputConstraints[Output]; 2455 } 2456 if (llvm::Type* AdjTy = 2457 getTargetHooks().adjustInlineAsmType(*this, ReplaceConstraint, 2458 Arg->getType())) 2459 Arg = Builder.CreateBitCast(Arg, AdjTy); 2460 else 2461 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input) 2462 << InputExpr->getType() << InputConstraint; 2463 2464 // Update largest vector width for any vector types. 2465 if (auto *VT = dyn_cast<llvm::VectorType>(Arg->getType())) 2466 LargestVectorWidth = 2467 std::max((uint64_t)LargestVectorWidth, 2468 VT->getPrimitiveSizeInBits().getKnownMinSize()); 2469 2470 ArgTypes.push_back(Arg->getType()); 2471 Args.push_back(Arg); 2472 Constraints += InputConstraint; 2473 } 2474 2475 // Labels 2476 SmallVector<llvm::BasicBlock *, 16> Transfer; 2477 llvm::BasicBlock *Fallthrough = nullptr; 2478 bool IsGCCAsmGoto = false; 2479 if (const auto *GS = dyn_cast<GCCAsmStmt>(&S)) { 2480 IsGCCAsmGoto = GS->isAsmGoto(); 2481 if (IsGCCAsmGoto) { 2482 for (const auto *E : GS->labels()) { 2483 JumpDest Dest = getJumpDestForLabel(E->getLabel()); 2484 Transfer.push_back(Dest.getBlock()); 2485 llvm::BlockAddress *BA = 2486 llvm::BlockAddress::get(CurFn, Dest.getBlock()); 2487 Args.push_back(BA); 2488 ArgTypes.push_back(BA->getType()); 2489 if (!Constraints.empty()) 2490 Constraints += ','; 2491 Constraints += 'X'; 2492 } 2493 Fallthrough = createBasicBlock("asm.fallthrough"); 2494 } 2495 } 2496 2497 // Append the "input" part of inout constraints last. 2498 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { 2499 ArgTypes.push_back(InOutArgTypes[i]); 2500 Args.push_back(InOutArgs[i]); 2501 } 2502 Constraints += InOutConstraints; 2503 2504 // Clobbers 2505 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { 2506 StringRef Clobber = S.getClobber(i); 2507 2508 if (Clobber == "memory") 2509 ReadOnly = ReadNone = false; 2510 else if (Clobber != "cc") { 2511 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber); 2512 if (CGM.getCodeGenOpts().StackClashProtector && 2513 getTarget().isSPRegName(Clobber)) { 2514 CGM.getDiags().Report(S.getAsmLoc(), 2515 diag::warn_stack_clash_protection_inline_asm); 2516 } 2517 } 2518 2519 if (isa<MSAsmStmt>(&S)) { 2520 if (Clobber == "eax" || Clobber == "edx") { 2521 if (Constraints.find("=&A") != std::string::npos) 2522 continue; 2523 std::string::size_type position1 = 2524 Constraints.find("={" + Clobber.str() + "}"); 2525 if (position1 != std::string::npos) { 2526 Constraints.insert(position1 + 1, "&"); 2527 continue; 2528 } 2529 std::string::size_type position2 = Constraints.find("=A"); 2530 if (position2 != std::string::npos) { 2531 Constraints.insert(position2 + 1, "&"); 2532 continue; 2533 } 2534 } 2535 } 2536 if (!Constraints.empty()) 2537 Constraints += ','; 2538 2539 Constraints += "~{"; 2540 Constraints += Clobber; 2541 Constraints += '}'; 2542 } 2543 2544 // Add machine specific clobbers 2545 std::string MachineClobbers = getTarget().getClobbers(); 2546 if (!MachineClobbers.empty()) { 2547 if (!Constraints.empty()) 2548 Constraints += ','; 2549 Constraints += MachineClobbers; 2550 } 2551 2552 llvm::Type *ResultType; 2553 if (ResultRegTypes.empty()) 2554 ResultType = VoidTy; 2555 else if (ResultRegTypes.size() == 1) 2556 ResultType = ResultRegTypes[0]; 2557 else 2558 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes); 2559 2560 llvm::FunctionType *FTy = 2561 llvm::FunctionType::get(ResultType, ArgTypes, false); 2562 2563 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0; 2564 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ? 2565 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT; 2566 llvm::InlineAsm *IA = 2567 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect, 2568 /* IsAlignStack */ false, AsmDialect); 2569 std::vector<llvm::Value*> RegResults; 2570 if (IsGCCAsmGoto) { 2571 llvm::CallBrInst *Result = 2572 Builder.CreateCallBr(IA, Fallthrough, Transfer, Args); 2573 EmitBlock(Fallthrough); 2574 UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly, 2575 ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes, 2576 *this, RegResults); 2577 } else { 2578 llvm::CallInst *Result = 2579 Builder.CreateCall(IA, Args, getBundlesForFunclet(IA)); 2580 UpdateAsmCallInst(cast<llvm::CallBase>(*Result), HasSideEffect, ReadOnly, 2581 ReadNone, InNoMergeAttributedStmt, S, ResultRegTypes, 2582 *this, RegResults); 2583 } 2584 2585 assert(RegResults.size() == ResultRegTypes.size()); 2586 assert(RegResults.size() == ResultTruncRegTypes.size()); 2587 assert(RegResults.size() == ResultRegDests.size()); 2588 // ResultRegDests can be also populated by addReturnRegisterOutputs() above, 2589 // in which case its size may grow. 2590 assert(ResultTypeRequiresCast.size() <= ResultRegDests.size()); 2591 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { 2592 llvm::Value *Tmp = RegResults[i]; 2593 2594 // If the result type of the LLVM IR asm doesn't match the result type of 2595 // the expression, do the conversion. 2596 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) { 2597 llvm::Type *TruncTy = ResultTruncRegTypes[i]; 2598 2599 // Truncate the integer result to the right size, note that TruncTy can be 2600 // a pointer. 2601 if (TruncTy->isFloatingPointTy()) 2602 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy); 2603 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { 2604 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy); 2605 Tmp = Builder.CreateTrunc(Tmp, 2606 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize)); 2607 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy); 2608 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { 2609 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType()); 2610 Tmp = Builder.CreatePtrToInt(Tmp, 2611 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize)); 2612 Tmp = Builder.CreateTrunc(Tmp, TruncTy); 2613 } else if (TruncTy->isIntegerTy()) { 2614 Tmp = Builder.CreateZExtOrTrunc(Tmp, TruncTy); 2615 } else if (TruncTy->isVectorTy()) { 2616 Tmp = Builder.CreateBitCast(Tmp, TruncTy); 2617 } 2618 } 2619 2620 LValue Dest = ResultRegDests[i]; 2621 // ResultTypeRequiresCast elements correspond to the first 2622 // ResultTypeRequiresCast.size() elements of RegResults. 2623 if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) { 2624 unsigned Size = getContext().getTypeSize(ResultRegQualTys[i]); 2625 Address A = Builder.CreateBitCast(Dest.getAddress(*this), 2626 ResultRegTypes[i]->getPointerTo()); 2627 QualType Ty = getContext().getIntTypeForBitwidth(Size, /*Signed*/ false); 2628 if (Ty.isNull()) { 2629 const Expr *OutExpr = S.getOutputExpr(i); 2630 CGM.Error( 2631 OutExpr->getExprLoc(), 2632 "impossible constraint in asm: can't store value into a register"); 2633 return; 2634 } 2635 Dest = MakeAddrLValue(A, Ty); 2636 } 2637 EmitStoreThroughLValue(RValue::get(Tmp), Dest); 2638 } 2639 } 2640 2641 LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) { 2642 const RecordDecl *RD = S.getCapturedRecordDecl(); 2643 QualType RecordTy = getContext().getRecordType(RD); 2644 2645 // Initialize the captured struct. 2646 LValue SlotLV = 2647 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy); 2648 2649 RecordDecl::field_iterator CurField = RD->field_begin(); 2650 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 2651 E = S.capture_init_end(); 2652 I != E; ++I, ++CurField) { 2653 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 2654 if (CurField->hasCapturedVLAType()) { 2655 EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV); 2656 } else { 2657 EmitInitializerForField(*CurField, LV, *I); 2658 } 2659 } 2660 2661 return SlotLV; 2662 } 2663 2664 /// Generate an outlined function for the body of a CapturedStmt, store any 2665 /// captured variables into the captured struct, and call the outlined function. 2666 llvm::Function * 2667 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) { 2668 LValue CapStruct = InitCapturedStruct(S); 2669 2670 // Emit the CapturedDecl 2671 CodeGenFunction CGF(CGM, true); 2672 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K)); 2673 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S); 2674 delete CGF.CapturedStmtInfo; 2675 2676 // Emit call to the helper function. 2677 EmitCallOrInvoke(F, CapStruct.getPointer(*this)); 2678 2679 return F; 2680 } 2681 2682 Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) { 2683 LValue CapStruct = InitCapturedStruct(S); 2684 return CapStruct.getAddress(*this); 2685 } 2686 2687 /// Creates the outlined function for a CapturedStmt. 2688 llvm::Function * 2689 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) { 2690 assert(CapturedStmtInfo && 2691 "CapturedStmtInfo should be set when generating the captured function"); 2692 const CapturedDecl *CD = S.getCapturedDecl(); 2693 const RecordDecl *RD = S.getCapturedRecordDecl(); 2694 SourceLocation Loc = S.getBeginLoc(); 2695 assert(CD->hasBody() && "missing CapturedDecl body"); 2696 2697 // Build the argument list. 2698 ASTContext &Ctx = CGM.getContext(); 2699 FunctionArgList Args; 2700 Args.append(CD->param_begin(), CD->param_end()); 2701 2702 // Create the function declaration. 2703 const CGFunctionInfo &FuncInfo = 2704 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args); 2705 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 2706 2707 llvm::Function *F = 2708 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 2709 CapturedStmtInfo->getHelperName(), &CGM.getModule()); 2710 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 2711 if (CD->isNothrow()) 2712 F->addFnAttr(llvm::Attribute::NoUnwind); 2713 2714 // Generate the function. 2715 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args, CD->getLocation(), 2716 CD->getBody()->getBeginLoc()); 2717 // Set the context parameter in CapturedStmtInfo. 2718 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam()); 2719 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr)); 2720 2721 // Initialize variable-length arrays. 2722 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(), 2723 Ctx.getTagDeclType(RD)); 2724 for (auto *FD : RD->fields()) { 2725 if (FD->hasCapturedVLAType()) { 2726 auto *ExprArg = 2727 EmitLoadOfLValue(EmitLValueForField(Base, FD), S.getBeginLoc()) 2728 .getScalarVal(); 2729 auto VAT = FD->getCapturedVLAType(); 2730 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 2731 } 2732 } 2733 2734 // If 'this' is captured, load it into CXXThisValue. 2735 if (CapturedStmtInfo->isCXXThisExprCaptured()) { 2736 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl(); 2737 LValue ThisLValue = EmitLValueForField(Base, FD); 2738 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal(); 2739 } 2740 2741 PGO.assignRegionCounters(GlobalDecl(CD), F); 2742 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 2743 FinishFunction(CD->getBodyRBrace()); 2744 2745 return F; 2746 } 2747