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