1 //===- CoroSplit.cpp - Converts a coroutine into a state machine ----------===// 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 // This pass builds the coroutine frame and outlines resume and destroy parts 9 // of the coroutine into separate functions. 10 // 11 // We present a coroutine to an LLVM as an ordinary function with suspension 12 // points marked up with intrinsics. We let the optimizer party on the coroutine 13 // as a single function for as long as possible. Shortly before the coroutine is 14 // eligible to be inlined into its callers, we split up the coroutine into parts 15 // corresponding to an initial, resume and destroy invocations of the coroutine, 16 // add them to the current SCC and restart the IPO pipeline to optimize the 17 // coroutine subfunctions we extracted before proceeding to the caller of the 18 // coroutine. 19 //===----------------------------------------------------------------------===// 20 21 #include "llvm/Transforms/Coroutines/CoroSplit.h" 22 #include "CoroInstr.h" 23 #include "CoroInternal.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/CallGraph.h" 30 #include "llvm/Analysis/CallGraphSCCPass.h" 31 #include "llvm/IR/Argument.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/CFG.h" 35 #include "llvm/IR/CallingConv.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DataLayout.h" 38 #include "llvm/IR/DerivedTypes.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GlobalValue.h" 41 #include "llvm/IR/GlobalVariable.h" 42 #include "llvm/IR/IRBuilder.h" 43 #include "llvm/IR/InstIterator.h" 44 #include "llvm/IR/InstrTypes.h" 45 #include "llvm/IR/Instruction.h" 46 #include "llvm/IR/Instructions.h" 47 #include "llvm/IR/IntrinsicInst.h" 48 #include "llvm/IR/LLVMContext.h" 49 #include "llvm/IR/LegacyPassManager.h" 50 #include "llvm/IR/Module.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/IR/Verifier.h" 54 #include "llvm/InitializePasses.h" 55 #include "llvm/Pass.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/PrettyStackTrace.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Transforms/Scalar.h" 61 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 62 #include "llvm/Transforms/Utils/CallGraphUpdater.h" 63 #include "llvm/Transforms/Utils/Cloning.h" 64 #include "llvm/Transforms/Utils/Local.h" 65 #include "llvm/Transforms/Utils/ValueMapper.h" 66 #include <cassert> 67 #include <cstddef> 68 #include <cstdint> 69 #include <initializer_list> 70 #include <iterator> 71 72 using namespace llvm; 73 74 #define DEBUG_TYPE "coro-split" 75 76 namespace { 77 78 /// A little helper class for building 79 class CoroCloner { 80 public: 81 enum class Kind { 82 /// The shared resume function for a switch lowering. 83 SwitchResume, 84 85 /// The shared unwind function for a switch lowering. 86 SwitchUnwind, 87 88 /// The shared cleanup function for a switch lowering. 89 SwitchCleanup, 90 91 /// An individual continuation function. 92 Continuation, 93 94 /// An async resume function. 95 Async, 96 }; 97 98 private: 99 Function &OrigF; 100 Function *NewF; 101 const Twine &Suffix; 102 coro::Shape &Shape; 103 Kind FKind; 104 ValueToValueMapTy VMap; 105 IRBuilder<> Builder; 106 Value *NewFramePtr = nullptr; 107 Value *SwiftErrorSlot = nullptr; 108 109 /// The active suspend instruction; meaningful only for continuation and async 110 /// ABIs. 111 AnyCoroSuspendInst *ActiveSuspend = nullptr; 112 113 public: 114 /// Create a cloner for a switch lowering. 115 CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, 116 Kind FKind) 117 : OrigF(OrigF), NewF(nullptr), Suffix(Suffix), Shape(Shape), 118 FKind(FKind), Builder(OrigF.getContext()) { 119 assert(Shape.ABI == coro::ABI::Switch); 120 } 121 122 /// Create a cloner for a continuation lowering. 123 CoroCloner(Function &OrigF, const Twine &Suffix, coro::Shape &Shape, 124 Function *NewF, AnyCoroSuspendInst *ActiveSuspend) 125 : OrigF(OrigF), NewF(NewF), Suffix(Suffix), Shape(Shape), 126 FKind(Shape.ABI == coro::ABI::Async ? Kind::Async : Kind::Continuation), 127 Builder(OrigF.getContext()), ActiveSuspend(ActiveSuspend) { 128 assert(Shape.ABI == coro::ABI::Retcon || 129 Shape.ABI == coro::ABI::RetconOnce || Shape.ABI == coro::ABI::Async); 130 assert(NewF && "need existing function for continuation"); 131 assert(ActiveSuspend && "need active suspend point for continuation"); 132 } 133 134 Function *getFunction() const { 135 assert(NewF != nullptr && "declaration not yet set"); 136 return NewF; 137 } 138 139 void create(); 140 141 private: 142 bool isSwitchDestroyFunction() { 143 switch (FKind) { 144 case Kind::Async: 145 case Kind::Continuation: 146 case Kind::SwitchResume: 147 return false; 148 case Kind::SwitchUnwind: 149 case Kind::SwitchCleanup: 150 return true; 151 } 152 llvm_unreachable("Unknown CoroCloner::Kind enum"); 153 } 154 155 void createDeclaration(); 156 void replaceEntryBlock(); 157 Value *deriveNewFramePointer(); 158 void replaceRetconOrAsyncSuspendUses(); 159 void replaceCoroSuspends(); 160 void replaceCoroEnds(); 161 void replaceSwiftErrorOps(); 162 void handleFinalSuspend(); 163 void maybeFreeContinuationStorage(); 164 }; 165 166 } // end anonymous namespace 167 168 static void maybeFreeRetconStorage(IRBuilder<> &Builder, 169 const coro::Shape &Shape, Value *FramePtr, 170 CallGraph *CG) { 171 assert(Shape.ABI == coro::ABI::Retcon || 172 Shape.ABI == coro::ABI::RetconOnce); 173 if (Shape.RetconLowering.IsFrameInlineInStorage) 174 return; 175 176 Shape.emitDealloc(Builder, FramePtr, CG); 177 } 178 179 /// Replace a non-unwind call to llvm.coro.end. 180 static void replaceFallthroughCoroEnd(CoroEndInst *End, 181 const coro::Shape &Shape, Value *FramePtr, 182 bool InResume, CallGraph *CG) { 183 // Start inserting right before the coro.end. 184 IRBuilder<> Builder(End); 185 186 // Create the return instruction. 187 switch (Shape.ABI) { 188 // The cloned functions in switch-lowering always return void. 189 case coro::ABI::Switch: 190 // coro.end doesn't immediately end the coroutine in the main function 191 // in this lowering, because we need to deallocate the coroutine. 192 if (!InResume) 193 return; 194 Builder.CreateRetVoid(); 195 break; 196 197 // In async lowering this returns. 198 case coro::ABI::Async: 199 Builder.CreateRetVoid(); 200 break; 201 202 // In unique continuation lowering, the continuations always return void. 203 // But we may have implicitly allocated storage. 204 case coro::ABI::RetconOnce: 205 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 206 Builder.CreateRetVoid(); 207 break; 208 209 // In non-unique continuation lowering, we signal completion by returning 210 // a null continuation. 211 case coro::ABI::Retcon: { 212 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 213 auto RetTy = Shape.getResumeFunctionType()->getReturnType(); 214 auto RetStructTy = dyn_cast<StructType>(RetTy); 215 PointerType *ContinuationTy = 216 cast<PointerType>(RetStructTy ? RetStructTy->getElementType(0) : RetTy); 217 218 Value *ReturnValue = ConstantPointerNull::get(ContinuationTy); 219 if (RetStructTy) { 220 ReturnValue = Builder.CreateInsertValue(UndefValue::get(RetStructTy), 221 ReturnValue, 0); 222 } 223 Builder.CreateRet(ReturnValue); 224 break; 225 } 226 } 227 228 // Remove the rest of the block, by splitting it into an unreachable block. 229 auto *BB = End->getParent(); 230 BB->splitBasicBlock(End); 231 BB->getTerminator()->eraseFromParent(); 232 } 233 234 /// Replace an unwind call to llvm.coro.end. 235 static void replaceUnwindCoroEnd(CoroEndInst *End, const coro::Shape &Shape, 236 Value *FramePtr, bool InResume, CallGraph *CG){ 237 IRBuilder<> Builder(End); 238 239 switch (Shape.ABI) { 240 // In switch-lowering, this does nothing in the main function. 241 case coro::ABI::Switch: 242 if (!InResume) 243 return; 244 break; 245 // In async lowering this does nothing. 246 case coro::ABI::Async: 247 break; 248 // In continuation-lowering, this frees the continuation storage. 249 case coro::ABI::Retcon: 250 case coro::ABI::RetconOnce: 251 maybeFreeRetconStorage(Builder, Shape, FramePtr, CG); 252 break; 253 } 254 255 // If coro.end has an associated bundle, add cleanupret instruction. 256 if (auto Bundle = End->getOperandBundle(LLVMContext::OB_funclet)) { 257 auto *FromPad = cast<CleanupPadInst>(Bundle->Inputs[0]); 258 auto *CleanupRet = Builder.CreateCleanupRet(FromPad, nullptr); 259 End->getParent()->splitBasicBlock(End); 260 CleanupRet->getParent()->getTerminator()->eraseFromParent(); 261 } 262 } 263 264 static void replaceCoroEnd(CoroEndInst *End, const coro::Shape &Shape, 265 Value *FramePtr, bool InResume, CallGraph *CG) { 266 if (End->isUnwind()) 267 replaceUnwindCoroEnd(End, Shape, FramePtr, InResume, CG); 268 else 269 replaceFallthroughCoroEnd(End, Shape, FramePtr, InResume, CG); 270 271 auto &Context = End->getContext(); 272 End->replaceAllUsesWith(InResume ? ConstantInt::getTrue(Context) 273 : ConstantInt::getFalse(Context)); 274 End->eraseFromParent(); 275 } 276 277 // Create an entry block for a resume function with a switch that will jump to 278 // suspend points. 279 static void createResumeEntryBlock(Function &F, coro::Shape &Shape) { 280 assert(Shape.ABI == coro::ABI::Switch); 281 LLVMContext &C = F.getContext(); 282 283 // resume.entry: 284 // %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0, 285 // i32 2 286 // % index = load i32, i32* %index.addr 287 // switch i32 %index, label %unreachable [ 288 // i32 0, label %resume.0 289 // i32 1, label %resume.1 290 // ... 291 // ] 292 293 auto *NewEntry = BasicBlock::Create(C, "resume.entry", &F); 294 auto *UnreachBB = BasicBlock::Create(C, "unreachable", &F); 295 296 IRBuilder<> Builder(NewEntry); 297 auto *FramePtr = Shape.FramePtr; 298 auto *FrameTy = Shape.FrameTy; 299 auto *GepIndex = Builder.CreateStructGEP( 300 FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr"); 301 auto *Index = Builder.CreateLoad(Shape.getIndexType(), GepIndex, "index"); 302 auto *Switch = 303 Builder.CreateSwitch(Index, UnreachBB, Shape.CoroSuspends.size()); 304 Shape.SwitchLowering.ResumeSwitch = Switch; 305 306 size_t SuspendIndex = 0; 307 for (auto *AnyS : Shape.CoroSuspends) { 308 auto *S = cast<CoroSuspendInst>(AnyS); 309 ConstantInt *IndexVal = Shape.getIndex(SuspendIndex); 310 311 // Replace CoroSave with a store to Index: 312 // %index.addr = getelementptr %f.frame... (index field number) 313 // store i32 0, i32* %index.addr1 314 auto *Save = S->getCoroSave(); 315 Builder.SetInsertPoint(Save); 316 if (S->isFinal()) { 317 // Final suspend point is represented by storing zero in ResumeFnAddr. 318 auto *GepIndex = Builder.CreateStructGEP(FrameTy, FramePtr, 319 coro::Shape::SwitchFieldIndex::Resume, 320 "ResumeFn.addr"); 321 auto *NullPtr = ConstantPointerNull::get(cast<PointerType>( 322 cast<PointerType>(GepIndex->getType())->getElementType())); 323 Builder.CreateStore(NullPtr, GepIndex); 324 } else { 325 auto *GepIndex = Builder.CreateStructGEP( 326 FrameTy, FramePtr, Shape.getSwitchIndexField(), "index.addr"); 327 Builder.CreateStore(IndexVal, GepIndex); 328 } 329 Save->replaceAllUsesWith(ConstantTokenNone::get(C)); 330 Save->eraseFromParent(); 331 332 // Split block before and after coro.suspend and add a jump from an entry 333 // switch: 334 // 335 // whateverBB: 336 // whatever 337 // %0 = call i8 @llvm.coro.suspend(token none, i1 false) 338 // switch i8 %0, label %suspend[i8 0, label %resume 339 // i8 1, label %cleanup] 340 // becomes: 341 // 342 // whateverBB: 343 // whatever 344 // br label %resume.0.landing 345 // 346 // resume.0: ; <--- jump from the switch in the resume.entry 347 // %0 = tail call i8 @llvm.coro.suspend(token none, i1 false) 348 // br label %resume.0.landing 349 // 350 // resume.0.landing: 351 // %1 = phi i8[-1, %whateverBB], [%0, %resume.0] 352 // switch i8 % 1, label %suspend [i8 0, label %resume 353 // i8 1, label %cleanup] 354 355 auto *SuspendBB = S->getParent(); 356 auto *ResumeBB = 357 SuspendBB->splitBasicBlock(S, "resume." + Twine(SuspendIndex)); 358 auto *LandingBB = ResumeBB->splitBasicBlock( 359 S->getNextNode(), ResumeBB->getName() + Twine(".landing")); 360 Switch->addCase(IndexVal, ResumeBB); 361 362 cast<BranchInst>(SuspendBB->getTerminator())->setSuccessor(0, LandingBB); 363 auto *PN = PHINode::Create(Builder.getInt8Ty(), 2, "", &LandingBB->front()); 364 S->replaceAllUsesWith(PN); 365 PN->addIncoming(Builder.getInt8(-1), SuspendBB); 366 PN->addIncoming(S, ResumeBB); 367 368 ++SuspendIndex; 369 } 370 371 Builder.SetInsertPoint(UnreachBB); 372 Builder.CreateUnreachable(); 373 374 Shape.SwitchLowering.ResumeEntryBlock = NewEntry; 375 } 376 377 378 // Rewrite final suspend point handling. We do not use suspend index to 379 // represent the final suspend point. Instead we zero-out ResumeFnAddr in the 380 // coroutine frame, since it is undefined behavior to resume a coroutine 381 // suspended at the final suspend point. Thus, in the resume function, we can 382 // simply remove the last case (when coro::Shape is built, the final suspend 383 // point (if present) is always the last element of CoroSuspends array). 384 // In the destroy function, we add a code sequence to check if ResumeFnAddress 385 // is Null, and if so, jump to the appropriate label to handle cleanup from the 386 // final suspend point. 387 void CoroCloner::handleFinalSuspend() { 388 assert(Shape.ABI == coro::ABI::Switch && 389 Shape.SwitchLowering.HasFinalSuspend); 390 auto *Switch = cast<SwitchInst>(VMap[Shape.SwitchLowering.ResumeSwitch]); 391 auto FinalCaseIt = std::prev(Switch->case_end()); 392 BasicBlock *ResumeBB = FinalCaseIt->getCaseSuccessor(); 393 Switch->removeCase(FinalCaseIt); 394 if (isSwitchDestroyFunction()) { 395 BasicBlock *OldSwitchBB = Switch->getParent(); 396 auto *NewSwitchBB = OldSwitchBB->splitBasicBlock(Switch, "Switch"); 397 Builder.SetInsertPoint(OldSwitchBB->getTerminator()); 398 auto *GepIndex = Builder.CreateStructGEP(Shape.FrameTy, NewFramePtr, 399 coro::Shape::SwitchFieldIndex::Resume, 400 "ResumeFn.addr"); 401 auto *Load = Builder.CreateLoad(Shape.getSwitchResumePointerType(), 402 GepIndex); 403 auto *Cond = Builder.CreateIsNull(Load); 404 Builder.CreateCondBr(Cond, ResumeBB, NewSwitchBB); 405 OldSwitchBB->getTerminator()->eraseFromParent(); 406 } 407 } 408 409 static Function *createCloneDeclaration(Function &OrigF, coro::Shape &Shape, 410 const Twine &Suffix, 411 Module::iterator InsertBefore) { 412 Module *M = OrigF.getParent(); 413 auto *FnTy = Shape.getResumeFunctionType(); 414 415 Function *NewF = 416 Function::Create(FnTy, GlobalValue::LinkageTypes::InternalLinkage, 417 OrigF.getName() + Suffix); 418 NewF->addParamAttr(0, Attribute::NonNull); 419 420 // For the async lowering ABI we can't guarantee that the context argument is 421 // not access via a different pointer not based on the argument. 422 if (Shape.ABI != coro::ABI::Async) 423 NewF->addParamAttr(0, Attribute::NoAlias); 424 425 M->getFunctionList().insert(InsertBefore, NewF); 426 427 return NewF; 428 } 429 430 /// Replace uses of the active llvm.coro.suspend.retcon/async call with the 431 /// arguments to the continuation function. 432 /// 433 /// This assumes that the builder has a meaningful insertion point. 434 void CoroCloner::replaceRetconOrAsyncSuspendUses() { 435 assert(Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce || 436 Shape.ABI == coro::ABI::Async); 437 438 auto NewS = VMap[ActiveSuspend]; 439 if (NewS->use_empty()) return; 440 441 // Copy out all the continuation arguments after the buffer pointer into 442 // an easily-indexed data structure for convenience. 443 SmallVector<Value*, 8> Args; 444 // The async ABI includes all arguments -- including the first argument. 445 bool IsAsyncABI = Shape.ABI == coro::ABI::Async; 446 for (auto I = IsAsyncABI ? NewF->arg_begin() : std::next(NewF->arg_begin()), 447 E = NewF->arg_end(); 448 I != E; ++I) 449 Args.push_back(&*I); 450 451 // If the suspend returns a single scalar value, we can just do a simple 452 // replacement. 453 if (!isa<StructType>(NewS->getType())) { 454 assert(Args.size() == 1); 455 NewS->replaceAllUsesWith(Args.front()); 456 return; 457 } 458 459 // Try to peephole extracts of an aggregate return. 460 for (auto UI = NewS->use_begin(), UE = NewS->use_end(); UI != UE; ) { 461 auto EVI = dyn_cast<ExtractValueInst>((UI++)->getUser()); 462 if (!EVI || EVI->getNumIndices() != 1) 463 continue; 464 465 EVI->replaceAllUsesWith(Args[EVI->getIndices().front()]); 466 EVI->eraseFromParent(); 467 } 468 469 // If we have no remaining uses, we're done. 470 if (NewS->use_empty()) return; 471 472 // Otherwise, we need to create an aggregate. 473 Value *Agg = UndefValue::get(NewS->getType()); 474 for (size_t I = 0, E = Args.size(); I != E; ++I) 475 Agg = Builder.CreateInsertValue(Agg, Args[I], I); 476 477 NewS->replaceAllUsesWith(Agg); 478 } 479 480 void CoroCloner::replaceCoroSuspends() { 481 Value *SuspendResult; 482 483 switch (Shape.ABI) { 484 // In switch lowering, replace coro.suspend with the appropriate value 485 // for the type of function we're extracting. 486 // Replacing coro.suspend with (0) will result in control flow proceeding to 487 // a resume label associated with a suspend point, replacing it with (1) will 488 // result in control flow proceeding to a cleanup label associated with this 489 // suspend point. 490 case coro::ABI::Switch: 491 SuspendResult = Builder.getInt8(isSwitchDestroyFunction() ? 1 : 0); 492 break; 493 494 // In async lowering there are no uses of the result. 495 case coro::ABI::Async: 496 return; 497 498 // In returned-continuation lowering, the arguments from earlier 499 // continuations are theoretically arbitrary, and they should have been 500 // spilled. 501 case coro::ABI::RetconOnce: 502 case coro::ABI::Retcon: 503 return; 504 } 505 506 for (AnyCoroSuspendInst *CS : Shape.CoroSuspends) { 507 // The active suspend was handled earlier. 508 if (CS == ActiveSuspend) continue; 509 510 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[CS]); 511 MappedCS->replaceAllUsesWith(SuspendResult); 512 MappedCS->eraseFromParent(); 513 } 514 } 515 516 void CoroCloner::replaceCoroEnds() { 517 for (CoroEndInst *CE : Shape.CoroEnds) { 518 // We use a null call graph because there's no call graph node for 519 // the cloned function yet. We'll just be rebuilding that later. 520 auto NewCE = cast<CoroEndInst>(VMap[CE]); 521 replaceCoroEnd(NewCE, Shape, NewFramePtr, /*in resume*/ true, nullptr); 522 } 523 } 524 525 static void replaceSwiftErrorOps(Function &F, coro::Shape &Shape, 526 ValueToValueMapTy *VMap) { 527 Value *CachedSlot = nullptr; 528 auto getSwiftErrorSlot = [&](Type *ValueTy) -> Value * { 529 if (CachedSlot) { 530 assert(CachedSlot->getType()->getPointerElementType() == ValueTy && 531 "multiple swifterror slots in function with different types"); 532 return CachedSlot; 533 } 534 535 // Check if the function has a swifterror argument. 536 for (auto &Arg : F.args()) { 537 if (Arg.isSwiftError()) { 538 CachedSlot = &Arg; 539 assert(Arg.getType()->getPointerElementType() == ValueTy && 540 "swifterror argument does not have expected type"); 541 return &Arg; 542 } 543 } 544 545 // Create a swifterror alloca. 546 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg()); 547 auto Alloca = Builder.CreateAlloca(ValueTy); 548 Alloca->setSwiftError(true); 549 550 CachedSlot = Alloca; 551 return Alloca; 552 }; 553 554 for (CallInst *Op : Shape.SwiftErrorOps) { 555 auto MappedOp = VMap ? cast<CallInst>((*VMap)[Op]) : Op; 556 IRBuilder<> Builder(MappedOp); 557 558 // If there are no arguments, this is a 'get' operation. 559 Value *MappedResult; 560 if (Op->getNumArgOperands() == 0) { 561 auto ValueTy = Op->getType(); 562 auto Slot = getSwiftErrorSlot(ValueTy); 563 MappedResult = Builder.CreateLoad(ValueTy, Slot); 564 } else { 565 assert(Op->getNumArgOperands() == 1); 566 auto Value = MappedOp->getArgOperand(0); 567 auto ValueTy = Value->getType(); 568 auto Slot = getSwiftErrorSlot(ValueTy); 569 Builder.CreateStore(Value, Slot); 570 MappedResult = Slot; 571 } 572 573 MappedOp->replaceAllUsesWith(MappedResult); 574 MappedOp->eraseFromParent(); 575 } 576 577 // If we're updating the original function, we've invalidated SwiftErrorOps. 578 if (VMap == nullptr) { 579 Shape.SwiftErrorOps.clear(); 580 } 581 } 582 583 void CoroCloner::replaceSwiftErrorOps() { 584 ::replaceSwiftErrorOps(*NewF, Shape, &VMap); 585 } 586 587 void CoroCloner::replaceEntryBlock() { 588 // In the original function, the AllocaSpillBlock is a block immediately 589 // following the allocation of the frame object which defines GEPs for 590 // all the allocas that have been moved into the frame, and it ends by 591 // branching to the original beginning of the coroutine. Make this 592 // the entry block of the cloned function. 593 auto *Entry = cast<BasicBlock>(VMap[Shape.AllocaSpillBlock]); 594 auto *OldEntry = &NewF->getEntryBlock(); 595 Entry->setName("entry" + Suffix); 596 Entry->moveBefore(OldEntry); 597 Entry->getTerminator()->eraseFromParent(); 598 599 // Clear all predecessors of the new entry block. There should be 600 // exactly one predecessor, which we created when splitting out 601 // AllocaSpillBlock to begin with. 602 assert(Entry->hasOneUse()); 603 auto BranchToEntry = cast<BranchInst>(Entry->user_back()); 604 assert(BranchToEntry->isUnconditional()); 605 Builder.SetInsertPoint(BranchToEntry); 606 Builder.CreateUnreachable(); 607 BranchToEntry->eraseFromParent(); 608 609 // Move any allocas into Entry that weren't moved into the frame. 610 for (auto IT = OldEntry->begin(), End = OldEntry->end(); IT != End;) { 611 Instruction &I = *IT++; 612 if (!isa<AllocaInst>(&I) || I.use_empty()) 613 continue; 614 615 I.moveBefore(*Entry, Entry->getFirstInsertionPt()); 616 } 617 618 // Branch from the entry to the appropriate place. 619 Builder.SetInsertPoint(Entry); 620 switch (Shape.ABI) { 621 case coro::ABI::Switch: { 622 // In switch-lowering, we built a resume-entry block in the original 623 // function. Make the entry block branch to this. 624 auto *SwitchBB = 625 cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]); 626 Builder.CreateBr(SwitchBB); 627 break; 628 } 629 case coro::ABI::Async: 630 case coro::ABI::Retcon: 631 case coro::ABI::RetconOnce: { 632 // In continuation ABIs, we want to branch to immediately after the 633 // active suspend point. Earlier phases will have put the suspend in its 634 // own basic block, so just thread our jump directly to its successor. 635 assert((Shape.ABI == coro::ABI::Async && 636 isa<CoroSuspendAsyncInst>(ActiveSuspend)) || 637 ((Shape.ABI == coro::ABI::Retcon || 638 Shape.ABI == coro::ABI::RetconOnce) && 639 isa<CoroSuspendRetconInst>(ActiveSuspend))); 640 auto *MappedCS = cast<AnyCoroSuspendInst>(VMap[ActiveSuspend]); 641 auto Branch = cast<BranchInst>(MappedCS->getNextNode()); 642 assert(Branch->isUnconditional()); 643 Builder.CreateBr(Branch->getSuccessor(0)); 644 break; 645 } 646 } 647 } 648 649 /// Derive the value of the new frame pointer. 650 Value *CoroCloner::deriveNewFramePointer() { 651 // Builder should be inserting to the front of the new entry block. 652 653 switch (Shape.ABI) { 654 // In switch-lowering, the argument is the frame pointer. 655 case coro::ABI::Switch: 656 return &*NewF->arg_begin(); 657 // In async-lowering, one of the arguments is an async context as determined 658 // by the `llvm.coro.id.async` intrinsic. We can retrieve the async context of 659 // the resume function from the async context projection function associated 660 // with the active suspend. The frame is located as a tail to the async 661 // context header. 662 case coro::ABI::Async: { 663 auto *CalleeContext = NewF->getArg(Shape.AsyncLowering.ContextArgNo); 664 auto *FramePtrTy = Shape.FrameTy->getPointerTo(); 665 auto *ProjectionFunc = cast<CoroSuspendAsyncInst>(ActiveSuspend) 666 ->getAsyncContextProjectionFunction(); 667 // Calling i8* (i8*) 668 auto *CallerContext = Builder.CreateCall( 669 cast<FunctionType>(ProjectionFunc->getType()->getPointerElementType()), 670 ProjectionFunc, CalleeContext); 671 CallerContext->setCallingConv(ProjectionFunc->getCallingConv()); 672 // The frame is located after the async_context header. 673 auto &Context = Builder.getContext(); 674 auto *FramePtrAddr = Builder.CreateConstInBoundsGEP1_32( 675 Type::getInt8Ty(Context), CallerContext, 676 Shape.AsyncLowering.FrameOffset, "async.ctx.frameptr"); 677 return Builder.CreateBitCast(FramePtrAddr, FramePtrTy); 678 } 679 // In continuation-lowering, the argument is the opaque storage. 680 case coro::ABI::Retcon: 681 case coro::ABI::RetconOnce: { 682 Argument *NewStorage = &*NewF->arg_begin(); 683 auto FramePtrTy = Shape.FrameTy->getPointerTo(); 684 685 // If the storage is inline, just bitcast to the storage to the frame type. 686 if (Shape.RetconLowering.IsFrameInlineInStorage) 687 return Builder.CreateBitCast(NewStorage, FramePtrTy); 688 689 // Otherwise, load the real frame from the opaque storage. 690 auto FramePtrPtr = 691 Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo()); 692 return Builder.CreateLoad(FramePtrTy, FramePtrPtr); 693 } 694 } 695 llvm_unreachable("bad ABI"); 696 } 697 698 static void addFramePointerAttrs(AttributeList &Attrs, LLVMContext &Context, 699 unsigned ParamIndex, 700 uint64_t Size, Align Alignment) { 701 AttrBuilder ParamAttrs; 702 ParamAttrs.addAttribute(Attribute::NonNull); 703 ParamAttrs.addAttribute(Attribute::NoAlias); 704 ParamAttrs.addAlignmentAttr(Alignment); 705 ParamAttrs.addDereferenceableAttr(Size); 706 Attrs = Attrs.addParamAttributes(Context, ParamIndex, ParamAttrs); 707 } 708 709 /// Clone the body of the original function into a resume function of 710 /// some sort. 711 void CoroCloner::create() { 712 // Create the new function if we don't already have one. 713 if (!NewF) { 714 NewF = createCloneDeclaration(OrigF, Shape, Suffix, 715 OrigF.getParent()->end()); 716 } 717 718 // Replace all args with undefs. The buildCoroutineFrame algorithm already 719 // rewritten access to the args that occurs after suspend points with loads 720 // and stores to/from the coroutine frame. 721 for (Argument &A : OrigF.args()) 722 VMap[&A] = UndefValue::get(A.getType()); 723 724 SmallVector<ReturnInst *, 4> Returns; 725 726 // Ignore attempts to change certain attributes of the function. 727 // TODO: maybe there should be a way to suppress this during cloning? 728 auto savedVisibility = NewF->getVisibility(); 729 auto savedUnnamedAddr = NewF->getUnnamedAddr(); 730 auto savedDLLStorageClass = NewF->getDLLStorageClass(); 731 732 // NewF's linkage (which CloneFunctionInto does *not* change) might not 733 // be compatible with the visibility of OrigF (which it *does* change), 734 // so protect against that. 735 auto savedLinkage = NewF->getLinkage(); 736 NewF->setLinkage(llvm::GlobalValue::ExternalLinkage); 737 738 CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns); 739 740 NewF->setLinkage(savedLinkage); 741 NewF->setVisibility(savedVisibility); 742 NewF->setUnnamedAddr(savedUnnamedAddr); 743 NewF->setDLLStorageClass(savedDLLStorageClass); 744 745 auto &Context = NewF->getContext(); 746 747 // Replace the attributes of the new function: 748 auto OrigAttrs = NewF->getAttributes(); 749 auto NewAttrs = AttributeList(); 750 751 switch (Shape.ABI) { 752 case coro::ABI::Switch: 753 // Bootstrap attributes by copying function attributes from the 754 // original function. This should include optimization settings and so on. 755 NewAttrs = NewAttrs.addAttributes(Context, AttributeList::FunctionIndex, 756 OrigAttrs.getFnAttributes()); 757 758 addFramePointerAttrs(NewAttrs, Context, 0, 759 Shape.FrameSize, Shape.FrameAlign); 760 break; 761 case coro::ABI::Async: 762 break; 763 case coro::ABI::Retcon: 764 case coro::ABI::RetconOnce: 765 // If we have a continuation prototype, just use its attributes, 766 // full-stop. 767 NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes(); 768 769 addFramePointerAttrs(NewAttrs, Context, 0, 770 Shape.getRetconCoroId()->getStorageSize(), 771 Shape.getRetconCoroId()->getStorageAlignment()); 772 break; 773 } 774 775 switch (Shape.ABI) { 776 // In these ABIs, the cloned functions always return 'void', and the 777 // existing return sites are meaningless. Note that for unique 778 // continuations, this includes the returns associated with suspends; 779 // this is fine because we can't suspend twice. 780 case coro::ABI::Switch: 781 case coro::ABI::RetconOnce: 782 // Remove old returns. 783 for (ReturnInst *Return : Returns) 784 changeToUnreachable(Return, /*UseLLVMTrap=*/false); 785 break; 786 787 // With multi-suspend continuations, we'll already have eliminated the 788 // original returns and inserted returns before all the suspend points, 789 // so we want to leave any returns in place. 790 case coro::ABI::Retcon: 791 break; 792 // Async lowering will insert musttail call functions at all suspend points 793 // followed by a return. 794 // Don't change returns to unreachable because that will trip up the verifier. 795 // These returns should be unreachable from the clone. 796 case coro::ABI::Async: 797 break; 798 } 799 800 NewF->setAttributes(NewAttrs); 801 NewF->setCallingConv(Shape.getResumeFunctionCC()); 802 803 // Set up the new entry block. 804 replaceEntryBlock(); 805 806 Builder.SetInsertPoint(&NewF->getEntryBlock().front()); 807 NewFramePtr = deriveNewFramePointer(); 808 809 // Remap frame pointer. 810 Value *OldFramePtr = VMap[Shape.FramePtr]; 811 NewFramePtr->takeName(OldFramePtr); 812 OldFramePtr->replaceAllUsesWith(NewFramePtr); 813 814 // Remap vFrame pointer. 815 auto *NewVFrame = Builder.CreateBitCast( 816 NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame"); 817 Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]); 818 OldVFrame->replaceAllUsesWith(NewVFrame); 819 820 switch (Shape.ABI) { 821 case coro::ABI::Switch: 822 // Rewrite final suspend handling as it is not done via switch (allows to 823 // remove final case from the switch, since it is undefined behavior to 824 // resume the coroutine suspended at the final suspend point. 825 if (Shape.SwitchLowering.HasFinalSuspend) 826 handleFinalSuspend(); 827 break; 828 case coro::ABI::Async: 829 case coro::ABI::Retcon: 830 case coro::ABI::RetconOnce: 831 // Replace uses of the active suspend with the corresponding 832 // continuation-function arguments. 833 assert(ActiveSuspend != nullptr && 834 "no active suspend when lowering a continuation-style coroutine"); 835 replaceRetconOrAsyncSuspendUses(); 836 break; 837 } 838 839 // Handle suspends. 840 replaceCoroSuspends(); 841 842 // Handle swifterror. 843 replaceSwiftErrorOps(); 844 845 // Remove coro.end intrinsics. 846 replaceCoroEnds(); 847 848 // Eliminate coro.free from the clones, replacing it with 'null' in cleanup, 849 // to suppress deallocation code. 850 if (Shape.ABI == coro::ABI::Switch) 851 coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]), 852 /*Elide=*/ FKind == CoroCloner::Kind::SwitchCleanup); 853 } 854 855 // Create a resume clone by cloning the body of the original function, setting 856 // new entry block and replacing coro.suspend an appropriate value to force 857 // resume or cleanup pass for every suspend point. 858 static Function *createClone(Function &F, const Twine &Suffix, 859 coro::Shape &Shape, CoroCloner::Kind FKind) { 860 CoroCloner Cloner(F, Suffix, Shape, FKind); 861 Cloner.create(); 862 return Cloner.getFunction(); 863 } 864 865 /// Remove calls to llvm.coro.end in the original function. 866 static void removeCoroEnds(const coro::Shape &Shape, CallGraph *CG) { 867 for (auto End : Shape.CoroEnds) { 868 replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, CG); 869 } 870 } 871 872 static void updateAsyncFuncPointerContextSize(coro::Shape &Shape) { 873 assert(Shape.ABI == coro::ABI::Async); 874 875 auto *FuncPtrStruct = cast<ConstantStruct>( 876 Shape.AsyncLowering.AsyncFuncPointer->getInitializer()); 877 auto *OrigRelativeFunOffset = FuncPtrStruct->getOperand(0); 878 auto *OrigContextSize = FuncPtrStruct->getOperand(1); 879 auto *NewContextSize = ConstantInt::get(OrigContextSize->getType(), 880 Shape.AsyncLowering.ContextSize); 881 auto *NewFuncPtrStruct = ConstantStruct::get( 882 FuncPtrStruct->getType(), OrigRelativeFunOffset, NewContextSize); 883 884 Shape.AsyncLowering.AsyncFuncPointer->setInitializer(NewFuncPtrStruct); 885 } 886 887 static void replaceFrameSize(coro::Shape &Shape) { 888 if (Shape.ABI == coro::ABI::Async) 889 updateAsyncFuncPointerContextSize(Shape); 890 891 if (Shape.CoroSizes.empty()) 892 return; 893 894 // In the same function all coro.sizes should have the same result type. 895 auto *SizeIntrin = Shape.CoroSizes.back(); 896 Module *M = SizeIntrin->getModule(); 897 const DataLayout &DL = M->getDataLayout(); 898 auto Size = DL.getTypeAllocSize(Shape.FrameTy); 899 auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size); 900 901 for (CoroSizeInst *CS : Shape.CoroSizes) { 902 CS->replaceAllUsesWith(SizeConstant); 903 CS->eraseFromParent(); 904 } 905 } 906 907 // Create a global constant array containing pointers to functions provided and 908 // set Info parameter of CoroBegin to point at this constant. Example: 909 // 910 // @f.resumers = internal constant [2 x void(%f.frame*)*] 911 // [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy] 912 // define void @f() { 913 // ... 914 // call i8* @llvm.coro.begin(i8* null, i32 0, i8* null, 915 // i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*)) 916 // 917 // Assumes that all the functions have the same signature. 918 static void setCoroInfo(Function &F, coro::Shape &Shape, 919 ArrayRef<Function *> Fns) { 920 // This only works under the switch-lowering ABI because coro elision 921 // only works on the switch-lowering ABI. 922 assert(Shape.ABI == coro::ABI::Switch); 923 924 SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end()); 925 assert(!Args.empty()); 926 Function *Part = *Fns.begin(); 927 Module *M = Part->getParent(); 928 auto *ArrTy = ArrayType::get(Part->getType(), Args.size()); 929 930 auto *ConstVal = ConstantArray::get(ArrTy, Args); 931 auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true, 932 GlobalVariable::PrivateLinkage, ConstVal, 933 F.getName() + Twine(".resumers")); 934 935 // Update coro.begin instruction to refer to this constant. 936 LLVMContext &C = F.getContext(); 937 auto *BC = ConstantExpr::getPointerCast(GV, Type::getInt8PtrTy(C)); 938 Shape.getSwitchCoroId()->setInfo(BC); 939 } 940 941 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame. 942 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn, 943 Function *DestroyFn, Function *CleanupFn) { 944 assert(Shape.ABI == coro::ABI::Switch); 945 946 IRBuilder<> Builder(Shape.FramePtr->getNextNode()); 947 auto *ResumeAddr = Builder.CreateStructGEP( 948 Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Resume, 949 "resume.addr"); 950 Builder.CreateStore(ResumeFn, ResumeAddr); 951 952 Value *DestroyOrCleanupFn = DestroyFn; 953 954 CoroIdInst *CoroId = Shape.getSwitchCoroId(); 955 if (CoroAllocInst *CA = CoroId->getCoroAlloc()) { 956 // If there is a CoroAlloc and it returns false (meaning we elide the 957 // allocation, use CleanupFn instead of DestroyFn). 958 DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn); 959 } 960 961 auto *DestroyAddr = Builder.CreateStructGEP( 962 Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Destroy, 963 "destroy.addr"); 964 Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr); 965 } 966 967 static void postSplitCleanup(Function &F) { 968 removeUnreachableBlocks(F); 969 970 // For now, we do a mandatory verification step because we don't 971 // entirely trust this pass. Note that we don't want to add a verifier 972 // pass to FPM below because it will also verify all the global data. 973 if (verifyFunction(F, &errs())) 974 report_fatal_error("Broken function"); 975 976 legacy::FunctionPassManager FPM(F.getParent()); 977 978 FPM.add(createSCCPPass()); 979 FPM.add(createCFGSimplificationPass()); 980 FPM.add(createEarlyCSEPass()); 981 FPM.add(createCFGSimplificationPass()); 982 983 FPM.doInitialization(); 984 FPM.run(F); 985 FPM.doFinalization(); 986 } 987 988 // Assuming we arrived at the block NewBlock from Prev instruction, store 989 // PHI's incoming values in the ResolvedValues map. 990 static void 991 scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock, 992 DenseMap<Value *, Value *> &ResolvedValues) { 993 auto *PrevBB = Prev->getParent(); 994 for (PHINode &PN : NewBlock->phis()) { 995 auto V = PN.getIncomingValueForBlock(PrevBB); 996 // See if we already resolved it. 997 auto VI = ResolvedValues.find(V); 998 if (VI != ResolvedValues.end()) 999 V = VI->second; 1000 // Remember the value. 1001 ResolvedValues[&PN] = V; 1002 } 1003 } 1004 1005 // Replace a sequence of branches leading to a ret, with a clone of a ret 1006 // instruction. Suspend instruction represented by a switch, track the PHI 1007 // values and select the correct case successor when possible. 1008 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) { 1009 DenseMap<Value *, Value *> ResolvedValues; 1010 BasicBlock *UnconditionalSucc = nullptr; 1011 1012 Instruction *I = InitialInst; 1013 while (I->isTerminator() || 1014 (isa<CmpInst>(I) && I->getNextNode()->isTerminator())) { 1015 if (isa<ReturnInst>(I)) { 1016 if (I != InitialInst) { 1017 // If InitialInst is an unconditional branch, 1018 // remove PHI values that come from basic block of InitialInst 1019 if (UnconditionalSucc) 1020 UnconditionalSucc->removePredecessor(InitialInst->getParent(), true); 1021 ReplaceInstWithInst(InitialInst, I->clone()); 1022 } 1023 return true; 1024 } 1025 if (auto *BR = dyn_cast<BranchInst>(I)) { 1026 if (BR->isUnconditional()) { 1027 BasicBlock *BB = BR->getSuccessor(0); 1028 if (I == InitialInst) 1029 UnconditionalSucc = BB; 1030 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 1031 I = BB->getFirstNonPHIOrDbgOrLifetime(); 1032 continue; 1033 } 1034 } else if (auto *CondCmp = dyn_cast<CmpInst>(I)) { 1035 auto *BR = dyn_cast<BranchInst>(I->getNextNode()); 1036 if (BR && BR->isConditional() && CondCmp == BR->getCondition()) { 1037 // If the case number of suspended switch instruction is reduced to 1038 // 1, then it is simplified to CmpInst in llvm::ConstantFoldTerminator. 1039 // And the comparsion looks like : %cond = icmp eq i8 %V, constant. 1040 ConstantInt *CondConst = dyn_cast<ConstantInt>(CondCmp->getOperand(1)); 1041 if (CondConst && CondCmp->getPredicate() == CmpInst::ICMP_EQ) { 1042 Value *V = CondCmp->getOperand(0); 1043 auto it = ResolvedValues.find(V); 1044 if (it != ResolvedValues.end()) 1045 V = it->second; 1046 1047 if (ConstantInt *Cond0 = dyn_cast<ConstantInt>(V)) { 1048 BasicBlock *BB = Cond0->equalsInt(CondConst->getZExtValue()) 1049 ? BR->getSuccessor(0) 1050 : BR->getSuccessor(1); 1051 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 1052 I = BB->getFirstNonPHIOrDbgOrLifetime(); 1053 continue; 1054 } 1055 } 1056 } 1057 } else if (auto *SI = dyn_cast<SwitchInst>(I)) { 1058 Value *V = SI->getCondition(); 1059 auto it = ResolvedValues.find(V); 1060 if (it != ResolvedValues.end()) 1061 V = it->second; 1062 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) { 1063 BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor(); 1064 scanPHIsAndUpdateValueMap(I, BB, ResolvedValues); 1065 I = BB->getFirstNonPHIOrDbgOrLifetime(); 1066 continue; 1067 } 1068 } 1069 return false; 1070 } 1071 return false; 1072 } 1073 1074 // Check whether CI obeys the rules of musttail attribute. 1075 static bool shouldBeMustTail(const CallInst &CI, const Function &F) { 1076 if (CI.isInlineAsm()) 1077 return false; 1078 1079 // Match prototypes and calling conventions of resume function. 1080 FunctionType *CalleeTy = CI.getFunctionType(); 1081 if (!CalleeTy->getReturnType()->isVoidTy() || (CalleeTy->getNumParams() != 1)) 1082 return false; 1083 1084 Type *CalleeParmTy = CalleeTy->getParamType(0); 1085 if (!CalleeParmTy->isPointerTy() || 1086 (CalleeParmTy->getPointerAddressSpace() != 0)) 1087 return false; 1088 1089 if (CI.getCallingConv() != F.getCallingConv()) 1090 return false; 1091 1092 // CI should not has any ABI-impacting function attributes. 1093 static const Attribute::AttrKind ABIAttrs[] = { 1094 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca, 1095 Attribute::Preallocated, Attribute::InReg, Attribute::Returned, 1096 Attribute::SwiftSelf, Attribute::SwiftError}; 1097 AttributeList Attrs = CI.getAttributes(); 1098 for (auto AK : ABIAttrs) 1099 if (Attrs.hasParamAttribute(0, AK)) 1100 return false; 1101 1102 return true; 1103 } 1104 1105 // Add musttail to any resume instructions that is immediately followed by a 1106 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call 1107 // for symmetrical coroutine control transfer (C++ Coroutines TS extension). 1108 // This transformation is done only in the resume part of the coroutine that has 1109 // identical signature and calling convention as the coro.resume call. 1110 static void addMustTailToCoroResumes(Function &F) { 1111 bool changed = false; 1112 1113 // Collect potential resume instructions. 1114 SmallVector<CallInst *, 4> Resumes; 1115 for (auto &I : instructions(F)) 1116 if (auto *Call = dyn_cast<CallInst>(&I)) 1117 if (shouldBeMustTail(*Call, F)) 1118 Resumes.push_back(Call); 1119 1120 // Set musttail on those that are followed by a ret instruction. 1121 for (CallInst *Call : Resumes) 1122 if (simplifyTerminatorLeadingToRet(Call->getNextNode())) { 1123 Call->setTailCallKind(CallInst::TCK_MustTail); 1124 changed = true; 1125 } 1126 1127 if (changed) 1128 removeUnreachableBlocks(F); 1129 } 1130 1131 // Coroutine has no suspend points. Remove heap allocation for the coroutine 1132 // frame if possible. 1133 static void handleNoSuspendCoroutine(coro::Shape &Shape) { 1134 auto *CoroBegin = Shape.CoroBegin; 1135 auto *CoroId = CoroBegin->getId(); 1136 auto *AllocInst = CoroId->getCoroAlloc(); 1137 switch (Shape.ABI) { 1138 case coro::ABI::Switch: { 1139 auto SwitchId = cast<CoroIdInst>(CoroId); 1140 coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr); 1141 if (AllocInst) { 1142 IRBuilder<> Builder(AllocInst); 1143 auto *Frame = Builder.CreateAlloca(Shape.FrameTy); 1144 Frame->setAlignment(Shape.FrameAlign); 1145 auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy()); 1146 AllocInst->replaceAllUsesWith(Builder.getFalse()); 1147 AllocInst->eraseFromParent(); 1148 CoroBegin->replaceAllUsesWith(VFrame); 1149 } else { 1150 CoroBegin->replaceAllUsesWith(CoroBegin->getMem()); 1151 } 1152 break; 1153 } 1154 case coro::ABI::Async: 1155 case coro::ABI::Retcon: 1156 case coro::ABI::RetconOnce: 1157 CoroBegin->replaceAllUsesWith(UndefValue::get(CoroBegin->getType())); 1158 break; 1159 } 1160 1161 CoroBegin->eraseFromParent(); 1162 } 1163 1164 // SimplifySuspendPoint needs to check that there is no calls between 1165 // coro_save and coro_suspend, since any of the calls may potentially resume 1166 // the coroutine and if that is the case we cannot eliminate the suspend point. 1167 static bool hasCallsInBlockBetween(Instruction *From, Instruction *To) { 1168 for (Instruction *I = From; I != To; I = I->getNextNode()) { 1169 // Assume that no intrinsic can resume the coroutine. 1170 if (isa<IntrinsicInst>(I)) 1171 continue; 1172 1173 if (isa<CallBase>(I)) 1174 return true; 1175 } 1176 return false; 1177 } 1178 1179 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) { 1180 SmallPtrSet<BasicBlock *, 8> Set; 1181 SmallVector<BasicBlock *, 8> Worklist; 1182 1183 Set.insert(SaveBB); 1184 Worklist.push_back(ResDesBB); 1185 1186 // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr 1187 // returns a token consumed by suspend instruction, all blocks in between 1188 // will have to eventually hit SaveBB when going backwards from ResDesBB. 1189 while (!Worklist.empty()) { 1190 auto *BB = Worklist.pop_back_val(); 1191 Set.insert(BB); 1192 for (auto *Pred : predecessors(BB)) 1193 if (Set.count(Pred) == 0) 1194 Worklist.push_back(Pred); 1195 } 1196 1197 // SaveBB and ResDesBB are checked separately in hasCallsBetween. 1198 Set.erase(SaveBB); 1199 Set.erase(ResDesBB); 1200 1201 for (auto *BB : Set) 1202 if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr)) 1203 return true; 1204 1205 return false; 1206 } 1207 1208 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) { 1209 auto *SaveBB = Save->getParent(); 1210 auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent(); 1211 1212 if (SaveBB == ResumeOrDestroyBB) 1213 return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy); 1214 1215 // Any calls from Save to the end of the block? 1216 if (hasCallsInBlockBetween(Save->getNextNode(), nullptr)) 1217 return true; 1218 1219 // Any calls from begging of the block up to ResumeOrDestroy? 1220 if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(), 1221 ResumeOrDestroy)) 1222 return true; 1223 1224 // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB? 1225 if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB)) 1226 return true; 1227 1228 return false; 1229 } 1230 1231 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the 1232 // suspend point and replace it with nornal control flow. 1233 static bool simplifySuspendPoint(CoroSuspendInst *Suspend, 1234 CoroBeginInst *CoroBegin) { 1235 Instruction *Prev = Suspend->getPrevNode(); 1236 if (!Prev) { 1237 auto *Pred = Suspend->getParent()->getSinglePredecessor(); 1238 if (!Pred) 1239 return false; 1240 Prev = Pred->getTerminator(); 1241 } 1242 1243 CallBase *CB = dyn_cast<CallBase>(Prev); 1244 if (!CB) 1245 return false; 1246 1247 auto *Callee = CB->getCalledOperand()->stripPointerCasts(); 1248 1249 // See if the callsite is for resumption or destruction of the coroutine. 1250 auto *SubFn = dyn_cast<CoroSubFnInst>(Callee); 1251 if (!SubFn) 1252 return false; 1253 1254 // Does not refer to the current coroutine, we cannot do anything with it. 1255 if (SubFn->getFrame() != CoroBegin) 1256 return false; 1257 1258 // See if the transformation is safe. Specifically, see if there are any 1259 // calls in between Save and CallInstr. They can potenitally resume the 1260 // coroutine rendering this optimization unsafe. 1261 auto *Save = Suspend->getCoroSave(); 1262 if (hasCallsBetween(Save, CB)) 1263 return false; 1264 1265 // Replace llvm.coro.suspend with the value that results in resumption over 1266 // the resume or cleanup path. 1267 Suspend->replaceAllUsesWith(SubFn->getRawIndex()); 1268 Suspend->eraseFromParent(); 1269 Save->eraseFromParent(); 1270 1271 // No longer need a call to coro.resume or coro.destroy. 1272 if (auto *Invoke = dyn_cast<InvokeInst>(CB)) { 1273 BranchInst::Create(Invoke->getNormalDest(), Invoke); 1274 } 1275 1276 // Grab the CalledValue from CB before erasing the CallInstr. 1277 auto *CalledValue = CB->getCalledOperand(); 1278 CB->eraseFromParent(); 1279 1280 // If no more users remove it. Usually it is a bitcast of SubFn. 1281 if (CalledValue != SubFn && CalledValue->user_empty()) 1282 if (auto *I = dyn_cast<Instruction>(CalledValue)) 1283 I->eraseFromParent(); 1284 1285 // Now we are good to remove SubFn. 1286 if (SubFn->user_empty()) 1287 SubFn->eraseFromParent(); 1288 1289 return true; 1290 } 1291 1292 // Remove suspend points that are simplified. 1293 static void simplifySuspendPoints(coro::Shape &Shape) { 1294 // Currently, the only simplification we do is switch-lowering-specific. 1295 if (Shape.ABI != coro::ABI::Switch) 1296 return; 1297 1298 auto &S = Shape.CoroSuspends; 1299 size_t I = 0, N = S.size(); 1300 if (N == 0) 1301 return; 1302 while (true) { 1303 auto SI = cast<CoroSuspendInst>(S[I]); 1304 // Leave final.suspend to handleFinalSuspend since it is undefined behavior 1305 // to resume a coroutine suspended at the final suspend point. 1306 if (!SI->isFinal() && simplifySuspendPoint(SI, Shape.CoroBegin)) { 1307 if (--N == I) 1308 break; 1309 std::swap(S[I], S[N]); 1310 continue; 1311 } 1312 if (++I == N) 1313 break; 1314 } 1315 S.resize(N); 1316 } 1317 1318 static void splitSwitchCoroutine(Function &F, coro::Shape &Shape, 1319 SmallVectorImpl<Function *> &Clones) { 1320 assert(Shape.ABI == coro::ABI::Switch); 1321 1322 createResumeEntryBlock(F, Shape); 1323 auto ResumeClone = createClone(F, ".resume", Shape, 1324 CoroCloner::Kind::SwitchResume); 1325 auto DestroyClone = createClone(F, ".destroy", Shape, 1326 CoroCloner::Kind::SwitchUnwind); 1327 auto CleanupClone = createClone(F, ".cleanup", Shape, 1328 CoroCloner::Kind::SwitchCleanup); 1329 1330 postSplitCleanup(*ResumeClone); 1331 postSplitCleanup(*DestroyClone); 1332 postSplitCleanup(*CleanupClone); 1333 1334 addMustTailToCoroResumes(*ResumeClone); 1335 1336 // Store addresses resume/destroy/cleanup functions in the coroutine frame. 1337 updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone); 1338 1339 assert(Clones.empty()); 1340 Clones.push_back(ResumeClone); 1341 Clones.push_back(DestroyClone); 1342 Clones.push_back(CleanupClone); 1343 1344 // Create a constant array referring to resume/destroy/clone functions pointed 1345 // by the last argument of @llvm.coro.info, so that CoroElide pass can 1346 // determined correct function to call. 1347 setCoroInfo(F, Shape, Clones); 1348 } 1349 1350 static void replaceAsyncResumeFunction(CoroSuspendAsyncInst *Suspend, 1351 Value *Continuation) { 1352 auto *ResumeIntrinsic = Suspend->getResumeFunction(); 1353 auto &Context = Suspend->getParent()->getParent()->getContext(); 1354 auto *Int8PtrTy = Type::getInt8PtrTy(Context); 1355 1356 IRBuilder<> Builder(ResumeIntrinsic); 1357 auto *Val = Builder.CreateBitOrPointerCast(Continuation, Int8PtrTy); 1358 ResumeIntrinsic->replaceAllUsesWith(Val); 1359 ResumeIntrinsic->eraseFromParent(); 1360 Suspend->setOperand(0, UndefValue::get(Int8PtrTy)); 1361 } 1362 1363 static void splitAsyncCoroutine(Function &F, coro::Shape &Shape, 1364 SmallVectorImpl<Function *> &Clones) { 1365 assert(Shape.ABI == coro::ABI::Async); 1366 assert(Clones.empty()); 1367 // Reset various things that the optimizer might have decided it 1368 // "knows" about the coroutine function due to not seeing a return. 1369 F.removeFnAttr(Attribute::NoReturn); 1370 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 1371 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 1372 1373 auto &Context = F.getContext(); 1374 auto *Int8PtrTy = Type::getInt8PtrTy(Context); 1375 1376 auto *Id = cast<CoroIdAsyncInst>(Shape.CoroBegin->getId()); 1377 IRBuilder<> Builder(Id); 1378 1379 auto *FramePtr = Id->getStorage(); 1380 FramePtr = Builder.CreateBitOrPointerCast(FramePtr, Int8PtrTy); 1381 FramePtr = Builder.CreateConstInBoundsGEP1_32( 1382 Type::getInt8Ty(Context), FramePtr, Shape.AsyncLowering.FrameOffset, 1383 "async.ctx.frameptr"); 1384 1385 // Map all uses of llvm.coro.begin to the allocated frame pointer. 1386 { 1387 // Make sure we don't invalidate Shape.FramePtr. 1388 TrackingVH<Instruction> Handle(Shape.FramePtr); 1389 Shape.CoroBegin->replaceAllUsesWith(FramePtr); 1390 Shape.FramePtr = Handle.getValPtr(); 1391 } 1392 1393 // Create all the functions in order after the main function. 1394 auto NextF = std::next(F.getIterator()); 1395 1396 // Create a continuation function for each of the suspend points. 1397 Clones.reserve(Shape.CoroSuspends.size()); 1398 for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) { 1399 auto *Suspend = cast<CoroSuspendAsyncInst>(Shape.CoroSuspends[Idx]); 1400 1401 // Create the clone declaration. 1402 auto *Continuation = 1403 createCloneDeclaration(F, Shape, ".resume." + Twine(Idx), NextF); 1404 Clones.push_back(Continuation); 1405 1406 // Insert a branch to a new return block immediately before the suspend 1407 // point. 1408 auto *SuspendBB = Suspend->getParent(); 1409 auto *NewSuspendBB = SuspendBB->splitBasicBlock(Suspend); 1410 auto *Branch = cast<BranchInst>(SuspendBB->getTerminator()); 1411 1412 // Place it before the first suspend. 1413 auto *ReturnBB = 1414 BasicBlock::Create(F.getContext(), "coro.return", &F, NewSuspendBB); 1415 Branch->setSuccessor(0, ReturnBB); 1416 1417 IRBuilder<> Builder(ReturnBB); 1418 1419 // Insert the call to the tail call function. 1420 auto *Fun = Suspend->getMustTailCallFunction(); 1421 SmallVector<Value *, 8> Args(Suspend->operand_values()); 1422 auto *TailCall = Builder.CreateCall( 1423 cast<FunctionType>(Fun->getType()->getPointerElementType()), Fun, 1424 ArrayRef<Value *>(Args).drop_front(3).drop_back(1)); 1425 TailCall->setTailCallKind(CallInst::TCK_MustTail); 1426 TailCall->setCallingConv(Fun->getCallingConv()); 1427 Builder.CreateRetVoid(); 1428 1429 // Replace the lvm.coro.async.resume intrisic call. 1430 replaceAsyncResumeFunction(Suspend, Continuation); 1431 } 1432 1433 assert(Clones.size() == Shape.CoroSuspends.size()); 1434 for (size_t Idx = 0, End = Shape.CoroSuspends.size(); Idx != End; ++Idx) { 1435 auto *Suspend = Shape.CoroSuspends[Idx]; 1436 auto *Clone = Clones[Idx]; 1437 1438 CoroCloner(F, "resume." + Twine(Idx), Shape, Clone, Suspend).create(); 1439 } 1440 } 1441 1442 static void splitRetconCoroutine(Function &F, coro::Shape &Shape, 1443 SmallVectorImpl<Function *> &Clones) { 1444 assert(Shape.ABI == coro::ABI::Retcon || 1445 Shape.ABI == coro::ABI::RetconOnce); 1446 assert(Clones.empty()); 1447 1448 // Reset various things that the optimizer might have decided it 1449 // "knows" about the coroutine function due to not seeing a return. 1450 F.removeFnAttr(Attribute::NoReturn); 1451 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias); 1452 F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull); 1453 1454 // Allocate the frame. 1455 auto *Id = cast<AnyCoroIdRetconInst>(Shape.CoroBegin->getId()); 1456 Value *RawFramePtr; 1457 if (Shape.RetconLowering.IsFrameInlineInStorage) { 1458 RawFramePtr = Id->getStorage(); 1459 } else { 1460 IRBuilder<> Builder(Id); 1461 1462 // Determine the size of the frame. 1463 const DataLayout &DL = F.getParent()->getDataLayout(); 1464 auto Size = DL.getTypeAllocSize(Shape.FrameTy); 1465 1466 // Allocate. We don't need to update the call graph node because we're 1467 // going to recompute it from scratch after splitting. 1468 // FIXME: pass the required alignment 1469 RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr); 1470 RawFramePtr = 1471 Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType()); 1472 1473 // Stash the allocated frame pointer in the continuation storage. 1474 auto Dest = Builder.CreateBitCast(Id->getStorage(), 1475 RawFramePtr->getType()->getPointerTo()); 1476 Builder.CreateStore(RawFramePtr, Dest); 1477 } 1478 1479 // Map all uses of llvm.coro.begin to the allocated frame pointer. 1480 { 1481 // Make sure we don't invalidate Shape.FramePtr. 1482 TrackingVH<Instruction> Handle(Shape.FramePtr); 1483 Shape.CoroBegin->replaceAllUsesWith(RawFramePtr); 1484 Shape.FramePtr = Handle.getValPtr(); 1485 } 1486 1487 // Create a unique return block. 1488 BasicBlock *ReturnBB = nullptr; 1489 SmallVector<PHINode *, 4> ReturnPHIs; 1490 1491 // Create all the functions in order after the main function. 1492 auto NextF = std::next(F.getIterator()); 1493 1494 // Create a continuation function for each of the suspend points. 1495 Clones.reserve(Shape.CoroSuspends.size()); 1496 for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) { 1497 auto Suspend = cast<CoroSuspendRetconInst>(Shape.CoroSuspends[i]); 1498 1499 // Create the clone declaration. 1500 auto Continuation = 1501 createCloneDeclaration(F, Shape, ".resume." + Twine(i), NextF); 1502 Clones.push_back(Continuation); 1503 1504 // Insert a branch to the unified return block immediately before 1505 // the suspend point. 1506 auto SuspendBB = Suspend->getParent(); 1507 auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend); 1508 auto Branch = cast<BranchInst>(SuspendBB->getTerminator()); 1509 1510 // Create the unified return block. 1511 if (!ReturnBB) { 1512 // Place it before the first suspend. 1513 ReturnBB = BasicBlock::Create(F.getContext(), "coro.return", &F, 1514 NewSuspendBB); 1515 Shape.RetconLowering.ReturnBlock = ReturnBB; 1516 1517 IRBuilder<> Builder(ReturnBB); 1518 1519 // Create PHIs for all the return values. 1520 assert(ReturnPHIs.empty()); 1521 1522 // First, the continuation. 1523 ReturnPHIs.push_back(Builder.CreatePHI(Continuation->getType(), 1524 Shape.CoroSuspends.size())); 1525 1526 // Next, all the directly-yielded values. 1527 for (auto ResultTy : Shape.getRetconResultTypes()) 1528 ReturnPHIs.push_back(Builder.CreatePHI(ResultTy, 1529 Shape.CoroSuspends.size())); 1530 1531 // Build the return value. 1532 auto RetTy = F.getReturnType(); 1533 1534 // Cast the continuation value if necessary. 1535 // We can't rely on the types matching up because that type would 1536 // have to be infinite. 1537 auto CastedContinuationTy = 1538 (ReturnPHIs.size() == 1 ? RetTy : RetTy->getStructElementType(0)); 1539 auto *CastedContinuation = 1540 Builder.CreateBitCast(ReturnPHIs[0], CastedContinuationTy); 1541 1542 Value *RetV; 1543 if (ReturnPHIs.size() == 1) { 1544 RetV = CastedContinuation; 1545 } else { 1546 RetV = UndefValue::get(RetTy); 1547 RetV = Builder.CreateInsertValue(RetV, CastedContinuation, 0); 1548 for (size_t I = 1, E = ReturnPHIs.size(); I != E; ++I) 1549 RetV = Builder.CreateInsertValue(RetV, ReturnPHIs[I], I); 1550 } 1551 1552 Builder.CreateRet(RetV); 1553 } 1554 1555 // Branch to the return block. 1556 Branch->setSuccessor(0, ReturnBB); 1557 ReturnPHIs[0]->addIncoming(Continuation, SuspendBB); 1558 size_t NextPHIIndex = 1; 1559 for (auto &VUse : Suspend->value_operands()) 1560 ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB); 1561 assert(NextPHIIndex == ReturnPHIs.size()); 1562 } 1563 1564 assert(Clones.size() == Shape.CoroSuspends.size()); 1565 for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) { 1566 auto Suspend = Shape.CoroSuspends[i]; 1567 auto Clone = Clones[i]; 1568 1569 CoroCloner(F, "resume." + Twine(i), Shape, Clone, Suspend).create(); 1570 } 1571 } 1572 1573 namespace { 1574 class PrettyStackTraceFunction : public PrettyStackTraceEntry { 1575 Function &F; 1576 public: 1577 PrettyStackTraceFunction(Function &F) : F(F) {} 1578 void print(raw_ostream &OS) const override { 1579 OS << "While splitting coroutine "; 1580 F.printAsOperand(OS, /*print type*/ false, F.getParent()); 1581 OS << "\n"; 1582 } 1583 }; 1584 } 1585 1586 static coro::Shape splitCoroutine(Function &F, 1587 SmallVectorImpl<Function *> &Clones, 1588 bool ReuseFrameSlot) { 1589 PrettyStackTraceFunction prettyStackTrace(F); 1590 1591 // The suspend-crossing algorithm in buildCoroutineFrame get tripped 1592 // up by uses in unreachable blocks, so remove them as a first pass. 1593 removeUnreachableBlocks(F); 1594 1595 coro::Shape Shape(F, ReuseFrameSlot); 1596 if (!Shape.CoroBegin) 1597 return Shape; 1598 1599 simplifySuspendPoints(Shape); 1600 buildCoroutineFrame(F, Shape); 1601 replaceFrameSize(Shape); 1602 1603 // If there are no suspend points, no split required, just remove 1604 // the allocation and deallocation blocks, they are not needed. 1605 if (Shape.CoroSuspends.empty()) { 1606 handleNoSuspendCoroutine(Shape); 1607 } else { 1608 switch (Shape.ABI) { 1609 case coro::ABI::Switch: 1610 splitSwitchCoroutine(F, Shape, Clones); 1611 break; 1612 case coro::ABI::Async: 1613 splitAsyncCoroutine(F, Shape, Clones); 1614 break; 1615 case coro::ABI::Retcon: 1616 case coro::ABI::RetconOnce: 1617 splitRetconCoroutine(F, Shape, Clones); 1618 break; 1619 } 1620 } 1621 1622 // Replace all the swifterror operations in the original function. 1623 // This invalidates SwiftErrorOps in the Shape. 1624 replaceSwiftErrorOps(F, Shape, nullptr); 1625 1626 return Shape; 1627 } 1628 1629 static void 1630 updateCallGraphAfterCoroutineSplit(Function &F, const coro::Shape &Shape, 1631 const SmallVectorImpl<Function *> &Clones, 1632 CallGraph &CG, CallGraphSCC &SCC) { 1633 if (!Shape.CoroBegin) 1634 return; 1635 1636 removeCoroEnds(Shape, &CG); 1637 postSplitCleanup(F); 1638 1639 // Update call graph and add the functions we created to the SCC. 1640 coro::updateCallGraph(F, Clones, CG, SCC); 1641 } 1642 1643 static void updateCallGraphAfterCoroutineSplit( 1644 LazyCallGraph::Node &N, const coro::Shape &Shape, 1645 const SmallVectorImpl<Function *> &Clones, LazyCallGraph::SCC &C, 1646 LazyCallGraph &CG, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, 1647 FunctionAnalysisManager &FAM) { 1648 if (!Shape.CoroBegin) 1649 return; 1650 1651 for (llvm::CoroEndInst *End : Shape.CoroEnds) { 1652 auto &Context = End->getContext(); 1653 End->replaceAllUsesWith(ConstantInt::getFalse(Context)); 1654 End->eraseFromParent(); 1655 } 1656 1657 postSplitCleanup(N.getFunction()); 1658 1659 // We've inserted instructions into coroutine 'f' that reference the three new 1660 // coroutine funclets. We must now update the call graph so that reference 1661 // edges between 'f' and its funclets are added to it. LazyCallGraph only 1662 // allows CGSCC passes to insert "trivial" reference edges. We've ensured 1663 // above, by inserting the funclets into the same SCC as the corutine, that 1664 // the edges are trivial. 1665 // 1666 // N.B.: If we didn't update the call graph here, a CGSCCToFunctionPassAdaptor 1667 // later in this CGSCC pass pipeline may be run, triggering a call graph 1668 // update of its own. Function passes run by the adaptor are not permitted to 1669 // add new edges of any kind to the graph, and the new edges inserted by this 1670 // pass would be misattributed to that unrelated function pass. 1671 updateCGAndAnalysisManagerForCGSCCPass(CG, C, N, AM, UR, FAM); 1672 } 1673 1674 // When we see the coroutine the first time, we insert an indirect call to a 1675 // devirt trigger function and mark the coroutine that it is now ready for 1676 // split. 1677 // Async lowering uses this after it has split the function to restart the 1678 // pipeline. 1679 static void prepareForSplit(Function &F, CallGraph &CG, 1680 bool MarkForAsyncRestart = false) { 1681 Module &M = *F.getParent(); 1682 LLVMContext &Context = F.getContext(); 1683 #ifndef NDEBUG 1684 Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN); 1685 assert(DevirtFn && "coro.devirt.trigger function not found"); 1686 #endif 1687 1688 F.addFnAttr(CORO_PRESPLIT_ATTR, MarkForAsyncRestart 1689 ? ASYNC_RESTART_AFTER_SPLIT 1690 : PREPARED_FOR_SPLIT); 1691 1692 // Insert an indirect call sequence that will be devirtualized by CoroElide 1693 // pass: 1694 // %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1) 1695 // %1 = bitcast i8* %0 to void(i8*)* 1696 // call void %1(i8* null) 1697 coro::LowererBase Lowerer(M); 1698 Instruction *InsertPt = 1699 MarkForAsyncRestart ? F.getEntryBlock().getFirstNonPHIOrDbgOrLifetime() 1700 : F.getEntryBlock().getTerminator(); 1701 auto *Null = ConstantPointerNull::get(Type::getInt8PtrTy(Context)); 1702 auto *DevirtFnAddr = 1703 Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt); 1704 FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Context), 1705 {Type::getInt8PtrTy(Context)}, false); 1706 auto *IndirectCall = CallInst::Create(FnTy, DevirtFnAddr, Null, "", InsertPt); 1707 1708 // Update CG graph with an indirect call we just added. 1709 CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode()); 1710 } 1711 1712 // Make sure that there is a devirtualization trigger function that the 1713 // coro-split pass uses to force a restart of the CGSCC pipeline. If the devirt 1714 // trigger function is not found, we will create one and add it to the current 1715 // SCC. 1716 static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC) { 1717 Module &M = CG.getModule(); 1718 if (M.getFunction(CORO_DEVIRT_TRIGGER_FN)) 1719 return; 1720 1721 LLVMContext &C = M.getContext(); 1722 auto *FnTy = FunctionType::get(Type::getVoidTy(C), Type::getInt8PtrTy(C), 1723 /*isVarArg=*/false); 1724 Function *DevirtFn = 1725 Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage, 1726 CORO_DEVIRT_TRIGGER_FN, &M); 1727 DevirtFn->addFnAttr(Attribute::AlwaysInline); 1728 auto *Entry = BasicBlock::Create(C, "entry", DevirtFn); 1729 ReturnInst::Create(C, Entry); 1730 1731 auto *Node = CG.getOrInsertFunction(DevirtFn); 1732 1733 SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end()); 1734 Nodes.push_back(Node); 1735 SCC.initialize(Nodes); 1736 } 1737 1738 /// Replace a call to llvm.coro.prepare.retcon. 1739 static void replacePrepare(CallInst *Prepare, LazyCallGraph &CG, 1740 LazyCallGraph::SCC &C) { 1741 auto CastFn = Prepare->getArgOperand(0); // as an i8* 1742 auto Fn = CastFn->stripPointerCasts(); // as its original type 1743 1744 // Attempt to peephole this pattern: 1745 // %0 = bitcast [[TYPE]] @some_function to i8* 1746 // %1 = call @llvm.coro.prepare.retcon(i8* %0) 1747 // %2 = bitcast %1 to [[TYPE]] 1748 // ==> 1749 // %2 = @some_function 1750 for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); UI != UE;) { 1751 // Look for bitcasts back to the original function type. 1752 auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser()); 1753 if (!Cast || Cast->getType() != Fn->getType()) 1754 continue; 1755 1756 // Replace and remove the cast. 1757 Cast->replaceAllUsesWith(Fn); 1758 Cast->eraseFromParent(); 1759 } 1760 1761 // Replace any remaining uses with the function as an i8*. 1762 // This can never directly be a callee, so we don't need to update CG. 1763 Prepare->replaceAllUsesWith(CastFn); 1764 Prepare->eraseFromParent(); 1765 1766 // Kill dead bitcasts. 1767 while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) { 1768 if (!Cast->use_empty()) 1769 break; 1770 CastFn = Cast->getOperand(0); 1771 Cast->eraseFromParent(); 1772 } 1773 } 1774 /// Replace a call to llvm.coro.prepare.retcon. 1775 static void replacePrepare(CallInst *Prepare, CallGraph &CG) { 1776 auto CastFn = Prepare->getArgOperand(0); // as an i8* 1777 auto Fn = CastFn->stripPointerCasts(); // as its original type 1778 1779 // Find call graph nodes for the preparation. 1780 CallGraphNode *PrepareUserNode = nullptr, *FnNode = nullptr; 1781 if (auto ConcreteFn = dyn_cast<Function>(Fn)) { 1782 PrepareUserNode = CG[Prepare->getFunction()]; 1783 FnNode = CG[ConcreteFn]; 1784 } 1785 1786 // Attempt to peephole this pattern: 1787 // %0 = bitcast [[TYPE]] @some_function to i8* 1788 // %1 = call @llvm.coro.prepare.retcon(i8* %0) 1789 // %2 = bitcast %1 to [[TYPE]] 1790 // ==> 1791 // %2 = @some_function 1792 for (auto UI = Prepare->use_begin(), UE = Prepare->use_end(); 1793 UI != UE; ) { 1794 // Look for bitcasts back to the original function type. 1795 auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser()); 1796 if (!Cast || Cast->getType() != Fn->getType()) continue; 1797 1798 // Check whether the replacement will introduce new direct calls. 1799 // If so, we'll need to update the call graph. 1800 if (PrepareUserNode) { 1801 for (auto &Use : Cast->uses()) { 1802 if (auto *CB = dyn_cast<CallBase>(Use.getUser())) { 1803 if (!CB->isCallee(&Use)) 1804 continue; 1805 PrepareUserNode->removeCallEdgeFor(*CB); 1806 PrepareUserNode->addCalledFunction(CB, FnNode); 1807 } 1808 } 1809 } 1810 1811 // Replace and remove the cast. 1812 Cast->replaceAllUsesWith(Fn); 1813 Cast->eraseFromParent(); 1814 } 1815 1816 // Replace any remaining uses with the function as an i8*. 1817 // This can never directly be a callee, so we don't need to update CG. 1818 Prepare->replaceAllUsesWith(CastFn); 1819 Prepare->eraseFromParent(); 1820 1821 // Kill dead bitcasts. 1822 while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) { 1823 if (!Cast->use_empty()) break; 1824 CastFn = Cast->getOperand(0); 1825 Cast->eraseFromParent(); 1826 } 1827 } 1828 1829 static bool replaceAllPrepares(Function *PrepareFn, LazyCallGraph &CG, 1830 LazyCallGraph::SCC &C) { 1831 bool Changed = false; 1832 for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); PI != PE;) { 1833 // Intrinsics can only be used in calls. 1834 auto *Prepare = cast<CallInst>((PI++)->getUser()); 1835 replacePrepare(Prepare, CG, C); 1836 Changed = true; 1837 } 1838 1839 return Changed; 1840 } 1841 1842 /// Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent 1843 /// IPO from operating on calls to a retcon coroutine before it's been 1844 /// split. This is only safe to do after we've split all retcon 1845 /// coroutines in the module. We can do that this in this pass because 1846 /// this pass does promise to split all retcon coroutines (as opposed to 1847 /// switch coroutines, which are lowered in multiple stages). 1848 static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG) { 1849 bool Changed = false; 1850 for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end(); 1851 PI != PE; ) { 1852 // Intrinsics can only be used in calls. 1853 auto *Prepare = cast<CallInst>((PI++)->getUser()); 1854 replacePrepare(Prepare, CG); 1855 Changed = true; 1856 } 1857 1858 return Changed; 1859 } 1860 1861 static bool declaresCoroSplitIntrinsics(const Module &M) { 1862 return coro::declaresIntrinsics(M, {"llvm.coro.begin", 1863 "llvm.coro.prepare.retcon", 1864 "llvm.coro.prepare.async"}); 1865 } 1866 1867 static void addPrepareFunction(const Module &M, 1868 SmallVectorImpl<Function *> &Fns, 1869 StringRef Name) { 1870 auto *PrepareFn = M.getFunction(Name); 1871 if (PrepareFn && !PrepareFn->use_empty()) 1872 Fns.push_back(PrepareFn); 1873 } 1874 1875 PreservedAnalyses CoroSplitPass::run(LazyCallGraph::SCC &C, 1876 CGSCCAnalysisManager &AM, 1877 LazyCallGraph &CG, CGSCCUpdateResult &UR) { 1878 // NB: One invariant of a valid LazyCallGraph::SCC is that it must contain a 1879 // non-zero number of nodes, so we assume that here and grab the first 1880 // node's function's module. 1881 Module &M = *C.begin()->getFunction().getParent(); 1882 auto &FAM = 1883 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 1884 1885 if (!declaresCoroSplitIntrinsics(M)) 1886 return PreservedAnalyses::all(); 1887 1888 // Check for uses of llvm.coro.prepare.retcon/async. 1889 SmallVector<Function *, 2> PrepareFns; 1890 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon"); 1891 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async"); 1892 1893 // Find coroutines for processing. 1894 SmallVector<LazyCallGraph::Node *, 4> Coroutines; 1895 for (LazyCallGraph::Node &N : C) 1896 if (N.getFunction().hasFnAttribute(CORO_PRESPLIT_ATTR)) 1897 Coroutines.push_back(&N); 1898 1899 if (Coroutines.empty() && PrepareFns.empty()) 1900 return PreservedAnalyses::all(); 1901 1902 if (Coroutines.empty()) { 1903 for (auto *PrepareFn : PrepareFns) { 1904 replaceAllPrepares(PrepareFn, CG, C); 1905 } 1906 } 1907 1908 // Split all the coroutines. 1909 for (LazyCallGraph::Node *N : Coroutines) { 1910 Function &F = N->getFunction(); 1911 Attribute Attr = F.getFnAttribute(CORO_PRESPLIT_ATTR); 1912 StringRef Value = Attr.getValueAsString(); 1913 LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F.getName() 1914 << "' state: " << Value << "\n"); 1915 if (Value == UNPREPARED_FOR_SPLIT) { 1916 // Enqueue a second iteration of the CGSCC pipeline. 1917 // N.B.: 1918 // The CoroSplitLegacy pass "triggers" a restart of the CGSCC pass 1919 // pipeline by inserting an indirect function call that the 1920 // CoroElideLegacy pass then replaces with a direct function call. The 1921 // legacy CGSCC pipeline's implicit behavior was as if wrapped in the new 1922 // pass manager abstraction DevirtSCCRepeatedPass. 1923 // 1924 // This pass does not need to "trigger" another run of the pipeline. 1925 // Instead, it simply enqueues the same RefSCC onto the pipeline's 1926 // worklist. 1927 UR.CWorklist.insert(&C); 1928 F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT); 1929 continue; 1930 } 1931 F.removeFnAttr(CORO_PRESPLIT_ATTR); 1932 1933 SmallVector<Function *, 4> Clones; 1934 const coro::Shape Shape = splitCoroutine(F, Clones, ReuseFrameSlot); 1935 updateCallGraphAfterCoroutineSplit(*N, Shape, Clones, C, CG, AM, UR, FAM); 1936 1937 if (Shape.ABI == coro::ABI::Async && !Shape.CoroSuspends.empty()) { 1938 // We want the inliner to be run on the newly inserted functions. 1939 UR.CWorklist.insert(&C); 1940 } 1941 } 1942 1943 if (!PrepareFns.empty()) { 1944 for (auto *PrepareFn : PrepareFns) { 1945 replaceAllPrepares(PrepareFn, CG, C); 1946 } 1947 } 1948 1949 return PreservedAnalyses::none(); 1950 } 1951 1952 namespace { 1953 1954 // We present a coroutine to LLVM as an ordinary function with suspension 1955 // points marked up with intrinsics. We let the optimizer party on the coroutine 1956 // as a single function for as long as possible. Shortly before the coroutine is 1957 // eligible to be inlined into its callers, we split up the coroutine into parts 1958 // corresponding to initial, resume and destroy invocations of the coroutine, 1959 // add them to the current SCC and restart the IPO pipeline to optimize the 1960 // coroutine subfunctions we extracted before proceeding to the caller of the 1961 // coroutine. 1962 struct CoroSplitLegacy : public CallGraphSCCPass { 1963 static char ID; // Pass identification, replacement for typeid 1964 1965 CoroSplitLegacy(bool ReuseFrameSlot = false) 1966 : CallGraphSCCPass(ID), ReuseFrameSlot(ReuseFrameSlot) { 1967 initializeCoroSplitLegacyPass(*PassRegistry::getPassRegistry()); 1968 } 1969 1970 bool Run = false; 1971 bool ReuseFrameSlot; 1972 1973 // A coroutine is identified by the presence of coro.begin intrinsic, if 1974 // we don't have any, this pass has nothing to do. 1975 bool doInitialization(CallGraph &CG) override { 1976 Run = declaresCoroSplitIntrinsics(CG.getModule()); 1977 return CallGraphSCCPass::doInitialization(CG); 1978 } 1979 1980 bool runOnSCC(CallGraphSCC &SCC) override { 1981 if (!Run) 1982 return false; 1983 1984 // Check for uses of llvm.coro.prepare.retcon. 1985 SmallVector<Function *, 2> PrepareFns; 1986 auto &M = SCC.getCallGraph().getModule(); 1987 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.retcon"); 1988 addPrepareFunction(M, PrepareFns, "llvm.coro.prepare.async"); 1989 1990 // Find coroutines for processing. 1991 SmallVector<Function *, 4> Coroutines; 1992 for (CallGraphNode *CGN : SCC) 1993 if (auto *F = CGN->getFunction()) 1994 if (F->hasFnAttribute(CORO_PRESPLIT_ATTR)) 1995 Coroutines.push_back(F); 1996 1997 if (Coroutines.empty() && PrepareFns.empty()) 1998 return false; 1999 2000 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 2001 2002 if (Coroutines.empty()) { 2003 bool Changed = false; 2004 for (auto *PrepareFn : PrepareFns) 2005 Changed |= replaceAllPrepares(PrepareFn, CG); 2006 return Changed; 2007 } 2008 2009 createDevirtTriggerFunc(CG, SCC); 2010 2011 // Split all the coroutines. 2012 for (Function *F : Coroutines) { 2013 Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR); 2014 StringRef Value = Attr.getValueAsString(); 2015 LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName() 2016 << "' state: " << Value << "\n"); 2017 // Async lowering marks coroutines to trigger a restart of the pipeline 2018 // after it has split them. 2019 if (Value == ASYNC_RESTART_AFTER_SPLIT) { 2020 F->removeFnAttr(CORO_PRESPLIT_ATTR); 2021 continue; 2022 } 2023 if (Value == UNPREPARED_FOR_SPLIT) { 2024 prepareForSplit(*F, CG); 2025 continue; 2026 } 2027 F->removeFnAttr(CORO_PRESPLIT_ATTR); 2028 2029 SmallVector<Function *, 4> Clones; 2030 const coro::Shape Shape = splitCoroutine(*F, Clones, ReuseFrameSlot); 2031 updateCallGraphAfterCoroutineSplit(*F, Shape, Clones, CG, SCC); 2032 if (Shape.ABI == coro::ABI::Async) { 2033 // Restart SCC passes. 2034 // Mark function for CoroElide pass. It will devirtualize causing a 2035 // restart of the SCC pipeline. 2036 prepareForSplit(*F, CG, true /*MarkForAsyncRestart*/); 2037 } 2038 } 2039 2040 for (auto *PrepareFn : PrepareFns) 2041 replaceAllPrepares(PrepareFn, CG); 2042 2043 return true; 2044 } 2045 2046 void getAnalysisUsage(AnalysisUsage &AU) const override { 2047 CallGraphSCCPass::getAnalysisUsage(AU); 2048 } 2049 2050 StringRef getPassName() const override { return "Coroutine Splitting"; } 2051 }; 2052 2053 } // end anonymous namespace 2054 2055 char CoroSplitLegacy::ID = 0; 2056 2057 INITIALIZE_PASS_BEGIN( 2058 CoroSplitLegacy, "coro-split", 2059 "Split coroutine into a set of functions driving its state machine", false, 2060 false) 2061 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 2062 INITIALIZE_PASS_END( 2063 CoroSplitLegacy, "coro-split", 2064 "Split coroutine into a set of functions driving its state machine", false, 2065 false) 2066 2067 Pass *llvm::createCoroSplitLegacyPass(bool ReuseFrameSlot) { 2068 return new CoroSplitLegacy(ReuseFrameSlot); 2069 } 2070