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