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 // TODO: pack values tightly using liveness info.
17 //===----------------------------------------------------------------------===//
18 
19 #include "CoroInternal.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Analysis/PtrUseVisitor.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/circular_raw_ostream.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
34 
35 using namespace llvm;
36 
37 // The "coro-suspend-crossing" flag is very noisy. There is another debug type,
38 // "coro-frame", which results in leaner debug spew.
39 #define DEBUG_TYPE "coro-suspend-crossing"
40 
41 enum { SmallVectorThreshold = 32 };
42 
43 // Provides two way mapping between the blocks and numbers.
44 namespace {
45 class BlockToIndexMapping {
46   SmallVector<BasicBlock *, SmallVectorThreshold> V;
47 
48 public:
49   size_t size() const { return V.size(); }
50 
51   BlockToIndexMapping(Function &F) {
52     for (BasicBlock &BB : F)
53       V.push_back(&BB);
54     llvm::sort(V);
55   }
56 
57   size_t blockToIndex(BasicBlock *BB) const {
58     auto *I = llvm::lower_bound(V, BB);
59     assert(I != V.end() && *I == BB && "BasicBlockNumberng: Unknown block");
60     return I - V.begin();
61   }
62 
63   BasicBlock *indexToBlock(unsigned Index) const { return V[Index]; }
64 };
65 } // end anonymous namespace
66 
67 // The SuspendCrossingInfo maintains data that allows to answer a question
68 // whether given two BasicBlocks A and B there is a path from A to B that
69 // passes through a suspend point.
70 //
71 // For every basic block 'i' it maintains a BlockData that consists of:
72 //   Consumes:  a bit vector which contains a set of indices of blocks that can
73 //              reach block 'i'
74 //   Kills: a bit vector which contains a set of indices of blocks that can
75 //          reach block 'i', but one of the path will cross a suspend point
76 //   Suspend: a boolean indicating whether block 'i' contains a suspend point.
77 //   End: a boolean indicating whether block 'i' contains a coro.end intrinsic.
78 //
79 namespace {
80 struct SuspendCrossingInfo {
81   BlockToIndexMapping Mapping;
82 
83   struct BlockData {
84     BitVector Consumes;
85     BitVector Kills;
86     bool Suspend = false;
87     bool End = false;
88   };
89   SmallVector<BlockData, SmallVectorThreshold> Block;
90 
91   iterator_range<succ_iterator> successors(BlockData const &BD) const {
92     BasicBlock *BB = Mapping.indexToBlock(&BD - &Block[0]);
93     return llvm::successors(BB);
94   }
95 
96   BlockData &getBlockData(BasicBlock *BB) {
97     return Block[Mapping.blockToIndex(BB)];
98   }
99 
100   void dump() const;
101   void dump(StringRef Label, BitVector const &BV) const;
102 
103   SuspendCrossingInfo(Function &F, coro::Shape &Shape);
104 
105   bool hasPathCrossingSuspendPoint(BasicBlock *DefBB, BasicBlock *UseBB) const {
106     size_t const DefIndex = Mapping.blockToIndex(DefBB);
107     size_t const UseIndex = Mapping.blockToIndex(UseBB);
108 
109     assert(Block[UseIndex].Consumes[DefIndex] && "use must consume def");
110     bool const Result = Block[UseIndex].Kills[DefIndex];
111     LLVM_DEBUG(dbgs() << UseBB->getName() << " => " << DefBB->getName()
112                       << " answer is " << Result << "\n");
113     return Result;
114   }
115 
116   bool isDefinitionAcrossSuspend(BasicBlock *DefBB, User *U) const {
117     auto *I = cast<Instruction>(U);
118 
119     // We rewrote PHINodes, so that only the ones with exactly one incoming
120     // value need to be analyzed.
121     if (auto *PN = dyn_cast<PHINode>(I))
122       if (PN->getNumIncomingValues() > 1)
123         return false;
124 
125     BasicBlock *UseBB = I->getParent();
126 
127     // As a special case, treat uses by an llvm.coro.suspend.retcon
128     // as if they were uses in the suspend's single predecessor: the
129     // uses conceptually occur before the suspend.
130     if (isa<CoroSuspendRetconInst>(I)) {
131       UseBB = UseBB->getSinglePredecessor();
132       assert(UseBB && "should have split coro.suspend into its own block");
133     }
134 
135     return hasPathCrossingSuspendPoint(DefBB, UseBB);
136   }
137 
138   bool isDefinitionAcrossSuspend(Argument &A, User *U) const {
139     return isDefinitionAcrossSuspend(&A.getParent()->getEntryBlock(), U);
140   }
141 
142   bool isDefinitionAcrossSuspend(Instruction &I, User *U) const {
143     auto *DefBB = I.getParent();
144 
145     // As a special case, treat values produced by an llvm.coro.suspend.*
146     // as if they were defined in the single successor: the uses
147     // conceptually occur after the suspend.
148     if (isa<AnyCoroSuspendInst>(I)) {
149       DefBB = DefBB->getSingleSuccessor();
150       assert(DefBB && "should have split coro.suspend into its own block");
151     }
152 
153     return isDefinitionAcrossSuspend(DefBB, U);
154   }
155 };
156 } // end anonymous namespace
157 
158 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
159 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump(StringRef Label,
160                                                 BitVector const &BV) const {
161   dbgs() << Label << ":";
162   for (size_t I = 0, N = BV.size(); I < N; ++I)
163     if (BV[I])
164       dbgs() << " " << Mapping.indexToBlock(I)->getName();
165   dbgs() << "\n";
166 }
167 
168 LLVM_DUMP_METHOD void SuspendCrossingInfo::dump() const {
169   for (size_t I = 0, N = Block.size(); I < N; ++I) {
170     BasicBlock *const B = Mapping.indexToBlock(I);
171     dbgs() << B->getName() << ":\n";
172     dump("   Consumes", Block[I].Consumes);
173     dump("      Kills", Block[I].Kills);
174   }
175   dbgs() << "\n";
176 }
177 #endif
178 
179 SuspendCrossingInfo::SuspendCrossingInfo(Function &F, coro::Shape &Shape)
180     : Mapping(F) {
181   const size_t N = Mapping.size();
182   Block.resize(N);
183 
184   // Initialize every block so that it consumes itself
185   for (size_t I = 0; I < N; ++I) {
186     auto &B = Block[I];
187     B.Consumes.resize(N);
188     B.Kills.resize(N);
189     B.Consumes.set(I);
190   }
191 
192   // Mark all CoroEnd Blocks. We do not propagate Kills beyond coro.ends as
193   // the code beyond coro.end is reachable during initial invocation of the
194   // coroutine.
195   for (auto *CE : Shape.CoroEnds)
196     getBlockData(CE->getParent()).End = true;
197 
198   // Mark all suspend blocks and indicate that they kill everything they
199   // consume. Note, that crossing coro.save also requires a spill, as any code
200   // between coro.save and coro.suspend may resume the coroutine and all of the
201   // state needs to be saved by that time.
202   auto markSuspendBlock = [&](IntrinsicInst *BarrierInst) {
203     BasicBlock *SuspendBlock = BarrierInst->getParent();
204     auto &B = getBlockData(SuspendBlock);
205     B.Suspend = true;
206     B.Kills |= B.Consumes;
207   };
208   for (auto *CSI : Shape.CoroSuspends) {
209     markSuspendBlock(CSI);
210     if (auto *Save = CSI->getCoroSave())
211       markSuspendBlock(Save);
212   }
213 
214   // Iterate propagating consumes and kills until they stop changing.
215   int Iteration = 0;
216   (void)Iteration;
217 
218   bool Changed;
219   do {
220     LLVM_DEBUG(dbgs() << "iteration " << ++Iteration);
221     LLVM_DEBUG(dbgs() << "==============\n");
222 
223     Changed = false;
224     for (size_t I = 0; I < N; ++I) {
225       auto &B = Block[I];
226       for (BasicBlock *SI : successors(B)) {
227 
228         auto SuccNo = Mapping.blockToIndex(SI);
229 
230         // Saved Consumes and Kills bitsets so that it is easy to see
231         // if anything changed after propagation.
232         auto &S = Block[SuccNo];
233         auto SavedConsumes = S.Consumes;
234         auto SavedKills = S.Kills;
235 
236         // Propagate Kills and Consumes from block B into its successor S.
237         S.Consumes |= B.Consumes;
238         S.Kills |= B.Kills;
239 
240         // If block B is a suspend block, it should propagate kills into the
241         // its successor for every block B consumes.
242         if (B.Suspend) {
243           S.Kills |= B.Consumes;
244         }
245         if (S.Suspend) {
246           // If block S is a suspend block, it should kill all of the blocks it
247           // consumes.
248           S.Kills |= S.Consumes;
249         } else if (S.End) {
250           // If block S is an end block, it should not propagate kills as the
251           // blocks following coro.end() are reached during initial invocation
252           // of the coroutine while all the data are still available on the
253           // stack or in the registers.
254           S.Kills.reset();
255         } else {
256           // This is reached when S block it not Suspend nor coro.end and it
257           // need to make sure that it is not in the kill set.
258           S.Kills.reset(SuccNo);
259         }
260 
261         // See if anything changed.
262         Changed |= (S.Kills != SavedKills) || (S.Consumes != SavedConsumes);
263 
264         if (S.Kills != SavedKills) {
265           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI->getName()
266                             << "\n");
267           LLVM_DEBUG(dump("S.Kills", S.Kills));
268           LLVM_DEBUG(dump("SavedKills", SavedKills));
269         }
270         if (S.Consumes != SavedConsumes) {
271           LLVM_DEBUG(dbgs() << "\nblock " << I << " follower " << SI << "\n");
272           LLVM_DEBUG(dump("S.Consume", S.Consumes));
273           LLVM_DEBUG(dump("SavedCons", SavedConsumes));
274         }
275       }
276     }
277   } while (Changed);
278   LLVM_DEBUG(dump());
279 }
280 
281 #undef DEBUG_TYPE // "coro-suspend-crossing"
282 #define DEBUG_TYPE "coro-frame"
283 
284 // We build up the list of spills for every case where a use is separated
285 // from the definition by a suspend point.
286 
287 static const unsigned InvalidFieldIndex = ~0U;
288 
289 namespace {
290 class Spill {
291   Value *Def = nullptr;
292   Instruction *User = nullptr;
293   unsigned FieldNo = InvalidFieldIndex;
294 
295 public:
296   Spill(Value *Def, llvm::User *U) : Def(Def), User(cast<Instruction>(U)) {}
297 
298   Value *def() const { return Def; }
299   Instruction *user() const { return User; }
300   BasicBlock *userBlock() const { return User->getParent(); }
301 
302   // Note that field index is stored in the first SpillEntry for a particular
303   // definition. Subsequent mentions of a defintion do not have fieldNo
304   // assigned. This works out fine as the users of Spills capture the info about
305   // the definition the first time they encounter it. Consider refactoring
306   // SpillInfo into two arrays to normalize the spill representation.
307   unsigned fieldIndex() const {
308     assert(FieldNo != InvalidFieldIndex && "Accessing unassigned field");
309     return FieldNo;
310   }
311   void setFieldIndex(unsigned FieldNumber) {
312     assert(FieldNo == InvalidFieldIndex && "Reassigning field number");
313     FieldNo = FieldNumber;
314   }
315 };
316 } // namespace
317 
318 // Note that there may be more than one record with the same value of Def in
319 // the SpillInfo vector.
320 using SpillInfo = SmallVector<Spill, 8>;
321 
322 #ifndef NDEBUG
323 static void dump(StringRef Title, SpillInfo const &Spills) {
324   dbgs() << "------------- " << Title << "--------------\n";
325   Value *CurrentValue = nullptr;
326   for (auto const &E : Spills) {
327     if (CurrentValue != E.def()) {
328       CurrentValue = E.def();
329       CurrentValue->dump();
330     }
331     dbgs() << "   user: ";
332     E.user()->dump();
333   }
334 }
335 #endif
336 
337 namespace {
338 // We cannot rely solely on natural alignment of a type when building a
339 // coroutine frame and if the alignment specified on the Alloca instruction
340 // differs from the natural alignment of the alloca type we will need to insert
341 // padding.
342 struct PaddingCalculator {
343   const DataLayout &DL;
344   LLVMContext &Context;
345   unsigned StructSize = 0;
346 
347   PaddingCalculator(LLVMContext &Context, DataLayout const &DL)
348       : DL(DL), Context(Context) {}
349 
350   // Replicate the logic from IR/DataLayout.cpp to match field offset
351   // computation for LLVM structs.
352   void addType(Type *Ty) {
353     unsigned TyAlign = DL.getABITypeAlignment(Ty);
354     if ((StructSize & (TyAlign - 1)) != 0)
355       StructSize = alignTo(StructSize, TyAlign);
356 
357     StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item.
358   }
359 
360   void addTypes(SmallVectorImpl<Type *> const &Types) {
361     for (auto *Ty : Types)
362       addType(Ty);
363   }
364 
365   unsigned computePadding(Type *Ty, unsigned ForcedAlignment) {
366     unsigned TyAlign = DL.getABITypeAlignment(Ty);
367     auto Natural = alignTo(StructSize, TyAlign);
368     auto Forced = alignTo(StructSize, ForcedAlignment);
369 
370     // Return how many bytes of padding we need to insert.
371     if (Natural != Forced)
372       return std::max(Natural, Forced) - StructSize;
373 
374     // Rely on natural alignment.
375     return 0;
376   }
377 
378   // If padding required, return the padding field type to insert.
379   ArrayType *getPaddingType(Type *Ty, unsigned ForcedAlignment) {
380     if (auto Padding = computePadding(Ty, ForcedAlignment))
381       return ArrayType::get(Type::getInt8Ty(Context), Padding);
382 
383     return nullptr;
384   }
385 };
386 } // namespace
387 
388 // Build a struct that will keep state for an active coroutine.
389 //   struct f.frame {
390 //     ResumeFnTy ResumeFnAddr;
391 //     ResumeFnTy DestroyFnAddr;
392 //     int ResumeIndex;
393 //     ... promise (if present) ...
394 //     ... spills ...
395 //   };
396 static StructType *buildFrameType(Function &F, coro::Shape &Shape,
397                                   SpillInfo &Spills) {
398   LLVMContext &C = F.getContext();
399   const DataLayout &DL = F.getParent()->getDataLayout();
400   PaddingCalculator Padder(C, DL);
401   SmallString<32> Name(F.getName());
402   Name.append(".Frame");
403   StructType *FrameTy = StructType::create(C, Name);
404   SmallVector<Type *, 8> Types;
405 
406   AllocaInst *PromiseAlloca = Shape.getPromiseAlloca();
407 
408   if (Shape.ABI == coro::ABI::Switch) {
409     auto *FramePtrTy = FrameTy->getPointerTo();
410     auto *FnTy = FunctionType::get(Type::getVoidTy(C), FramePtrTy,
411                                    /*IsVarArg=*/false);
412     auto *FnPtrTy = FnTy->getPointerTo();
413 
414     // Figure out how wide should be an integer type storing the suspend index.
415     unsigned IndexBits = std::max(1U, Log2_64_Ceil(Shape.CoroSuspends.size()));
416     Type *PromiseType = PromiseAlloca
417                             ? PromiseAlloca->getType()->getElementType()
418                             : Type::getInt1Ty(C);
419     Type *IndexType = Type::getIntNTy(C, IndexBits);
420     Types.push_back(FnPtrTy);
421     Types.push_back(FnPtrTy);
422     Types.push_back(PromiseType);
423     Types.push_back(IndexType);
424   } else {
425     assert(PromiseAlloca == nullptr && "lowering doesn't support promises");
426   }
427 
428   Value *CurrentDef = nullptr;
429 
430   Padder.addTypes(Types);
431 
432   // Create an entry for every spilled value.
433   for (auto &S : Spills) {
434     if (CurrentDef == S.def())
435       continue;
436 
437     CurrentDef = S.def();
438     // PromiseAlloca was already added to Types array earlier.
439     if (CurrentDef == PromiseAlloca)
440       continue;
441 
442     uint64_t Count = 1;
443     Type *Ty = nullptr;
444     if (auto *AI = dyn_cast<AllocaInst>(CurrentDef)) {
445       Ty = AI->getAllocatedType();
446       if (unsigned AllocaAlignment = AI->getAlignment()) {
447         // If alignment is specified in alloca, see if we need to insert extra
448         // padding.
449         if (auto PaddingTy = Padder.getPaddingType(Ty, AllocaAlignment)) {
450           Types.push_back(PaddingTy);
451           Padder.addType(PaddingTy);
452         }
453       }
454       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize()))
455         Count = CI->getValue().getZExtValue();
456       else
457         report_fatal_error("Coroutines cannot handle non static allocas yet");
458     } else {
459       Ty = CurrentDef->getType();
460     }
461     S.setFieldIndex(Types.size());
462     if (Count == 1)
463       Types.push_back(Ty);
464     else
465       Types.push_back(ArrayType::get(Ty, Count));
466     Padder.addType(Ty);
467   }
468   FrameTy->setBody(Types);
469 
470   switch (Shape.ABI) {
471   case coro::ABI::Switch:
472     break;
473 
474   // Remember whether the frame is inline in the storage.
475   case coro::ABI::Retcon:
476   case coro::ABI::RetconOnce: {
477     auto &Layout = F.getParent()->getDataLayout();
478     auto Id = Shape.getRetconCoroId();
479     Shape.RetconLowering.IsFrameInlineInStorage
480       = (Layout.getTypeAllocSize(FrameTy) <= Id->getStorageSize() &&
481          Layout.getABITypeAlignment(FrameTy) <= Id->getStorageAlignment());
482     break;
483   }
484   }
485 
486   return FrameTy;
487 }
488 
489 // We use a pointer use visitor to discover if there are any writes into an
490 // alloca that dominates CoroBegin. If that is the case, insertSpills will copy
491 // the value from the alloca into the coroutine frame spill slot corresponding
492 // to that alloca.
493 namespace {
494 struct AllocaUseVisitor : PtrUseVisitor<AllocaUseVisitor> {
495   using Base = PtrUseVisitor<AllocaUseVisitor>;
496   AllocaUseVisitor(const DataLayout &DL, const DominatorTree &DT,
497                    const CoroBeginInst &CB)
498       : PtrUseVisitor(DL), DT(DT), CoroBegin(CB) {}
499 
500   // We are only interested in uses that dominate coro.begin.
501   void visit(Instruction &I) {
502     if (DT.dominates(&I, &CoroBegin))
503       Base::visit(I);
504   }
505   // We need to provide this overload as PtrUseVisitor uses a pointer based
506   // visiting function.
507   void visit(Instruction *I) { return visit(*I); }
508 
509   void visitLoadInst(LoadInst &) {} // Good. Nothing to do.
510 
511   // If the use is an operand, the pointer escaped and anything can write into
512   // that memory. If the use is the pointer, we are definitely writing into the
513   // alloca and therefore we need to copy.
514   void visitStoreInst(StoreInst &SI) { PI.setAborted(&SI); }
515 
516   // Any other instruction that is not filtered out by PtrUseVisitor, will
517   // result in the copy.
518   void visitInstruction(Instruction &I) { PI.setAborted(&I); }
519 
520 private:
521   const DominatorTree &DT;
522   const CoroBeginInst &CoroBegin;
523 };
524 } // namespace
525 static bool mightWriteIntoAllocaPtr(AllocaInst &A, const DominatorTree &DT,
526                                     const CoroBeginInst &CB) {
527   const DataLayout &DL = A.getModule()->getDataLayout();
528   AllocaUseVisitor Visitor(DL, DT, CB);
529   auto PtrI = Visitor.visitPtr(A);
530   if (PtrI.isEscaped() || PtrI.isAborted()) {
531     auto *PointerEscapingInstr = PtrI.getEscapingInst()
532                                      ? PtrI.getEscapingInst()
533                                      : PtrI.getAbortingInst();
534     if (PointerEscapingInstr) {
535       LLVM_DEBUG(
536           dbgs() << "AllocaInst copy was triggered by instruction: "
537                  << *PointerEscapingInstr << "\n");
538     }
539     return true;
540   }
541   return false;
542 }
543 
544 // We need to make room to insert a spill after initial PHIs, but before
545 // catchswitch instruction. Placing it before violates the requirement that
546 // catchswitch, like all other EHPads must be the first nonPHI in a block.
547 //
548 // Split away catchswitch into a separate block and insert in its place:
549 //
550 //   cleanuppad <InsertPt> cleanupret.
551 //
552 // cleanupret instruction will act as an insert point for the spill.
553 static Instruction *splitBeforeCatchSwitch(CatchSwitchInst *CatchSwitch) {
554   BasicBlock *CurrentBlock = CatchSwitch->getParent();
555   BasicBlock *NewBlock = CurrentBlock->splitBasicBlock(CatchSwitch);
556   CurrentBlock->getTerminator()->eraseFromParent();
557 
558   auto *CleanupPad =
559       CleanupPadInst::Create(CatchSwitch->getParentPad(), {}, "", CurrentBlock);
560   auto *CleanupRet =
561       CleanupReturnInst::Create(CleanupPad, NewBlock, CurrentBlock);
562   return CleanupRet;
563 }
564 
565 // Replace all alloca and SSA values that are accessed across suspend points
566 // with GetElementPointer from coroutine frame + loads and stores. Create an
567 // AllocaSpillBB that will become the new entry block for the resume parts of
568 // the coroutine:
569 //
570 //    %hdl = coro.begin(...)
571 //    whatever
572 //
573 // becomes:
574 //
575 //    %hdl = coro.begin(...)
576 //    %FramePtr = bitcast i8* hdl to %f.frame*
577 //    br label %AllocaSpillBB
578 //
579 //  AllocaSpillBB:
580 //    ; geps corresponding to allocas that were moved to coroutine frame
581 //    br label PostSpill
582 //
583 //  PostSpill:
584 //    whatever
585 //
586 //
587 static Instruction *insertSpills(const SpillInfo &Spills, coro::Shape &Shape) {
588   auto *CB = Shape.CoroBegin;
589   LLVMContext &C = CB->getContext();
590   IRBuilder<> Builder(CB->getNextNode());
591   StructType *FrameTy = Shape.FrameTy;
592   PointerType *FramePtrTy = FrameTy->getPointerTo();
593   auto *FramePtr =
594       cast<Instruction>(Builder.CreateBitCast(CB, FramePtrTy, "FramePtr"));
595   DominatorTree DT(*CB->getFunction());
596 
597   Value *CurrentValue = nullptr;
598   BasicBlock *CurrentBlock = nullptr;
599   Value *CurrentReload = nullptr;
600 
601   // Proper field number will be read from field definition.
602   unsigned Index = InvalidFieldIndex;
603 
604   // We need to keep track of any allocas that need "spilling"
605   // since they will live in the coroutine frame now, all access to them
606   // need to be changed, not just the access across suspend points
607   // we remember allocas and their indices to be handled once we processed
608   // all the spills.
609   SmallVector<std::pair<AllocaInst *, unsigned>, 4> Allocas;
610   // Promise alloca (if present) has a fixed field number.
611   if (auto *PromiseAlloca = Shape.getPromiseAlloca()) {
612     assert(Shape.ABI == coro::ABI::Switch);
613     Allocas.emplace_back(PromiseAlloca, coro::Shape::SwitchFieldIndex::Promise);
614   }
615 
616   // Create a GEP with the given index into the coroutine frame for the original
617   // value Orig. Appends an extra 0 index for array-allocas, preserving the
618   // original type.
619   auto GetFramePointer = [&](uint32_t Index, Value *Orig) -> Value * {
620     SmallVector<Value *, 3> Indices = {
621         ConstantInt::get(Type::getInt32Ty(C), 0),
622         ConstantInt::get(Type::getInt32Ty(C), Index),
623     };
624 
625     if (auto *AI = dyn_cast<AllocaInst>(Orig)) {
626       if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
627         auto Count = CI->getValue().getZExtValue();
628         if (Count > 1) {
629           Indices.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
630         }
631       } else {
632         report_fatal_error("Coroutines cannot handle non static allocas yet");
633       }
634     }
635 
636     return Builder.CreateInBoundsGEP(FrameTy, FramePtr, Indices);
637   };
638 
639   // Create a load instruction to reload the spilled value from the coroutine
640   // frame.
641   auto CreateReload = [&](Instruction *InsertBefore) {
642     assert(Index != InvalidFieldIndex && "accessing unassigned field number");
643     Builder.SetInsertPoint(InsertBefore);
644 
645     auto *G = GetFramePointer(Index, CurrentValue);
646     G->setName(CurrentValue->getName() + Twine(".reload.addr"));
647 
648     return isa<AllocaInst>(CurrentValue)
649                ? G
650                : Builder.CreateLoad(FrameTy->getElementType(Index), G,
651                                     CurrentValue->getName() + Twine(".reload"));
652   };
653 
654   for (auto const &E : Spills) {
655     // If we have not seen the value, generate a spill.
656     if (CurrentValue != E.def()) {
657       CurrentValue = E.def();
658       CurrentBlock = nullptr;
659       CurrentReload = nullptr;
660 
661       Index = E.fieldIndex();
662 
663       if (auto *AI = dyn_cast<AllocaInst>(CurrentValue)) {
664         // Spilled AllocaInst will be replaced with GEP from the coroutine frame
665         // there is no spill required.
666         Allocas.emplace_back(AI, Index);
667         if (!AI->isStaticAlloca())
668           report_fatal_error("Coroutines cannot handle non static allocas yet");
669       } else {
670         // Otherwise, create a store instruction storing the value into the
671         // coroutine frame.
672 
673         Instruction *InsertPt = nullptr;
674         if (auto Arg = dyn_cast<Argument>(CurrentValue)) {
675           // For arguments, we will place the store instruction right after
676           // the coroutine frame pointer instruction, i.e. bitcast of
677           // coro.begin from i8* to %f.frame*.
678           InsertPt = FramePtr->getNextNode();
679 
680           // If we're spilling an Argument, make sure we clear 'nocapture'
681           // from the coroutine function.
682           Arg->getParent()->removeParamAttr(Arg->getArgNo(),
683                                             Attribute::NoCapture);
684 
685         } else if (auto *II = dyn_cast<InvokeInst>(CurrentValue)) {
686           // If we are spilling the result of the invoke instruction, split the
687           // normal edge and insert the spill in the new block.
688           auto NewBB = SplitEdge(II->getParent(), II->getNormalDest());
689           InsertPt = NewBB->getTerminator();
690         } else if (isa<PHINode>(CurrentValue)) {
691           // Skip the PHINodes and EH pads instructions.
692           BasicBlock *DefBlock = cast<Instruction>(E.def())->getParent();
693           if (auto *CSI = dyn_cast<CatchSwitchInst>(DefBlock->getTerminator()))
694             InsertPt = splitBeforeCatchSwitch(CSI);
695           else
696             InsertPt = &*DefBlock->getFirstInsertionPt();
697         } else if (auto CSI = dyn_cast<AnyCoroSuspendInst>(CurrentValue)) {
698           // Don't spill immediately after a suspend; splitting assumes
699           // that the suspend will be followed by a branch.
700           InsertPt = CSI->getParent()->getSingleSuccessor()->getFirstNonPHI();
701         } else {
702           auto *I = cast<Instruction>(E.def());
703           assert(!I->isTerminator() && "unexpected terminator");
704           // For all other values, the spill is placed immediately after
705           // the definition.
706           if (DT.dominates(CB, I)) {
707             InsertPt = I->getNextNode();
708           } else {
709             // Unless, it is not dominated by CoroBegin, then it will be
710             // inserted immediately after CoroFrame is computed.
711             InsertPt = FramePtr->getNextNode();
712           }
713         }
714 
715         Builder.SetInsertPoint(InsertPt);
716         auto *G = Builder.CreateConstInBoundsGEP2_32(
717             FrameTy, FramePtr, 0, Index,
718             CurrentValue->getName() + Twine(".spill.addr"));
719         Builder.CreateStore(CurrentValue, G);
720       }
721     }
722 
723     // If we have not seen the use block, generate a reload in it.
724     if (CurrentBlock != E.userBlock()) {
725       CurrentBlock = E.userBlock();
726       CurrentReload = CreateReload(&*CurrentBlock->getFirstInsertionPt());
727     }
728 
729     // If we have a single edge PHINode, remove it and replace it with a reload
730     // from the coroutine frame. (We already took care of multi edge PHINodes
731     // by rewriting them in the rewritePHIs function).
732     if (auto *PN = dyn_cast<PHINode>(E.user())) {
733       assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming "
734                                                 "values in the PHINode");
735       PN->replaceAllUsesWith(CurrentReload);
736       PN->eraseFromParent();
737       continue;
738     }
739 
740     // Replace all uses of CurrentValue in the current instruction with reload.
741     E.user()->replaceUsesOfWith(CurrentValue, CurrentReload);
742   }
743 
744   BasicBlock *FramePtrBB = FramePtr->getParent();
745 
746   auto SpillBlock =
747     FramePtrBB->splitBasicBlock(FramePtr->getNextNode(), "AllocaSpillBB");
748   SpillBlock->splitBasicBlock(&SpillBlock->front(), "PostSpill");
749   Shape.AllocaSpillBlock = SpillBlock;
750   // If we found any allocas, replace all of their remaining uses with Geps.
751   // Note: we cannot do it indiscriminately as some of the uses may not be
752   // dominated by CoroBegin.
753   bool MightNeedToCopy = false;
754   Builder.SetInsertPoint(&Shape.AllocaSpillBlock->front());
755   SmallVector<Instruction *, 4> UsersToUpdate;
756   for (auto &P : Allocas) {
757     AllocaInst *const A = P.first;
758     UsersToUpdate.clear();
759     for (User *U : A->users()) {
760       auto *I = cast<Instruction>(U);
761       if (DT.dominates(CB, I))
762         UsersToUpdate.push_back(I);
763       else
764         MightNeedToCopy = true;
765     }
766     if (!UsersToUpdate.empty()) {
767       auto *G = GetFramePointer(P.second, A);
768       G->takeName(A);
769       for (Instruction *I : UsersToUpdate)
770         I->replaceUsesOfWith(A, G);
771     }
772   }
773   // If we discovered such uses not dominated by CoroBegin, see if any of them
774   // preceed coro begin and have instructions that can modify the
775   // value of the alloca and therefore would require a copying the value into
776   // the spill slot in the coroutine frame.
777   if (MightNeedToCopy) {
778     Builder.SetInsertPoint(FramePtr->getNextNode());
779 
780     for (auto &P : Allocas) {
781       AllocaInst *const A = P.first;
782       if (mightWriteIntoAllocaPtr(*A, DT, *CB)) {
783         if (A->isArrayAllocation())
784           report_fatal_error(
785               "Coroutines cannot handle copying of array allocas yet");
786 
787         auto *G = GetFramePointer(P.second, A);
788         auto *Value = Builder.CreateLoad(A->getAllocatedType(), A);
789         Builder.CreateStore(Value, G);
790       }
791     }
792   }
793   return FramePtr;
794 }
795 
796 // Sets the unwind edge of an instruction to a particular successor.
797 static void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
798   if (auto *II = dyn_cast<InvokeInst>(TI))
799     II->setUnwindDest(Succ);
800   else if (auto *CS = dyn_cast<CatchSwitchInst>(TI))
801     CS->setUnwindDest(Succ);
802   else if (auto *CR = dyn_cast<CleanupReturnInst>(TI))
803     CR->setUnwindDest(Succ);
804   else
805     llvm_unreachable("unexpected terminator instruction");
806 }
807 
808 // Replaces all uses of OldPred with the NewPred block in all PHINodes in a
809 // block.
810 static void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
811                            BasicBlock *NewPred,
812                            PHINode *LandingPadReplacement) {
813   unsigned BBIdx = 0;
814   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
815     PHINode *PN = cast<PHINode>(I);
816 
817     // We manually update the LandingPadReplacement PHINode and it is the last
818     // PHI Node. So, if we find it, we are done.
819     if (LandingPadReplacement == PN)
820       break;
821 
822     // Reuse the previous value of BBIdx if it lines up.  In cases where we
823     // have multiple phi nodes with *lots* of predecessors, this is a speed
824     // win because we don't have to scan the PHI looking for TIBB.  This
825     // happens because the BB list of PHI nodes are usually in the same
826     // order.
827     if (PN->getIncomingBlock(BBIdx) != OldPred)
828       BBIdx = PN->getBasicBlockIndex(OldPred);
829 
830     assert(BBIdx != (unsigned)-1 && "Invalid PHI Index!");
831     PN->setIncomingBlock(BBIdx, NewPred);
832   }
833 }
834 
835 // Uses SplitEdge unless the successor block is an EHPad, in which case do EH
836 // specific handling.
837 static BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
838                                     LandingPadInst *OriginalPad,
839                                     PHINode *LandingPadReplacement) {
840   auto *PadInst = Succ->getFirstNonPHI();
841   if (!LandingPadReplacement && !PadInst->isEHPad())
842     return SplitEdge(BB, Succ);
843 
844   auto *NewBB = BasicBlock::Create(BB->getContext(), "", BB->getParent(), Succ);
845   setUnwindEdgeTo(BB->getTerminator(), NewBB);
846   updatePhiNodes(Succ, BB, NewBB, LandingPadReplacement);
847 
848   if (LandingPadReplacement) {
849     auto *NewLP = OriginalPad->clone();
850     auto *Terminator = BranchInst::Create(Succ, NewBB);
851     NewLP->insertBefore(Terminator);
852     LandingPadReplacement->addIncoming(NewLP, NewBB);
853     return NewBB;
854   }
855   Value *ParentPad = nullptr;
856   if (auto *FuncletPad = dyn_cast<FuncletPadInst>(PadInst))
857     ParentPad = FuncletPad->getParentPad();
858   else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(PadInst))
859     ParentPad = CatchSwitch->getParentPad();
860   else
861     llvm_unreachable("handling for other EHPads not implemented yet");
862 
863   auto *NewCleanupPad = CleanupPadInst::Create(ParentPad, {}, "", NewBB);
864   CleanupReturnInst::Create(NewCleanupPad, Succ, NewBB);
865   return NewBB;
866 }
867 
868 static void rewritePHIs(BasicBlock &BB) {
869   // For every incoming edge we will create a block holding all
870   // incoming values in a single PHI nodes.
871   //
872   // loop:
873   //    %n.val = phi i32[%n, %entry], [%inc, %loop]
874   //
875   // It will create:
876   //
877   // loop.from.entry:
878   //    %n.loop.pre = phi i32 [%n, %entry]
879   //    br %label loop
880   // loop.from.loop:
881   //    %inc.loop.pre = phi i32 [%inc, %loop]
882   //    br %label loop
883   //
884   // After this rewrite, further analysis will ignore any phi nodes with more
885   // than one incoming edge.
886 
887   // TODO: Simplify PHINodes in the basic block to remove duplicate
888   // predecessors.
889 
890   LandingPadInst *LandingPad = nullptr;
891   PHINode *ReplPHI = nullptr;
892   if ((LandingPad = dyn_cast_or_null<LandingPadInst>(BB.getFirstNonPHI()))) {
893     // ehAwareSplitEdge will clone the LandingPad in all the edge blocks.
894     // We replace the original landing pad with a PHINode that will collect the
895     // results from all of them.
896     ReplPHI = PHINode::Create(LandingPad->getType(), 1, "", LandingPad);
897     ReplPHI->takeName(LandingPad);
898     LandingPad->replaceAllUsesWith(ReplPHI);
899     // We will erase the original landing pad at the end of this function after
900     // ehAwareSplitEdge cloned it in the transition blocks.
901   }
902 
903   SmallVector<BasicBlock *, 8> Preds(pred_begin(&BB), pred_end(&BB));
904   for (BasicBlock *Pred : Preds) {
905     auto *IncomingBB = ehAwareSplitEdge(Pred, &BB, LandingPad, ReplPHI);
906     IncomingBB->setName(BB.getName() + Twine(".from.") + Pred->getName());
907     auto *PN = cast<PHINode>(&BB.front());
908     do {
909       int Index = PN->getBasicBlockIndex(IncomingBB);
910       Value *V = PN->getIncomingValue(Index);
911       PHINode *InputV = PHINode::Create(
912           V->getType(), 1, V->getName() + Twine(".") + BB.getName(),
913           &IncomingBB->front());
914       InputV->addIncoming(V, Pred);
915       PN->setIncomingValue(Index, InputV);
916       PN = dyn_cast<PHINode>(PN->getNextNode());
917     } while (PN != ReplPHI); // ReplPHI is either null or the PHI that replaced
918                              // the landing pad.
919   }
920 
921   if (LandingPad) {
922     // Calls to ehAwareSplitEdge function cloned the original lading pad.
923     // No longer need it.
924     LandingPad->eraseFromParent();
925   }
926 }
927 
928 static void rewritePHIs(Function &F) {
929   SmallVector<BasicBlock *, 8> WorkList;
930 
931   for (BasicBlock &BB : F)
932     if (auto *PN = dyn_cast<PHINode>(&BB.front()))
933       if (PN->getNumIncomingValues() > 1)
934         WorkList.push_back(&BB);
935 
936   for (BasicBlock *BB : WorkList)
937     rewritePHIs(*BB);
938 }
939 
940 // Check for instructions that we can recreate on resume as opposed to spill
941 // the result into a coroutine frame.
942 static bool materializable(Instruction &V) {
943   return isa<CastInst>(&V) || isa<GetElementPtrInst>(&V) ||
944          isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<SelectInst>(&V);
945 }
946 
947 // Check for structural coroutine intrinsics that should not be spilled into
948 // the coroutine frame.
949 static bool isCoroutineStructureIntrinsic(Instruction &I) {
950   return isa<CoroIdInst>(&I) || isa<CoroSaveInst>(&I) ||
951          isa<CoroSuspendInst>(&I);
952 }
953 
954 // For every use of the value that is across suspend point, recreate that value
955 // after a suspend point.
956 static void rewriteMaterializableInstructions(IRBuilder<> &IRB,
957                                               SpillInfo const &Spills) {
958   BasicBlock *CurrentBlock = nullptr;
959   Instruction *CurrentMaterialization = nullptr;
960   Instruction *CurrentDef = nullptr;
961 
962   for (auto const &E : Spills) {
963     // If it is a new definition, update CurrentXXX variables.
964     if (CurrentDef != E.def()) {
965       CurrentDef = cast<Instruction>(E.def());
966       CurrentBlock = nullptr;
967       CurrentMaterialization = nullptr;
968     }
969 
970     // If we have not seen this block, materialize the value.
971     if (CurrentBlock != E.userBlock()) {
972       CurrentBlock = E.userBlock();
973       CurrentMaterialization = cast<Instruction>(CurrentDef)->clone();
974       CurrentMaterialization->setName(CurrentDef->getName());
975       CurrentMaterialization->insertBefore(
976           &*CurrentBlock->getFirstInsertionPt());
977     }
978 
979     if (auto *PN = dyn_cast<PHINode>(E.user())) {
980       assert(PN->getNumIncomingValues() == 1 && "unexpected number of incoming "
981                                                 "values in the PHINode");
982       PN->replaceAllUsesWith(CurrentMaterialization);
983       PN->eraseFromParent();
984       continue;
985     }
986 
987     // Replace all uses of CurrentDef in the current instruction with the
988     // CurrentMaterialization for the block.
989     E.user()->replaceUsesOfWith(CurrentDef, CurrentMaterialization);
990   }
991 }
992 
993 // Splits the block at a particular instruction unless it is the first
994 // instruction in the block with a single predecessor.
995 static BasicBlock *splitBlockIfNotFirst(Instruction *I, const Twine &Name) {
996   auto *BB = I->getParent();
997   if (&BB->front() == I) {
998     if (BB->getSinglePredecessor()) {
999       BB->setName(Name);
1000       return BB;
1001     }
1002   }
1003   return BB->splitBasicBlock(I, Name);
1004 }
1005 
1006 // Split above and below a particular instruction so that it
1007 // will be all alone by itself in a block.
1008 static void splitAround(Instruction *I, const Twine &Name) {
1009   splitBlockIfNotFirst(I, Name);
1010   splitBlockIfNotFirst(I->getNextNode(), "After" + Name);
1011 }
1012 
1013 static bool isSuspendBlock(BasicBlock *BB) {
1014   return isa<AnyCoroSuspendInst>(BB->front());
1015 }
1016 
1017 typedef SmallPtrSet<BasicBlock*, 8> VisitedBlocksSet;
1018 
1019 /// Does control flow starting at the given block ever reach a suspend
1020 /// instruction before reaching a block in VisitedOrFreeBBs?
1021 static bool isSuspendReachableFrom(BasicBlock *From,
1022                                    VisitedBlocksSet &VisitedOrFreeBBs) {
1023   // Eagerly try to add this block to the visited set.  If it's already
1024   // there, stop recursing; this path doesn't reach a suspend before
1025   // either looping or reaching a freeing block.
1026   if (!VisitedOrFreeBBs.insert(From).second)
1027     return false;
1028 
1029   // We assume that we'll already have split suspends into their own blocks.
1030   if (isSuspendBlock(From))
1031     return true;
1032 
1033   // Recurse on the successors.
1034   for (auto Succ : successors(From)) {
1035     if (isSuspendReachableFrom(Succ, VisitedOrFreeBBs))
1036       return true;
1037   }
1038 
1039   return false;
1040 }
1041 
1042 /// Is the given alloca "local", i.e. bounded in lifetime to not cross a
1043 /// suspend point?
1044 static bool isLocalAlloca(CoroAllocaAllocInst *AI) {
1045   // Seed the visited set with all the basic blocks containing a free
1046   // so that we won't pass them up.
1047   VisitedBlocksSet VisitedOrFreeBBs;
1048   for (auto User : AI->users()) {
1049     if (auto FI = dyn_cast<CoroAllocaFreeInst>(User))
1050       VisitedOrFreeBBs.insert(FI->getParent());
1051   }
1052 
1053   return !isSuspendReachableFrom(AI->getParent(), VisitedOrFreeBBs);
1054 }
1055 
1056 /// After we split the coroutine, will the given basic block be along
1057 /// an obvious exit path for the resumption function?
1058 static bool willLeaveFunctionImmediatelyAfter(BasicBlock *BB,
1059                                               unsigned depth = 3) {
1060   // If we've bottomed out our depth count, stop searching and assume
1061   // that the path might loop back.
1062   if (depth == 0) return false;
1063 
1064   // If this is a suspend block, we're about to exit the resumption function.
1065   if (isSuspendBlock(BB)) return true;
1066 
1067   // Recurse into the successors.
1068   for (auto Succ : successors(BB)) {
1069     if (!willLeaveFunctionImmediatelyAfter(Succ, depth - 1))
1070       return false;
1071   }
1072 
1073   // If none of the successors leads back in a loop, we're on an exit/abort.
1074   return true;
1075 }
1076 
1077 static bool localAllocaNeedsStackSave(CoroAllocaAllocInst *AI) {
1078   // Look for a free that isn't sufficiently obviously followed by
1079   // either a suspend or a termination, i.e. something that will leave
1080   // the coro resumption frame.
1081   for (auto U : AI->users()) {
1082     auto FI = dyn_cast<CoroAllocaFreeInst>(U);
1083     if (!FI) continue;
1084 
1085     if (!willLeaveFunctionImmediatelyAfter(FI->getParent()))
1086       return true;
1087   }
1088 
1089   // If we never found one, we don't need a stack save.
1090   return false;
1091 }
1092 
1093 /// Turn each of the given local allocas into a normal (dynamic) alloca
1094 /// instruction.
1095 static void lowerLocalAllocas(ArrayRef<CoroAllocaAllocInst*> LocalAllocas,
1096                               SmallVectorImpl<Instruction*> &DeadInsts) {
1097   for (auto AI : LocalAllocas) {
1098     auto M = AI->getModule();
1099     IRBuilder<> Builder(AI);
1100 
1101     // Save the stack depth.  Try to avoid doing this if the stackrestore
1102     // is going to immediately precede a return or something.
1103     Value *StackSave = nullptr;
1104     if (localAllocaNeedsStackSave(AI))
1105       StackSave = Builder.CreateCall(
1106                             Intrinsic::getDeclaration(M, Intrinsic::stacksave));
1107 
1108     // Allocate memory.
1109     auto Alloca = Builder.CreateAlloca(Builder.getInt8Ty(), AI->getSize());
1110     Alloca->setAlignment(MaybeAlign(AI->getAlignment()));
1111 
1112     for (auto U : AI->users()) {
1113       // Replace gets with the allocation.
1114       if (isa<CoroAllocaGetInst>(U)) {
1115         U->replaceAllUsesWith(Alloca);
1116 
1117       // Replace frees with stackrestores.  This is safe because
1118       // alloca.alloc is required to obey a stack discipline, although we
1119       // don't enforce that structurally.
1120       } else {
1121         auto FI = cast<CoroAllocaFreeInst>(U);
1122         if (StackSave) {
1123           Builder.SetInsertPoint(FI);
1124           Builder.CreateCall(
1125                     Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
1126                              StackSave);
1127         }
1128       }
1129       DeadInsts.push_back(cast<Instruction>(U));
1130     }
1131 
1132     DeadInsts.push_back(AI);
1133   }
1134 }
1135 
1136 /// Turn the given coro.alloca.alloc call into a dynamic allocation.
1137 /// This happens during the all-instructions iteration, so it must not
1138 /// delete the call.
1139 static Instruction *lowerNonLocalAlloca(CoroAllocaAllocInst *AI,
1140                                         coro::Shape &Shape,
1141                                    SmallVectorImpl<Instruction*> &DeadInsts) {
1142   IRBuilder<> Builder(AI);
1143   auto Alloc = Shape.emitAlloc(Builder, AI->getSize(), nullptr);
1144 
1145   for (User *U : AI->users()) {
1146     if (isa<CoroAllocaGetInst>(U)) {
1147       U->replaceAllUsesWith(Alloc);
1148     } else {
1149       auto FI = cast<CoroAllocaFreeInst>(U);
1150       Builder.SetInsertPoint(FI);
1151       Shape.emitDealloc(Builder, Alloc, nullptr);
1152     }
1153     DeadInsts.push_back(cast<Instruction>(U));
1154   }
1155 
1156   // Push this on last so that it gets deleted after all the others.
1157   DeadInsts.push_back(AI);
1158 
1159   // Return the new allocation value so that we can check for needed spills.
1160   return cast<Instruction>(Alloc);
1161 }
1162 
1163 /// Get the current swifterror value.
1164 static Value *emitGetSwiftErrorValue(IRBuilder<> &Builder, Type *ValueTy,
1165                                      coro::Shape &Shape) {
1166   // Make a fake function pointer as a sort of intrinsic.
1167   auto FnTy = FunctionType::get(ValueTy, {}, false);
1168   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1169 
1170   auto Call = Builder.CreateCall(FnTy, Fn, {});
1171   Shape.SwiftErrorOps.push_back(Call);
1172 
1173   return Call;
1174 }
1175 
1176 /// Set the given value as the current swifterror value.
1177 ///
1178 /// Returns a slot that can be used as a swifterror slot.
1179 static Value *emitSetSwiftErrorValue(IRBuilder<> &Builder, Value *V,
1180                                      coro::Shape &Shape) {
1181   // Make a fake function pointer as a sort of intrinsic.
1182   auto FnTy = FunctionType::get(V->getType()->getPointerTo(),
1183                                 {V->getType()}, false);
1184   auto Fn = ConstantPointerNull::get(FnTy->getPointerTo());
1185 
1186   auto Call = Builder.CreateCall(FnTy, Fn, { V });
1187   Shape.SwiftErrorOps.push_back(Call);
1188 
1189   return Call;
1190 }
1191 
1192 /// Set the swifterror value from the given alloca before a call,
1193 /// then put in back in the alloca afterwards.
1194 ///
1195 /// Returns an address that will stand in for the swifterror slot
1196 /// until splitting.
1197 static Value *emitSetAndGetSwiftErrorValueAround(Instruction *Call,
1198                                                  AllocaInst *Alloca,
1199                                                  coro::Shape &Shape) {
1200   auto ValueTy = Alloca->getAllocatedType();
1201   IRBuilder<> Builder(Call);
1202 
1203   // Load the current value from the alloca and set it as the
1204   // swifterror value.
1205   auto ValueBeforeCall = Builder.CreateLoad(ValueTy, Alloca);
1206   auto Addr = emitSetSwiftErrorValue(Builder, ValueBeforeCall, Shape);
1207 
1208   // Move to after the call.  Since swifterror only has a guaranteed
1209   // value on normal exits, we can ignore implicit and explicit unwind
1210   // edges.
1211   if (isa<CallInst>(Call)) {
1212     Builder.SetInsertPoint(Call->getNextNode());
1213   } else {
1214     auto Invoke = cast<InvokeInst>(Call);
1215     Builder.SetInsertPoint(Invoke->getNormalDest()->getFirstNonPHIOrDbg());
1216   }
1217 
1218   // Get the current swifterror value and store it to the alloca.
1219   auto ValueAfterCall = emitGetSwiftErrorValue(Builder, ValueTy, Shape);
1220   Builder.CreateStore(ValueAfterCall, Alloca);
1221 
1222   return Addr;
1223 }
1224 
1225 /// Eliminate a formerly-swifterror alloca by inserting the get/set
1226 /// intrinsics and attempting to MemToReg the alloca away.
1227 static void eliminateSwiftErrorAlloca(Function &F, AllocaInst *Alloca,
1228                                       coro::Shape &Shape) {
1229   for (auto UI = Alloca->use_begin(), UE = Alloca->use_end(); UI != UE; ) {
1230     // We're likely changing the use list, so use a mutation-safe
1231     // iteration pattern.
1232     auto &Use = *UI;
1233     ++UI;
1234 
1235     // swifterror values can only be used in very specific ways.
1236     // We take advantage of that here.
1237     auto User = Use.getUser();
1238     if (isa<LoadInst>(User) || isa<StoreInst>(User))
1239       continue;
1240 
1241     assert(isa<CallInst>(User) || isa<InvokeInst>(User));
1242     auto Call = cast<Instruction>(User);
1243 
1244     auto Addr = emitSetAndGetSwiftErrorValueAround(Call, Alloca, Shape);
1245 
1246     // Use the returned slot address as the call argument.
1247     Use.set(Addr);
1248   }
1249 
1250   // All the uses should be loads and stores now.
1251   assert(isAllocaPromotable(Alloca));
1252 }
1253 
1254 /// "Eliminate" a swifterror argument by reducing it to the alloca case
1255 /// and then loading and storing in the prologue and epilog.
1256 ///
1257 /// The argument keeps the swifterror flag.
1258 static void eliminateSwiftErrorArgument(Function &F, Argument &Arg,
1259                                         coro::Shape &Shape,
1260                              SmallVectorImpl<AllocaInst*> &AllocasToPromote) {
1261   IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIOrDbg());
1262 
1263   auto ArgTy = cast<PointerType>(Arg.getType());
1264   auto ValueTy = ArgTy->getElementType();
1265 
1266   // Reduce to the alloca case:
1267 
1268   // Create an alloca and replace all uses of the arg with it.
1269   auto Alloca = Builder.CreateAlloca(ValueTy, ArgTy->getAddressSpace());
1270   Arg.replaceAllUsesWith(Alloca);
1271 
1272   // Set an initial value in the alloca.  swifterror is always null on entry.
1273   auto InitialValue = Constant::getNullValue(ValueTy);
1274   Builder.CreateStore(InitialValue, Alloca);
1275 
1276   // Find all the suspends in the function and save and restore around them.
1277   for (auto Suspend : Shape.CoroSuspends) {
1278     (void) emitSetAndGetSwiftErrorValueAround(Suspend, Alloca, Shape);
1279   }
1280 
1281   // Find all the coro.ends in the function and restore the error value.
1282   for (auto End : Shape.CoroEnds) {
1283     Builder.SetInsertPoint(End);
1284     auto FinalValue = Builder.CreateLoad(ValueTy, Alloca);
1285     (void) emitSetSwiftErrorValue(Builder, FinalValue, Shape);
1286   }
1287 
1288   // Now we can use the alloca logic.
1289   AllocasToPromote.push_back(Alloca);
1290   eliminateSwiftErrorAlloca(F, Alloca, Shape);
1291 }
1292 
1293 /// Eliminate all problematic uses of swifterror arguments and allocas
1294 /// from the function.  We'll fix them up later when splitting the function.
1295 static void eliminateSwiftError(Function &F, coro::Shape &Shape) {
1296   SmallVector<AllocaInst*, 4> AllocasToPromote;
1297 
1298   // Look for a swifterror argument.
1299   for (auto &Arg : F.args()) {
1300     if (!Arg.hasSwiftErrorAttr()) continue;
1301 
1302     eliminateSwiftErrorArgument(F, Arg, Shape, AllocasToPromote);
1303     break;
1304   }
1305 
1306   // Look for swifterror allocas.
1307   for (auto &Inst : F.getEntryBlock()) {
1308     auto Alloca = dyn_cast<AllocaInst>(&Inst);
1309     if (!Alloca || !Alloca->isSwiftError()) continue;
1310 
1311     // Clear the swifterror flag.
1312     Alloca->setSwiftError(false);
1313 
1314     AllocasToPromote.push_back(Alloca);
1315     eliminateSwiftErrorAlloca(F, Alloca, Shape);
1316   }
1317 
1318   // If we have any allocas to promote, compute a dominator tree and
1319   // promote them en masse.
1320   if (!AllocasToPromote.empty()) {
1321     DominatorTree DT(F);
1322     PromoteMemToReg(AllocasToPromote, DT);
1323   }
1324 }
1325 
1326 void coro::buildCoroutineFrame(Function &F, Shape &Shape) {
1327   // Lower coro.dbg.declare to coro.dbg.value, since we are going to rewrite
1328   // access to local variables.
1329   LowerDbgDeclare(F);
1330 
1331   eliminateSwiftError(F, Shape);
1332 
1333   if (Shape.ABI == coro::ABI::Switch &&
1334       Shape.SwitchLowering.PromiseAlloca) {
1335     Shape.getSwitchCoroId()->clearPromise();
1336   }
1337 
1338   // Make sure that all coro.save, coro.suspend and the fallthrough coro.end
1339   // intrinsics are in their own blocks to simplify the logic of building up
1340   // SuspendCrossing data.
1341   for (auto *CSI : Shape.CoroSuspends) {
1342     if (auto *Save = CSI->getCoroSave())
1343       splitAround(Save, "CoroSave");
1344     splitAround(CSI, "CoroSuspend");
1345   }
1346 
1347   // Put CoroEnds into their own blocks.
1348   for (CoroEndInst *CE : Shape.CoroEnds)
1349     splitAround(CE, "CoroEnd");
1350 
1351   // Transforms multi-edge PHI Nodes, so that any value feeding into a PHI will
1352   // never has its definition separated from the PHI by the suspend point.
1353   rewritePHIs(F);
1354 
1355   // Build suspend crossing info.
1356   SuspendCrossingInfo Checker(F, Shape);
1357 
1358   IRBuilder<> Builder(F.getContext());
1359   SpillInfo Spills;
1360   SmallVector<CoroAllocaAllocInst*, 4> LocalAllocas;
1361   SmallVector<Instruction*, 4> DeadInstructions;
1362 
1363   for (int Repeat = 0; Repeat < 4; ++Repeat) {
1364     // See if there are materializable instructions across suspend points.
1365     for (Instruction &I : instructions(F))
1366       if (materializable(I))
1367         for (User *U : I.users())
1368           if (Checker.isDefinitionAcrossSuspend(I, U))
1369             Spills.emplace_back(&I, U);
1370 
1371     if (Spills.empty())
1372       break;
1373 
1374     // Rewrite materializable instructions to be materialized at the use point.
1375     LLVM_DEBUG(dump("Materializations", Spills));
1376     rewriteMaterializableInstructions(Builder, Spills);
1377     Spills.clear();
1378   }
1379 
1380   // Collect the spills for arguments and other not-materializable values.
1381   for (Argument &A : F.args())
1382     for (User *U : A.users())
1383       if (Checker.isDefinitionAcrossSuspend(A, U))
1384         Spills.emplace_back(&A, U);
1385 
1386   for (Instruction &I : instructions(F)) {
1387     // Values returned from coroutine structure intrinsics should not be part
1388     // of the Coroutine Frame.
1389     if (isCoroutineStructureIntrinsic(I) || &I == Shape.CoroBegin)
1390       continue;
1391 
1392     // The Coroutine Promise always included into coroutine frame, no need to
1393     // check for suspend crossing.
1394     if (Shape.ABI == coro::ABI::Switch &&
1395         Shape.SwitchLowering.PromiseAlloca == &I)
1396       continue;
1397 
1398     // Handle alloca.alloc specially here.
1399     if (auto AI = dyn_cast<CoroAllocaAllocInst>(&I)) {
1400       // Check whether the alloca's lifetime is bounded by suspend points.
1401       if (isLocalAlloca(AI)) {
1402         LocalAllocas.push_back(AI);
1403         continue;
1404       }
1405 
1406       // If not, do a quick rewrite of the alloca and then add spills of
1407       // the rewritten value.  The rewrite doesn't invalidate anything in
1408       // Spills because the other alloca intrinsics have no other operands
1409       // besides AI, and it doesn't invalidate the iteration because we delay
1410       // erasing AI.
1411       auto Alloc = lowerNonLocalAlloca(AI, Shape, DeadInstructions);
1412 
1413       for (User *U : Alloc->users()) {
1414         if (Checker.isDefinitionAcrossSuspend(*Alloc, U))
1415           Spills.emplace_back(Alloc, U);
1416       }
1417       continue;
1418     }
1419 
1420     // Ignore alloca.get; we process this as part of coro.alloca.alloc.
1421     if (isa<CoroAllocaGetInst>(I)) {
1422       continue;
1423     }
1424 
1425     for (User *U : I.users())
1426       if (Checker.isDefinitionAcrossSuspend(I, U)) {
1427         // We cannot spill a token.
1428         if (I.getType()->isTokenTy())
1429           report_fatal_error(
1430               "token definition is separated from the use by a suspend point");
1431         Spills.emplace_back(&I, U);
1432       }
1433   }
1434   LLVM_DEBUG(dump("Spills", Spills));
1435   Shape.FrameTy = buildFrameType(F, Shape, Spills);
1436   Shape.FramePtr = insertSpills(Spills, Shape);
1437   lowerLocalAllocas(LocalAllocas, DeadInstructions);
1438 
1439   for (auto I : DeadInstructions)
1440     I->eraseFromParent();
1441 }
1442