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