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