Sink.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. //===-- Sink.cpp - Code Sinking -------------------------------------------===//
  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. // This pass moves instructions into successor blocks, when possible, so that
  10. // they aren't executed on paths where their results aren't needed.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar/Sink.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/LoopInfo.h"
  17. #include "llvm/IR/Dominators.h"
  18. #include "llvm/InitializePasses.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include "llvm/Transforms/Scalar.h"
  22. using namespace llvm;
  23. #define DEBUG_TYPE "sink"
  24. STATISTIC(NumSunk, "Number of instructions sunk");
  25. STATISTIC(NumSinkIter, "Number of sinking iterations");
  26. static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA,
  27. SmallPtrSetImpl<Instruction *> &Stores) {
  28. if (Inst->mayWriteToMemory()) {
  29. Stores.insert(Inst);
  30. return false;
  31. }
  32. if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
  33. MemoryLocation Loc = MemoryLocation::get(L);
  34. for (Instruction *S : Stores)
  35. if (isModSet(AA.getModRefInfo(S, Loc)))
  36. return false;
  37. }
  38. if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() ||
  39. Inst->mayThrow() || !Inst->willReturn())
  40. return false;
  41. if (auto *Call = dyn_cast<CallBase>(Inst)) {
  42. // Convergent operations cannot be made control-dependent on additional
  43. // values.
  44. if (Call->isConvergent())
  45. return false;
  46. for (Instruction *S : Stores)
  47. if (isModSet(AA.getModRefInfo(S, Call)))
  48. return false;
  49. }
  50. return true;
  51. }
  52. /// IsAcceptableTarget - Return true if it is possible to sink the instruction
  53. /// in the specified basic block.
  54. static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
  55. DominatorTree &DT, LoopInfo &LI) {
  56. assert(Inst && "Instruction to be sunk is null");
  57. assert(SuccToSinkTo && "Candidate sink target is null");
  58. // It's never legal to sink an instruction into a block which terminates in an
  59. // EH-pad.
  60. if (SuccToSinkTo->getTerminator()->isExceptionalTerminator())
  61. return false;
  62. // If the block has multiple predecessors, this would introduce computation
  63. // on different code paths. We could split the critical edge, but for now we
  64. // just punt.
  65. // FIXME: Split critical edges if not backedges.
  66. if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
  67. // We cannot sink a load across a critical edge - there may be stores in
  68. // other code paths.
  69. if (Inst->mayReadFromMemory() &&
  70. !Inst->hasMetadata(LLVMContext::MD_invariant_load))
  71. return false;
  72. // We don't want to sink across a critical edge if we don't dominate the
  73. // successor. We could be introducing calculations to new code paths.
  74. if (!DT.dominates(Inst->getParent(), SuccToSinkTo))
  75. return false;
  76. // Don't sink instructions into a loop.
  77. Loop *succ = LI.getLoopFor(SuccToSinkTo);
  78. Loop *cur = LI.getLoopFor(Inst->getParent());
  79. if (succ != nullptr && succ != cur)
  80. return false;
  81. }
  82. return true;
  83. }
  84. /// SinkInstruction - Determine whether it is safe to sink the specified machine
  85. /// instruction out of its current block into a successor.
  86. static bool SinkInstruction(Instruction *Inst,
  87. SmallPtrSetImpl<Instruction *> &Stores,
  88. DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
  89. // Don't sink static alloca instructions. CodeGen assumes allocas outside the
  90. // entry block are dynamically sized stack objects.
  91. if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
  92. if (AI->isStaticAlloca())
  93. return false;
  94. // Check if it's safe to move the instruction.
  95. if (!isSafeToMove(Inst, AA, Stores))
  96. return false;
  97. // FIXME: This should include support for sinking instructions within the
  98. // block they are currently in to shorten the live ranges. We often get
  99. // instructions sunk into the top of a large block, but it would be better to
  100. // also sink them down before their first use in the block. This xform has to
  101. // be careful not to *increase* register pressure though, e.g. sinking
  102. // "x = y + z" down if it kills y and z would increase the live ranges of y
  103. // and z and only shrink the live range of x.
  104. // SuccToSinkTo - This is the successor to sink this instruction to, once we
  105. // decide.
  106. BasicBlock *SuccToSinkTo = nullptr;
  107. // Find the nearest common dominator of all users as the candidate.
  108. BasicBlock *BB = Inst->getParent();
  109. for (Use &U : Inst->uses()) {
  110. Instruction *UseInst = cast<Instruction>(U.getUser());
  111. BasicBlock *UseBlock = UseInst->getParent();
  112. // Don't worry about dead users.
  113. if (!DT.isReachableFromEntry(UseBlock))
  114. continue;
  115. if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
  116. // PHI nodes use the operand in the predecessor block, not the block with
  117. // the PHI.
  118. unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
  119. UseBlock = PN->getIncomingBlock(Num);
  120. }
  121. if (SuccToSinkTo)
  122. SuccToSinkTo = DT.findNearestCommonDominator(SuccToSinkTo, UseBlock);
  123. else
  124. SuccToSinkTo = UseBlock;
  125. // The current basic block needs to dominate the candidate.
  126. if (!DT.dominates(BB, SuccToSinkTo))
  127. return false;
  128. }
  129. if (SuccToSinkTo) {
  130. // The nearest common dominator may be in a parent loop of BB, which may not
  131. // be beneficial. Find an ancestor.
  132. while (SuccToSinkTo != BB &&
  133. !IsAcceptableTarget(Inst, SuccToSinkTo, DT, LI))
  134. SuccToSinkTo = DT.getNode(SuccToSinkTo)->getIDom()->getBlock();
  135. if (SuccToSinkTo == BB)
  136. SuccToSinkTo = nullptr;
  137. }
  138. // If we couldn't find a block to sink to, ignore this instruction.
  139. if (!SuccToSinkTo)
  140. return false;
  141. LLVM_DEBUG(dbgs() << "Sink" << *Inst << " (";
  142. Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> ";
  143. SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n");
  144. // Move the instruction.
  145. Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
  146. return true;
  147. }
  148. static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI,
  149. AAResults &AA) {
  150. // Don't bother sinking code out of unreachable blocks. In addition to being
  151. // unprofitable, it can also lead to infinite looping, because in an
  152. // unreachable loop there may be nowhere to stop.
  153. if (!DT.isReachableFromEntry(&BB)) return false;
  154. bool MadeChange = false;
  155. // Walk the basic block bottom-up. Remember if we saw a store.
  156. BasicBlock::iterator I = BB.end();
  157. --I;
  158. bool ProcessedBegin = false;
  159. SmallPtrSet<Instruction *, 8> Stores;
  160. do {
  161. Instruction *Inst = &*I; // The instruction to sink.
  162. // Predecrement I (if it's not begin) so that it isn't invalidated by
  163. // sinking.
  164. ProcessedBegin = I == BB.begin();
  165. if (!ProcessedBegin)
  166. --I;
  167. if (Inst->isDebugOrPseudoInst())
  168. continue;
  169. if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
  170. ++NumSunk;
  171. MadeChange = true;
  172. }
  173. // If we just processed the first instruction in the block, we're done.
  174. } while (!ProcessedBegin);
  175. return MadeChange;
  176. }
  177. static bool iterativelySinkInstructions(Function &F, DominatorTree &DT,
  178. LoopInfo &LI, AAResults &AA) {
  179. bool MadeChange, EverMadeChange = false;
  180. do {
  181. MadeChange = false;
  182. LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
  183. // Process all basic blocks.
  184. for (BasicBlock &I : F)
  185. MadeChange |= ProcessBlock(I, DT, LI, AA);
  186. EverMadeChange |= MadeChange;
  187. NumSinkIter++;
  188. } while (MadeChange);
  189. return EverMadeChange;
  190. }
  191. PreservedAnalyses SinkingPass::run(Function &F, FunctionAnalysisManager &AM) {
  192. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  193. auto &LI = AM.getResult<LoopAnalysis>(F);
  194. auto &AA = AM.getResult<AAManager>(F);
  195. if (!iterativelySinkInstructions(F, DT, LI, AA))
  196. return PreservedAnalyses::all();
  197. PreservedAnalyses PA;
  198. PA.preserveSet<CFGAnalyses>();
  199. return PA;
  200. }
  201. namespace {
  202. class SinkingLegacyPass : public FunctionPass {
  203. public:
  204. static char ID; // Pass identification
  205. SinkingLegacyPass() : FunctionPass(ID) {
  206. initializeSinkingLegacyPassPass(*PassRegistry::getPassRegistry());
  207. }
  208. bool runOnFunction(Function &F) override {
  209. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  210. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  211. auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
  212. return iterativelySinkInstructions(F, DT, LI, AA);
  213. }
  214. void getAnalysisUsage(AnalysisUsage &AU) const override {
  215. AU.setPreservesCFG();
  216. FunctionPass::getAnalysisUsage(AU);
  217. AU.addRequired<AAResultsWrapperPass>();
  218. AU.addRequired<DominatorTreeWrapperPass>();
  219. AU.addRequired<LoopInfoWrapperPass>();
  220. AU.addPreserved<DominatorTreeWrapperPass>();
  221. AU.addPreserved<LoopInfoWrapperPass>();
  222. }
  223. };
  224. } // end anonymous namespace
  225. char SinkingLegacyPass::ID = 0;
  226. INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
  227. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  228. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  229. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  230. INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
  231. FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }