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