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