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