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/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"
82 #define DEBUG_TYPE "safepoint-placement"
83 STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
84 STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
85 STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
87 STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
88 STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
92 // Ignore oppurtunities to avoid placing safepoints on backedges, useful for
94 static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
97 /// If true, do not place backedge safepoints in counted loops.
98 static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
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
104 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
107 // Print tracing output
108 static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
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. */
114 struct PlaceBackedgeSafepointsImpl : public LoopPass {
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;
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) {
126 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
129 bool runOnLoop(Loop *, LPPassManager &LPM) override;
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);
138 // We no longer modify the IR at all in this pass. Thus all
139 // analysis are preserved.
140 AU.setPreservesAll();
145 static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
146 static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
147 static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
150 struct PlaceSafepoints : public ModulePass {
151 static char ID; // Pass identification, replacement for typeid
153 PlaceSafepoints() : ModulePass(ID) {
154 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
156 bool runOnModule(Module &M) override {
157 bool modified = false;
158 for (Function &F : M) {
159 modified |= runOnFunction(F);
163 bool runOnFunction(Function &F);
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
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
177 InsertSafepointPoll(DominatorTree &DT, Instruction *after,
178 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
180 static bool isGCLeafFunction(const CallSite &CS);
182 static bool needsStatepoint(const CallSite &CS) {
183 if (isGCLeafFunction(CS))
186 CallInst *call = cast<CallInst>(CS.getInstruction());
187 if (call->isInlineAsm())
190 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
196 static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
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.
202 static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
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?");
217 BasicBlock *Current = Pred;
219 for (Instruction &I : *Current) {
220 if (auto CS = CallSite(&I))
221 // Note: Technically, needing a safepoint isn't quite the right
222 // condition here. We should instead be checking if the target method
224 // unconditional poll. In practice, this is only a theoretical concern
225 // since we don't have any methods with conditional-only safepoint
227 if (needsStatepoint(CS))
231 if (Current == Header)
233 Current = DT.getNode(Current)->getIDom()->getBlock();
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.
243 static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
245 // Only used when SkipCounted is off
246 const unsigned upperTripBound = 8192;
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))
254 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
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))
269 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
274 return /* not finite */ false;
277 static void scanOneBB(Instruction *start, Instruction *end,
278 std::vector<CallInst *> &calls,
279 std::set<BasicBlock *> &seen,
280 std::vector<BasicBlock *> &worklist) {
281 for (BasicBlock::iterator itr(start);
282 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
284 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
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();
294 for (BasicBlock *Succ : successors(BB)) {
295 if (seen.count(Succ) == 0) {
296 worklist.push_back(Succ);
303 static void scanInlinedCode(Instruction *start, Instruction *end,
304 std::vector<CallInst *> &calls,
305 std::set<BasicBlock *> &seen) {
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();
313 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
317 bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L, LPPassManager &LPM) {
318 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
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
324 BasicBlock *header = L->getHeader();
326 // TODO: Use the analysis pass infrastructure for this. There is no reason
327 // to recalculate this here.
329 DT.recalculate(*header->getParent());
331 bool modified = false;
332 for (BasicBlock *pred : predecessors(header)) {
333 if (!L->contains(pred)) {
334 // This is not a backedge, it's coming from outside the loop
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.
342 if (mustBeFiniteCountedLoop(L, SE, pred)) {
344 errs() << "skipping safepoint placement in finite loop\n";
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.
354 errs() << "skipping safepoint placement due to unconditional call\n";
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.
365 // We're unconditionally going to modify this loop.
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();
374 errs() << "[LSP] terminator instruction: ";
378 PollLocations.push_back(term);
384 static Instruction *findLocationForEntrySafepoint(Function &F,
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.
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.
399 // hasNextInstruction and nextInstruction are used to iterate
400 // through a "straight line" execution sequence.
402 auto hasNextInstruction = [](Instruction *I) {
403 if (!I->isTerminator()) {
406 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
407 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
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();
416 return std::next(BasicBlock::iterator(I));
420 Instruction *cursor = nullptr;
421 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
422 cursor = nextInstruction(cursor)) {
424 // 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
427 if (CallSite(cursor)) {
428 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) {
429 // llvm.assume(...) are not really calls.
430 if (II->getIntrinsicID() == Intrinsic::assume) {
433 // llvm.frameescape() intrinsic is not a real call. The intrinsic can
434 // exist only in the entry block.
435 // Inserting a statepoint before llvm.frameescape() may split the
436 // entry block, and push the intrinsic out of the entry block.
437 if (II->getIntrinsicID() == Intrinsic::frameescape) {
445 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
446 "either we stopped because of a call, or because of terminator");
448 if (cursor->isTerminator()) {
452 BasicBlock *BB = cursor->getParent();
453 SplitBlock(BB, cursor, nullptr);
455 // Note: SplitBlock modifies the DT. Simply passing a Pass (which is a
456 // module pass) is not enough.
459 // SplitBlock updates the DT
463 return BB->getTerminator();
466 /// Identify the list of call sites which need to be have parseable state
467 static void findCallSafepoints(Function &F,
468 std::vector<CallSite> &Found /*rval*/) {
469 assert(Found.empty() && "must be empty!");
470 for (Instruction &I : inst_range(F)) {
471 Instruction *inst = &I;
472 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
475 // No safepoint needed or wanted
476 if (!needsStatepoint(CS)) {
485 /// Implement a unique function which doesn't require we sort the input
486 /// vector. Doing so has the effect of changing the output of a couple of
487 /// tests in ways which make them less useful in testing fused safepoints.
488 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
491 vec.reserve(vec.size());
494 if (seen.insert(V).second) {
500 static std::string GCSafepointPollName("gc.safepoint_poll");
502 static bool isGCSafepointPoll(Function &F) {
503 return F.getName().equals(GCSafepointPollName);
506 /// Returns true if this function should be rewritten to include safepoint
507 /// polls and parseable call sites. The main point of this function is to be
508 /// an extension point for custom logic.
509 static bool shouldRewriteFunction(Function &F) {
510 // TODO: This should check the GCStrategy
512 const std::string StatepointExampleName("statepoint-example");
513 return StatepointExampleName == F.getGC();
518 // TODO: These should become properties of the GCStrategy, possibly with
519 // command line overrides.
520 static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
521 static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
522 static bool enableCallSafepoints(Function &F) { return !NoCall; }
525 bool PlaceSafepoints::runOnFunction(Function &F) {
526 if (F.isDeclaration() || F.empty()) {
527 // This is a declaration, nothing to do. Must exit early to avoid crash in
528 // dom tree calculation
532 if (isGCSafepointPoll(F)) {
533 // Given we're inlining this inside of safepoint poll insertion, this
534 // doesn't make any sense. Note that we do make any contained calls
535 // parseable after we inline a poll.
539 if (!shouldRewriteFunction(F))
542 bool modified = false;
544 // In various bits below, we rely on the fact that uses are reachable from
545 // defs. When there are basic blocks unreachable from the entry, dominance
546 // and reachablity queries return non-sensical results. Thus, we preprocess
547 // the function to ensure these properties hold.
548 modified |= removeUnreachableBlocks(F);
550 // STEP 1 - Insert the safepoint polling locations. We do not need to
551 // actually insert parse points yet. That will be done for all polls and
552 // calls in a single pass.
554 // Note: With the migration, we need to recompute this for each 'pass'. Once
555 // we merge these, we'll do it once before the analysis
558 std::vector<CallSite> ParsePointNeeded;
560 if (enableBackedgeSafepoints(F)) {
561 // Construct a pass manager to run the LoopPass backedge logic. We
562 // need the pass manager to handle scheduling all the loop passes
563 // appropriately. Doing this by hand is painful and just not worth messing
564 // with for the moment.
565 legacy::FunctionPassManager FPM(F.getParent());
566 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
567 PlaceBackedgeSafepointsImpl *PBS =
568 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
570 // Note: While the analysis pass itself won't modify the IR, LoopSimplify
571 // (which it depends on) may. i.e. analysis must be recalculated after run
574 // We preserve dominance information when inserting the poll, otherwise
575 // we'd have to recalculate this on every insert
578 // Insert a poll at each point the analysis pass identified
579 for (size_t i = 0; i < PBS->PollLocations.size(); i++) {
580 // We are inserting a poll, the function is modified
583 // The poll location must be the terminator of a loop latch block.
584 TerminatorInst *Term = PBS->PollLocations[i];
586 std::vector<CallSite> ParsePoints;
588 // Split the backedge of the loop and insert the poll within that new
589 // basic block. This creates a loop with two latches per original
590 // latch (which is non-ideal), but this appears to be easier to
591 // optimize in practice than inserting the poll immediately before the
594 // Since this is a latch, at least one of the successors must dominate
595 // it. Its possible that we have a) duplicate edges to the same header
596 // and b) edges to distinct loop headers. We need to insert pools on
597 // each. (Note: This still relies on LoopSimplify.)
598 DenseSet<BasicBlock *> Headers;
599 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
600 BasicBlock *Succ = Term->getSuccessor(i);
601 if (DT.dominates(Succ, Term->getParent())) {
602 Headers.insert(Succ);
605 assert(!Headers.empty() && "poll location is not a loop latch?");
607 // The split loop structure here is so that we only need to recalculate
608 // the dominator tree once. Alternatively, we could just keep it up to
609 // date and use a more natural merged loop.
610 DenseSet<BasicBlock *> SplitBackedges;
611 for (BasicBlock *Header : Headers) {
612 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, nullptr);
613 SplitBackedges.insert(NewBB);
616 for (BasicBlock *NewBB : SplitBackedges) {
617 InsertSafepointPoll(DT, NewBB->getTerminator(), ParsePoints);
618 NumBackedgeSafepoints++;
622 // Split the latch block itself, right before the terminator.
623 InsertSafepointPoll(DT, Term, ParsePoints);
624 NumBackedgeSafepoints++;
627 // Record the parse points for later use
628 ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
633 if (enableEntrySafepoints(F)) {
635 Instruction *term = findLocationForEntrySafepoint(F, DT);
637 // policy choice not to insert?
639 std::vector<CallSite> RuntimeCalls;
640 InsertSafepointPoll(DT, term, RuntimeCalls);
642 NumEntrySafepoints++;
643 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
648 if (enableCallSafepoints(F)) {
650 std::vector<CallSite> Calls;
651 findCallSafepoints(F, Calls);
652 NumCallSafepoints += Calls.size();
653 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
656 // Unique the vectors since we can end up with duplicates if we scan the call
657 // site for call safepoints after we add it for entry or backedge. The
658 // only reason we need tracking at all is that some functions might have
659 // polls but not call safepoints and thus we might miss marking the runtime
660 // calls for the polls. (This is useful in test cases!)
661 unique_unsorted(ParsePointNeeded);
663 // Any parse point (no matter what source) will be handled here
664 DT.recalculate(F); // Needed?
666 // We're about to start modifying the function
667 if (!ParsePointNeeded.empty())
670 // Now run through and insert the safepoints, but do _NOT_ update or remove
671 // any existing uses. We have references to live variables that need to
672 // survive to the last iteration of this loop.
673 std::vector<Value *> Results;
674 Results.reserve(ParsePointNeeded.size());
675 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
676 CallSite &CS = ParsePointNeeded[i];
677 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
678 Results.push_back(GCResult);
680 assert(Results.size() == ParsePointNeeded.size());
682 // Adjust all users of the old call sites to use the new ones instead
683 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
684 CallSite &CS = ParsePointNeeded[i];
685 Value *GCResult = Results[i];
687 // In case if we inserted result in a different basic block than the
688 // original safepoint (this can happen for invokes). We need to be sure
690 // original result value was not used in any of the phi nodes at the
691 // beginning of basic block with gc result. Because we know that all such
692 // blocks will have single predecessor we can safely assume that all phi
693 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
694 // Just remove them all here.
696 FoldSingleEntryPHINodes(cast<Instruction>(GCResult)->getParent(),
699 !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
702 // Replace all uses with the new call
703 CS.getInstruction()->replaceAllUsesWith(GCResult);
706 // Now that we've handled all uses, remove the original call itself
707 // Note: The insert point can't be the deleted instruction!
708 CS.getInstruction()->eraseFromParent();
713 char PlaceBackedgeSafepointsImpl::ID = 0;
714 char PlaceSafepoints::ID = 0;
716 ModulePass *llvm::createPlaceSafepointsPass() { return new PlaceSafepoints(); }
718 INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
719 "place-backedge-safepoints-impl",
720 "Place Backedge Safepoints", false, false)
721 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
722 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
723 INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
724 "place-backedge-safepoints-impl",
725 "Place Backedge Safepoints", false, false)
727 INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
729 INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
732 static bool isGCLeafFunction(const CallSite &CS) {
733 Instruction *inst = CS.getInstruction();
734 if (isa<IntrinsicInst>(inst)) {
735 // Most LLVM intrinsics are things which can never take a safepoint.
736 // As a result, we don't need to have the stack parsable at the
737 // callsite. This is a highly useful optimization since intrinsic
738 // calls are fairly prevelent, particularly in debug builds.
742 // If this function is marked explicitly as a leaf call, we don't need to
743 // place a safepoint of it. In fact, for correctness we *can't* in many
744 // cases. Note: Indirect calls return Null for the called function,
745 // these obviously aren't runtime functions with attributes
746 // TODO: Support attributes on the call site as well.
747 const Function *F = CS.getCalledFunction();
750 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
758 InsertSafepointPoll(DominatorTree &DT, Instruction *term,
759 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
760 Module *M = term->getParent()->getParent()->getParent();
763 // Inline the safepoint poll implementation - this will get all the branch,
764 // control flow, etc.. Most importantly, it will introduce the actual slow
765 // path call - where we need to insert a safepoint (parsepoint).
766 FunctionType *ftype =
767 FunctionType::get(Type::getVoidTy(M->getContext()), false);
768 assert(ftype && "null?");
769 // Note: This cast can fail if there's a function of the same name with a
770 // different type inserted previously
772 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
773 assert(F && "void @gc.safepoint_poll() must be defined");
774 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
775 CallInst *poll = CallInst::Create(F, "", term);
777 // Record some information about the call site we're replacing
778 BasicBlock *OrigBB = term->getParent();
779 BasicBlock::iterator before(poll), after(poll);
781 if (before == term->getParent()->begin()) {
787 assert(after != poll->getParent()->end() && "must have successor");
788 assert(DT.dominates(before, after) && "trivially true");
790 // do the actual inlining
791 InlineFunctionInfo IFI;
792 bool inlineStatus = InlineFunction(poll, IFI);
793 assert(inlineStatus && "inline must succeed");
794 (void)inlineStatus; // suppress warning in release-asserts
796 // Check post conditions
797 assert(IFI.StaticAllocas.empty() && "can't have allocs");
799 std::vector<CallInst *> calls; // new calls
800 std::set<BasicBlock *> BBs; // new BBs + insertee
801 // Include only the newly inserted instructions, Note: begin may not be valid
802 // if we inserted to the beginning of the basic block
803 BasicBlock::iterator start;
805 start = OrigBB->begin();
811 // If your poll function includes an unreachable at the end, that's not
812 // valid. Bugpoint likes to create this, so check for it.
813 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
814 "malformed poll function");
816 scanInlinedCode(&*(start), &*(after), calls, BBs);
818 // Recompute since we've invalidated cached data. Conceptually we
819 // shouldn't need to do this, but implementation wise we appear to. Needed
820 // so we can insert safepoints correctly.
821 // TODO: update more cheaply
822 DT.recalculate(*after->getParent()->getParent());
824 assert(!calls.empty() && "slow path not found for safepoint poll");
826 // Record the fact we need a parsable state at the runtime call contained in
827 // the poll function. This is required so that the runtime knows how to
828 // parse the last frame when we actually take the safepoint (i.e. execute
830 assert(ParsePointsNeeded.empty());
831 for (size_t i = 0; i < calls.size(); i++) {
833 // No safepoint needed or wanted
834 if (!needsStatepoint(calls[i])) {
838 // These are likely runtime calls. Should we assert that via calling
839 // convention or something?
840 ParsePointsNeeded.push_back(CallSite(calls[i]));
842 assert(ParsePointsNeeded.size() <= calls.size());
845 // Normalize basic block to make it ready to be target of invoke statepoint.
846 // It means spliting it to have single predecessor. Return newly created BB
847 // ready to be successor of invoke statepoint.
848 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
849 BasicBlock *InvokeParent) {
850 BasicBlock *ret = BB;
852 if (!BB->getUniquePredecessor()) {
853 ret = SplitBlockPredecessors(BB, InvokeParent, "");
856 // Another requirement for such basic blocks is to not have any phi nodes.
857 // Since we just ensured that new BB will have single predecessor,
858 // all phi nodes in it will have one value. Here it would be naturall place
860 // remove them all. But we can not do this because we are risking to remove
861 // one of the values stored in liveset of another statepoint. We will do it
862 // later after placing all safepoints.
867 /// Replaces the given call site (Call or Invoke) with a gc.statepoint
868 /// intrinsic with an empty deoptimization arguments list. This does
869 /// NOT do explicit relocation for GC support.
870 static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
872 BasicBlock *BB = CS.getInstruction()->getParent();
873 Function *F = BB->getParent();
874 Module *M = F->getParent();
875 assert(M && "must be set");
877 // TODO: technically, a pass is not allowed to get functions from within a
878 // function pass since it might trigger a new function addition. Refactor
879 // this logic out to the initialization of the pass. Doesn't appear to
880 // matter in practice.
882 // Then go ahead and use the builder do actually do the inserts. We insert
883 // immediately before the previous instruction under the assumption that all
884 // arguments will be available here. We can't insert afterwards since we may
885 // be replacing a terminator.
886 Instruction *insertBefore = CS.getInstruction();
887 IRBuilder<> Builder(insertBefore);
889 // Note: The gc args are not filled in at this time, that's handled by
890 // RewriteStatepointsForGC (which is currently under review).
892 // Create the statepoint given all the arguments
893 Instruction *token = nullptr;
894 AttributeSet return_attributes;
896 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
897 CallInst *Call = Builder.CreateGCStatepoint(
898 CS.getCalledValue(), makeArrayRef(CS.arg_begin(), CS.arg_end()), None,
899 None, "safepoint_token");
900 Call->setTailCall(toReplace->isTailCall());
901 Call->setCallingConv(toReplace->getCallingConv());
903 // Before we have to worry about GC semantics, all attributes are legal
904 AttributeSet new_attrs = toReplace->getAttributes();
905 // In case if we can handle this set of sttributes - set up function attrs
906 // directly on statepoint and return attrs later for gc_result intrinsic.
907 Call->setAttributes(new_attrs.getFnAttributes());
908 return_attributes = new_attrs.getRetAttributes();
909 // TODO: handle param attributes
913 // Put the following gc_result and gc_relocate calls immediately after the
914 // the old call (which we're about to delete)
915 BasicBlock::iterator next(toReplace);
916 assert(BB->end() != next && "not a terminator, must have next");
918 Instruction *IP = &*(next);
919 Builder.SetInsertPoint(IP);
920 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
922 } else if (CS.isInvoke()) {
923 // TODO: make CreateGCStatepoint return an Instruction that we can cast to a
924 // Call or Invoke, instead of doing this junk here.
926 // Fill in the one generic type'd argument (the function is also
928 std::vector<Type *> argTypes;
929 argTypes.push_back(CS.getCalledValue()->getType());
931 Function *gc_statepoint_decl = Intrinsic::getDeclaration(
932 M, Intrinsic::experimental_gc_statepoint, argTypes);
934 // First, create the statepoint (with all live ptrs as arguments).
935 std::vector<llvm::Value *> args;
936 // target, #call args, unused, ... call parameters, #deopt args, ... deopt
937 // parameters, ... gc parameters
938 Value *Target = CS.getCalledValue();
939 args.push_back(Target);
940 int callArgSize = CS.arg_size();
942 args.push_back(Builder.getInt32(callArgSize));
944 args.push_back(Builder.getInt32(0));
946 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
948 args.push_back(Builder.getInt32(0));
950 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
952 // Insert the new invoke into the old block. We'll remove the old one in a
953 // moment at which point this will become the new terminator for the
955 InvokeInst *invoke = InvokeInst::Create(
956 gc_statepoint_decl, toReplace->getNormalDest(),
957 toReplace->getUnwindDest(), args, "", toReplace->getParent());
958 invoke->setCallingConv(toReplace->getCallingConv());
960 // Currently we will fail on parameter attributes and on certain
961 // function attributes.
962 AttributeSet new_attrs = toReplace->getAttributes();
963 // In case if we can handle this set of sttributes - set up function attrs
964 // directly on statepoint and return attrs later for gc_result intrinsic.
965 invoke->setAttributes(new_attrs.getFnAttributes());
966 return_attributes = new_attrs.getRetAttributes();
970 // We'll insert the gc.result into the normal block
971 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
972 toReplace->getNormalDest(), invoke->getParent());
973 Instruction *IP = &*(normalDest->getFirstInsertionPt());
974 Builder.SetInsertPoint(IP);
976 llvm_unreachable("unexpect type of CallSite");
980 // Handle the return value of the original call - update all uses to use a
981 // gc_result hanging off the statepoint node we just inserted
983 // Only add the gc_result iff there is actually a used result
984 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
985 std::string takenName =
986 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
987 CallInst *gc_result =
988 Builder.CreateGCResult(token, CS.getType(), takenName);
989 gc_result->setAttributes(return_attributes);
992 // No return value for the call.