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