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