blob: 1473e3db7c74822c9a946b7c479bc7e686dd18f2 [file] [log] [blame]
Philip Reames47cc6732015-02-04 00:37:33 +00001//===- 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 Reamesd4a912f2015-02-09 22:44:03 +000014// 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
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +000019// point is represented by a call wrapped in an gc.statepoint intrinsic.
Philip Reamesd4a912f2015-02-09 22:44:03 +000020// - 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
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000030// are necessary to ensure a finite period between poll sites. This is not
Philip Reamesd4a912f2015-02-09 22:44:03 +000031// 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 Reames47cc6732015-02-04 00:37:33 +000039// This pass will insert:
Philip Reamesd4a912f2015-02-09 22:44:03 +000040// - 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 Reames47cc6732015-02-04 00:37:33 +000044//
Philip Reamesd4a912f2015-02-09 22:44:03 +000045// 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 Reames47cc6732015-02-04 00:37:33 +000048//
49//===----------------------------------------------------------------------===//
50
51#include "llvm/Pass.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000052#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000053#include "llvm/ADT/SetOperations.h"
Philip Reames5708cca2015-05-12 20:43:48 +000054#include "llvm/ADT/SetVector.h"
Philip Reames47cc6732015-02-04 00:37:33 +000055#include "llvm/ADT/Statistic.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000056#include "llvm/ADT/StringRef.h"
Philip Reames47cc6732015-02-04 00:37:33 +000057#include "llvm/Analysis/LoopPass.h"
58#include "llvm/Analysis/LoopInfo.h"
59#include "llvm/Analysis/ScalarEvolution.h"
60#include "llvm/Analysis/ScalarEvolutionExpressions.h"
61#include "llvm/Analysis/CFG.h"
62#include "llvm/Analysis/InstructionSimplify.h"
63#include "llvm/IR/BasicBlock.h"
64#include "llvm/IR/CallSite.h"
65#include "llvm/IR/Dominators.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/InstIterator.h"
69#include "llvm/IR/Instructions.h"
70#include "llvm/IR/Intrinsics.h"
71#include "llvm/IR/IntrinsicInst.h"
72#include "llvm/IR/Module.h"
73#include "llvm/IR/Statepoint.h"
74#include "llvm/IR/Value.h"
75#include "llvm/IR/Verifier.h"
76#include "llvm/Support/Debug.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/raw_ostream.h"
79#include "llvm/Transforms/Scalar.h"
80#include "llvm/Transforms/Utils/BasicBlockUtils.h"
81#include "llvm/Transforms/Utils/Cloning.h"
82#include "llvm/Transforms/Utils/Local.h"
83
84#define DEBUG_TYPE "safepoint-placement"
85STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
86STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
87STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
88
89STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
90STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
91
92using namespace llvm;
93
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000094// Ignore opportunities to avoid placing safepoints on backedges, useful for
Philip Reames47cc6732015-02-04 00:37:33 +000095// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000096static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
97 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000098
Sanjoy Dasf75e15e2015-09-15 01:42:48 +000099/// How narrow does the trip count of a loop have to be to have to be considered
100/// "counted"? Counted loops do not get safepoints at backedges.
101static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
102 cl::Hidden, cl::init(32));
Philip Reames47cc6732015-02-04 00:37:33 +0000103
104// If true, split the backedge of a loop when placing the safepoint, otherwise
105// split the latch block itself. Both are useful to support for
106// experimentation, but in practice, it looks like splitting the backedge
107// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +0000108static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
109 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000110
111// Print tracing output
Philip Reames1f3e5c12015-02-20 23:32:03 +0000112static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000113
114namespace {
115
Philip Reames9f129042015-05-12 21:09:36 +0000116/// An analysis pass whose purpose is to identify each of the backedges in
117/// the function which require a safepoint poll to be inserted.
118struct PlaceBackedgeSafepointsImpl : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000119 static char ID;
120
121 /// The output of the pass - gives a list of each backedge (described by
122 /// pointing at the branch) which need a poll inserted.
123 std::vector<TerminatorInst *> PollLocations;
124
125 /// True unless we're running spp-no-calls in which case we need to disable
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000126 /// the call-dependent placement opts.
Philip Reames47cc6732015-02-04 00:37:33 +0000127 bool CallSafepointsEnabled;
Philip Reames9f129042015-05-12 21:09:36 +0000128
129 ScalarEvolution *SE = nullptr;
130 DominatorTree *DT = nullptr;
131 LoopInfo *LI = nullptr;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000132
Philip Reames47cc6732015-02-04 00:37:33 +0000133 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
Philip Reames9f129042015-05-12 21:09:36 +0000134 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000135 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000136 }
137
Philip Reames9f129042015-05-12 21:09:36 +0000138 bool runOnLoop(Loop *);
139 void runOnLoopAndSubLoops(Loop *L) {
140 // Visit all the subloops
141 for (auto I = L->begin(), E = L->end(); I != E; I++)
142 runOnLoopAndSubLoops(*I);
143 runOnLoop(L);
144 }
Justin Bogner383749a2015-05-12 21:49:47 +0000145
146 bool runOnFunction(Function &F) override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000147 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Philip Reames9f129042015-05-12 21:09:36 +0000148 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
149 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
150 for (auto I = LI->begin(), E = LI->end(); I != E; I++) {
151 runOnLoopAndSubLoops(*I);
152 }
153 return false;
154 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000155
Philip Reames47cc6732015-02-04 00:37:33 +0000156 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000157 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000158 AU.addRequired<ScalarEvolutionWrapperPass>();
Philip Reames9f129042015-05-12 21:09:36 +0000159 AU.addRequired<LoopInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000160 // We no longer modify the IR at all in this pass. Thus all
161 // analysis are preserved.
162 AU.setPreservesAll();
163 }
164};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000165}
Philip Reames47cc6732015-02-04 00:37:33 +0000166
Philip Reames1f3e5c12015-02-20 23:32:03 +0000167static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
168static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
169static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000170
171namespace {
Philip Reames7b981792015-05-12 21:21:18 +0000172struct PlaceSafepoints : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000173 static char ID; // Pass identification, replacement for typeid
174
Philip Reames7b981792015-05-12 21:21:18 +0000175 PlaceSafepoints() : FunctionPass(ID) {
Philip Reames47cc6732015-02-04 00:37:33 +0000176 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000177 }
Philip Reames7b981792015-05-12 21:21:18 +0000178 bool runOnFunction(Function &F) override;
Philip Reames47cc6732015-02-04 00:37:33 +0000179
180 void getAnalysisUsage(AnalysisUsage &AU) const override {
181 // We modify the graph wholesale (inlining, block insertion, etc). We
182 // preserve nothing at the moment. We could potentially preserve dom tree
183 // if that was worth doing
184 }
185};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000186}
Philip Reames47cc6732015-02-04 00:37:33 +0000187
188// Insert a safepoint poll immediately before the given instruction. Does
189// not handle the parsability of state at the runtime call, that's the
190// callers job.
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000191static void
Philip Reames388402452015-05-26 21:03:23 +0000192InsertSafepointPoll(Instruction *InsertBefore,
Philip Reames5a9685d2015-02-04 00:39:57 +0000193 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
Philip Reames47cc6732015-02-04 00:37:33 +0000194
195static bool isGCLeafFunction(const CallSite &CS);
196
197static bool needsStatepoint(const CallSite &CS) {
198 if (isGCLeafFunction(CS))
199 return false;
200 if (CS.isCall()) {
201 CallInst *call = cast<CallInst>(CS.getInstruction());
202 if (call->isInlineAsm())
203 return false;
204 }
205 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
206 return false;
207 }
208 return true;
209}
210
Philip Reames5a9685d2015-02-04 00:39:57 +0000211static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
Philip Reames47cc6732015-02-04 00:37:33 +0000212
213/// Returns true if this loop is known to contain a call safepoint which
214/// must unconditionally execute on any iteration of the loop which returns
215/// to the loop header via an edge from Pred. Returns a conservative correct
216/// answer; i.e. false is always valid.
217static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
218 BasicBlock *Pred,
219 DominatorTree &DT) {
220 // In general, we're looking for any cut of the graph which ensures
221 // there's a call safepoint along every edge between Header and Pred.
222 // For the moment, we look only for the 'cuts' that consist of a single call
223 // instruction in a block which is dominated by the Header and dominates the
224 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000225 // of such dominating blocks gets substantially more occurrences than just
Philip Reames47cc6732015-02-04 00:37:33 +0000226 // checking the Pred and Header blocks themselves. This may be due to the
227 // density of loop exit conditions caused by range and null checks.
228 // TODO: structure this as an analysis pass, cache the result for subloops,
229 // avoid dom tree recalculations
230 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
231
232 BasicBlock *Current = Pred;
233 while (true) {
234 for (Instruction &I : *Current) {
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000235 if (auto CS = CallSite(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000236 // Note: Technically, needing a safepoint isn't quite the right
237 // condition here. We should instead be checking if the target method
238 // has an
239 // unconditional poll. In practice, this is only a theoretical concern
240 // since we don't have any methods with conditional-only safepoint
241 // polls.
242 if (needsStatepoint(CS))
243 return true;
244 }
245
246 if (Current == Header)
247 break;
248 Current = DT.getNode(Current)->getIDom()->getBlock();
249 }
250
251 return false;
252}
253
254/// Returns true if this loop is known to terminate in a finite number of
255/// iterations. Note that this function may return false for a loop which
256/// does actual terminate in a finite constant number of iterations due to
257/// conservatism in the analysis.
258static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000259 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000260 // A conservative bound on the loop as a whole.
261 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000262 if (MaxTrips != SE->getCouldNotCompute() &&
263 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
264 CountedLoopTripWidth))
265 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000266
267 // If this is a conditional branch to the header with the alternate path
268 // being outside the loop, we can ask questions about the execution frequency
269 // of the exit block.
270 if (L->isLoopExiting(Pred)) {
271 // This returns an exact expression only. TODO: We really only need an
272 // upper bound here, but SE doesn't expose that.
273 const SCEV *MaxExec = SE->getExitCount(L, Pred);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000274 if (MaxExec != SE->getCouldNotCompute() &&
275 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
276 CountedLoopTripWidth))
Philip Reames47cc6732015-02-04 00:37:33 +0000277 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000278 }
279
280 return /* not finite */ false;
281}
282
283static void scanOneBB(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000284 std::vector<CallInst *> &calls,
285 std::set<BasicBlock *> &seen,
286 std::vector<BasicBlock *> &worklist) {
Philip Reames47cc6732015-02-04 00:37:33 +0000287 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 Reamesa29de872015-02-09 22:26:11 +0000300 for (BasicBlock *Succ : successors(BB)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000301 if (seen.count(Succ) == 0) {
302 worklist.push_back(Succ);
303 seen.insert(Succ);
304 }
305 }
306 }
307 }
308}
309static void scanInlinedCode(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000310 std::vector<CallInst *> &calls,
311 std::set<BasicBlock *> &seen) {
Philip Reames47cc6732015-02-04 00:37:33 +0000312 calls.clear();
313 std::vector<BasicBlock *> worklist;
314 seen.insert(start->getParent());
315 scanOneBB(start, end, calls, seen, worklist);
316 while (!worklist.empty()) {
317 BasicBlock *BB = worklist.back();
318 worklist.pop_back();
319 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
320 }
321}
322
Philip Reames9f129042015-05-12 21:09:36 +0000323bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
Philip Reames5708cca2015-05-12 20:43:48 +0000324 // Loop through all loop latches (branches controlling backedges). We need
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000325 // to place a safepoint on every backedge (potentially).
Philip Reames5708cca2015-05-12 20:43:48 +0000326 // Note: In common usage, there will be only one edge due to LoopSimplify
327 // having run sometime earlier in the pipeline, but this code must be correct
328 // w.r.t. loops with multiple backedges.
Philip Reames47cc6732015-02-04 00:37:33 +0000329 BasicBlock *header = L->getHeader();
Philip Reames5708cca2015-05-12 20:43:48 +0000330 SmallVector<BasicBlock*, 16> LoopLatches;
331 L->getLoopLatches(LoopLatches);
332 for (BasicBlock *pred : LoopLatches) {
333 assert(L->contains(pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000334
335 // Make a policy decision about whether this loop needs a safepoint or
336 // not. Note that this is about unburdening the optimizer in loops, not
337 // avoiding the runtime cost of the actual safepoint.
338 if (!AllBackedges) {
339 if (mustBeFiniteCountedLoop(L, SE, pred)) {
340 if (TraceLSP)
341 errs() << "skipping safepoint placement in finite loop\n";
342 FiniteExecution++;
343 continue;
344 }
345 if (CallSafepointsEnabled &&
Philip Reames57bdac92015-05-12 20:56:33 +0000346 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000347 // Note: This is only semantically legal since we won't do any further
348 // IPO or inlining before the actual call insertion.. If we hadn't, we
349 // might latter loose this call safepoint.
350 if (TraceLSP)
351 errs() << "skipping safepoint placement due to unconditional call\n";
352 CallInLoop++;
353 continue;
354 }
355 }
356
357 // TODO: We can create an inner loop which runs a finite number of
358 // iterations with an outer loop which contains a safepoint. This would
359 // not help runtime performance that much, but it might help our ability to
360 // optimize the inner loop.
361
Philip Reames47cc6732015-02-04 00:37:33 +0000362 // Safepoint insertion would involve creating a new basic block (as the
363 // target of the current backedge) which does the safepoint (of all live
364 // variables) and branches to the true header
365 TerminatorInst *term = pred->getTerminator();
366
367 if (TraceLSP) {
368 errs() << "[LSP] terminator instruction: ";
369 term->dump();
370 }
371
372 PollLocations.push_back(term);
373 }
374
Philip Reames5708cca2015-05-12 20:43:48 +0000375 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000376}
377
Philip Reamesd97cdf22015-05-19 23:40:11 +0000378/// Returns true if an entry safepoint is not required before this callsite in
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000379/// the caller function.
Philip Reamesd97cdf22015-05-19 23:40:11 +0000380static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
381 Instruction *Inst = CS.getInstruction();
382 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
383 switch (II->getIntrinsicID()) {
384 case Intrinsic::experimental_gc_statepoint:
385 case Intrinsic::experimental_patchpoint_void:
386 case Intrinsic::experimental_patchpoint_i64:
387 // The can wrap an actual call which may grow the stack by an unbounded
388 // amount or run forever.
389 return false;
390 default:
391 // Most LLVM intrinsics are things which do not expand to actual calls, or
392 // at least if they do, are leaf functions that cause only finite stack
393 // growth. In particular, the optimizer likes to form things like memsets
394 // out of stores in the original IR. Another important example is
Reid Kleckner60381792015-07-07 22:25:32 +0000395 // llvm.localescape which must occur in the entry block. Inserting a
396 // safepoint before it is not legal since it could push the localescape
Philip Reamesd97cdf22015-05-19 23:40:11 +0000397 // out of the entry block.
398 return true;
399 }
400 }
401 return false;
402}
403
Philip Reames47cc6732015-02-04 00:37:33 +0000404static Instruction *findLocationForEntrySafepoint(Function &F,
405 DominatorTree &DT) {
406
407 // Conceptually, this poll needs to be on method entry, but in
408 // practice, we place it as late in the entry block as possible. We
409 // can place it as late as we want as long as it dominates all calls
410 // that can grow the stack. This, combined with backedge polls,
411 // give us all the progress guarantees we need.
412
Philip Reames47cc6732015-02-04 00:37:33 +0000413 // hasNextInstruction and nextInstruction are used to iterate
414 // through a "straight line" execution sequence.
415
416 auto hasNextInstruction = [](Instruction *I) {
417 if (!I->isTerminator()) {
418 return true;
419 }
420 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
421 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
422 };
423
424 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
425 assert(hasNextInstruction(I) &&
426 "first check if there is a next instruction!");
427 if (I->isTerminator()) {
428 return I->getParent()->getUniqueSuccessor()->begin();
429 } else {
430 return std::next(BasicBlock::iterator(I));
431 }
432 };
433
434 Instruction *cursor = nullptr;
435 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
436 cursor = nextInstruction(cursor)) {
437
Philip Reamesd97cdf22015-05-19 23:40:11 +0000438 // We need to ensure a safepoint poll occurs before any 'real' call. The
439 // easiest way to ensure finite execution between safepoints in the face of
440 // recursive and mutually recursive functions is to enforce that each take
441 // a safepoint. Additionally, we need to ensure a poll before any call
442 // which can grow the stack by an unbounded amount. This isn't required
443 // for GC semantics per se, but is a common requirement for languages
444 // which detect stack overflow via guard pages and then throw exceptions.
445 if (auto CS = CallSite(cursor)) {
446 if (doesNotRequireEntrySafepointBefore(CS))
447 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000448 break;
449 }
450 }
451
Philip Reames5a9685d2015-02-04 00:39:57 +0000452 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
453 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000454
Philip Reames52e7a592015-05-26 21:16:42 +0000455 return cursor;
Philip Reames47cc6732015-02-04 00:37:33 +0000456}
457
458/// Identify the list of call sites which need to be have parseable state
459static void findCallSafepoints(Function &F,
460 std::vector<CallSite> &Found /*rval*/) {
461 assert(Found.empty() && "must be empty!");
Nico Rieck78199512015-08-06 19:10:45 +0000462 for (Instruction &I : instructions(F)) {
Philip Reamesa29de872015-02-09 22:26:11 +0000463 Instruction *inst = &I;
Philip Reames47cc6732015-02-04 00:37:33 +0000464 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
465 CallSite CS(inst);
466
467 // No safepoint needed or wanted
468 if (!needsStatepoint(CS)) {
469 continue;
470 }
471
472 Found.push_back(CS);
473 }
474 }
475}
476
477/// Implement a unique function which doesn't require we sort the input
478/// vector. Doing so has the effect of changing the output of a couple of
479/// tests in ways which make them less useful in testing fused safepoints.
480template <typename T> static void unique_unsorted(std::vector<T> &vec) {
481 std::set<T> seen;
482 std::vector<T> tmp;
483 vec.reserve(vec.size());
484 std::swap(tmp, vec);
485 for (auto V : tmp) {
486 if (seen.insert(V).second) {
487 vec.push_back(V);
488 }
489 }
490}
491
Benjamin Kramer82f86522015-06-07 16:36:28 +0000492static const char *const GCSafepointPollName = "gc.safepoint_poll";
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000493
494static bool isGCSafepointPoll(Function &F) {
495 return F.getName().equals(GCSafepointPollName);
496}
497
Philip Reames0b1b3872015-02-21 00:09:09 +0000498/// Returns true if this function should be rewritten to include safepoint
499/// polls and parseable call sites. The main point of this function is to be
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000500/// an extension point for custom logic.
Philip Reames0b1b3872015-02-21 00:09:09 +0000501static bool shouldRewriteFunction(Function &F) {
502 // TODO: This should check the GCStrategy
503 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000504 const char *FunctionGCName = F.getGC();
505 const StringRef StatepointExampleName("statepoint-example");
506 const StringRef CoreCLRName("coreclr");
507 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +0000508 (CoreCLRName == FunctionGCName);
Philip Reames0b1b3872015-02-21 00:09:09 +0000509 } else
510 return false;
511}
512
513// TODO: These should become properties of the GCStrategy, possibly with
514// command line overrides.
515static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
516static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
517static bool enableCallSafepoints(Function &F) { return !NoCall; }
518
Igor Laevsky5e23e162015-05-08 11:59:09 +0000519// Normalize basic block to make it ready to be target of invoke statepoint.
520// Ensure that 'BB' does not have phi nodes. It may require spliting it.
521static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
522 BasicBlock *InvokeParent) {
523 BasicBlock *ret = BB;
524
525 if (!BB->getUniquePredecessor()) {
526 ret = SplitBlockPredecessors(BB, InvokeParent, "");
527 }
528
529 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
530 // from it
531 FoldSingleEntryPHINodes(ret);
532 assert(!isa<PHINode>(ret->begin()));
533
534 return ret;
535}
Philip Reames0b1b3872015-02-21 00:09:09 +0000536
Philip Reames47cc6732015-02-04 00:37:33 +0000537bool PlaceSafepoints::runOnFunction(Function &F) {
538 if (F.isDeclaration() || F.empty()) {
539 // This is a declaration, nothing to do. Must exit early to avoid crash in
540 // dom tree calculation
541 return false;
542 }
543
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000544 if (isGCSafepointPoll(F)) {
545 // Given we're inlining this inside of safepoint poll insertion, this
546 // doesn't make any sense. Note that we do make any contained calls
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000547 // parseable after we inline a poll.
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000548 return false;
549 }
550
Philip Reames0b1b3872015-02-21 00:09:09 +0000551 if (!shouldRewriteFunction(F))
552 return false;
553
Philip Reames47cc6732015-02-04 00:37:33 +0000554 bool modified = false;
555
556 // In various bits below, we rely on the fact that uses are reachable from
557 // defs. When there are basic blocks unreachable from the entry, dominance
558 // and reachablity queries return non-sensical results. Thus, we preprocess
559 // the function to ensure these properties hold.
560 modified |= removeUnreachableBlocks(F);
561
562 // STEP 1 - Insert the safepoint polling locations. We do not need to
563 // actually insert parse points yet. That will be done for all polls and
564 // calls in a single pass.
565
Philip Reames47cc6732015-02-04 00:37:33 +0000566 DominatorTree DT;
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000567 DT.recalculate(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000568
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000569 SmallVector<Instruction *, 16> PollsNeeded;
Philip Reames47cc6732015-02-04 00:37:33 +0000570 std::vector<CallSite> ParsePointNeeded;
571
Philip Reames0b1b3872015-02-21 00:09:09 +0000572 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000573 // Construct a pass manager to run the LoopPass backedge logic. We
574 // need the pass manager to handle scheduling all the loop passes
575 // appropriately. Doing this by hand is painful and just not worth messing
576 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000577 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000578 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000579 PlaceBackedgeSafepointsImpl *PBS =
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000580 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000581 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000582 FPM.run(F);
583
584 // We preserve dominance information when inserting the poll, otherwise
585 // we'd have to recalculate this on every insert
586 DT.recalculate(F);
587
Philip Reames5708cca2015-05-12 20:43:48 +0000588 auto &PollLocations = PBS->PollLocations;
589
590 auto OrderByBBName = [](Instruction *a, Instruction *b) {
591 return a->getParent()->getName() < b->getParent()->getName();
592 };
593 // We need the order of list to be stable so that naming ends up stable
594 // when we split edges. This makes test cases much easier to write.
595 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
596
597 // We can sometimes end up with duplicate poll locations. This happens if
598 // a single loop is visited more than once. The fact this happens seems
599 // wrong, but it does happen for the split-backedge.ll test case.
600 PollLocations.erase(std::unique(PollLocations.begin(),
601 PollLocations.end()),
602 PollLocations.end());
603
Philip Reames47cc6732015-02-04 00:37:33 +0000604 // Insert a poll at each point the analysis pass identified
Philip Reames89fe5702015-05-12 23:39:23 +0000605 // The poll location must be the terminator of a loop latch block.
606 for (TerminatorInst *Term : PollLocations) {
Philip Reames47cc6732015-02-04 00:37:33 +0000607 // We are inserting a poll, the function is modified
608 modified = true;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000609
Philip Reames47cc6732015-02-04 00:37:33 +0000610 if (SplitBackedge) {
611 // Split the backedge of the loop and insert the poll within that new
612 // basic block. This creates a loop with two latches per original
613 // latch (which is non-ideal), but this appears to be easier to
614 // optimize in practice than inserting the poll immediately before the
615 // latch test.
616
617 // Since this is a latch, at least one of the successors must dominate
618 // it. Its possible that we have a) duplicate edges to the same header
619 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000620 // each.
621 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000622 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
623 BasicBlock *Succ = Term->getSuccessor(i);
624 if (DT.dominates(Succ, Term->getParent())) {
625 Headers.insert(Succ);
626 }
627 }
628 assert(!Headers.empty() && "poll location is not a loop latch?");
629
630 // The split loop structure here is so that we only need to recalculate
631 // the dominator tree once. Alternatively, we could just keep it up to
632 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000633 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000634 for (BasicBlock *Header : Headers) {
Philip Reames89fe5702015-05-12 23:39:23 +0000635 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000636 PollsNeeded.push_back(NewBB->getTerminator());
Philip Reames47cc6732015-02-04 00:37:33 +0000637 NumBackedgeSafepoints++;
638 }
Philip Reames47cc6732015-02-04 00:37:33 +0000639 } else {
640 // Split the latch block itself, right before the terminator.
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000641 PollsNeeded.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000642 NumBackedgeSafepoints++;
643 }
Philip Reames47cc6732015-02-04 00:37:33 +0000644 }
645 }
646
Philip Reames0b1b3872015-02-21 00:09:09 +0000647 if (enableEntrySafepoints(F)) {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000648 Instruction *Location = findLocationForEntrySafepoint(F, DT);
649 if (!Location) {
Philip Reames47cc6732015-02-04 00:37:33 +0000650 // policy choice not to insert?
651 } else {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000652 PollsNeeded.push_back(Location);
Philip Reames47cc6732015-02-04 00:37:33 +0000653 modified = true;
654 NumEntrySafepoints++;
Philip Reames47cc6732015-02-04 00:37:33 +0000655 }
656 }
657
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000658 // Now that we've identified all the needed safepoint poll locations, insert
659 // safepoint polls themselves.
660 for (Instruction *PollLocation : PollsNeeded) {
661 std::vector<CallSite> RuntimeCalls;
662 InsertSafepointPoll(PollLocation, RuntimeCalls);
663 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
664 RuntimeCalls.end());
665 }
666 PollsNeeded.clear(); // make sure we don't accidentally use
667 // The dominator tree has been invalidated by the inlining performed in the
668 // above loop. TODO: Teach the inliner how to update the dom tree?
669 DT.recalculate(F);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000670
Philip Reames0b1b3872015-02-21 00:09:09 +0000671 if (enableCallSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000672 std::vector<CallSite> Calls;
673 findCallSafepoints(F, Calls);
674 NumCallSafepoints += Calls.size();
Philip Reames5a9685d2015-02-04 00:39:57 +0000675 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000676 }
677
678 // Unique the vectors since we can end up with duplicates if we scan the call
679 // site for call safepoints after we add it for entry or backedge. The
680 // only reason we need tracking at all is that some functions might have
681 // polls but not call safepoints and thus we might miss marking the runtime
682 // calls for the polls. (This is useful in test cases!)
683 unique_unsorted(ParsePointNeeded);
684
685 // Any parse point (no matter what source) will be handled here
Philip Reames47cc6732015-02-04 00:37:33 +0000686
687 // We're about to start modifying the function
688 if (!ParsePointNeeded.empty())
689 modified = true;
690
691 // Now run through and insert the safepoints, but do _NOT_ update or remove
692 // any existing uses. We have references to live variables that need to
693 // survive to the last iteration of this loop.
694 std::vector<Value *> Results;
695 Results.reserve(ParsePointNeeded.size());
696 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
697 CallSite &CS = ParsePointNeeded[i];
Igor Laevsky5e23e162015-05-08 11:59:09 +0000698
699 // For invoke statepoints we need to remove all phi nodes at the normal
700 // destination block.
701 // Reason for this is that we can place gc_result only after last phi node
702 // in basic block. We will get malformed code after RAUW for the
703 // gc_result if one of this phi nodes uses result from the invoke.
704 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
705 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
706 Invoke->getParent());
707 }
708
Philip Reames47cc6732015-02-04 00:37:33 +0000709 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
710 Results.push_back(GCResult);
711 }
712 assert(Results.size() == ParsePointNeeded.size());
713
714 // Adjust all users of the old call sites to use the new ones instead
715 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
716 CallSite &CS = ParsePointNeeded[i];
717 Value *GCResult = Results[i];
718 if (GCResult) {
Chen Li74ca2a82015-05-18 19:02:25 +0000719 // Can not RAUW for the invoke gc result in case of phi nodes preset.
720 assert(CS.isCall() || !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
Philip Reames47cc6732015-02-04 00:37:33 +0000721
722 // Replace all uses with the new call
723 CS.getInstruction()->replaceAllUsesWith(GCResult);
724 }
725
726 // Now that we've handled all uses, remove the original call itself
727 // Note: The insert point can't be the deleted instruction!
728 CS.getInstruction()->eraseFromParent();
729 }
730 return modified;
731}
732
733char PlaceBackedgeSafepointsImpl::ID = 0;
734char PlaceSafepoints::ID = 0;
735
Philip Reames7b981792015-05-12 21:21:18 +0000736FunctionPass *llvm::createPlaceSafepointsPass() {
737 return new PlaceSafepoints();
738}
Philip Reames47cc6732015-02-04 00:37:33 +0000739
740INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
741 "place-backedge-safepoints-impl",
742 "Place Backedge Safepoints", false, false)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000743INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Philip Reames57bdac92015-05-12 20:56:33 +0000744INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames9f129042015-05-12 21:09:36 +0000745INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000746INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
747 "place-backedge-safepoints-impl",
748 "Place Backedge Safepoints", false, false)
749
750INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
751 false, false)
752INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
753 false, false)
754
755static bool isGCLeafFunction(const CallSite &CS) {
756 Instruction *inst = CS.getInstruction();
Aaron Ballman94d4d332015-02-05 13:52:42 +0000757 if (isa<IntrinsicInst>(inst)) {
Aaron Ballman1b072b32015-02-05 13:40:04 +0000758 // Most LLVM intrinsics are things which can never take a safepoint.
759 // As a result, we don't need to have the stack parsable at the
760 // callsite. This is a highly useful optimization since intrinsic
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000761 // calls are fairly prevalent, particularly in debug builds.
Aaron Ballman1b072b32015-02-05 13:40:04 +0000762 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000763 }
764
765 // If this function is marked explicitly as a leaf call, we don't need to
766 // place a safepoint of it. In fact, for correctness we *can't* in many
767 // cases. Note: Indirect calls return Null for the called function,
768 // these obviously aren't runtime functions with attributes
769 // TODO: Support attributes on the call site as well.
770 const Function *F = CS.getCalledFunction();
771 bool isLeaf =
772 F &&
773 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
774 if (isLeaf) {
775 return true;
776 }
777 return false;
778}
779
Philip Reames5a9685d2015-02-04 00:39:57 +0000780static void
Philip Reames388402452015-05-26 21:03:23 +0000781InsertSafepointPoll(Instruction *InsertBefore,
Philip Reames5a9685d2015-02-04 00:39:57 +0000782 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
Philip Reames388402452015-05-26 21:03:23 +0000783 BasicBlock *OrigBB = InsertBefore->getParent();
784 Module *M = InsertBefore->getModule();
785 assert(M && "must be part of a module");
Philip Reames47cc6732015-02-04 00:37:33 +0000786
787 // Inline the safepoint poll implementation - this will get all the branch,
788 // control flow, etc.. Most importantly, it will introduce the actual slow
789 // path call - where we need to insert a safepoint (parsepoint).
Philip Reames388402452015-05-26 21:03:23 +0000790
791 auto *F = M->getFunction(GCSafepointPollName);
792 assert(F->getType()->getElementType() ==
793 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
794 "gc.safepoint_poll declared with wrong type");
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000795 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames388402452015-05-26 21:03:23 +0000796 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
Philip Reames47cc6732015-02-04 00:37:33 +0000797
798 // Record some information about the call site we're replacing
Philip Reames388402452015-05-26 21:03:23 +0000799 BasicBlock::iterator before(PollCall), after(PollCall);
Philip Reames47cc6732015-02-04 00:37:33 +0000800 bool isBegin(false);
Philip Reames388402452015-05-26 21:03:23 +0000801 if (before == OrigBB->begin()) {
Philip Reames47cc6732015-02-04 00:37:33 +0000802 isBegin = true;
803 } else {
804 before--;
805 }
806 after++;
Philip Reames388402452015-05-26 21:03:23 +0000807 assert(after != OrigBB->end() && "must have successor");
Philip Reames47cc6732015-02-04 00:37:33 +0000808
809 // do the actual inlining
810 InlineFunctionInfo IFI;
Philip Reames388402452015-05-26 21:03:23 +0000811 bool InlineStatus = InlineFunction(PollCall, IFI);
812 assert(InlineStatus && "inline must succeed");
813 (void)InlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000814
815 // Check post conditions
816 assert(IFI.StaticAllocas.empty() && "can't have allocs");
817
818 std::vector<CallInst *> calls; // new calls
819 std::set<BasicBlock *> BBs; // new BBs + insertee
820 // Include only the newly inserted instructions, Note: begin may not be valid
821 // if we inserted to the beginning of the basic block
822 BasicBlock::iterator start;
823 if (isBegin) {
824 start = OrigBB->begin();
825 } else {
826 start = before;
827 start++;
828 }
829
830 // If your poll function includes an unreachable at the end, that's not
831 // valid. Bugpoint likes to create this, so check for it.
832 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
833 "malformed poll function");
834
835 scanInlinedCode(&*(start), &*(after), calls, BBs);
Philip Reames47cc6732015-02-04 00:37:33 +0000836 assert(!calls.empty() && "slow path not found for safepoint poll");
837
838 // Record the fact we need a parsable state at the runtime call contained in
839 // the poll function. This is required so that the runtime knows how to
840 // parse the last frame when we actually take the safepoint (i.e. execute
841 // the slow path)
842 assert(ParsePointsNeeded.empty());
843 for (size_t i = 0; i < calls.size(); i++) {
844
845 // No safepoint needed or wanted
846 if (!needsStatepoint(calls[i])) {
847 continue;
848 }
849
850 // These are likely runtime calls. Should we assert that via calling
851 // convention or something?
852 ParsePointsNeeded.push_back(CallSite(calls[i]));
853 }
854 assert(ParsePointsNeeded.size() <= calls.size());
855}
856
Philip Reames47cc6732015-02-04 00:37:33 +0000857/// Replaces the given call site (Call or Invoke) with a gc.statepoint
858/// intrinsic with an empty deoptimization arguments list. This does
859/// NOT do explicit relocation for GC support.
860static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
861 Pass *P) {
NAKAMURA Takumi2a5bd542015-05-07 10:18:46 +0000862 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
863 "must be set");
Philip Reames47cc6732015-02-04 00:37:33 +0000864
865 // TODO: technically, a pass is not allowed to get functions from within a
866 // function pass since it might trigger a new function addition. Refactor
867 // this logic out to the initialization of the pass. Doesn't appear to
868 // matter in practice.
869
Philip Reames47cc6732015-02-04 00:37:33 +0000870 // Then go ahead and use the builder do actually do the inserts. We insert
871 // immediately before the previous instruction under the assumption that all
872 // arguments will be available here. We can't insert afterwards since we may
873 // be replacing a terminator.
Sanjoy Das93abd812015-05-06 23:53:19 +0000874 IRBuilder<> Builder(CS.getInstruction());
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000875
876 // Note: The gc args are not filled in at this time, that's handled by
877 // RewriteStatepointsForGC (which is currently under review).
878
Philip Reames47cc6732015-02-04 00:37:33 +0000879 // Create the statepoint given all the arguments
Sanjoy Das93abd812015-05-06 23:53:19 +0000880 Instruction *Token = nullptr;
Sanjoy Dasba74e642015-05-13 20:11:31 +0000881
882 uint64_t ID;
883 uint32_t NumPatchBytes;
884
885 AttributeSet OriginalAttrs = CS.getAttributes();
886 Attribute AttrID =
887 OriginalAttrs.getAttribute(AttributeSet::FunctionIndex, "statepoint-id");
888 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
889 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
890
891 AttrBuilder AttrsToRemove;
892 bool HasID = AttrID.isStringAttribute() &&
893 !AttrID.getValueAsString().getAsInteger(10, ID);
894
895 if (HasID)
896 AttrsToRemove.addAttribute("statepoint-id");
897 else
898 ID = 0xABCDEF00;
899
900 bool HasNumPatchBytes =
901 AttrNumPatchBytes.isStringAttribute() &&
902 !AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
903
904 if (HasNumPatchBytes)
905 AttrsToRemove.addAttribute("statepoint-num-patch-bytes");
906 else
907 NumPatchBytes = 0;
908
909 OriginalAttrs = OriginalAttrs.removeAttributes(
910 CS.getInstruction()->getContext(), AttributeSet::FunctionIndex,
911 AttrsToRemove);
912
Philip Reames47cc6732015-02-04 00:37:33 +0000913 if (CS.isCall()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000914 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Dasabe1c682015-05-06 23:53:09 +0000915 CallInst *Call = Builder.CreateGCStatepointCall(
Sanjoy Dascfe41f02015-07-28 23:50:30 +0000916 ID, NumPatchBytes, CS.getCalledValue(),
Sanjoy Dasba74e642015-05-13 20:11:31 +0000917 makeArrayRef(CS.arg_begin(), CS.arg_end()), None, None,
918 "safepoint_token");
Sanjoy Das93abd812015-05-06 23:53:19 +0000919 Call->setTailCall(ToReplace->isTailCall());
920 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reames47cc6732015-02-04 00:37:33 +0000921
Sanjoy Dasabf15602015-05-06 23:53:21 +0000922 // In case if we can handle this set of attributes - set up function
923 // attributes directly on statepoint and return attributes later for
924 // gc_result intrinsic.
925 Call->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000926
Sanjoy Das93abd812015-05-06 23:53:19 +0000927 Token = Call;
Philip Reames47cc6732015-02-04 00:37:33 +0000928
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000929 // Put the following gc_result and gc_relocate calls immediately after
Sanjoy Dasabf15602015-05-06 23:53:21 +0000930 // the old call (which we're about to delete).
931 assert(ToReplace->getNextNode() && "not a terminator, must have next");
932 Builder.SetInsertPoint(ToReplace->getNextNode());
933 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
Philip Reames47cc6732015-02-04 00:37:33 +0000934 } else if (CS.isInvoke()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000935 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reames47cc6732015-02-04 00:37:33 +0000936
937 // Insert the new invoke into the old block. We'll remove the old one in a
938 // moment at which point this will become the new terminator for the
939 // original block.
Sanjoy Das93abd812015-05-06 23:53:19 +0000940 Builder.SetInsertPoint(ToReplace->getParent());
941 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
Sanjoy Dascfe41f02015-07-28 23:50:30 +0000942 ID, NumPatchBytes, CS.getCalledValue(), ToReplace->getNormalDest(),
Sanjoy Das93abd812015-05-06 23:53:19 +0000943 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
Sanjoy Das80458102015-05-15 00:26:15 +0000944 None, None, "safepoint_token");
Philip Reames47cc6732015-02-04 00:37:33 +0000945
Sanjoy Das2c266142015-05-15 00:26:21 +0000946 Invoke->setCallingConv(ToReplace->getCallingConv());
947
Sanjoy Dasabf15602015-05-06 23:53:21 +0000948 // In case if we can handle this set of attributes - set up function
949 // attributes directly on statepoint and return attributes later for
950 // gc_result intrinsic.
Sanjoy Das93abd812015-05-06 23:53:19 +0000951 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000952
Sanjoy Das93abd812015-05-06 23:53:19 +0000953 Token = Invoke;
Philip Reames47cc6732015-02-04 00:37:33 +0000954
955 // We'll insert the gc.result into the normal block
Igor Laevsky5e23e162015-05-08 11:59:09 +0000956 BasicBlock *NormalDest = ToReplace->getNormalDest();
957 // Can not insert gc.result in case of phi nodes preset.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000958 // Should have removed this cases prior to running this function
Igor Laevsky5e23e162015-05-08 11:59:09 +0000959 assert(!isa<PHINode>(NormalDest->begin()));
960 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
961 Builder.SetInsertPoint(IP);
Philip Reames47cc6732015-02-04 00:37:33 +0000962 } else {
963 llvm_unreachable("unexpect type of CallSite");
964 }
Sanjoy Das93abd812015-05-06 23:53:19 +0000965 assert(Token);
Philip Reames47cc6732015-02-04 00:37:33 +0000966
967 // Handle the return value of the original call - update all uses to use a
968 // gc_result hanging off the statepoint node we just inserted
969
970 // Only add the gc_result iff there is actually a used result
971 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000972 std::string TakenName =
973 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
974 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
Sanjoy Dasabf15602015-05-06 23:53:21 +0000975 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
Sanjoy Das93abd812015-05-06 23:53:19 +0000976 return GCResult;
Philip Reames47cc6732015-02-04 00:37:33 +0000977 } else {
978 // No return value for the call.
979 return nullptr;
980 }
981}