PlaceSafepoints.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Place garbage collection safepoints at appropriate locations in the IR. This
  10. // does not make relocation semantics or variable liveness explicit. That's
  11. // done by RewriteStatepointsForGC.
  12. //
  13. // Terminology:
  14. // - A call is said to be "parseable" if there is a stack map generated for the
  15. // return PC of the call. A runtime can determine where values listed in the
  16. // deopt arguments and (after RewriteStatepointsForGC) gc arguments are located
  17. // on the stack when the code is suspended inside such a call. Every parse
  18. // point is represented by a call wrapped in an gc.statepoint intrinsic.
  19. // - A "poll" is an explicit check in the generated code to determine if the
  20. // runtime needs the generated code to cooperate by calling a helper routine
  21. // and thus suspending its execution at a known state. The call to the helper
  22. // routine will be parseable. The (gc & runtime specific) logic of a poll is
  23. // assumed to be provided in a function of the name "gc.safepoint_poll".
  24. //
  25. // We aim to insert polls such that running code can quickly be brought to a
  26. // well defined state for inspection by the collector. In the current
  27. // implementation, this is done via the insertion of poll sites at method entry
  28. // and the backedge of most loops. We try to avoid inserting more polls than
  29. // are necessary to ensure a finite period between poll sites. This is not
  30. // because the poll itself is expensive in the generated code; it's not. Polls
  31. // do tend to impact the optimizer itself in negative ways; we'd like to avoid
  32. // perturbing the optimization of the method as much as we can.
  33. //
  34. // We also need to make most call sites parseable. The callee might execute a
  35. // poll (or otherwise be inspected by the GC). If so, the entire stack
  36. // (including the suspended frame of the current method) must be parseable.
  37. //
  38. // This pass will insert:
  39. // - Call parse points ("call safepoints") for any call which may need to
  40. // reach a safepoint during the execution of the callee function.
  41. // - Backedge safepoint polls and entry safepoint polls to ensure that
  42. // executing code reaches a safepoint poll in a finite amount of time.
  43. //
  44. // We do not currently support return statepoints, but adding them would not
  45. // be hard. They are not required for correctness - entry safepoints are an
  46. // alternative - but some GCs may prefer them. Patches welcome.
  47. //
  48. //===----------------------------------------------------------------------===//
  49. #include "llvm/InitializePasses.h"
  50. #include "llvm/Pass.h"
  51. #include "llvm/ADT/SetVector.h"
  52. #include "llvm/ADT/Statistic.h"
  53. #include "llvm/Analysis/CFG.h"
  54. #include "llvm/Analysis/ScalarEvolution.h"
  55. #include "llvm/Analysis/TargetLibraryInfo.h"
  56. #include "llvm/Transforms/Utils/Local.h"
  57. #include "llvm/IR/Dominators.h"
  58. #include "llvm/IR/IntrinsicInst.h"
  59. #include "llvm/IR/LegacyPassManager.h"
  60. #include "llvm/IR/Statepoint.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Transforms/Scalar.h"
  64. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  65. #include "llvm/Transforms/Utils/Cloning.h"
  66. #define DEBUG_TYPE "safepoint-placement"
  67. STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
  68. STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
  69. STATISTIC(CallInLoop,
  70. "Number of loops without safepoints due to calls in loop");
  71. STATISTIC(FiniteExecution,
  72. "Number of loops without safepoints finite execution");
  73. using namespace llvm;
  74. // Ignore opportunities to avoid placing safepoints on backedges, useful for
  75. // validation
  76. static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
  77. cl::init(false));
  78. /// How narrow does the trip count of a loop have to be to have to be considered
  79. /// "counted"? Counted loops do not get safepoints at backedges.
  80. static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
  81. cl::Hidden, cl::init(32));
  82. // If true, split the backedge of a loop when placing the safepoint, otherwise
  83. // split the latch block itself. Both are useful to support for
  84. // experimentation, but in practice, it looks like splitting the backedge
  85. // optimizes better.
  86. static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
  87. cl::init(false));
  88. namespace {
  89. /// An analysis pass whose purpose is to identify each of the backedges in
  90. /// the function which require a safepoint poll to be inserted.
  91. struct PlaceBackedgeSafepointsImpl : public FunctionPass {
  92. static char ID;
  93. /// The output of the pass - gives a list of each backedge (described by
  94. /// pointing at the branch) which need a poll inserted.
  95. std::vector<Instruction *> PollLocations;
  96. /// True unless we're running spp-no-calls in which case we need to disable
  97. /// the call-dependent placement opts.
  98. bool CallSafepointsEnabled;
  99. ScalarEvolution *SE = nullptr;
  100. DominatorTree *DT = nullptr;
  101. LoopInfo *LI = nullptr;
  102. TargetLibraryInfo *TLI = nullptr;
  103. PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
  104. : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
  105. initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
  106. }
  107. bool runOnLoop(Loop *);
  108. void runOnLoopAndSubLoops(Loop *L) {
  109. // Visit all the subloops
  110. for (Loop *I : *L)
  111. runOnLoopAndSubLoops(I);
  112. runOnLoop(L);
  113. }
  114. bool runOnFunction(Function &F) override {
  115. SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  116. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  117. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  118. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  119. for (Loop *I : *LI) {
  120. runOnLoopAndSubLoops(I);
  121. }
  122. return false;
  123. }
  124. void getAnalysisUsage(AnalysisUsage &AU) const override {
  125. AU.addRequired<DominatorTreeWrapperPass>();
  126. AU.addRequired<ScalarEvolutionWrapperPass>();
  127. AU.addRequired<LoopInfoWrapperPass>();
  128. AU.addRequired<TargetLibraryInfoWrapperPass>();
  129. // We no longer modify the IR at all in this pass. Thus all
  130. // analysis are preserved.
  131. AU.setPreservesAll();
  132. }
  133. };
  134. }
  135. static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
  136. static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
  137. static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
  138. namespace {
  139. struct PlaceSafepoints : public FunctionPass {
  140. static char ID; // Pass identification, replacement for typeid
  141. PlaceSafepoints() : FunctionPass(ID) {
  142. initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
  143. }
  144. bool runOnFunction(Function &F) override;
  145. void getAnalysisUsage(AnalysisUsage &AU) const override {
  146. // We modify the graph wholesale (inlining, block insertion, etc). We
  147. // preserve nothing at the moment. We could potentially preserve dom tree
  148. // if that was worth doing
  149. AU.addRequired<TargetLibraryInfoWrapperPass>();
  150. }
  151. };
  152. }
  153. // Insert a safepoint poll immediately before the given instruction. Does
  154. // not handle the parsability of state at the runtime call, that's the
  155. // callers job.
  156. static void
  157. InsertSafepointPoll(Instruction *InsertBefore,
  158. std::vector<CallBase *> &ParsePointsNeeded /*rval*/,
  159. const TargetLibraryInfo &TLI);
  160. static bool needsStatepoint(CallBase *Call, const TargetLibraryInfo &TLI) {
  161. if (callsGCLeafFunction(Call, TLI))
  162. return false;
  163. if (auto *CI = dyn_cast<CallInst>(Call)) {
  164. if (CI->isInlineAsm())
  165. return false;
  166. }
  167. return !(isa<GCStatepointInst>(Call) || isa<GCRelocateInst>(Call) ||
  168. isa<GCResultInst>(Call));
  169. }
  170. /// Returns true if this loop is known to contain a call safepoint which
  171. /// must unconditionally execute on any iteration of the loop which returns
  172. /// to the loop header via an edge from Pred. Returns a conservative correct
  173. /// answer; i.e. false is always valid.
  174. static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
  175. BasicBlock *Pred,
  176. DominatorTree &DT,
  177. const TargetLibraryInfo &TLI) {
  178. // In general, we're looking for any cut of the graph which ensures
  179. // there's a call safepoint along every edge between Header and Pred.
  180. // For the moment, we look only for the 'cuts' that consist of a single call
  181. // instruction in a block which is dominated by the Header and dominates the
  182. // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
  183. // of such dominating blocks gets substantially more occurrences than just
  184. // checking the Pred and Header blocks themselves. This may be due to the
  185. // density of loop exit conditions caused by range and null checks.
  186. // TODO: structure this as an analysis pass, cache the result for subloops,
  187. // avoid dom tree recalculations
  188. assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
  189. BasicBlock *Current = Pred;
  190. while (true) {
  191. for (Instruction &I : *Current) {
  192. if (auto *Call = dyn_cast<CallBase>(&I))
  193. // Note: Technically, needing a safepoint isn't quite the right
  194. // condition here. We should instead be checking if the target method
  195. // has an
  196. // unconditional poll. In practice, this is only a theoretical concern
  197. // since we don't have any methods with conditional-only safepoint
  198. // polls.
  199. if (needsStatepoint(Call, TLI))
  200. return true;
  201. }
  202. if (Current == Header)
  203. break;
  204. Current = DT.getNode(Current)->getIDom()->getBlock();
  205. }
  206. return false;
  207. }
  208. /// Returns true if this loop is known to terminate in a finite number of
  209. /// iterations. Note that this function may return false for a loop which
  210. /// does actual terminate in a finite constant number of iterations due to
  211. /// conservatism in the analysis.
  212. static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
  213. BasicBlock *Pred) {
  214. // A conservative bound on the loop as a whole.
  215. const SCEV *MaxTrips = SE->getConstantMaxBackedgeTakenCount(L);
  216. if (!isa<SCEVCouldNotCompute>(MaxTrips) &&
  217. SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
  218. CountedLoopTripWidth))
  219. return true;
  220. // If this is a conditional branch to the header with the alternate path
  221. // being outside the loop, we can ask questions about the execution frequency
  222. // of the exit block.
  223. if (L->isLoopExiting(Pred)) {
  224. // This returns an exact expression only. TODO: We really only need an
  225. // upper bound here, but SE doesn't expose that.
  226. const SCEV *MaxExec = SE->getExitCount(L, Pred);
  227. if (!isa<SCEVCouldNotCompute>(MaxExec) &&
  228. SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
  229. CountedLoopTripWidth))
  230. return true;
  231. }
  232. return /* not finite */ false;
  233. }
  234. static void scanOneBB(Instruction *Start, Instruction *End,
  235. std::vector<CallInst *> &Calls,
  236. DenseSet<BasicBlock *> &Seen,
  237. std::vector<BasicBlock *> &Worklist) {
  238. for (BasicBlock::iterator BBI(Start), BBE0 = Start->getParent()->end(),
  239. BBE1 = BasicBlock::iterator(End);
  240. BBI != BBE0 && BBI != BBE1; BBI++) {
  241. if (CallInst *CI = dyn_cast<CallInst>(&*BBI))
  242. Calls.push_back(CI);
  243. // FIXME: This code does not handle invokes
  244. assert(!isa<InvokeInst>(&*BBI) &&
  245. "support for invokes in poll code needed");
  246. // Only add the successor blocks if we reach the terminator instruction
  247. // without encountering end first
  248. if (BBI->isTerminator()) {
  249. BasicBlock *BB = BBI->getParent();
  250. for (BasicBlock *Succ : successors(BB)) {
  251. if (Seen.insert(Succ).second) {
  252. Worklist.push_back(Succ);
  253. }
  254. }
  255. }
  256. }
  257. }
  258. static void scanInlinedCode(Instruction *Start, Instruction *End,
  259. std::vector<CallInst *> &Calls,
  260. DenseSet<BasicBlock *> &Seen) {
  261. Calls.clear();
  262. std::vector<BasicBlock *> Worklist;
  263. Seen.insert(Start->getParent());
  264. scanOneBB(Start, End, Calls, Seen, Worklist);
  265. while (!Worklist.empty()) {
  266. BasicBlock *BB = Worklist.back();
  267. Worklist.pop_back();
  268. scanOneBB(&*BB->begin(), End, Calls, Seen, Worklist);
  269. }
  270. }
  271. bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
  272. // Loop through all loop latches (branches controlling backedges). We need
  273. // to place a safepoint on every backedge (potentially).
  274. // Note: In common usage, there will be only one edge due to LoopSimplify
  275. // having run sometime earlier in the pipeline, but this code must be correct
  276. // w.r.t. loops with multiple backedges.
  277. BasicBlock *Header = L->getHeader();
  278. SmallVector<BasicBlock*, 16> LoopLatches;
  279. L->getLoopLatches(LoopLatches);
  280. for (BasicBlock *Pred : LoopLatches) {
  281. assert(L->contains(Pred));
  282. // Make a policy decision about whether this loop needs a safepoint or
  283. // not. Note that this is about unburdening the optimizer in loops, not
  284. // avoiding the runtime cost of the actual safepoint.
  285. if (!AllBackedges) {
  286. if (mustBeFiniteCountedLoop(L, SE, Pred)) {
  287. LLVM_DEBUG(dbgs() << "skipping safepoint placement in finite loop\n");
  288. FiniteExecution++;
  289. continue;
  290. }
  291. if (CallSafepointsEnabled &&
  292. containsUnconditionalCallSafepoint(L, Header, Pred, *DT, *TLI)) {
  293. // Note: This is only semantically legal since we won't do any further
  294. // IPO or inlining before the actual call insertion.. If we hadn't, we
  295. // might latter loose this call safepoint.
  296. LLVM_DEBUG(
  297. dbgs()
  298. << "skipping safepoint placement due to unconditional call\n");
  299. CallInLoop++;
  300. continue;
  301. }
  302. }
  303. // TODO: We can create an inner loop which runs a finite number of
  304. // iterations with an outer loop which contains a safepoint. This would
  305. // not help runtime performance that much, but it might help our ability to
  306. // optimize the inner loop.
  307. // Safepoint insertion would involve creating a new basic block (as the
  308. // target of the current backedge) which does the safepoint (of all live
  309. // variables) and branches to the true header
  310. Instruction *Term = Pred->getTerminator();
  311. LLVM_DEBUG(dbgs() << "[LSP] terminator instruction: " << *Term);
  312. PollLocations.push_back(Term);
  313. }
  314. return false;
  315. }
  316. /// Returns true if an entry safepoint is not required before this callsite in
  317. /// the caller function.
  318. static bool doesNotRequireEntrySafepointBefore(CallBase *Call) {
  319. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call)) {
  320. switch (II->getIntrinsicID()) {
  321. case Intrinsic::experimental_gc_statepoint:
  322. case Intrinsic::experimental_patchpoint_void:
  323. case Intrinsic::experimental_patchpoint_i64:
  324. // The can wrap an actual call which may grow the stack by an unbounded
  325. // amount or run forever.
  326. return false;
  327. default:
  328. // Most LLVM intrinsics are things which do not expand to actual calls, or
  329. // at least if they do, are leaf functions that cause only finite stack
  330. // growth. In particular, the optimizer likes to form things like memsets
  331. // out of stores in the original IR. Another important example is
  332. // llvm.localescape which must occur in the entry block. Inserting a
  333. // safepoint before it is not legal since it could push the localescape
  334. // out of the entry block.
  335. return true;
  336. }
  337. }
  338. return false;
  339. }
  340. static Instruction *findLocationForEntrySafepoint(Function &F,
  341. DominatorTree &DT) {
  342. // Conceptually, this poll needs to be on method entry, but in
  343. // practice, we place it as late in the entry block as possible. We
  344. // can place it as late as we want as long as it dominates all calls
  345. // that can grow the stack. This, combined with backedge polls,
  346. // give us all the progress guarantees we need.
  347. // hasNextInstruction and nextInstruction are used to iterate
  348. // through a "straight line" execution sequence.
  349. auto HasNextInstruction = [](Instruction *I) {
  350. if (!I->isTerminator())
  351. return true;
  352. BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
  353. return nextBB && (nextBB->getUniquePredecessor() != nullptr);
  354. };
  355. auto NextInstruction = [&](Instruction *I) {
  356. assert(HasNextInstruction(I) &&
  357. "first check if there is a next instruction!");
  358. if (I->isTerminator())
  359. return &I->getParent()->getUniqueSuccessor()->front();
  360. return &*++I->getIterator();
  361. };
  362. Instruction *Cursor = nullptr;
  363. for (Cursor = &F.getEntryBlock().front(); HasNextInstruction(Cursor);
  364. Cursor = NextInstruction(Cursor)) {
  365. // We need to ensure a safepoint poll occurs before any 'real' call. The
  366. // easiest way to ensure finite execution between safepoints in the face of
  367. // recursive and mutually recursive functions is to enforce that each take
  368. // a safepoint. Additionally, we need to ensure a poll before any call
  369. // which can grow the stack by an unbounded amount. This isn't required
  370. // for GC semantics per se, but is a common requirement for languages
  371. // which detect stack overflow via guard pages and then throw exceptions.
  372. if (auto *Call = dyn_cast<CallBase>(Cursor)) {
  373. if (doesNotRequireEntrySafepointBefore(Call))
  374. continue;
  375. break;
  376. }
  377. }
  378. assert((HasNextInstruction(Cursor) || Cursor->isTerminator()) &&
  379. "either we stopped because of a call, or because of terminator");
  380. return Cursor;
  381. }
  382. const char GCSafepointPollName[] = "gc.safepoint_poll";
  383. static bool isGCSafepointPoll(Function &F) {
  384. return F.getName().equals(GCSafepointPollName);
  385. }
  386. /// Returns true if this function should be rewritten to include safepoint
  387. /// polls and parseable call sites. The main point of this function is to be
  388. /// an extension point for custom logic.
  389. static bool shouldRewriteFunction(Function &F) {
  390. // TODO: This should check the GCStrategy
  391. if (F.hasGC()) {
  392. const auto &FunctionGCName = F.getGC();
  393. const StringRef StatepointExampleName("statepoint-example");
  394. const StringRef CoreCLRName("coreclr");
  395. return (StatepointExampleName == FunctionGCName) ||
  396. (CoreCLRName == FunctionGCName);
  397. } else
  398. return false;
  399. }
  400. // TODO: These should become properties of the GCStrategy, possibly with
  401. // command line overrides.
  402. static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
  403. static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
  404. static bool enableCallSafepoints(Function &F) { return !NoCall; }
  405. bool PlaceSafepoints::runOnFunction(Function &F) {
  406. if (F.isDeclaration() || F.empty()) {
  407. // This is a declaration, nothing to do. Must exit early to avoid crash in
  408. // dom tree calculation
  409. return false;
  410. }
  411. if (isGCSafepointPoll(F)) {
  412. // Given we're inlining this inside of safepoint poll insertion, this
  413. // doesn't make any sense. Note that we do make any contained calls
  414. // parseable after we inline a poll.
  415. return false;
  416. }
  417. if (!shouldRewriteFunction(F))
  418. return false;
  419. const TargetLibraryInfo &TLI =
  420. getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  421. bool Modified = false;
  422. // In various bits below, we rely on the fact that uses are reachable from
  423. // defs. When there are basic blocks unreachable from the entry, dominance
  424. // and reachablity queries return non-sensical results. Thus, we preprocess
  425. // the function to ensure these properties hold.
  426. Modified |= removeUnreachableBlocks(F);
  427. // STEP 1 - Insert the safepoint polling locations. We do not need to
  428. // actually insert parse points yet. That will be done for all polls and
  429. // calls in a single pass.
  430. DominatorTree DT;
  431. DT.recalculate(F);
  432. SmallVector<Instruction *, 16> PollsNeeded;
  433. std::vector<CallBase *> ParsePointNeeded;
  434. if (enableBackedgeSafepoints(F)) {
  435. // Construct a pass manager to run the LoopPass backedge logic. We
  436. // need the pass manager to handle scheduling all the loop passes
  437. // appropriately. Doing this by hand is painful and just not worth messing
  438. // with for the moment.
  439. legacy::FunctionPassManager FPM(F.getParent());
  440. bool CanAssumeCallSafepoints = enableCallSafepoints(F);
  441. auto *PBS = new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
  442. FPM.add(PBS);
  443. FPM.run(F);
  444. // We preserve dominance information when inserting the poll, otherwise
  445. // we'd have to recalculate this on every insert
  446. DT.recalculate(F);
  447. auto &PollLocations = PBS->PollLocations;
  448. auto OrderByBBName = [](Instruction *a, Instruction *b) {
  449. return a->getParent()->getName() < b->getParent()->getName();
  450. };
  451. // We need the order of list to be stable so that naming ends up stable
  452. // when we split edges. This makes test cases much easier to write.
  453. llvm::sort(PollLocations, OrderByBBName);
  454. // We can sometimes end up with duplicate poll locations. This happens if
  455. // a single loop is visited more than once. The fact this happens seems
  456. // wrong, but it does happen for the split-backedge.ll test case.
  457. PollLocations.erase(std::unique(PollLocations.begin(),
  458. PollLocations.end()),
  459. PollLocations.end());
  460. // Insert a poll at each point the analysis pass identified
  461. // The poll location must be the terminator of a loop latch block.
  462. for (Instruction *Term : PollLocations) {
  463. // We are inserting a poll, the function is modified
  464. Modified = true;
  465. if (SplitBackedge) {
  466. // Split the backedge of the loop and insert the poll within that new
  467. // basic block. This creates a loop with two latches per original
  468. // latch (which is non-ideal), but this appears to be easier to
  469. // optimize in practice than inserting the poll immediately before the
  470. // latch test.
  471. // Since this is a latch, at least one of the successors must dominate
  472. // it. Its possible that we have a) duplicate edges to the same header
  473. // and b) edges to distinct loop headers. We need to insert pools on
  474. // each.
  475. SetVector<BasicBlock *> Headers;
  476. for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
  477. BasicBlock *Succ = Term->getSuccessor(i);
  478. if (DT.dominates(Succ, Term->getParent())) {
  479. Headers.insert(Succ);
  480. }
  481. }
  482. assert(!Headers.empty() && "poll location is not a loop latch?");
  483. // The split loop structure here is so that we only need to recalculate
  484. // the dominator tree once. Alternatively, we could just keep it up to
  485. // date and use a more natural merged loop.
  486. SetVector<BasicBlock *> SplitBackedges;
  487. for (BasicBlock *Header : Headers) {
  488. BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
  489. PollsNeeded.push_back(NewBB->getTerminator());
  490. NumBackedgeSafepoints++;
  491. }
  492. } else {
  493. // Split the latch block itself, right before the terminator.
  494. PollsNeeded.push_back(Term);
  495. NumBackedgeSafepoints++;
  496. }
  497. }
  498. }
  499. if (enableEntrySafepoints(F)) {
  500. if (Instruction *Location = findLocationForEntrySafepoint(F, DT)) {
  501. PollsNeeded.push_back(Location);
  502. Modified = true;
  503. NumEntrySafepoints++;
  504. }
  505. // TODO: else we should assert that there was, in fact, a policy choice to
  506. // not insert a entry safepoint poll.
  507. }
  508. // Now that we've identified all the needed safepoint poll locations, insert
  509. // safepoint polls themselves.
  510. for (Instruction *PollLocation : PollsNeeded) {
  511. std::vector<CallBase *> RuntimeCalls;
  512. InsertSafepointPoll(PollLocation, RuntimeCalls, TLI);
  513. llvm::append_range(ParsePointNeeded, RuntimeCalls);
  514. }
  515. return Modified;
  516. }
  517. char PlaceBackedgeSafepointsImpl::ID = 0;
  518. char PlaceSafepoints::ID = 0;
  519. FunctionPass *llvm::createPlaceSafepointsPass() {
  520. return new PlaceSafepoints();
  521. }
  522. INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
  523. "place-backedge-safepoints-impl",
  524. "Place Backedge Safepoints", false, false)
  525. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  526. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  527. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  528. INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
  529. "place-backedge-safepoints-impl",
  530. "Place Backedge Safepoints", false, false)
  531. INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
  532. false, false)
  533. INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
  534. false, false)
  535. static void
  536. InsertSafepointPoll(Instruction *InsertBefore,
  537. std::vector<CallBase *> &ParsePointsNeeded /*rval*/,
  538. const TargetLibraryInfo &TLI) {
  539. BasicBlock *OrigBB = InsertBefore->getParent();
  540. Module *M = InsertBefore->getModule();
  541. assert(M && "must be part of a module");
  542. // Inline the safepoint poll implementation - this will get all the branch,
  543. // control flow, etc.. Most importantly, it will introduce the actual slow
  544. // path call - where we need to insert a safepoint (parsepoint).
  545. auto *F = M->getFunction(GCSafepointPollName);
  546. assert(F && "gc.safepoint_poll function is missing");
  547. assert(F->getValueType() ==
  548. FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
  549. "gc.safepoint_poll declared with wrong type");
  550. assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
  551. CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
  552. // Record some information about the call site we're replacing
  553. BasicBlock::iterator Before(PollCall), After(PollCall);
  554. bool IsBegin = false;
  555. if (Before == OrigBB->begin())
  556. IsBegin = true;
  557. else
  558. Before--;
  559. After++;
  560. assert(After != OrigBB->end() && "must have successor");
  561. // Do the actual inlining
  562. InlineFunctionInfo IFI;
  563. bool InlineStatus = InlineFunction(*PollCall, IFI).isSuccess();
  564. assert(InlineStatus && "inline must succeed");
  565. (void)InlineStatus; // suppress warning in release-asserts
  566. // Check post-conditions
  567. assert(IFI.StaticAllocas.empty() && "can't have allocs");
  568. std::vector<CallInst *> Calls; // new calls
  569. DenseSet<BasicBlock *> BBs; // new BBs + insertee
  570. // Include only the newly inserted instructions, Note: begin may not be valid
  571. // if we inserted to the beginning of the basic block
  572. BasicBlock::iterator Start = IsBegin ? OrigBB->begin() : std::next(Before);
  573. // If your poll function includes an unreachable at the end, that's not
  574. // valid. Bugpoint likes to create this, so check for it.
  575. assert(isPotentiallyReachable(&*Start, &*After) &&
  576. "malformed poll function");
  577. scanInlinedCode(&*Start, &*After, Calls, BBs);
  578. assert(!Calls.empty() && "slow path not found for safepoint poll");
  579. // Record the fact we need a parsable state at the runtime call contained in
  580. // the poll function. This is required so that the runtime knows how to
  581. // parse the last frame when we actually take the safepoint (i.e. execute
  582. // the slow path)
  583. assert(ParsePointsNeeded.empty());
  584. for (auto *CI : Calls) {
  585. // No safepoint needed or wanted
  586. if (!needsStatepoint(CI, TLI))
  587. continue;
  588. // These are likely runtime calls. Should we assert that via calling
  589. // convention or something?
  590. ParsePointsNeeded.push_back(CI);
  591. }
  592. assert(ParsePointsNeeded.size() <= Calls.size());
  593. }