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