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