Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 1 | //===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // Place garbage collection safepoints at appropriate locations in the IR. This |
| 11 | // does not make relocation semantics or variable liveness explicit. That's |
| 12 | // done by RewriteStatepointsForGC. |
| 13 | // |
Philip Reames | d4a912f | 2015-02-09 22:44:03 +0000 | [diff] [blame] | 14 | // Terminology: |
| 15 | // - A call is said to be "parseable" if there is a stack map generated for the |
| 16 | // return PC of the call. A runtime can determine where values listed in the |
| 17 | // deopt arguments and (after RewriteStatepointsForGC) gc arguments are located |
| 18 | // on the stack when the code is suspended inside such a call. Every parse |
| 19 | // point is represented by a call wrapped in an gc.statepoint intrinsic. |
| 20 | // - A "poll" is an explicit check in the generated code to determine if the |
| 21 | // runtime needs the generated code to cooperate by calling a helper routine |
| 22 | // and thus suspending its execution at a known state. The call to the helper |
| 23 | // routine will be parseable. The (gc & runtime specific) logic of a poll is |
| 24 | // assumed to be provided in a function of the name "gc.safepoint_poll". |
| 25 | // |
| 26 | // We aim to insert polls such that running code can quickly be brought to a |
| 27 | // well defined state for inspection by the collector. In the current |
| 28 | // implementation, this is done via the insertion of poll sites at method entry |
| 29 | // and the backedge of most loops. We try to avoid inserting more polls than |
| 30 | // are neccessary to ensure a finite period between poll sites. This is not |
| 31 | // because the poll itself is expensive in the generated code; it's not. Polls |
| 32 | // do tend to impact the optimizer itself in negative ways; we'd like to avoid |
| 33 | // perturbing the optimization of the method as much as we can. |
| 34 | // |
| 35 | // We also need to make most call sites parseable. The callee might execute a |
| 36 | // poll (or otherwise be inspected by the GC). If so, the entire stack |
| 37 | // (including the suspended frame of the current method) must be parseable. |
| 38 | // |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 39 | // This pass will insert: |
Philip Reames | d4a912f | 2015-02-09 22:44:03 +0000 | [diff] [blame] | 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. |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 44 | // |
Philip Reames | d4a912f | 2015-02-09 22:44:03 +0000 | [diff] [blame] | 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. |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 48 | // |
| 49 | //===----------------------------------------------------------------------===// |
| 50 | |
| 51 | #include "llvm/Pass.h" |
Chandler Carruth | 30d69c2 | 2015-02-13 10:01:29 +0000 | [diff] [blame] | 52 | #include "llvm/IR/LegacyPassManager.h" |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 53 | #include "llvm/ADT/SetOperations.h" |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 54 | #include "llvm/ADT/SetVector.h" |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 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" |
| 82 | |
| 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"); |
| 87 | |
| 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"); |
| 90 | |
| 91 | using namespace llvm; |
| 92 | |
| 93 | // Ignore oppurtunities to avoid placing safepoints on backedges, useful for |
| 94 | // validation |
Philip Reames | 1f3e5c1 | 2015-02-20 23:32:03 +0000 | [diff] [blame] | 95 | static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden, |
| 96 | cl::init(false)); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 97 | |
| 98 | /// If true, do not place backedge safepoints in counted loops. |
Philip Reames | 1f3e5c1 | 2015-02-20 23:32:03 +0000 | [diff] [blame] | 99 | static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true)); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 100 | |
| 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 |
| 104 | // optimizes better. |
Philip Reames | 1f3e5c1 | 2015-02-20 23:32:03 +0000 | [diff] [blame] | 105 | static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden, |
| 106 | cl::init(false)); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 107 | |
| 108 | // Print tracing output |
Philip Reames | 1f3e5c1 | 2015-02-20 23:32:03 +0000 | [diff] [blame] | 109 | static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false)); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 110 | |
| 111 | namespace { |
| 112 | |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 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 FunctionPass { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 116 | static char ID; |
| 117 | |
| 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; |
| 121 | |
| 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; |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 125 | |
| 126 | ScalarEvolution *SE = nullptr; |
| 127 | DominatorTree *DT = nullptr; |
| 128 | LoopInfo *LI = nullptr; |
| 129 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 130 | PlaceBackedgeSafepointsImpl(bool CallSafepoints = false) |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 131 | : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) { |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 132 | initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 133 | } |
| 134 | |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 135 | bool runOnLoop(Loop *); |
| 136 | void runOnLoopAndSubLoops(Loop *L) { |
| 137 | // Visit all the subloops |
| 138 | for (auto I = L->begin(), E = L->end(); I != E; I++) |
| 139 | runOnLoopAndSubLoops(*I); |
| 140 | runOnLoop(L); |
| 141 | } |
Justin Bogner | 383749a | 2015-05-12 21:49:47 +0000 | [diff] [blame] | 142 | |
| 143 | bool runOnFunction(Function &F) override { |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 144 | SE = &getAnalysis<ScalarEvolution>(); |
| 145 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 146 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 147 | for (auto I = LI->begin(), E = LI->end(); I != E; I++) { |
| 148 | runOnLoopAndSubLoops(*I); |
| 149 | } |
| 150 | return false; |
| 151 | } |
| 152 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 153 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Philip Reames | 57bdac9 | 2015-05-12 20:56:33 +0000 | [diff] [blame] | 154 | AU.addRequired<DominatorTreeWrapperPass>(); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 155 | AU.addRequired<ScalarEvolution>(); |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 156 | AU.addRequired<LoopInfoWrapperPass>(); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 157 | // We no longer modify the IR at all in this pass. Thus all |
| 158 | // analysis are preserved. |
| 159 | AU.setPreservesAll(); |
| 160 | } |
| 161 | }; |
| 162 | } |
| 163 | |
Philip Reames | 1f3e5c1 | 2015-02-20 23:32:03 +0000 | [diff] [blame] | 164 | static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false)); |
| 165 | static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false)); |
| 166 | static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false)); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 167 | |
| 168 | namespace { |
Philip Reames | 7b98179 | 2015-05-12 21:21:18 +0000 | [diff] [blame] | 169 | struct PlaceSafepoints : public FunctionPass { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 170 | static char ID; // Pass identification, replacement for typeid |
| 171 | |
Philip Reames | 7b98179 | 2015-05-12 21:21:18 +0000 | [diff] [blame] | 172 | PlaceSafepoints() : FunctionPass(ID) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 173 | initializePlaceSafepointsPass(*PassRegistry::getPassRegistry()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 174 | } |
Philip Reames | 7b98179 | 2015-05-12 21:21:18 +0000 | [diff] [blame] | 175 | bool runOnFunction(Function &F) override; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 176 | |
| 177 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 178 | // We modify the graph wholesale (inlining, block insertion, etc). We |
| 179 | // preserve nothing at the moment. We could potentially preserve dom tree |
| 180 | // if that was worth doing |
| 181 | } |
| 182 | }; |
| 183 | } |
| 184 | |
| 185 | // Insert a safepoint poll immediately before the given instruction. Does |
| 186 | // not handle the parsability of state at the runtime call, that's the |
| 187 | // callers job. |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 188 | static void |
| 189 | InsertSafepointPoll(Instruction *after, |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 190 | std::vector<CallSite> &ParsePointsNeeded /*rval*/); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 191 | |
| 192 | static bool isGCLeafFunction(const CallSite &CS); |
| 193 | |
| 194 | static bool needsStatepoint(const CallSite &CS) { |
| 195 | if (isGCLeafFunction(CS)) |
| 196 | return false; |
| 197 | if (CS.isCall()) { |
| 198 | CallInst *call = cast<CallInst>(CS.getInstruction()); |
| 199 | if (call->isInlineAsm()) |
| 200 | return false; |
| 201 | } |
| 202 | if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) { |
| 203 | return false; |
| 204 | } |
| 205 | return true; |
| 206 | } |
| 207 | |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 208 | static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 209 | |
| 210 | /// Returns true if this loop is known to contain a call safepoint which |
| 211 | /// must unconditionally execute on any iteration of the loop which returns |
| 212 | /// to the loop header via an edge from Pred. Returns a conservative correct |
| 213 | /// answer; i.e. false is always valid. |
| 214 | static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header, |
| 215 | BasicBlock *Pred, |
| 216 | DominatorTree &DT) { |
| 217 | // In general, we're looking for any cut of the graph which ensures |
| 218 | // there's a call safepoint along every edge between Header and Pred. |
| 219 | // For the moment, we look only for the 'cuts' that consist of a single call |
| 220 | // instruction in a block which is dominated by the Header and dominates the |
| 221 | // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain |
| 222 | // of such dominating blocks gets substaintially more occurences than just |
| 223 | // checking the Pred and Header blocks themselves. This may be due to the |
| 224 | // density of loop exit conditions caused by range and null checks. |
| 225 | // TODO: structure this as an analysis pass, cache the result for subloops, |
| 226 | // avoid dom tree recalculations |
| 227 | assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?"); |
| 228 | |
| 229 | BasicBlock *Current = Pred; |
| 230 | while (true) { |
| 231 | for (Instruction &I : *Current) { |
Benjamin Kramer | 3a09ef6 | 2015-04-10 14:50:08 +0000 | [diff] [blame] | 232 | if (auto CS = CallSite(&I)) |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 233 | // Note: Technically, needing a safepoint isn't quite the right |
| 234 | // condition here. We should instead be checking if the target method |
| 235 | // has an |
| 236 | // unconditional poll. In practice, this is only a theoretical concern |
| 237 | // since we don't have any methods with conditional-only safepoint |
| 238 | // polls. |
| 239 | if (needsStatepoint(CS)) |
| 240 | return true; |
| 241 | } |
| 242 | |
| 243 | if (Current == Header) |
| 244 | break; |
| 245 | Current = DT.getNode(Current)->getIDom()->getBlock(); |
| 246 | } |
| 247 | |
| 248 | return false; |
| 249 | } |
| 250 | |
| 251 | /// Returns true if this loop is known to terminate in a finite number of |
| 252 | /// iterations. Note that this function may return false for a loop which |
| 253 | /// does actual terminate in a finite constant number of iterations due to |
| 254 | /// conservatism in the analysis. |
| 255 | static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE, |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 256 | BasicBlock *Pred) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 257 | // Only used when SkipCounted is off |
| 258 | const unsigned upperTripBound = 8192; |
| 259 | |
| 260 | // A conservative bound on the loop as a whole. |
| 261 | const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L); |
| 262 | if (MaxTrips != SE->getCouldNotCompute()) { |
| 263 | if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound)) |
| 264 | return true; |
| 265 | if (SkipCounted && |
| 266 | SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32)) |
| 267 | return true; |
| 268 | } |
| 269 | |
| 270 | // If this is a conditional branch to the header with the alternate path |
| 271 | // being outside the loop, we can ask questions about the execution frequency |
| 272 | // of the exit block. |
| 273 | if (L->isLoopExiting(Pred)) { |
| 274 | // This returns an exact expression only. TODO: We really only need an |
| 275 | // upper bound here, but SE doesn't expose that. |
| 276 | const SCEV *MaxExec = SE->getExitCount(L, Pred); |
| 277 | if (MaxExec != SE->getCouldNotCompute()) { |
| 278 | if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound)) |
| 279 | return true; |
| 280 | if (SkipCounted && |
| 281 | SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32)) |
| 282 | return true; |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | return /* not finite */ false; |
| 287 | } |
| 288 | |
| 289 | static void scanOneBB(Instruction *start, Instruction *end, |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 290 | std::vector<CallInst *> &calls, |
| 291 | std::set<BasicBlock *> &seen, |
| 292 | std::vector<BasicBlock *> &worklist) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 293 | for (BasicBlock::iterator itr(start); |
| 294 | itr != start->getParent()->end() && itr != BasicBlock::iterator(end); |
| 295 | itr++) { |
| 296 | if (CallInst *CI = dyn_cast<CallInst>(&*itr)) { |
| 297 | calls.push_back(CI); |
| 298 | } |
| 299 | // FIXME: This code does not handle invokes |
| 300 | assert(!dyn_cast<InvokeInst>(&*itr) && |
| 301 | "support for invokes in poll code needed"); |
| 302 | // Only add the successor blocks if we reach the terminator instruction |
| 303 | // without encountering end first |
| 304 | if (itr->isTerminator()) { |
| 305 | BasicBlock *BB = itr->getParent(); |
Philip Reames | a29de87 | 2015-02-09 22:26:11 +0000 | [diff] [blame] | 306 | for (BasicBlock *Succ : successors(BB)) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 307 | if (seen.count(Succ) == 0) { |
| 308 | worklist.push_back(Succ); |
| 309 | seen.insert(Succ); |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | static void scanInlinedCode(Instruction *start, Instruction *end, |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 316 | std::vector<CallInst *> &calls, |
| 317 | std::set<BasicBlock *> &seen) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 318 | calls.clear(); |
| 319 | std::vector<BasicBlock *> worklist; |
| 320 | seen.insert(start->getParent()); |
| 321 | scanOneBB(start, end, calls, seen, worklist); |
| 322 | while (!worklist.empty()) { |
| 323 | BasicBlock *BB = worklist.back(); |
| 324 | worklist.pop_back(); |
| 325 | scanOneBB(&*BB->begin(), end, calls, seen, worklist); |
| 326 | } |
| 327 | } |
| 328 | |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 329 | bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) { |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 330 | // Loop through all loop latches (branches controlling backedges). We need |
| 331 | // to place a safepoint on every backedge (potentially). |
| 332 | // Note: In common usage, there will be only one edge due to LoopSimplify |
| 333 | // having run sometime earlier in the pipeline, but this code must be correct |
| 334 | // w.r.t. loops with multiple backedges. |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 335 | BasicBlock *header = L->getHeader(); |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 336 | SmallVector<BasicBlock*, 16> LoopLatches; |
| 337 | L->getLoopLatches(LoopLatches); |
| 338 | for (BasicBlock *pred : LoopLatches) { |
| 339 | assert(L->contains(pred)); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 340 | |
| 341 | // Make a policy decision about whether this loop needs a safepoint or |
| 342 | // not. Note that this is about unburdening the optimizer in loops, not |
| 343 | // avoiding the runtime cost of the actual safepoint. |
| 344 | if (!AllBackedges) { |
| 345 | if (mustBeFiniteCountedLoop(L, SE, pred)) { |
| 346 | if (TraceLSP) |
| 347 | errs() << "skipping safepoint placement in finite loop\n"; |
| 348 | FiniteExecution++; |
| 349 | continue; |
| 350 | } |
| 351 | if (CallSafepointsEnabled && |
Philip Reames | 57bdac9 | 2015-05-12 20:56:33 +0000 | [diff] [blame] | 352 | containsUnconditionalCallSafepoint(L, header, pred, *DT)) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 353 | // Note: This is only semantically legal since we won't do any further |
| 354 | // IPO or inlining before the actual call insertion.. If we hadn't, we |
| 355 | // might latter loose this call safepoint. |
| 356 | if (TraceLSP) |
| 357 | errs() << "skipping safepoint placement due to unconditional call\n"; |
| 358 | CallInLoop++; |
| 359 | continue; |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // TODO: We can create an inner loop which runs a finite number of |
| 364 | // iterations with an outer loop which contains a safepoint. This would |
| 365 | // not help runtime performance that much, but it might help our ability to |
| 366 | // optimize the inner loop. |
| 367 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 368 | // Safepoint insertion would involve creating a new basic block (as the |
| 369 | // target of the current backedge) which does the safepoint (of all live |
| 370 | // variables) and branches to the true header |
| 371 | TerminatorInst *term = pred->getTerminator(); |
| 372 | |
| 373 | if (TraceLSP) { |
| 374 | errs() << "[LSP] terminator instruction: "; |
| 375 | term->dump(); |
| 376 | } |
| 377 | |
| 378 | PollLocations.push_back(term); |
| 379 | } |
| 380 | |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 381 | return false; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 382 | } |
| 383 | |
| 384 | static Instruction *findLocationForEntrySafepoint(Function &F, |
| 385 | DominatorTree &DT) { |
| 386 | |
| 387 | // Conceptually, this poll needs to be on method entry, but in |
| 388 | // practice, we place it as late in the entry block as possible. We |
| 389 | // can place it as late as we want as long as it dominates all calls |
| 390 | // that can grow the stack. This, combined with backedge polls, |
| 391 | // give us all the progress guarantees we need. |
| 392 | |
| 393 | // Due to the way the frontend generates IR, we may have a couple of initial |
| 394 | // basic blocks before the first bytecode. These will be single-entry |
| 395 | // single-exit blocks which conceptually are just part of the first 'real |
| 396 | // basic block'. Since we don't have deopt state until the first bytecode, |
| 397 | // walk forward until we've found the first unconditional branch or merge. |
| 398 | |
| 399 | // hasNextInstruction and nextInstruction are used to iterate |
| 400 | // through a "straight line" execution sequence. |
| 401 | |
| 402 | auto hasNextInstruction = [](Instruction *I) { |
| 403 | if (!I->isTerminator()) { |
| 404 | return true; |
| 405 | } |
| 406 | BasicBlock *nextBB = I->getParent()->getUniqueSuccessor(); |
| 407 | return nextBB && (nextBB->getUniquePredecessor() != nullptr); |
| 408 | }; |
| 409 | |
| 410 | auto nextInstruction = [&hasNextInstruction](Instruction *I) { |
| 411 | assert(hasNextInstruction(I) && |
| 412 | "first check if there is a next instruction!"); |
| 413 | if (I->isTerminator()) { |
| 414 | return I->getParent()->getUniqueSuccessor()->begin(); |
| 415 | } else { |
| 416 | return std::next(BasicBlock::iterator(I)); |
| 417 | } |
| 418 | }; |
| 419 | |
| 420 | Instruction *cursor = nullptr; |
| 421 | for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor); |
| 422 | cursor = nextInstruction(cursor)) { |
| 423 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 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 |
| 426 | // size). |
Benjamin Kramer | 3a09ef6 | 2015-04-10 14:50:08 +0000 | [diff] [blame] | 427 | if (CallSite(cursor)) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 428 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) { |
| 429 | // llvm.assume(...) are not really calls. |
| 430 | if (II->getIntrinsicID() == Intrinsic::assume) { |
| 431 | continue; |
| 432 | } |
Philip Reames | 2e78fa4 | 2015-04-26 19:41:23 +0000 | [diff] [blame] | 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) { |
| 438 | continue; |
| 439 | } |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 440 | } |
| 441 | break; |
| 442 | } |
| 443 | } |
| 444 | |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 445 | assert((hasNextInstruction(cursor) || cursor->isTerminator()) && |
| 446 | "either we stopped because of a call, or because of terminator"); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 447 | |
| 448 | if (cursor->isTerminator()) { |
| 449 | return cursor; |
| 450 | } |
| 451 | |
| 452 | BasicBlock *BB = cursor->getParent(); |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 453 | SplitBlock(BB, cursor, &DT); |
Adam Nemet | e340f85 | 2015-05-06 08:18:41 +0000 | [diff] [blame] | 454 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 455 | // SplitBlock updates the DT |
Adam Nemet | e340f85 | 2015-05-06 08:18:41 +0000 | [diff] [blame] | 456 | DEBUG(DT.verifyDomTree()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 457 | |
| 458 | return BB->getTerminator(); |
| 459 | } |
| 460 | |
| 461 | /// Identify the list of call sites which need to be have parseable state |
| 462 | static void findCallSafepoints(Function &F, |
| 463 | std::vector<CallSite> &Found /*rval*/) { |
| 464 | assert(Found.empty() && "must be empty!"); |
Philip Reames | a29de87 | 2015-02-09 22:26:11 +0000 | [diff] [blame] | 465 | for (Instruction &I : inst_range(F)) { |
| 466 | Instruction *inst = &I; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 467 | if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) { |
| 468 | CallSite CS(inst); |
| 469 | |
| 470 | // No safepoint needed or wanted |
| 471 | if (!needsStatepoint(CS)) { |
| 472 | continue; |
| 473 | } |
| 474 | |
| 475 | Found.push_back(CS); |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /// Implement a unique function which doesn't require we sort the input |
| 481 | /// vector. Doing so has the effect of changing the output of a couple of |
| 482 | /// tests in ways which make them less useful in testing fused safepoints. |
| 483 | template <typename T> static void unique_unsorted(std::vector<T> &vec) { |
| 484 | std::set<T> seen; |
| 485 | std::vector<T> tmp; |
| 486 | vec.reserve(vec.size()); |
| 487 | std::swap(tmp, vec); |
| 488 | for (auto V : tmp) { |
| 489 | if (seen.insert(V).second) { |
| 490 | vec.push_back(V); |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | |
Philip Reames | b1ed02f | 2015-02-09 21:48:05 +0000 | [diff] [blame] | 495 | static std::string GCSafepointPollName("gc.safepoint_poll"); |
| 496 | |
| 497 | static bool isGCSafepointPoll(Function &F) { |
| 498 | return F.getName().equals(GCSafepointPollName); |
| 499 | } |
| 500 | |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 501 | /// Returns true if this function should be rewritten to include safepoint |
| 502 | /// polls and parseable call sites. The main point of this function is to be |
| 503 | /// an extension point for custom logic. |
| 504 | static bool shouldRewriteFunction(Function &F) { |
| 505 | // TODO: This should check the GCStrategy |
| 506 | if (F.hasGC()) { |
| 507 | const std::string StatepointExampleName("statepoint-example"); |
| 508 | return StatepointExampleName == F.getGC(); |
| 509 | } else |
| 510 | return false; |
| 511 | } |
| 512 | |
| 513 | // TODO: These should become properties of the GCStrategy, possibly with |
| 514 | // command line overrides. |
| 515 | static bool enableEntrySafepoints(Function &F) { return !NoEntry; } |
| 516 | static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; } |
| 517 | static bool enableCallSafepoints(Function &F) { return !NoCall; } |
| 518 | |
Igor Laevsky | 5e23e16 | 2015-05-08 11:59:09 +0000 | [diff] [blame] | 519 | // Normalize basic block to make it ready to be target of invoke statepoint. |
| 520 | // Ensure that 'BB' does not have phi nodes. It may require spliting it. |
| 521 | static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB, |
| 522 | BasicBlock *InvokeParent) { |
| 523 | BasicBlock *ret = BB; |
| 524 | |
| 525 | if (!BB->getUniquePredecessor()) { |
| 526 | ret = SplitBlockPredecessors(BB, InvokeParent, ""); |
| 527 | } |
| 528 | |
| 529 | // Now that 'ret' has unique predecessor we can safely remove all phi nodes |
| 530 | // from it |
| 531 | FoldSingleEntryPHINodes(ret); |
| 532 | assert(!isa<PHINode>(ret->begin())); |
| 533 | |
| 534 | return ret; |
| 535 | } |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 536 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 537 | bool PlaceSafepoints::runOnFunction(Function &F) { |
| 538 | if (F.isDeclaration() || F.empty()) { |
| 539 | // This is a declaration, nothing to do. Must exit early to avoid crash in |
| 540 | // dom tree calculation |
| 541 | return false; |
| 542 | } |
| 543 | |
Philip Reames | 7e7dc3e | 2015-02-10 00:04:53 +0000 | [diff] [blame] | 544 | if (isGCSafepointPoll(F)) { |
| 545 | // Given we're inlining this inside of safepoint poll insertion, this |
| 546 | // doesn't make any sense. Note that we do make any contained calls |
| 547 | // parseable after we inline a poll. |
| 548 | return false; |
| 549 | } |
| 550 | |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 551 | if (!shouldRewriteFunction(F)) |
| 552 | return false; |
| 553 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 554 | bool modified = false; |
| 555 | |
| 556 | // In various bits below, we rely on the fact that uses are reachable from |
| 557 | // defs. When there are basic blocks unreachable from the entry, dominance |
| 558 | // and reachablity queries return non-sensical results. Thus, we preprocess |
| 559 | // the function to ensure these properties hold. |
| 560 | modified |= removeUnreachableBlocks(F); |
| 561 | |
| 562 | // STEP 1 - Insert the safepoint polling locations. We do not need to |
| 563 | // actually insert parse points yet. That will be done for all polls and |
| 564 | // calls in a single pass. |
| 565 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 566 | DominatorTree DT; |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 567 | DT.recalculate(F); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 568 | |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 569 | SmallVector<Instruction *, 16> PollsNeeded; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 570 | std::vector<CallSite> ParsePointNeeded; |
| 571 | |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 572 | if (enableBackedgeSafepoints(F)) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 573 | // Construct a pass manager to run the LoopPass backedge logic. We |
| 574 | // need the pass manager to handle scheduling all the loop passes |
| 575 | // appropriately. Doing this by hand is painful and just not worth messing |
| 576 | // with for the moment. |
Chandler Carruth | 30d69c2 | 2015-02-13 10:01:29 +0000 | [diff] [blame] | 577 | legacy::FunctionPassManager FPM(F.getParent()); |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 578 | bool CanAssumeCallSafepoints = enableCallSafepoints(F); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 579 | PlaceBackedgeSafepointsImpl *PBS = |
Philip Reames | b1ed02f | 2015-02-09 21:48:05 +0000 | [diff] [blame] | 580 | new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 581 | FPM.add(PBS); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 582 | FPM.run(F); |
| 583 | |
| 584 | // We preserve dominance information when inserting the poll, otherwise |
| 585 | // we'd have to recalculate this on every insert |
| 586 | DT.recalculate(F); |
| 587 | |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 588 | auto &PollLocations = PBS->PollLocations; |
| 589 | |
| 590 | auto OrderByBBName = [](Instruction *a, Instruction *b) { |
| 591 | return a->getParent()->getName() < b->getParent()->getName(); |
| 592 | }; |
| 593 | // We need the order of list to be stable so that naming ends up stable |
| 594 | // when we split edges. This makes test cases much easier to write. |
| 595 | std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName); |
| 596 | |
| 597 | // We can sometimes end up with duplicate poll locations. This happens if |
| 598 | // a single loop is visited more than once. The fact this happens seems |
| 599 | // wrong, but it does happen for the split-backedge.ll test case. |
| 600 | PollLocations.erase(std::unique(PollLocations.begin(), |
| 601 | PollLocations.end()), |
| 602 | PollLocations.end()); |
| 603 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 604 | // Insert a poll at each point the analysis pass identified |
Philip Reames | 89fe570 | 2015-05-12 23:39:23 +0000 | [diff] [blame] | 605 | // The poll location must be the terminator of a loop latch block. |
| 606 | for (TerminatorInst *Term : PollLocations) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 607 | // We are inserting a poll, the function is modified |
| 608 | modified = true; |
Philip Reames | 89fe570 | 2015-05-12 23:39:23 +0000 | [diff] [blame] | 609 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 610 | if (SplitBackedge) { |
| 611 | // Split the backedge of the loop and insert the poll within that new |
| 612 | // basic block. This creates a loop with two latches per original |
| 613 | // latch (which is non-ideal), but this appears to be easier to |
| 614 | // optimize in practice than inserting the poll immediately before the |
| 615 | // latch test. |
| 616 | |
| 617 | // Since this is a latch, at least one of the successors must dominate |
| 618 | // it. Its possible that we have a) duplicate edges to the same header |
| 619 | // and b) edges to distinct loop headers. We need to insert pools on |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 620 | // each. |
| 621 | SetVector<BasicBlock *> Headers; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 622 | for (unsigned i = 0; i < Term->getNumSuccessors(); i++) { |
| 623 | BasicBlock *Succ = Term->getSuccessor(i); |
| 624 | if (DT.dominates(Succ, Term->getParent())) { |
| 625 | Headers.insert(Succ); |
| 626 | } |
| 627 | } |
| 628 | assert(!Headers.empty() && "poll location is not a loop latch?"); |
| 629 | |
| 630 | // The split loop structure here is so that we only need to recalculate |
| 631 | // the dominator tree once. Alternatively, we could just keep it up to |
| 632 | // date and use a more natural merged loop. |
Philip Reames | 5708cca | 2015-05-12 20:43:48 +0000 | [diff] [blame] | 633 | SetVector<BasicBlock *> SplitBackedges; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 634 | for (BasicBlock *Header : Headers) { |
Philip Reames | 89fe570 | 2015-05-12 23:39:23 +0000 | [diff] [blame] | 635 | BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT); |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 636 | PollsNeeded.push_back(NewBB->getTerminator()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 637 | NumBackedgeSafepoints++; |
| 638 | } |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 639 | } else { |
| 640 | // Split the latch block itself, right before the terminator. |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 641 | PollsNeeded.push_back(Term); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 642 | NumBackedgeSafepoints++; |
| 643 | } |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 644 | } |
| 645 | } |
| 646 | |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 647 | if (enableEntrySafepoints(F)) { |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 648 | Instruction *Location = findLocationForEntrySafepoint(F, DT); |
| 649 | if (!Location) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 650 | // policy choice not to insert? |
| 651 | } else { |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 652 | PollsNeeded.push_back(Location); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 653 | modified = true; |
| 654 | NumEntrySafepoints++; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 655 | } |
| 656 | } |
| 657 | |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 658 | // Now that we've identified all the needed safepoint poll locations, insert |
| 659 | // safepoint polls themselves. |
| 660 | for (Instruction *PollLocation : PollsNeeded) { |
| 661 | std::vector<CallSite> RuntimeCalls; |
| 662 | InsertSafepointPoll(PollLocation, RuntimeCalls); |
| 663 | ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(), |
| 664 | RuntimeCalls.end()); |
| 665 | } |
| 666 | PollsNeeded.clear(); // make sure we don't accidentally use |
| 667 | // The dominator tree has been invalidated by the inlining performed in the |
| 668 | // above loop. TODO: Teach the inliner how to update the dom tree? |
| 669 | DT.recalculate(F); |
| 670 | |
Philip Reames | 0b1b387 | 2015-02-21 00:09:09 +0000 | [diff] [blame] | 671 | if (enableCallSafepoints(F)) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 672 | std::vector<CallSite> Calls; |
| 673 | findCallSafepoints(F, Calls); |
| 674 | NumCallSafepoints += Calls.size(); |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 675 | ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 676 | } |
| 677 | |
| 678 | // Unique the vectors since we can end up with duplicates if we scan the call |
| 679 | // site for call safepoints after we add it for entry or backedge. The |
| 680 | // only reason we need tracking at all is that some functions might have |
| 681 | // polls but not call safepoints and thus we might miss marking the runtime |
| 682 | // calls for the polls. (This is useful in test cases!) |
| 683 | unique_unsorted(ParsePointNeeded); |
| 684 | |
| 685 | // Any parse point (no matter what source) will be handled here |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 686 | |
| 687 | // We're about to start modifying the function |
| 688 | if (!ParsePointNeeded.empty()) |
| 689 | modified = true; |
| 690 | |
| 691 | // Now run through and insert the safepoints, but do _NOT_ update or remove |
| 692 | // any existing uses. We have references to live variables that need to |
| 693 | // survive to the last iteration of this loop. |
| 694 | std::vector<Value *> Results; |
| 695 | Results.reserve(ParsePointNeeded.size()); |
| 696 | for (size_t i = 0; i < ParsePointNeeded.size(); i++) { |
| 697 | CallSite &CS = ParsePointNeeded[i]; |
Igor Laevsky | 5e23e16 | 2015-05-08 11:59:09 +0000 | [diff] [blame] | 698 | |
| 699 | // For invoke statepoints we need to remove all phi nodes at the normal |
| 700 | // destination block. |
| 701 | // Reason for this is that we can place gc_result only after last phi node |
| 702 | // in basic block. We will get malformed code after RAUW for the |
| 703 | // gc_result if one of this phi nodes uses result from the invoke. |
| 704 | if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) { |
| 705 | normalizeForInvokeSafepoint(Invoke->getNormalDest(), |
| 706 | Invoke->getParent()); |
| 707 | } |
| 708 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 709 | Value *GCResult = ReplaceWithStatepoint(CS, nullptr); |
| 710 | Results.push_back(GCResult); |
| 711 | } |
| 712 | assert(Results.size() == ParsePointNeeded.size()); |
| 713 | |
| 714 | // Adjust all users of the old call sites to use the new ones instead |
| 715 | for (size_t i = 0; i < ParsePointNeeded.size(); i++) { |
| 716 | CallSite &CS = ParsePointNeeded[i]; |
| 717 | Value *GCResult = Results[i]; |
| 718 | if (GCResult) { |
Chen Li | 74ca2a8 | 2015-05-18 19:02:25 +0000 | [diff] [blame^] | 719 | // Can not RAUW for the invoke gc result in case of phi nodes preset. |
| 720 | assert(CS.isCall() || !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin())); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 721 | |
| 722 | // Replace all uses with the new call |
| 723 | CS.getInstruction()->replaceAllUsesWith(GCResult); |
| 724 | } |
| 725 | |
| 726 | // Now that we've handled all uses, remove the original call itself |
| 727 | // Note: The insert point can't be the deleted instruction! |
| 728 | CS.getInstruction()->eraseFromParent(); |
| 729 | } |
| 730 | return modified; |
| 731 | } |
| 732 | |
| 733 | char PlaceBackedgeSafepointsImpl::ID = 0; |
| 734 | char PlaceSafepoints::ID = 0; |
| 735 | |
Philip Reames | 7b98179 | 2015-05-12 21:21:18 +0000 | [diff] [blame] | 736 | FunctionPass *llvm::createPlaceSafepointsPass() { |
| 737 | return new PlaceSafepoints(); |
| 738 | } |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 739 | |
| 740 | INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl, |
| 741 | "place-backedge-safepoints-impl", |
| 742 | "Place Backedge Safepoints", false, false) |
| 743 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
Philip Reames | 57bdac9 | 2015-05-12 20:56:33 +0000 | [diff] [blame] | 744 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Philip Reames | 9f12904 | 2015-05-12 21:09:36 +0000 | [diff] [blame] | 745 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 746 | INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl, |
| 747 | "place-backedge-safepoints-impl", |
| 748 | "Place Backedge Safepoints", false, false) |
| 749 | |
| 750 | INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints", |
| 751 | false, false) |
| 752 | INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints", |
| 753 | false, false) |
| 754 | |
| 755 | static bool isGCLeafFunction(const CallSite &CS) { |
| 756 | Instruction *inst = CS.getInstruction(); |
Aaron Ballman | 94d4d33 | 2015-02-05 13:52:42 +0000 | [diff] [blame] | 757 | if (isa<IntrinsicInst>(inst)) { |
Aaron Ballman | 1b072b3 | 2015-02-05 13:40:04 +0000 | [diff] [blame] | 758 | // Most LLVM intrinsics are things which can never take a safepoint. |
| 759 | // As a result, we don't need to have the stack parsable at the |
| 760 | // callsite. This is a highly useful optimization since intrinsic |
| 761 | // calls are fairly prevelent, particularly in debug builds. |
| 762 | return true; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 763 | } |
| 764 | |
| 765 | // If this function is marked explicitly as a leaf call, we don't need to |
| 766 | // place a safepoint of it. In fact, for correctness we *can't* in many |
| 767 | // cases. Note: Indirect calls return Null for the called function, |
| 768 | // these obviously aren't runtime functions with attributes |
| 769 | // TODO: Support attributes on the call site as well. |
| 770 | const Function *F = CS.getCalledFunction(); |
| 771 | bool isLeaf = |
| 772 | F && |
| 773 | F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true"); |
| 774 | if (isLeaf) { |
| 775 | return true; |
| 776 | } |
| 777 | return false; |
| 778 | } |
| 779 | |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 780 | static void |
Philip Reames | 4d1a3ef | 2015-05-13 00:32:23 +0000 | [diff] [blame] | 781 | InsertSafepointPoll(Instruction *term, |
Philip Reames | 5a9685d | 2015-02-04 00:39:57 +0000 | [diff] [blame] | 782 | std::vector<CallSite> &ParsePointsNeeded /*rval*/) { |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 783 | Module *M = term->getParent()->getParent()->getParent(); |
| 784 | assert(M); |
| 785 | |
| 786 | // Inline the safepoint poll implementation - this will get all the branch, |
| 787 | // control flow, etc.. Most importantly, it will introduce the actual slow |
| 788 | // path call - where we need to insert a safepoint (parsepoint). |
| 789 | FunctionType *ftype = |
| 790 | FunctionType::get(Type::getVoidTy(M->getContext()), false); |
| 791 | assert(ftype && "null?"); |
| 792 | // Note: This cast can fail if there's a function of the same name with a |
| 793 | // different type inserted previously |
| 794 | Function *F = |
| 795 | dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype)); |
Ramkumar Ramachandra | 3edf74f | 2015-02-09 23:02:10 +0000 | [diff] [blame] | 796 | assert(F && "void @gc.safepoint_poll() must be defined"); |
| 797 | assert(!F->empty() && "gc.safepoint_poll must be a non-empty function"); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 798 | CallInst *poll = CallInst::Create(F, "", term); |
| 799 | |
| 800 | // Record some information about the call site we're replacing |
| 801 | BasicBlock *OrigBB = term->getParent(); |
| 802 | BasicBlock::iterator before(poll), after(poll); |
| 803 | bool isBegin(false); |
| 804 | if (before == term->getParent()->begin()) { |
| 805 | isBegin = true; |
| 806 | } else { |
| 807 | before--; |
| 808 | } |
| 809 | after++; |
| 810 | assert(after != poll->getParent()->end() && "must have successor"); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 811 | |
| 812 | // do the actual inlining |
| 813 | InlineFunctionInfo IFI; |
| 814 | bool inlineStatus = InlineFunction(poll, IFI); |
| 815 | assert(inlineStatus && "inline must succeed"); |
Philip Reames | 72634d6 | 2015-02-04 05:11:20 +0000 | [diff] [blame] | 816 | (void)inlineStatus; // suppress warning in release-asserts |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 817 | |
| 818 | // Check post conditions |
| 819 | assert(IFI.StaticAllocas.empty() && "can't have allocs"); |
| 820 | |
| 821 | std::vector<CallInst *> calls; // new calls |
| 822 | std::set<BasicBlock *> BBs; // new BBs + insertee |
| 823 | // Include only the newly inserted instructions, Note: begin may not be valid |
| 824 | // if we inserted to the beginning of the basic block |
| 825 | BasicBlock::iterator start; |
| 826 | if (isBegin) { |
| 827 | start = OrigBB->begin(); |
| 828 | } else { |
| 829 | start = before; |
| 830 | start++; |
| 831 | } |
| 832 | |
| 833 | // If your poll function includes an unreachable at the end, that's not |
| 834 | // valid. Bugpoint likes to create this, so check for it. |
| 835 | assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) && |
| 836 | "malformed poll function"); |
| 837 | |
| 838 | scanInlinedCode(&*(start), &*(after), calls, BBs); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 839 | assert(!calls.empty() && "slow path not found for safepoint poll"); |
| 840 | |
| 841 | // Record the fact we need a parsable state at the runtime call contained in |
| 842 | // the poll function. This is required so that the runtime knows how to |
| 843 | // parse the last frame when we actually take the safepoint (i.e. execute |
| 844 | // the slow path) |
| 845 | assert(ParsePointsNeeded.empty()); |
| 846 | for (size_t i = 0; i < calls.size(); i++) { |
| 847 | |
| 848 | // No safepoint needed or wanted |
| 849 | if (!needsStatepoint(calls[i])) { |
| 850 | continue; |
| 851 | } |
| 852 | |
| 853 | // These are likely runtime calls. Should we assert that via calling |
| 854 | // convention or something? |
| 855 | ParsePointsNeeded.push_back(CallSite(calls[i])); |
| 856 | } |
| 857 | assert(ParsePointsNeeded.size() <= calls.size()); |
| 858 | } |
| 859 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 860 | /// Replaces the given call site (Call or Invoke) with a gc.statepoint |
| 861 | /// intrinsic with an empty deoptimization arguments list. This does |
| 862 | /// NOT do explicit relocation for GC support. |
| 863 | static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */ |
| 864 | Pass *P) { |
NAKAMURA Takumi | 2a5bd54 | 2015-05-07 10:18:46 +0000 | [diff] [blame] | 865 | assert(CS.getInstruction()->getParent()->getParent()->getParent() && |
| 866 | "must be set"); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 867 | |
| 868 | // TODO: technically, a pass is not allowed to get functions from within a |
| 869 | // function pass since it might trigger a new function addition. Refactor |
| 870 | // this logic out to the initialization of the pass. Doesn't appear to |
| 871 | // matter in practice. |
| 872 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 873 | // Then go ahead and use the builder do actually do the inserts. We insert |
| 874 | // immediately before the previous instruction under the assumption that all |
| 875 | // arguments will be available here. We can't insert afterwards since we may |
| 876 | // be replacing a terminator. |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 877 | IRBuilder<> Builder(CS.getInstruction()); |
Philip Reames | b1ed02f | 2015-02-09 21:48:05 +0000 | [diff] [blame] | 878 | |
| 879 | // Note: The gc args are not filled in at this time, that's handled by |
| 880 | // RewriteStatepointsForGC (which is currently under review). |
| 881 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 882 | // Create the statepoint given all the arguments |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 883 | Instruction *Token = nullptr; |
Sanjoy Das | ba74e64 | 2015-05-13 20:11:31 +0000 | [diff] [blame] | 884 | |
| 885 | uint64_t ID; |
| 886 | uint32_t NumPatchBytes; |
| 887 | |
| 888 | AttributeSet OriginalAttrs = CS.getAttributes(); |
| 889 | Attribute AttrID = |
| 890 | OriginalAttrs.getAttribute(AttributeSet::FunctionIndex, "statepoint-id"); |
| 891 | Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute( |
| 892 | AttributeSet::FunctionIndex, "statepoint-num-patch-bytes"); |
| 893 | |
| 894 | AttrBuilder AttrsToRemove; |
| 895 | bool HasID = AttrID.isStringAttribute() && |
| 896 | !AttrID.getValueAsString().getAsInteger(10, ID); |
| 897 | |
| 898 | if (HasID) |
| 899 | AttrsToRemove.addAttribute("statepoint-id"); |
| 900 | else |
| 901 | ID = 0xABCDEF00; |
| 902 | |
| 903 | bool HasNumPatchBytes = |
| 904 | AttrNumPatchBytes.isStringAttribute() && |
| 905 | !AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes); |
| 906 | |
| 907 | if (HasNumPatchBytes) |
| 908 | AttrsToRemove.addAttribute("statepoint-num-patch-bytes"); |
| 909 | else |
| 910 | NumPatchBytes = 0; |
| 911 | |
| 912 | OriginalAttrs = OriginalAttrs.removeAttributes( |
| 913 | CS.getInstruction()->getContext(), AttributeSet::FunctionIndex, |
| 914 | AttrsToRemove); |
| 915 | |
| 916 | Value *StatepointTarget = NumPatchBytes == 0 |
| 917 | ? CS.getCalledValue() |
| 918 | : ConstantPointerNull::get(cast<PointerType>( |
| 919 | CS.getCalledValue()->getType())); |
Sanjoy Das | abf1560 | 2015-05-06 23:53:21 +0000 | [diff] [blame] | 920 | |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 921 | if (CS.isCall()) { |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 922 | CallInst *ToReplace = cast<CallInst>(CS.getInstruction()); |
Sanjoy Das | abe1c68 | 2015-05-06 23:53:09 +0000 | [diff] [blame] | 923 | CallInst *Call = Builder.CreateGCStatepointCall( |
Sanjoy Das | ba74e64 | 2015-05-13 20:11:31 +0000 | [diff] [blame] | 924 | ID, NumPatchBytes, StatepointTarget, |
| 925 | makeArrayRef(CS.arg_begin(), CS.arg_end()), None, None, |
| 926 | "safepoint_token"); |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 927 | Call->setTailCall(ToReplace->isTailCall()); |
| 928 | Call->setCallingConv(ToReplace->getCallingConv()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 929 | |
Sanjoy Das | abf1560 | 2015-05-06 23:53:21 +0000 | [diff] [blame] | 930 | // In case if we can handle this set of attributes - set up function |
| 931 | // attributes directly on statepoint and return attributes later for |
| 932 | // gc_result intrinsic. |
| 933 | Call->setAttributes(OriginalAttrs.getFnAttributes()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 934 | |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 935 | Token = Call; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 936 | |
| 937 | // Put the following gc_result and gc_relocate calls immediately after the |
Sanjoy Das | abf1560 | 2015-05-06 23:53:21 +0000 | [diff] [blame] | 938 | // the old call (which we're about to delete). |
| 939 | assert(ToReplace->getNextNode() && "not a terminator, must have next"); |
| 940 | Builder.SetInsertPoint(ToReplace->getNextNode()); |
| 941 | Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 942 | } else if (CS.isInvoke()) { |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 943 | InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 944 | |
| 945 | // Insert the new invoke into the old block. We'll remove the old one in a |
| 946 | // moment at which point this will become the new terminator for the |
| 947 | // original block. |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 948 | Builder.SetInsertPoint(ToReplace->getParent()); |
| 949 | InvokeInst *Invoke = Builder.CreateGCStatepointInvoke( |
Sanjoy Das | ba74e64 | 2015-05-13 20:11:31 +0000 | [diff] [blame] | 950 | ID, NumPatchBytes, StatepointTarget, ToReplace->getNormalDest(), |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 951 | ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()), |
Sanjoy Das | 8045810 | 2015-05-15 00:26:15 +0000 | [diff] [blame] | 952 | None, None, "safepoint_token"); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 953 | |
Sanjoy Das | 2c26614 | 2015-05-15 00:26:21 +0000 | [diff] [blame] | 954 | Invoke->setCallingConv(ToReplace->getCallingConv()); |
| 955 | |
Sanjoy Das | abf1560 | 2015-05-06 23:53:21 +0000 | [diff] [blame] | 956 | // In case if we can handle this set of attributes - set up function |
| 957 | // attributes directly on statepoint and return attributes later for |
| 958 | // gc_result intrinsic. |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 959 | Invoke->setAttributes(OriginalAttrs.getFnAttributes()); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 960 | |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 961 | Token = Invoke; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 962 | |
| 963 | // We'll insert the gc.result into the normal block |
Igor Laevsky | 5e23e16 | 2015-05-08 11:59:09 +0000 | [diff] [blame] | 964 | BasicBlock *NormalDest = ToReplace->getNormalDest(); |
| 965 | // Can not insert gc.result in case of phi nodes preset. |
| 966 | // Should have removed this cases prior to runnning this function |
| 967 | assert(!isa<PHINode>(NormalDest->begin())); |
| 968 | Instruction *IP = &*(NormalDest->getFirstInsertionPt()); |
| 969 | Builder.SetInsertPoint(IP); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 970 | } else { |
| 971 | llvm_unreachable("unexpect type of CallSite"); |
| 972 | } |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 973 | assert(Token); |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 974 | |
| 975 | // Handle the return value of the original call - update all uses to use a |
| 976 | // gc_result hanging off the statepoint node we just inserted |
| 977 | |
| 978 | // Only add the gc_result iff there is actually a used result |
| 979 | if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) { |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 980 | std::string TakenName = |
| 981 | CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : ""; |
| 982 | CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName); |
Sanjoy Das | abf1560 | 2015-05-06 23:53:21 +0000 | [diff] [blame] | 983 | GCResult->setAttributes(OriginalAttrs.getRetAttributes()); |
Sanjoy Das | 93abd81 | 2015-05-06 23:53:19 +0000 | [diff] [blame] | 984 | return GCResult; |
Philip Reames | 47cc673 | 2015-02-04 00:37:33 +0000 | [diff] [blame] | 985 | } else { |
| 986 | // No return value for the call. |
| 987 | return nullptr; |
| 988 | } |
| 989 | } |