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