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