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/ADT/StringRef.h"
57 #include "llvm/Analysis/LoopPass.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/ScalarEvolution.h"
60 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
61 #include "llvm/Analysis/CFG.h"
62 #include "llvm/Analysis/InstructionSimplify.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CallSite.h"
65 #include "llvm/IR/Dominators.h"
66 #include "llvm/IR/Function.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/InstIterator.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/IR/Intrinsics.h"
71 #include "llvm/IR/IntrinsicInst.h"
72 #include "llvm/IR/Module.h"
73 #include "llvm/IR/Statepoint.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/Support/Debug.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Transforms/Scalar.h"
80 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
81 #include "llvm/Transforms/Utils/Cloning.h"
82 #include "llvm/Transforms/Utils/Local.h"
84 #define DEBUG_TYPE "safepoint-placement"
85 STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
86 STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
87 STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
89 STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
90 STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
94 // Ignore oppurtunities to avoid placing safepoints on backedges, useful for
96 static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
99 /// If true, do not place backedge safepoints in counted loops.
100 static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
102 // If true, split the backedge of a loop when placing the safepoint, otherwise
103 // split the latch block itself. Both are useful to support for
104 // experimentation, but in practice, it looks like splitting the backedge
106 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
109 // Print tracing output
110 static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
114 /// An analysis pass whose purpose is to identify each of the backedges in
115 /// the function which require a safepoint poll to be inserted.
116 struct PlaceBackedgeSafepointsImpl : public FunctionPass {
119 /// The output of the pass - gives a list of each backedge (described by
120 /// pointing at the branch) which need a poll inserted.
121 std::vector<TerminatorInst *> PollLocations;
123 /// True unless we're running spp-no-calls in which case we need to disable
124 /// the call dependend placement opts.
125 bool CallSafepointsEnabled;
127 ScalarEvolution *SE = nullptr;
128 DominatorTree *DT = nullptr;
129 LoopInfo *LI = nullptr;
131 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
132 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
133 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
136 bool runOnLoop(Loop *);
137 void runOnLoopAndSubLoops(Loop *L) {
138 // Visit all the subloops
139 for (auto I = L->begin(), E = L->end(); I != E; I++)
140 runOnLoopAndSubLoops(*I);
144 bool runOnFunction(Function &F) override {
145 SE = &getAnalysis<ScalarEvolution>();
146 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
147 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
148 for (auto I = LI->begin(), E = LI->end(); I != E; I++) {
149 runOnLoopAndSubLoops(*I);
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.addRequired<DominatorTreeWrapperPass>();
156 AU.addRequired<ScalarEvolution>();
157 AU.addRequired<LoopInfoWrapperPass>();
158 // We no longer modify the IR at all in this pass. Thus all
159 // analysis are preserved.
160 AU.setPreservesAll();
165 static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
166 static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
167 static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
170 struct PlaceSafepoints : public FunctionPass {
171 static char ID; // Pass identification, replacement for typeid
173 PlaceSafepoints() : FunctionPass(ID) {
174 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
176 bool runOnFunction(Function &F) override;
178 void getAnalysisUsage(AnalysisUsage &AU) const override {
179 // We modify the graph wholesale (inlining, block insertion, etc). We
180 // preserve nothing at the moment. We could potentially preserve dom tree
181 // if that was worth doing
186 // Insert a safepoint poll immediately before the given instruction. Does
187 // not handle the parsability of state at the runtime call, that's the
190 InsertSafepointPoll(Instruction *InsertBefore,
191 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
193 static bool isGCLeafFunction(const CallSite &CS);
195 static bool needsStatepoint(const CallSite &CS) {
196 if (isGCLeafFunction(CS))
199 CallInst *call = cast<CallInst>(CS.getInstruction());
200 if (call->isInlineAsm())
203 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
209 static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
211 /// Returns true if this loop is known to contain a call safepoint which
212 /// must unconditionally execute on any iteration of the loop which returns
213 /// to the loop header via an edge from Pred. Returns a conservative correct
214 /// answer; i.e. false is always valid.
215 static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
218 // In general, we're looking for any cut of the graph which ensures
219 // there's a call safepoint along every edge between Header and Pred.
220 // For the moment, we look only for the 'cuts' that consist of a single call
221 // instruction in a block which is dominated by the Header and dominates the
222 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
223 // of such dominating blocks gets substaintially more occurences than just
224 // checking the Pred and Header blocks themselves. This may be due to the
225 // density of loop exit conditions caused by range and null checks.
226 // TODO: structure this as an analysis pass, cache the result for subloops,
227 // avoid dom tree recalculations
228 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
230 BasicBlock *Current = Pred;
232 for (Instruction &I : *Current) {
233 if (auto CS = CallSite(&I))
234 // Note: Technically, needing a safepoint isn't quite the right
235 // condition here. We should instead be checking if the target method
237 // unconditional poll. In practice, this is only a theoretical concern
238 // since we don't have any methods with conditional-only safepoint
240 if (needsStatepoint(CS))
244 if (Current == Header)
246 Current = DT.getNode(Current)->getIDom()->getBlock();
252 /// Returns true if this loop is known to terminate in a finite number of
253 /// iterations. Note that this function may return false for a loop which
254 /// does actual terminate in a finite constant number of iterations due to
255 /// conservatism in the analysis.
256 static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
258 // Only used when SkipCounted is off
259 const unsigned upperTripBound = 8192;
261 // A conservative bound on the loop as a whole.
262 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
263 if (MaxTrips != SE->getCouldNotCompute()) {
264 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
267 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
271 // If this is a conditional branch to the header with the alternate path
272 // being outside the loop, we can ask questions about the execution frequency
273 // of the exit block.
274 if (L->isLoopExiting(Pred)) {
275 // This returns an exact expression only. TODO: We really only need an
276 // upper bound here, but SE doesn't expose that.
277 const SCEV *MaxExec = SE->getExitCount(L, Pred);
278 if (MaxExec != SE->getCouldNotCompute()) {
279 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
282 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
287 return /* not finite */ false;
290 static void scanOneBB(Instruction *start, Instruction *end,
291 std::vector<CallInst *> &calls,
292 std::set<BasicBlock *> &seen,
293 std::vector<BasicBlock *> &worklist) {
294 for (BasicBlock::iterator itr(start);
295 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
297 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
300 // FIXME: This code does not handle invokes
301 assert(!dyn_cast<InvokeInst>(&*itr) &&
302 "support for invokes in poll code needed");
303 // Only add the successor blocks if we reach the terminator instruction
304 // without encountering end first
305 if (itr->isTerminator()) {
306 BasicBlock *BB = itr->getParent();
307 for (BasicBlock *Succ : successors(BB)) {
308 if (seen.count(Succ) == 0) {
309 worklist.push_back(Succ);
316 static void scanInlinedCode(Instruction *start, Instruction *end,
317 std::vector<CallInst *> &calls,
318 std::set<BasicBlock *> &seen) {
320 std::vector<BasicBlock *> worklist;
321 seen.insert(start->getParent());
322 scanOneBB(start, end, calls, seen, worklist);
323 while (!worklist.empty()) {
324 BasicBlock *BB = worklist.back();
326 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
330 bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
331 // Loop through all loop latches (branches controlling backedges). We need
332 // to place a safepoint on every backedge (potentially).
333 // Note: In common usage, there will be only one edge due to LoopSimplify
334 // having run sometime earlier in the pipeline, but this code must be correct
335 // w.r.t. loops with multiple backedges.
336 BasicBlock *header = L->getHeader();
337 SmallVector<BasicBlock*, 16> LoopLatches;
338 L->getLoopLatches(LoopLatches);
339 for (BasicBlock *pred : LoopLatches) {
340 assert(L->contains(pred));
342 // Make a policy decision about whether this loop needs a safepoint or
343 // not. Note that this is about unburdening the optimizer in loops, not
344 // avoiding the runtime cost of the actual safepoint.
346 if (mustBeFiniteCountedLoop(L, SE, pred)) {
348 errs() << "skipping safepoint placement in finite loop\n";
352 if (CallSafepointsEnabled &&
353 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
354 // Note: This is only semantically legal since we won't do any further
355 // IPO or inlining before the actual call insertion.. If we hadn't, we
356 // might latter loose this call safepoint.
358 errs() << "skipping safepoint placement due to unconditional call\n";
364 // TODO: We can create an inner loop which runs a finite number of
365 // iterations with an outer loop which contains a safepoint. This would
366 // not help runtime performance that much, but it might help our ability to
367 // optimize the inner loop.
369 // Safepoint insertion would involve creating a new basic block (as the
370 // target of the current backedge) which does the safepoint (of all live
371 // variables) and branches to the true header
372 TerminatorInst *term = pred->getTerminator();
375 errs() << "[LSP] terminator instruction: ";
379 PollLocations.push_back(term);
385 /// Returns true if an entry safepoint is not required before this callsite in
386 /// the caller function.
387 static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
388 Instruction *Inst = CS.getInstruction();
389 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
390 switch (II->getIntrinsicID()) {
391 case Intrinsic::experimental_gc_statepoint:
392 case Intrinsic::experimental_patchpoint_void:
393 case Intrinsic::experimental_patchpoint_i64:
394 // The can wrap an actual call which may grow the stack by an unbounded
395 // amount or run forever.
398 // Most LLVM intrinsics are things which do not expand to actual calls, or
399 // at least if they do, are leaf functions that cause only finite stack
400 // growth. In particular, the optimizer likes to form things like memsets
401 // out of stores in the original IR. Another important example is
402 // llvm.frameescape which must occur in the entry block. Inserting a
403 // safepoint before it is not legal since it could push the frameescape
404 // out of the entry block.
411 static Instruction *findLocationForEntrySafepoint(Function &F,
414 // Conceptually, this poll needs to be on method entry, but in
415 // practice, we place it as late in the entry block as possible. We
416 // can place it as late as we want as long as it dominates all calls
417 // that can grow the stack. This, combined with backedge polls,
418 // give us all the progress guarantees we need.
420 // hasNextInstruction and nextInstruction are used to iterate
421 // through a "straight line" execution sequence.
423 auto hasNextInstruction = [](Instruction *I) {
424 if (!I->isTerminator()) {
427 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
428 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
431 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
432 assert(hasNextInstruction(I) &&
433 "first check if there is a next instruction!");
434 if (I->isTerminator()) {
435 return I->getParent()->getUniqueSuccessor()->begin();
437 return std::next(BasicBlock::iterator(I));
441 Instruction *cursor = nullptr;
442 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
443 cursor = nextInstruction(cursor)) {
445 // We need to ensure a safepoint poll occurs before any 'real' call. The
446 // easiest way to ensure finite execution between safepoints in the face of
447 // recursive and mutually recursive functions is to enforce that each take
448 // a safepoint. Additionally, we need to ensure a poll before any call
449 // which can grow the stack by an unbounded amount. This isn't required
450 // for GC semantics per se, but is a common requirement for languages
451 // which detect stack overflow via guard pages and then throw exceptions.
452 if (auto CS = CallSite(cursor)) {
453 if (doesNotRequireEntrySafepointBefore(CS))
459 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
460 "either we stopped because of a call, or because of terminator");
465 /// Identify the list of call sites which need to be have parseable state
466 static void findCallSafepoints(Function &F,
467 std::vector<CallSite> &Found /*rval*/) {
468 assert(Found.empty() && "must be empty!");
469 for (Instruction &I : inst_range(F)) {
470 Instruction *inst = &I;
471 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
474 // No safepoint needed or wanted
475 if (!needsStatepoint(CS)) {
484 /// Implement a unique function which doesn't require we sort the input
485 /// vector. Doing so has the effect of changing the output of a couple of
486 /// tests in ways which make them less useful in testing fused safepoints.
487 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
490 vec.reserve(vec.size());
493 if (seen.insert(V).second) {
499 static const char *const GCSafepointPollName = "gc.safepoint_poll";
501 static bool isGCSafepointPoll(Function &F) {
502 return F.getName().equals(GCSafepointPollName);
505 /// Returns true if this function should be rewritten to include safepoint
506 /// polls and parseable call sites. The main point of this function is to be
507 /// an extension point for custom logic.
508 static bool shouldRewriteFunction(Function &F) {
509 // TODO: This should check the GCStrategy
511 const char *FunctionGCName = F.getGC();
512 const StringRef StatepointExampleName("statepoint-example");
513 const StringRef CoreCLRName("coreclr");
514 return (StatepointExampleName == FunctionGCName) ||
515 (CoreCLRName == FunctionGCName);
520 // TODO: These should become properties of the GCStrategy, possibly with
521 // command line overrides.
522 static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
523 static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
524 static bool enableCallSafepoints(Function &F) { return !NoCall; }
526 // Normalize basic block to make it ready to be target of invoke statepoint.
527 // Ensure that 'BB' does not have phi nodes. It may require spliting it.
528 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
529 BasicBlock *InvokeParent) {
530 BasicBlock *ret = BB;
532 if (!BB->getUniquePredecessor()) {
533 ret = SplitBlockPredecessors(BB, InvokeParent, "");
536 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
538 FoldSingleEntryPHINodes(ret);
539 assert(!isa<PHINode>(ret->begin()));
544 bool PlaceSafepoints::runOnFunction(Function &F) {
545 if (F.isDeclaration() || F.empty()) {
546 // This is a declaration, nothing to do. Must exit early to avoid crash in
547 // dom tree calculation
551 if (isGCSafepointPoll(F)) {
552 // Given we're inlining this inside of safepoint poll insertion, this
553 // doesn't make any sense. Note that we do make any contained calls
554 // parseable after we inline a poll.
558 if (!shouldRewriteFunction(F))
561 bool modified = false;
563 // In various bits below, we rely on the fact that uses are reachable from
564 // defs. When there are basic blocks unreachable from the entry, dominance
565 // and reachablity queries return non-sensical results. Thus, we preprocess
566 // the function to ensure these properties hold.
567 modified |= removeUnreachableBlocks(F);
569 // STEP 1 - Insert the safepoint polling locations. We do not need to
570 // actually insert parse points yet. That will be done for all polls and
571 // calls in a single pass.
576 SmallVector<Instruction *, 16> PollsNeeded;
577 std::vector<CallSite> ParsePointNeeded;
579 if (enableBackedgeSafepoints(F)) {
580 // Construct a pass manager to run the LoopPass backedge logic. We
581 // need the pass manager to handle scheduling all the loop passes
582 // appropriately. Doing this by hand is painful and just not worth messing
583 // with for the moment.
584 legacy::FunctionPassManager FPM(F.getParent());
585 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
586 PlaceBackedgeSafepointsImpl *PBS =
587 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
591 // We preserve dominance information when inserting the poll, otherwise
592 // we'd have to recalculate this on every insert
595 auto &PollLocations = PBS->PollLocations;
597 auto OrderByBBName = [](Instruction *a, Instruction *b) {
598 return a->getParent()->getName() < b->getParent()->getName();
600 // We need the order of list to be stable so that naming ends up stable
601 // when we split edges. This makes test cases much easier to write.
602 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
604 // We can sometimes end up with duplicate poll locations. This happens if
605 // a single loop is visited more than once. The fact this happens seems
606 // wrong, but it does happen for the split-backedge.ll test case.
607 PollLocations.erase(std::unique(PollLocations.begin(),
608 PollLocations.end()),
609 PollLocations.end());
611 // Insert a poll at each point the analysis pass identified
612 // The poll location must be the terminator of a loop latch block.
613 for (TerminatorInst *Term : PollLocations) {
614 // We are inserting a poll, the function is modified
618 // Split the backedge of the loop and insert the poll within that new
619 // basic block. This creates a loop with two latches per original
620 // latch (which is non-ideal), but this appears to be easier to
621 // optimize in practice than inserting the poll immediately before the
624 // Since this is a latch, at least one of the successors must dominate
625 // it. Its possible that we have a) duplicate edges to the same header
626 // and b) edges to distinct loop headers. We need to insert pools on
628 SetVector<BasicBlock *> Headers;
629 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
630 BasicBlock *Succ = Term->getSuccessor(i);
631 if (DT.dominates(Succ, Term->getParent())) {
632 Headers.insert(Succ);
635 assert(!Headers.empty() && "poll location is not a loop latch?");
637 // The split loop structure here is so that we only need to recalculate
638 // the dominator tree once. Alternatively, we could just keep it up to
639 // date and use a more natural merged loop.
640 SetVector<BasicBlock *> SplitBackedges;
641 for (BasicBlock *Header : Headers) {
642 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
643 PollsNeeded.push_back(NewBB->getTerminator());
644 NumBackedgeSafepoints++;
647 // Split the latch block itself, right before the terminator.
648 PollsNeeded.push_back(Term);
649 NumBackedgeSafepoints++;
654 if (enableEntrySafepoints(F)) {
655 Instruction *Location = findLocationForEntrySafepoint(F, DT);
657 // policy choice not to insert?
659 PollsNeeded.push_back(Location);
661 NumEntrySafepoints++;
665 // Now that we've identified all the needed safepoint poll locations, insert
666 // safepoint polls themselves.
667 for (Instruction *PollLocation : PollsNeeded) {
668 std::vector<CallSite> RuntimeCalls;
669 InsertSafepointPoll(PollLocation, RuntimeCalls);
670 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
673 PollsNeeded.clear(); // make sure we don't accidentally use
674 // The dominator tree has been invalidated by the inlining performed in the
675 // above loop. TODO: Teach the inliner how to update the dom tree?
678 if (enableCallSafepoints(F)) {
679 std::vector<CallSite> Calls;
680 findCallSafepoints(F, Calls);
681 NumCallSafepoints += Calls.size();
682 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
685 // Unique the vectors since we can end up with duplicates if we scan the call
686 // site for call safepoints after we add it for entry or backedge. The
687 // only reason we need tracking at all is that some functions might have
688 // polls but not call safepoints and thus we might miss marking the runtime
689 // calls for the polls. (This is useful in test cases!)
690 unique_unsorted(ParsePointNeeded);
692 // Any parse point (no matter what source) will be handled here
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 invoke gc result in case of phi nodes preset.
727 assert(CS.isCall() || !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 FunctionPass *llvm::createPlaceSafepointsPass() {
744 return new PlaceSafepoints();
747 INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
748 "place-backedge-safepoints-impl",
749 "Place Backedge Safepoints", false, false)
750 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
751 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
752 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
753 INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
754 "place-backedge-safepoints-impl",
755 "Place Backedge Safepoints", false, false)
757 INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
759 INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
762 static bool isGCLeafFunction(const CallSite &CS) {
763 Instruction *inst = CS.getInstruction();
764 if (isa<IntrinsicInst>(inst)) {
765 // Most LLVM intrinsics are things which can never take a safepoint.
766 // As a result, we don't need to have the stack parsable at the
767 // callsite. This is a highly useful optimization since intrinsic
768 // calls are fairly prevelent, particularly in debug builds.
772 // If this function is marked explicitly as a leaf call, we don't need to
773 // place a safepoint of it. In fact, for correctness we *can't* in many
774 // cases. Note: Indirect calls return Null for the called function,
775 // these obviously aren't runtime functions with attributes
776 // TODO: Support attributes on the call site as well.
777 const Function *F = CS.getCalledFunction();
780 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
788 InsertSafepointPoll(Instruction *InsertBefore,
789 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
790 BasicBlock *OrigBB = InsertBefore->getParent();
791 Module *M = InsertBefore->getModule();
792 assert(M && "must be part of a module");
794 // Inline the safepoint poll implementation - this will get all the branch,
795 // control flow, etc.. Most importantly, it will introduce the actual slow
796 // path call - where we need to insert a safepoint (parsepoint).
798 auto *F = M->getFunction(GCSafepointPollName);
799 assert(F->getType()->getElementType() ==
800 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
801 "gc.safepoint_poll declared with wrong type");
802 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
803 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
805 // Record some information about the call site we're replacing
806 BasicBlock::iterator before(PollCall), after(PollCall);
808 if (before == OrigBB->begin()) {
814 assert(after != OrigBB->end() && "must have successor");
816 // do the actual inlining
817 InlineFunctionInfo IFI;
818 bool InlineStatus = InlineFunction(PollCall, 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);
843 assert(!calls.empty() && "slow path not found for safepoint poll");
845 // Record the fact we need a parsable state at the runtime call contained in
846 // the poll function. This is required so that the runtime knows how to
847 // parse the last frame when we actually take the safepoint (i.e. execute
849 assert(ParsePointsNeeded.empty());
850 for (size_t i = 0; i < calls.size(); i++) {
852 // No safepoint needed or wanted
853 if (!needsStatepoint(calls[i])) {
857 // These are likely runtime calls. Should we assert that via calling
858 // convention or something?
859 ParsePointsNeeded.push_back(CallSite(calls[i]));
861 assert(ParsePointsNeeded.size() <= calls.size());
864 /// Replaces the given call site (Call or Invoke) with a gc.statepoint
865 /// intrinsic with an empty deoptimization arguments list. This does
866 /// NOT do explicit relocation for GC support.
867 static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
869 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
872 // TODO: technically, a pass is not allowed to get functions from within a
873 // function pass since it might trigger a new function addition. Refactor
874 // this logic out to the initialization of the pass. Doesn't appear to
875 // matter in practice.
877 // Then go ahead and use the builder do actually do the inserts. We insert
878 // immediately before the previous instruction under the assumption that all
879 // arguments will be available here. We can't insert afterwards since we may
880 // be replacing a terminator.
881 IRBuilder<> Builder(CS.getInstruction());
883 // Note: The gc args are not filled in at this time, that's handled by
884 // RewriteStatepointsForGC (which is currently under review).
886 // Create the statepoint given all the arguments
887 Instruction *Token = nullptr;
890 uint32_t NumPatchBytes;
892 AttributeSet OriginalAttrs = CS.getAttributes();
894 OriginalAttrs.getAttribute(AttributeSet::FunctionIndex, "statepoint-id");
895 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
896 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
898 AttrBuilder AttrsToRemove;
899 bool HasID = AttrID.isStringAttribute() &&
900 !AttrID.getValueAsString().getAsInteger(10, ID);
903 AttrsToRemove.addAttribute("statepoint-id");
907 bool HasNumPatchBytes =
908 AttrNumPatchBytes.isStringAttribute() &&
909 !AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
911 if (HasNumPatchBytes)
912 AttrsToRemove.addAttribute("statepoint-num-patch-bytes");
916 OriginalAttrs = OriginalAttrs.removeAttributes(
917 CS.getInstruction()->getContext(), AttributeSet::FunctionIndex,
920 Value *StatepointTarget = NumPatchBytes == 0
921 ? CS.getCalledValue()
922 : ConstantPointerNull::get(cast<PointerType>(
923 CS.getCalledValue()->getType()));
926 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
927 CallInst *Call = Builder.CreateGCStatepointCall(
928 ID, NumPatchBytes, StatepointTarget,
929 makeArrayRef(CS.arg_begin(), CS.arg_end()), None, None,
931 Call->setTailCall(ToReplace->isTailCall());
932 Call->setCallingConv(ToReplace->getCallingConv());
934 // In case if we can handle this set of attributes - set up function
935 // attributes directly on statepoint and return attributes later for
936 // gc_result intrinsic.
937 Call->setAttributes(OriginalAttrs.getFnAttributes());
941 // Put the following gc_result and gc_relocate calls immediately after the
942 // the old call (which we're about to delete).
943 assert(ToReplace->getNextNode() && "not a terminator, must have next");
944 Builder.SetInsertPoint(ToReplace->getNextNode());
945 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
946 } else if (CS.isInvoke()) {
947 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
949 // Insert the new invoke into the old block. We'll remove the old one in a
950 // moment at which point this will become the new terminator for the
952 Builder.SetInsertPoint(ToReplace->getParent());
953 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
954 ID, NumPatchBytes, StatepointTarget, ToReplace->getNormalDest(),
955 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
956 None, None, "safepoint_token");
958 Invoke->setCallingConv(ToReplace->getCallingConv());
960 // In case if we can handle this set of attributes - set up function
961 // attributes directly on statepoint and return attributes later for
962 // gc_result intrinsic.
963 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
967 // We'll insert the gc.result into the normal block
968 BasicBlock *NormalDest = ToReplace->getNormalDest();
969 // Can not insert gc.result in case of phi nodes preset.
970 // Should have removed this cases prior to runnning this function
971 assert(!isa<PHINode>(NormalDest->begin()));
972 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
973 Builder.SetInsertPoint(IP);
975 llvm_unreachable("unexpect type of CallSite");
979 // Handle the return value of the original call - update all uses to use a
980 // gc_result hanging off the statepoint node we just inserted
982 // Only add the gc_result iff there is actually a used result
983 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
984 std::string TakenName =
985 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
986 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
987 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
990 // No return value for the call.