LoopInstSimplify.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //===- LoopInstSimplify.cpp - Loop Instruction Simplification Pass --------===//
  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 performs lightweight instruction simplification on loop bodies.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
  13. #include "llvm/ADT/PointerIntPair.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/LoopInfo.h"
  21. #include "llvm/Analysis/LoopIterator.h"
  22. #include "llvm/Analysis/LoopPass.h"
  23. #include "llvm/Analysis/MemorySSA.h"
  24. #include "llvm/Analysis/MemorySSAUpdater.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/CFG.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Instruction.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/PassManager.h"
  34. #include "llvm/IR/User.h"
  35. #include "llvm/Pass.h"
  36. #include "llvm/Support/Casting.h"
  37. #include "llvm/Transforms/Scalar.h"
  38. #include "llvm/Transforms/Utils/Local.h"
  39. #include "llvm/Transforms/Utils/LoopUtils.h"
  40. #include <algorithm>
  41. #include <utility>
  42. using namespace llvm;
  43. #define DEBUG_TYPE "loop-instsimplify"
  44. STATISTIC(NumSimplified, "Number of redundant instructions simplified");
  45. static bool simplifyLoopInst(Loop &L, DominatorTree &DT, LoopInfo &LI,
  46. AssumptionCache &AC, const TargetLibraryInfo &TLI,
  47. MemorySSAUpdater *MSSAU) {
  48. const DataLayout &DL = L.getHeader()->getModule()->getDataLayout();
  49. SimplifyQuery SQ(DL, &TLI, &DT, &AC);
  50. // On the first pass over the loop body we try to simplify every instruction.
  51. // On subsequent passes, we can restrict this to only simplifying instructions
  52. // where the inputs have been updated. We end up needing two sets: one
  53. // containing the instructions we are simplifying in *this* pass, and one for
  54. // the instructions we will want to simplify in the *next* pass. We use
  55. // pointers so we can swap between two stably allocated sets.
  56. SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
  57. // Track the PHI nodes that have already been visited during each iteration so
  58. // that we can identify when it is necessary to iterate.
  59. SmallPtrSet<PHINode *, 4> VisitedPHIs;
  60. // While simplifying we may discover dead code or cause code to become dead.
  61. // Keep track of all such instructions and we will delete them at the end.
  62. SmallVector<Instruction *, 8> DeadInsts;
  63. // First we want to create an RPO traversal of the loop body. By processing in
  64. // RPO we can ensure that definitions are processed prior to uses (for non PHI
  65. // uses) in all cases. This ensures we maximize the simplifications in each
  66. // iteration over the loop and minimizes the possible causes for continuing to
  67. // iterate.
  68. LoopBlocksRPO RPOT(&L);
  69. RPOT.perform(&LI);
  70. MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr;
  71. bool Changed = false;
  72. for (;;) {
  73. if (MSSAU && VerifyMemorySSA)
  74. MSSA->verifyMemorySSA();
  75. for (BasicBlock *BB : RPOT) {
  76. for (Instruction &I : *BB) {
  77. if (auto *PI = dyn_cast<PHINode>(&I))
  78. VisitedPHIs.insert(PI);
  79. if (I.use_empty()) {
  80. if (isInstructionTriviallyDead(&I, &TLI))
  81. DeadInsts.push_back(&I);
  82. continue;
  83. }
  84. // We special case the first iteration which we can detect due to the
  85. // empty `ToSimplify` set.
  86. bool IsFirstIteration = ToSimplify->empty();
  87. if (!IsFirstIteration && !ToSimplify->count(&I))
  88. continue;
  89. Value *V = SimplifyInstruction(&I, SQ.getWithInstruction(&I));
  90. if (!V || !LI.replacementPreservesLCSSAForm(&I, V))
  91. continue;
  92. for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
  93. UI != UE;) {
  94. Use &U = *UI++;
  95. auto *UserI = cast<Instruction>(U.getUser());
  96. U.set(V);
  97. // If the instruction is used by a PHI node we have already processed
  98. // we'll need to iterate on the loop body to converge, so add it to
  99. // the next set.
  100. if (auto *UserPI = dyn_cast<PHINode>(UserI))
  101. if (VisitedPHIs.count(UserPI)) {
  102. Next->insert(UserPI);
  103. continue;
  104. }
  105. // If we are only simplifying targeted instructions and the user is an
  106. // instruction in the loop body, add it to our set of targeted
  107. // instructions. Because we process defs before uses (outside of PHIs)
  108. // we won't have visited it yet.
  109. //
  110. // We also skip any uses outside of the loop being simplified. Those
  111. // should always be PHI nodes due to LCSSA form, and we don't want to
  112. // try to simplify those away.
  113. assert((L.contains(UserI) || isa<PHINode>(UserI)) &&
  114. "Uses outside the loop should be PHI nodes due to LCSSA!");
  115. if (!IsFirstIteration && L.contains(UserI))
  116. ToSimplify->insert(UserI);
  117. }
  118. if (MSSAU)
  119. if (Instruction *SimpleI = dyn_cast_or_null<Instruction>(V))
  120. if (MemoryAccess *MA = MSSA->getMemoryAccess(&I))
  121. if (MemoryAccess *ReplacementMA = MSSA->getMemoryAccess(SimpleI))
  122. MA->replaceAllUsesWith(ReplacementMA);
  123. assert(I.use_empty() && "Should always have replaced all uses!");
  124. if (isInstructionTriviallyDead(&I, &TLI))
  125. DeadInsts.push_back(&I);
  126. ++NumSimplified;
  127. Changed = true;
  128. }
  129. }
  130. // Delete any dead instructions found thus far now that we've finished an
  131. // iteration over all instructions in all the loop blocks.
  132. if (!DeadInsts.empty()) {
  133. Changed = true;
  134. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, &TLI, MSSAU);
  135. }
  136. if (MSSAU && VerifyMemorySSA)
  137. MSSA->verifyMemorySSA();
  138. // If we never found a PHI that needs to be simplified in the next
  139. // iteration, we're done.
  140. if (Next->empty())
  141. break;
  142. // Otherwise, put the next set in place for the next iteration and reset it
  143. // and the visited PHIs for that iteration.
  144. std::swap(Next, ToSimplify);
  145. Next->clear();
  146. VisitedPHIs.clear();
  147. DeadInsts.clear();
  148. }
  149. return Changed;
  150. }
  151. namespace {
  152. class LoopInstSimplifyLegacyPass : public LoopPass {
  153. public:
  154. static char ID; // Pass ID, replacement for typeid
  155. LoopInstSimplifyLegacyPass() : LoopPass(ID) {
  156. initializeLoopInstSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
  157. }
  158. bool runOnLoop(Loop *L, LPPassManager &LPM) override {
  159. if (skipLoop(L))
  160. return false;
  161. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  162. LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  163. AssumptionCache &AC =
  164. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
  165. *L->getHeader()->getParent());
  166. const TargetLibraryInfo &TLI =
  167. getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
  168. *L->getHeader()->getParent());
  169. MemorySSA *MSSA = nullptr;
  170. Optional<MemorySSAUpdater> MSSAU;
  171. if (EnableMSSALoopDependency) {
  172. MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
  173. MSSAU = MemorySSAUpdater(MSSA);
  174. }
  175. return simplifyLoopInst(*L, DT, LI, AC, TLI,
  176. MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
  177. }
  178. void getAnalysisUsage(AnalysisUsage &AU) const override {
  179. AU.addRequired<AssumptionCacheTracker>();
  180. AU.addRequired<DominatorTreeWrapperPass>();
  181. AU.addRequired<TargetLibraryInfoWrapperPass>();
  182. AU.setPreservesCFG();
  183. if (EnableMSSALoopDependency) {
  184. AU.addRequired<MemorySSAWrapperPass>();
  185. AU.addPreserved<MemorySSAWrapperPass>();
  186. }
  187. getLoopAnalysisUsage(AU);
  188. }
  189. };
  190. } // end anonymous namespace
  191. PreservedAnalyses LoopInstSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
  192. LoopStandardAnalysisResults &AR,
  193. LPMUpdater &) {
  194. Optional<MemorySSAUpdater> MSSAU;
  195. if (AR.MSSA) {
  196. MSSAU = MemorySSAUpdater(AR.MSSA);
  197. AR.MSSA->verifyMemorySSA();
  198. }
  199. if (!simplifyLoopInst(L, AR.DT, AR.LI, AR.AC, AR.TLI,
  200. MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
  201. return PreservedAnalyses::all();
  202. auto PA = getLoopPassPreservedAnalyses();
  203. PA.preserveSet<CFGAnalyses>();
  204. if (AR.MSSA)
  205. PA.preserve<MemorySSAAnalysis>();
  206. return PA;
  207. }
  208. char LoopInstSimplifyLegacyPass::ID = 0;
  209. INITIALIZE_PASS_BEGIN(LoopInstSimplifyLegacyPass, "loop-instsimplify",
  210. "Simplify instructions in loops", false, false)
  211. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  212. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  213. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  214. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  215. INITIALIZE_PASS_END(LoopInstSimplifyLegacyPass, "loop-instsimplify",
  216. "Simplify instructions in loops", false, false)
  217. Pass *llvm::createLoopInstSimplifyPass() {
  218. return new LoopInstSimplifyLegacyPass();
  219. }