1 //===- CoroFrame.cpp - Builds and manipulates coroutine frame -------------===//
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 file contains classes used to discover if for a particular value
9 // there from sue to definition that crosses a suspend block.
10 //
11 // Using the information discovered we form a Coroutine Frame structure to
12 // contain those values. All uses of those values are replaced with appropriate
13 // GEP + load from the coroutine frame. At the point of the definition we spill
14 // the value into the coroutine frame.
15 //===----------------------------------------------------------------------===//
16 
17 #include "CoroInternal.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Analysis/PtrUseVisitor.h"
21 #include "llvm/Analysis/StackLifetime.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/DIBuilder.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstIterator.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/OptimizedStructLayout.h"
32 #include "llvm/Support/circular_raw_ostream.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
36 #include <algorithm>
37 
38 using namespace llvm;
39 
40 // The "coro-suspend-crossing" flag is very noisy. There is another debug type,
41 // "coro-frame", which results in leaner debug spew.
42 #define DEBUG_TYPE "coro-suspend-crossing"
43 
44 static cl::opt<bool> EnableReuseStorageInFrame(
45     "reuse-storage-in-coroutine-frame", cl::Hidden,
46     cl::desc(
47         "Enable the optimization which would reuse the storage in the coroutine \
48          frame for allocas whose liferanges are not overlapped, for testing purposes"),
49     llvm::cl::init(false));
50 
51 enum { SmallVectorThreshold = 32 };
52 
53 // Provides two way mapping between the blocks and numbers.
54 namespace {
55 class BlockToIndexMapping {
56   SmallVector<BasicBlock *, SmallVectorThreshold> V;
57 
58 public:
59   size_t size() const { return V.size(); }
60 
61   BlockToIndexMapping(Function &F) {
62     for (BasicBlock &BB : F)
63       V.push_back(&BB);
64     llvm::sort(V);
65   }
66 
67   size_t blockToIndex(BasicBlock *BB) const {
68     auto *I = llvm::lower_bound(V, BB);
69     assert(I != V.end() && *I == BB && "BasicBlockNumberng: Unknown block");
70     return I - V.begin();
71   }
72 
73   BasicBlock *indexToBlock(unsigned Index) const { return V[Index]; }
74 };
75 } // end anonymous namespace
76 
77 // The SuspendCrossingInfo maintains data that allows to answer a question
78 // whether given two BasicBlocks A and B there is a path from A to B that
79 // passes through a suspend point.
80 //
81 // For every basic block 'i' it maintains a BlockData that consists of:
82 //   Consumes:  a bit vector which contains a set of indices of blocks that can
83 //              reach block 'i'
84 //   Kills: a bit vector which contains a set of indices of blocks that can
85 //          reach block 'i', but one of the path will cross a suspend point
86 //   Suspend: a boolean indicating whether block 'i' contains a suspend point.
87 //   End: a boolean indicating whether block 'i' contains a coro.end intrinsic.
88 //
89 namespace {
90 struct SuspendCrossingInfo {
91   BlockToIndexMapping Mapping;
92 
93   struct BlockData {
94     BitVector Consumes;
95     BitVector Kills;
96     bool Suspend = false;
97     bool End = false;
98   };
99   SmallVector<BlockData, SmallVectorThreshold> Block;
100 
101   iterator_range<succ_iterator> successors(BlockData const &BD) const {
102     BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]);
103     return llvm::successors(BB);
104   }
105 
106   BlockData &getBlockData(BasicBlock *BB) {
107     return Block[Mapping.blockToIndex(BB)];
108   }
109 
110   void dump() const;
111   void dump(StringRef Label, BitVector const &BV) const;
112 
113   SuspendCrossingInfo(Function &F, coro::Shape &Shape);
114 
115   bool hasPathCrossingSuspendPoint(BasicBlock *DefBB, BasicBlock *UseBB) const {
116     size_t const DefIndex = Mapping.blockToIndex(DefBB);
117     size_t const UseIndex = Mapping.blockToIndex(UseBB);
118 
119     bool const Result = Block[UseIndex].Kills[DefIndex];
120     LLVM_DEBUG(dbgs() << UseBB->getName() << " => " << DefBB->getName()
121                       << " answer is " << Result << "\n");
122     return Result;
123   }
124 
125   bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const {
126     auto *I = cast<Instruction>(U);
127 
128     // We rewrote PHINodes, so that only the ones with exactly one incoming
129     // value need to be analyzed.
130     if (auto *PN = dyn_cast<PHINode>(I))
131       if (PN->getNumIncomingValues() > 1)
132         return false;
133 
134     BasicBlock *UseBB = I->getParent();
135 
136     // As a special case, treat uses by an llvm.coro.suspend.retcon or an
137     // llvm.coro.suspend.async as if they were uses in the suspend's single
138     // predecessor: the uses conceptually occur before the suspend.
139     if (isa<CoroSuspendRetconInst>(I) || isa<CoroSuspendAsyncInst>(I)) {
140       UseBB = UseBB->getSinglePredecessor();
141       assert(UseBB && "should have split coro.suspend into its own block");
142     }
143 
144     return hasPathCrossingSuspendPoint(DefBB, UseBB);
145   }
146 
147   bool isDefinitionAcrossSuspend(Argument &A, User *U) const {
148     return isDefinitionAcrossSuspend(&A.getParent()->getEntryBlock(), U);
149   }
150 
151   bool isDefinitionAcrossSuspend(Instruction &I, User *U) const {
152     auto *DefBB = I.getParent();
153 
154     // As a special case, treat values produced by an llvm.coro.suspend.*
155     // as if they were defined in the single successor: the uses
156     // conceptually occur after the suspend.
157     if (isa<AnyCoroSuspendInst>(I)) {
158       DefBB = DefBB->getSingleSuccessor();
159       assert(DefBB && "should have split coro.suspend into its own block");
160     }
161 
162     return isDefinitionAcrossSuspend(DefBB, U);
163   }
164 };
165 } // end anonymous namespace
166 
167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump(StringRef Label,
169                                                 BitVector const &BV) const {
170   dbgs() << Label << ":";
171   for (size_t I = 0, N = BV.size(); I < N; ++I)
172     if (BV[I])
173       dbgs() << " " << Mapping.indexToBlock(I)->getName();
174   dbgs() << "\n";
175 }
176 
177 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump() const {
178   for (size_t I = 0, N = Block.size(); I < N; ++I) {
179     BasicBlock *const B = Mapping.indexToBlock(I);
180     dbgs() << B->getName() << ":\n";
181     dump("   Consumes", Block[I].Consumes);
182     dump("      Kills", Block[I].Kills);
183   }
184   dbgs() << "\n";
185 }
186 #endif
187 
188 SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape)
189     : Mapping(F) {
190   const size_t N = Mapping.size();
191   Block.resize(N);
192 
193   // Initialize every block so that it consumes itself
194   for (size_t I = 0; I < N; ++I) {
195     auto &B = Block[I];
196     B.Consumes.resize(N);
197     B.Kills.resize(N);
198     B.Consumes.set(I);
199   }
200 
201   // Mark all CoroEnd Blocks. We do not propagate Kills beyond coro.ends as
202   // the code beyond coro.end is reachable during initial invocation of the
203   // coroutine.
204   for (auto *CE : Shape.CoroEnds)
205     getBlockData(CE->getParent()).End = true;
206 
207   // Mark all suspend blocks and indicate that they kill everything they
208   // consume. Note, that crossing coro.save also requires a spill, as any code
209   // between coro.save and coro.suspend may resume the coroutine and all of the
210   // state needs to be saved by that time.
211   auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) {
212     BasicBlock *SuspendBlock = BarrierInst->getParent();
213     auto &B = getBlockData(SuspendBlock);
214     B.Suspend = true;
215     B.Kills |= B.Consumes;
216   };
217   for (auto *CSI : Shape.CoroSuspends) {
218     markSuspendBlock(CSI);
219     if (auto *Save = CSI->getCoroSave())
220       markSuspendBlock(Save);
221   }
222 
223   // Iterate propagating consumes and kills until they stop changing.
224   int Iteration = 0;
225   (void)Iteration;
226 
227   bool Changed;
228   do {
229     LLVM_DEBUG(dbgs() << "iteration " << ++Iteration);
230     LLVM_DEBUG(dbgs() << "==============\n");
231 
232     Changed = false;
233     for (size_t I = 0; I < N; ++I) {
234       auto &B = Block[I];
235       for (BasicBlock *SI : successors(B)) {
236 
237         auto SuccNo = Mapping.blockToIndex(SI);
238 
239         // Saved Consumes and Kills bitsets so that it is easy to see
240         // if anything changed after propagation.
241         auto &S = Block[SuccNo];
242         auto SavedConsumes = S.Consumes;
243         auto SavedKills = S.Kills;
244 
245         // Propagate Kills and Consumes from block B into its successor S.
246         S.Consumes |= B.Consumes;
247         S.Kills |= B.Kills;
248 
249         // If block B is a suspend block, it should propagate kills into the
250         // its successor for every block B consumes.
251         if (B.Suspend) {
252           S.Kills |= B.Consumes;
253         }
254         if (S.Suspend) {
255           // If block S is a suspend block, it should kill all of the blocks it
256           // consumes.
257           S.Kills |= S.Consumes;
258         } else if (S.End) {
259           // If block S is an end block, it should not propagate kills as the
260           // blocks following coro.end() are reached during initial invocation
261           // of the coroutine while all the data are still available on the
262           // stack or in the registers.
263           S.Kills.reset();
264         } else {
265           // This is reached when S block it not Suspend nor coro.end and it
266           // need to make sure that it is not in the kill set.
267           S.Kills.reset(SuccNo);
268         }
269 
270         // See if anything changed.
271         Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes);
272 
273         if (S.Kills != SavedKills) {
274           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI->getName()
275                             << "\n");
276           LLVM_DEBUG(dump("S.Kills", S.Kills));
277           LLVM_DEBUG(dump("SavedKills", SavedKills));
278         }
279         if (S.Consumes != SavedConsumes) {
280           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI << "\n");
281           LLVM_DEBUG(dump("S.Consume", S.Consumes));
282           LLVM_DEBUG(dump("SavedCons", SavedConsumes));
283         }
284       }
285     }
286   } while (Changed);
287   LLVM_DEBUG(dump());
288 }
289 
290 #undef DEBUG_TYPE // "coro-suspend-crossing"
291 #define DEBUG_TYPE "coro-frame"
292 
293 namespace {
294 class FrameTypeBuilder;
295 // Mapping from the to-be-spilled value to all the users that need reload.
296 using SpillInfo = SmallMapVector<Value *, SmallVector<Instruction *, 2>, 8>;
297 struct AllocaInfo {
298   AllocaInst *Alloca;
299   DenseMap<Instruction *, llvm::Optional<APInt>> Aliases;
300   bool MayWriteBeforeCoroBegin;
301   AllocaInfo(AllocaInst *Alloca,
302              DenseMap<Instruction *, llvm::Optional<APInt>> Aliases,
303              bool MayWriteBeforeCoroBegin)
304       : Alloca(Alloca), Aliases(std::move(Aliases)),
305         MayWriteBeforeCoroBegin(MayWriteBeforeCoroBegin) {}
306 };
307 struct FrameDataInfo {
308   // All the values (that are not allocas) that needs to be spilled to the
309   // frame.
310   SpillInfo Spills;
311   // Allocas contains all values defined as allocas that need to live in the
312   // frame.
313   SmallVector<AllocaInfo, 8> Allocas;
314 
315   SmallVector<Value *, 8> getAllDefs() const {
316     SmallVector<Value *, 8> Defs;
317     for (const auto &P : Spills)
318       Defs.push_back(P.first);
319     for (const auto &A : Allocas)
320       Defs.push_back(A.Alloca);
321     return Defs;
322   }
323 
324   uint32_t getFieldIndex(Value *V) const {
325     auto Itr = FieldIndexMap.find(V);
326     assert(Itr != FieldIndexMap.end() &&
327            "Value does not have a frame field index");
328     return Itr->second;
329   }
330 
331   void setFieldIndex(Value *V, uint32_t Index) {
332     assert((LayoutIndexUpdateStarted || FieldIndexMap.count(V) == 0) &&
333            "Cannot set the index for the same field twice.");
334     FieldIndexMap[V] = Index;
335   }
336 
337   // Remap the index of every field in the frame, using the final layout index.
338   void updateLayoutIndex(FrameTypeBuilder &B);
339 
340 private:
341   // LayoutIndexUpdateStarted is used to avoid updating the index of any field
342   // twice by mistake.
343   bool LayoutIndexUpdateStarted = false;
344   // Map from values to their slot indexes on the frame. They will be first set
345   // with their original insertion field index. After the frame is built, their
346   // indexes will be updated into the final layout index.
347   DenseMap<Value *, uint32_t> FieldIndexMap;
348 };
349 } // namespace
350 
351 #ifndef NDEBUG
352 static void dumpSpills(StringRef Title, const SpillInfo &Spills) {
353   dbgs() << "------------- " << Title << "--------------\n";
354   for (const auto &E : Spills) {
355     E.first->dump();
356     dbgs() << "   user: ";
357     for (auto *I : E.second)
358       I->dump();
359   }
360 }
361 
362 static void dumpAllocas(const SmallVectorImpl<AllocaInfo> &Allocas) {
363   dbgs() << "------------- Allocas --------------\n";
364   for (const auto &A : Allocas) {
365     A.Alloca->dump();
366   }
367 }
368 #endif
369 
370 namespace {
371 using FieldIDType = size_t;
372 // We cannot rely solely on natural alignment of a type when building a
373 // coroutine frame and if the alignment specified on the Alloca instruction
374 // differs from the natural alignment of the alloca type we will need to insert
375 // padding.
376 class FrameTypeBuilder {
377 private:
378   struct Field {
379     uint64_t Size;
380     uint64_t Offset;
381     Type *Ty;
382     FieldIDType LayoutFieldIndex;
383     Align Alignment;
384     Align TyAlignment;
385   };
386 
387   const DataLayout &DL;
388   LLVMContext &Context;
389   uint64_t StructSize = 0;
390   Align StructAlign;
391   bool IsFinished = false;
392 
393   SmallVector<Field, 8> Fields;
394   DenseMap<Value*, unsigned> FieldIndexByKey;
395 
396 public:
397   FrameTypeBuilder(LLVMContext &Context, DataLayout const &DL)
398       : DL(DL), Context(Context) {}
399 
400   /// Add a field to this structure for the storage of an `alloca`
401   /// instruction.
402   LLVM_NODISCARD FieldIDType addFieldForAlloca(AllocaInst *AI,
403                                                bool IsHeader = false) {
404     Type *Ty = AI->getAllocatedType();
405 
406     // Make an array type if this is a static array allocation.
407     if (AI->isArrayAllocation()) {
408       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
409         Ty = ArrayType::get(Ty, CI->getValue().getZExtValue());
410       else
411         report_fatal_error("Coroutines cannot handle non static allocas yet");
412     }
413 
414     return addField(Ty, AI->getAlign(), IsHeader);
415   }
416 
417   /// We want to put the allocas whose lifetime-ranges are not overlapped
418   /// into one slot of coroutine frame.
419   /// Consider the example at:https://bugs.llvm.org/show_bug.cgi?id=45566
420   ///
421   ///     cppcoro::task<void> alternative_paths(bool cond) {
422   ///         if (cond) {
423   ///             big_structure a;
424   ///             process(a);
425   ///             co_await something();
426   ///         } else {
427   ///             big_structure b;
428   ///             process2(b);
429   ///             co_await something();
430   ///         }
431   ///     }
432   ///
433   /// We want to put variable a and variable b in the same slot to
434   /// reduce the size of coroutine frame.
435   ///
436   /// This function use StackLifetime algorithm to partition the AllocaInsts in
437   /// Spills to non-overlapped sets in order to put Alloca in the same
438   /// non-overlapped set into the same slot in the Coroutine Frame. Then add
439   /// field for the allocas in the same non-overlapped set by using the largest
440   /// type as the field type.
441   ///
442   /// Side Effects: Because We sort the allocas, the order of allocas in the
443   /// frame may be different with the order in the source code.
444   void addFieldForAllocas(const Function &F, FrameDataInfo &FrameData,
445                           coro::Shape &Shape);
446 
447   /// Add a field to this structure.
448   LLVM_NODISCARD FieldIDType addField(Type *Ty, MaybeAlign FieldAlignment,
449                                       bool IsHeader = false) {
450     assert(!IsFinished && "adding fields to a finished builder");
451     assert(Ty && "must provide a type for a field");
452 
453     // The field size is always the alloc size of the type.
454     uint64_t FieldSize = DL.getTypeAllocSize(Ty);
455 
456     // The field alignment might not be the type alignment, but we need
457     // to remember the type alignment anyway to build the type.
458     Align TyAlignment = DL.getABITypeAlign(Ty);
459     if (!FieldAlignment) FieldAlignment = TyAlignment;
460 
461     // Lay out header fields immediately.
462     uint64_t Offset;
463     if (IsHeader) {
464       Offset = alignTo(StructSize, FieldAlignment);
465       StructSize = Offset + FieldSize;
466 
467     // Everything else has a flexible offset.
468     } else {
469       Offset = OptimizedStructLayoutField::FlexibleOffset;
470     }
471 
472     Fields.push_back({FieldSize, Offset, Ty, 0, *FieldAlignment, TyAlignment});
473     return Fields.size() - 1;
474   }
475 
476   /// Finish the layout and set the body on the given type.
477   void finish(StructType *Ty);
478 
479   uint64_t getStructSize() const {
480     assert(IsFinished && "not yet finished!");
481     return StructSize;
482   }
483 
484   Align getStructAlign() const {
485     assert(IsFinished && "not yet finished!");
486     return StructAlign;
487   }
488 
489   FieldIDType getLayoutFieldIndex(FieldIDType Id) const {
490     assert(IsFinished && "not yet finished!");
491     return Fields[Id].LayoutFieldIndex;
492   }
493 };
494 } // namespace
495 
496 void FrameDataInfo::updateLayoutIndex(FrameTypeBuilder &B) {
497   auto Updater = [&](Value *I) {
498     setFieldIndex(I, B.getLayoutFieldIndex(getFieldIndex(I)));
499   };
500   LayoutIndexUpdateStarted = true;
501   for (auto &S : Spills)
502     Updater(S.first);
503   for (const auto &A : Allocas)
504     Updater(A.Alloca);
505   LayoutIndexUpdateStarted = false;
506 }
507 
508 void FrameTypeBuilder::addFieldForAllocas(const Function &F,
509                                           FrameDataInfo &FrameData,
510                                           coro::Shape &Shape) {
511   DenseMap<AllocaInst *, unsigned int> AllocaIndex;
512   using AllocaSetType = SmallVector<AllocaInst *, 4>;
513   SmallVector<AllocaSetType, 4> NonOverlapedAllocas;
514 
515   // We need to add field for allocas at the end of this function. However, this
516   // function has multiple exits, so we use this helper to avoid redundant code.
517   struct RTTIHelper {
518     std::function<void()> func;
519     RTTIHelper(std::function<void()> &&func) : func(func) {}
520     ~RTTIHelper() { func(); }
521   } Helper([&]() {
522     for (auto AllocaList : NonOverlapedAllocas) {
523       auto *LargestAI = *AllocaList.begin();
524       FieldIDType Id = addFieldForAlloca(LargestAI);
525       for (auto *Alloca : AllocaList)
526         FrameData.setFieldIndex(Alloca, Id);
527     }
528   });
529 
530   if (!Shape.ReuseFrameSlot && !EnableReuseStorageInFrame) {
531     for (const auto &A : FrameData.Allocas) {
532       AllocaInst *Alloca = A.Alloca;
533       AllocaIndex[Alloca] = NonOverlapedAllocas.size();
534       NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
535     }
536     return;
537   }
538 
539   // Because there are pathes from the lifetime.start to coro.end
540   // for each alloca, the liferanges for every alloca is overlaped
541   // in the blocks who contain coro.end and the successor blocks.
542   // So we choose to skip there blocks when we calculates the liferange
543   // for each alloca. It should be reasonable since there shouldn't be uses
544   // in these blocks and the coroutine frame shouldn't be used outside the
545   // coroutine body.
546   //
547   // Note that the user of coro.suspend may not be SwitchInst. However, this
548   // case seems too complex to handle. And it is harmless to skip these
549   // patterns since it just prevend putting the allocas to live in the same
550   // slot.
551   DenseMap<SwitchInst *, BasicBlock *> DefaultSuspendDest;
552   for (auto CoroSuspendInst : Shape.CoroSuspends) {
553     for (auto U : CoroSuspendInst->users()) {
554       if (auto *ConstSWI = dyn_cast<SwitchInst>(U)) {
555         auto *SWI = const_cast<SwitchInst *>(ConstSWI);
556         DefaultSuspendDest[SWI] = SWI->getDefaultDest();
557         SWI->setDefaultDest(SWI->getSuccessor(1));
558       }
559     }
560   }
561 
562   auto ExtractAllocas = [&]() {
563     AllocaSetType Allocas;
564     Allocas.reserve(FrameData.Allocas.size());
565     for (const auto &A : FrameData.Allocas)
566       Allocas.push_back(A.Alloca);
567     return Allocas;
568   };
569   StackLifetime StackLifetimeAnalyzer(F, ExtractAllocas(),
570                                       StackLifetime::LivenessType::May);
571   StackLifetimeAnalyzer.run();
572   auto IsAllocaInferenre = [&](const AllocaInst *AI1, const AllocaInst *AI2) {
573     return StackLifetimeAnalyzer.getLiveRange(AI1).overlaps(
574         StackLifetimeAnalyzer.getLiveRange(AI2));
575   };
576   auto GetAllocaSize = [&](const AllocaInfo &A) {
577     Optional<TypeSize> RetSize = A.Alloca->getAllocationSizeInBits(DL);
578     assert(RetSize && "Variable Length Arrays (VLA) are not supported.\n");
579     assert(!RetSize->isScalable() && "Scalable vectors are not yet supported");
580     return RetSize->getFixedSize();
581   };
582   // Put larger allocas in the front. So the larger allocas have higher
583   // priority to merge, which can save more space potentially. Also each
584   // AllocaSet would be ordered. So we can get the largest Alloca in one
585   // AllocaSet easily.
586   sort(FrameData.Allocas, [&](const auto &Iter1, const auto &Iter2) {
587     return GetAllocaSize(Iter1) > GetAllocaSize(Iter2);
588   });
589   for (const auto &A : FrameData.Allocas) {
590     AllocaInst *Alloca = A.Alloca;
591     bool Merged = false;
592     // Try to find if the Alloca is not inferenced with any existing
593     // NonOverlappedAllocaSet. If it is true, insert the alloca to that
594     // NonOverlappedAllocaSet.
595     for (auto &AllocaSet : NonOverlapedAllocas) {
596       assert(!AllocaSet.empty() && "Processing Alloca Set is not empty.\n");
597       bool NoInference = none_of(AllocaSet, [&](auto Iter) {
598         return IsAllocaInferenre(Alloca, Iter);
599       });
600       // If the alignment of A is multiple of the alignment of B, the address
601       // of A should satisfy the requirement for aligning for B.
602       //
603       // There may be other more fine-grained strategies to handle the alignment
604       // infomation during the merging process. But it seems hard to handle
605       // these strategies and benefit little.
606       bool Alignable = [&]() -> bool {
607         auto *LargestAlloca = *AllocaSet.begin();
608         return LargestAlloca->getAlign().value() % Alloca->getAlign().value() ==
609                0;
610       }();
611       bool CouldMerge = NoInference && Alignable;
612       if (!CouldMerge)
613         continue;
614       AllocaIndex[Alloca] = AllocaIndex[*AllocaSet.begin()];
615       AllocaSet.push_back(Alloca);
616       Merged = true;
617       break;
618     }
619     if (!Merged) {
620       AllocaIndex[Alloca] = NonOverlapedAllocas.size();
621       NonOverlapedAllocas.emplace_back(AllocaSetType(1, Alloca));
622     }
623   }
624   // Recover the default target destination for each Switch statement
625   // reserved.
626   for (auto SwitchAndDefaultDest : DefaultSuspendDest) {
627     SwitchInst *SWI = SwitchAndDefaultDest.first;
628     BasicBlock *DestBB = SwitchAndDefaultDest.second;
629     SWI->setDefaultDest(DestBB);
630   }
631   // This Debug Info could tell us which allocas are merged into one slot.
632   LLVM_DEBUG(for (auto &AllocaSet
633                   : NonOverlapedAllocas) {
634     if (AllocaSet.size() > 1) {
635       dbgs() << "In Function:" << F.getName() << "\n";
636       dbgs() << "Find Union Set "
637              << "\n";
638       dbgs() << "\tAllocas are \n";
639       for (auto Alloca : AllocaSet)
640         dbgs() << "\t\t" << *Alloca << "\n";
641     }
642   });
643 }
644 
645 void FrameTypeBuilder::finish(StructType *Ty) {
646   assert(!IsFinished && "already finished!");
647 
648   // Prepare the optimal-layout field array.
649   // The Id in the layout field is a pointer to our Field for it.
650   SmallVector<OptimizedStructLayoutField, 8> LayoutFields;
651   LayoutFields.reserve(Fields.size());
652   for (auto &Field : Fields) {
653     LayoutFields.emplace_back(&Field, Field.Size, Field.Alignment,
654                               Field.Offset);
655   }
656 
657   // Perform layout.
658   auto SizeAndAlign = performOptimizedStructLayout(LayoutFields);
659   StructSize = SizeAndAlign.first;
660   StructAlign = SizeAndAlign.second;
661 
662   auto getField = [](const OptimizedStructLayoutField &LayoutField) -> Field & {
663     return *static_cast<Field *>(const_cast<void*>(LayoutField.Id));
664   };
665 
666   // We need to produce a packed struct type if there's a field whose
667   // assigned offset isn't a multiple of its natural type alignment.
668   bool Packed = [&] {
669     for (auto &LayoutField : LayoutFields) {
670       auto &F = getField(LayoutField);
671       if (!isAligned(F.TyAlignment, LayoutField.Offset))
672         return true;
673     }
674     return false;
675   }();
676 
677   // Build the struct body.
678   SmallVector<Type*, 16> FieldTypes;
679   FieldTypes.reserve(LayoutFields.size() * 3 / 2);
680   uint64_t LastOffset = 0;
681   for (auto &LayoutField : LayoutFields) {
682     auto &F = getField(LayoutField);
683 
684     auto Offset = LayoutField.Offset;
685 
686     // Add a padding field if there's a padding gap and we're either
687     // building a packed struct or the padding gap is more than we'd
688     // get from aligning to the field type's natural alignment.
689     assert(Offset >= LastOffset);
690     if (Offset != LastOffset) {
691       if (Packed || alignTo(LastOffset, F.TyAlignment) != Offset)
692         FieldTypes.push_back(ArrayType::get(Type::getInt8Ty(Context),
693                                             Offset - LastOffset));
694     }
695 
696     F.Offset = Offset;
697     F.LayoutFieldIndex = FieldTypes.size();
698 
699     FieldTypes.push_back(F.Ty);
700     LastOffset = Offset + F.Size;
701   }
702 
703   Ty->setBody(FieldTypes, Packed);
704 
705 #ifndef NDEBUG
706   // Check that the IR layout matches the offsets we expect.
707   auto Layout = DL.getStructLayout(Ty);
708   for (auto &F : Fields) {
709     assert(Ty->getElementType(F.LayoutFieldIndex) == F.Ty);
710     assert(Layout->getElementOffset(F.LayoutFieldIndex) == F.Offset);
711   }
712 #endif
713 
714   IsFinished = true;
715 }
716 
717 // Build a struct that will keep state for an active coroutine.
718 //   struct f.frame {
719 //     ResumeFnTy ResumeFnAddr;
720 //     ResumeFnTy DestroyFnAddr;
721 //     int ResumeIndex;
722 //     ... promise (if present) ...
723 //     ... spills ...
724 //   };
725 static StructType *buildFrameType(Function &F, coro::Shape &Shape,
726                                   FrameDataInfo &FrameData) {
727   LLVMContext &C = F.getContext();
728   const DataLayout &DL = F.getParent()->getDataLayout();
729   StructType *FrameTy = [&] {
730     SmallString<32> Name(F.getName());
731     Name.append(".Frame");
732     return StructType::create(C, Name);
733   }();
734 
735   FrameTypeBuilder B(C, DL);
736 
737   AllocaInst *PromiseAlloca = Shape.getPromiseAlloca();
738   Optional<FieldIDType> SwitchIndexFieldId;
739 
740   if (Shape.ABI == coro::ABI::Switch) {
741     auto *FramePtrTy = FrameTy->getPointerTo();
742     auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy,
743                                    /*IsVarArg=*/false);
744     auto *FnPtrTy = FnTy->getPointerTo();
745 
746     // Add header fields for the resume and destroy functions.
747     // We can rely on these being perfectly packed.
748     (void)B.addField(FnPtrTy, None, /*header*/ true);
749     (void)B.addField(FnPtrTy, None, /*header*/ true);
750 
751     // PromiseAlloca field needs to be explicitly added here because it's
752     // a header field with a fixed offset based on its alignment. Hence it
753     // needs special handling and cannot be added to FrameData.Allocas.
754     if (PromiseAlloca)
755       FrameData.setFieldIndex(
756           PromiseAlloca, B.addFieldForAlloca(PromiseAlloca, /*header*/ true));
757 
758     // Add a field to store the suspend index.  This doesn't need to
759     // be in the header.
760     unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size()));
761     Type *IndexType = Type::getIntNTy(C, IndexBits);
762 
763     SwitchIndexFieldId = B.addField(IndexType, None);
764   } else {
765     assert(PromiseAlloca == nullptr && "lowering doesn't support promises");
766   }
767 
768   // Because multiple allocas may own the same field slot,
769   // we add allocas to field here.
770   B.addFieldForAllocas(F, FrameData, Shape);
771   // Add PromiseAlloca to Allocas list so that
772   // 1. updateLayoutIndex could update its index after
773   // `performOptimizedStructLayout`
774   // 2. it is processed in insertSpills.
775   if (Shape.ABI == coro::ABI::Switch && PromiseAlloca)
776     // We assume that the promise alloca won't be modified before
777     // CoroBegin and no alias will be create before CoroBegin.
778     FrameData.Allocas.emplace_back(
779         PromiseAlloca, DenseMap<Instruction *, llvm::Optional<APInt>>{}, false);
780   // Create an entry for every spilled value.
781   for (auto &S : FrameData.Spills) {
782     FieldIDType Id = B.addField(S.first->getType(), None);
783     FrameData.setFieldIndex(S.first, Id);
784   }
785 
786   B.finish(FrameTy);
787   FrameData.updateLayoutIndex(B);
788   Shape.FrameAlign = B.getStructAlign();
789   Shape.FrameSize = B.getStructSize();
790 
791   switch (Shape.ABI) {
792   case coro::ABI::Switch:
793     // In the switch ABI, remember the switch-index field.
794     Shape.SwitchLowering.IndexField =
795         B.getLayoutFieldIndex(*SwitchIndexFieldId);
796 
797     // Also round the frame size up to a multiple of its alignment, as is
798     // generally expected in C/C++.
799     Shape.FrameSize = alignTo(Shape.FrameSize, Shape.FrameAlign);
800     break;
801 
802   // In the retcon ABI, remember whether the frame is inline in the storage.
803   case coro::ABI::Retcon:
804   case coro::ABI::RetconOnce: {
805     auto Id = Shape.getRetconCoroId();
806     Shape.RetconLowering.IsFrameInlineInStorage
807       = (B.getStructSize() <= Id->getStorageSize() &&
808          B.getStructAlign() <= Id->getStorageAlignment());
809     break;
810   }
811   case coro::ABI::Async: {
812     Shape.AsyncLowering.FrameOffset =
813         alignTo(Shape.AsyncLowering.ContextHeaderSize, Shape.FrameAlign);
814     // Also make the final context size a multiple of the context alignment to
815     // make allocation easier for allocators.
816     Shape.AsyncLowering.ContextSize =
817         alignTo(Shape.AsyncLowering.FrameOffset + Shape.FrameSize,
818                 Shape.AsyncLowering.getContextAlignment());
819     if (Shape.AsyncLowering.getContextAlignment() < Shape.FrameAlign) {
820       report_fatal_error(
821           "The alignment requirment of frame variables cannot be higher than "
822           "the alignment of the async function context");
823     }
824     break;
825   }
826   }
827 
828   return FrameTy;
829 }
830 
831 // We use a pointer use visitor to track how an alloca is being used.
832 // The goal is to be able to answer the following three questions:
833 // 1. Should this alloca be allocated on the frame instead.
834 // 2. Could the content of the alloca be modified prior to CoroBegn, which would
835 // require copying the data from alloca to the frame after CoroBegin.
836 // 3. Is there any alias created for this alloca prior to CoroBegin, but used
837 // after CoroBegin. In that case, we will need to recreate the alias after
838 // CoroBegin based off the frame. To answer question 1, we track two things:
839 //   a. List of all BasicBlocks that use this alloca or any of the aliases of
840 //   the alloca. In the end, we check if there exists any two basic blocks that
841 //   cross suspension points. If so, this alloca must be put on the frame. b.
842 //   Whether the alloca or any alias of the alloca is escaped at some point,
843 //   either by storing the address somewhere, or the address is used in a
844 //   function call that might capture. If it's ever escaped, this alloca must be
845 //   put on the frame conservatively.
846 // To answer quetion 2, we track through the variable MayWriteBeforeCoroBegin.
847 // Whenever a potential write happens, either through a store instruction, a
848 // function call or any of the memory intrinsics, we check whether this
849 // instruction is prior to CoroBegin. To answer question 3, we track the offsets
850 // of all aliases created for the alloca prior to CoroBegin but used after
851 // CoroBegin. llvm::Optional is used to be able to represent the case when the
852 // offset is unknown (e.g. when you have a PHINode that takes in different
853 // offset values). We cannot handle unknown offsets and will assert. This is the
854 // potential issue left out. An ideal solution would likely require a
855 // significant redesign.
856 namespace {
857 struct AllocaUseVisitor : PtrUseVisitor<AllocaUseVisitor> {
858   using Base = PtrUseVisitor<AllocaUseVisitor>;
859   AllocaUseVisitor(const DataLayout &DL, const DominatorTree &DT,
860                    const CoroBeginInst &CB, const SuspendCrossingInfo &Checker)
861       : PtrUseVisitor(DL), DT(DT), CoroBegin(CB), Checker(Checker) {}
862 
863   void visit(Instruction &I) {
864     UserBBs.insert(I.getParent());
865     Base::visit(I);
866     // If the pointer is escaped prior to CoroBegin, we have to assume it would
867     // be written into before CoroBegin as well.
868     if (PI.isEscaped() && !DT.dominates(&CoroBegin, PI.getEscapingInst())) {
869       MayWriteBeforeCoroBegin = true;
870     }
871   }
872   // We need to provide this overload as PtrUseVisitor uses a pointer based
873   // visiting function.
874   void visit(Instruction *I) { return visit(*I); }
875 
876   void visitPHINode(PHINode &I) {
877     enqueueUsers(I);
878     handleAlias(I);
879   }
880 
881   void visitSelectInst(SelectInst &I) {
882     enqueueUsers(I);
883     handleAlias(I);
884   }
885 
886   void visitStoreInst(StoreInst &SI) {
887     // Regardless whether the alias of the alloca is the value operand or the
888     // pointer operand, we need to assume the alloca is been written.
889     handleMayWrite(SI);
890 
891     if (SI.getValueOperand() != U->get())
892       return;
893 
894     // We are storing the pointer into a memory location, potentially escaping.
895     // As an optimization, we try to detect simple cases where it doesn't
896     // actually escape, for example:
897     //   %ptr = alloca ..
898     //   %addr = alloca ..
899     //   store %ptr, %addr
900     //   %x = load %addr
901     //   ..
902     // If %addr is only used by loading from it, we could simply treat %x as
903     // another alias of %ptr, and not considering %ptr being escaped.
904     auto IsSimpleStoreThenLoad = [&]() {
905       auto *AI = dyn_cast<AllocaInst>(SI.getPointerOperand());
906       // If the memory location we are storing to is not an alloca, it
907       // could be an alias of some other memory locations, which is difficult
908       // to analyze.
909       if (!AI)
910         return false;
911       // StoreAliases contains aliases of the memory location stored into.
912       SmallVector<Instruction *, 4> StoreAliases = {AI};
913       while (!StoreAliases.empty()) {
914         Instruction *I = StoreAliases.pop_back_val();
915         for (User *U : I->users()) {
916           // If we are loading from the memory location, we are creating an
917           // alias of the original pointer.
918           if (auto *LI = dyn_cast<LoadInst>(U)) {
919             enqueueUsers(*LI);
920             handleAlias(*LI);
921             continue;
922           }
923           // If we are overriding the memory location, the pointer certainly
924           // won't escape.
925           if (auto *S = dyn_cast<StoreInst>(U))
926             if (S->getPointerOperand() == I)
927               continue;
928           if (auto *II = dyn_cast<IntrinsicInst>(U))
929             if (II->isLifetimeStartOrEnd())
930               continue;
931           // BitCastInst creats aliases of the memory location being stored
932           // into.
933           if (auto *BI = dyn_cast<BitCastInst>(U)) {
934             StoreAliases.push_back(BI);
935             continue;
936           }
937           return false;
938         }
939       }
940 
941       return true;
942     };
943 
944     if (!IsSimpleStoreThenLoad())
945       PI.setEscaped(&SI);
946   }
947 
948   // All mem intrinsics modify the data.
949   void visitMemIntrinsic(MemIntrinsic &MI) { handleMayWrite(MI); }
950 
951   void visitBitCastInst(BitCastInst &BC) {
952     Base::visitBitCastInst(BC);
953     handleAlias(BC);
954   }
955 
956   void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
957     Base::visitAddrSpaceCastInst(ASC);
958     handleAlias(ASC);
959   }
960 
961   void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
962     // The base visitor will adjust Offset accordingly.
963     Base::visitGetElementPtrInst(GEPI);
964     handleAlias(GEPI);
965   }
966 
967   void visitCallBase(CallBase &CB) {
968     for (unsigned Op = 0, OpCount = CB.getNumArgOperands(); Op < OpCount; ++Op)
969       if (U->get() == CB.getArgOperand(Op) && !CB.doesNotCapture(Op))
970         PI.setEscaped(&CB);
971     handleMayWrite(CB);
972   }
973 
974   bool getShouldLiveOnFrame() const {
975     if (!ShouldLiveOnFrame)
976       ShouldLiveOnFrame = computeShouldLiveOnFrame();
977     return ShouldLiveOnFrame.getValue();
978   }
979 
980   bool getMayWriteBeforeCoroBegin() const { return MayWriteBeforeCoroBegin; }
981 
982   DenseMap<Instruction *, llvm::Optional<APInt>> getAliasesCopy() const {
983     assert(getShouldLiveOnFrame() && "This method should only be called if the "
984                                      "alloca needs to live on the frame.");
985     for (const auto &P : AliasOffetMap)
986       if (!P.second)
987         report_fatal_error("Unable to handle an alias with unknown offset "
988                            "created before CoroBegin.");
989     return AliasOffetMap;
990   }
991 
992 private:
993   const DominatorTree &DT;
994   const CoroBeginInst &CoroBegin;
995   const SuspendCrossingInfo &Checker;
996   // All alias to the original AllocaInst, created before CoroBegin and used
997   // after CoroBegin. Each entry contains the instruction and the offset in the
998   // original Alloca. They need to be recreated after CoroBegin off the frame.
999   DenseMap<Instruction *, llvm::Optional<APInt>> AliasOffetMap{};
1000   SmallPtrSet<BasicBlock *, 2> UserBBs{};
1001   bool MayWriteBeforeCoroBegin{false};
1002 
1003   mutable llvm::Optional<bool> ShouldLiveOnFrame{};
1004 
1005   bool computeShouldLiveOnFrame() const {
1006     if (PI.isEscaped())
1007       return true;
1008 
1009     for (auto *BB1 : UserBBs)
1010       for (auto *BB2 : UserBBs)
1011         if (Checker.hasPathCrossingSuspendPoint(BB1, BB2))
1012           return true;
1013 
1014     return false;
1015   }
1016 
1017   void handleMayWrite(const Instruction &I) {
1018     if (!DT.dominates(&CoroBegin, &I))
1019       MayWriteBeforeCoroBegin = true;
1020   }
1021 
1022   bool usedAfterCoroBegin(Instruction &I) {
1023     for (auto &U : I.uses())
1024       if (DT.dominates(&CoroBegin, U))
1025         return true;
1026     return false;
1027   }
1028 
1029   void handleAlias(Instruction &I) {
1030     // We track all aliases created prior to CoroBegin but used after.
1031     // These aliases may need to be recreated after CoroBegin if the alloca
1032     // need to live on the frame.
1033     if (DT.dominates(&CoroBegin, &I) || !usedAfterCoroBegin(I))
1034       return;
1035 
1036     if (!IsOffsetKnown) {
1037       AliasOffetMap[&I].reset();
1038     } else {
1039       auto Itr = AliasOffetMap.find(&I);
1040       if (Itr == AliasOffetMap.end()) {
1041         AliasOffetMap[&I] = Offset;
1042       } else if (Itr->second.hasValue() && Itr->second.getValue() != Offset) {
1043         // If we have seen two different possible values for this alias, we set
1044         // it to empty.
1045         AliasOffetMap[&I].reset();
1046       }
1047     }
1048   }
1049 };
1050 } // namespace
1051 
1052 // We need to make room to insert a spill after initial PHIs, but before
1053 // catchswitch instruction. Placing it before violates the requirement that
1054 // catchswitch, like all other EHPads must be the first nonPHI in a block.
1055 //
1056 // Split away catchswitch into a separate block and insert in its place:
1057 //
1058 //   cleanuppad <InsertPt> cleanupret.
1059 //
1060 // cleanupret instruction will act as an insert point for the spill.
1061 static Instruction *splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch) {
1062   BasicBlock *CurrentBlock = CatchSwitch->getParent();
1063   BasicBlock *NewBlock = CurrentBlock->splitBasicBlock(CatchSwitch);
1064   CurrentBlock->getTerminator()->eraseFromParent();
1065 
1066   auto *CleanupPad =
1067       CleanupPadInst::Create(CatchSwitch->getParentPad(), {}, "", CurrentBlock);
1068   auto *CleanupRet =
1069       CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock);
1070   return CleanupRet;
1071 }
1072 
1073 // Replace all alloca and SSA values that are accessed across suspend points
1074 // with GetElementPointer from coroutine frame + loads and stores. Create an
1075 // AllocaSpillBB that will become the new entry block for the resume parts of
1076 // the coroutine:
1077 //
1078 //    %hdl = coro.begin(...)
1079 //    whatever
1080 //
1081 // becomes:
1082 //
1083 //    %hdl = coro.begin(...)
1084 //    %FramePtr = bitcast i8* hdl to %f.frame*
1085 //    br label %AllocaSpillBB
1086 //
1087 //  AllocaSpillBB:
1088 //    ; geps corresponding to allocas that were moved to coroutine frame
1089 //    br label PostSpill
1090 //
1091 //  PostSpill:
1092 //    whatever
1093 //
1094 //
1095 static Instruction *insertSpills(const FrameDataInfo &FrameData,
1096                                  coro::Shape &Shape) {
1097   auto *CB = Shape.CoroBegin;
1098   LLVMContext &C = CB->getContext();
1099   IRBuilder<> Builder(CB->getNextNode());
1100   StructType *FrameTy = Shape.FrameTy;
1101   PointerType *FramePtrTy = FrameTy->getPointerTo();
1102   auto *FramePtr =
1103       cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy, "FramePtr"));
1104   DominatorTree DT(*CB->getFunction());
1105   SmallDenseMap<llvm::Value *, llvm::AllocaInst *, 4> DbgPtrAllocaCache;
1106 
1107   // Create a GEP with the given index into the coroutine frame for the original
1108   // value Orig. Appends an extra 0 index for array-allocas, preserving the
1109   // original type.
1110   auto GetFramePointer = [&](Value *Orig) -> Value * {
1111     FieldIDType Index = FrameData.getFieldIndex(Orig);
1112     SmallVector<Value *, 3> Indices = {
1113         ConstantInt::get(Type::getInt32Ty(C), 0),
1114         ConstantInt::get(Type::getInt32Ty(C), Index),
1115     };
1116 
1117     if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
1118       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
1119         auto Count = CI->getValue().getZExtValue();
1120         if (Count > 1) {
1121           Indices.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
1122         }
1123       } else {
1124         report_fatal_error("Coroutines cannot handle non static allocas yet");
1125       }
1126     }
1127 
1128     auto GEP = cast<GetElementPtrInst>(
1129         Builder.CreateInBoundsGEP(FrameTy, FramePtr, Indices));
1130     if (isa<AllocaInst>(Orig)) {
1131       // If the type of GEP is not equal to the type of AllocaInst, it implies
1132       // that the AllocaInst may be reused in the Frame slot of other
1133       // AllocaInst. So We cast GEP to the AllocaInst here to re-use
1134       // the Frame storage.
1135       //
1136       // Note: If we change the strategy dealing with alignment, we need to refine
1137       // this casting.
1138       if (GEP->getResultElementType() != Orig->getType())
1139         return Builder.CreateBitCast(GEP, Orig->getType(),
1140                                      Orig->getName() + Twine(".cast"));
1141     }
1142     return GEP;
1143   };
1144 
1145   for (auto const &E : FrameData.Spills) {
1146     Value *Def = E.first;
1147     // Create a store instruction storing the value into the
1148     // coroutine frame.
1149     Instruction *InsertPt = nullptr;
1150     if (auto *Arg = dyn_cast<Argument>(Def)) {
1151       // For arguments, we will place the store instruction right after
1152       // the coroutine frame pointer instruction, i.e. bitcast of
1153       // coro.begin from i8* to %f.frame*.
1154       InsertPt = FramePtr->getNextNode();
1155 
1156       // If we're spilling an Argument, make sure we clear 'nocapture'
1157       // from the coroutine function.
1158       Arg->getParent()->removeParamAttr(Arg->getArgNo(), Attribute::NoCapture);
1159 
1160     } else if (auto *CSI = dyn_cast<AnyCoroSuspendInst>(Def)) {
1161       // Don't spill immediately after a suspend; splitting assumes
1162       // that the suspend will be followed by a branch.
1163       InsertPt = CSI->getParent()->getSingleSuccessor()->getFirstNonPHI();
1164     } else {
1165       auto *I = cast<Instruction>(Def);
1166       if (!DT.dominates(CB, I)) {
1167         // If it is not dominated by CoroBegin, then spill should be
1168         // inserted immediately after CoroFrame is computed.
1169         InsertPt = FramePtr->getNextNode();
1170       } else if (auto *II = dyn_cast<InvokeInst>(I)) {
1171         // If we are spilling the result of the invoke instruction, split
1172         // the normal edge and insert the spill in the new block.
1173         auto *NewBB = SplitEdge(II->getParent(), II->getNormalDest());
1174         InsertPt = NewBB->getTerminator();
1175       } else if (isa<PHINode>(I)) {
1176         // Skip the PHINodes and EH pads instructions.
1177         BasicBlock *DefBlock = I->getParent();
1178         if (auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->getTerminator()))
1179           InsertPt = splitBeforeCatchSwitch(CSI);
1180         else
1181           InsertPt = &*DefBlock->getFirstInsertionPt();
1182       } else {
1183         assert(!I->isTerminator() && "unexpected terminator");
1184         // For all other values, the spill is placed immediately after
1185         // the definition.
1186         InsertPt = I->getNextNode();
1187       }
1188     }
1189 
1190     auto Index = FrameData.getFieldIndex(Def);
1191     Builder.SetInsertPoint(InsertPt);
1192     auto *G = Builder.CreateConstInBoundsGEP2_32(
1193         FrameTy, FramePtr, 0, Index, Def->getName() + Twine(".spill.addr"));
1194     Builder.CreateStore(Def, G);
1195 
1196     BasicBlock *CurrentBlock = nullptr;
1197     Value *CurrentReload = nullptr;
1198     for (auto *U : E.second) {
1199       // If we have not seen the use block, create a load instruction to reload
1200       // the spilled value from the coroutine frame. Populates the Value pointer
1201       // reference provided with the frame GEP.
1202       if (CurrentBlock != U->getParent()) {
1203         CurrentBlock = U->getParent();
1204         Builder.SetInsertPoint(&*CurrentBlock->getFirstInsertionPt());
1205 
1206         auto *GEP = GetFramePointer(E.first);
1207         GEP->setName(E.first->getName() + Twine(".reload.addr"));
1208         CurrentReload = Builder.CreateLoad(
1209             FrameTy->getElementType(FrameData.getFieldIndex(E.first)), GEP,
1210             E.first->getName() + Twine(".reload"));
1211 
1212         TinyPtrVector<DbgDeclareInst *> DIs = FindDbgDeclareUses(Def);
1213         for (DbgDeclareInst *DDI : DIs) {
1214           bool AllowUnresolved = false;
1215           // This dbg.declare is preserved for all coro-split function
1216           // fragments. It will be unreachable in the main function, and
1217           // processed by coro::salvageDebugInfo() by CoroCloner.
1218           DIBuilder(*CurrentBlock->getParent()->getParent(), AllowUnresolved)
1219               .insertDeclare(CurrentReload, DDI->getVariable(),
1220                              DDI->getExpression(), DDI->getDebugLoc(),
1221                              &*Builder.GetInsertPoint());
1222           // This dbg.declare is for the main function entry point.  It
1223           // will be deleted in all coro-split functions.
1224           coro::salvageDebugInfo(DbgPtrAllocaCache, DDI);
1225         }
1226       }
1227 
1228       // If we have a single edge PHINode, remove it and replace it with a
1229       // reload from the coroutine frame. (We already took care of multi edge
1230       // PHINodes by rewriting them in the rewritePHIs function).
1231       if (auto *PN = dyn_cast<PHINode>(U)) {
1232         assert(PN->getNumIncomingValues() == 1 &&
1233                "unexpected number of incoming "
1234                "values in the PHINode");
1235         PN->replaceAllUsesWith(CurrentReload);
1236         PN->eraseFromParent();
1237         continue;
1238       }
1239 
1240       // Replace all uses of CurrentValue in the current instruction with
1241       // reload.
1242       U->replaceUsesOfWith(Def, CurrentReload);
1243     }
1244   }
1245 
1246   BasicBlock *FramePtrBB = FramePtr->getParent();
1247 
1248   auto SpillBlock =
1249       FramePtrBB->splitBasicBlock(FramePtr->getNextNode(), "AllocaSpillBB");
1250   SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill");
1251   Shape.AllocaSpillBlock = SpillBlock;
1252 
1253   // retcon and retcon.once lowering assumes all uses have been sunk.
1254   if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
1255       Shape.ABI == coro::ABI::Async) {
1256     // If we found any allocas, replace all of their remaining uses with Geps.
1257     Builder.SetInsertPoint(&SpillBlock->front());
1258     for (const auto &P : FrameData.Allocas) {
1259       AllocaInst *Alloca = P.Alloca;
1260       auto *G = GetFramePointer(Alloca);
1261 
1262       // We are not using ReplaceInstWithInst(P.first, cast<Instruction>(G))
1263       // here, as we are changing location of the instruction.
1264       G->takeName(Alloca);
1265       Alloca->replaceAllUsesWith(G);
1266       Alloca->eraseFromParent();
1267     }
1268     return FramePtr;
1269   }
1270 
1271   // If we found any alloca, replace all of their remaining uses with GEP
1272   // instructions. Because new dbg.declare have been created for these alloca,
1273   // we also delete the original dbg.declare and replace other uses with undef.
1274   // Note: We cannot replace the alloca with GEP instructions indiscriminately,
1275   // as some of the uses may not be dominated by CoroBegin.
1276   Builder.SetInsertPoint(&Shape.AllocaSpillBlock->front());
1277   SmallVector<Instruction *, 4> UsersToUpdate;
1278   for (const auto &A : FrameData.Allocas) {
1279     AllocaInst *Alloca = A.Alloca;
1280     UsersToUpdate.clear();
1281     for (User *U : Alloca->users()) {
1282       auto *I = cast<Instruction>(U);
1283       if (DT.dominates(CB, I))
1284         UsersToUpdate.push_back(I);
1285     }
1286     if (UsersToUpdate.empty())
1287       continue;
1288     auto *G = GetFramePointer(Alloca);
1289     G->setName(Alloca->getName() + Twine(".reload.addr"));
1290 
1291     SmallPtrSet<BasicBlock *, 4> SeenDbgBBs;
1292     TinyPtrVector<DbgDeclareInst *> DIs = FindDbgDeclareUses(Alloca);
1293     if (!DIs.empty())
1294       DIBuilder(*Alloca->getModule(),
1295                 /*AllowUnresolved*/ false)
1296           .insertDeclare(G, DIs.front()->getVariable(),
1297                          DIs.front()->getExpression(),
1298                          DIs.front()->getDebugLoc(), DIs.front());
1299     for (auto *DI : FindDbgDeclareUses(Alloca))
1300       DI->eraseFromParent();
1301     replaceDbgUsesWithUndef(Alloca);
1302 
1303     for (Instruction *I : UsersToUpdate)
1304       I->replaceUsesOfWith(Alloca, G);
1305   }
1306   Builder.SetInsertPoint(FramePtr->getNextNode());
1307   for (const auto &A : FrameData.Allocas) {
1308     AllocaInst *Alloca = A.Alloca;
1309     if (A.MayWriteBeforeCoroBegin) {
1310       // isEscaped really means potentially modified before CoroBegin.
1311       if (Alloca->isArrayAllocation())
1312         report_fatal_error(
1313             "Coroutines cannot handle copying of array allocas yet");
1314 
1315       auto *G = GetFramePointer(Alloca);
1316       auto *Value = Builder.CreateLoad(Alloca->getAllocatedType(), Alloca);
1317       Builder.CreateStore(Value, G);
1318     }
1319     // For each alias to Alloca created before CoroBegin but used after
1320     // CoroBegin, we recreate them after CoroBegin by appplying the offset
1321     // to the pointer in the frame.
1322     for (const auto &Alias : A.Aliases) {
1323       auto *FramePtr = GetFramePointer(Alloca);
1324       auto *FramePtrRaw =
1325           Builder.CreateBitCast(FramePtr, Type::getInt8PtrTy(C));
1326       auto *AliasPtr = Builder.CreateGEP(
1327           FramePtrRaw,
1328           ConstantInt::get(Type::getInt64Ty(C), Alias.second.getValue()));
1329       auto *AliasPtrTyped =
1330           Builder.CreateBitCast(AliasPtr, Alias.first->getType());
1331       Alias.first->replaceUsesWithIf(
1332           AliasPtrTyped, [&](Use &U) { return DT.dominates(CB, U); });
1333     }
1334   }
1335   return FramePtr;
1336 }
1337 
1338 // Sets the unwind edge of an instruction to a particular successor.
1339 static void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
1340   if (auto *II = dyn_cast<InvokeInst>(TI))
1341     II->setUnwindDest(Succ);
1342   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
1343     CS->setUnwindDest(Succ);
1344   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
1345     CR->setUnwindDest(Succ);
1346   else
1347     llvm_unreachable("unexpected terminator instruction");
1348 }
1349 
1350 // Replaces all uses of OldPred with the NewPred block in all PHINodes in a
1351 // block.
1352 static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
1353                            BasicBlock *NewPred, PHINode *Until = nullptr) {
1354   unsigned BBIdx = 0;
1355   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
1356     PHINode *PN = cast<PHINode>(I);
1357 
1358     // We manually update the LandingPadReplacement PHINode and it is the last
1359     // PHI Node. So, if we find it, we are done.
1360     if (Until == PN)
1361       break;
1362 
1363     // Reuse the previous value of BBIdx if it lines up.  In cases where we
1364     // have multiple phi nodes with *lots* of predecessors, this is a speed
1365     // win because we don't have to scan the PHI looking for TIBB.  This
1366     // happens because the BB list of PHI nodes are usually in the same
1367     // order.
1368     if (PN->getIncomingBlock(BBIdx) != OldPred)
1369       BBIdx = PN->getBasicBlockIndex(OldPred);
1370 
1371     assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!");
1372     PN->setIncomingBlock(BBIdx, NewPred);
1373   }
1374 }
1375 
1376 // Uses SplitEdge unless the successor block is an EHPad, in which case do EH
1377 // specific handling.
1378 static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
1379                                     LandingPadInst *OriginalPad,
1380                                     PHINode *LandingPadReplacement) {
1381   auto *PadInst = Succ->getFirstNonPHI();
1382   if (!LandingPadReplacement && !PadInst->isEHPad())
1383     return SplitEdge(BB, Succ);
1384 
1385   auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ);
1386   setUnwindEdgeTo(BB->getTerminator(), NewBB);
1387   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
1388 
1389   if (LandingPadReplacement) {
1390     auto *NewLP = OriginalPad->clone();
1391     auto *Terminator = BranchInst::Create(Succ, NewBB);
1392     NewLP->insertBefore(Terminator);
1393     LandingPadReplacement->addIncoming(NewLP, NewBB);
1394     return NewBB;
1395   }
1396   Value *ParentPad = nullptr;
1397   if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
1398     ParentPad = FuncletPad->getParentPad();
1399   else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
1400     ParentPad = CatchSwitch->getParentPad();
1401   else
1402     llvm_unreachable("handling for other EHPads not implemented yet");
1403 
1404   auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB);
1405   CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
1406   return NewBB;
1407 }
1408 
1409 // Moves the values in the PHIs in SuccBB that correspong to PredBB into a new
1410 // PHI in InsertedBB.
1411 static void movePHIValuesToInsertedBlock(BasicBlock *SuccBB,
1412                                          BasicBlock *InsertedBB,
1413                                          BasicBlock *PredBB,
1414                                          PHINode *UntilPHI = nullptr) {
1415   auto *PN = cast<PHINode>(&SuccBB->front());
1416   do {
1417     int Index = PN->getBasicBlockIndex(InsertedBB);
1418     Value *V = PN->getIncomingValue(Index);
1419     PHINode *InputV = PHINode::Create(
1420         V->getType(), 1, V->getName() + Twine(".") + SuccBB->getName(),
1421         &InsertedBB->front());
1422     InputV->addIncoming(V, PredBB);
1423     PN->setIncomingValue(Index, InputV);
1424     PN = dyn_cast<PHINode>(PN->getNextNode());
1425   } while (PN != UntilPHI);
1426 }
1427 
1428 // Rewrites the PHI Nodes in a cleanuppad.
1429 static void rewritePHIsForCleanupPad(BasicBlock *CleanupPadBB,
1430                                      CleanupPadInst *CleanupPad) {
1431   // For every incoming edge to a CleanupPad we will create a new block holding
1432   // all incoming values in single-value PHI nodes. We will then create another
1433   // block to act as a dispather (as all unwind edges for related EH blocks
1434   // must be the same).
1435   //
1436   // cleanuppad:
1437   //    %2 = phi i32[%0, %catchswitch], [%1, %catch.1]
1438   //    %3 = cleanuppad within none []
1439   //
1440   // It will create:
1441   //
1442   // cleanuppad.corodispatch
1443   //    %2 = phi i8[0, %catchswitch], [1, %catch.1]
1444   //    %3 = cleanuppad within none []
1445   //    switch i8 % 2, label %unreachable
1446   //            [i8 0, label %cleanuppad.from.catchswitch
1447   //             i8 1, label %cleanuppad.from.catch.1]
1448   // cleanuppad.from.catchswitch:
1449   //    %4 = phi i32 [%0, %catchswitch]
1450   //    br %label cleanuppad
1451   // cleanuppad.from.catch.1:
1452   //    %6 = phi i32 [%1, %catch.1]
1453   //    br %label cleanuppad
1454   // cleanuppad:
1455   //    %8 = phi i32 [%4, %cleanuppad.from.catchswitch],
1456   //                 [%6, %cleanuppad.from.catch.1]
1457 
1458   // Unreachable BB, in case switching on an invalid value in the dispatcher.
1459   auto *UnreachBB = BasicBlock::Create(
1460       CleanupPadBB->getContext(), "unreachable", CleanupPadBB->getParent());
1461   IRBuilder<> Builder(UnreachBB);
1462   Builder.CreateUnreachable();
1463 
1464   // Create a new cleanuppad which will be the dispatcher.
1465   auto *NewCleanupPadBB =
1466       BasicBlock::Create(CleanupPadBB->getContext(),
1467                          CleanupPadBB->getName() + Twine(".corodispatch"),
1468                          CleanupPadBB->getParent(), CleanupPadBB);
1469   Builder.SetInsertPoint(NewCleanupPadBB);
1470   auto *SwitchType = Builder.getInt8Ty();
1471   auto *SetDispatchValuePN =
1472       Builder.CreatePHI(SwitchType, pred_size(CleanupPadBB));
1473   CleanupPad->removeFromParent();
1474   CleanupPad->insertAfter(SetDispatchValuePN);
1475   auto *SwitchOnDispatch = Builder.CreateSwitch(SetDispatchValuePN, UnreachBB,
1476                                                 pred_size(CleanupPadBB));
1477 
1478   int SwitchIndex = 0;
1479   SmallVector<BasicBlock *, 8> Preds(predecessors(CleanupPadBB));
1480   for (BasicBlock *Pred : Preds) {
1481     // Create a new cleanuppad and move the PHI values to there.
1482     auto *CaseBB = BasicBlock::Create(CleanupPadBB->getContext(),
1483                                       CleanupPadBB->getName() +
1484                                           Twine(".from.") + Pred->getName(),
1485                                       CleanupPadBB->getParent(), CleanupPadBB);
1486     updatePhiNodes(CleanupPadBB, Pred, CaseBB);
1487     CaseBB->setName(CleanupPadBB->getName() + Twine(".from.") +
1488                     Pred->getName());
1489     Builder.SetInsertPoint(CaseBB);
1490     Builder.CreateBr(CleanupPadBB);
1491     movePHIValuesToInsertedBlock(CleanupPadBB, CaseBB, NewCleanupPadBB);
1492 
1493     // Update this Pred to the new unwind point.
1494     setUnwindEdgeTo(Pred->getTerminator(), NewCleanupPadBB);
1495 
1496     // Setup the switch in the dispatcher.
1497     auto *SwitchConstant = ConstantInt::get(SwitchType, SwitchIndex);
1498     SetDispatchValuePN->addIncoming(SwitchConstant, Pred);
1499     SwitchOnDispatch->addCase(SwitchConstant, CaseBB);
1500     SwitchIndex++;
1501   }
1502 }
1503 
1504 static void rewritePHIs(BasicBlock &BB) {
1505   // For every incoming edge we will create a block holding all
1506   // incoming values in a single PHI nodes.
1507   //
1508   // loop:
1509   //    %n.val = phi i32[%n, %entry], [%inc, %loop]
1510   //
1511   // It will create:
1512   //
1513   // loop.from.entry:
1514   //    %n.loop.pre = phi i32 [%n, %entry]
1515   //    br %label loop
1516   // loop.from.loop:
1517   //    %inc.loop.pre = phi i32 [%inc, %loop]
1518   //    br %label loop
1519   //
1520   // After this rewrite, further analysis will ignore any phi nodes with more
1521   // than one incoming edge.
1522 
1523   // TODO: Simplify PHINodes in the basic block to remove duplicate
1524   // predecessors.
1525 
1526   // Special case for CleanupPad: all EH blocks must have the same unwind edge
1527   // so we need to create an additional "dispatcher" block.
1528   if (auto *CleanupPad =
1529           dyn_cast_or_null<CleanupPadInst>(BB.getFirstNonPHI())) {
1530     SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
1531     for (BasicBlock *Pred : Preds) {
1532       if (CatchSwitchInst *CS =
1533               dyn_cast<CatchSwitchInst>(Pred->getTerminator())) {
1534         // CleanupPad with a CatchSwitch predecessor: therefore this is an
1535         // unwind destination that needs to be handle specially.
1536         assert(CS->getUnwindDest() == &BB);
1537         (void)CS;
1538         rewritePHIsForCleanupPad(&BB, CleanupPad);
1539         return;
1540       }
1541     }
1542   }
1543 
1544   LandingPadInst *LandingPad = nullptr;
1545   PHINode *ReplPHI = nullptr;
1546   if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) {
1547     // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
1548     // We replace the original landing pad with a PHINode that will collect the
1549     // results from all of them.
1550     ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad);
1551     ReplPHI->takeName(LandingPad);
1552     LandingPad->replaceAllUsesWith(ReplPHI);
1553     // We will erase the original landing pad at the end of this function after
1554     // ehAwareSplitEdge cloned it in the transition blocks.
1555   }
1556 
1557   SmallVector<BasicBlock *, 8> Preds(predecessors(&BB));
1558   for (BasicBlock *Pred : Preds) {
1559     auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI);
1560     IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName());
1561 
1562     // Stop the moving of values at ReplPHI, as this is either null or the PHI
1563     // that replaced the landing pad.
1564     movePHIValuesToInsertedBlock(&BB, IncomingBB, Pred, ReplPHI);
1565   }
1566 
1567   if (LandingPad) {
1568     // Calls to ehAwareSplitEdge function cloned the original lading pad.
1569     // No longer need it.
1570     LandingPad->eraseFromParent();
1571   }
1572 }
1573 
1574 static void rewritePHIs(Function &F) {
1575   SmallVector<BasicBlock *, 8> WorkList;
1576 
1577   for (BasicBlock &BB : F)
1578     if (auto *PN = dyn_cast<PHINode>(&BB.front()))
1579       if (PN->getNumIncomingValues() > 1)
1580         WorkList.push_back(&BB);
1581 
1582   for (BasicBlock *BB : WorkList)
1583     rewritePHIs(*BB);
1584 }
1585 
1586 // Check for instructions that we can recreate on resume as opposed to spill
1587 // the result into a coroutine frame.
1588 static bool materializable(Instruction &V) {
1589   return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) ||
1590          isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V);
1591 }
1592 
1593 // Check for structural coroutine intrinsics that should not be spilled into
1594 // the coroutine frame.
1595 static bool isCoroutineStructureIntrinsic(Instruction &I) {
1596   return isa<CoroIdInst>(&I) || isa<CoroSaveInst>(&I) ||
1597          isa<CoroSuspendInst>(&I);
1598 }
1599 
1600 // For every use of the value that is across suspend point, recreate that value
1601 // after a suspend point.
1602 static void rewriteMaterializableInstructions(IRBuilder<> &IRB,
1603                                               const SpillInfo &Spills) {
1604   for (const auto &E : Spills) {
1605     Value *Def = E.first;
1606     BasicBlock *CurrentBlock = nullptr;
1607     Instruction *CurrentMaterialization = nullptr;
1608     for (Instruction *U : E.second) {
1609       // If we have not seen this block, materialize the value.
1610       if (CurrentBlock != U->getParent()) {
1611         CurrentBlock = U->getParent();
1612         CurrentMaterialization = cast<Instruction>(Def)->clone();
1613         CurrentMaterialization->setName(Def->getName());
1614         CurrentMaterialization->insertBefore(
1615             &*CurrentBlock->getFirstInsertionPt());
1616       }
1617       if (auto *PN = dyn_cast<PHINode>(U)) {
1618         assert(PN->getNumIncomingValues() == 1 &&
1619                "unexpected number of incoming "
1620                "values in the PHINode");
1621         PN->replaceAllUsesWith(CurrentMaterialization);
1622         PN->eraseFromParent();
1623         continue;
1624       }
1625       // Replace all uses of Def in the current instruction with the
1626       // CurrentMaterialization for the block.
1627       U->replaceUsesOfWith(Def, CurrentMaterialization);
1628     }
1629   }
1630 }
1631 
1632 // Splits the block at a particular instruction unless it is the first
1633 // instruction in the block with a single predecessor.
1634 static BasicBlock *splitBlockIfNotFirst(Instruction *I, const Twine &Name) {
1635   auto *BB = I->getParent();
1636   if (&BB->front() == I) {
1637     if (BB->getSinglePredecessor()) {
1638       BB->setName(Name);
1639       return BB;
1640     }
1641   }
1642   return BB->splitBasicBlock(I, Name);
1643 }
1644 
1645 // Split above and below a particular instruction so that it
1646 // will be all alone by itself in a block.
1647 static void splitAround(Instruction *I, const Twine &Name) {
1648   splitBlockIfNotFirst(I, Name);
1649   splitBlockIfNotFirst(I->getNextNode(), "After" + Name);
1650 }
1651 
1652 static bool isSuspendBlock(BasicBlock *BB) {
1653   return isa<AnyCoroSuspendInst>(BB->front());
1654 }
1655 
1656 typedef SmallPtrSet<BasicBlock*, 8> VisitedBlocksSet;
1657 
1658 /// Does control flow starting at the given block ever reach a suspend
1659 /// instruction before reaching a block in VisitedOrFreeBBs?
1660 static bool isSuspendReachableFrom(BasicBlock *From,
1661                                    VisitedBlocksSet &VisitedOrFreeBBs) {
1662   // Eagerly try to add this block to the visited set.  If it's already
1663   // there, stop recursing; this path doesn't reach a suspend before
1664   // either looping or reaching a freeing block.
1665   if (!VisitedOrFreeBBs.insert(From).second)
1666     return false;
1667 
1668   // We assume that we'll already have split suspends into their own blocks.
1669   if (isSuspendBlock(From))
1670     return true;
1671 
1672   // Recurse on the successors.
1673   for (auto Succ : successors(From)) {
1674     if (isSuspendReachableFrom(Succ, VisitedOrFreeBBs))
1675       return true;
1676   }
1677 
1678   return false;
1679 }
1680 
1681 /// Is the given alloca "local", i.e. bounded in lifetime to not cross a
1682 /// suspend point?
1683 static bool isLocalAlloca(CoroAllocaAllocInst *AI) {
1684   // Seed the visited set with all the basic blocks containing a free
1685   // so that we won't pass them up.
1686   VisitedBlocksSet VisitedOrFreeBBs;
1687   for (auto User : AI->users()) {
1688     if (auto FI = dyn_cast<CoroAllocaFreeInst>(User))
1689       VisitedOrFreeBBs.insert(FI->getParent());
1690   }
1691 
1692   return !isSuspendReachableFrom(AI->getParent(), VisitedOrFreeBBs);
1693 }
1694 
1695 /// After we split the coroutine, will the given basic block be along
1696 /// an obvious exit path for the resumption function?
1697 static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB,
1698                                               unsigned depth = 3) {
1699   // If we've bottomed out our depth count, stop searching and assume
1700   // that the path might loop back.
1701   if (depth == 0) return false;
1702 
1703   // If this is a suspend block, we're about to exit the resumption function.
1704   if (isSuspendBlock(BB)) return true;
1705 
1706   // Recurse into the successors.
1707   for (auto Succ : successors(BB)) {
1708     if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1))
1709       return false;
1710   }
1711 
1712   // If none of the successors leads back in a loop, we're on an exit/abort.
1713   return true;
1714 }
1715 
1716 static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI) {
1717   // Look for a free that isn't sufficiently obviously followed by
1718   // either a suspend or a termination, i.e. something that will leave
1719   // the coro resumption frame.
1720   for (auto U : AI->users()) {
1721     auto FI = dyn_cast<CoroAllocaFreeInst>(U);
1722     if (!FI) continue;
1723 
1724     if (!willLeaveFunctionImmediatelyAfter(FI->getParent()))
1725       return true;
1726   }
1727 
1728   // If we never found one, we don't need a stack save.
1729   return false;
1730 }
1731 
1732 /// Turn each of the given local allocas into a normal (dynamic) alloca
1733 /// instruction.
1734 static void lowerLocalAllocas(ArrayRef<CoroAllocaAllocInst*> LocalAllocas,
1735                               SmallVectorImpl<Instruction*> &DeadInsts) {
1736   for (auto AI : LocalAllocas) {
1737     auto M = AI->getModule();
1738     IRBuilder<> Builder(AI);
1739 
1740     // Save the stack depth.  Try to avoid doing this if the stackrestore
1741     // is going to immediately precede a return or something.
1742     Value *StackSave = nullptr;
1743     if (localAllocaNeedsStackSave(AI))
1744       StackSave = Builder.CreateCall(
1745                             Intrinsic::getDeclaration(M, Intrinsic::stacksave));
1746 
1747     // Allocate memory.
1748     auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize());
1749     Alloca->setAlignment(Align(AI->getAlignment()));
1750 
1751     for (auto U : AI->users()) {
1752       // Replace gets with the allocation.
1753       if (isa<CoroAllocaGetInst>(U)) {
1754         U->replaceAllUsesWith(Alloca);
1755 
1756       // Replace frees with stackrestores.  This is safe because
1757       // alloca.alloc is required to obey a stack discipline, although we
1758       // don't enforce that structurally.
1759       } else {
1760         auto FI = cast<CoroAllocaFreeInst>(U);
1761         if (StackSave) {
1762           Builder.SetInsertPoint(FI);
1763           Builder.CreateCall(
1764                     Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
1765                              StackSave);
1766         }
1767       }
1768       DeadInsts.push_back(cast<Instruction>(U));
1769     }
1770 
1771     DeadInsts.push_back(AI);
1772   }
1773 }
1774 
1775 /// Turn the given coro.alloca.alloc call into a dynamic allocation.
1776 /// This happens during the all-instructions iteration, so it must not
1777 /// delete the call.
1778 static Instruction *lowerNonLocalAlloca(CoroAllocaAllocInst *AI,
1779                                         coro::Shape &Shape,
1780                                    SmallVectorImpl<Instruction*> &DeadInsts) {
1781   IRBuilder<> Builder(AI);
1782   auto Alloc = Shape.emitAlloc(Builder, AI->getSize(), nullptr);
1783 
1784   for (User *U : AI->users()) {
1785     if (isa<CoroAllocaGetInst>(U)) {
1786       U->replaceAllUsesWith(Alloc);
1787     } else {
1788       auto FI = cast<CoroAllocaFreeInst>(U);
1789       Builder.SetInsertPoint(FI);
1790       Shape.emitDealloc(Builder, Alloc, nullptr);
1791     }
1792     DeadInsts.push_back(cast<Instruction>(U));
1793   }
1794 
1795   // Push this on last so that it gets deleted after all the others.
1796   DeadInsts.push_back(AI);
1797 
1798   // Return the new allocation value so that we can check for needed spills.
1799   return cast<Instruction>(Alloc);
1800 }
1801 
1802 /// Get the current swifterror value.
1803 static Value *emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy,
1804                                      coro::Shape &Shape) {
1805   // Make a fake function pointer as a sort of intrinsic.
1806   auto FnTy = FunctionType::get(ValueTy, {}, false);
1807   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1808 
1809   auto Call = Builder.CreateCall(FnTy, Fn, {});
1810   Shape.SwiftErrorOps.push_back(Call);
1811 
1812   return Call;
1813 }
1814 
1815 /// Set the given value as the current swifterror value.
1816 ///
1817 /// Returns a slot that can be used as a swifterror slot.
1818 static Value *emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V,
1819                                      coro::Shape &Shape) {
1820   // Make a fake function pointer as a sort of intrinsic.
1821   auto FnTy = FunctionType::get(V->getType()->getPointerTo(),
1822                                 {V->getType()}, false);
1823   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1824 
1825   auto Call = Builder.CreateCall(FnTy, Fn, { V });
1826   Shape.SwiftErrorOps.push_back(Call);
1827 
1828   return Call;
1829 }
1830 
1831 /// Set the swifterror value from the given alloca before a call,
1832 /// then put in back in the alloca afterwards.
1833 ///
1834 /// Returns an address that will stand in for the swifterror slot
1835 /// until splitting.
1836 static Value *emitSetAndGetSwiftErrorValueAround(Instruction *Call,
1837                                                  AllocaInst *Alloca,
1838                                                  coro::Shape &Shape) {
1839   auto ValueTy = Alloca->getAllocatedType();
1840   IRBuilder<> Builder(Call);
1841 
1842   // Load the current value from the alloca and set it as the
1843   // swifterror value.
1844   auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca);
1845   auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape);
1846 
1847   // Move to after the call.  Since swifterror only has a guaranteed
1848   // value on normal exits, we can ignore implicit and explicit unwind
1849   // edges.
1850   if (isa<CallInst>(Call)) {
1851     Builder.SetInsertPoint(Call->getNextNode());
1852   } else {
1853     auto Invoke = cast<InvokeInst>(Call);
1854     Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg());
1855   }
1856 
1857   // Get the current swifterror value and store it to the alloca.
1858   auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape);
1859   Builder.CreateStore(ValueAfterCall, Alloca);
1860 
1861   return Addr;
1862 }
1863 
1864 /// Eliminate a formerly-swifterror alloca by inserting the get/set
1865 /// intrinsics and attempting to MemToReg the alloca away.
1866 static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca,
1867                                       coro::Shape &Shape) {
1868   for (auto UI = Alloca->use_begin(), UE = Alloca->use_end(); UI != UE; ) {
1869     // We're likely changing the use list, so use a mutation-safe
1870     // iteration pattern.
1871     auto &Use = *UI;
1872     ++UI;
1873 
1874     // swifterror values can only be used in very specific ways.
1875     // We take advantage of that here.
1876     auto User = Use.getUser();
1877     if (isa<LoadInst>(User) || isa<StoreInst>(User))
1878       continue;
1879 
1880     assert(isa<CallInst>(User) || isa<InvokeInst>(User));
1881     auto Call = cast<Instruction>(User);
1882 
1883     auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape);
1884 
1885     // Use the returned slot address as the call argument.
1886     Use.set(Addr);
1887   }
1888 
1889   // All the uses should be loads and stores now.
1890   assert(isAllocaPromotable(Alloca));
1891 }
1892 
1893 /// "Eliminate" a swifterror argument by reducing it to the alloca case
1894 /// and then loading and storing in the prologue and epilog.
1895 ///
1896 /// The argument keeps the swifterror flag.
1897 static void eliminateSwiftErrorArgument(Function &F, Argument &Arg,
1898                                         coro::Shape &Shape,
1899                              SmallVectorImpl<AllocaInst*> &AllocasToPromote) {
1900   IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
1901 
1902   auto ArgTy = cast<PointerType>(Arg.getType());
1903   auto ValueTy = ArgTy->getElementType();
1904 
1905   // Reduce to the alloca case:
1906 
1907   // Create an alloca and replace all uses of the arg with it.
1908   auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace());
1909   Arg.replaceAllUsesWith(Alloca);
1910 
1911   // Set an initial value in the alloca.  swifterror is always null on entry.
1912   auto InitialValue = Constant::getNullValue(ValueTy);
1913   Builder.CreateStore(InitialValue, Alloca);
1914 
1915   // Find all the suspends in the function and save and restore around them.
1916   for (auto Suspend : Shape.CoroSuspends) {
1917     (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape);
1918   }
1919 
1920   // Find all the coro.ends in the function and restore the error value.
1921   for (auto End : Shape.CoroEnds) {
1922     Builder.SetInsertPoint(End);
1923     auto FinalValue = Builder.CreateLoad(ValueTy, Alloca);
1924     (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape);
1925   }
1926 
1927   // Now we can use the alloca logic.
1928   AllocasToPromote.push_back(Alloca);
1929   eliminateSwiftErrorAlloca(F, Alloca, Shape);
1930 }
1931 
1932 /// Eliminate all problematic uses of swifterror arguments and allocas
1933 /// from the function.  We'll fix them up later when splitting the function.
1934 static void eliminateSwiftError(Function &F, coro::Shape &Shape) {
1935   SmallVector<AllocaInst*, 4> AllocasToPromote;
1936 
1937   // Look for a swifterror argument.
1938   for (auto &Arg : F.args()) {
1939     if (!Arg.hasSwiftErrorAttr()) continue;
1940 
1941     eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote);
1942     break;
1943   }
1944 
1945   // Look for swifterror allocas.
1946   for (auto &Inst : F.getEntryBlock()) {
1947     auto Alloca = dyn_cast<AllocaInst>(&Inst);
1948     if (!Alloca || !Alloca->isSwiftError()) continue;
1949 
1950     // Clear the swifterror flag.
1951     Alloca->setSwiftError(false);
1952 
1953     AllocasToPromote.push_back(Alloca);
1954     eliminateSwiftErrorAlloca(F, Alloca, Shape);
1955   }
1956 
1957   // If we have any allocas to promote, compute a dominator tree and
1958   // promote them en masse.
1959   if (!AllocasToPromote.empty()) {
1960     DominatorTree DT(F);
1961     PromoteMemToReg(AllocasToPromote, DT);
1962   }
1963 }
1964 
1965 /// retcon and retcon.once conventions assume that all spill uses can be sunk
1966 /// after the coro.begin intrinsic.
1967 static void sinkSpillUsesAfterCoroBegin(Function &F,
1968                                         const FrameDataInfo &FrameData,
1969                                         CoroBeginInst *CoroBegin) {
1970   DominatorTree Dom(F);
1971 
1972   SmallSetVector<Instruction *, 32> ToMove;
1973   SmallVector<Instruction *, 32> Worklist;
1974 
1975   // Collect all users that precede coro.begin.
1976   for (auto *Def : FrameData.getAllDefs()) {
1977     for (User *U : Def->users()) {
1978       auto Inst = cast<Instruction>(U);
1979       if (Inst->getParent() != CoroBegin->getParent() ||
1980           Dom.dominates(CoroBegin, Inst))
1981         continue;
1982       if (ToMove.insert(Inst))
1983         Worklist.push_back(Inst);
1984     }
1985   }
1986   // Recursively collect users before coro.begin.
1987   while (!Worklist.empty()) {
1988     auto *Def = Worklist.pop_back_val();
1989     for (User *U : Def->users()) {
1990       auto Inst = cast<Instruction>(U);
1991       if (Dom.dominates(CoroBegin, Inst))
1992         continue;
1993       if (ToMove.insert(Inst))
1994         Worklist.push_back(Inst);
1995     }
1996   }
1997 
1998   // Sort by dominance.
1999   SmallVector<Instruction *, 64> InsertionList(ToMove.begin(), ToMove.end());
2000   llvm::sort(InsertionList, [&Dom](Instruction *A, Instruction *B) -> bool {
2001     // If a dominates b it should preceed (<) b.
2002     return Dom.dominates(A, B);
2003   });
2004 
2005   Instruction *InsertPt = CoroBegin->getNextNode();
2006   for (Instruction *Inst : InsertionList)
2007     Inst->moveBefore(InsertPt);
2008 }
2009 
2010 /// For each local variable that all of its user are only used inside one of
2011 /// suspended region, we sink their lifetime.start markers to the place where
2012 /// after the suspend block. Doing so minimizes the lifetime of each variable,
2013 /// hence minimizing the amount of data we end up putting on the frame.
2014 static void sinkLifetimeStartMarkers(Function &F, coro::Shape &Shape,
2015                                      SuspendCrossingInfo &Checker) {
2016   DominatorTree DT(F);
2017 
2018   // Collect all possible basic blocks which may dominate all uses of allocas.
2019   SmallPtrSet<BasicBlock *, 4> DomSet;
2020   DomSet.insert(&F.getEntryBlock());
2021   for (auto *CSI : Shape.CoroSuspends) {
2022     BasicBlock *SuspendBlock = CSI->getParent();
2023     assert(isSuspendBlock(SuspendBlock) && SuspendBlock->getSingleSuccessor() &&
2024            "should have split coro.suspend into its own block");
2025     DomSet.insert(SuspendBlock->getSingleSuccessor());
2026   }
2027 
2028   for (Instruction &I : instructions(F)) {
2029     AllocaInst* AI = dyn_cast<AllocaInst>(&I);
2030     if (!AI)
2031       continue;
2032 
2033     for (BasicBlock *DomBB : DomSet) {
2034       bool Valid = true;
2035       SmallVector<Instruction *, 1> Lifetimes;
2036 
2037       auto isLifetimeStart = [](Instruction* I) {
2038         if (auto* II = dyn_cast<IntrinsicInst>(I))
2039           return II->getIntrinsicID() == Intrinsic::lifetime_start;
2040         return false;
2041       };
2042 
2043       auto collectLifetimeStart = [&](Instruction *U, AllocaInst *AI) {
2044         if (isLifetimeStart(U)) {
2045           Lifetimes.push_back(U);
2046           return true;
2047         }
2048         if (!U->hasOneUse() || U->stripPointerCasts() != AI)
2049           return false;
2050         if (isLifetimeStart(U->user_back())) {
2051           Lifetimes.push_back(U->user_back());
2052           return true;
2053         }
2054         return false;
2055       };
2056 
2057       for (User *U : AI->users()) {
2058         Instruction *UI = cast<Instruction>(U);
2059         // For all users except lifetime.start markers, if they are all
2060         // dominated by one of the basic blocks and do not cross
2061         // suspend points as well, then there is no need to spill the
2062         // instruction.
2063         if (!DT.dominates(DomBB, UI->getParent()) ||
2064             Checker.isDefinitionAcrossSuspend(DomBB, UI)) {
2065           // Skip lifetime.start, GEP and bitcast used by lifetime.start
2066           // markers.
2067           if (collectLifetimeStart(UI, AI))
2068             continue;
2069           Valid = false;
2070           break;
2071         }
2072       }
2073       // Sink lifetime.start markers to dominate block when they are
2074       // only used outside the region.
2075       if (Valid && Lifetimes.size() != 0) {
2076         // May be AI itself, when the type of AI is i8*
2077         auto *NewBitCast = [&](AllocaInst *AI) -> Value* {
2078           if (isa<AllocaInst>(Lifetimes[0]->getOperand(1)))
2079             return AI;
2080           auto *Int8PtrTy = Type::getInt8PtrTy(F.getContext());
2081           return CastInst::Create(Instruction::BitCast, AI, Int8PtrTy, "",
2082                                   DomBB->getTerminator());
2083         }(AI);
2084 
2085         auto *NewLifetime = Lifetimes[0]->clone();
2086         NewLifetime->replaceUsesOfWith(NewLifetime->getOperand(1), NewBitCast);
2087         NewLifetime->insertBefore(DomBB->getTerminator());
2088 
2089         // All the outsided lifetime.start markers are no longer necessary.
2090         for (Instruction *S : Lifetimes)
2091           S->eraseFromParent();
2092 
2093         break;
2094       }
2095     }
2096   }
2097 }
2098 
2099 static void collectFrameAllocas(Function &F, coro::Shape &Shape,
2100                                 const SuspendCrossingInfo &Checker,
2101                                 SmallVectorImpl<AllocaInfo> &Allocas) {
2102   // Collect lifetime.start info for each alloca.
2103   using LifetimeStart = SmallPtrSet<Instruction *, 2>;
2104   llvm::DenseMap<AllocaInst *, std::unique_ptr<LifetimeStart>> LifetimeMap;
2105   for (Instruction &I : instructions(F)) {
2106     auto *II = dyn_cast<IntrinsicInst>(&I);
2107     if (!II || II->getIntrinsicID() != Intrinsic::lifetime_start)
2108       continue;
2109 
2110     if (auto *OpInst = dyn_cast<Instruction>(II->getOperand(1))) {
2111       if (auto *AI = dyn_cast<AllocaInst>(OpInst->stripPointerCasts())) {
2112 
2113         if (LifetimeMap.find(AI) == LifetimeMap.end())
2114           LifetimeMap[AI] = std::make_unique<LifetimeStart>();
2115         LifetimeMap[AI]->insert(isa<AllocaInst>(OpInst) ? II : OpInst);
2116       }
2117     }
2118   }
2119 
2120   for (Instruction &I : instructions(F)) {
2121     auto *AI = dyn_cast<AllocaInst>(&I);
2122     if (!AI)
2123       continue;
2124     // The PromiseAlloca will be specially handled since it needs to be in a
2125     // fixed position in the frame.
2126     if (AI == Shape.SwitchLowering.PromiseAlloca) {
2127       continue;
2128     }
2129     bool ShouldLiveOnFrame = false;
2130     auto Iter = LifetimeMap.find(AI);
2131     if (Iter != LifetimeMap.end()) {
2132       // Check against lifetime.start if the instruction has the info.
2133       for (User *U : I.users()) {
2134         for (auto *S : *Iter->second)
2135           if ((ShouldLiveOnFrame = Checker.isDefinitionAcrossSuspend(*S, U)))
2136             break;
2137         if (ShouldLiveOnFrame)
2138           break;
2139       }
2140       if (!ShouldLiveOnFrame)
2141         continue;
2142     }
2143     // At this point, either ShouldLiveOnFrame is true or we didn't have
2144     // lifetime information. We will need to rely on more precise pointer
2145     // tracking.
2146     DominatorTree DT(F);
2147     AllocaUseVisitor Visitor{F.getParent()->getDataLayout(), DT,
2148                              *Shape.CoroBegin, Checker};
2149     Visitor.visitPtr(*AI);
2150     if (!Visitor.getShouldLiveOnFrame())
2151       continue;
2152     Allocas.emplace_back(AI, Visitor.getAliasesCopy(),
2153                          Visitor.getMayWriteBeforeCoroBegin());
2154   }
2155 }
2156 
2157 void coro::salvageDebugInfo(
2158     SmallDenseMap<llvm::Value *, llvm::AllocaInst *, 4> &DbgPtrAllocaCache,
2159     DbgDeclareInst *DDI) {
2160   Function *F = DDI->getFunction();
2161   IRBuilder<> Builder(F->getContext());
2162   auto InsertPt = F->getEntryBlock().getFirstInsertionPt();
2163   while (isa<IntrinsicInst>(InsertPt))
2164     ++InsertPt;
2165   Builder.SetInsertPoint(&F->getEntryBlock(), InsertPt);
2166   DIExpression *Expr = DDI->getExpression();
2167   // Follow the pointer arithmetic all the way to the incoming
2168   // function argument and convert into a DIExpression.
2169   bool OutermostLoad = true;
2170   Value *Storage = DDI->getAddress();
2171   while (Storage) {
2172     if (auto *LdInst = dyn_cast<LoadInst>(Storage)) {
2173       Storage = LdInst->getOperand(0);
2174       // FIXME: This is a heuristic that works around the fact that
2175       // LLVM IR debug intrinsics cannot yet distinguish between
2176       // memory and value locations: Because a dbg.declare(alloca) is
2177       // implicitly a memory location no DW_OP_deref operation for the
2178       // last direct load from an alloca is necessary.  This condition
2179       // effectively drops the *last* DW_OP_deref in the expression.
2180       if (!OutermostLoad)
2181         Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2182       OutermostLoad = false;
2183     } else if (auto *StInst = dyn_cast<StoreInst>(Storage)) {
2184       Storage = StInst->getOperand(0);
2185     } else if (auto *GEPInst = dyn_cast<GetElementPtrInst>(Storage)) {
2186       Expr = llvm::salvageDebugInfoImpl(*GEPInst, Expr,
2187                                         /*WithStackValue=*/false);
2188       Storage = GEPInst->getOperand(0);
2189     } else if (auto *BCInst = dyn_cast<llvm::BitCastInst>(Storage))
2190       Storage = BCInst->getOperand(0);
2191     else
2192       break;
2193   }
2194   // Store a pointer to the coroutine frame object in an alloca so it
2195   // is available throughout the function when producing unoptimized
2196   // code. Extending the lifetime this way is correct because the
2197   // variable has been declared by a dbg.declare intrinsic.
2198   if (auto Arg = dyn_cast_or_null<llvm::Argument>(Storage)) {
2199     auto &Cached = DbgPtrAllocaCache[Storage];
2200     if (!Cached) {
2201       Cached = Builder.CreateAlloca(Storage->getType(), 0, nullptr,
2202                                     Arg->getName() + ".debug");
2203       Builder.CreateStore(Storage, Cached);
2204     }
2205     Storage = Cached;
2206     // FIXME: LLVM lacks nuanced semantics to differentiate between
2207     // memory and direct locations at the IR level. The backend will
2208     // turn a dbg.declare(alloca, ..., DIExpression()) into a memory
2209     // location. Thus, if there are deref and offset operations in the
2210     // expression, we need to add a DW_OP_deref at the *start* of the
2211     // expression to first load the contents of the alloca before
2212     // adjusting it with the expression.
2213     if (Expr && Expr->isComplex())
2214       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
2215   }
2216   auto &VMContext = DDI->getFunction()->getContext();
2217   DDI->setOperand(
2218       0, MetadataAsValue::get(VMContext, ValueAsMetadata::get(Storage)));
2219   DDI->setOperand(2, MetadataAsValue::get(VMContext, Expr));
2220   if (auto *InsertPt = dyn_cast_or_null<Instruction>(Storage))
2221     DDI->moveAfter(InsertPt);
2222 }
2223 
2224 void coro::buildCoroutineFrame(Function &F, Shape &Shape) {
2225   eliminateSwiftError(F, Shape);
2226 
2227   if (Shape.ABI == coro::ABI::Switch &&
2228       Shape.SwitchLowering.PromiseAlloca) {
2229     Shape.getSwitchCoroId()->clearPromise();
2230   }
2231 
2232   // Make sure that all coro.save, coro.suspend and the fallthrough coro.end
2233   // intrinsics are in their own blocks to simplify the logic of building up
2234   // SuspendCrossing data.
2235   for (auto *CSI : Shape.CoroSuspends) {
2236     if (auto *Save = CSI->getCoroSave())
2237       splitAround(Save, "CoroSave");
2238     splitAround(CSI, "CoroSuspend");
2239   }
2240 
2241   // Put CoroEnds into their own blocks.
2242   for (AnyCoroEndInst *CE : Shape.CoroEnds) {
2243     splitAround(CE, "CoroEnd");
2244 
2245     // Emit the musttail call function in a new block before the CoroEnd.
2246     // We do this here so that the right suspend crossing info is computed for
2247     // the uses of the musttail call function call. (Arguments to the coro.end
2248     // instructions would be ignored)
2249     if (auto *AsyncEnd = dyn_cast<CoroAsyncEndInst>(CE)) {
2250       auto *MustTailCallFn = AsyncEnd->getMustTailCallFunction();
2251       if (!MustTailCallFn)
2252         continue;
2253       IRBuilder<> Builder(AsyncEnd);
2254       SmallVector<Value *, 8> Args(AsyncEnd->args());
2255       auto Arguments = ArrayRef<Value *>(Args).drop_front(3);
2256       auto *Call = createMustTailCall(AsyncEnd->getDebugLoc(), MustTailCallFn,
2257                                       Arguments, Builder);
2258       splitAround(Call, "MustTailCall.Before.CoroEnd");
2259     }
2260   }
2261 
2262   // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will
2263   // never has its definition separated from the PHI by the suspend point.
2264   rewritePHIs(F);
2265 
2266   // Build suspend crossing info.
2267   SuspendCrossingInfo Checker(F, Shape);
2268 
2269   IRBuilder<> Builder(F.getContext());
2270   FrameDataInfo FrameData;
2271   SmallVector<CoroAllocaAllocInst*, 4> LocalAllocas;
2272   SmallVector<Instruction*, 4> DeadInstructions;
2273 
2274   {
2275     SpillInfo Spills;
2276     for (int Repeat = 0; Repeat < 4; ++Repeat) {
2277       // See if there are materializable instructions across suspend points.
2278       for (Instruction &I : instructions(F))
2279         if (materializable(I))
2280           for (User *U : I.users())
2281             if (Checker.isDefinitionAcrossSuspend(I, U))
2282               Spills[&I].push_back(cast<Instruction>(U));
2283 
2284       if (Spills.empty())
2285         break;
2286 
2287       // Rewrite materializable instructions to be materialized at the use
2288       // point.
2289       LLVM_DEBUG(dumpSpills("Materializations", Spills));
2290       rewriteMaterializableInstructions(Builder, Spills);
2291       Spills.clear();
2292     }
2293   }
2294 
2295   sinkLifetimeStartMarkers(F, Shape, Checker);
2296   collectFrameAllocas(F, Shape, Checker, FrameData.Allocas);
2297   LLVM_DEBUG(dumpAllocas(FrameData.Allocas));
2298 
2299   // Collect the spills for arguments and other not-materializable values.
2300   for (Argument &A : F.args())
2301     for (User *U : A.users())
2302       if (Checker.isDefinitionAcrossSuspend(A, U))
2303         FrameData.Spills[&A].push_back(cast<Instruction>(U));
2304 
2305   for (Instruction &I : instructions(F)) {
2306     // Values returned from coroutine structure intrinsics should not be part
2307     // of the Coroutine Frame.
2308     if (isCoroutineStructureIntrinsic(I) || &I == Shape.CoroBegin)
2309       continue;
2310 
2311     // The Coroutine Promise always included into coroutine frame, no need to
2312     // check for suspend crossing.
2313     if (Shape.ABI == coro::ABI::Switch &&
2314         Shape.SwitchLowering.PromiseAlloca == &I)
2315       continue;
2316 
2317     // Handle alloca.alloc specially here.
2318     if (auto AI = dyn_cast<CoroAllocaAllocInst>(&I)) {
2319       // Check whether the alloca's lifetime is bounded by suspend points.
2320       if (isLocalAlloca(AI)) {
2321         LocalAllocas.push_back(AI);
2322         continue;
2323       }
2324 
2325       // If not, do a quick rewrite of the alloca and then add spills of
2326       // the rewritten value.  The rewrite doesn't invalidate anything in
2327       // Spills because the other alloca intrinsics have no other operands
2328       // besides AI, and it doesn't invalidate the iteration because we delay
2329       // erasing AI.
2330       auto Alloc = lowerNonLocalAlloca(AI, Shape, DeadInstructions);
2331 
2332       for (User *U : Alloc->users()) {
2333         if (Checker.isDefinitionAcrossSuspend(*Alloc, U))
2334           FrameData.Spills[Alloc].push_back(cast<Instruction>(U));
2335       }
2336       continue;
2337     }
2338 
2339     // Ignore alloca.get; we process this as part of coro.alloca.alloc.
2340     if (isa<CoroAllocaGetInst>(I))
2341       continue;
2342 
2343     if (isa<AllocaInst>(I))
2344       continue;
2345 
2346     for (User *U : I.users())
2347       if (Checker.isDefinitionAcrossSuspend(I, U)) {
2348         // We cannot spill a token.
2349         if (I.getType()->isTokenTy())
2350           report_fatal_error(
2351               "token definition is separated from the use by a suspend point");
2352         FrameData.Spills[&I].push_back(cast<Instruction>(U));
2353       }
2354   }
2355   LLVM_DEBUG(dumpSpills("Spills", FrameData.Spills));
2356   if (Shape.ABI == coro::ABI::Retcon || Shape.ABI == coro::ABI::RetconOnce ||
2357       Shape.ABI == coro::ABI::Async)
2358     sinkSpillUsesAfterCoroBegin(F, FrameData, Shape.CoroBegin);
2359   Shape.FrameTy = buildFrameType(F, Shape, FrameData);
2360   Shape.FramePtr = insertSpills(FrameData, Shape);
2361   lowerLocalAllocas(LocalAllocas, DeadInstructions);
2362 
2363   for (auto I : DeadInstructions)
2364     I->eraseFromParent();
2365 }
2366