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