blob: 2d0cb6fbf2118d1b49270a68de13d31828da69fd [file] [log] [blame]
Philip Reames47cc6732015-02-04 00:37:33 +00001//===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
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//
10// Place garbage collection safepoints at appropriate locations in the IR. This
11// does not make relocation semantics or variable liveness explicit. That's
12// done by RewriteStatepointsForGC.
13//
Philip Reamesd4a912f2015-02-09 22:44:03 +000014// Terminology:
15// - A call is said to be "parseable" if there is a stack map generated for the
16// return PC of the call. A runtime can determine where values listed in the
17// deopt arguments and (after RewriteStatepointsForGC) gc arguments are located
18// on the stack when the code is suspended inside such a call. Every parse
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +000019// point is represented by a call wrapped in an gc.statepoint intrinsic.
Philip Reamesd4a912f2015-02-09 22:44:03 +000020// - A "poll" is an explicit check in the generated code to determine if the
21// runtime needs the generated code to cooperate by calling a helper routine
22// and thus suspending its execution at a known state. The call to the helper
23// routine will be parseable. The (gc & runtime specific) logic of a poll is
24// assumed to be provided in a function of the name "gc.safepoint_poll".
25//
26// We aim to insert polls such that running code can quickly be brought to a
27// well defined state for inspection by the collector. In the current
28// implementation, this is done via the insertion of poll sites at method entry
29// and the backedge of most loops. We try to avoid inserting more polls than
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000030// are necessary to ensure a finite period between poll sites. This is not
Philip Reamesd4a912f2015-02-09 22:44:03 +000031// because the poll itself is expensive in the generated code; it's not. Polls
32// do tend to impact the optimizer itself in negative ways; we'd like to avoid
33// perturbing the optimization of the method as much as we can.
34//
35// We also need to make most call sites parseable. The callee might execute a
36// poll (or otherwise be inspected by the GC). If so, the entire stack
37// (including the suspended frame of the current method) must be parseable.
38//
Philip Reames47cc6732015-02-04 00:37:33 +000039// This pass will insert:
Philip Reamesd4a912f2015-02-09 22:44:03 +000040// - Call parse points ("call safepoints") for any call which may need to
41// reach a safepoint during the execution of the callee function.
42// - Backedge safepoint polls and entry safepoint polls to ensure that
43// executing code reaches a safepoint poll in a finite amount of time.
Philip Reames47cc6732015-02-04 00:37:33 +000044//
Philip Reamesd4a912f2015-02-09 22:44:03 +000045// We do not currently support return statepoints, but adding them would not
46// be hard. They are not required for correctness - entry safepoints are an
47// alternative - but some GCs may prefer them. Patches welcome.
Philip Reames47cc6732015-02-04 00:37:33 +000048//
49//===----------------------------------------------------------------------===//
50
51#include "llvm/Pass.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000052
Philip Reames5708cca2015-05-12 20:43:48 +000053#include "llvm/ADT/SetVector.h"
Philip Reames47cc6732015-02-04 00:37:33 +000054#include "llvm/ADT/Statistic.h"
Philip Reames47cc6732015-02-04 00:37:33 +000055#include "llvm/Analysis/CFG.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000056#include "llvm/Analysis/ScalarEvolution.h"
Daniel Neilson2574d7c2017-07-27 16:49:39 +000057#include "llvm/Analysis/TargetLibraryInfo.h"
Philip Reames47cc6732015-02-04 00:37:33 +000058#include "llvm/IR/CallSite.h"
59#include "llvm/IR/Dominators.h"
Philip Reames47cc6732015-02-04 00:37:33 +000060#include "llvm/IR/IntrinsicInst.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000061#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000062#include "llvm/IR/Statepoint.h"
Philip Reames47cc6732015-02-04 00:37:33 +000063#include "llvm/Support/CommandLine.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000064#include "llvm/Support/Debug.h"
Philip Reames47cc6732015-02-04 00:37:33 +000065#include "llvm/Transforms/Scalar.h"
66#include "llvm/Transforms/Utils/BasicBlockUtils.h"
67#include "llvm/Transforms/Utils/Cloning.h"
68#include "llvm/Transforms/Utils/Local.h"
69
70#define DEBUG_TYPE "safepoint-placement"
Sanjoy Dascd23fec2016-01-28 23:03:19 +000071
Philip Reames47cc6732015-02-04 00:37:33 +000072STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
Philip Reames47cc6732015-02-04 00:37:33 +000073STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
74
Sanjoy Dascd23fec2016-01-28 23:03:19 +000075STATISTIC(CallInLoop,
76 "Number of loops without safepoints due to calls in loop");
77STATISTIC(FiniteExecution,
78 "Number of loops without safepoints finite execution");
Philip Reames47cc6732015-02-04 00:37:33 +000079
80using namespace llvm;
81
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000082// Ignore opportunities to avoid placing safepoints on backedges, useful for
Philip Reames47cc6732015-02-04 00:37:33 +000083// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000084static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
85 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000086
Sanjoy Dasf75e15e2015-09-15 01:42:48 +000087/// How narrow does the trip count of a loop have to be to have to be considered
88/// "counted"? Counted loops do not get safepoints at backedges.
89static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
90 cl::Hidden, cl::init(32));
Philip Reames47cc6732015-02-04 00:37:33 +000091
92// If true, split the backedge of a loop when placing the safepoint, otherwise
93// split the latch block itself. Both are useful to support for
94// experimentation, but in practice, it looks like splitting the backedge
95// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +000096static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
97 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000098
Philip Reames47cc6732015-02-04 00:37:33 +000099namespace {
100
Philip Reames9f129042015-05-12 21:09:36 +0000101/// An analysis pass whose purpose is to identify each of the backedges in
102/// the function which require a safepoint poll to be inserted.
103struct PlaceBackedgeSafepointsImpl : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000104 static char ID;
105
106 /// The output of the pass - gives a list of each backedge (described by
107 /// pointing at the branch) which need a poll inserted.
108 std::vector<TerminatorInst *> PollLocations;
109
110 /// True unless we're running spp-no-calls in which case we need to disable
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000111 /// the call-dependent placement opts.
Philip Reames47cc6732015-02-04 00:37:33 +0000112 bool CallSafepointsEnabled;
Philip Reames9f129042015-05-12 21:09:36 +0000113
114 ScalarEvolution *SE = nullptr;
115 DominatorTree *DT = nullptr;
116 LoopInfo *LI = nullptr;
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000117 TargetLibraryInfo *TLI = nullptr;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000118
Philip Reames47cc6732015-02-04 00:37:33 +0000119 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
Philip Reames9f129042015-05-12 21:09:36 +0000120 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000121 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000122 }
123
Philip Reames9f129042015-05-12 21:09:36 +0000124 bool runOnLoop(Loop *);
125 void runOnLoopAndSubLoops(Loop *L) {
126 // Visit all the subloops
Benjamin Kramer135f7352016-06-26 12:28:59 +0000127 for (Loop *I : *L)
128 runOnLoopAndSubLoops(I);
Philip Reames9f129042015-05-12 21:09:36 +0000129 runOnLoop(L);
130 }
Justin Bogner383749a2015-05-12 21:49:47 +0000131
132 bool runOnFunction(Function &F) override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000133 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Philip Reames9f129042015-05-12 21:09:36 +0000134 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
135 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000136 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000137 for (Loop *I : *LI) {
138 runOnLoopAndSubLoops(I);
Philip Reames9f129042015-05-12 21:09:36 +0000139 }
140 return false;
141 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000142
Philip Reames47cc6732015-02-04 00:37:33 +0000143 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000144 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000145 AU.addRequired<ScalarEvolutionWrapperPass>();
Philip Reames9f129042015-05-12 21:09:36 +0000146 AU.addRequired<LoopInfoWrapperPass>();
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000147 AU.addRequired<TargetLibraryInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000148 // We no longer modify the IR at all in this pass. Thus all
149 // analysis are preserved.
150 AU.setPreservesAll();
151 }
152};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000153}
Philip Reames47cc6732015-02-04 00:37:33 +0000154
Philip Reames1f3e5c12015-02-20 23:32:03 +0000155static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
156static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
157static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000158
159namespace {
Philip Reames7b981792015-05-12 21:21:18 +0000160struct PlaceSafepoints : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000161 static char ID; // Pass identification, replacement for typeid
162
Philip Reames7b981792015-05-12 21:21:18 +0000163 PlaceSafepoints() : FunctionPass(ID) {
Philip Reames47cc6732015-02-04 00:37:33 +0000164 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000165 }
Philip Reames7b981792015-05-12 21:21:18 +0000166 bool runOnFunction(Function &F) override;
Philip Reames47cc6732015-02-04 00:37:33 +0000167
168 void getAnalysisUsage(AnalysisUsage &AU) const override {
169 // We modify the graph wholesale (inlining, block insertion, etc). We
170 // preserve nothing at the moment. We could potentially preserve dom tree
171 // if that was worth doing
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000172 AU.addRequired<TargetLibraryInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000173 }
174};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000175}
Philip Reames47cc6732015-02-04 00:37:33 +0000176
177// Insert a safepoint poll immediately before the given instruction. Does
178// not handle the parsability of state at the runtime call, that's the
179// callers job.
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000180static void
Philip Reames388402452015-05-26 21:03:23 +0000181InsertSafepointPoll(Instruction *InsertBefore,
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000182 std::vector<CallSite> &ParsePointsNeeded /*rval*/,
183 const TargetLibraryInfo &TLI);
Philip Reames47cc6732015-02-04 00:37:33 +0000184
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000185static bool needsStatepoint(const CallSite &CS, const TargetLibraryInfo &TLI) {
186 if (callsGCLeafFunction(CS, TLI))
Philip Reames47cc6732015-02-04 00:37:33 +0000187 return false;
188 if (CS.isCall()) {
189 CallInst *call = cast<CallInst>(CS.getInstruction());
190 if (call->isInlineAsm())
191 return false;
192 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000193
194 return !(isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS));
Philip Reames47cc6732015-02-04 00:37:33 +0000195}
196
Philip Reames47cc6732015-02-04 00:37:33 +0000197/// Returns true if this loop is known to contain a call safepoint which
198/// must unconditionally execute on any iteration of the loop which returns
199/// to the loop header via an edge from Pred. Returns a conservative correct
200/// answer; i.e. false is always valid.
201static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
202 BasicBlock *Pred,
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000203 DominatorTree &DT,
204 const TargetLibraryInfo &TLI) {
Philip Reames47cc6732015-02-04 00:37:33 +0000205 // In general, we're looking for any cut of the graph which ensures
206 // there's a call safepoint along every edge between Header and Pred.
207 // For the moment, we look only for the 'cuts' that consist of a single call
208 // instruction in a block which is dominated by the Header and dominates the
209 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000210 // of such dominating blocks gets substantially more occurrences than just
Philip Reames47cc6732015-02-04 00:37:33 +0000211 // checking the Pred and Header blocks themselves. This may be due to the
212 // density of loop exit conditions caused by range and null checks.
213 // TODO: structure this as an analysis pass, cache the result for subloops,
214 // avoid dom tree recalculations
215 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
216
217 BasicBlock *Current = Pred;
218 while (true) {
219 for (Instruction &I : *Current) {
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000220 if (auto CS = CallSite(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000221 // Note: Technically, needing a safepoint isn't quite the right
222 // condition here. We should instead be checking if the target method
223 // has an
224 // unconditional poll. In practice, this is only a theoretical concern
225 // since we don't have any methods with conditional-only safepoint
226 // polls.
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000227 if (needsStatepoint(CS, TLI))
Philip Reames47cc6732015-02-04 00:37:33 +0000228 return true;
229 }
230
231 if (Current == Header)
232 break;
233 Current = DT.getNode(Current)->getIDom()->getBlock();
234 }
235
236 return false;
237}
238
239/// Returns true if this loop is known to terminate in a finite number of
240/// iterations. Note that this function may return false for a loop which
241/// does actual terminate in a finite constant number of iterations due to
242/// conservatism in the analysis.
243static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000244 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000245 // A conservative bound on the loop as a whole.
246 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000247 if (MaxTrips != SE->getCouldNotCompute() &&
248 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
249 CountedLoopTripWidth))
250 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000251
252 // If this is a conditional branch to the header with the alternate path
253 // being outside the loop, we can ask questions about the execution frequency
254 // of the exit block.
255 if (L->isLoopExiting(Pred)) {
256 // This returns an exact expression only. TODO: We really only need an
257 // upper bound here, but SE doesn't expose that.
258 const SCEV *MaxExec = SE->getExitCount(L, Pred);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000259 if (MaxExec != SE->getCouldNotCompute() &&
260 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
261 CountedLoopTripWidth))
Philip Reames47cc6732015-02-04 00:37:33 +0000262 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000263 }
264
265 return /* not finite */ false;
266}
267
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000268static void scanOneBB(Instruction *Start, Instruction *End,
269 std::vector<CallInst *> &Calls,
270 DenseSet<BasicBlock *> &Seen,
271 std::vector<BasicBlock *> &Worklist) {
272 for (BasicBlock::iterator BBI(Start), BBE0 = Start->getParent()->end(),
273 BBE1 = BasicBlock::iterator(End);
274 BBI != BBE0 && BBI != BBE1; BBI++) {
275 if (CallInst *CI = dyn_cast<CallInst>(&*BBI))
276 Calls.push_back(CI);
277
Philip Reames47cc6732015-02-04 00:37:33 +0000278 // FIXME: This code does not handle invokes
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000279 assert(!isa<InvokeInst>(&*BBI) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000280 "support for invokes in poll code needed");
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000281
Philip Reames47cc6732015-02-04 00:37:33 +0000282 // Only add the successor blocks if we reach the terminator instruction
283 // without encountering end first
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000284 if (BBI->isTerminator()) {
285 BasicBlock *BB = BBI->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000286 for (BasicBlock *Succ : successors(BB)) {
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000287 if (Seen.insert(Succ).second) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000288 Worklist.push_back(Succ);
Philip Reames47cc6732015-02-04 00:37:33 +0000289 }
290 }
291 }
292 }
293}
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000294
295static void scanInlinedCode(Instruction *Start, Instruction *End,
296 std::vector<CallInst *> &Calls,
297 DenseSet<BasicBlock *> &Seen) {
298 Calls.clear();
299 std::vector<BasicBlock *> Worklist;
300 Seen.insert(Start->getParent());
301 scanOneBB(Start, End, Calls, Seen, Worklist);
302 while (!Worklist.empty()) {
303 BasicBlock *BB = Worklist.back();
304 Worklist.pop_back();
305 scanOneBB(&*BB->begin(), End, Calls, Seen, Worklist);
Philip Reames47cc6732015-02-04 00:37:33 +0000306 }
307}
308
Philip Reames9f129042015-05-12 21:09:36 +0000309bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
Philip Reames5708cca2015-05-12 20:43:48 +0000310 // Loop through all loop latches (branches controlling backedges). We need
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000311 // to place a safepoint on every backedge (potentially).
Philip Reames5708cca2015-05-12 20:43:48 +0000312 // Note: In common usage, there will be only one edge due to LoopSimplify
313 // having run sometime earlier in the pipeline, but this code must be correct
314 // w.r.t. loops with multiple backedges.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000315 BasicBlock *Header = L->getHeader();
Philip Reames5708cca2015-05-12 20:43:48 +0000316 SmallVector<BasicBlock*, 16> LoopLatches;
317 L->getLoopLatches(LoopLatches);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000318 for (BasicBlock *Pred : LoopLatches) {
319 assert(L->contains(Pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000320
321 // Make a policy decision about whether this loop needs a safepoint or
322 // not. Note that this is about unburdening the optimizer in loops, not
323 // avoiding the runtime cost of the actual safepoint.
324 if (!AllBackedges) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000325 if (mustBeFiniteCountedLoop(L, SE, Pred)) {
Sanjoy Dasbb04f6e2016-01-28 23:49:27 +0000326 DEBUG(dbgs() << "skipping safepoint placement in finite loop\n");
Philip Reames47cc6732015-02-04 00:37:33 +0000327 FiniteExecution++;
328 continue;
329 }
330 if (CallSafepointsEnabled &&
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000331 containsUnconditionalCallSafepoint(L, Header, Pred, *DT, *TLI)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000332 // Note: This is only semantically legal since we won't do any further
333 // IPO or inlining before the actual call insertion.. If we hadn't, we
334 // might latter loose this call safepoint.
Sanjoy Dasbb04f6e2016-01-28 23:49:27 +0000335 DEBUG(dbgs() << "skipping safepoint placement due to unconditional call\n");
Philip Reames47cc6732015-02-04 00:37:33 +0000336 CallInLoop++;
337 continue;
338 }
339 }
340
341 // TODO: We can create an inner loop which runs a finite number of
342 // iterations with an outer loop which contains a safepoint. This would
343 // not help runtime performance that much, but it might help our ability to
344 // optimize the inner loop.
345
Philip Reames47cc6732015-02-04 00:37:33 +0000346 // Safepoint insertion would involve creating a new basic block (as the
347 // target of the current backedge) which does the safepoint (of all live
348 // variables) and branches to the true header
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000349 TerminatorInst *Term = Pred->getTerminator();
Philip Reames47cc6732015-02-04 00:37:33 +0000350
Sanjoy Dasbb04f6e2016-01-28 23:49:27 +0000351 DEBUG(dbgs() << "[LSP] terminator instruction: " << *Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000352
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000353 PollLocations.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000354 }
355
Philip Reames5708cca2015-05-12 20:43:48 +0000356 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000357}
358
Philip Reamesd97cdf22015-05-19 23:40:11 +0000359/// Returns true if an entry safepoint is not required before this callsite in
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000360/// the caller function.
Philip Reamesd97cdf22015-05-19 23:40:11 +0000361static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
362 Instruction *Inst = CS.getInstruction();
363 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
364 switch (II->getIntrinsicID()) {
365 case Intrinsic::experimental_gc_statepoint:
366 case Intrinsic::experimental_patchpoint_void:
367 case Intrinsic::experimental_patchpoint_i64:
368 // The can wrap an actual call which may grow the stack by an unbounded
369 // amount or run forever.
370 return false;
371 default:
372 // Most LLVM intrinsics are things which do not expand to actual calls, or
373 // at least if they do, are leaf functions that cause only finite stack
374 // growth. In particular, the optimizer likes to form things like memsets
375 // out of stores in the original IR. Another important example is
Reid Kleckner60381792015-07-07 22:25:32 +0000376 // llvm.localescape which must occur in the entry block. Inserting a
377 // safepoint before it is not legal since it could push the localescape
Philip Reamesd97cdf22015-05-19 23:40:11 +0000378 // out of the entry block.
379 return true;
380 }
381 }
382 return false;
383}
384
Philip Reames47cc6732015-02-04 00:37:33 +0000385static Instruction *findLocationForEntrySafepoint(Function &F,
386 DominatorTree &DT) {
387
388 // Conceptually, this poll needs to be on method entry, but in
389 // practice, we place it as late in the entry block as possible. We
390 // can place it as late as we want as long as it dominates all calls
391 // that can grow the stack. This, combined with backedge polls,
392 // give us all the progress guarantees we need.
393
Philip Reames47cc6732015-02-04 00:37:33 +0000394 // hasNextInstruction and nextInstruction are used to iterate
395 // through a "straight line" execution sequence.
396
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000397 auto HasNextInstruction = [](Instruction *I) {
398 if (!I->isTerminator())
Philip Reames47cc6732015-02-04 00:37:33 +0000399 return true;
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000400
Philip Reames47cc6732015-02-04 00:37:33 +0000401 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
402 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
403 };
404
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000405 auto NextInstruction = [&](Instruction *I) {
406 assert(HasNextInstruction(I) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000407 "first check if there is a next instruction!");
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000408
409 if (I->isTerminator())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000410 return &I->getParent()->getUniqueSuccessor()->front();
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000411 return &*++I->getIterator();
Philip Reames47cc6732015-02-04 00:37:33 +0000412 };
413
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000414 Instruction *Cursor = nullptr;
415 for (Cursor = &F.getEntryBlock().front(); HasNextInstruction(Cursor);
416 Cursor = NextInstruction(Cursor)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000417
Philip Reamesd97cdf22015-05-19 23:40:11 +0000418 // We need to ensure a safepoint poll occurs before any 'real' call. The
419 // easiest way to ensure finite execution between safepoints in the face of
420 // recursive and mutually recursive functions is to enforce that each take
421 // a safepoint. Additionally, we need to ensure a poll before any call
422 // which can grow the stack by an unbounded amount. This isn't required
423 // for GC semantics per se, but is a common requirement for languages
424 // which detect stack overflow via guard pages and then throw exceptions.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000425 if (auto CS = CallSite(Cursor)) {
Philip Reamesd97cdf22015-05-19 23:40:11 +0000426 if (doesNotRequireEntrySafepointBefore(CS))
427 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000428 break;
429 }
430 }
431
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000432 assert((HasNextInstruction(Cursor) || Cursor->isTerminator()) &&
Philip Reames5a9685d2015-02-04 00:39:57 +0000433 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000434
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000435 return Cursor;
Philip Reames47cc6732015-02-04 00:37:33 +0000436}
437
Benjamin Kramer82f86522015-06-07 16:36:28 +0000438static const char *const GCSafepointPollName = "gc.safepoint_poll";
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000439
440static bool isGCSafepointPoll(Function &F) {
441 return F.getName().equals(GCSafepointPollName);
442}
443
Philip Reames0b1b3872015-02-21 00:09:09 +0000444/// Returns true if this function should be rewritten to include safepoint
445/// polls and parseable call sites. The main point of this function is to be
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000446/// an extension point for custom logic.
Philip Reames0b1b3872015-02-21 00:09:09 +0000447static bool shouldRewriteFunction(Function &F) {
448 // TODO: This should check the GCStrategy
449 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +0000450 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000451 const StringRef StatepointExampleName("statepoint-example");
452 const StringRef CoreCLRName("coreclr");
453 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +0000454 (CoreCLRName == FunctionGCName);
Philip Reames0b1b3872015-02-21 00:09:09 +0000455 } else
456 return false;
457}
458
459// TODO: These should become properties of the GCStrategy, possibly with
460// command line overrides.
461static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
462static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
463static bool enableCallSafepoints(Function &F) { return !NoCall; }
464
Philip Reames47cc6732015-02-04 00:37:33 +0000465bool PlaceSafepoints::runOnFunction(Function &F) {
466 if (F.isDeclaration() || F.empty()) {
467 // This is a declaration, nothing to do. Must exit early to avoid crash in
468 // dom tree calculation
469 return false;
470 }
471
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000472 if (isGCSafepointPoll(F)) {
473 // Given we're inlining this inside of safepoint poll insertion, this
474 // doesn't make any sense. Note that we do make any contained calls
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000475 // parseable after we inline a poll.
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000476 return false;
477 }
478
Philip Reames0b1b3872015-02-21 00:09:09 +0000479 if (!shouldRewriteFunction(F))
480 return false;
481
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000482 const TargetLibraryInfo &TLI =
483 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
484
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000485 bool Modified = false;
Philip Reames47cc6732015-02-04 00:37:33 +0000486
487 // In various bits below, we rely on the fact that uses are reachable from
488 // defs. When there are basic blocks unreachable from the entry, dominance
489 // and reachablity queries return non-sensical results. Thus, we preprocess
490 // the function to ensure these properties hold.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000491 Modified |= removeUnreachableBlocks(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000492
493 // STEP 1 - Insert the safepoint polling locations. We do not need to
494 // actually insert parse points yet. That will be done for all polls and
495 // calls in a single pass.
496
Philip Reames47cc6732015-02-04 00:37:33 +0000497 DominatorTree DT;
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000498 DT.recalculate(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000499
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000500 SmallVector<Instruction *, 16> PollsNeeded;
Philip Reames47cc6732015-02-04 00:37:33 +0000501 std::vector<CallSite> ParsePointNeeded;
502
Philip Reames0b1b3872015-02-21 00:09:09 +0000503 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000504 // Construct a pass manager to run the LoopPass backedge logic. We
505 // need the pass manager to handle scheduling all the loop passes
506 // appropriately. Doing this by hand is painful and just not worth messing
507 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000508 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000509 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000510 auto *PBS = new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000511 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000512 FPM.run(F);
513
514 // We preserve dominance information when inserting the poll, otherwise
515 // we'd have to recalculate this on every insert
516 DT.recalculate(F);
517
Philip Reames5708cca2015-05-12 20:43:48 +0000518 auto &PollLocations = PBS->PollLocations;
519
520 auto OrderByBBName = [](Instruction *a, Instruction *b) {
521 return a->getParent()->getName() < b->getParent()->getName();
522 };
523 // We need the order of list to be stable so that naming ends up stable
524 // when we split edges. This makes test cases much easier to write.
525 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
526
527 // We can sometimes end up with duplicate poll locations. This happens if
528 // a single loop is visited more than once. The fact this happens seems
529 // wrong, but it does happen for the split-backedge.ll test case.
530 PollLocations.erase(std::unique(PollLocations.begin(),
531 PollLocations.end()),
532 PollLocations.end());
533
Philip Reames47cc6732015-02-04 00:37:33 +0000534 // Insert a poll at each point the analysis pass identified
Philip Reames89fe5702015-05-12 23:39:23 +0000535 // The poll location must be the terminator of a loop latch block.
536 for (TerminatorInst *Term : PollLocations) {
Philip Reames47cc6732015-02-04 00:37:33 +0000537 // We are inserting a poll, the function is modified
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000538 Modified = true;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000539
Philip Reames47cc6732015-02-04 00:37:33 +0000540 if (SplitBackedge) {
541 // Split the backedge of the loop and insert the poll within that new
542 // basic block. This creates a loop with two latches per original
543 // latch (which is non-ideal), but this appears to be easier to
544 // optimize in practice than inserting the poll immediately before the
545 // latch test.
546
547 // Since this is a latch, at least one of the successors must dominate
548 // it. Its possible that we have a) duplicate edges to the same header
549 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000550 // each.
551 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000552 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
553 BasicBlock *Succ = Term->getSuccessor(i);
554 if (DT.dominates(Succ, Term->getParent())) {
555 Headers.insert(Succ);
556 }
557 }
558 assert(!Headers.empty() && "poll location is not a loop latch?");
559
560 // The split loop structure here is so that we only need to recalculate
561 // the dominator tree once. Alternatively, we could just keep it up to
562 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000563 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000564 for (BasicBlock *Header : Headers) {
Philip Reames89fe5702015-05-12 23:39:23 +0000565 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000566 PollsNeeded.push_back(NewBB->getTerminator());
Philip Reames47cc6732015-02-04 00:37:33 +0000567 NumBackedgeSafepoints++;
568 }
Philip Reames47cc6732015-02-04 00:37:33 +0000569 } else {
570 // Split the latch block itself, right before the terminator.
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000571 PollsNeeded.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000572 NumBackedgeSafepoints++;
573 }
Philip Reames47cc6732015-02-04 00:37:33 +0000574 }
575 }
576
Philip Reames0b1b3872015-02-21 00:09:09 +0000577 if (enableEntrySafepoints(F)) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000578 if (Instruction *Location = findLocationForEntrySafepoint(F, DT)) {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000579 PollsNeeded.push_back(Location);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000580 Modified = true;
Philip Reames47cc6732015-02-04 00:37:33 +0000581 NumEntrySafepoints++;
Philip Reames47cc6732015-02-04 00:37:33 +0000582 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000583 // TODO: else we should assert that there was, in fact, a policy choice to
584 // not insert a entry safepoint poll.
Philip Reames47cc6732015-02-04 00:37:33 +0000585 }
586
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000587 // Now that we've identified all the needed safepoint poll locations, insert
588 // safepoint polls themselves.
589 for (Instruction *PollLocation : PollsNeeded) {
590 std::vector<CallSite> RuntimeCalls;
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000591 InsertSafepointPoll(PollLocation, RuntimeCalls, TLI);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000592 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
593 RuntimeCalls.end());
594 }
Sanjoy Das95639742016-01-22 21:02:55 +0000595
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000596 return Modified;
Philip Reames47cc6732015-02-04 00:37:33 +0000597}
598
599char PlaceBackedgeSafepointsImpl::ID = 0;
600char PlaceSafepoints::ID = 0;
601
Philip Reames7b981792015-05-12 21:21:18 +0000602FunctionPass *llvm::createPlaceSafepointsPass() {
603 return new PlaceSafepoints();
604}
Philip Reames47cc6732015-02-04 00:37:33 +0000605
606INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
607 "place-backedge-safepoints-impl",
608 "Place Backedge Safepoints", false, false)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000609INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Philip Reames57bdac92015-05-12 20:56:33 +0000610INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames9f129042015-05-12 21:09:36 +0000611INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000612INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
613 "place-backedge-safepoints-impl",
614 "Place Backedge Safepoints", false, false)
615
616INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
617 false, false)
618INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
619 false, false)
620
Philip Reames5a9685d2015-02-04 00:39:57 +0000621static void
Philip Reames388402452015-05-26 21:03:23 +0000622InsertSafepointPoll(Instruction *InsertBefore,
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000623 std::vector<CallSite> &ParsePointsNeeded /*rval*/,
624 const TargetLibraryInfo &TLI) {
Philip Reames388402452015-05-26 21:03:23 +0000625 BasicBlock *OrigBB = InsertBefore->getParent();
626 Module *M = InsertBefore->getModule();
627 assert(M && "must be part of a module");
Philip Reames47cc6732015-02-04 00:37:33 +0000628
629 // Inline the safepoint poll implementation - this will get all the branch,
630 // control flow, etc.. Most importantly, it will introduce the actual slow
631 // path call - where we need to insert a safepoint (parsepoint).
Philip Reames388402452015-05-26 21:03:23 +0000632
633 auto *F = M->getFunction(GCSafepointPollName);
Manuel Jacobe3773d62015-12-29 21:57:55 +0000634 assert(F && "gc.safepoint_poll function is missing");
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000635 assert(F->getValueType() ==
Philip Reames388402452015-05-26 21:03:23 +0000636 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
637 "gc.safepoint_poll declared with wrong type");
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000638 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames388402452015-05-26 21:03:23 +0000639 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
Philip Reames47cc6732015-02-04 00:37:33 +0000640
641 // Record some information about the call site we're replacing
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000642 BasicBlock::iterator Before(PollCall), After(PollCall);
643 bool IsBegin = false;
644 if (Before == OrigBB->begin())
645 IsBegin = true;
646 else
647 Before--;
Philip Reames47cc6732015-02-04 00:37:33 +0000648
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000649 After++;
650 assert(After != OrigBB->end() && "must have successor");
651
652 // Do the actual inlining
Philip Reames47cc6732015-02-04 00:37:33 +0000653 InlineFunctionInfo IFI;
Philip Reames388402452015-05-26 21:03:23 +0000654 bool InlineStatus = InlineFunction(PollCall, IFI);
655 assert(InlineStatus && "inline must succeed");
656 (void)InlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000657
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000658 // Check post-conditions
Philip Reames47cc6732015-02-04 00:37:33 +0000659 assert(IFI.StaticAllocas.empty() && "can't have allocs");
660
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000661 std::vector<CallInst *> Calls; // new calls
662 DenseSet<BasicBlock *> BBs; // new BBs + insertee
663
Philip Reames47cc6732015-02-04 00:37:33 +0000664 // Include only the newly inserted instructions, Note: begin may not be valid
665 // if we inserted to the beginning of the basic block
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000666 BasicBlock::iterator Start = IsBegin ? OrigBB->begin() : std::next(Before);
Philip Reames47cc6732015-02-04 00:37:33 +0000667
668 // If your poll function includes an unreachable at the end, that's not
669 // valid. Bugpoint likes to create this, so check for it.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000670 assert(isPotentiallyReachable(&*Start, &*After) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000671 "malformed poll function");
672
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000673 scanInlinedCode(&*Start, &*After, Calls, BBs);
674 assert(!Calls.empty() && "slow path not found for safepoint poll");
Philip Reames47cc6732015-02-04 00:37:33 +0000675
676 // Record the fact we need a parsable state at the runtime call contained in
677 // the poll function. This is required so that the runtime knows how to
678 // parse the last frame when we actually take the safepoint (i.e. execute
679 // the slow path)
680 assert(ParsePointsNeeded.empty());
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000681 for (auto *CI : Calls) {
Philip Reames47cc6732015-02-04 00:37:33 +0000682 // No safepoint needed or wanted
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000683 if (!needsStatepoint(CI, TLI))
Philip Reames47cc6732015-02-04 00:37:33 +0000684 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000685
686 // These are likely runtime calls. Should we assert that via calling
687 // convention or something?
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000688 ParsePointsNeeded.push_back(CallSite(CI));
Philip Reames47cc6732015-02-04 00:37:33 +0000689 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000690 assert(ParsePointsNeeded.size() <= Calls.size());
Philip Reames47cc6732015-02-04 00:37:33 +0000691}