PlaceSafepoints.cpp 27 KB

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