blob: 029178388b78d454ce37274e91f0ea56a22f61fe [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"
Philip Reames47cc6732015-02-04 00:37:33 +000057#include "llvm/IR/CallSite.h"
58#include "llvm/IR/Dominators.h"
Philip Reames47cc6732015-02-04 00:37:33 +000059#include "llvm/IR/IntrinsicInst.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000060#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000061#include "llvm/IR/Statepoint.h"
Philip Reames47cc6732015-02-04 00:37:33 +000062#include "llvm/Support/CommandLine.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000063#include "llvm/Support/Debug.h"
Philip Reames47cc6732015-02-04 00:37:33 +000064#include "llvm/Transforms/Scalar.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Cloning.h"
67#include "llvm/Transforms/Utils/Local.h"
68
69#define DEBUG_TYPE "safepoint-placement"
Sanjoy Dascd23fec2016-01-28 23:03:19 +000070
Philip Reames47cc6732015-02-04 00:37:33 +000071STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
Philip Reames47cc6732015-02-04 00:37:33 +000072STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
73
Sanjoy Dascd23fec2016-01-28 23:03:19 +000074STATISTIC(CallInLoop,
75 "Number of loops without safepoints due to calls in loop");
76STATISTIC(FiniteExecution,
77 "Number of loops without safepoints finite execution");
Philip Reames47cc6732015-02-04 00:37:33 +000078
79using namespace llvm;
80
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000081// Ignore opportunities to avoid placing safepoints on backedges, useful for
Philip Reames47cc6732015-02-04 00:37:33 +000082// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000083static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
84 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000085
Sanjoy Dasf75e15e2015-09-15 01:42:48 +000086/// How narrow does the trip count of a loop have to be to have to be considered
87/// "counted"? Counted loops do not get safepoints at backedges.
88static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
89 cl::Hidden, cl::init(32));
Philip Reames47cc6732015-02-04 00:37:33 +000090
91// If true, split the backedge of a loop when placing the safepoint, otherwise
92// split the latch block itself. Both are useful to support for
93// experimentation, but in practice, it looks like splitting the backedge
94// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +000095static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
96 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000097
Philip Reames47cc6732015-02-04 00:37:33 +000098namespace {
99
Philip Reames9f129042015-05-12 21:09:36 +0000100/// An analysis pass whose purpose is to identify each of the backedges in
101/// the function which require a safepoint poll to be inserted.
102struct PlaceBackedgeSafepointsImpl : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000103 static char ID;
104
105 /// The output of the pass - gives a list of each backedge (described by
106 /// pointing at the branch) which need a poll inserted.
107 std::vector<TerminatorInst *> PollLocations;
108
109 /// True unless we're running spp-no-calls in which case we need to disable
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000110 /// the call-dependent placement opts.
Philip Reames47cc6732015-02-04 00:37:33 +0000111 bool CallSafepointsEnabled;
Philip Reames9f129042015-05-12 21:09:36 +0000112
113 ScalarEvolution *SE = nullptr;
114 DominatorTree *DT = nullptr;
115 LoopInfo *LI = nullptr;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000116
Philip Reames47cc6732015-02-04 00:37:33 +0000117 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
Philip Reames9f129042015-05-12 21:09:36 +0000118 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000119 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000120 }
121
Philip Reames9f129042015-05-12 21:09:36 +0000122 bool runOnLoop(Loop *);
123 void runOnLoopAndSubLoops(Loop *L) {
124 // Visit all the subloops
125 for (auto I = L->begin(), E = L->end(); I != E; I++)
126 runOnLoopAndSubLoops(*I);
127 runOnLoop(L);
128 }
Justin Bogner383749a2015-05-12 21:49:47 +0000129
130 bool runOnFunction(Function &F) override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000131 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Philip Reames9f129042015-05-12 21:09:36 +0000132 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
133 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
134 for (auto I = LI->begin(), E = LI->end(); I != E; I++) {
135 runOnLoopAndSubLoops(*I);
136 }
137 return false;
138 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000139
Philip Reames47cc6732015-02-04 00:37:33 +0000140 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000141 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000142 AU.addRequired<ScalarEvolutionWrapperPass>();
Philip Reames9f129042015-05-12 21:09:36 +0000143 AU.addRequired<LoopInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000144 // We no longer modify the IR at all in this pass. Thus all
145 // analysis are preserved.
146 AU.setPreservesAll();
147 }
148};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000149}
Philip Reames47cc6732015-02-04 00:37:33 +0000150
Philip Reames1f3e5c12015-02-20 23:32:03 +0000151static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
152static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
153static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000154
155namespace {
Philip Reames7b981792015-05-12 21:21:18 +0000156struct PlaceSafepoints : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000157 static char ID; // Pass identification, replacement for typeid
158
Philip Reames7b981792015-05-12 21:21:18 +0000159 PlaceSafepoints() : FunctionPass(ID) {
Philip Reames47cc6732015-02-04 00:37:33 +0000160 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000161 }
Philip Reames7b981792015-05-12 21:21:18 +0000162 bool runOnFunction(Function &F) override;
Philip Reames47cc6732015-02-04 00:37:33 +0000163
164 void getAnalysisUsage(AnalysisUsage &AU) const override {
165 // We modify the graph wholesale (inlining, block insertion, etc). We
166 // preserve nothing at the moment. We could potentially preserve dom tree
167 // if that was worth doing
168 }
169};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000170}
Philip Reames47cc6732015-02-04 00:37:33 +0000171
172// Insert a safepoint poll immediately before the given instruction. Does
173// not handle the parsability of state at the runtime call, that's the
174// callers job.
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000175static void
Philip Reames388402452015-05-26 21:03:23 +0000176InsertSafepointPoll(Instruction *InsertBefore,
Philip Reames5a9685d2015-02-04 00:39:57 +0000177 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
Philip Reames47cc6732015-02-04 00:37:33 +0000178
Philip Reames47cc6732015-02-04 00:37:33 +0000179static bool needsStatepoint(const CallSite &CS) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +0000180 if (callsGCLeafFunction(CS))
Philip Reames47cc6732015-02-04 00:37:33 +0000181 return false;
182 if (CS.isCall()) {
183 CallInst *call = cast<CallInst>(CS.getInstruction());
184 if (call->isInlineAsm())
185 return false;
186 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000187
188 return !(isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS));
Philip Reames47cc6732015-02-04 00:37:33 +0000189}
190
Philip Reames47cc6732015-02-04 00:37:33 +0000191/// Returns true if this loop is known to contain a call safepoint which
192/// must unconditionally execute on any iteration of the loop which returns
193/// to the loop header via an edge from Pred. Returns a conservative correct
194/// answer; i.e. false is always valid.
195static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
196 BasicBlock *Pred,
197 DominatorTree &DT) {
198 // In general, we're looking for any cut of the graph which ensures
199 // there's a call safepoint along every edge between Header and Pred.
200 // For the moment, we look only for the 'cuts' that consist of a single call
201 // instruction in a block which is dominated by the Header and dominates the
202 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000203 // of such dominating blocks gets substantially more occurrences than just
Philip Reames47cc6732015-02-04 00:37:33 +0000204 // checking the Pred and Header blocks themselves. This may be due to the
205 // density of loop exit conditions caused by range and null checks.
206 // TODO: structure this as an analysis pass, cache the result for subloops,
207 // avoid dom tree recalculations
208 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
209
210 BasicBlock *Current = Pred;
211 while (true) {
212 for (Instruction &I : *Current) {
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000213 if (auto CS = CallSite(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000214 // Note: Technically, needing a safepoint isn't quite the right
215 // condition here. We should instead be checking if the target method
216 // has an
217 // unconditional poll. In practice, this is only a theoretical concern
218 // since we don't have any methods with conditional-only safepoint
219 // polls.
220 if (needsStatepoint(CS))
221 return true;
222 }
223
224 if (Current == Header)
225 break;
226 Current = DT.getNode(Current)->getIDom()->getBlock();
227 }
228
229 return false;
230}
231
232/// Returns true if this loop is known to terminate in a finite number of
233/// iterations. Note that this function may return false for a loop which
234/// does actual terminate in a finite constant number of iterations due to
235/// conservatism in the analysis.
236static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000237 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000238 // A conservative bound on the loop as a whole.
239 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000240 if (MaxTrips != SE->getCouldNotCompute() &&
241 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
242 CountedLoopTripWidth))
243 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000244
245 // If this is a conditional branch to the header with the alternate path
246 // being outside the loop, we can ask questions about the execution frequency
247 // of the exit block.
248 if (L->isLoopExiting(Pred)) {
249 // This returns an exact expression only. TODO: We really only need an
250 // upper bound here, but SE doesn't expose that.
251 const SCEV *MaxExec = SE->getExitCount(L, Pred);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000252 if (MaxExec != SE->getCouldNotCompute() &&
253 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
254 CountedLoopTripWidth))
Philip Reames47cc6732015-02-04 00:37:33 +0000255 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000256 }
257
258 return /* not finite */ false;
259}
260
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000261static void scanOneBB(Instruction *Start, Instruction *End,
262 std::vector<CallInst *> &Calls,
263 DenseSet<BasicBlock *> &Seen,
264 std::vector<BasicBlock *> &Worklist) {
265 for (BasicBlock::iterator BBI(Start), BBE0 = Start->getParent()->end(),
266 BBE1 = BasicBlock::iterator(End);
267 BBI != BBE0 && BBI != BBE1; BBI++) {
268 if (CallInst *CI = dyn_cast<CallInst>(&*BBI))
269 Calls.push_back(CI);
270
Philip Reames47cc6732015-02-04 00:37:33 +0000271 // FIXME: This code does not handle invokes
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000272 assert(!isa<InvokeInst>(&*BBI) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000273 "support for invokes in poll code needed");
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000274
Philip Reames47cc6732015-02-04 00:37:33 +0000275 // Only add the successor blocks if we reach the terminator instruction
276 // without encountering end first
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000277 if (BBI->isTerminator()) {
278 BasicBlock *BB = BBI->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000279 for (BasicBlock *Succ : successors(BB)) {
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000280 if (Seen.insert(Succ).second) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000281 Worklist.push_back(Succ);
Philip Reames47cc6732015-02-04 00:37:33 +0000282 }
283 }
284 }
285 }
286}
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000287
288static void scanInlinedCode(Instruction *Start, Instruction *End,
289 std::vector<CallInst *> &Calls,
290 DenseSet<BasicBlock *> &Seen) {
291 Calls.clear();
292 std::vector<BasicBlock *> Worklist;
293 Seen.insert(Start->getParent());
294 scanOneBB(Start, End, Calls, Seen, Worklist);
295 while (!Worklist.empty()) {
296 BasicBlock *BB = Worklist.back();
297 Worklist.pop_back();
298 scanOneBB(&*BB->begin(), End, Calls, Seen, Worklist);
Philip Reames47cc6732015-02-04 00:37:33 +0000299 }
300}
301
Philip Reames9f129042015-05-12 21:09:36 +0000302bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
Philip Reames5708cca2015-05-12 20:43:48 +0000303 // Loop through all loop latches (branches controlling backedges). We need
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000304 // to place a safepoint on every backedge (potentially).
Philip Reames5708cca2015-05-12 20:43:48 +0000305 // Note: In common usage, there will be only one edge due to LoopSimplify
306 // having run sometime earlier in the pipeline, but this code must be correct
307 // w.r.t. loops with multiple backedges.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000308 BasicBlock *Header = L->getHeader();
Philip Reames5708cca2015-05-12 20:43:48 +0000309 SmallVector<BasicBlock*, 16> LoopLatches;
310 L->getLoopLatches(LoopLatches);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000311 for (BasicBlock *Pred : LoopLatches) {
312 assert(L->contains(Pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000313
314 // Make a policy decision about whether this loop needs a safepoint or
315 // not. Note that this is about unburdening the optimizer in loops, not
316 // avoiding the runtime cost of the actual safepoint.
317 if (!AllBackedges) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000318 if (mustBeFiniteCountedLoop(L, SE, Pred)) {
Sanjoy Dasbb04f6e2016-01-28 23:49:27 +0000319 DEBUG(dbgs() << "skipping safepoint placement in finite loop\n");
Philip Reames47cc6732015-02-04 00:37:33 +0000320 FiniteExecution++;
321 continue;
322 }
323 if (CallSafepointsEnabled &&
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000324 containsUnconditionalCallSafepoint(L, Header, Pred, *DT)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000325 // Note: This is only semantically legal since we won't do any further
326 // IPO or inlining before the actual call insertion.. If we hadn't, we
327 // might latter loose this call safepoint.
Sanjoy Dasbb04f6e2016-01-28 23:49:27 +0000328 DEBUG(dbgs() << "skipping safepoint placement due to unconditional call\n");
Philip Reames47cc6732015-02-04 00:37:33 +0000329 CallInLoop++;
330 continue;
331 }
332 }
333
334 // TODO: We can create an inner loop which runs a finite number of
335 // iterations with an outer loop which contains a safepoint. This would
336 // not help runtime performance that much, but it might help our ability to
337 // optimize the inner loop.
338
Philip Reames47cc6732015-02-04 00:37:33 +0000339 // Safepoint insertion would involve creating a new basic block (as the
340 // target of the current backedge) which does the safepoint (of all live
341 // variables) and branches to the true header
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000342 TerminatorInst *Term = Pred->getTerminator();
Philip Reames47cc6732015-02-04 00:37:33 +0000343
Sanjoy Dasbb04f6e2016-01-28 23:49:27 +0000344 DEBUG(dbgs() << "[LSP] terminator instruction: " << *Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000345
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000346 PollLocations.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000347 }
348
Philip Reames5708cca2015-05-12 20:43:48 +0000349 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000350}
351
Philip Reamesd97cdf22015-05-19 23:40:11 +0000352/// Returns true if an entry safepoint is not required before this callsite in
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000353/// the caller function.
Philip Reamesd97cdf22015-05-19 23:40:11 +0000354static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
355 Instruction *Inst = CS.getInstruction();
356 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
357 switch (II->getIntrinsicID()) {
358 case Intrinsic::experimental_gc_statepoint:
359 case Intrinsic::experimental_patchpoint_void:
360 case Intrinsic::experimental_patchpoint_i64:
361 // The can wrap an actual call which may grow the stack by an unbounded
362 // amount or run forever.
363 return false;
364 default:
365 // Most LLVM intrinsics are things which do not expand to actual calls, or
366 // at least if they do, are leaf functions that cause only finite stack
367 // growth. In particular, the optimizer likes to form things like memsets
368 // out of stores in the original IR. Another important example is
Reid Kleckner60381792015-07-07 22:25:32 +0000369 // llvm.localescape which must occur in the entry block. Inserting a
370 // safepoint before it is not legal since it could push the localescape
Philip Reamesd97cdf22015-05-19 23:40:11 +0000371 // out of the entry block.
372 return true;
373 }
374 }
375 return false;
376}
377
Philip Reames47cc6732015-02-04 00:37:33 +0000378static Instruction *findLocationForEntrySafepoint(Function &F,
379 DominatorTree &DT) {
380
381 // Conceptually, this poll needs to be on method entry, but in
382 // practice, we place it as late in the entry block as possible. We
383 // can place it as late as we want as long as it dominates all calls
384 // that can grow the stack. This, combined with backedge polls,
385 // give us all the progress guarantees we need.
386
Philip Reames47cc6732015-02-04 00:37:33 +0000387 // hasNextInstruction and nextInstruction are used to iterate
388 // through a "straight line" execution sequence.
389
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000390 auto HasNextInstruction = [](Instruction *I) {
391 if (!I->isTerminator())
Philip Reames47cc6732015-02-04 00:37:33 +0000392 return true;
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000393
Philip Reames47cc6732015-02-04 00:37:33 +0000394 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
395 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
396 };
397
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000398 auto NextInstruction = [&](Instruction *I) {
399 assert(HasNextInstruction(I) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000400 "first check if there is a next instruction!");
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000401
402 if (I->isTerminator())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000403 return &I->getParent()->getUniqueSuccessor()->front();
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000404 return &*++I->getIterator();
Philip Reames47cc6732015-02-04 00:37:33 +0000405 };
406
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000407 Instruction *Cursor = nullptr;
408 for (Cursor = &F.getEntryBlock().front(); HasNextInstruction(Cursor);
409 Cursor = NextInstruction(Cursor)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000410
Philip Reamesd97cdf22015-05-19 23:40:11 +0000411 // We need to ensure a safepoint poll occurs before any 'real' call. The
412 // easiest way to ensure finite execution between safepoints in the face of
413 // recursive and mutually recursive functions is to enforce that each take
414 // a safepoint. Additionally, we need to ensure a poll before any call
415 // which can grow the stack by an unbounded amount. This isn't required
416 // for GC semantics per se, but is a common requirement for languages
417 // which detect stack overflow via guard pages and then throw exceptions.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000418 if (auto CS = CallSite(Cursor)) {
Philip Reamesd97cdf22015-05-19 23:40:11 +0000419 if (doesNotRequireEntrySafepointBefore(CS))
420 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000421 break;
422 }
423 }
424
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000425 assert((HasNextInstruction(Cursor) || Cursor->isTerminator()) &&
Philip Reames5a9685d2015-02-04 00:39:57 +0000426 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000427
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000428 return Cursor;
Philip Reames47cc6732015-02-04 00:37:33 +0000429}
430
Benjamin Kramer82f86522015-06-07 16:36:28 +0000431static const char *const GCSafepointPollName = "gc.safepoint_poll";
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000432
433static bool isGCSafepointPoll(Function &F) {
434 return F.getName().equals(GCSafepointPollName);
435}
436
Philip Reames0b1b3872015-02-21 00:09:09 +0000437/// Returns true if this function should be rewritten to include safepoint
438/// polls and parseable call sites. The main point of this function is to be
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000439/// an extension point for custom logic.
Philip Reames0b1b3872015-02-21 00:09:09 +0000440static bool shouldRewriteFunction(Function &F) {
441 // TODO: This should check the GCStrategy
442 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +0000443 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000444 const StringRef StatepointExampleName("statepoint-example");
445 const StringRef CoreCLRName("coreclr");
446 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +0000447 (CoreCLRName == FunctionGCName);
Philip Reames0b1b3872015-02-21 00:09:09 +0000448 } else
449 return false;
450}
451
452// TODO: These should become properties of the GCStrategy, possibly with
453// command line overrides.
454static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
455static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
456static bool enableCallSafepoints(Function &F) { return !NoCall; }
457
Philip Reames47cc6732015-02-04 00:37:33 +0000458bool PlaceSafepoints::runOnFunction(Function &F) {
459 if (F.isDeclaration() || F.empty()) {
460 // This is a declaration, nothing to do. Must exit early to avoid crash in
461 // dom tree calculation
462 return false;
463 }
464
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000465 if (isGCSafepointPoll(F)) {
466 // Given we're inlining this inside of safepoint poll insertion, this
467 // doesn't make any sense. Note that we do make any contained calls
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000468 // parseable after we inline a poll.
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000469 return false;
470 }
471
Philip Reames0b1b3872015-02-21 00:09:09 +0000472 if (!shouldRewriteFunction(F))
473 return false;
474
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000475 bool Modified = false;
Philip Reames47cc6732015-02-04 00:37:33 +0000476
477 // In various bits below, we rely on the fact that uses are reachable from
478 // defs. When there are basic blocks unreachable from the entry, dominance
479 // and reachablity queries return non-sensical results. Thus, we preprocess
480 // the function to ensure these properties hold.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000481 Modified |= removeUnreachableBlocks(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000482
483 // STEP 1 - Insert the safepoint polling locations. We do not need to
484 // actually insert parse points yet. That will be done for all polls and
485 // calls in a single pass.
486
Philip Reames47cc6732015-02-04 00:37:33 +0000487 DominatorTree DT;
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000488 DT.recalculate(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000489
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000490 SmallVector<Instruction *, 16> PollsNeeded;
Philip Reames47cc6732015-02-04 00:37:33 +0000491 std::vector<CallSite> ParsePointNeeded;
492
Philip Reames0b1b3872015-02-21 00:09:09 +0000493 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000494 // Construct a pass manager to run the LoopPass backedge logic. We
495 // need the pass manager to handle scheduling all the loop passes
496 // appropriately. Doing this by hand is painful and just not worth messing
497 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000498 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000499 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000500 auto *PBS = new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000501 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000502 FPM.run(F);
503
504 // We preserve dominance information when inserting the poll, otherwise
505 // we'd have to recalculate this on every insert
506 DT.recalculate(F);
507
Philip Reames5708cca2015-05-12 20:43:48 +0000508 auto &PollLocations = PBS->PollLocations;
509
510 auto OrderByBBName = [](Instruction *a, Instruction *b) {
511 return a->getParent()->getName() < b->getParent()->getName();
512 };
513 // We need the order of list to be stable so that naming ends up stable
514 // when we split edges. This makes test cases much easier to write.
515 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
516
517 // We can sometimes end up with duplicate poll locations. This happens if
518 // a single loop is visited more than once. The fact this happens seems
519 // wrong, but it does happen for the split-backedge.ll test case.
520 PollLocations.erase(std::unique(PollLocations.begin(),
521 PollLocations.end()),
522 PollLocations.end());
523
Philip Reames47cc6732015-02-04 00:37:33 +0000524 // Insert a poll at each point the analysis pass identified
Philip Reames89fe5702015-05-12 23:39:23 +0000525 // The poll location must be the terminator of a loop latch block.
526 for (TerminatorInst *Term : PollLocations) {
Philip Reames47cc6732015-02-04 00:37:33 +0000527 // We are inserting a poll, the function is modified
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000528 Modified = true;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000529
Philip Reames47cc6732015-02-04 00:37:33 +0000530 if (SplitBackedge) {
531 // Split the backedge of the loop and insert the poll within that new
532 // basic block. This creates a loop with two latches per original
533 // latch (which is non-ideal), but this appears to be easier to
534 // optimize in practice than inserting the poll immediately before the
535 // latch test.
536
537 // Since this is a latch, at least one of the successors must dominate
538 // it. Its possible that we have a) duplicate edges to the same header
539 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000540 // each.
541 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000542 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
543 BasicBlock *Succ = Term->getSuccessor(i);
544 if (DT.dominates(Succ, Term->getParent())) {
545 Headers.insert(Succ);
546 }
547 }
548 assert(!Headers.empty() && "poll location is not a loop latch?");
549
550 // The split loop structure here is so that we only need to recalculate
551 // the dominator tree once. Alternatively, we could just keep it up to
552 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000553 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000554 for (BasicBlock *Header : Headers) {
Philip Reames89fe5702015-05-12 23:39:23 +0000555 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000556 PollsNeeded.push_back(NewBB->getTerminator());
Philip Reames47cc6732015-02-04 00:37:33 +0000557 NumBackedgeSafepoints++;
558 }
Philip Reames47cc6732015-02-04 00:37:33 +0000559 } else {
560 // Split the latch block itself, right before the terminator.
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000561 PollsNeeded.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000562 NumBackedgeSafepoints++;
563 }
Philip Reames47cc6732015-02-04 00:37:33 +0000564 }
565 }
566
Philip Reames0b1b3872015-02-21 00:09:09 +0000567 if (enableEntrySafepoints(F)) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000568 if (Instruction *Location = findLocationForEntrySafepoint(F, DT)) {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000569 PollsNeeded.push_back(Location);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000570 Modified = true;
Philip Reames47cc6732015-02-04 00:37:33 +0000571 NumEntrySafepoints++;
Philip Reames47cc6732015-02-04 00:37:33 +0000572 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000573 // TODO: else we should assert that there was, in fact, a policy choice to
574 // not insert a entry safepoint poll.
Philip Reames47cc6732015-02-04 00:37:33 +0000575 }
576
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000577 // Now that we've identified all the needed safepoint poll locations, insert
578 // safepoint polls themselves.
579 for (Instruction *PollLocation : PollsNeeded) {
580 std::vector<CallSite> RuntimeCalls;
581 InsertSafepointPoll(PollLocation, RuntimeCalls);
582 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
583 RuntimeCalls.end());
584 }
Sanjoy Das95639742016-01-22 21:02:55 +0000585
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000586 return Modified;
Philip Reames47cc6732015-02-04 00:37:33 +0000587}
588
589char PlaceBackedgeSafepointsImpl::ID = 0;
590char PlaceSafepoints::ID = 0;
591
Philip Reames7b981792015-05-12 21:21:18 +0000592FunctionPass *llvm::createPlaceSafepointsPass() {
593 return new PlaceSafepoints();
594}
Philip Reames47cc6732015-02-04 00:37:33 +0000595
596INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
597 "place-backedge-safepoints-impl",
598 "Place Backedge Safepoints", false, false)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000599INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Philip Reames57bdac92015-05-12 20:56:33 +0000600INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames9f129042015-05-12 21:09:36 +0000601INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000602INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
603 "place-backedge-safepoints-impl",
604 "Place Backedge Safepoints", false, false)
605
606INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
607 false, false)
608INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
609 false, false)
610
Philip Reames5a9685d2015-02-04 00:39:57 +0000611static void
Philip Reames388402452015-05-26 21:03:23 +0000612InsertSafepointPoll(Instruction *InsertBefore,
Philip Reames5a9685d2015-02-04 00:39:57 +0000613 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
Philip Reames388402452015-05-26 21:03:23 +0000614 BasicBlock *OrigBB = InsertBefore->getParent();
615 Module *M = InsertBefore->getModule();
616 assert(M && "must be part of a module");
Philip Reames47cc6732015-02-04 00:37:33 +0000617
618 // Inline the safepoint poll implementation - this will get all the branch,
619 // control flow, etc.. Most importantly, it will introduce the actual slow
620 // path call - where we need to insert a safepoint (parsepoint).
Philip Reames388402452015-05-26 21:03:23 +0000621
622 auto *F = M->getFunction(GCSafepointPollName);
Manuel Jacobe3773d62015-12-29 21:57:55 +0000623 assert(F && "gc.safepoint_poll function is missing");
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000624 assert(F->getValueType() ==
Philip Reames388402452015-05-26 21:03:23 +0000625 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
626 "gc.safepoint_poll declared with wrong type");
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000627 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames388402452015-05-26 21:03:23 +0000628 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
Philip Reames47cc6732015-02-04 00:37:33 +0000629
630 // Record some information about the call site we're replacing
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000631 BasicBlock::iterator Before(PollCall), After(PollCall);
632 bool IsBegin = false;
633 if (Before == OrigBB->begin())
634 IsBegin = true;
635 else
636 Before--;
Philip Reames47cc6732015-02-04 00:37:33 +0000637
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000638 After++;
639 assert(After != OrigBB->end() && "must have successor");
640
641 // Do the actual inlining
Philip Reames47cc6732015-02-04 00:37:33 +0000642 InlineFunctionInfo IFI;
Philip Reames388402452015-05-26 21:03:23 +0000643 bool InlineStatus = InlineFunction(PollCall, IFI);
644 assert(InlineStatus && "inline must succeed");
645 (void)InlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000646
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000647 // Check post-conditions
Philip Reames47cc6732015-02-04 00:37:33 +0000648 assert(IFI.StaticAllocas.empty() && "can't have allocs");
649
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000650 std::vector<CallInst *> Calls; // new calls
651 DenseSet<BasicBlock *> BBs; // new BBs + insertee
652
Philip Reames47cc6732015-02-04 00:37:33 +0000653 // Include only the newly inserted instructions, Note: begin may not be valid
654 // if we inserted to the beginning of the basic block
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000655 BasicBlock::iterator Start = IsBegin ? OrigBB->begin() : std::next(Before);
Philip Reames47cc6732015-02-04 00:37:33 +0000656
657 // If your poll function includes an unreachable at the end, that's not
658 // valid. Bugpoint likes to create this, so check for it.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000659 assert(isPotentiallyReachable(&*Start, &*After) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000660 "malformed poll function");
661
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000662 scanInlinedCode(&*Start, &*After, Calls, BBs);
663 assert(!Calls.empty() && "slow path not found for safepoint poll");
Philip Reames47cc6732015-02-04 00:37:33 +0000664
665 // Record the fact we need a parsable state at the runtime call contained in
666 // the poll function. This is required so that the runtime knows how to
667 // parse the last frame when we actually take the safepoint (i.e. execute
668 // the slow path)
669 assert(ParsePointsNeeded.empty());
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000670 for (auto *CI : Calls) {
Philip Reames47cc6732015-02-04 00:37:33 +0000671 // No safepoint needed or wanted
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000672 if (!needsStatepoint(CI))
Philip Reames47cc6732015-02-04 00:37:33 +0000673 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000674
675 // These are likely runtime calls. Should we assert that via calling
676 // convention or something?
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000677 ParsePointsNeeded.push_back(CallSite(CI));
Philip Reames47cc6732015-02-04 00:37:33 +0000678 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000679 assert(ParsePointsNeeded.size() <= Calls.size());
Philip Reames47cc6732015-02-04 00:37:33 +0000680}