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