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