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