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