LoopUnrollAnalyzer.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. //===- LoopUnrollAnalyzer.cpp - Unrolling Effect Estimation -----*- C++ -*-===//
  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 file implements UnrolledInstAnalyzer class. It's used for predicting
  10. // potential effects that loop unrolling might have, such as enabling constant
  11. // propagation and other optimizations.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/LoopUnrollAnalyzer.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. using namespace llvm;
  17. /// Try to simplify instruction \param I using its SCEV expression.
  18. ///
  19. /// The idea is that some AddRec expressions become constants, which then
  20. /// could trigger folding of other instructions. However, that only happens
  21. /// for expressions whose start value is also constant, which isn't always the
  22. /// case. In another common and important case the start value is just some
  23. /// address (i.e. SCEVUnknown) - in this case we compute the offset and save
  24. /// it along with the base address instead.
  25. bool UnrolledInstAnalyzer::simplifyInstWithSCEV(Instruction *I) {
  26. if (!SE.isSCEVable(I->getType()))
  27. return false;
  28. const SCEV *S = SE.getSCEV(I);
  29. if (auto *SC = dyn_cast<SCEVConstant>(S)) {
  30. SimplifiedValues[I] = SC->getValue();
  31. return true;
  32. }
  33. // If we have a loop invariant computation, we only need to compute it once.
  34. // Given that, all but the first occurance are free.
  35. if (!IterationNumber->isZero() && SE.isLoopInvariant(S, L))
  36. return true;
  37. auto *AR = dyn_cast<SCEVAddRecExpr>(S);
  38. if (!AR || AR->getLoop() != L)
  39. return false;
  40. const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE);
  41. // Check if the AddRec expression becomes a constant.
  42. if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) {
  43. SimplifiedValues[I] = SC->getValue();
  44. return true;
  45. }
  46. // Check if the offset from the base address becomes a constant.
  47. auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S));
  48. if (!Base)
  49. return false;
  50. auto *Offset =
  51. dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base));
  52. if (!Offset)
  53. return false;
  54. SimplifiedAddress Address;
  55. Address.Base = Base->getValue();
  56. Address.Offset = Offset->getValue();
  57. SimplifiedAddresses[I] = Address;
  58. return false;
  59. }
  60. /// Try to simplify binary operator I.
  61. ///
  62. /// TODO: Probably it's worth to hoist the code for estimating the
  63. /// simplifications effects to a separate class, since we have a very similar
  64. /// code in InlineCost already.
  65. bool UnrolledInstAnalyzer::visitBinaryOperator(BinaryOperator &I) {
  66. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  67. if (!isa<Constant>(LHS))
  68. if (Value *SimpleLHS = SimplifiedValues.lookup(LHS))
  69. LHS = SimpleLHS;
  70. if (!isa<Constant>(RHS))
  71. if (Value *SimpleRHS = SimplifiedValues.lookup(RHS))
  72. RHS = SimpleRHS;
  73. Value *SimpleV = nullptr;
  74. const DataLayout &DL = I.getModule()->getDataLayout();
  75. if (auto FI = dyn_cast<FPMathOperator>(&I))
  76. SimpleV =
  77. SimplifyBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
  78. else
  79. SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
  80. if (SimpleV) {
  81. SimplifiedValues[&I] = SimpleV;
  82. return true;
  83. }
  84. return Base::visitBinaryOperator(I);
  85. }
  86. /// Try to fold load I.
  87. bool UnrolledInstAnalyzer::visitLoad(LoadInst &I) {
  88. Value *AddrOp = I.getPointerOperand();
  89. auto AddressIt = SimplifiedAddresses.find(AddrOp);
  90. if (AddressIt == SimplifiedAddresses.end())
  91. return false;
  92. ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset;
  93. auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base);
  94. // We're only interested in loads that can be completely folded to a
  95. // constant.
  96. if (!GV || !GV->hasDefinitiveInitializer() || !GV->isConstant())
  97. return false;
  98. ConstantDataSequential *CDS =
  99. dyn_cast<ConstantDataSequential>(GV->getInitializer());
  100. if (!CDS)
  101. return false;
  102. // We might have a vector load from an array. FIXME: for now we just bail
  103. // out in this case, but we should be able to resolve and simplify such
  104. // loads.
  105. if (CDS->getElementType() != I.getType())
  106. return false;
  107. unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U;
  108. if (SimplifiedAddrOp->getValue().getActiveBits() > 64)
  109. return false;
  110. int64_t SimplifiedAddrOpV = SimplifiedAddrOp->getSExtValue();
  111. if (SimplifiedAddrOpV < 0) {
  112. // FIXME: For now we conservatively ignore out of bound accesses, but
  113. // we're allowed to perform the optimization in this case.
  114. return false;
  115. }
  116. uint64_t Index = static_cast<uint64_t>(SimplifiedAddrOpV) / ElemSize;
  117. if (Index >= CDS->getNumElements()) {
  118. // FIXME: For now we conservatively ignore out of bound accesses, but
  119. // we're allowed to perform the optimization in this case.
  120. return false;
  121. }
  122. Constant *CV = CDS->getElementAsConstant(Index);
  123. assert(CV && "Constant expected.");
  124. SimplifiedValues[&I] = CV;
  125. return true;
  126. }
  127. /// Try to simplify cast instruction.
  128. bool UnrolledInstAnalyzer::visitCastInst(CastInst &I) {
  129. Value *Op = I.getOperand(0);
  130. if (Value *Simplified = SimplifiedValues.lookup(Op))
  131. Op = Simplified;
  132. // The cast can be invalid, because SimplifiedValues contains results of SCEV
  133. // analysis, which operates on integers (and, e.g., might convert i8* null to
  134. // i32 0).
  135. if (CastInst::castIsValid(I.getOpcode(), Op, I.getType())) {
  136. const DataLayout &DL = I.getModule()->getDataLayout();
  137. if (Value *V = SimplifyCastInst(I.getOpcode(), Op, I.getType(), DL)) {
  138. SimplifiedValues[&I] = V;
  139. return true;
  140. }
  141. }
  142. return Base::visitCastInst(I);
  143. }
  144. /// Try to simplify cmp instruction.
  145. bool UnrolledInstAnalyzer::visitCmpInst(CmpInst &I) {
  146. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
  147. // First try to handle simplified comparisons.
  148. if (!isa<Constant>(LHS))
  149. if (Value *SimpleLHS = SimplifiedValues.lookup(LHS))
  150. LHS = SimpleLHS;
  151. if (!isa<Constant>(RHS))
  152. if (Value *SimpleRHS = SimplifiedValues.lookup(RHS))
  153. RHS = SimpleRHS;
  154. if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) {
  155. auto SimplifiedLHS = SimplifiedAddresses.find(LHS);
  156. if (SimplifiedLHS != SimplifiedAddresses.end()) {
  157. auto SimplifiedRHS = SimplifiedAddresses.find(RHS);
  158. if (SimplifiedRHS != SimplifiedAddresses.end()) {
  159. SimplifiedAddress &LHSAddr = SimplifiedLHS->second;
  160. SimplifiedAddress &RHSAddr = SimplifiedRHS->second;
  161. if (LHSAddr.Base == RHSAddr.Base) {
  162. LHS = LHSAddr.Offset;
  163. RHS = RHSAddr.Offset;
  164. }
  165. }
  166. }
  167. }
  168. const DataLayout &DL = I.getModule()->getDataLayout();
  169. if (Value *V = SimplifyCmpInst(I.getPredicate(), LHS, RHS, DL)) {
  170. SimplifiedValues[&I] = V;
  171. return true;
  172. }
  173. return Base::visitCmpInst(I);
  174. }
  175. bool UnrolledInstAnalyzer::visitPHINode(PHINode &PN) {
  176. // Run base visitor first. This way we can gather some useful for later
  177. // analysis information.
  178. if (Base::visitPHINode(PN))
  179. return true;
  180. // The loop induction PHI nodes are definitionally free.
  181. return PN.getParent() == L->getHeader();
  182. }
  183. bool UnrolledInstAnalyzer::visitInstruction(Instruction &I) {
  184. return simplifyInstWithSCEV(&I);
  185. }