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