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