blob: 376be88fe8a456a8995ceff687593119c4dedd2e [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
19// point is represented by a call wrapped in an gc.statepoint intrinsic.
20// - 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
30// are neccessary to ensure a finite period between poll sites. This is not
31// 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"
Chandler Carruth30d69c22015-02-13 10:01:29 +000052#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000053#include "llvm/ADT/SetOperations.h"
54#include "llvm/ADT/Statistic.h"
55#include "llvm/Analysis/LoopPass.h"
56#include "llvm/Analysis/LoopInfo.h"
57#include "llvm/Analysis/ScalarEvolution.h"
58#include "llvm/Analysis/ScalarEvolutionExpressions.h"
59#include "llvm/Analysis/CFG.h"
60#include "llvm/Analysis/InstructionSimplify.h"
61#include "llvm/IR/BasicBlock.h"
62#include "llvm/IR/CallSite.h"
63#include "llvm/IR/Dominators.h"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/IRBuilder.h"
66#include "llvm/IR/InstIterator.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/Intrinsics.h"
69#include "llvm/IR/IntrinsicInst.h"
70#include "llvm/IR/Module.h"
71#include "llvm/IR/Statepoint.h"
72#include "llvm/IR/Value.h"
73#include "llvm/IR/Verifier.h"
74#include "llvm/Support/Debug.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/raw_ostream.h"
77#include "llvm/Transforms/Scalar.h"
78#include "llvm/Transforms/Utils/BasicBlockUtils.h"
79#include "llvm/Transforms/Utils/Cloning.h"
80#include "llvm/Transforms/Utils/Local.h"
81
82#define DEBUG_TYPE "safepoint-placement"
83STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
84STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
85STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
86
87STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
88STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
89
90using namespace llvm;
91
92// Ignore oppurtunities to avoid placing safepoints on backedges, useful for
93// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000094static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
95 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000096
97/// If true, do not place backedge safepoints in counted loops.
Philip Reames1f3e5c12015-02-20 23:32:03 +000098static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
Philip Reames47cc6732015-02-04 00:37:33 +000099
100// If true, split the backedge of a loop when placing the safepoint, otherwise
101// split the latch block itself. Both are useful to support for
102// experimentation, but in practice, it looks like splitting the backedge
103// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +0000104static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
105 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000106
107// Print tracing output
Philip Reames1f3e5c12015-02-20 23:32:03 +0000108static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000109
110namespace {
111
112/** An analysis pass whose purpose is to identify each of the backedges in
113 the function which require a safepoint poll to be inserted. */
114struct PlaceBackedgeSafepointsImpl : public LoopPass {
115 static char ID;
116
117 /// The output of the pass - gives a list of each backedge (described by
118 /// pointing at the branch) which need a poll inserted.
119 std::vector<TerminatorInst *> PollLocations;
120
121 /// True unless we're running spp-no-calls in which case we need to disable
122 /// the call dependend placement opts.
123 bool CallSafepointsEnabled;
124 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
125 : LoopPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000126 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000127 }
128
129 bool runOnLoop(Loop *, LPPassManager &LPM) override;
130
131 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 // needed for determining if the loop is finite
133 AU.addRequired<ScalarEvolution>();
134 // to ensure each edge has a single backedge
135 // TODO: is this still required?
136 AU.addRequiredID(LoopSimplifyID);
137
138 // We no longer modify the IR at all in this pass. Thus all
139 // analysis are preserved.
140 AU.setPreservesAll();
141 }
142};
143}
144
Philip Reames1f3e5c12015-02-20 23:32:03 +0000145static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
146static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
147static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000148
149namespace {
150struct PlaceSafepoints : public ModulePass {
151 static char ID; // Pass identification, replacement for typeid
152
Philip Reames47cc6732015-02-04 00:37:33 +0000153 PlaceSafepoints() : ModulePass(ID) {
154 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000155 }
156 bool runOnModule(Module &M) override {
157 bool modified = false;
158 for (Function &F : M) {
159 modified |= runOnFunction(F);
160 }
161 return modified;
162 }
163 bool runOnFunction(Function &F);
164
165 void getAnalysisUsage(AnalysisUsage &AU) const override {
166 // We modify the graph wholesale (inlining, block insertion, etc). We
167 // preserve nothing at the moment. We could potentially preserve dom tree
168 // if that was worth doing
169 }
170};
171}
172
173// Insert a safepoint poll immediately before the given instruction. Does
174// not handle the parsability of state at the runtime call, that's the
175// callers job.
Philip Reames5a9685d2015-02-04 00:39:57 +0000176static void
177InsertSafepointPoll(DominatorTree &DT, Instruction *after,
178 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
Philip Reames47cc6732015-02-04 00:37:33 +0000179
180static bool isGCLeafFunction(const CallSite &CS);
181
182static bool needsStatepoint(const CallSite &CS) {
183 if (isGCLeafFunction(CS))
184 return false;
185 if (CS.isCall()) {
186 CallInst *call = cast<CallInst>(CS.getInstruction());
187 if (call->isInlineAsm())
188 return false;
189 }
190 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
191 return false;
192 }
193 return true;
194}
195
Philip Reames5a9685d2015-02-04 00:39:57 +0000196static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
Philip Reames47cc6732015-02-04 00:37:33 +0000197
198/// Returns true if this loop is known to contain a call safepoint which
199/// must unconditionally execute on any iteration of the loop which returns
200/// to the loop header via an edge from Pred. Returns a conservative correct
201/// answer; i.e. false is always valid.
202static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
203 BasicBlock *Pred,
204 DominatorTree &DT) {
205 // 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
210 // of such dominating blocks gets substaintially more occurences than just
211 // 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) {
220 if (CallSite CS = &I)
221 // 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.
227 if (needsStatepoint(CS))
228 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 // Only used when SkipCounted is off
246 const unsigned upperTripBound = 8192;
247
248 // A conservative bound on the loop as a whole.
249 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
250 if (MaxTrips != SE->getCouldNotCompute()) {
251 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
252 return true;
253 if (SkipCounted &&
254 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
255 return true;
256 }
257
258 // If this is a conditional branch to the header with the alternate path
259 // being outside the loop, we can ask questions about the execution frequency
260 // of the exit block.
261 if (L->isLoopExiting(Pred)) {
262 // This returns an exact expression only. TODO: We really only need an
263 // upper bound here, but SE doesn't expose that.
264 const SCEV *MaxExec = SE->getExitCount(L, Pred);
265 if (MaxExec != SE->getCouldNotCompute()) {
266 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
267 return true;
268 if (SkipCounted &&
269 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
270 return true;
271 }
272 }
273
274 return /* not finite */ false;
275}
276
277static void scanOneBB(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000278 std::vector<CallInst *> &calls,
279 std::set<BasicBlock *> &seen,
280 std::vector<BasicBlock *> &worklist) {
Philip Reames47cc6732015-02-04 00:37:33 +0000281 for (BasicBlock::iterator itr(start);
282 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
283 itr++) {
284 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
285 calls.push_back(CI);
286 }
287 // FIXME: This code does not handle invokes
288 assert(!dyn_cast<InvokeInst>(&*itr) &&
289 "support for invokes in poll code needed");
290 // Only add the successor blocks if we reach the terminator instruction
291 // without encountering end first
292 if (itr->isTerminator()) {
293 BasicBlock *BB = itr->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000294 for (BasicBlock *Succ : successors(BB)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000295 if (seen.count(Succ) == 0) {
296 worklist.push_back(Succ);
297 seen.insert(Succ);
298 }
299 }
300 }
301 }
302}
303static void scanInlinedCode(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000304 std::vector<CallInst *> &calls,
305 std::set<BasicBlock *> &seen) {
Philip Reames47cc6732015-02-04 00:37:33 +0000306 calls.clear();
307 std::vector<BasicBlock *> worklist;
308 seen.insert(start->getParent());
309 scanOneBB(start, end, calls, seen, worklist);
310 while (!worklist.empty()) {
311 BasicBlock *BB = worklist.back();
312 worklist.pop_back();
313 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
314 }
315}
316
317bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L, LPPassManager &LPM) {
318 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
319
320 // Loop through all predecessors of the loop header and identify all
321 // backedges. We need to place a safepoint on every backedge (potentially).
322 // Note: Due to LoopSimplify there should only be one. Assert? Or can we
323 // relax this?
324 BasicBlock *header = L->getHeader();
325
326 // TODO: Use the analysis pass infrastructure for this. There is no reason
327 // to recalculate this here.
328 DominatorTree DT;
329 DT.recalculate(*header->getParent());
330
331 bool modified = false;
Philip Reamesa29de872015-02-09 22:26:11 +0000332 for (BasicBlock *pred : predecessors(header)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000333 if (!L->contains(pred)) {
334 // This is not a backedge, it's coming from outside the loop
335 continue;
336 }
337
338 // Make a policy decision about whether this loop needs a safepoint or
339 // not. Note that this is about unburdening the optimizer in loops, not
340 // avoiding the runtime cost of the actual safepoint.
341 if (!AllBackedges) {
342 if (mustBeFiniteCountedLoop(L, SE, pred)) {
343 if (TraceLSP)
344 errs() << "skipping safepoint placement in finite loop\n";
345 FiniteExecution++;
346 continue;
347 }
348 if (CallSafepointsEnabled &&
349 containsUnconditionalCallSafepoint(L, header, pred, DT)) {
350 // Note: This is only semantically legal since we won't do any further
351 // IPO or inlining before the actual call insertion.. If we hadn't, we
352 // might latter loose this call safepoint.
353 if (TraceLSP)
354 errs() << "skipping safepoint placement due to unconditional call\n";
355 CallInLoop++;
356 continue;
357 }
358 }
359
360 // TODO: We can create an inner loop which runs a finite number of
361 // iterations with an outer loop which contains a safepoint. This would
362 // not help runtime performance that much, but it might help our ability to
363 // optimize the inner loop.
364
365 // We're unconditionally going to modify this loop.
366 modified = true;
367
368 // Safepoint insertion would involve creating a new basic block (as the
369 // target of the current backedge) which does the safepoint (of all live
370 // variables) and branches to the true header
371 TerminatorInst *term = pred->getTerminator();
372
373 if (TraceLSP) {
374 errs() << "[LSP] terminator instruction: ";
375 term->dump();
376 }
377
378 PollLocations.push_back(term);
379 }
380
381 return modified;
382}
383
384static Instruction *findLocationForEntrySafepoint(Function &F,
385 DominatorTree &DT) {
386
387 // Conceptually, this poll needs to be on method entry, but in
388 // practice, we place it as late in the entry block as possible. We
389 // can place it as late as we want as long as it dominates all calls
390 // that can grow the stack. This, combined with backedge polls,
391 // give us all the progress guarantees we need.
392
393 // Due to the way the frontend generates IR, we may have a couple of initial
394 // basic blocks before the first bytecode. These will be single-entry
395 // single-exit blocks which conceptually are just part of the first 'real
396 // basic block'. Since we don't have deopt state until the first bytecode,
397 // walk forward until we've found the first unconditional branch or merge.
398
399 // hasNextInstruction and nextInstruction are used to iterate
400 // through a "straight line" execution sequence.
401
402 auto hasNextInstruction = [](Instruction *I) {
403 if (!I->isTerminator()) {
404 return true;
405 }
406 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
407 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
408 };
409
410 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
411 assert(hasNextInstruction(I) &&
412 "first check if there is a next instruction!");
413 if (I->isTerminator()) {
414 return I->getParent()->getUniqueSuccessor()->begin();
415 } else {
416 return std::next(BasicBlock::iterator(I));
417 }
418 };
419
420 Instruction *cursor = nullptr;
421 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
422 cursor = nextInstruction(cursor)) {
423
Philip Reames47cc6732015-02-04 00:37:33 +0000424 // We need to stop going forward as soon as we see a call that can
425 // grow the stack (i.e. the call target has a non-zero frame
426 // size).
427 if (CallSite CS = cursor) {
428 (void)CS; // Silence an unused variable warning by gcc 4.8.2
429 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) {
430 // llvm.assume(...) are not really calls.
431 if (II->getIntrinsicID() == Intrinsic::assume) {
432 continue;
433 }
434 }
435 break;
436 }
437 }
438
Philip Reames5a9685d2015-02-04 00:39:57 +0000439 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
440 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000441
442 if (cursor->isTerminator()) {
443 return cursor;
444 }
445
446 BasicBlock *BB = cursor->getParent();
447 SplitBlock(BB, cursor, nullptr);
448
449 // Note: SplitBlock modifies the DT. Simply passing a Pass (which is a
450 // module pass) is not enough.
451 DT.recalculate(F);
452#ifndef NDEBUG
453 // SplitBlock updates the DT
454 DT.verifyDomTree();
455#endif
456
457 return BB->getTerminator();
458}
459
460/// Identify the list of call sites which need to be have parseable state
461static void findCallSafepoints(Function &F,
462 std::vector<CallSite> &Found /*rval*/) {
463 assert(Found.empty() && "must be empty!");
Philip Reamesa29de872015-02-09 22:26:11 +0000464 for (Instruction &I : inst_range(F)) {
465 Instruction *inst = &I;
Philip Reames47cc6732015-02-04 00:37:33 +0000466 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
467 CallSite CS(inst);
468
469 // No safepoint needed or wanted
470 if (!needsStatepoint(CS)) {
471 continue;
472 }
473
474 Found.push_back(CS);
475 }
476 }
477}
478
479/// Implement a unique function which doesn't require we sort the input
480/// vector. Doing so has the effect of changing the output of a couple of
481/// tests in ways which make them less useful in testing fused safepoints.
482template <typename T> static void unique_unsorted(std::vector<T> &vec) {
483 std::set<T> seen;
484 std::vector<T> tmp;
485 vec.reserve(vec.size());
486 std::swap(tmp, vec);
487 for (auto V : tmp) {
488 if (seen.insert(V).second) {
489 vec.push_back(V);
490 }
491 }
492}
493
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000494static std::string GCSafepointPollName("gc.safepoint_poll");
495
496static bool isGCSafepointPoll(Function &F) {
497 return F.getName().equals(GCSafepointPollName);
498}
499
Philip Reames0b1b3872015-02-21 00:09:09 +0000500/// Returns true if this function should be rewritten to include safepoint
501/// polls and parseable call sites. The main point of this function is to be
502/// an extension point for custom logic.
503static bool shouldRewriteFunction(Function &F) {
504 // TODO: This should check the GCStrategy
505 if (F.hasGC()) {
506 const std::string StatepointExampleName("statepoint-example");
507 return StatepointExampleName == F.getGC();
508 } else
509 return false;
510}
511
512// TODO: These should become properties of the GCStrategy, possibly with
513// command line overrides.
514static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
515static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
516static bool enableCallSafepoints(Function &F) { return !NoCall; }
517
518
Philip Reames47cc6732015-02-04 00:37:33 +0000519bool PlaceSafepoints::runOnFunction(Function &F) {
520 if (F.isDeclaration() || F.empty()) {
521 // This is a declaration, nothing to do. Must exit early to avoid crash in
522 // dom tree calculation
523 return false;
524 }
525
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000526 if (isGCSafepointPoll(F)) {
527 // Given we're inlining this inside of safepoint poll insertion, this
528 // doesn't make any sense. Note that we do make any contained calls
529 // parseable after we inline a poll.
530 return false;
531 }
532
Philip Reames0b1b3872015-02-21 00:09:09 +0000533 if (!shouldRewriteFunction(F))
534 return false;
535
Philip Reames47cc6732015-02-04 00:37:33 +0000536 bool modified = false;
537
538 // In various bits below, we rely on the fact that uses are reachable from
539 // defs. When there are basic blocks unreachable from the entry, dominance
540 // and reachablity queries return non-sensical results. Thus, we preprocess
541 // the function to ensure these properties hold.
542 modified |= removeUnreachableBlocks(F);
543
544 // STEP 1 - Insert the safepoint polling locations. We do not need to
545 // actually insert parse points yet. That will be done for all polls and
546 // calls in a single pass.
547
548 // Note: With the migration, we need to recompute this for each 'pass'. Once
549 // we merge these, we'll do it once before the analysis
550 DominatorTree DT;
551
552 std::vector<CallSite> ParsePointNeeded;
553
Philip Reames0b1b3872015-02-21 00:09:09 +0000554 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000555 // Construct a pass manager to run the LoopPass backedge logic. We
556 // need the pass manager to handle scheduling all the loop passes
557 // appropriately. Doing this by hand is painful and just not worth messing
558 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000559 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000560 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000561 PlaceBackedgeSafepointsImpl *PBS =
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000562 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000563 FPM.add(PBS);
564 // Note: While the analysis pass itself won't modify the IR, LoopSimplify
565 // (which it depends on) may. i.e. analysis must be recalculated after run
566 FPM.run(F);
567
568 // We preserve dominance information when inserting the poll, otherwise
569 // we'd have to recalculate this on every insert
570 DT.recalculate(F);
571
572 // Insert a poll at each point the analysis pass identified
573 for (size_t i = 0; i < PBS->PollLocations.size(); i++) {
574 // We are inserting a poll, the function is modified
575 modified = true;
576
577 // The poll location must be the terminator of a loop latch block.
578 TerminatorInst *Term = PBS->PollLocations[i];
579
580 std::vector<CallSite> ParsePoints;
581 if (SplitBackedge) {
582 // Split the backedge of the loop and insert the poll within that new
583 // basic block. This creates a loop with two latches per original
584 // latch (which is non-ideal), but this appears to be easier to
585 // optimize in practice than inserting the poll immediately before the
586 // latch test.
587
588 // Since this is a latch, at least one of the successors must dominate
589 // it. Its possible that we have a) duplicate edges to the same header
590 // and b) edges to distinct loop headers. We need to insert pools on
591 // each. (Note: This still relies on LoopSimplify.)
Philip Reames5a9685d2015-02-04 00:39:57 +0000592 DenseSet<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000593 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
594 BasicBlock *Succ = Term->getSuccessor(i);
595 if (DT.dominates(Succ, Term->getParent())) {
596 Headers.insert(Succ);
597 }
598 }
599 assert(!Headers.empty() && "poll location is not a loop latch?");
600
601 // The split loop structure here is so that we only need to recalculate
602 // the dominator tree once. Alternatively, we could just keep it up to
603 // date and use a more natural merged loop.
Philip Reames5a9685d2015-02-04 00:39:57 +0000604 DenseSet<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000605 for (BasicBlock *Header : Headers) {
606 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, nullptr);
607 SplitBackedges.insert(NewBB);
608 }
609 DT.recalculate(F);
610 for (BasicBlock *NewBB : SplitBackedges) {
611 InsertSafepointPoll(DT, NewBB->getTerminator(), ParsePoints);
612 NumBackedgeSafepoints++;
613 }
614
615 } else {
616 // Split the latch block itself, right before the terminator.
617 InsertSafepointPoll(DT, Term, ParsePoints);
618 NumBackedgeSafepoints++;
619 }
620
Philip Reames47cc6732015-02-04 00:37:33 +0000621 // Record the parse points for later use
622 ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
623 ParsePoints.end());
624 }
625 }
626
Philip Reames0b1b3872015-02-21 00:09:09 +0000627 if (enableEntrySafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000628 DT.recalculate(F);
629 Instruction *term = findLocationForEntrySafepoint(F, DT);
630 if (!term) {
631 // policy choice not to insert?
632 } else {
633 std::vector<CallSite> RuntimeCalls;
634 InsertSafepointPoll(DT, term, RuntimeCalls);
635 modified = true;
636 NumEntrySafepoints++;
637 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
638 RuntimeCalls.end());
639 }
640 }
641
Philip Reames0b1b3872015-02-21 00:09:09 +0000642 if (enableCallSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000643 DT.recalculate(F);
644 std::vector<CallSite> Calls;
645 findCallSafepoints(F, Calls);
646 NumCallSafepoints += Calls.size();
Philip Reames5a9685d2015-02-04 00:39:57 +0000647 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000648 }
649
650 // Unique the vectors since we can end up with duplicates if we scan the call
651 // site for call safepoints after we add it for entry or backedge. The
652 // only reason we need tracking at all is that some functions might have
653 // polls but not call safepoints and thus we might miss marking the runtime
654 // calls for the polls. (This is useful in test cases!)
655 unique_unsorted(ParsePointNeeded);
656
657 // Any parse point (no matter what source) will be handled here
658 DT.recalculate(F); // Needed?
659
660 // We're about to start modifying the function
661 if (!ParsePointNeeded.empty())
662 modified = true;
663
664 // Now run through and insert the safepoints, but do _NOT_ update or remove
665 // any existing uses. We have references to live variables that need to
666 // survive to the last iteration of this loop.
667 std::vector<Value *> Results;
668 Results.reserve(ParsePointNeeded.size());
669 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
670 CallSite &CS = ParsePointNeeded[i];
671 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
672 Results.push_back(GCResult);
673 }
674 assert(Results.size() == ParsePointNeeded.size());
675
676 // Adjust all users of the old call sites to use the new ones instead
677 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
678 CallSite &CS = ParsePointNeeded[i];
679 Value *GCResult = Results[i];
680 if (GCResult) {
681 // In case if we inserted result in a different basic block than the
682 // original safepoint (this can happen for invokes). We need to be sure
683 // that
684 // original result value was not used in any of the phi nodes at the
685 // beginning of basic block with gc result. Because we know that all such
686 // blocks will have single predecessor we can safely assume that all phi
687 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
688 // Just remove them all here.
689 if (CS.isInvoke()) {
690 FoldSingleEntryPHINodes(cast<Instruction>(GCResult)->getParent(),
691 nullptr);
692 assert(
693 !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
694 }
695
696 // Replace all uses with the new call
697 CS.getInstruction()->replaceAllUsesWith(GCResult);
698 }
699
700 // Now that we've handled all uses, remove the original call itself
701 // Note: The insert point can't be the deleted instruction!
702 CS.getInstruction()->eraseFromParent();
703 }
704 return modified;
705}
706
707char PlaceBackedgeSafepointsImpl::ID = 0;
708char PlaceSafepoints::ID = 0;
709
Philip Reames5a9685d2015-02-04 00:39:57 +0000710ModulePass *llvm::createPlaceSafepointsPass() { return new PlaceSafepoints(); }
Philip Reames47cc6732015-02-04 00:37:33 +0000711
712INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
713 "place-backedge-safepoints-impl",
714 "Place Backedge Safepoints", false, false)
715INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
716INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
717INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
718 "place-backedge-safepoints-impl",
719 "Place Backedge Safepoints", false, false)
720
721INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
722 false, false)
723INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
724 false, false)
725
726static bool isGCLeafFunction(const CallSite &CS) {
727 Instruction *inst = CS.getInstruction();
Aaron Ballman94d4d332015-02-05 13:52:42 +0000728 if (isa<IntrinsicInst>(inst)) {
Aaron Ballman1b072b32015-02-05 13:40:04 +0000729 // Most LLVM intrinsics are things which can never take a safepoint.
730 // As a result, we don't need to have the stack parsable at the
731 // callsite. This is a highly useful optimization since intrinsic
732 // calls are fairly prevelent, particularly in debug builds.
733 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000734 }
735
736 // If this function is marked explicitly as a leaf call, we don't need to
737 // place a safepoint of it. In fact, for correctness we *can't* in many
738 // cases. Note: Indirect calls return Null for the called function,
739 // these obviously aren't runtime functions with attributes
740 // TODO: Support attributes on the call site as well.
741 const Function *F = CS.getCalledFunction();
742 bool isLeaf =
743 F &&
744 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
745 if (isLeaf) {
746 return true;
747 }
748 return false;
749}
750
Philip Reames5a9685d2015-02-04 00:39:57 +0000751static void
752InsertSafepointPoll(DominatorTree &DT, Instruction *term,
753 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
Philip Reames47cc6732015-02-04 00:37:33 +0000754 Module *M = term->getParent()->getParent()->getParent();
755 assert(M);
756
757 // Inline the safepoint poll implementation - this will get all the branch,
758 // control flow, etc.. Most importantly, it will introduce the actual slow
759 // path call - where we need to insert a safepoint (parsepoint).
760 FunctionType *ftype =
761 FunctionType::get(Type::getVoidTy(M->getContext()), false);
762 assert(ftype && "null?");
763 // Note: This cast can fail if there's a function of the same name with a
764 // different type inserted previously
765 Function *F =
766 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000767 assert(F && "void @gc.safepoint_poll() must be defined");
768 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames47cc6732015-02-04 00:37:33 +0000769 CallInst *poll = CallInst::Create(F, "", term);
770
771 // Record some information about the call site we're replacing
772 BasicBlock *OrigBB = term->getParent();
773 BasicBlock::iterator before(poll), after(poll);
774 bool isBegin(false);
775 if (before == term->getParent()->begin()) {
776 isBegin = true;
777 } else {
778 before--;
779 }
780 after++;
781 assert(after != poll->getParent()->end() && "must have successor");
782 assert(DT.dominates(before, after) && "trivially true");
783
784 // do the actual inlining
785 InlineFunctionInfo IFI;
786 bool inlineStatus = InlineFunction(poll, IFI);
787 assert(inlineStatus && "inline must succeed");
Philip Reames72634d62015-02-04 05:11:20 +0000788 (void)inlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000789
790 // Check post conditions
791 assert(IFI.StaticAllocas.empty() && "can't have allocs");
792
793 std::vector<CallInst *> calls; // new calls
794 std::set<BasicBlock *> BBs; // new BBs + insertee
795 // Include only the newly inserted instructions, Note: begin may not be valid
796 // if we inserted to the beginning of the basic block
797 BasicBlock::iterator start;
798 if (isBegin) {
799 start = OrigBB->begin();
800 } else {
801 start = before;
802 start++;
803 }
804
805 // If your poll function includes an unreachable at the end, that's not
806 // valid. Bugpoint likes to create this, so check for it.
807 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
808 "malformed poll function");
809
810 scanInlinedCode(&*(start), &*(after), calls, BBs);
811
812 // Recompute since we've invalidated cached data. Conceptually we
813 // shouldn't need to do this, but implementation wise we appear to. Needed
814 // so we can insert safepoints correctly.
815 // TODO: update more cheaply
816 DT.recalculate(*after->getParent()->getParent());
817
818 assert(!calls.empty() && "slow path not found for safepoint poll");
819
820 // Record the fact we need a parsable state at the runtime call contained in
821 // the poll function. This is required so that the runtime knows how to
822 // parse the last frame when we actually take the safepoint (i.e. execute
823 // the slow path)
824 assert(ParsePointsNeeded.empty());
825 for (size_t i = 0; i < calls.size(); i++) {
826
827 // No safepoint needed or wanted
828 if (!needsStatepoint(calls[i])) {
829 continue;
830 }
831
832 // These are likely runtime calls. Should we assert that via calling
833 // convention or something?
834 ParsePointsNeeded.push_back(CallSite(calls[i]));
835 }
836 assert(ParsePointsNeeded.size() <= calls.size());
837}
838
839// Normalize basic block to make it ready to be target of invoke statepoint.
840// It means spliting it to have single predecessor. Return newly created BB
841// ready to be successor of invoke statepoint.
842static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
843 BasicBlock *InvokeParent) {
844 BasicBlock *ret = BB;
845
846 if (!BB->getUniquePredecessor()) {
847 ret = SplitBlockPredecessors(BB, InvokeParent, "");
848 }
849
850 // Another requirement for such basic blocks is to not have any phi nodes.
851 // Since we just ensured that new BB will have single predecessor,
852 // all phi nodes in it will have one value. Here it would be naturall place
853 // to
854 // remove them all. But we can not do this because we are risking to remove
855 // one of the values stored in liveset of another statepoint. We will do it
856 // later after placing all safepoints.
857
858 return ret;
859}
860
861/// Replaces the given call site (Call or Invoke) with a gc.statepoint
862/// intrinsic with an empty deoptimization arguments list. This does
863/// NOT do explicit relocation for GC support.
864static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
865 Pass *P) {
866 BasicBlock *BB = CS.getInstruction()->getParent();
867 Function *F = BB->getParent();
868 Module *M = F->getParent();
869 assert(M && "must be set");
870
871 // TODO: technically, a pass is not allowed to get functions from within a
872 // function pass since it might trigger a new function addition. Refactor
873 // this logic out to the initialization of the pass. Doesn't appear to
874 // matter in practice.
875
876 // Fill in the one generic type'd argument (the function is also vararg)
877 std::vector<Type *> argTypes;
878 argTypes.push_back(CS.getCalledValue()->getType());
879
880 Function *gc_statepoint_decl = Intrinsic::getDeclaration(
881 M, Intrinsic::experimental_gc_statepoint, argTypes);
882
883 // Then go ahead and use the builder do actually do the inserts. We insert
884 // immediately before the previous instruction under the assumption that all
885 // arguments will be available here. We can't insert afterwards since we may
886 // be replacing a terminator.
887 Instruction *insertBefore = CS.getInstruction();
888 IRBuilder<> Builder(insertBefore);
889 // First, create the statepoint (with all live ptrs as arguments).
890 std::vector<llvm::Value *> args;
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000891 // target, #call args, unused, call args..., #deopt args, deopt args..., gc args...
Philip Reames47cc6732015-02-04 00:37:33 +0000892 Value *Target = CS.getCalledValue();
893 args.push_back(Target);
894 int callArgSize = CS.arg_size();
895 args.push_back(
896 ConstantInt::get(Type::getInt32Ty(M->getContext()), callArgSize));
897 // TODO: add a 'Needs GC-rewrite' later flag
898 args.push_back(ConstantInt::get(Type::getInt32Ty(M->getContext()), 0));
899
900 // Copy all the arguments of the original call
901 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
902
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000903 // # of deopt arguments: this pass currently does not support the
904 // identification of deopt arguments. If this is interesting to you,
905 // please ask on llvm-dev.
906 args.push_back(ConstantInt::get(Type::getInt32Ty(M->getContext()), 0));
907
908 // Note: The gc args are not filled in at this time, that's handled by
909 // RewriteStatepointsForGC (which is currently under review).
910
Philip Reames47cc6732015-02-04 00:37:33 +0000911 // Create the statepoint given all the arguments
912 Instruction *token = nullptr;
913 AttributeSet return_attributes;
914 if (CS.isCall()) {
915 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
916 CallInst *call =
917 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
918 call->setTailCall(toReplace->isTailCall());
919 call->setCallingConv(toReplace->getCallingConv());
920
921 // Before we have to worry about GC semantics, all attributes are legal
922 AttributeSet new_attrs = toReplace->getAttributes();
923 // In case if we can handle this set of sttributes - set up function attrs
924 // directly on statepoint and return attrs later for gc_result intrinsic.
925 call->setAttributes(new_attrs.getFnAttributes());
926 return_attributes = new_attrs.getRetAttributes();
927 // TODO: handle param attributes
928
929 token = call;
930
931 // Put the following gc_result and gc_relocate calls immediately after the
932 // the old call (which we're about to delete)
933 BasicBlock::iterator next(toReplace);
934 assert(BB->end() != next && "not a terminator, must have next");
935 next++;
936 Instruction *IP = &*(next);
937 Builder.SetInsertPoint(IP);
938 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
939
940 } else if (CS.isInvoke()) {
941 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
942
943 // Insert the new invoke into the old block. We'll remove the old one in a
944 // moment at which point this will become the new terminator for the
945 // original block.
946 InvokeInst *invoke = InvokeInst::Create(
947 gc_statepoint_decl, toReplace->getNormalDest(),
948 toReplace->getUnwindDest(), args, "", toReplace->getParent());
949 invoke->setCallingConv(toReplace->getCallingConv());
950
951 // Currently we will fail on parameter attributes and on certain
952 // function attributes.
953 AttributeSet new_attrs = toReplace->getAttributes();
954 // In case if we can handle this set of sttributes - set up function attrs
955 // directly on statepoint and return attrs later for gc_result intrinsic.
956 invoke->setAttributes(new_attrs.getFnAttributes());
957 return_attributes = new_attrs.getRetAttributes();
958
959 token = invoke;
960
961 // We'll insert the gc.result into the normal block
962 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
963 toReplace->getNormalDest(), invoke->getParent());
964 Instruction *IP = &*(normalDest->getFirstInsertionPt());
965 Builder.SetInsertPoint(IP);
966 } else {
967 llvm_unreachable("unexpect type of CallSite");
968 }
969 assert(token);
970
971 // Handle the return value of the original call - update all uses to use a
972 // gc_result hanging off the statepoint node we just inserted
973
974 // Only add the gc_result iff there is actually a used result
975 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
976 Instruction *gc_result = nullptr;
Philip Reames5a9685d2015-02-04 00:39:57 +0000977 std::vector<Type *> types; // one per 'any' type
Philip Reames47cc6732015-02-04 00:37:33 +0000978 types.push_back(CS.getType()); // result type
Ramkumar Ramachandra2e4b9e02015-02-09 23:00:40 +0000979 Intrinsic::ID Id = Intrinsic::experimental_gc_result;
Philip Reames47cc6732015-02-04 00:37:33 +0000980 Value *gc_result_func = Intrinsic::getDeclaration(M, Id, types);
981
982 std::vector<Value *> args;
983 args.push_back(token);
984 gc_result = Builder.CreateCall(
985 gc_result_func, args,
986 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "");
987
988 cast<CallInst>(gc_result)->setAttributes(return_attributes);
989 return gc_result;
990 } else {
991 // No return value for the call.
992 return nullptr;
993 }
994}