LoopInstSimplify.cpp 9.1 KB

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