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, coro::Shape::SwitchFieldIndex::Index, "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, coro::Shape::SwitchFieldIndex::Index, "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   Entry->setName("entry" + Suffix);
571   Entry->moveBefore(&NewF->getEntryBlock());
572   Entry->getTerminator()->eraseFromParent();
573 
574   // Clear all predecessors of the new entry block.  There should be
575   // exactly one predecessor, which we created when splitting out
576   // AllocaSpillBlock to begin with.
577   assert(Entry->hasOneUse());
578   auto BranchToEntry = cast<BranchInst>(Entry->user_back());
579   assert(BranchToEntry->isUnconditional());
580   Builder.SetInsertPoint(BranchToEntry);
581   Builder.CreateUnreachable();
582   BranchToEntry->eraseFromParent();
583 
584   // TODO: move any allocas into Entry that weren't moved into the frame.
585   // (Currently we move all allocas into the frame.)
586 
587   // Branch from the entry to the appropriate place.
588   Builder.SetInsertPoint(Entry);
589   switch (Shape.ABI) {
590   case coro::ABI::Switch: {
591     // In switch-lowering, we built a resume-entry block in the original
592     // function.  Make the entry block branch to this.
593     auto *SwitchBB =
594       cast<BasicBlock>(VMap[Shape.SwitchLowering.ResumeEntryBlock]);
595     Builder.CreateBr(SwitchBB);
596     break;
597   }
598 
599   case coro::ABI::Retcon:
600   case coro::ABI::RetconOnce: {
601     // In continuation ABIs, we want to branch to immediately after the
602     // active suspend point.  Earlier phases will have put the suspend in its
603     // own basic block, so just thread our jump directly to its successor.
604     auto MappedCS = cast<CoroSuspendRetconInst>(VMap[ActiveSuspend]);
605     auto Branch = cast<BranchInst>(MappedCS->getNextNode());
606     assert(Branch->isUnconditional());
607     Builder.CreateBr(Branch->getSuccessor(0));
608     break;
609   }
610   }
611 }
612 
613 /// Derive the value of the new frame pointer.
614 Value *CoroCloner::deriveNewFramePointer() {
615   // Builder should be inserting to the front of the new entry block.
616 
617   switch (Shape.ABI) {
618   // In switch-lowering, the argument is the frame pointer.
619   case coro::ABI::Switch:
620     return &*NewF->arg_begin();
621 
622   // In continuation-lowering, the argument is the opaque storage.
623   case coro::ABI::Retcon:
624   case coro::ABI::RetconOnce: {
625     Argument *NewStorage = &*NewF->arg_begin();
626     auto FramePtrTy = Shape.FrameTy->getPointerTo();
627 
628     // If the storage is inline, just bitcast to the storage to the frame type.
629     if (Shape.RetconLowering.IsFrameInlineInStorage)
630       return Builder.CreateBitCast(NewStorage, FramePtrTy);
631 
632     // Otherwise, load the real frame from the opaque storage.
633     auto FramePtrPtr =
634       Builder.CreateBitCast(NewStorage, FramePtrTy->getPointerTo());
635     return Builder.CreateLoad(FramePtrTy, FramePtrPtr);
636   }
637   }
638   llvm_unreachable("bad ABI");
639 }
640 
641 /// Clone the body of the original function into a resume function of
642 /// some sort.
643 void CoroCloner::create() {
644   // Create the new function if we don't already have one.
645   if (!NewF) {
646     NewF = createCloneDeclaration(OrigF, Shape, Suffix,
647                                   OrigF.getParent()->end());
648   }
649 
650   // Replace all args with undefs. The buildCoroutineFrame algorithm already
651   // rewritten access to the args that occurs after suspend points with loads
652   // and stores to/from the coroutine frame.
653   for (Argument &A : OrigF.args())
654     VMap[&A] = UndefValue::get(A.getType());
655 
656   SmallVector<ReturnInst *, 4> Returns;
657 
658   // Ignore attempts to change certain attributes of the function.
659   // TODO: maybe there should be a way to suppress this during cloning?
660   auto savedVisibility = NewF->getVisibility();
661   auto savedUnnamedAddr = NewF->getUnnamedAddr();
662   auto savedDLLStorageClass = NewF->getDLLStorageClass();
663 
664   // NewF's linkage (which CloneFunctionInto does *not* change) might not
665   // be compatible with the visibility of OrigF (which it *does* change),
666   // so protect against that.
667   auto savedLinkage = NewF->getLinkage();
668   NewF->setLinkage(llvm::GlobalValue::ExternalLinkage);
669 
670   CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns);
671 
672   NewF->setLinkage(savedLinkage);
673   NewF->setVisibility(savedVisibility);
674   NewF->setUnnamedAddr(savedUnnamedAddr);
675   NewF->setDLLStorageClass(savedDLLStorageClass);
676 
677   auto &Context = NewF->getContext();
678 
679   // Replace the attributes of the new function:
680   auto OrigAttrs = NewF->getAttributes();
681   auto NewAttrs = AttributeList();
682 
683   switch (Shape.ABI) {
684   case coro::ABI::Switch:
685     // Bootstrap attributes by copying function attributes from the
686     // original function.  This should include optimization settings and so on.
687     NewAttrs = NewAttrs.addAttributes(Context, AttributeList::FunctionIndex,
688                                       OrigAttrs.getFnAttributes());
689     break;
690 
691   case coro::ABI::Retcon:
692   case coro::ABI::RetconOnce:
693     // If we have a continuation prototype, just use its attributes,
694     // full-stop.
695     NewAttrs = Shape.RetconLowering.ResumePrototype->getAttributes();
696     break;
697   }
698 
699   // Make the frame parameter nonnull and noalias.
700   NewAttrs = NewAttrs.addParamAttribute(Context, 0, Attribute::NonNull);
701   NewAttrs = NewAttrs.addParamAttribute(Context, 0, Attribute::NoAlias);
702 
703   switch (Shape.ABI) {
704   // In these ABIs, the cloned functions always return 'void', and the
705   // existing return sites are meaningless.  Note that for unique
706   // continuations, this includes the returns associated with suspends;
707   // this is fine because we can't suspend twice.
708   case coro::ABI::Switch:
709   case coro::ABI::RetconOnce:
710     // Remove old returns.
711     for (ReturnInst *Return : Returns)
712       changeToUnreachable(Return, /*UseLLVMTrap=*/false);
713     break;
714 
715   // With multi-suspend continuations, we'll already have eliminated the
716   // original returns and inserted returns before all the suspend points,
717   // so we want to leave any returns in place.
718   case coro::ABI::Retcon:
719     break;
720   }
721 
722   NewF->setAttributes(NewAttrs);
723   NewF->setCallingConv(Shape.getResumeFunctionCC());
724 
725   // Set up the new entry block.
726   replaceEntryBlock();
727 
728   Builder.SetInsertPoint(&NewF->getEntryBlock().front());
729   NewFramePtr = deriveNewFramePointer();
730 
731   // Remap frame pointer.
732   Value *OldFramePtr = VMap[Shape.FramePtr];
733   NewFramePtr->takeName(OldFramePtr);
734   OldFramePtr->replaceAllUsesWith(NewFramePtr);
735 
736   // Remap vFrame pointer.
737   auto *NewVFrame = Builder.CreateBitCast(
738       NewFramePtr, Type::getInt8PtrTy(Builder.getContext()), "vFrame");
739   Value *OldVFrame = cast<Value>(VMap[Shape.CoroBegin]);
740   OldVFrame->replaceAllUsesWith(NewVFrame);
741 
742   switch (Shape.ABI) {
743   case coro::ABI::Switch:
744     // Rewrite final suspend handling as it is not done via switch (allows to
745     // remove final case from the switch, since it is undefined behavior to
746     // resume the coroutine suspended at the final suspend point.
747     if (Shape.SwitchLowering.HasFinalSuspend)
748       handleFinalSuspend();
749     break;
750 
751   case coro::ABI::Retcon:
752   case coro::ABI::RetconOnce:
753     // Replace uses of the active suspend with the corresponding
754     // continuation-function arguments.
755     assert(ActiveSuspend != nullptr &&
756            "no active suspend when lowering a continuation-style coroutine");
757     replaceRetconSuspendUses();
758     break;
759   }
760 
761   // Handle suspends.
762   replaceCoroSuspends();
763 
764   // Handle swifterror.
765   replaceSwiftErrorOps();
766 
767   // Remove coro.end intrinsics.
768   replaceCoroEnds();
769 
770   // Eliminate coro.free from the clones, replacing it with 'null' in cleanup,
771   // to suppress deallocation code.
772   if (Shape.ABI == coro::ABI::Switch)
773     coro::replaceCoroFree(cast<CoroIdInst>(VMap[Shape.CoroBegin->getId()]),
774                           /*Elide=*/ FKind == CoroCloner::Kind::SwitchCleanup);
775 }
776 
777 // Create a resume clone by cloning the body of the original function, setting
778 // new entry block and replacing coro.suspend an appropriate value to force
779 // resume or cleanup pass for every suspend point.
780 static Function *createClone(Function &F, const Twine &Suffix,
781                              coro::Shape &Shape, CoroCloner::Kind FKind) {
782   CoroCloner Cloner(F, Suffix, Shape, FKind);
783   Cloner.create();
784   return Cloner.getFunction();
785 }
786 
787 /// Remove calls to llvm.coro.end in the original function.
788 static void removeCoroEnds(const coro::Shape &Shape, CallGraph *CG) {
789   for (auto End : Shape.CoroEnds) {
790     replaceCoroEnd(End, Shape, Shape.FramePtr, /*in resume*/ false, CG);
791   }
792 }
793 
794 static void replaceFrameSize(coro::Shape &Shape) {
795   if (Shape.CoroSizes.empty())
796     return;
797 
798   // In the same function all coro.sizes should have the same result type.
799   auto *SizeIntrin = Shape.CoroSizes.back();
800   Module *M = SizeIntrin->getModule();
801   const DataLayout &DL = M->getDataLayout();
802   auto Size = DL.getTypeAllocSize(Shape.FrameTy);
803   auto *SizeConstant = ConstantInt::get(SizeIntrin->getType(), Size);
804 
805   for (CoroSizeInst *CS : Shape.CoroSizes) {
806     CS->replaceAllUsesWith(SizeConstant);
807     CS->eraseFromParent();
808   }
809 }
810 
811 // Create a global constant array containing pointers to functions provided and
812 // set Info parameter of CoroBegin to point at this constant. Example:
813 //
814 //   @f.resumers = internal constant [2 x void(%f.frame*)*]
815 //                    [void(%f.frame*)* @f.resume, void(%f.frame*)* @f.destroy]
816 //   define void @f() {
817 //     ...
818 //     call i8* @llvm.coro.begin(i8* null, i32 0, i8* null,
819 //                    i8* bitcast([2 x void(%f.frame*)*] * @f.resumers to i8*))
820 //
821 // Assumes that all the functions have the same signature.
822 static void setCoroInfo(Function &F, coro::Shape &Shape,
823                         ArrayRef<Function *> Fns) {
824   // This only works under the switch-lowering ABI because coro elision
825   // only works on the switch-lowering ABI.
826   assert(Shape.ABI == coro::ABI::Switch);
827 
828   SmallVector<Constant *, 4> Args(Fns.begin(), Fns.end());
829   assert(!Args.empty());
830   Function *Part = *Fns.begin();
831   Module *M = Part->getParent();
832   auto *ArrTy = ArrayType::get(Part->getType(), Args.size());
833 
834   auto *ConstVal = ConstantArray::get(ArrTy, Args);
835   auto *GV = new GlobalVariable(*M, ConstVal->getType(), /*isConstant=*/true,
836                                 GlobalVariable::PrivateLinkage, ConstVal,
837                                 F.getName() + Twine(".resumers"));
838 
839   // Update coro.begin instruction to refer to this constant.
840   LLVMContext &C = F.getContext();
841   auto *BC = ConstantExpr::getPointerCast(GV, Type::getInt8PtrTy(C));
842   Shape.getSwitchCoroId()->setInfo(BC);
843 }
844 
845 // Store addresses of Resume/Destroy/Cleanup functions in the coroutine frame.
846 static void updateCoroFrame(coro::Shape &Shape, Function *ResumeFn,
847                             Function *DestroyFn, Function *CleanupFn) {
848   assert(Shape.ABI == coro::ABI::Switch);
849 
850   IRBuilder<> Builder(Shape.FramePtr->getNextNode());
851   auto *ResumeAddr = Builder.CreateStructGEP(
852       Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Resume,
853       "resume.addr");
854   Builder.CreateStore(ResumeFn, ResumeAddr);
855 
856   Value *DestroyOrCleanupFn = DestroyFn;
857 
858   CoroIdInst *CoroId = Shape.getSwitchCoroId();
859   if (CoroAllocInst *CA = CoroId->getCoroAlloc()) {
860     // If there is a CoroAlloc and it returns false (meaning we elide the
861     // allocation, use CleanupFn instead of DestroyFn).
862     DestroyOrCleanupFn = Builder.CreateSelect(CA, DestroyFn, CleanupFn);
863   }
864 
865   auto *DestroyAddr = Builder.CreateStructGEP(
866       Shape.FrameTy, Shape.FramePtr, coro::Shape::SwitchFieldIndex::Destroy,
867       "destroy.addr");
868   Builder.CreateStore(DestroyOrCleanupFn, DestroyAddr);
869 }
870 
871 static void postSplitCleanup(Function &F) {
872   removeUnreachableBlocks(F);
873 
874   // For now, we do a mandatory verification step because we don't
875   // entirely trust this pass.  Note that we don't want to add a verifier
876   // pass to FPM below because it will also verify all the global data.
877   verifyFunction(F);
878 
879   legacy::FunctionPassManager FPM(F.getParent());
880 
881   FPM.add(createSCCPPass());
882   FPM.add(createCFGSimplificationPass());
883   FPM.add(createEarlyCSEPass());
884   FPM.add(createCFGSimplificationPass());
885 
886   FPM.doInitialization();
887   FPM.run(F);
888   FPM.doFinalization();
889 }
890 
891 // Assuming we arrived at the block NewBlock from Prev instruction, store
892 // PHI's incoming values in the ResolvedValues map.
893 static void
894 scanPHIsAndUpdateValueMap(Instruction *Prev, BasicBlock *NewBlock,
895                           DenseMap<Value *, Value *> &ResolvedValues) {
896   auto *PrevBB = Prev->getParent();
897   for (PHINode &PN : NewBlock->phis()) {
898     auto V = PN.getIncomingValueForBlock(PrevBB);
899     // See if we already resolved it.
900     auto VI = ResolvedValues.find(V);
901     if (VI != ResolvedValues.end())
902       V = VI->second;
903     // Remember the value.
904     ResolvedValues[&PN] = V;
905   }
906 }
907 
908 // Replace a sequence of branches leading to a ret, with a clone of a ret
909 // instruction. Suspend instruction represented by a switch, track the PHI
910 // values and select the correct case successor when possible.
911 static bool simplifyTerminatorLeadingToRet(Instruction *InitialInst) {
912   DenseMap<Value *, Value *> ResolvedValues;
913   BasicBlock *UnconditionalSucc = nullptr;
914 
915   Instruction *I = InitialInst;
916   while (I->isTerminator()) {
917     if (isa<ReturnInst>(I)) {
918       if (I != InitialInst) {
919         // If InitialInst is an unconditional branch,
920         // remove PHI values that come from basic block of InitialInst
921         if (UnconditionalSucc)
922           for (PHINode &PN : UnconditionalSucc->phis()) {
923             int idx = PN.getBasicBlockIndex(InitialInst->getParent());
924             if (idx != -1)
925               PN.removeIncomingValue(idx);
926           }
927         ReplaceInstWithInst(InitialInst, I->clone());
928       }
929       return true;
930     }
931     if (auto *BR = dyn_cast<BranchInst>(I)) {
932       if (BR->isUnconditional()) {
933         BasicBlock *BB = BR->getSuccessor(0);
934         if (I == InitialInst)
935           UnconditionalSucc = BB;
936         scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
937         I = BB->getFirstNonPHIOrDbgOrLifetime();
938         continue;
939       }
940     } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
941       Value *V = SI->getCondition();
942       auto it = ResolvedValues.find(V);
943       if (it != ResolvedValues.end())
944         V = it->second;
945       if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
946         BasicBlock *BB = SI->findCaseValue(Cond)->getCaseSuccessor();
947         scanPHIsAndUpdateValueMap(I, BB, ResolvedValues);
948         I = BB->getFirstNonPHIOrDbgOrLifetime();
949         continue;
950       }
951     }
952     return false;
953   }
954   return false;
955 }
956 
957 // Add musttail to any resume instructions that is immediately followed by a
958 // suspend (i.e. ret). We do this even in -O0 to support guaranteed tail call
959 // for symmetrical coroutine control transfer (C++ Coroutines TS extension).
960 // This transformation is done only in the resume part of the coroutine that has
961 // identical signature and calling convention as the coro.resume call.
962 static void addMustTailToCoroResumes(Function &F) {
963   bool changed = false;
964 
965   // Collect potential resume instructions.
966   SmallVector<CallInst *, 4> Resumes;
967   for (auto &I : instructions(F))
968     if (auto *Call = dyn_cast<CallInst>(&I))
969       if (auto *CalledValue = Call->getCalledValue())
970         // CoroEarly pass replaced coro resumes with indirect calls to an
971         // address return by CoroSubFnInst intrinsic. See if it is one of those.
972         if (isa<CoroSubFnInst>(CalledValue->stripPointerCasts()))
973           Resumes.push_back(Call);
974 
975   // Set musttail on those that are followed by a ret instruction.
976   for (CallInst *Call : Resumes)
977     if (simplifyTerminatorLeadingToRet(Call->getNextNode())) {
978       Call->setTailCallKind(CallInst::TCK_MustTail);
979       changed = true;
980     }
981 
982   if (changed)
983     removeUnreachableBlocks(F);
984 }
985 
986 // Coroutine has no suspend points. Remove heap allocation for the coroutine
987 // frame if possible.
988 static void handleNoSuspendCoroutine(coro::Shape &Shape) {
989   auto *CoroBegin = Shape.CoroBegin;
990   auto *CoroId = CoroBegin->getId();
991   auto *AllocInst = CoroId->getCoroAlloc();
992   switch (Shape.ABI) {
993   case coro::ABI::Switch: {
994     auto SwitchId = cast<CoroIdInst>(CoroId);
995     coro::replaceCoroFree(SwitchId, /*Elide=*/AllocInst != nullptr);
996     if (AllocInst) {
997       IRBuilder<> Builder(AllocInst);
998       // FIXME: Need to handle overaligned members.
999       auto *Frame = Builder.CreateAlloca(Shape.FrameTy);
1000       auto *VFrame = Builder.CreateBitCast(Frame, Builder.getInt8PtrTy());
1001       AllocInst->replaceAllUsesWith(Builder.getFalse());
1002       AllocInst->eraseFromParent();
1003       CoroBegin->replaceAllUsesWith(VFrame);
1004     } else {
1005       CoroBegin->replaceAllUsesWith(CoroBegin->getMem());
1006     }
1007     break;
1008   }
1009 
1010   case coro::ABI::Retcon:
1011   case coro::ABI::RetconOnce:
1012     CoroBegin->replaceAllUsesWith(UndefValue::get(CoroBegin->getType()));
1013     break;
1014   }
1015 
1016   CoroBegin->eraseFromParent();
1017 }
1018 
1019 // SimplifySuspendPoint needs to check that there is no calls between
1020 // coro_save and coro_suspend, since any of the calls may potentially resume
1021 // the coroutine and if that is the case we cannot eliminate the suspend point.
1022 static bool hasCallsInBlockBetween(Instruction *From, Instruction *To) {
1023   for (Instruction *I = From; I != To; I = I->getNextNode()) {
1024     // Assume that no intrinsic can resume the coroutine.
1025     if (isa<IntrinsicInst>(I))
1026       continue;
1027 
1028     if (CallSite(I))
1029       return true;
1030   }
1031   return false;
1032 }
1033 
1034 static bool hasCallsInBlocksBetween(BasicBlock *SaveBB, BasicBlock *ResDesBB) {
1035   SmallPtrSet<BasicBlock *, 8> Set;
1036   SmallVector<BasicBlock *, 8> Worklist;
1037 
1038   Set.insert(SaveBB);
1039   Worklist.push_back(ResDesBB);
1040 
1041   // Accumulate all blocks between SaveBB and ResDesBB. Because CoroSaveIntr
1042   // returns a token consumed by suspend instruction, all blocks in between
1043   // will have to eventually hit SaveBB when going backwards from ResDesBB.
1044   while (!Worklist.empty()) {
1045     auto *BB = Worklist.pop_back_val();
1046     Set.insert(BB);
1047     for (auto *Pred : predecessors(BB))
1048       if (Set.count(Pred) == 0)
1049         Worklist.push_back(Pred);
1050   }
1051 
1052   // SaveBB and ResDesBB are checked separately in hasCallsBetween.
1053   Set.erase(SaveBB);
1054   Set.erase(ResDesBB);
1055 
1056   for (auto *BB : Set)
1057     if (hasCallsInBlockBetween(BB->getFirstNonPHI(), nullptr))
1058       return true;
1059 
1060   return false;
1061 }
1062 
1063 static bool hasCallsBetween(Instruction *Save, Instruction *ResumeOrDestroy) {
1064   auto *SaveBB = Save->getParent();
1065   auto *ResumeOrDestroyBB = ResumeOrDestroy->getParent();
1066 
1067   if (SaveBB == ResumeOrDestroyBB)
1068     return hasCallsInBlockBetween(Save->getNextNode(), ResumeOrDestroy);
1069 
1070   // Any calls from Save to the end of the block?
1071   if (hasCallsInBlockBetween(Save->getNextNode(), nullptr))
1072     return true;
1073 
1074   // Any calls from begging of the block up to ResumeOrDestroy?
1075   if (hasCallsInBlockBetween(ResumeOrDestroyBB->getFirstNonPHI(),
1076                              ResumeOrDestroy))
1077     return true;
1078 
1079   // Any calls in all of the blocks between SaveBB and ResumeOrDestroyBB?
1080   if (hasCallsInBlocksBetween(SaveBB, ResumeOrDestroyBB))
1081     return true;
1082 
1083   return false;
1084 }
1085 
1086 // If a SuspendIntrin is preceded by Resume or Destroy, we can eliminate the
1087 // suspend point and replace it with nornal control flow.
1088 static bool simplifySuspendPoint(CoroSuspendInst *Suspend,
1089                                  CoroBeginInst *CoroBegin) {
1090   Instruction *Prev = Suspend->getPrevNode();
1091   if (!Prev) {
1092     auto *Pred = Suspend->getParent()->getSinglePredecessor();
1093     if (!Pred)
1094       return false;
1095     Prev = Pred->getTerminator();
1096   }
1097 
1098   CallSite CS{Prev};
1099   if (!CS)
1100     return false;
1101 
1102   auto *CallInstr = CS.getInstruction();
1103 
1104   auto *Callee = CS.getCalledValue()->stripPointerCasts();
1105 
1106   // See if the callsite is for resumption or destruction of the coroutine.
1107   auto *SubFn = dyn_cast<CoroSubFnInst>(Callee);
1108   if (!SubFn)
1109     return false;
1110 
1111   // Does not refer to the current coroutine, we cannot do anything with it.
1112   if (SubFn->getFrame() != CoroBegin)
1113     return false;
1114 
1115   // See if the transformation is safe. Specifically, see if there are any
1116   // calls in between Save and CallInstr. They can potenitally resume the
1117   // coroutine rendering this optimization unsafe.
1118   auto *Save = Suspend->getCoroSave();
1119   if (hasCallsBetween(Save, CallInstr))
1120     return false;
1121 
1122   // Replace llvm.coro.suspend with the value that results in resumption over
1123   // the resume or cleanup path.
1124   Suspend->replaceAllUsesWith(SubFn->getRawIndex());
1125   Suspend->eraseFromParent();
1126   Save->eraseFromParent();
1127 
1128   // No longer need a call to coro.resume or coro.destroy.
1129   if (auto *Invoke = dyn_cast<InvokeInst>(CallInstr)) {
1130     BranchInst::Create(Invoke->getNormalDest(), Invoke);
1131   }
1132 
1133   // Grab the CalledValue from CS before erasing the CallInstr.
1134   auto *CalledValue = CS.getCalledValue();
1135   CallInstr->eraseFromParent();
1136 
1137   // If no more users remove it. Usually it is a bitcast of SubFn.
1138   if (CalledValue != SubFn && CalledValue->user_empty())
1139     if (auto *I = dyn_cast<Instruction>(CalledValue))
1140       I->eraseFromParent();
1141 
1142   // Now we are good to remove SubFn.
1143   if (SubFn->user_empty())
1144     SubFn->eraseFromParent();
1145 
1146   return true;
1147 }
1148 
1149 // Remove suspend points that are simplified.
1150 static void simplifySuspendPoints(coro::Shape &Shape) {
1151   // Currently, the only simplification we do is switch-lowering-specific.
1152   if (Shape.ABI != coro::ABI::Switch)
1153     return;
1154 
1155   auto &S = Shape.CoroSuspends;
1156   size_t I = 0, N = S.size();
1157   if (N == 0)
1158     return;
1159   while (true) {
1160     auto SI = cast<CoroSuspendInst>(S[I]);
1161     // Leave final.suspend to handleFinalSuspend since it is undefined behavior
1162     // to resume a coroutine suspended at the final suspend point.
1163     if (!SI->isFinal() && simplifySuspendPoint(SI, Shape.CoroBegin)) {
1164       if (--N == I)
1165         break;
1166       std::swap(S[I], S[N]);
1167       continue;
1168     }
1169     if (++I == N)
1170       break;
1171   }
1172   S.resize(N);
1173 }
1174 
1175 static void splitSwitchCoroutine(Function &F, coro::Shape &Shape,
1176                                  SmallVectorImpl<Function *> &Clones) {
1177   assert(Shape.ABI == coro::ABI::Switch);
1178 
1179   createResumeEntryBlock(F, Shape);
1180   auto ResumeClone = createClone(F, ".resume", Shape,
1181                                  CoroCloner::Kind::SwitchResume);
1182   auto DestroyClone = createClone(F, ".destroy", Shape,
1183                                   CoroCloner::Kind::SwitchUnwind);
1184   auto CleanupClone = createClone(F, ".cleanup", Shape,
1185                                   CoroCloner::Kind::SwitchCleanup);
1186 
1187   postSplitCleanup(*ResumeClone);
1188   postSplitCleanup(*DestroyClone);
1189   postSplitCleanup(*CleanupClone);
1190 
1191   addMustTailToCoroResumes(*ResumeClone);
1192 
1193   // Store addresses resume/destroy/cleanup functions in the coroutine frame.
1194   updateCoroFrame(Shape, ResumeClone, DestroyClone, CleanupClone);
1195 
1196   assert(Clones.empty());
1197   Clones.push_back(ResumeClone);
1198   Clones.push_back(DestroyClone);
1199   Clones.push_back(CleanupClone);
1200 
1201   // Create a constant array referring to resume/destroy/clone functions pointed
1202   // by the last argument of @llvm.coro.info, so that CoroElide pass can
1203   // determined correct function to call.
1204   setCoroInfo(F, Shape, Clones);
1205 }
1206 
1207 static void splitRetconCoroutine(Function &F, coro::Shape &Shape,
1208                                  SmallVectorImpl<Function *> &Clones) {
1209   assert(Shape.ABI == coro::ABI::Retcon ||
1210          Shape.ABI == coro::ABI::RetconOnce);
1211   assert(Clones.empty());
1212 
1213   // Reset various things that the optimizer might have decided it
1214   // "knows" about the coroutine function due to not seeing a return.
1215   F.removeFnAttr(Attribute::NoReturn);
1216   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NoAlias);
1217   F.removeAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1218 
1219   // Allocate the frame.
1220   auto *Id = cast<AnyCoroIdRetconInst>(Shape.CoroBegin->getId());
1221   Value *RawFramePtr;
1222   if (Shape.RetconLowering.IsFrameInlineInStorage) {
1223     RawFramePtr = Id->getStorage();
1224   } else {
1225     IRBuilder<> Builder(Id);
1226 
1227     // Determine the size of the frame.
1228     const DataLayout &DL = F.getParent()->getDataLayout();
1229     auto Size = DL.getTypeAllocSize(Shape.FrameTy);
1230 
1231     // Allocate.  We don't need to update the call graph node because we're
1232     // going to recompute it from scratch after splitting.
1233     RawFramePtr = Shape.emitAlloc(Builder, Builder.getInt64(Size), nullptr);
1234     RawFramePtr =
1235       Builder.CreateBitCast(RawFramePtr, Shape.CoroBegin->getType());
1236 
1237     // Stash the allocated frame pointer in the continuation storage.
1238     auto Dest = Builder.CreateBitCast(Id->getStorage(),
1239                                       RawFramePtr->getType()->getPointerTo());
1240     Builder.CreateStore(RawFramePtr, Dest);
1241   }
1242 
1243   // Map all uses of llvm.coro.begin to the allocated frame pointer.
1244   {
1245     // Make sure we don't invalidate Shape.FramePtr.
1246     TrackingVH<Instruction> Handle(Shape.FramePtr);
1247     Shape.CoroBegin->replaceAllUsesWith(RawFramePtr);
1248     Shape.FramePtr = Handle.getValPtr();
1249   }
1250 
1251   // Create a unique return block.
1252   BasicBlock *ReturnBB = nullptr;
1253   SmallVector<PHINode *, 4> ReturnPHIs;
1254 
1255   // Create all the functions in order after the main function.
1256   auto NextF = std::next(F.getIterator());
1257 
1258   // Create a continuation function for each of the suspend points.
1259   Clones.reserve(Shape.CoroSuspends.size());
1260   for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) {
1261     auto Suspend = cast<CoroSuspendRetconInst>(Shape.CoroSuspends[i]);
1262 
1263     // Create the clone declaration.
1264     auto Continuation =
1265       createCloneDeclaration(F, Shape, ".resume." + Twine(i), NextF);
1266     Clones.push_back(Continuation);
1267 
1268     // Insert a branch to the unified return block immediately before
1269     // the suspend point.
1270     auto SuspendBB = Suspend->getParent();
1271     auto NewSuspendBB = SuspendBB->splitBasicBlock(Suspend);
1272     auto Branch = cast<BranchInst>(SuspendBB->getTerminator());
1273 
1274     // Create the unified return block.
1275     if (!ReturnBB) {
1276       // Place it before the first suspend.
1277       ReturnBB = BasicBlock::Create(F.getContext(), "coro.return", &F,
1278                                     NewSuspendBB);
1279       Shape.RetconLowering.ReturnBlock = ReturnBB;
1280 
1281       IRBuilder<> Builder(ReturnBB);
1282 
1283       // Create PHIs for all the return values.
1284       assert(ReturnPHIs.empty());
1285 
1286       // First, the continuation.
1287       ReturnPHIs.push_back(Builder.CreatePHI(Continuation->getType(),
1288                                              Shape.CoroSuspends.size()));
1289 
1290       // Next, all the directly-yielded values.
1291       for (auto ResultTy : Shape.getRetconResultTypes())
1292         ReturnPHIs.push_back(Builder.CreatePHI(ResultTy,
1293                                                Shape.CoroSuspends.size()));
1294 
1295       // Build the return value.
1296       auto RetTy = F.getReturnType();
1297 
1298       // Cast the continuation value if necessary.
1299       // We can't rely on the types matching up because that type would
1300       // have to be infinite.
1301       auto CastedContinuationTy =
1302         (ReturnPHIs.size() == 1 ? RetTy : RetTy->getStructElementType(0));
1303       auto *CastedContinuation =
1304         Builder.CreateBitCast(ReturnPHIs[0], CastedContinuationTy);
1305 
1306       Value *RetV;
1307       if (ReturnPHIs.size() == 1) {
1308         RetV = CastedContinuation;
1309       } else {
1310         RetV = UndefValue::get(RetTy);
1311         RetV = Builder.CreateInsertValue(RetV, CastedContinuation, 0);
1312         for (size_t I = 1, E = ReturnPHIs.size(); I != E; ++I)
1313           RetV = Builder.CreateInsertValue(RetV, ReturnPHIs[I], I);
1314       }
1315 
1316       Builder.CreateRet(RetV);
1317     }
1318 
1319     // Branch to the return block.
1320     Branch->setSuccessor(0, ReturnBB);
1321     ReturnPHIs[0]->addIncoming(Continuation, SuspendBB);
1322     size_t NextPHIIndex = 1;
1323     for (auto &VUse : Suspend->value_operands())
1324       ReturnPHIs[NextPHIIndex++]->addIncoming(&*VUse, SuspendBB);
1325     assert(NextPHIIndex == ReturnPHIs.size());
1326   }
1327 
1328   assert(Clones.size() == Shape.CoroSuspends.size());
1329   for (size_t i = 0, e = Shape.CoroSuspends.size(); i != e; ++i) {
1330     auto Suspend = Shape.CoroSuspends[i];
1331     auto Clone = Clones[i];
1332 
1333     CoroCloner(F, "resume." + Twine(i), Shape, Clone, Suspend).create();
1334   }
1335 }
1336 
1337 namespace {
1338   class PrettyStackTraceFunction : public PrettyStackTraceEntry {
1339     Function &F;
1340   public:
1341     PrettyStackTraceFunction(Function &F) : F(F) {}
1342     void print(raw_ostream &OS) const override {
1343       OS << "While splitting coroutine ";
1344       F.printAsOperand(OS, /*print type*/ false, F.getParent());
1345       OS << "\n";
1346     }
1347   };
1348 }
1349 
1350 static coro::Shape splitCoroutine(Function &F,
1351                                   SmallVectorImpl<Function *> &Clones) {
1352   PrettyStackTraceFunction prettyStackTrace(F);
1353 
1354   // The suspend-crossing algorithm in buildCoroutineFrame get tripped
1355   // up by uses in unreachable blocks, so remove them as a first pass.
1356   removeUnreachableBlocks(F);
1357 
1358   coro::Shape Shape(F);
1359   if (!Shape.CoroBegin)
1360     return Shape;
1361 
1362   simplifySuspendPoints(Shape);
1363   buildCoroutineFrame(F, Shape);
1364   replaceFrameSize(Shape);
1365 
1366   // If there are no suspend points, no split required, just remove
1367   // the allocation and deallocation blocks, they are not needed.
1368   if (Shape.CoroSuspends.empty()) {
1369     handleNoSuspendCoroutine(Shape);
1370   } else {
1371     switch (Shape.ABI) {
1372     case coro::ABI::Switch:
1373       splitSwitchCoroutine(F, Shape, Clones);
1374       break;
1375     case coro::ABI::Retcon:
1376     case coro::ABI::RetconOnce:
1377       splitRetconCoroutine(F, Shape, Clones);
1378       break;
1379     }
1380   }
1381 
1382   // Replace all the swifterror operations in the original function.
1383   // This invalidates SwiftErrorOps in the Shape.
1384   replaceSwiftErrorOps(F, Shape, nullptr);
1385 
1386   return Shape;
1387 }
1388 
1389 static void
1390 updateCallGraphAfterCoroutineSplit(Function &F, const coro::Shape &Shape,
1391                                    const SmallVectorImpl<Function *> &Clones,
1392                                    CallGraph &CG, CallGraphSCC &SCC) {
1393   if (!Shape.CoroBegin)
1394     return;
1395 
1396   removeCoroEnds(Shape, &CG);
1397   postSplitCleanup(F);
1398 
1399   // Update call graph and add the functions we created to the SCC.
1400   coro::updateCallGraph(F, Clones, CG, SCC);
1401 }
1402 
1403 static void updateCallGraphAfterCoroutineSplit(
1404     LazyCallGraph::Node &N, const coro::Shape &Shape,
1405     const SmallVectorImpl<Function *> &Clones, LazyCallGraph::SCC &C,
1406     LazyCallGraph &CG, CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) {
1407   if (!Shape.CoroBegin)
1408     return;
1409 
1410   for (llvm::CoroEndInst *End : Shape.CoroEnds) {
1411     auto &Context = End->getContext();
1412     End->replaceAllUsesWith(ConstantInt::getFalse(Context));
1413     End->eraseFromParent();
1414   }
1415 
1416   postSplitCleanup(N.getFunction());
1417 
1418   // To insert the newly created coroutine funclets 'f.resume', 'f.destroy', and
1419   // 'f.cleanup' into the same SCC as the coroutine 'f' they were outlined from,
1420   // we make use of the CallGraphUpdater class, which can modify the internal
1421   // state of the LazyCallGraph.
1422   for (Function *Clone : Clones)
1423     CG.addNewFunctionIntoRefSCC(*Clone, C.getOuterRefSCC());
1424 
1425   // We've inserted instructions into coroutine 'f' that reference the three new
1426   // coroutine funclets. We must now update the call graph so that reference
1427   // edges between 'f' and its funclets are added to it. LazyCallGraph only
1428   // allows CGSCC passes to insert "trivial" reference edges. We've ensured
1429   // above, by inserting the funclets into the same SCC as the corutine, that
1430   // the edges are trivial.
1431   //
1432   // N.B.: If we didn't update the call graph here, a CGSCCToFunctionPassAdaptor
1433   // later in this CGSCC pass pipeline may be run, triggering a call graph
1434   // update of its own. Function passes run by the adaptor are not permitted to
1435   // add new edges of any kind to the graph, and the new edges inserted by this
1436   // pass would be misattributed to that unrelated function pass.
1437   updateCGAndAnalysisManagerForCGSCCPass(CG, C, N, AM, UR);
1438 }
1439 
1440 // When we see the coroutine the first time, we insert an indirect call to a
1441 // devirt trigger function and mark the coroutine that it is now ready for
1442 // split.
1443 static void prepareForSplit(Function &F, CallGraph &CG) {
1444   Module &M = *F.getParent();
1445   LLVMContext &Context = F.getContext();
1446 #ifndef NDEBUG
1447   Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN);
1448   assert(DevirtFn && "coro.devirt.trigger function not found");
1449 #endif
1450 
1451   F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT);
1452 
1453   // Insert an indirect call sequence that will be devirtualized by CoroElide
1454   // pass:
1455   //    %0 = call i8* @llvm.coro.subfn.addr(i8* null, i8 -1)
1456   //    %1 = bitcast i8* %0 to void(i8*)*
1457   //    call void %1(i8* null)
1458   coro::LowererBase Lowerer(M);
1459   Instruction *InsertPt = F.getEntryBlock().getTerminator();
1460   auto *Null = ConstantPointerNull::get(Type::getInt8PtrTy(Context));
1461   auto *DevirtFnAddr =
1462       Lowerer.makeSubFnCall(Null, CoroSubFnInst::RestartTrigger, InsertPt);
1463   FunctionType *FnTy = FunctionType::get(Type::getVoidTy(Context),
1464                                          {Type::getInt8PtrTy(Context)}, false);
1465   auto *IndirectCall = CallInst::Create(FnTy, DevirtFnAddr, Null, "", InsertPt);
1466 
1467   // Update CG graph with an indirect call we just added.
1468   CG[&F]->addCalledFunction(IndirectCall, CG.getCallsExternalNode());
1469 }
1470 
1471 // Make sure that there is a devirtualization trigger function that the
1472 // coro-split pass uses to force a restart of the CGSCC pipeline. If the devirt
1473 // trigger function is not found, we will create one and add it to the current
1474 // SCC.
1475 static void createDevirtTriggerFunc(CallGraph &CG, CallGraphSCC &SCC) {
1476   Module &M = CG.getModule();
1477   if (M.getFunction(CORO_DEVIRT_TRIGGER_FN))
1478     return;
1479 
1480   LLVMContext &C = M.getContext();
1481   auto *FnTy = FunctionType::get(Type::getVoidTy(C), Type::getInt8PtrTy(C),
1482                                  /*isVarArg=*/false);
1483   Function *DevirtFn =
1484       Function::Create(FnTy, GlobalValue::LinkageTypes::PrivateLinkage,
1485                        CORO_DEVIRT_TRIGGER_FN, &M);
1486   DevirtFn->addFnAttr(Attribute::AlwaysInline);
1487   auto *Entry = BasicBlock::Create(C, "entry", DevirtFn);
1488   ReturnInst::Create(C, Entry);
1489 
1490   auto *Node = CG.getOrInsertFunction(DevirtFn);
1491 
1492   SmallVector<CallGraphNode *, 8> Nodes(SCC.begin(), SCC.end());
1493   Nodes.push_back(Node);
1494   SCC.initialize(Nodes);
1495 }
1496 
1497 /// Replace a call to llvm.coro.prepare.retcon.
1498 static void replacePrepare(CallInst *Prepare, CallGraph &CG) {
1499   auto CastFn = Prepare->getArgOperand(0); // as an i8*
1500   auto Fn = CastFn->stripPointerCasts(); // as its original type
1501 
1502   // Find call graph nodes for the preparation.
1503   CallGraphNode *PrepareUserNode = nullptr, *FnNode = nullptr;
1504   if (auto ConcreteFn = dyn_cast<Function>(Fn)) {
1505     PrepareUserNode = CG[Prepare->getFunction()];
1506     FnNode = CG[ConcreteFn];
1507   }
1508 
1509   // Attempt to peephole this pattern:
1510   //    %0 = bitcast [[TYPE]] @some_function to i8*
1511   //    %1 = call @llvm.coro.prepare.retcon(i8* %0)
1512   //    %2 = bitcast %1 to [[TYPE]]
1513   // ==>
1514   //    %2 = @some_function
1515   for (auto UI = Prepare->use_begin(), UE = Prepare->use_end();
1516          UI != UE; ) {
1517     // Look for bitcasts back to the original function type.
1518     auto *Cast = dyn_cast<BitCastInst>((UI++)->getUser());
1519     if (!Cast || Cast->getType() != Fn->getType()) continue;
1520 
1521     // Check whether the replacement will introduce new direct calls.
1522     // If so, we'll need to update the call graph.
1523     if (PrepareUserNode) {
1524       for (auto &Use : Cast->uses()) {
1525         if (auto *CB = dyn_cast<CallBase>(Use.getUser())) {
1526           if (!CB->isCallee(&Use))
1527             continue;
1528           PrepareUserNode->removeCallEdgeFor(*CB);
1529           PrepareUserNode->addCalledFunction(CB, FnNode);
1530         }
1531       }
1532     }
1533 
1534     // Replace and remove the cast.
1535     Cast->replaceAllUsesWith(Fn);
1536     Cast->eraseFromParent();
1537   }
1538 
1539   // Replace any remaining uses with the function as an i8*.
1540   // This can never directly be a callee, so we don't need to update CG.
1541   Prepare->replaceAllUsesWith(CastFn);
1542   Prepare->eraseFromParent();
1543 
1544   // Kill dead bitcasts.
1545   while (auto *Cast = dyn_cast<BitCastInst>(CastFn)) {
1546     if (!Cast->use_empty()) break;
1547     CastFn = Cast->getOperand(0);
1548     Cast->eraseFromParent();
1549   }
1550 }
1551 
1552 /// Remove calls to llvm.coro.prepare.retcon, a barrier meant to prevent
1553 /// IPO from operating on calls to a retcon coroutine before it's been
1554 /// split.  This is only safe to do after we've split all retcon
1555 /// coroutines in the module.  We can do that this in this pass because
1556 /// this pass does promise to split all retcon coroutines (as opposed to
1557 /// switch coroutines, which are lowered in multiple stages).
1558 static bool replaceAllPrepares(Function *PrepareFn, CallGraph &CG) {
1559   bool Changed = false;
1560   for (auto PI = PrepareFn->use_begin(), PE = PrepareFn->use_end();
1561          PI != PE; ) {
1562     // Intrinsics can only be used in calls.
1563     auto *Prepare = cast<CallInst>((PI++)->getUser());
1564     replacePrepare(Prepare, CG);
1565     Changed = true;
1566   }
1567 
1568   return Changed;
1569 }
1570 
1571 static bool declaresCoroSplitIntrinsics(const Module &M) {
1572   return coro::declaresIntrinsics(
1573       M, {"llvm.coro.begin", "llvm.coro.prepare.retcon"});
1574 }
1575 
1576 PreservedAnalyses CoroSplitPass::run(LazyCallGraph::SCC &C,
1577                                      CGSCCAnalysisManager &AM,
1578                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
1579   // NB: One invariant of a valid LazyCallGraph::SCC is that it must contain a
1580   //     non-zero number of nodes, so we assume that here and grab the first
1581   //     node's function's module.
1582   Module &M = *C.begin()->getFunction().getParent();
1583   if (!declaresCoroSplitIntrinsics(M))
1584     return PreservedAnalyses::all();
1585 
1586   // Check for uses of llvm.coro.prepare.retcon.
1587   const auto *PrepareFn = M.getFunction("llvm.coro.prepare.retcon");
1588   if (PrepareFn && PrepareFn->use_empty())
1589     PrepareFn = nullptr;
1590 
1591   // Find coroutines for processing.
1592   SmallVector<LazyCallGraph::Node *, 4> Coroutines;
1593   for (LazyCallGraph::Node &N : C)
1594     if (N.getFunction().hasFnAttribute(CORO_PRESPLIT_ATTR))
1595       Coroutines.push_back(&N);
1596 
1597   if (Coroutines.empty() && !PrepareFn)
1598     return PreservedAnalyses::all();
1599 
1600   if (Coroutines.empty())
1601     llvm_unreachable("new pass manager cannot yet handle "
1602                      "'llvm.coro.prepare.retcon'");
1603 
1604   // Split all the coroutines.
1605   for (LazyCallGraph::Node *N : Coroutines) {
1606     Function &F = N->getFunction();
1607     Attribute Attr = F.getFnAttribute(CORO_PRESPLIT_ATTR);
1608     StringRef Value = Attr.getValueAsString();
1609     LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F.getName()
1610                       << "' state: " << Value << "\n");
1611     if (Value == UNPREPARED_FOR_SPLIT) {
1612       // Enqueue a second iteration of the CGSCC pipeline.
1613       // N.B.:
1614       // The CoroSplitLegacy pass "triggers" a restart of the CGSCC pass
1615       // pipeline by inserting an indirect function call that the
1616       // CoroElideLegacy pass then replaces with a direct function call. The
1617       // legacy CGSCC pipeline's implicit behavior was as if wrapped in the new
1618       // pass manager abstraction DevirtSCCRepeatedPass.
1619       //
1620       // This pass does not need to "trigger" another run of the pipeline.
1621       // Instead, it simply enqueues the same RefSCC onto the pipeline's
1622       // worklist.
1623       UR.CWorklist.insert(&C);
1624       F.addFnAttr(CORO_PRESPLIT_ATTR, PREPARED_FOR_SPLIT);
1625       continue;
1626     }
1627     F.removeFnAttr(CORO_PRESPLIT_ATTR);
1628 
1629     SmallVector<Function *, 4> Clones;
1630     const coro::Shape Shape = splitCoroutine(F, Clones);
1631     updateCallGraphAfterCoroutineSplit(*N, Shape, Clones, C, CG, AM, UR);
1632   }
1633 
1634   if (PrepareFn)
1635     llvm_unreachable("new pass manager cannot yet handle "
1636                      "'llvm.coro.prepare.retcon'");
1637 
1638   return PreservedAnalyses::none();
1639 }
1640 
1641 namespace {
1642 
1643 // We present a coroutine to LLVM as an ordinary function with suspension
1644 // points marked up with intrinsics. We let the optimizer party on the coroutine
1645 // as a single function for as long as possible. Shortly before the coroutine is
1646 // eligible to be inlined into its callers, we split up the coroutine into parts
1647 // corresponding to initial, resume and destroy invocations of the coroutine,
1648 // add them to the current SCC and restart the IPO pipeline to optimize the
1649 // coroutine subfunctions we extracted before proceeding to the caller of the
1650 // coroutine.
1651 struct CoroSplitLegacy : public CallGraphSCCPass {
1652   static char ID; // Pass identification, replacement for typeid
1653 
1654   CoroSplitLegacy() : CallGraphSCCPass(ID) {
1655     initializeCoroSplitLegacyPass(*PassRegistry::getPassRegistry());
1656   }
1657 
1658   bool Run = false;
1659 
1660   // A coroutine is identified by the presence of coro.begin intrinsic, if
1661   // we don't have any, this pass has nothing to do.
1662   bool doInitialization(CallGraph &CG) override {
1663     Run = declaresCoroSplitIntrinsics(CG.getModule());
1664     return CallGraphSCCPass::doInitialization(CG);
1665   }
1666 
1667   bool runOnSCC(CallGraphSCC &SCC) override {
1668     if (!Run)
1669       return false;
1670 
1671     // Check for uses of llvm.coro.prepare.retcon.
1672     auto PrepareFn =
1673       SCC.getCallGraph().getModule().getFunction("llvm.coro.prepare.retcon");
1674     if (PrepareFn && PrepareFn->use_empty())
1675       PrepareFn = nullptr;
1676 
1677     // Find coroutines for processing.
1678     SmallVector<Function *, 4> Coroutines;
1679     for (CallGraphNode *CGN : SCC)
1680       if (auto *F = CGN->getFunction())
1681         if (F->hasFnAttribute(CORO_PRESPLIT_ATTR))
1682           Coroutines.push_back(F);
1683 
1684     if (Coroutines.empty() && !PrepareFn)
1685       return false;
1686 
1687     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1688 
1689     if (Coroutines.empty())
1690       return replaceAllPrepares(PrepareFn, CG);
1691 
1692     createDevirtTriggerFunc(CG, SCC);
1693 
1694     // Split all the coroutines.
1695     for (Function *F : Coroutines) {
1696       Attribute Attr = F->getFnAttribute(CORO_PRESPLIT_ATTR);
1697       StringRef Value = Attr.getValueAsString();
1698       LLVM_DEBUG(dbgs() << "CoroSplit: Processing coroutine '" << F->getName()
1699                         << "' state: " << Value << "\n");
1700       if (Value == UNPREPARED_FOR_SPLIT) {
1701         prepareForSplit(*F, CG);
1702         continue;
1703       }
1704       F->removeFnAttr(CORO_PRESPLIT_ATTR);
1705 
1706       SmallVector<Function *, 4> Clones;
1707       const coro::Shape Shape = splitCoroutine(*F, Clones);
1708       updateCallGraphAfterCoroutineSplit(*F, Shape, Clones, CG, SCC);
1709     }
1710 
1711     if (PrepareFn)
1712       replaceAllPrepares(PrepareFn, CG);
1713 
1714     return true;
1715   }
1716 
1717   void getAnalysisUsage(AnalysisUsage &AU) const override {
1718     CallGraphSCCPass::getAnalysisUsage(AU);
1719   }
1720 
1721   StringRef getPassName() const override { return "Coroutine Splitting"; }
1722 };
1723 
1724 } // end anonymous namespace
1725 
1726 char CoroSplitLegacy::ID = 0;
1727 
1728 INITIALIZE_PASS_BEGIN(
1729     CoroSplitLegacy, "coro-split",
1730     "Split coroutine into a set of functions driving its state machine", false,
1731     false)
1732 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1733 INITIALIZE_PASS_END(
1734     CoroSplitLegacy, "coro-split",
1735     "Split coroutine into a set of functions driving its state machine", false,
1736     false)
1737 
1738 Pass *llvm::createCoroSplitLegacyPass() { return new CoroSplitLegacy(); }
1739