1 //===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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".
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.
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.
39 // This pass will insert:
40 // - 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.
45 // 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.
49 //===----------------------------------------------------------------------===//
51 #include "llvm/Pass.h"
52 #include "llvm/IR/LegacyPassManager.h"
53 #include "llvm/ADT/SetOperations.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/Analysis/LoopPass.h"
57 #include "llvm/Analysis/LoopInfo.h"
58 #include "llvm/Analysis/ScalarEvolution.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/Analysis/CFG.h"
61 #include "llvm/Analysis/InstructionSimplify.h"
62 #include "llvm/IR/BasicBlock.h"
63 #include "llvm/IR/CallSite.h"
64 #include "llvm/IR/Dominators.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/InstIterator.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicInst.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Statepoint.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/Verifier.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Scalar.h"
79 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
80 #include "llvm/Transforms/Utils/Cloning.h"
81 #include "llvm/Transforms/Utils/Local.h"
83 #define DEBUG_TYPE "safepoint-placement"
84 STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
85 STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
86 STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
88 STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
89 STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
93 // Ignore oppurtunities to avoid placing safepoints on backedges, useful for
95 static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
98 /// If true, do not place backedge safepoints in counted loops.
99 static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
101 // If true, split the backedge of a loop when placing the safepoint, otherwise
102 // split the latch block itself. Both are useful to support for
103 // experimentation, but in practice, it looks like splitting the backedge
105 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
108 // Print tracing output
109 static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
113 /** An analysis pass whose purpose is to identify each of the backedges in
114 the function which require a safepoint poll to be inserted. */
115 struct PlaceBackedgeSafepointsImpl : public LoopPass {
118 /// The output of the pass - gives a list of each backedge (described by
119 /// pointing at the branch) which need a poll inserted.
120 std::vector<TerminatorInst *> PollLocations;
122 /// True unless we're running spp-no-calls in which case we need to disable
123 /// the call dependend placement opts.
124 bool CallSafepointsEnabled;
125 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
126 : LoopPass(ID), CallSafepointsEnabled(CallSafepoints) {
127 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
130 bool runOnLoop(Loop *, LPPassManager &LPM) override;
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.addRequired<ScalarEvolution>();
134 // We no longer modify the IR at all in this pass. Thus all
135 // analysis are preserved.
136 AU.setPreservesAll();
141 static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
142 static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
143 static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
146 struct PlaceSafepoints : public ModulePass {
147 static char ID; // Pass identification, replacement for typeid
149 PlaceSafepoints() : ModulePass(ID) {
150 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
152 bool runOnModule(Module &M) override {
153 bool modified = false;
154 for (Function &F : M) {
155 modified |= runOnFunction(F);
159 bool runOnFunction(Function &F);
161 void getAnalysisUsage(AnalysisUsage &AU) const override {
162 // We modify the graph wholesale (inlining, block insertion, etc). We
163 // preserve nothing at the moment. We could potentially preserve dom tree
164 // if that was worth doing
169 // Insert a safepoint poll immediately before the given instruction. Does
170 // not handle the parsability of state at the runtime call, that's the
173 InsertSafepointPoll(DominatorTree &DT, Instruction *after,
174 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
176 static bool isGCLeafFunction(const CallSite &CS);
178 static bool needsStatepoint(const CallSite &CS) {
179 if (isGCLeafFunction(CS))
182 CallInst *call = cast<CallInst>(CS.getInstruction());
183 if (call->isInlineAsm())
186 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
192 static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
194 /// Returns true if this loop is known to contain a call safepoint which
195 /// must unconditionally execute on any iteration of the loop which returns
196 /// to the loop header via an edge from Pred. Returns a conservative correct
197 /// answer; i.e. false is always valid.
198 static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
201 // In general, we're looking for any cut of the graph which ensures
202 // there's a call safepoint along every edge between Header and Pred.
203 // For the moment, we look only for the 'cuts' that consist of a single call
204 // instruction in a block which is dominated by the Header and dominates the
205 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
206 // of such dominating blocks gets substaintially more occurences than just
207 // checking the Pred and Header blocks themselves. This may be due to the
208 // density of loop exit conditions caused by range and null checks.
209 // TODO: structure this as an analysis pass, cache the result for subloops,
210 // avoid dom tree recalculations
211 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
213 BasicBlock *Current = Pred;
215 for (Instruction &I : *Current) {
216 if (auto CS = CallSite(&I))
217 // Note: Technically, needing a safepoint isn't quite the right
218 // condition here. We should instead be checking if the target method
220 // unconditional poll. In practice, this is only a theoretical concern
221 // since we don't have any methods with conditional-only safepoint
223 if (needsStatepoint(CS))
227 if (Current == Header)
229 Current = DT.getNode(Current)->getIDom()->getBlock();
235 /// Returns true if this loop is known to terminate in a finite number of
236 /// iterations. Note that this function may return false for a loop which
237 /// does actual terminate in a finite constant number of iterations due to
238 /// conservatism in the analysis.
239 static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
241 // Only used when SkipCounted is off
242 const unsigned upperTripBound = 8192;
244 // A conservative bound on the loop as a whole.
245 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
246 if (MaxTrips != SE->getCouldNotCompute()) {
247 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
250 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
254 // If this is a conditional branch to the header with the alternate path
255 // being outside the loop, we can ask questions about the execution frequency
256 // of the exit block.
257 if (L->isLoopExiting(Pred)) {
258 // This returns an exact expression only. TODO: We really only need an
259 // upper bound here, but SE doesn't expose that.
260 const SCEV *MaxExec = SE->getExitCount(L, Pred);
261 if (MaxExec != SE->getCouldNotCompute()) {
262 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
265 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
270 return /* not finite */ false;
273 static void scanOneBB(Instruction *start, Instruction *end,
274 std::vector<CallInst *> &calls,
275 std::set<BasicBlock *> &seen,
276 std::vector<BasicBlock *> &worklist) {
277 for (BasicBlock::iterator itr(start);
278 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
280 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
283 // FIXME: This code does not handle invokes
284 assert(!dyn_cast<InvokeInst>(&*itr) &&
285 "support for invokes in poll code needed");
286 // Only add the successor blocks if we reach the terminator instruction
287 // without encountering end first
288 if (itr->isTerminator()) {
289 BasicBlock *BB = itr->getParent();
290 for (BasicBlock *Succ : successors(BB)) {
291 if (seen.count(Succ) == 0) {
292 worklist.push_back(Succ);
299 static void scanInlinedCode(Instruction *start, Instruction *end,
300 std::vector<CallInst *> &calls,
301 std::set<BasicBlock *> &seen) {
303 std::vector<BasicBlock *> worklist;
304 seen.insert(start->getParent());
305 scanOneBB(start, end, calls, seen, worklist);
306 while (!worklist.empty()) {
307 BasicBlock *BB = worklist.back();
309 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
313 bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L, LPPassManager &LPM) {
314 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
316 // Loop through all loop latches (branches controlling backedges). We need
317 // to place a safepoint on every backedge (potentially).
318 // Note: In common usage, there will be only one edge due to LoopSimplify
319 // having run sometime earlier in the pipeline, but this code must be correct
320 // w.r.t. loops with multiple backedges.
321 BasicBlock *header = L->getHeader();
323 // TODO: Use the analysis pass infrastructure for this. There is no reason
324 // to recalculate this here.
326 DT.recalculate(*header->getParent());
328 SmallVector<BasicBlock*, 16> LoopLatches;
329 L->getLoopLatches(LoopLatches);
330 for (BasicBlock *pred : LoopLatches) {
331 assert(L->contains(pred));
333 // Make a policy decision about whether this loop needs a safepoint or
334 // not. Note that this is about unburdening the optimizer in loops, not
335 // avoiding the runtime cost of the actual safepoint.
337 if (mustBeFiniteCountedLoop(L, SE, pred)) {
339 errs() << "skipping safepoint placement in finite loop\n";
343 if (CallSafepointsEnabled &&
344 containsUnconditionalCallSafepoint(L, header, pred, DT)) {
345 // Note: This is only semantically legal since we won't do any further
346 // IPO or inlining before the actual call insertion.. If we hadn't, we
347 // might latter loose this call safepoint.
349 errs() << "skipping safepoint placement due to unconditional call\n";
355 // TODO: We can create an inner loop which runs a finite number of
356 // iterations with an outer loop which contains a safepoint. This would
357 // not help runtime performance that much, but it might help our ability to
358 // optimize the inner loop.
360 // Safepoint insertion would involve creating a new basic block (as the
361 // target of the current backedge) which does the safepoint (of all live
362 // variables) and branches to the true header
363 TerminatorInst *term = pred->getTerminator();
366 errs() << "[LSP] terminator instruction: ";
370 PollLocations.push_back(term);
376 static Instruction *findLocationForEntrySafepoint(Function &F,
379 // Conceptually, this poll needs to be on method entry, but in
380 // practice, we place it as late in the entry block as possible. We
381 // can place it as late as we want as long as it dominates all calls
382 // that can grow the stack. This, combined with backedge polls,
383 // give us all the progress guarantees we need.
385 // Due to the way the frontend generates IR, we may have a couple of initial
386 // basic blocks before the first bytecode. These will be single-entry
387 // single-exit blocks which conceptually are just part of the first 'real
388 // basic block'. Since we don't have deopt state until the first bytecode,
389 // walk forward until we've found the first unconditional branch or merge.
391 // hasNextInstruction and nextInstruction are used to iterate
392 // through a "straight line" execution sequence.
394 auto hasNextInstruction = [](Instruction *I) {
395 if (!I->isTerminator()) {
398 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
399 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
402 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
403 assert(hasNextInstruction(I) &&
404 "first check if there is a next instruction!");
405 if (I->isTerminator()) {
406 return I->getParent()->getUniqueSuccessor()->begin();
408 return std::next(BasicBlock::iterator(I));
412 Instruction *cursor = nullptr;
413 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
414 cursor = nextInstruction(cursor)) {
416 // We need to stop going forward as soon as we see a call that can
417 // grow the stack (i.e. the call target has a non-zero frame
419 if (CallSite(cursor)) {
420 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) {
421 // llvm.assume(...) are not really calls.
422 if (II->getIntrinsicID() == Intrinsic::assume) {
425 // llvm.frameescape() intrinsic is not a real call. The intrinsic can
426 // exist only in the entry block.
427 // Inserting a statepoint before llvm.frameescape() may split the
428 // entry block, and push the intrinsic out of the entry block.
429 if (II->getIntrinsicID() == Intrinsic::frameescape) {
437 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
438 "either we stopped because of a call, or because of terminator");
440 if (cursor->isTerminator()) {
444 BasicBlock *BB = cursor->getParent();
445 SplitBlock(BB, cursor, nullptr);
447 // Note: SplitBlock modifies the DT. Simply passing a Pass (which is a
448 // module pass) is not enough.
451 // SplitBlock updates the DT
452 DEBUG(DT.verifyDomTree());
454 return BB->getTerminator();
457 /// Identify the list of call sites which need to be have parseable state
458 static void findCallSafepoints(Function &F,
459 std::vector<CallSite> &Found /*rval*/) {
460 assert(Found.empty() && "must be empty!");
461 for (Instruction &I : inst_range(F)) {
462 Instruction *inst = &I;
463 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
466 // No safepoint needed or wanted
467 if (!needsStatepoint(CS)) {
476 /// Implement a unique function which doesn't require we sort the input
477 /// vector. Doing so has the effect of changing the output of a couple of
478 /// tests in ways which make them less useful in testing fused safepoints.
479 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
482 vec.reserve(vec.size());
485 if (seen.insert(V).second) {
491 static std::string GCSafepointPollName("gc.safepoint_poll");
493 static bool isGCSafepointPoll(Function &F) {
494 return F.getName().equals(GCSafepointPollName);
497 /// Returns true if this function should be rewritten to include safepoint
498 /// polls and parseable call sites. The main point of this function is to be
499 /// an extension point for custom logic.
500 static bool shouldRewriteFunction(Function &F) {
501 // TODO: This should check the GCStrategy
503 const std::string StatepointExampleName("statepoint-example");
504 return StatepointExampleName == F.getGC();
509 // TODO: These should become properties of the GCStrategy, possibly with
510 // command line overrides.
511 static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
512 static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
513 static bool enableCallSafepoints(Function &F) { return !NoCall; }
515 // Normalize basic block to make it ready to be target of invoke statepoint.
516 // Ensure that 'BB' does not have phi nodes. It may require spliting it.
517 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
518 BasicBlock *InvokeParent) {
519 BasicBlock *ret = BB;
521 if (!BB->getUniquePredecessor()) {
522 ret = SplitBlockPredecessors(BB, InvokeParent, "");
525 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
527 FoldSingleEntryPHINodes(ret);
528 assert(!isa<PHINode>(ret->begin()));
533 bool PlaceSafepoints::runOnFunction(Function &F) {
534 if (F.isDeclaration() || F.empty()) {
535 // This is a declaration, nothing to do. Must exit early to avoid crash in
536 // dom tree calculation
540 if (isGCSafepointPoll(F)) {
541 // Given we're inlining this inside of safepoint poll insertion, this
542 // doesn't make any sense. Note that we do make any contained calls
543 // parseable after we inline a poll.
547 if (!shouldRewriteFunction(F))
550 bool modified = false;
552 // In various bits below, we rely on the fact that uses are reachable from
553 // defs. When there are basic blocks unreachable from the entry, dominance
554 // and reachablity queries return non-sensical results. Thus, we preprocess
555 // the function to ensure these properties hold.
556 modified |= removeUnreachableBlocks(F);
558 // STEP 1 - Insert the safepoint polling locations. We do not need to
559 // actually insert parse points yet. That will be done for all polls and
560 // calls in a single pass.
562 // Note: With the migration, we need to recompute this for each 'pass'. Once
563 // we merge these, we'll do it once before the analysis
566 std::vector<CallSite> ParsePointNeeded;
568 if (enableBackedgeSafepoints(F)) {
569 // Construct a pass manager to run the LoopPass backedge logic. We
570 // need the pass manager to handle scheduling all the loop passes
571 // appropriately. Doing this by hand is painful and just not worth messing
572 // with for the moment.
573 legacy::FunctionPassManager FPM(F.getParent());
574 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
575 PlaceBackedgeSafepointsImpl *PBS =
576 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
580 // We preserve dominance information when inserting the poll, otherwise
581 // we'd have to recalculate this on every insert
584 auto &PollLocations = PBS->PollLocations;
586 auto OrderByBBName = [](Instruction *a, Instruction *b) {
587 return a->getParent()->getName() < b->getParent()->getName();
589 // We need the order of list to be stable so that naming ends up stable
590 // when we split edges. This makes test cases much easier to write.
591 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
593 // We can sometimes end up with duplicate poll locations. This happens if
594 // a single loop is visited more than once. The fact this happens seems
595 // wrong, but it does happen for the split-backedge.ll test case.
596 PollLocations.erase(std::unique(PollLocations.begin(),
597 PollLocations.end()),
598 PollLocations.end());
600 // Insert a poll at each point the analysis pass identified
601 for (size_t i = 0; i < PollLocations.size(); i++) {
602 // We are inserting a poll, the function is modified
605 // The poll location must be the terminator of a loop latch block.
606 TerminatorInst *Term = PollLocations[i];
608 std::vector<CallSite> ParsePoints;
610 // Split the backedge of the loop and insert the poll within that new
611 // basic block. This creates a loop with two latches per original
612 // latch (which is non-ideal), but this appears to be easier to
613 // optimize in practice than inserting the poll immediately before the
616 // Since this is a latch, at least one of the successors must dominate
617 // it. Its possible that we have a) duplicate edges to the same header
618 // and b) edges to distinct loop headers. We need to insert pools on
620 SetVector<BasicBlock *> Headers;
621 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
622 BasicBlock *Succ = Term->getSuccessor(i);
623 if (DT.dominates(Succ, Term->getParent())) {
624 Headers.insert(Succ);
627 assert(!Headers.empty() && "poll location is not a loop latch?");
629 // The split loop structure here is so that we only need to recalculate
630 // the dominator tree once. Alternatively, we could just keep it up to
631 // date and use a more natural merged loop.
632 SetVector<BasicBlock *> SplitBackedges;
633 for (BasicBlock *Header : Headers) {
634 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, nullptr);
635 SplitBackedges.insert(NewBB);
638 for (BasicBlock *NewBB : SplitBackedges) {
639 std::vector<CallSite> RuntimeCalls;
640 InsertSafepointPoll(DT, NewBB->getTerminator(), RuntimeCalls);
641 NumBackedgeSafepoints++;
642 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
647 // Split the latch block itself, right before the terminator.
648 std::vector<CallSite> RuntimeCalls;
649 InsertSafepointPoll(DT, Term, RuntimeCalls);
650 NumBackedgeSafepoints++;
651 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
655 // Record the parse points for later use
656 ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
661 if (enableEntrySafepoints(F)) {
663 Instruction *term = findLocationForEntrySafepoint(F, DT);
665 // policy choice not to insert?
667 std::vector<CallSite> RuntimeCalls;
668 InsertSafepointPoll(DT, term, RuntimeCalls);
670 NumEntrySafepoints++;
671 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
676 if (enableCallSafepoints(F)) {
678 std::vector<CallSite> Calls;
679 findCallSafepoints(F, Calls);
680 NumCallSafepoints += Calls.size();
681 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
684 // Unique the vectors since we can end up with duplicates if we scan the call
685 // site for call safepoints after we add it for entry or backedge. The
686 // only reason we need tracking at all is that some functions might have
687 // polls but not call safepoints and thus we might miss marking the runtime
688 // calls for the polls. (This is useful in test cases!)
689 unique_unsorted(ParsePointNeeded);
691 // Any parse point (no matter what source) will be handled here
692 DT.recalculate(F); // Needed?
694 // We're about to start modifying the function
695 if (!ParsePointNeeded.empty())
698 // Now run through and insert the safepoints, but do _NOT_ update or remove
699 // any existing uses. We have references to live variables that need to
700 // survive to the last iteration of this loop.
701 std::vector<Value *> Results;
702 Results.reserve(ParsePointNeeded.size());
703 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
704 CallSite &CS = ParsePointNeeded[i];
706 // For invoke statepoints we need to remove all phi nodes at the normal
707 // destination block.
708 // Reason for this is that we can place gc_result only after last phi node
709 // in basic block. We will get malformed code after RAUW for the
710 // gc_result if one of this phi nodes uses result from the invoke.
711 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
712 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
713 Invoke->getParent());
716 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
717 Results.push_back(GCResult);
719 assert(Results.size() == ParsePointNeeded.size());
721 // Adjust all users of the old call sites to use the new ones instead
722 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
723 CallSite &CS = ParsePointNeeded[i];
724 Value *GCResult = Results[i];
726 // Can not RAUW for the gc result in case of phi nodes preset.
727 assert(!isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
729 // Replace all uses with the new call
730 CS.getInstruction()->replaceAllUsesWith(GCResult);
733 // Now that we've handled all uses, remove the original call itself
734 // Note: The insert point can't be the deleted instruction!
735 CS.getInstruction()->eraseFromParent();
740 char PlaceBackedgeSafepointsImpl::ID = 0;
741 char PlaceSafepoints::ID = 0;
743 ModulePass *llvm::createPlaceSafepointsPass() { return new PlaceSafepoints(); }
745 INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
746 "place-backedge-safepoints-impl",
747 "Place Backedge Safepoints", false, false)
748 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
749 INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
750 "place-backedge-safepoints-impl",
751 "Place Backedge Safepoints", false, false)
753 INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
755 INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
758 static bool isGCLeafFunction(const CallSite &CS) {
759 Instruction *inst = CS.getInstruction();
760 if (isa<IntrinsicInst>(inst)) {
761 // Most LLVM intrinsics are things which can never take a safepoint.
762 // As a result, we don't need to have the stack parsable at the
763 // callsite. This is a highly useful optimization since intrinsic
764 // calls are fairly prevelent, particularly in debug builds.
768 // If this function is marked explicitly as a leaf call, we don't need to
769 // place a safepoint of it. In fact, for correctness we *can't* in many
770 // cases. Note: Indirect calls return Null for the called function,
771 // these obviously aren't runtime functions with attributes
772 // TODO: Support attributes on the call site as well.
773 const Function *F = CS.getCalledFunction();
776 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
784 InsertSafepointPoll(DominatorTree &DT, Instruction *term,
785 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
786 Module *M = term->getParent()->getParent()->getParent();
789 // Inline the safepoint poll implementation - this will get all the branch,
790 // control flow, etc.. Most importantly, it will introduce the actual slow
791 // path call - where we need to insert a safepoint (parsepoint).
792 FunctionType *ftype =
793 FunctionType::get(Type::getVoidTy(M->getContext()), false);
794 assert(ftype && "null?");
795 // Note: This cast can fail if there's a function of the same name with a
796 // different type inserted previously
798 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
799 assert(F && "void @gc.safepoint_poll() must be defined");
800 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
801 CallInst *poll = CallInst::Create(F, "", term);
803 // Record some information about the call site we're replacing
804 BasicBlock *OrigBB = term->getParent();
805 BasicBlock::iterator before(poll), after(poll);
807 if (before == term->getParent()->begin()) {
813 assert(after != poll->getParent()->end() && "must have successor");
814 assert(DT.dominates(before, after) && "trivially true");
816 // do the actual inlining
817 InlineFunctionInfo IFI;
818 bool inlineStatus = InlineFunction(poll, IFI);
819 assert(inlineStatus && "inline must succeed");
820 (void)inlineStatus; // suppress warning in release-asserts
822 // Check post conditions
823 assert(IFI.StaticAllocas.empty() && "can't have allocs");
825 std::vector<CallInst *> calls; // new calls
826 std::set<BasicBlock *> BBs; // new BBs + insertee
827 // Include only the newly inserted instructions, Note: begin may not be valid
828 // if we inserted to the beginning of the basic block
829 BasicBlock::iterator start;
831 start = OrigBB->begin();
837 // If your poll function includes an unreachable at the end, that's not
838 // valid. Bugpoint likes to create this, so check for it.
839 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
840 "malformed poll function");
842 scanInlinedCode(&*(start), &*(after), calls, BBs);
844 // Recompute since we've invalidated cached data. Conceptually we
845 // shouldn't need to do this, but implementation wise we appear to. Needed
846 // so we can insert safepoints correctly.
847 // TODO: update more cheaply
848 DT.recalculate(*after->getParent()->getParent());
850 assert(!calls.empty() && "slow path not found for safepoint poll");
852 // Record the fact we need a parsable state at the runtime call contained in
853 // the poll function. This is required so that the runtime knows how to
854 // parse the last frame when we actually take the safepoint (i.e. execute
856 assert(ParsePointsNeeded.empty());
857 for (size_t i = 0; i < calls.size(); i++) {
859 // No safepoint needed or wanted
860 if (!needsStatepoint(calls[i])) {
864 // These are likely runtime calls. Should we assert that via calling
865 // convention or something?
866 ParsePointsNeeded.push_back(CallSite(calls[i]));
868 assert(ParsePointsNeeded.size() <= calls.size());
871 /// Replaces the given call site (Call or Invoke) with a gc.statepoint
872 /// intrinsic with an empty deoptimization arguments list. This does
873 /// NOT do explicit relocation for GC support.
874 static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
876 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
879 // TODO: technically, a pass is not allowed to get functions from within a
880 // function pass since it might trigger a new function addition. Refactor
881 // this logic out to the initialization of the pass. Doesn't appear to
882 // matter in practice.
884 // Then go ahead and use the builder do actually do the inserts. We insert
885 // immediately before the previous instruction under the assumption that all
886 // arguments will be available here. We can't insert afterwards since we may
887 // be replacing a terminator.
888 IRBuilder<> Builder(CS.getInstruction());
890 // Note: The gc args are not filled in at this time, that's handled by
891 // RewriteStatepointsForGC (which is currently under review).
893 // Create the statepoint given all the arguments
894 Instruction *Token = nullptr;
895 AttributeSet OriginalAttrs;
898 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
899 CallInst *Call = Builder.CreateGCStatepointCall(
900 CS.getCalledValue(), makeArrayRef(CS.arg_begin(), CS.arg_end()), None,
901 None, "safepoint_token");
902 Call->setTailCall(ToReplace->isTailCall());
903 Call->setCallingConv(ToReplace->getCallingConv());
905 // Before we have to worry about GC semantics, all attributes are legal
906 // TODO: handle param attributes
907 OriginalAttrs = ToReplace->getAttributes();
909 // In case if we can handle this set of attributes - set up function
910 // attributes directly on statepoint and return attributes later for
911 // gc_result intrinsic.
912 Call->setAttributes(OriginalAttrs.getFnAttributes());
916 // Put the following gc_result and gc_relocate calls immediately after the
917 // the old call (which we're about to delete).
918 assert(ToReplace->getNextNode() && "not a terminator, must have next");
919 Builder.SetInsertPoint(ToReplace->getNextNode());
920 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
921 } else if (CS.isInvoke()) {
922 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
924 // Insert the new invoke into the old block. We'll remove the old one in a
925 // moment at which point this will become the new terminator for the
927 Builder.SetInsertPoint(ToReplace->getParent());
928 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
929 CS.getCalledValue(), ToReplace->getNormalDest(),
930 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
931 Builder.getInt32(0), None, "safepoint_token");
933 // Currently we will fail on parameter attributes and on certain
934 // function attributes.
935 OriginalAttrs = ToReplace->getAttributes();
937 // In case if we can handle this set of attributes - set up function
938 // attributes directly on statepoint and return attributes later for
939 // gc_result intrinsic.
940 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
944 // We'll insert the gc.result into the normal block
945 BasicBlock *NormalDest = ToReplace->getNormalDest();
946 // Can not insert gc.result in case of phi nodes preset.
947 // Should have removed this cases prior to runnning this function
948 assert(!isa<PHINode>(NormalDest->begin()));
949 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
950 Builder.SetInsertPoint(IP);
952 llvm_unreachable("unexpect type of CallSite");
956 // Handle the return value of the original call - update all uses to use a
957 // gc_result hanging off the statepoint node we just inserted
959 // Only add the gc_result iff there is actually a used result
960 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
961 std::string TakenName =
962 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
963 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
964 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
967 // No return value for the call.