xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/PlaceSafepoints.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // Place garbage collection safepoints at appropriate locations in the IR. This
11*9880d681SAndroid Build Coastguard Worker // does not make relocation semantics or variable liveness explicit.  That's
12*9880d681SAndroid Build Coastguard Worker // done by RewriteStatepointsForGC.
13*9880d681SAndroid Build Coastguard Worker //
14*9880d681SAndroid Build Coastguard Worker // Terminology:
15*9880d681SAndroid Build Coastguard Worker // - A call is said to be "parseable" if there is a stack map generated for the
16*9880d681SAndroid Build Coastguard Worker // return PC of the call.  A runtime can determine where values listed in the
17*9880d681SAndroid Build Coastguard Worker // deopt arguments and (after RewriteStatepointsForGC) gc arguments are located
18*9880d681SAndroid Build Coastguard Worker // on the stack when the code is suspended inside such a call.  Every parse
19*9880d681SAndroid Build Coastguard Worker // point is represented by a call wrapped in an gc.statepoint intrinsic.
20*9880d681SAndroid Build Coastguard Worker // - A "poll" is an explicit check in the generated code to determine if the
21*9880d681SAndroid Build Coastguard Worker // runtime needs the generated code to cooperate by calling a helper routine
22*9880d681SAndroid Build Coastguard Worker // and thus suspending its execution at a known state. The call to the helper
23*9880d681SAndroid Build Coastguard Worker // routine will be parseable.  The (gc & runtime specific) logic of a poll is
24*9880d681SAndroid Build Coastguard Worker // assumed to be provided in a function of the name "gc.safepoint_poll".
25*9880d681SAndroid Build Coastguard Worker //
26*9880d681SAndroid Build Coastguard Worker // We aim to insert polls such that running code can quickly be brought to a
27*9880d681SAndroid Build Coastguard Worker // well defined state for inspection by the collector.  In the current
28*9880d681SAndroid Build Coastguard Worker // implementation, this is done via the insertion of poll sites at method entry
29*9880d681SAndroid Build Coastguard Worker // and the backedge of most loops.  We try to avoid inserting more polls than
30*9880d681SAndroid Build Coastguard Worker // are necessary to ensure a finite period between poll sites.  This is not
31*9880d681SAndroid Build Coastguard Worker // because the poll itself is expensive in the generated code; it's not.  Polls
32*9880d681SAndroid Build Coastguard Worker // do tend to impact the optimizer itself in negative ways; we'd like to avoid
33*9880d681SAndroid Build Coastguard Worker // perturbing the optimization of the method as much as we can.
34*9880d681SAndroid Build Coastguard Worker //
35*9880d681SAndroid Build Coastguard Worker // We also need to make most call sites parseable.  The callee might execute a
36*9880d681SAndroid Build Coastguard Worker // poll (or otherwise be inspected by the GC).  If so, the entire stack
37*9880d681SAndroid Build Coastguard Worker // (including the suspended frame of the current method) must be parseable.
38*9880d681SAndroid Build Coastguard Worker //
39*9880d681SAndroid Build Coastguard Worker // This pass will insert:
40*9880d681SAndroid Build Coastguard Worker // - Call parse points ("call safepoints") for any call which may need to
41*9880d681SAndroid Build Coastguard Worker // reach a safepoint during the execution of the callee function.
42*9880d681SAndroid Build Coastguard Worker // - Backedge safepoint polls and entry safepoint polls to ensure that
43*9880d681SAndroid Build Coastguard Worker // executing code reaches a safepoint poll in a finite amount of time.
44*9880d681SAndroid Build Coastguard Worker //
45*9880d681SAndroid Build Coastguard Worker // We do not currently support return statepoints, but adding them would not
46*9880d681SAndroid Build Coastguard Worker // be hard.  They are not required for correctness - entry safepoints are an
47*9880d681SAndroid Build Coastguard Worker // alternative - but some GCs may prefer them.  Patches welcome.
48*9880d681SAndroid Build Coastguard Worker //
49*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
50*9880d681SAndroid Build Coastguard Worker 
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
52*9880d681SAndroid Build Coastguard Worker 
53*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
54*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
55*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CFG.h"
56*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ScalarEvolution.h"
57*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/CallSite.h"
58*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
59*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
60*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LegacyPassManager.h"
61*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Statepoint.h"
62*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
63*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
64*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
65*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Cloning.h"
67*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
68*9880d681SAndroid Build Coastguard Worker 
69*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "safepoint-placement"
70*9880d681SAndroid Build Coastguard Worker 
71*9880d681SAndroid Build Coastguard Worker STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
72*9880d681SAndroid Build Coastguard Worker STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
73*9880d681SAndroid Build Coastguard Worker 
74*9880d681SAndroid Build Coastguard Worker STATISTIC(CallInLoop,
75*9880d681SAndroid Build Coastguard Worker           "Number of loops without safepoints due to calls in loop");
76*9880d681SAndroid Build Coastguard Worker STATISTIC(FiniteExecution,
77*9880d681SAndroid Build Coastguard Worker           "Number of loops without safepoints finite execution");
78*9880d681SAndroid Build Coastguard Worker 
79*9880d681SAndroid Build Coastguard Worker using namespace llvm;
80*9880d681SAndroid Build Coastguard Worker 
81*9880d681SAndroid Build Coastguard Worker // Ignore opportunities to avoid placing safepoints on backedges, useful for
82*9880d681SAndroid Build Coastguard Worker // validation
83*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
84*9880d681SAndroid Build Coastguard Worker                                   cl::init(false));
85*9880d681SAndroid Build Coastguard Worker 
86*9880d681SAndroid Build Coastguard Worker /// How narrow does the trip count of a loop have to be to have to be considered
87*9880d681SAndroid Build Coastguard Worker /// "counted"?  Counted loops do not get safepoints at backedges.
88*9880d681SAndroid Build Coastguard Worker static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
89*9880d681SAndroid Build Coastguard Worker                                          cl::Hidden, cl::init(32));
90*9880d681SAndroid Build Coastguard Worker 
91*9880d681SAndroid Build Coastguard Worker // If true, split the backedge of a loop when placing the safepoint, otherwise
92*9880d681SAndroid Build Coastguard Worker // split the latch block itself.  Both are useful to support for
93*9880d681SAndroid Build Coastguard Worker // experimentation, but in practice, it looks like splitting the backedge
94*9880d681SAndroid Build Coastguard Worker // optimizes better.
95*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
96*9880d681SAndroid Build Coastguard Worker                                    cl::init(false));
97*9880d681SAndroid Build Coastguard Worker 
98*9880d681SAndroid Build Coastguard Worker namespace {
99*9880d681SAndroid Build Coastguard Worker 
100*9880d681SAndroid Build Coastguard Worker /// An analysis pass whose purpose is to identify each of the backedges in
101*9880d681SAndroid Build Coastguard Worker /// the function which require a safepoint poll to be inserted.
102*9880d681SAndroid Build Coastguard Worker struct PlaceBackedgeSafepointsImpl : public FunctionPass {
103*9880d681SAndroid Build Coastguard Worker   static char ID;
104*9880d681SAndroid Build Coastguard Worker 
105*9880d681SAndroid Build Coastguard Worker   /// The output of the pass - gives a list of each backedge (described by
106*9880d681SAndroid Build Coastguard Worker   /// pointing at the branch) which need a poll inserted.
107*9880d681SAndroid Build Coastguard Worker   std::vector<TerminatorInst *> PollLocations;
108*9880d681SAndroid Build Coastguard Worker 
109*9880d681SAndroid Build Coastguard Worker   /// True unless we're running spp-no-calls in which case we need to disable
110*9880d681SAndroid Build Coastguard Worker   /// the call-dependent placement opts.
111*9880d681SAndroid Build Coastguard Worker   bool CallSafepointsEnabled;
112*9880d681SAndroid Build Coastguard Worker 
113*9880d681SAndroid Build Coastguard Worker   ScalarEvolution *SE = nullptr;
114*9880d681SAndroid Build Coastguard Worker   DominatorTree *DT = nullptr;
115*9880d681SAndroid Build Coastguard Worker   LoopInfo *LI = nullptr;
116*9880d681SAndroid Build Coastguard Worker 
PlaceBackedgeSafepointsImpl__anond7d7cdcc0111::PlaceBackedgeSafepointsImpl117*9880d681SAndroid Build Coastguard Worker   PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
118*9880d681SAndroid Build Coastguard Worker       : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
119*9880d681SAndroid Build Coastguard Worker     initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
120*9880d681SAndroid Build Coastguard Worker   }
121*9880d681SAndroid Build Coastguard Worker 
122*9880d681SAndroid Build Coastguard Worker   bool runOnLoop(Loop *);
runOnLoopAndSubLoops__anond7d7cdcc0111::PlaceBackedgeSafepointsImpl123*9880d681SAndroid Build Coastguard Worker   void runOnLoopAndSubLoops(Loop *L) {
124*9880d681SAndroid Build Coastguard Worker     // Visit all the subloops
125*9880d681SAndroid Build Coastguard Worker     for (Loop *I : *L)
126*9880d681SAndroid Build Coastguard Worker       runOnLoopAndSubLoops(I);
127*9880d681SAndroid Build Coastguard Worker     runOnLoop(L);
128*9880d681SAndroid Build Coastguard Worker   }
129*9880d681SAndroid Build Coastguard Worker 
runOnFunction__anond7d7cdcc0111::PlaceBackedgeSafepointsImpl130*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &F) override {
131*9880d681SAndroid Build Coastguard Worker     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
132*9880d681SAndroid Build Coastguard Worker     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
133*9880d681SAndroid Build Coastguard Worker     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
134*9880d681SAndroid Build Coastguard Worker     for (Loop *I : *LI) {
135*9880d681SAndroid Build Coastguard Worker       runOnLoopAndSubLoops(I);
136*9880d681SAndroid Build Coastguard Worker     }
137*9880d681SAndroid Build Coastguard Worker     return false;
138*9880d681SAndroid Build Coastguard Worker   }
139*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage__anond7d7cdcc0111::PlaceBackedgeSafepointsImpl140*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
141*9880d681SAndroid Build Coastguard Worker     AU.addRequired<DominatorTreeWrapperPass>();
142*9880d681SAndroid Build Coastguard Worker     AU.addRequired<ScalarEvolutionWrapperPass>();
143*9880d681SAndroid Build Coastguard Worker     AU.addRequired<LoopInfoWrapperPass>();
144*9880d681SAndroid Build Coastguard Worker     // We no longer modify the IR at all in this pass.  Thus all
145*9880d681SAndroid Build Coastguard Worker     // analysis are preserved.
146*9880d681SAndroid Build Coastguard Worker     AU.setPreservesAll();
147*9880d681SAndroid Build Coastguard Worker   }
148*9880d681SAndroid Build Coastguard Worker };
149*9880d681SAndroid Build Coastguard Worker }
150*9880d681SAndroid Build Coastguard Worker 
151*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
152*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
153*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker namespace {
156*9880d681SAndroid Build Coastguard Worker struct PlaceSafepoints : public FunctionPass {
157*9880d681SAndroid Build Coastguard Worker   static char ID; // Pass identification, replacement for typeid
158*9880d681SAndroid Build Coastguard Worker 
PlaceSafepoints__anond7d7cdcc0211::PlaceSafepoints159*9880d681SAndroid Build Coastguard Worker   PlaceSafepoints() : FunctionPass(ID) {
160*9880d681SAndroid Build Coastguard Worker     initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
161*9880d681SAndroid Build Coastguard Worker   }
162*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &F) override;
163*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage__anond7d7cdcc0211::PlaceSafepoints164*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
165*9880d681SAndroid Build Coastguard Worker     // We modify the graph wholesale (inlining, block insertion, etc).  We
166*9880d681SAndroid Build Coastguard Worker     // preserve nothing at the moment.  We could potentially preserve dom tree
167*9880d681SAndroid Build Coastguard Worker     // if that was worth doing
168*9880d681SAndroid Build Coastguard Worker   }
169*9880d681SAndroid Build Coastguard Worker };
170*9880d681SAndroid Build Coastguard Worker }
171*9880d681SAndroid Build Coastguard Worker 
172*9880d681SAndroid Build Coastguard Worker // Insert a safepoint poll immediately before the given instruction.  Does
173*9880d681SAndroid Build Coastguard Worker // not handle the parsability of state at the runtime call, that's the
174*9880d681SAndroid Build Coastguard Worker // callers job.
175*9880d681SAndroid Build Coastguard Worker static void
176*9880d681SAndroid Build Coastguard Worker InsertSafepointPoll(Instruction *InsertBefore,
177*9880d681SAndroid Build Coastguard Worker                     std::vector<CallSite> &ParsePointsNeeded /*rval*/);
178*9880d681SAndroid Build Coastguard Worker 
needsStatepoint(const CallSite & CS)179*9880d681SAndroid Build Coastguard Worker static bool needsStatepoint(const CallSite &CS) {
180*9880d681SAndroid Build Coastguard Worker   if (callsGCLeafFunction(CS))
181*9880d681SAndroid Build Coastguard Worker     return false;
182*9880d681SAndroid Build Coastguard Worker   if (CS.isCall()) {
183*9880d681SAndroid Build Coastguard Worker     CallInst *call = cast<CallInst>(CS.getInstruction());
184*9880d681SAndroid Build Coastguard Worker     if (call->isInlineAsm())
185*9880d681SAndroid Build Coastguard Worker       return false;
186*9880d681SAndroid Build Coastguard Worker   }
187*9880d681SAndroid Build Coastguard Worker 
188*9880d681SAndroid Build Coastguard Worker   return !(isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS));
189*9880d681SAndroid Build Coastguard Worker }
190*9880d681SAndroid Build Coastguard Worker 
191*9880d681SAndroid Build Coastguard Worker /// Returns true if this loop is known to contain a call safepoint which
192*9880d681SAndroid Build Coastguard Worker /// must unconditionally execute on any iteration of the loop which returns
193*9880d681SAndroid Build Coastguard Worker /// to the loop header via an edge from Pred.  Returns a conservative correct
194*9880d681SAndroid Build Coastguard Worker /// answer; i.e. false is always valid.
containsUnconditionalCallSafepoint(Loop * L,BasicBlock * Header,BasicBlock * Pred,DominatorTree & DT)195*9880d681SAndroid Build Coastguard Worker static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
196*9880d681SAndroid Build Coastguard Worker                                                BasicBlock *Pred,
197*9880d681SAndroid Build Coastguard Worker                                                DominatorTree &DT) {
198*9880d681SAndroid Build Coastguard Worker   // In general, we're looking for any cut of the graph which ensures
199*9880d681SAndroid Build Coastguard Worker   // there's a call safepoint along every edge between Header and Pred.
200*9880d681SAndroid Build Coastguard Worker   // For the moment, we look only for the 'cuts' that consist of a single call
201*9880d681SAndroid Build Coastguard Worker   // instruction in a block which is dominated by the Header and dominates the
202*9880d681SAndroid Build Coastguard Worker   // loop latch (Pred) block.  Somewhat surprisingly, walking the entire chain
203*9880d681SAndroid Build Coastguard Worker   // of such dominating blocks gets substantially more occurrences than just
204*9880d681SAndroid Build Coastguard Worker   // checking the Pred and Header blocks themselves.  This may be due to the
205*9880d681SAndroid Build Coastguard Worker   // density of loop exit conditions caused by range and null checks.
206*9880d681SAndroid Build Coastguard Worker   // TODO: structure this as an analysis pass, cache the result for subloops,
207*9880d681SAndroid Build Coastguard Worker   // avoid dom tree recalculations
208*9880d681SAndroid Build Coastguard Worker   assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
209*9880d681SAndroid Build Coastguard Worker 
210*9880d681SAndroid Build Coastguard Worker   BasicBlock *Current = Pred;
211*9880d681SAndroid Build Coastguard Worker   while (true) {
212*9880d681SAndroid Build Coastguard Worker     for (Instruction &I : *Current) {
213*9880d681SAndroid Build Coastguard Worker       if (auto CS = CallSite(&I))
214*9880d681SAndroid Build Coastguard Worker         // Note: Technically, needing a safepoint isn't quite the right
215*9880d681SAndroid Build Coastguard Worker         // condition here.  We should instead be checking if the target method
216*9880d681SAndroid Build Coastguard Worker         // has an
217*9880d681SAndroid Build Coastguard Worker         // unconditional poll. In practice, this is only a theoretical concern
218*9880d681SAndroid Build Coastguard Worker         // since we don't have any methods with conditional-only safepoint
219*9880d681SAndroid Build Coastguard Worker         // polls.
220*9880d681SAndroid Build Coastguard Worker         if (needsStatepoint(CS))
221*9880d681SAndroid Build Coastguard Worker           return true;
222*9880d681SAndroid Build Coastguard Worker     }
223*9880d681SAndroid Build Coastguard Worker 
224*9880d681SAndroid Build Coastguard Worker     if (Current == Header)
225*9880d681SAndroid Build Coastguard Worker       break;
226*9880d681SAndroid Build Coastguard Worker     Current = DT.getNode(Current)->getIDom()->getBlock();
227*9880d681SAndroid Build Coastguard Worker   }
228*9880d681SAndroid Build Coastguard Worker 
229*9880d681SAndroid Build Coastguard Worker   return false;
230*9880d681SAndroid Build Coastguard Worker }
231*9880d681SAndroid Build Coastguard Worker 
232*9880d681SAndroid Build Coastguard Worker /// Returns true if this loop is known to terminate in a finite number of
233*9880d681SAndroid Build Coastguard Worker /// iterations.  Note that this function may return false for a loop which
234*9880d681SAndroid Build Coastguard Worker /// does actual terminate in a finite constant number of iterations due to
235*9880d681SAndroid Build Coastguard Worker /// conservatism in the analysis.
mustBeFiniteCountedLoop(Loop * L,ScalarEvolution * SE,BasicBlock * Pred)236*9880d681SAndroid Build Coastguard Worker static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
237*9880d681SAndroid Build Coastguard Worker                                     BasicBlock *Pred) {
238*9880d681SAndroid Build Coastguard Worker   // A conservative bound on the loop as a whole.
239*9880d681SAndroid Build Coastguard Worker   const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
240*9880d681SAndroid Build Coastguard Worker   if (MaxTrips != SE->getCouldNotCompute() &&
241*9880d681SAndroid Build Coastguard Worker       SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
242*9880d681SAndroid Build Coastguard Worker           CountedLoopTripWidth))
243*9880d681SAndroid Build Coastguard Worker     return true;
244*9880d681SAndroid Build Coastguard Worker 
245*9880d681SAndroid Build Coastguard Worker   // If this is a conditional branch to the header with the alternate path
246*9880d681SAndroid Build Coastguard Worker   // being outside the loop, we can ask questions about the execution frequency
247*9880d681SAndroid Build Coastguard Worker   // of the exit block.
248*9880d681SAndroid Build Coastguard Worker   if (L->isLoopExiting(Pred)) {
249*9880d681SAndroid Build Coastguard Worker     // This returns an exact expression only.  TODO: We really only need an
250*9880d681SAndroid Build Coastguard Worker     // upper bound here, but SE doesn't expose that.
251*9880d681SAndroid Build Coastguard Worker     const SCEV *MaxExec = SE->getExitCount(L, Pred);
252*9880d681SAndroid Build Coastguard Worker     if (MaxExec != SE->getCouldNotCompute() &&
253*9880d681SAndroid Build Coastguard Worker         SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
254*9880d681SAndroid Build Coastguard Worker             CountedLoopTripWidth))
255*9880d681SAndroid Build Coastguard Worker         return true;
256*9880d681SAndroid Build Coastguard Worker   }
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker   return /* not finite */ false;
259*9880d681SAndroid Build Coastguard Worker }
260*9880d681SAndroid Build Coastguard Worker 
scanOneBB(Instruction * Start,Instruction * End,std::vector<CallInst * > & Calls,DenseSet<BasicBlock * > & Seen,std::vector<BasicBlock * > & Worklist)261*9880d681SAndroid Build Coastguard Worker static void scanOneBB(Instruction *Start, Instruction *End,
262*9880d681SAndroid Build Coastguard Worker                       std::vector<CallInst *> &Calls,
263*9880d681SAndroid Build Coastguard Worker                       DenseSet<BasicBlock *> &Seen,
264*9880d681SAndroid Build Coastguard Worker                       std::vector<BasicBlock *> &Worklist) {
265*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator BBI(Start), BBE0 = Start->getParent()->end(),
266*9880d681SAndroid Build Coastguard Worker                                         BBE1 = BasicBlock::iterator(End);
267*9880d681SAndroid Build Coastguard Worker        BBI != BBE0 && BBI != BBE1; BBI++) {
268*9880d681SAndroid Build Coastguard Worker     if (CallInst *CI = dyn_cast<CallInst>(&*BBI))
269*9880d681SAndroid Build Coastguard Worker       Calls.push_back(CI);
270*9880d681SAndroid Build Coastguard Worker 
271*9880d681SAndroid Build Coastguard Worker     // FIXME: This code does not handle invokes
272*9880d681SAndroid Build Coastguard Worker     assert(!isa<InvokeInst>(&*BBI) &&
273*9880d681SAndroid Build Coastguard Worker            "support for invokes in poll code needed");
274*9880d681SAndroid Build Coastguard Worker 
275*9880d681SAndroid Build Coastguard Worker     // Only add the successor blocks if we reach the terminator instruction
276*9880d681SAndroid Build Coastguard Worker     // without encountering end first
277*9880d681SAndroid Build Coastguard Worker     if (BBI->isTerminator()) {
278*9880d681SAndroid Build Coastguard Worker       BasicBlock *BB = BBI->getParent();
279*9880d681SAndroid Build Coastguard Worker       for (BasicBlock *Succ : successors(BB)) {
280*9880d681SAndroid Build Coastguard Worker         if (Seen.insert(Succ).second) {
281*9880d681SAndroid Build Coastguard Worker           Worklist.push_back(Succ);
282*9880d681SAndroid Build Coastguard Worker         }
283*9880d681SAndroid Build Coastguard Worker       }
284*9880d681SAndroid Build Coastguard Worker     }
285*9880d681SAndroid Build Coastguard Worker   }
286*9880d681SAndroid Build Coastguard Worker }
287*9880d681SAndroid Build Coastguard Worker 
scanInlinedCode(Instruction * Start,Instruction * End,std::vector<CallInst * > & Calls,DenseSet<BasicBlock * > & Seen)288*9880d681SAndroid Build Coastguard Worker static void scanInlinedCode(Instruction *Start, Instruction *End,
289*9880d681SAndroid Build Coastguard Worker                             std::vector<CallInst *> &Calls,
290*9880d681SAndroid Build Coastguard Worker                             DenseSet<BasicBlock *> &Seen) {
291*9880d681SAndroid Build Coastguard Worker   Calls.clear();
292*9880d681SAndroid Build Coastguard Worker   std::vector<BasicBlock *> Worklist;
293*9880d681SAndroid Build Coastguard Worker   Seen.insert(Start->getParent());
294*9880d681SAndroid Build Coastguard Worker   scanOneBB(Start, End, Calls, Seen, Worklist);
295*9880d681SAndroid Build Coastguard Worker   while (!Worklist.empty()) {
296*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB = Worklist.back();
297*9880d681SAndroid Build Coastguard Worker     Worklist.pop_back();
298*9880d681SAndroid Build Coastguard Worker     scanOneBB(&*BB->begin(), End, Calls, Seen, Worklist);
299*9880d681SAndroid Build Coastguard Worker   }
300*9880d681SAndroid Build Coastguard Worker }
301*9880d681SAndroid Build Coastguard Worker 
runOnLoop(Loop * L)302*9880d681SAndroid Build Coastguard Worker bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
303*9880d681SAndroid Build Coastguard Worker   // Loop through all loop latches (branches controlling backedges).  We need
304*9880d681SAndroid Build Coastguard Worker   // to place a safepoint on every backedge (potentially).
305*9880d681SAndroid Build Coastguard Worker   // Note: In common usage, there will be only one edge due to LoopSimplify
306*9880d681SAndroid Build Coastguard Worker   // having run sometime earlier in the pipeline, but this code must be correct
307*9880d681SAndroid Build Coastguard Worker   // w.r.t. loops with multiple backedges.
308*9880d681SAndroid Build Coastguard Worker   BasicBlock *Header = L->getHeader();
309*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 16> LoopLatches;
310*9880d681SAndroid Build Coastguard Worker   L->getLoopLatches(LoopLatches);
311*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *Pred : LoopLatches) {
312*9880d681SAndroid Build Coastguard Worker     assert(L->contains(Pred));
313*9880d681SAndroid Build Coastguard Worker 
314*9880d681SAndroid Build Coastguard Worker     // Make a policy decision about whether this loop needs a safepoint or
315*9880d681SAndroid Build Coastguard Worker     // not.  Note that this is about unburdening the optimizer in loops, not
316*9880d681SAndroid Build Coastguard Worker     // avoiding the runtime cost of the actual safepoint.
317*9880d681SAndroid Build Coastguard Worker     if (!AllBackedges) {
318*9880d681SAndroid Build Coastguard Worker       if (mustBeFiniteCountedLoop(L, SE, Pred)) {
319*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "skipping safepoint placement in finite loop\n");
320*9880d681SAndroid Build Coastguard Worker         FiniteExecution++;
321*9880d681SAndroid Build Coastguard Worker         continue;
322*9880d681SAndroid Build Coastguard Worker       }
323*9880d681SAndroid Build Coastguard Worker       if (CallSafepointsEnabled &&
324*9880d681SAndroid Build Coastguard Worker           containsUnconditionalCallSafepoint(L, Header, Pred, *DT)) {
325*9880d681SAndroid Build Coastguard Worker         // Note: This is only semantically legal since we won't do any further
326*9880d681SAndroid Build Coastguard Worker         // IPO or inlining before the actual call insertion..  If we hadn't, we
327*9880d681SAndroid Build Coastguard Worker         // might latter loose this call safepoint.
328*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "skipping safepoint placement due to unconditional call\n");
329*9880d681SAndroid Build Coastguard Worker         CallInLoop++;
330*9880d681SAndroid Build Coastguard Worker         continue;
331*9880d681SAndroid Build Coastguard Worker       }
332*9880d681SAndroid Build Coastguard Worker     }
333*9880d681SAndroid Build Coastguard Worker 
334*9880d681SAndroid Build Coastguard Worker     // TODO: We can create an inner loop which runs a finite number of
335*9880d681SAndroid Build Coastguard Worker     // iterations with an outer loop which contains a safepoint.  This would
336*9880d681SAndroid Build Coastguard Worker     // not help runtime performance that much, but it might help our ability to
337*9880d681SAndroid Build Coastguard Worker     // optimize the inner loop.
338*9880d681SAndroid Build Coastguard Worker 
339*9880d681SAndroid Build Coastguard Worker     // Safepoint insertion would involve creating a new basic block (as the
340*9880d681SAndroid Build Coastguard Worker     // target of the current backedge) which does the safepoint (of all live
341*9880d681SAndroid Build Coastguard Worker     // variables) and branches to the true header
342*9880d681SAndroid Build Coastguard Worker     TerminatorInst *Term = Pred->getTerminator();
343*9880d681SAndroid Build Coastguard Worker 
344*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "[LSP] terminator instruction: " << *Term);
345*9880d681SAndroid Build Coastguard Worker 
346*9880d681SAndroid Build Coastguard Worker     PollLocations.push_back(Term);
347*9880d681SAndroid Build Coastguard Worker   }
348*9880d681SAndroid Build Coastguard Worker 
349*9880d681SAndroid Build Coastguard Worker   return false;
350*9880d681SAndroid Build Coastguard Worker }
351*9880d681SAndroid Build Coastguard Worker 
352*9880d681SAndroid Build Coastguard Worker /// Returns true if an entry safepoint is not required before this callsite in
353*9880d681SAndroid Build Coastguard Worker /// the caller function.
doesNotRequireEntrySafepointBefore(const CallSite & CS)354*9880d681SAndroid Build Coastguard Worker static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
355*9880d681SAndroid Build Coastguard Worker   Instruction *Inst = CS.getInstruction();
356*9880d681SAndroid Build Coastguard Worker   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
357*9880d681SAndroid Build Coastguard Worker     switch (II->getIntrinsicID()) {
358*9880d681SAndroid Build Coastguard Worker     case Intrinsic::experimental_gc_statepoint:
359*9880d681SAndroid Build Coastguard Worker     case Intrinsic::experimental_patchpoint_void:
360*9880d681SAndroid Build Coastguard Worker     case Intrinsic::experimental_patchpoint_i64:
361*9880d681SAndroid Build Coastguard Worker       // The can wrap an actual call which may grow the stack by an unbounded
362*9880d681SAndroid Build Coastguard Worker       // amount or run forever.
363*9880d681SAndroid Build Coastguard Worker       return false;
364*9880d681SAndroid Build Coastguard Worker     default:
365*9880d681SAndroid Build Coastguard Worker       // Most LLVM intrinsics are things which do not expand to actual calls, or
366*9880d681SAndroid Build Coastguard Worker       // at least if they do, are leaf functions that cause only finite stack
367*9880d681SAndroid Build Coastguard Worker       // growth.  In particular, the optimizer likes to form things like memsets
368*9880d681SAndroid Build Coastguard Worker       // out of stores in the original IR.  Another important example is
369*9880d681SAndroid Build Coastguard Worker       // llvm.localescape which must occur in the entry block.  Inserting a
370*9880d681SAndroid Build Coastguard Worker       // safepoint before it is not legal since it could push the localescape
371*9880d681SAndroid Build Coastguard Worker       // out of the entry block.
372*9880d681SAndroid Build Coastguard Worker       return true;
373*9880d681SAndroid Build Coastguard Worker     }
374*9880d681SAndroid Build Coastguard Worker   }
375*9880d681SAndroid Build Coastguard Worker   return false;
376*9880d681SAndroid Build Coastguard Worker }
377*9880d681SAndroid Build Coastguard Worker 
findLocationForEntrySafepoint(Function & F,DominatorTree & DT)378*9880d681SAndroid Build Coastguard Worker static Instruction *findLocationForEntrySafepoint(Function &F,
379*9880d681SAndroid Build Coastguard Worker                                                   DominatorTree &DT) {
380*9880d681SAndroid Build Coastguard Worker 
381*9880d681SAndroid Build Coastguard Worker   // Conceptually, this poll needs to be on method entry, but in
382*9880d681SAndroid Build Coastguard Worker   // practice, we place it as late in the entry block as possible.  We
383*9880d681SAndroid Build Coastguard Worker   // can place it as late as we want as long as it dominates all calls
384*9880d681SAndroid Build Coastguard Worker   // that can grow the stack.  This, combined with backedge polls,
385*9880d681SAndroid Build Coastguard Worker   // give us all the progress guarantees we need.
386*9880d681SAndroid Build Coastguard Worker 
387*9880d681SAndroid Build Coastguard Worker   // hasNextInstruction and nextInstruction are used to iterate
388*9880d681SAndroid Build Coastguard Worker   // through a "straight line" execution sequence.
389*9880d681SAndroid Build Coastguard Worker 
390*9880d681SAndroid Build Coastguard Worker   auto HasNextInstruction = [](Instruction *I) {
391*9880d681SAndroid Build Coastguard Worker     if (!I->isTerminator())
392*9880d681SAndroid Build Coastguard Worker       return true;
393*9880d681SAndroid Build Coastguard Worker 
394*9880d681SAndroid Build Coastguard Worker     BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
395*9880d681SAndroid Build Coastguard Worker     return nextBB && (nextBB->getUniquePredecessor() != nullptr);
396*9880d681SAndroid Build Coastguard Worker   };
397*9880d681SAndroid Build Coastguard Worker 
398*9880d681SAndroid Build Coastguard Worker   auto NextInstruction = [&](Instruction *I) {
399*9880d681SAndroid Build Coastguard Worker     assert(HasNextInstruction(I) &&
400*9880d681SAndroid Build Coastguard Worker            "first check if there is a next instruction!");
401*9880d681SAndroid Build Coastguard Worker 
402*9880d681SAndroid Build Coastguard Worker     if (I->isTerminator())
403*9880d681SAndroid Build Coastguard Worker       return &I->getParent()->getUniqueSuccessor()->front();
404*9880d681SAndroid Build Coastguard Worker     return &*++I->getIterator();
405*9880d681SAndroid Build Coastguard Worker   };
406*9880d681SAndroid Build Coastguard Worker 
407*9880d681SAndroid Build Coastguard Worker   Instruction *Cursor = nullptr;
408*9880d681SAndroid Build Coastguard Worker   for (Cursor = &F.getEntryBlock().front(); HasNextInstruction(Cursor);
409*9880d681SAndroid Build Coastguard Worker        Cursor = NextInstruction(Cursor)) {
410*9880d681SAndroid Build Coastguard Worker 
411*9880d681SAndroid Build Coastguard Worker     // We need to ensure a safepoint poll occurs before any 'real' call.  The
412*9880d681SAndroid Build Coastguard Worker     // easiest way to ensure finite execution between safepoints in the face of
413*9880d681SAndroid Build Coastguard Worker     // recursive and mutually recursive functions is to enforce that each take
414*9880d681SAndroid Build Coastguard Worker     // a safepoint.  Additionally, we need to ensure a poll before any call
415*9880d681SAndroid Build Coastguard Worker     // which can grow the stack by an unbounded amount.  This isn't required
416*9880d681SAndroid Build Coastguard Worker     // for GC semantics per se, but is a common requirement for languages
417*9880d681SAndroid Build Coastguard Worker     // which detect stack overflow via guard pages and then throw exceptions.
418*9880d681SAndroid Build Coastguard Worker     if (auto CS = CallSite(Cursor)) {
419*9880d681SAndroid Build Coastguard Worker       if (doesNotRequireEntrySafepointBefore(CS))
420*9880d681SAndroid Build Coastguard Worker         continue;
421*9880d681SAndroid Build Coastguard Worker       break;
422*9880d681SAndroid Build Coastguard Worker     }
423*9880d681SAndroid Build Coastguard Worker   }
424*9880d681SAndroid Build Coastguard Worker 
425*9880d681SAndroid Build Coastguard Worker   assert((HasNextInstruction(Cursor) || Cursor->isTerminator()) &&
426*9880d681SAndroid Build Coastguard Worker          "either we stopped because of a call, or because of terminator");
427*9880d681SAndroid Build Coastguard Worker 
428*9880d681SAndroid Build Coastguard Worker   return Cursor;
429*9880d681SAndroid Build Coastguard Worker }
430*9880d681SAndroid Build Coastguard Worker 
431*9880d681SAndroid Build Coastguard Worker static const char *const GCSafepointPollName = "gc.safepoint_poll";
432*9880d681SAndroid Build Coastguard Worker 
isGCSafepointPoll(Function & F)433*9880d681SAndroid Build Coastguard Worker static bool isGCSafepointPoll(Function &F) {
434*9880d681SAndroid Build Coastguard Worker   return F.getName().equals(GCSafepointPollName);
435*9880d681SAndroid Build Coastguard Worker }
436*9880d681SAndroid Build Coastguard Worker 
437*9880d681SAndroid Build Coastguard Worker /// Returns true if this function should be rewritten to include safepoint
438*9880d681SAndroid Build Coastguard Worker /// polls and parseable call sites.  The main point of this function is to be
439*9880d681SAndroid Build Coastguard Worker /// an extension point for custom logic.
shouldRewriteFunction(Function & F)440*9880d681SAndroid Build Coastguard Worker static bool shouldRewriteFunction(Function &F) {
441*9880d681SAndroid Build Coastguard Worker   // TODO: This should check the GCStrategy
442*9880d681SAndroid Build Coastguard Worker   if (F.hasGC()) {
443*9880d681SAndroid Build Coastguard Worker     const auto &FunctionGCName = F.getGC();
444*9880d681SAndroid Build Coastguard Worker     const StringRef StatepointExampleName("statepoint-example");
445*9880d681SAndroid Build Coastguard Worker     const StringRef CoreCLRName("coreclr");
446*9880d681SAndroid Build Coastguard Worker     return (StatepointExampleName == FunctionGCName) ||
447*9880d681SAndroid Build Coastguard Worker            (CoreCLRName == FunctionGCName);
448*9880d681SAndroid Build Coastguard Worker   } else
449*9880d681SAndroid Build Coastguard Worker     return false;
450*9880d681SAndroid Build Coastguard Worker }
451*9880d681SAndroid Build Coastguard Worker 
452*9880d681SAndroid Build Coastguard Worker // TODO: These should become properties of the GCStrategy, possibly with
453*9880d681SAndroid Build Coastguard Worker // command line overrides.
enableEntrySafepoints(Function & F)454*9880d681SAndroid Build Coastguard Worker static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
enableBackedgeSafepoints(Function & F)455*9880d681SAndroid Build Coastguard Worker static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
enableCallSafepoints(Function & F)456*9880d681SAndroid Build Coastguard Worker static bool enableCallSafepoints(Function &F) { return !NoCall; }
457*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)458*9880d681SAndroid Build Coastguard Worker bool PlaceSafepoints::runOnFunction(Function &F) {
459*9880d681SAndroid Build Coastguard Worker   if (F.isDeclaration() || F.empty()) {
460*9880d681SAndroid Build Coastguard Worker     // This is a declaration, nothing to do.  Must exit early to avoid crash in
461*9880d681SAndroid Build Coastguard Worker     // dom tree calculation
462*9880d681SAndroid Build Coastguard Worker     return false;
463*9880d681SAndroid Build Coastguard Worker   }
464*9880d681SAndroid Build Coastguard Worker 
465*9880d681SAndroid Build Coastguard Worker   if (isGCSafepointPoll(F)) {
466*9880d681SAndroid Build Coastguard Worker     // Given we're inlining this inside of safepoint poll insertion, this
467*9880d681SAndroid Build Coastguard Worker     // doesn't make any sense.  Note that we do make any contained calls
468*9880d681SAndroid Build Coastguard Worker     // parseable after we inline a poll.
469*9880d681SAndroid Build Coastguard Worker     return false;
470*9880d681SAndroid Build Coastguard Worker   }
471*9880d681SAndroid Build Coastguard Worker 
472*9880d681SAndroid Build Coastguard Worker   if (!shouldRewriteFunction(F))
473*9880d681SAndroid Build Coastguard Worker     return false;
474*9880d681SAndroid Build Coastguard Worker 
475*9880d681SAndroid Build Coastguard Worker   bool Modified = false;
476*9880d681SAndroid Build Coastguard Worker 
477*9880d681SAndroid Build Coastguard Worker   // In various bits below, we rely on the fact that uses are reachable from
478*9880d681SAndroid Build Coastguard Worker   // defs.  When there are basic blocks unreachable from the entry, dominance
479*9880d681SAndroid Build Coastguard Worker   // and reachablity queries return non-sensical results.  Thus, we preprocess
480*9880d681SAndroid Build Coastguard Worker   // the function to ensure these properties hold.
481*9880d681SAndroid Build Coastguard Worker   Modified |= removeUnreachableBlocks(F);
482*9880d681SAndroid Build Coastguard Worker 
483*9880d681SAndroid Build Coastguard Worker   // STEP 1 - Insert the safepoint polling locations.  We do not need to
484*9880d681SAndroid Build Coastguard Worker   // actually insert parse points yet.  That will be done for all polls and
485*9880d681SAndroid Build Coastguard Worker   // calls in a single pass.
486*9880d681SAndroid Build Coastguard Worker 
487*9880d681SAndroid Build Coastguard Worker   DominatorTree DT;
488*9880d681SAndroid Build Coastguard Worker   DT.recalculate(F);
489*9880d681SAndroid Build Coastguard Worker 
490*9880d681SAndroid Build Coastguard Worker   SmallVector<Instruction *, 16> PollsNeeded;
491*9880d681SAndroid Build Coastguard Worker   std::vector<CallSite> ParsePointNeeded;
492*9880d681SAndroid Build Coastguard Worker 
493*9880d681SAndroid Build Coastguard Worker   if (enableBackedgeSafepoints(F)) {
494*9880d681SAndroid Build Coastguard Worker     // Construct a pass manager to run the LoopPass backedge logic.  We
495*9880d681SAndroid Build Coastguard Worker     // need the pass manager to handle scheduling all the loop passes
496*9880d681SAndroid Build Coastguard Worker     // appropriately.  Doing this by hand is painful and just not worth messing
497*9880d681SAndroid Build Coastguard Worker     // with for the moment.
498*9880d681SAndroid Build Coastguard Worker     legacy::FunctionPassManager FPM(F.getParent());
499*9880d681SAndroid Build Coastguard Worker     bool CanAssumeCallSafepoints = enableCallSafepoints(F);
500*9880d681SAndroid Build Coastguard Worker     auto *PBS = new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
501*9880d681SAndroid Build Coastguard Worker     FPM.add(PBS);
502*9880d681SAndroid Build Coastguard Worker     FPM.run(F);
503*9880d681SAndroid Build Coastguard Worker 
504*9880d681SAndroid Build Coastguard Worker     // We preserve dominance information when inserting the poll, otherwise
505*9880d681SAndroid Build Coastguard Worker     // we'd have to recalculate this on every insert
506*9880d681SAndroid Build Coastguard Worker     DT.recalculate(F);
507*9880d681SAndroid Build Coastguard Worker 
508*9880d681SAndroid Build Coastguard Worker     auto &PollLocations = PBS->PollLocations;
509*9880d681SAndroid Build Coastguard Worker 
510*9880d681SAndroid Build Coastguard Worker     auto OrderByBBName = [](Instruction *a, Instruction *b) {
511*9880d681SAndroid Build Coastguard Worker       return a->getParent()->getName() < b->getParent()->getName();
512*9880d681SAndroid Build Coastguard Worker     };
513*9880d681SAndroid Build Coastguard Worker     // We need the order of list to be stable so that naming ends up stable
514*9880d681SAndroid Build Coastguard Worker     // when we split edges.  This makes test cases much easier to write.
515*9880d681SAndroid Build Coastguard Worker     std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
516*9880d681SAndroid Build Coastguard Worker 
517*9880d681SAndroid Build Coastguard Worker     // We can sometimes end up with duplicate poll locations.  This happens if
518*9880d681SAndroid Build Coastguard Worker     // a single loop is visited more than once.   The fact this happens seems
519*9880d681SAndroid Build Coastguard Worker     // wrong, but it does happen for the split-backedge.ll test case.
520*9880d681SAndroid Build Coastguard Worker     PollLocations.erase(std::unique(PollLocations.begin(),
521*9880d681SAndroid Build Coastguard Worker                                     PollLocations.end()),
522*9880d681SAndroid Build Coastguard Worker                         PollLocations.end());
523*9880d681SAndroid Build Coastguard Worker 
524*9880d681SAndroid Build Coastguard Worker     // Insert a poll at each point the analysis pass identified
525*9880d681SAndroid Build Coastguard Worker     // The poll location must be the terminator of a loop latch block.
526*9880d681SAndroid Build Coastguard Worker     for (TerminatorInst *Term : PollLocations) {
527*9880d681SAndroid Build Coastguard Worker       // We are inserting a poll, the function is modified
528*9880d681SAndroid Build Coastguard Worker       Modified = true;
529*9880d681SAndroid Build Coastguard Worker 
530*9880d681SAndroid Build Coastguard Worker       if (SplitBackedge) {
531*9880d681SAndroid Build Coastguard Worker         // Split the backedge of the loop and insert the poll within that new
532*9880d681SAndroid Build Coastguard Worker         // basic block.  This creates a loop with two latches per original
533*9880d681SAndroid Build Coastguard Worker         // latch (which is non-ideal), but this appears to be easier to
534*9880d681SAndroid Build Coastguard Worker         // optimize in practice than inserting the poll immediately before the
535*9880d681SAndroid Build Coastguard Worker         // latch test.
536*9880d681SAndroid Build Coastguard Worker 
537*9880d681SAndroid Build Coastguard Worker         // Since this is a latch, at least one of the successors must dominate
538*9880d681SAndroid Build Coastguard Worker         // it. Its possible that we have a) duplicate edges to the same header
539*9880d681SAndroid Build Coastguard Worker         // and b) edges to distinct loop headers.  We need to insert pools on
540*9880d681SAndroid Build Coastguard Worker         // each.
541*9880d681SAndroid Build Coastguard Worker         SetVector<BasicBlock *> Headers;
542*9880d681SAndroid Build Coastguard Worker         for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
543*9880d681SAndroid Build Coastguard Worker           BasicBlock *Succ = Term->getSuccessor(i);
544*9880d681SAndroid Build Coastguard Worker           if (DT.dominates(Succ, Term->getParent())) {
545*9880d681SAndroid Build Coastguard Worker             Headers.insert(Succ);
546*9880d681SAndroid Build Coastguard Worker           }
547*9880d681SAndroid Build Coastguard Worker         }
548*9880d681SAndroid Build Coastguard Worker         assert(!Headers.empty() && "poll location is not a loop latch?");
549*9880d681SAndroid Build Coastguard Worker 
550*9880d681SAndroid Build Coastguard Worker         // The split loop structure here is so that we only need to recalculate
551*9880d681SAndroid Build Coastguard Worker         // the dominator tree once.  Alternatively, we could just keep it up to
552*9880d681SAndroid Build Coastguard Worker         // date and use a more natural merged loop.
553*9880d681SAndroid Build Coastguard Worker         SetVector<BasicBlock *> SplitBackedges;
554*9880d681SAndroid Build Coastguard Worker         for (BasicBlock *Header : Headers) {
555*9880d681SAndroid Build Coastguard Worker           BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
556*9880d681SAndroid Build Coastguard Worker           PollsNeeded.push_back(NewBB->getTerminator());
557*9880d681SAndroid Build Coastguard Worker           NumBackedgeSafepoints++;
558*9880d681SAndroid Build Coastguard Worker         }
559*9880d681SAndroid Build Coastguard Worker       } else {
560*9880d681SAndroid Build Coastguard Worker         // Split the latch block itself, right before the terminator.
561*9880d681SAndroid Build Coastguard Worker         PollsNeeded.push_back(Term);
562*9880d681SAndroid Build Coastguard Worker         NumBackedgeSafepoints++;
563*9880d681SAndroid Build Coastguard Worker       }
564*9880d681SAndroid Build Coastguard Worker     }
565*9880d681SAndroid Build Coastguard Worker   }
566*9880d681SAndroid Build Coastguard Worker 
567*9880d681SAndroid Build Coastguard Worker   if (enableEntrySafepoints(F)) {
568*9880d681SAndroid Build Coastguard Worker     if (Instruction *Location = findLocationForEntrySafepoint(F, DT)) {
569*9880d681SAndroid Build Coastguard Worker       PollsNeeded.push_back(Location);
570*9880d681SAndroid Build Coastguard Worker       Modified = true;
571*9880d681SAndroid Build Coastguard Worker       NumEntrySafepoints++;
572*9880d681SAndroid Build Coastguard Worker     }
573*9880d681SAndroid Build Coastguard Worker     // TODO: else we should assert that there was, in fact, a policy choice to
574*9880d681SAndroid Build Coastguard Worker     // not insert a entry safepoint poll.
575*9880d681SAndroid Build Coastguard Worker   }
576*9880d681SAndroid Build Coastguard Worker 
577*9880d681SAndroid Build Coastguard Worker   // Now that we've identified all the needed safepoint poll locations, insert
578*9880d681SAndroid Build Coastguard Worker   // safepoint polls themselves.
579*9880d681SAndroid Build Coastguard Worker   for (Instruction *PollLocation : PollsNeeded) {
580*9880d681SAndroid Build Coastguard Worker     std::vector<CallSite> RuntimeCalls;
581*9880d681SAndroid Build Coastguard Worker     InsertSafepointPoll(PollLocation, RuntimeCalls);
582*9880d681SAndroid Build Coastguard Worker     ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
583*9880d681SAndroid Build Coastguard Worker                             RuntimeCalls.end());
584*9880d681SAndroid Build Coastguard Worker   }
585*9880d681SAndroid Build Coastguard Worker 
586*9880d681SAndroid Build Coastguard Worker   return Modified;
587*9880d681SAndroid Build Coastguard Worker }
588*9880d681SAndroid Build Coastguard Worker 
589*9880d681SAndroid Build Coastguard Worker char PlaceBackedgeSafepointsImpl::ID = 0;
590*9880d681SAndroid Build Coastguard Worker char PlaceSafepoints::ID = 0;
591*9880d681SAndroid Build Coastguard Worker 
createPlaceSafepointsPass()592*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createPlaceSafepointsPass() {
593*9880d681SAndroid Build Coastguard Worker   return new PlaceSafepoints();
594*9880d681SAndroid Build Coastguard Worker }
595*9880d681SAndroid Build Coastguard Worker 
596*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
597*9880d681SAndroid Build Coastguard Worker                       "place-backedge-safepoints-impl",
598*9880d681SAndroid Build Coastguard Worker                       "Place Backedge Safepoints", false, false)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)599*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
600*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
601*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
602*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
603*9880d681SAndroid Build Coastguard Worker                     "place-backedge-safepoints-impl",
604*9880d681SAndroid Build Coastguard Worker                     "Place Backedge Safepoints", false, false)
605*9880d681SAndroid Build Coastguard Worker 
606*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
607*9880d681SAndroid Build Coastguard Worker                       false, false)
608*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
609*9880d681SAndroid Build Coastguard Worker                     false, false)
610*9880d681SAndroid Build Coastguard Worker 
611*9880d681SAndroid Build Coastguard Worker static void
612*9880d681SAndroid Build Coastguard Worker InsertSafepointPoll(Instruction *InsertBefore,
613*9880d681SAndroid Build Coastguard Worker                     std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
614*9880d681SAndroid Build Coastguard Worker   BasicBlock *OrigBB = InsertBefore->getParent();
615*9880d681SAndroid Build Coastguard Worker   Module *M = InsertBefore->getModule();
616*9880d681SAndroid Build Coastguard Worker   assert(M && "must be part of a module");
617*9880d681SAndroid Build Coastguard Worker 
618*9880d681SAndroid Build Coastguard Worker   // Inline the safepoint poll implementation - this will get all the branch,
619*9880d681SAndroid Build Coastguard Worker   // control flow, etc..  Most importantly, it will introduce the actual slow
620*9880d681SAndroid Build Coastguard Worker   // path call - where we need to insert a safepoint (parsepoint).
621*9880d681SAndroid Build Coastguard Worker 
622*9880d681SAndroid Build Coastguard Worker   auto *F = M->getFunction(GCSafepointPollName);
623*9880d681SAndroid Build Coastguard Worker   assert(F && "gc.safepoint_poll function is missing");
624*9880d681SAndroid Build Coastguard Worker   assert(F->getValueType() ==
625*9880d681SAndroid Build Coastguard Worker          FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
626*9880d681SAndroid Build Coastguard Worker          "gc.safepoint_poll declared with wrong type");
627*9880d681SAndroid Build Coastguard Worker   assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
628*9880d681SAndroid Build Coastguard Worker   CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
629*9880d681SAndroid Build Coastguard Worker 
630*9880d681SAndroid Build Coastguard Worker   // Record some information about the call site we're replacing
631*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator Before(PollCall), After(PollCall);
632*9880d681SAndroid Build Coastguard Worker   bool IsBegin = false;
633*9880d681SAndroid Build Coastguard Worker   if (Before == OrigBB->begin())
634*9880d681SAndroid Build Coastguard Worker     IsBegin = true;
635*9880d681SAndroid Build Coastguard Worker   else
636*9880d681SAndroid Build Coastguard Worker     Before--;
637*9880d681SAndroid Build Coastguard Worker 
638*9880d681SAndroid Build Coastguard Worker   After++;
639*9880d681SAndroid Build Coastguard Worker   assert(After != OrigBB->end() && "must have successor");
640*9880d681SAndroid Build Coastguard Worker 
641*9880d681SAndroid Build Coastguard Worker   // Do the actual inlining
642*9880d681SAndroid Build Coastguard Worker   InlineFunctionInfo IFI;
643*9880d681SAndroid Build Coastguard Worker   bool InlineStatus = InlineFunction(PollCall, IFI);
644*9880d681SAndroid Build Coastguard Worker   assert(InlineStatus && "inline must succeed");
645*9880d681SAndroid Build Coastguard Worker   (void)InlineStatus; // suppress warning in release-asserts
646*9880d681SAndroid Build Coastguard Worker 
647*9880d681SAndroid Build Coastguard Worker   // Check post-conditions
648*9880d681SAndroid Build Coastguard Worker   assert(IFI.StaticAllocas.empty() && "can't have allocs");
649*9880d681SAndroid Build Coastguard Worker 
650*9880d681SAndroid Build Coastguard Worker   std::vector<CallInst *> Calls; // new calls
651*9880d681SAndroid Build Coastguard Worker   DenseSet<BasicBlock *> BBs;    // new BBs + insertee
652*9880d681SAndroid Build Coastguard Worker 
653*9880d681SAndroid Build Coastguard Worker   // Include only the newly inserted instructions, Note: begin may not be valid
654*9880d681SAndroid Build Coastguard Worker   // if we inserted to the beginning of the basic block
655*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator Start = IsBegin ? OrigBB->begin() : std::next(Before);
656*9880d681SAndroid Build Coastguard Worker 
657*9880d681SAndroid Build Coastguard Worker   // If your poll function includes an unreachable at the end, that's not
658*9880d681SAndroid Build Coastguard Worker   // valid.  Bugpoint likes to create this, so check for it.
659*9880d681SAndroid Build Coastguard Worker   assert(isPotentiallyReachable(&*Start, &*After) &&
660*9880d681SAndroid Build Coastguard Worker          "malformed poll function");
661*9880d681SAndroid Build Coastguard Worker 
662*9880d681SAndroid Build Coastguard Worker   scanInlinedCode(&*Start, &*After, Calls, BBs);
663*9880d681SAndroid Build Coastguard Worker   assert(!Calls.empty() && "slow path not found for safepoint poll");
664*9880d681SAndroid Build Coastguard Worker 
665*9880d681SAndroid Build Coastguard Worker   // Record the fact we need a parsable state at the runtime call contained in
666*9880d681SAndroid Build Coastguard Worker   // the poll function.  This is required so that the runtime knows how to
667*9880d681SAndroid Build Coastguard Worker   // parse the last frame when we actually take  the safepoint (i.e. execute
668*9880d681SAndroid Build Coastguard Worker   // the slow path)
669*9880d681SAndroid Build Coastguard Worker   assert(ParsePointsNeeded.empty());
670*9880d681SAndroid Build Coastguard Worker   for (auto *CI : Calls) {
671*9880d681SAndroid Build Coastguard Worker     // No safepoint needed or wanted
672*9880d681SAndroid Build Coastguard Worker     if (!needsStatepoint(CI))
673*9880d681SAndroid Build Coastguard Worker       continue;
674*9880d681SAndroid Build Coastguard Worker 
675*9880d681SAndroid Build Coastguard Worker     // These are likely runtime calls.  Should we assert that via calling
676*9880d681SAndroid Build Coastguard Worker     // convention or something?
677*9880d681SAndroid Build Coastguard Worker     ParsePointsNeeded.push_back(CallSite(CI));
678*9880d681SAndroid Build Coastguard Worker   }
679*9880d681SAndroid Build Coastguard Worker   assert(ParsePointsNeeded.size() <= Calls.size());
680*9880d681SAndroid Build Coastguard Worker }
681