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