1 //===- CoroElide.cpp - Coroutine Frame Allocation Elision Pass ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // This pass replaces dynamic allocation of coroutine frame with alloca and
10 // replaces calls to llvm.coro.resume and llvm.coro.destroy with direct calls
11 // to coroutine sub-functions.
12 //===----------------------------------------------------------------------===//
13 
14 #include "CoroInternal.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/InstIterator.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/ErrorHandling.h"
20 
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "coro-elide"
24 
25 namespace {
26 // Created on demand if CoroElide pass has work to do.
27 struct Lowerer : coro::LowererBase {
28   SmallVector<CoroIdInst *, 4> CoroIds;
29   SmallVector<CoroBeginInst *, 1> CoroBegins;
30   SmallVector<CoroAllocInst *, 1> CoroAllocs;
31   SmallVector<CoroSubFnInst *, 4> ResumeAddr;
32   SmallVector<CoroSubFnInst *, 4> DestroyAddr;
33   SmallVector<CoroFreeInst *, 1> CoroFrees;
34 
35   Lowerer(Module &M) : LowererBase(M) {}
36 
37   void elideHeapAllocations(Function *F, Type *FrameTy, AAResults &AA);
38   bool processCoroId(CoroIdInst *, AAResults &AA);
39 };
40 } // end anonymous namespace
41 
42 // Go through the list of coro.subfn.addr intrinsics and replace them with the
43 // provided constant.
44 static void replaceWithConstant(Constant *Value,
45                                 SmallVectorImpl<CoroSubFnInst *> &Users) {
46   if (Users.empty())
47     return;
48 
49   // See if we need to bitcast the constant to match the type of the intrinsic
50   // being replaced. Note: All coro.subfn.addr intrinsics return the same type,
51   // so we only need to examine the type of the first one in the list.
52   Type *IntrTy = Users.front()->getType();
53   Type *ValueTy = Value->getType();
54   if (ValueTy != IntrTy) {
55     // May need to tweak the function type to match the type expected at the
56     // use site.
57     assert(ValueTy->isPointerTy() && IntrTy->isPointerTy());
58     Value = ConstantExpr::getBitCast(Value, IntrTy);
59   }
60 
61   // Now the value type matches the type of the intrinsic. Replace them all!
62   for (CoroSubFnInst *I : Users)
63     replaceAndRecursivelySimplify(I, Value);
64 }
65 
66 // See if any operand of the call instruction references the coroutine frame.
67 static bool operandReferences(CallInst *CI, AllocaInst *Frame, AAResults &AA) {
68   for (Value *Op : CI->operand_values())
69     if (AA.alias(Op, Frame) != NoAlias)
70       return true;
71   return false;
72 }
73 
74 // Look for any tail calls referencing the coroutine frame and remove tail
75 // attribute from them, since now coroutine frame resides on the stack and tail
76 // call implies that the function does not references anything on the stack.
77 static void removeTailCallAttribute(AllocaInst *Frame, AAResults &AA) {
78   Function &F = *Frame->getFunction();
79   MemoryLocation Mem(Frame);
80   for (Instruction &I : instructions(F))
81     if (auto *Call = dyn_cast<CallInst>(&I))
82       if (Call->isTailCall() && operandReferences(Call, Frame, AA)) {
83         // FIXME: If we ever hit this check. Evaluate whether it is more
84         // appropriate to retain musttail and allow the code to compile.
85         if (Call->isMustTailCall())
86           report_fatal_error("Call referring to the coroutine frame cannot be "
87                              "marked as musttail");
88         Call->setTailCall(false);
89       }
90 }
91 
92 // Given a resume function @f.resume(%f.frame* %frame), returns %f.frame type.
93 static Type *getFrameType(Function *Resume) {
94   auto *ArgType = Resume->getArgumentList().front().getType();
95   return cast<PointerType>(ArgType)->getElementType();
96 }
97 
98 // Finds first non alloca instruction in the entry block of a function.
99 static Instruction *getFirstNonAllocaInTheEntryBlock(Function *F) {
100   for (Instruction &I : F->getEntryBlock())
101     if (!isa<AllocaInst>(&I))
102       return &I;
103   llvm_unreachable("no terminator in the entry block");
104 }
105 
106 // To elide heap allocations we need to suppress code blocks guarded by
107 // llvm.coro.alloc and llvm.coro.free instructions.
108 void Lowerer::elideHeapAllocations(Function *F, Type *FrameTy, AAResults &AA) {
109   LLVMContext &C = FrameTy->getContext();
110   auto *InsertPt =
111       getFirstNonAllocaInTheEntryBlock(CoroIds.front()->getFunction());
112 
113   // Replacing llvm.coro.alloc with false will suppress dynamic
114   // allocation as it is expected for the frontend to generate the code that
115   // looks like:
116   //   id = coro.id(...)
117   //   mem = coro.alloc(id) ? malloc(coro.size()) : 0;
118   //   coro.begin(id, mem)
119   auto *False = ConstantInt::getFalse(C);
120   for (auto *CA : CoroAllocs) {
121     CA->replaceAllUsesWith(False);
122     CA->eraseFromParent();
123   }
124 
125   // To suppress deallocation code, we replace all llvm.coro.free intrinsics
126   // associated with this coro.begin with null constant.
127   auto *NullPtr = ConstantPointerNull::get(Type::getInt8PtrTy(C));
128   for (auto *CF : CoroFrees) {
129     CF->replaceAllUsesWith(NullPtr);
130     CF->eraseFromParent();
131   }
132 
133   // FIXME: Design how to transmit alignment information for every alloca that
134   // is spilled into the coroutine frame and recreate the alignment information
135   // here. Possibly we will need to do a mini SROA here and break the coroutine
136   // frame into individual AllocaInst recreating the original alignment.
137   auto *Frame = new AllocaInst(FrameTy, "", InsertPt);
138   auto *FrameVoidPtr =
139       new BitCastInst(Frame, Type::getInt8PtrTy(C), "vFrame", InsertPt);
140 
141   for (auto *CB : CoroBegins) {
142     CB->replaceAllUsesWith(FrameVoidPtr);
143     CB->eraseFromParent();
144   }
145 
146   // Since now coroutine frame lives on the stack we need to make sure that
147   // any tail call referencing it, must be made non-tail call.
148   removeTailCallAttribute(Frame, AA);
149 }
150 
151 bool Lowerer::processCoroId(CoroIdInst *CoroId, AAResults &AA) {
152   CoroBegins.clear();
153   CoroAllocs.clear();
154   ResumeAddr.clear();
155   DestroyAddr.clear();
156 
157   // Collect all coro.begin and coro.allocs associated with this coro.id.
158   for (User *U : CoroId->users()) {
159     if (auto *CB = dyn_cast<CoroBeginInst>(U))
160       CoroBegins.push_back(CB);
161     else if (auto *CA = dyn_cast<CoroAllocInst>(U))
162       CoroAllocs.push_back(CA);
163   }
164 
165   // Collect all coro.subfn.addrs associated with coro.begin.
166   // Note, we only devirtualize the calls if their coro.subfn.addr refers to
167   // coro.begin directly. If we run into cases where this check is too
168   // conservative, we can consider relaxing the check.
169   for (CoroBeginInst *CB : CoroBegins) {
170     for (User *U : CB->users())
171       if (auto *II = dyn_cast<CoroSubFnInst>(U))
172         switch (II->getIndex()) {
173         case CoroSubFnInst::ResumeIndex:
174           ResumeAddr.push_back(II);
175           break;
176         case CoroSubFnInst::DestroyIndex:
177           DestroyAddr.push_back(II);
178           break;
179         default:
180           llvm_unreachable("unexpected coro.subfn.addr constant");
181         }
182   }
183 
184   // PostSplit coro.id refers to an array of subfunctions in its Info
185   // argument.
186   ConstantArray *Resumers = CoroId->getInfo().Resumers;
187   assert(Resumers && "PostSplit coro.id Info argument must refer to an array"
188                      "of coroutine subfunctions");
189   auto *ResumeAddrConstant =
190       ConstantExpr::getExtractValue(Resumers, CoroSubFnInst::ResumeIndex);
191 
192   replaceWithConstant(ResumeAddrConstant, ResumeAddr);
193 
194   if (DestroyAddr.empty())
195     return true;
196 
197   auto *DestroyAddrConstant =
198       ConstantExpr::getExtractValue(Resumers, CoroSubFnInst::DestroyIndex);
199 
200   replaceWithConstant(DestroyAddrConstant, DestroyAddr);
201 
202   // If there is a coro.alloc that llvm.coro.id refers to, we have the ability
203   // to suppress dynamic allocation.
204   if (!CoroAllocs.empty()) {
205     // FIXME: The check above is overly lax. It only checks for whether we have
206     // an ability to elide heap allocations, not whether it is safe to do so.
207     // We need to do something like:
208     // If for every exit from the function where coro.begin is
209     // live, there is a coro.free or coro.destroy dominating that exit block,
210     // then it is safe to elide heap allocation, since the lifetime of coroutine
211     // is fully enclosed in its caller.
212     auto *FrameTy = getFrameType(cast<Function>(ResumeAddrConstant));
213     elideHeapAllocations(CoroId->getFunction(), FrameTy, AA);
214   }
215   return true;
216 }
217 
218 // See if there are any coro.subfn.addr instructions referring to coro.devirt
219 // trigger, if so, replace them with a direct call to devirt trigger function.
220 static bool replaceDevirtTrigger(Function &F) {
221   SmallVector<CoroSubFnInst *, 1> DevirtAddr;
222   for (auto &I : instructions(F))
223     if (auto *SubFn = dyn_cast<CoroSubFnInst>(&I))
224       if (SubFn->getIndex() == CoroSubFnInst::RestartTrigger)
225         DevirtAddr.push_back(SubFn);
226 
227   if (DevirtAddr.empty())
228     return false;
229 
230   Module &M = *F.getParent();
231   Function *DevirtFn = M.getFunction(CORO_DEVIRT_TRIGGER_FN);
232   assert(DevirtFn && "coro.devirt.fn not found");
233   replaceWithConstant(DevirtFn, DevirtAddr);
234 
235   return true;
236 }
237 
238 //===----------------------------------------------------------------------===//
239 //                              Top Level Driver
240 //===----------------------------------------------------------------------===//
241 
242 namespace {
243 struct CoroElide : FunctionPass {
244   static char ID;
245   CoroElide() : FunctionPass(ID) {}
246 
247   std::unique_ptr<Lowerer> L;
248 
249   bool doInitialization(Module &M) override {
250     if (coro::declaresIntrinsics(M, {"llvm.coro.id"}))
251       L = llvm::make_unique<Lowerer>(M);
252     return false;
253   }
254 
255   bool runOnFunction(Function &F) override {
256     if (!L)
257       return false;
258 
259     bool Changed = false;
260 
261     if (F.hasFnAttribute(CORO_PRESPLIT_ATTR))
262       Changed = replaceDevirtTrigger(F);
263 
264     L->CoroIds.clear();
265     L->CoroFrees.clear();
266 
267     // Collect all PostSplit coro.ids and all coro.free.
268     for (auto &I : instructions(F))
269       if (auto *CF = dyn_cast<CoroFreeInst>(&I))
270         L->CoroFrees.push_back(CF);
271       else if (auto *CII = dyn_cast<CoroIdInst>(&I))
272         if (CII->getInfo().isPostSplit())
273           L->CoroIds.push_back(CII);
274 
275     // If we did not find any coro.id, there is nothing to do.
276     if (L->CoroIds.empty())
277       return Changed;
278 
279     AAResults &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
280     for (auto *CII : L->CoroIds)
281       Changed |= L->processCoroId(CII, AA);
282 
283     return Changed;
284   }
285   void getAnalysisUsage(AnalysisUsage &AU) const override {
286     AU.addRequired<AAResultsWrapperPass>();
287     AU.setPreservesCFG();
288   }
289 };
290 }
291 
292 char CoroElide::ID = 0;
293 INITIALIZE_PASS_BEGIN(
294     CoroElide, "coro-elide",
295     "Coroutine frame allocation elision and indirect calls replacement", false,
296     false)
297 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
298 INITIALIZE_PASS_END(
299     CoroElide, "coro-elide",
300     "Coroutine frame allocation elision and indirect calls replacement", false,
301     false)
302 
303 Pass *llvm::createCoroElidePass() { return new CoroElide(); }
304