ScalarEvolutionNormalization.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. //===- ScalarEvolutionNormalization.cpp - See below -------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements utilities for working with "normalized" expressions.
  11. // See the comments at the top of ScalarEvolutionNormalization.h for details.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/IR/Dominators.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  17. #include "llvm/Analysis/ScalarEvolutionNormalization.h"
  18. using namespace llvm;
  19. /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
  20. /// and now we need to decide whether the user should use the preinc or post-inc
  21. /// value. If this user should use the post-inc version of the IV, return true.
  22. ///
  23. /// Choosing wrong here can break dominance properties (if we choose to use the
  24. /// post-inc value when we cannot) or it can end up adding extra live-ranges to
  25. /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
  26. /// should use the post-inc value).
  27. static bool IVUseShouldUsePostIncValue(Instruction *User, Value *Operand,
  28. const Loop *L, DominatorTree *DT) {
  29. // If the user is in the loop, use the preinc value.
  30. if (L->contains(User)) return false;
  31. BasicBlock *LatchBlock = L->getLoopLatch();
  32. if (!LatchBlock)
  33. return false;
  34. // Ok, the user is outside of the loop. If it is dominated by the latch
  35. // block, use the post-inc value.
  36. if (DT->dominates(LatchBlock, User->getParent()))
  37. return true;
  38. // There is one case we have to be careful of: PHI nodes. These little guys
  39. // can live in blocks that are not dominated by the latch block, but (since
  40. // their uses occur in the predecessor block, not the block the PHI lives in)
  41. // should still use the post-inc value. Check for this case now.
  42. PHINode *PN = dyn_cast<PHINode>(User);
  43. if (!PN || !Operand) return false; // not a phi, not dominated by latch block.
  44. // Look at all of the uses of Operand by the PHI node. If any use corresponds
  45. // to a block that is not dominated by the latch block, give up and use the
  46. // preincremented value.
  47. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  48. if (PN->getIncomingValue(i) == Operand &&
  49. !DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
  50. return false;
  51. // Okay, all uses of Operand by PN are in predecessor blocks that really are
  52. // dominated by the latch block. Use the post-incremented value.
  53. return true;
  54. }
  55. namespace {
  56. /// Hold the state used during post-inc expression transformation, including a
  57. /// map of transformed expressions.
  58. class PostIncTransform {
  59. TransformKind Kind;
  60. PostIncLoopSet &Loops;
  61. ScalarEvolution &SE;
  62. DominatorTree &DT;
  63. DenseMap<const SCEV*, const SCEV*> Transformed;
  64. public:
  65. PostIncTransform(TransformKind kind, PostIncLoopSet &loops,
  66. ScalarEvolution &se, DominatorTree &dt):
  67. Kind(kind), Loops(loops), SE(se), DT(dt) {}
  68. const SCEV *TransformSubExpr(const SCEV *S, Instruction *User,
  69. Value *OperandValToReplace);
  70. protected:
  71. const SCEV *TransformImpl(const SCEV *S, Instruction *User,
  72. Value *OperandValToReplace);
  73. };
  74. } // namespace
  75. /// Implement post-inc transformation for all valid expression types.
  76. const SCEV *PostIncTransform::
  77. TransformImpl(const SCEV *S, Instruction *User, Value *OperandValToReplace) {
  78. if (const SCEVCastExpr *X = dyn_cast<SCEVCastExpr>(S)) {
  79. const SCEV *O = X->getOperand();
  80. const SCEV *N = TransformSubExpr(O, User, OperandValToReplace);
  81. if (O != N)
  82. switch (S->getSCEVType()) {
  83. case scZeroExtend: return SE.getZeroExtendExpr(N, S->getType());
  84. case scSignExtend: return SE.getSignExtendExpr(N, S->getType());
  85. case scTruncate: return SE.getTruncateExpr(N, S->getType());
  86. default: llvm_unreachable("Unexpected SCEVCastExpr kind!");
  87. }
  88. return S;
  89. }
  90. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  91. // An addrec. This is the interesting part.
  92. SmallVector<const SCEV *, 8> Operands;
  93. const Loop *L = AR->getLoop();
  94. // The addrec conceptually uses its operands at loop entry.
  95. Instruction *LUser = L->getHeader()->begin();
  96. // Transform each operand.
  97. for (SCEVNAryExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
  98. I != E; ++I) {
  99. Operands.push_back(TransformSubExpr(*I, LUser, nullptr));
  100. }
  101. // Conservatively use AnyWrap until/unless we need FlagNW.
  102. const SCEV *Result = SE.getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
  103. switch (Kind) {
  104. case NormalizeAutodetect:
  105. // Normalize this SCEV by subtracting the expression for the final step.
  106. // We only allow affine AddRecs to be normalized, otherwise we would not
  107. // be able to correctly denormalize.
  108. // e.g. {1,+,3,+,2} == {-2,+,1,+,2} + {3,+,2}
  109. // Normalized form: {-2,+,1,+,2}
  110. // Denormalized form: {1,+,3,+,2}
  111. //
  112. // However, denormalization would use a different step expression than
  113. // normalization (see getPostIncExpr), generating the wrong final
  114. // expression: {-2,+,1,+,2} + {1,+,2} => {-1,+,3,+,2}
  115. if (AR->isAffine() &&
  116. IVUseShouldUsePostIncValue(User, OperandValToReplace, L, &DT)) {
  117. const SCEV *TransformedStep =
  118. TransformSubExpr(AR->getStepRecurrence(SE),
  119. User, OperandValToReplace);
  120. Result = SE.getMinusSCEV(Result, TransformedStep);
  121. Loops.insert(L);
  122. }
  123. #if 0
  124. // This assert is conceptually correct, but ScalarEvolution currently
  125. // sometimes fails to canonicalize two equal SCEVs to exactly the same
  126. // form. It's possibly a pessimization when this happens, but it isn't a
  127. // correctness problem, so disable this assert for now.
  128. assert(S == TransformSubExpr(Result, User, OperandValToReplace) &&
  129. "SCEV normalization is not invertible!");
  130. #endif
  131. break;
  132. case Normalize:
  133. // We want to normalize step expression, because otherwise we might not be
  134. // able to denormalize to the original expression.
  135. //
  136. // Here is an example what will happen if we don't normalize step:
  137. // ORIGINAL ISE:
  138. // {(100 /u {1,+,1}<%bb16>),+,(100 /u {1,+,1}<%bb16>)}<%bb25>
  139. // NORMALIZED ISE:
  140. // {((-1 * (100 /u {1,+,1}<%bb16>)) + (100 /u {0,+,1}<%bb16>)),+,
  141. // (100 /u {0,+,1}<%bb16>)}<%bb25>
  142. // DENORMALIZED BACK ISE:
  143. // {((2 * (100 /u {1,+,1}<%bb16>)) + (-1 * (100 /u {2,+,1}<%bb16>))),+,
  144. // (100 /u {1,+,1}<%bb16>)}<%bb25>
  145. // Note that the initial value changes after normalization +
  146. // denormalization, which isn't correct.
  147. if (Loops.count(L)) {
  148. const SCEV *TransformedStep =
  149. TransformSubExpr(AR->getStepRecurrence(SE),
  150. User, OperandValToReplace);
  151. Result = SE.getMinusSCEV(Result, TransformedStep);
  152. }
  153. #if 0
  154. // See the comment on the assert above.
  155. assert(S == TransformSubExpr(Result, User, OperandValToReplace) &&
  156. "SCEV normalization is not invertible!");
  157. #endif
  158. break;
  159. case Denormalize:
  160. // Here we want to normalize step expressions for the same reasons, as
  161. // stated above.
  162. if (Loops.count(L)) {
  163. const SCEV *TransformedStep =
  164. TransformSubExpr(AR->getStepRecurrence(SE),
  165. User, OperandValToReplace);
  166. Result = SE.getAddExpr(Result, TransformedStep);
  167. }
  168. break;
  169. }
  170. return Result;
  171. }
  172. if (const SCEVNAryExpr *X = dyn_cast<SCEVNAryExpr>(S)) {
  173. SmallVector<const SCEV *, 8> Operands;
  174. bool Changed = false;
  175. // Transform each operand.
  176. for (SCEVNAryExpr::op_iterator I = X->op_begin(), E = X->op_end();
  177. I != E; ++I) {
  178. const SCEV *O = *I;
  179. const SCEV *N = TransformSubExpr(O, User, OperandValToReplace);
  180. Changed |= N != O;
  181. Operands.push_back(N);
  182. }
  183. // If any operand actually changed, return a transformed result.
  184. if (Changed)
  185. switch (S->getSCEVType()) {
  186. case scAddExpr: return SE.getAddExpr(Operands);
  187. case scMulExpr: return SE.getMulExpr(Operands);
  188. case scSMaxExpr: return SE.getSMaxExpr(Operands);
  189. case scUMaxExpr: return SE.getUMaxExpr(Operands);
  190. default: llvm_unreachable("Unexpected SCEVNAryExpr kind!");
  191. }
  192. return S;
  193. }
  194. if (const SCEVUDivExpr *X = dyn_cast<SCEVUDivExpr>(S)) {
  195. const SCEV *LO = X->getLHS();
  196. const SCEV *RO = X->getRHS();
  197. const SCEV *LN = TransformSubExpr(LO, User, OperandValToReplace);
  198. const SCEV *RN = TransformSubExpr(RO, User, OperandValToReplace);
  199. if (LO != LN || RO != RN)
  200. return SE.getUDivExpr(LN, RN);
  201. return S;
  202. }
  203. llvm_unreachable("Unexpected SCEV kind!");
  204. }
  205. /// Manage recursive transformation across an expression DAG. Revisiting
  206. /// expressions would lead to exponential recursion.
  207. const SCEV *PostIncTransform::
  208. TransformSubExpr(const SCEV *S, Instruction *User, Value *OperandValToReplace) {
  209. if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S))
  210. return S;
  211. const SCEV *Result = Transformed.lookup(S);
  212. if (Result)
  213. return Result;
  214. Result = TransformImpl(S, User, OperandValToReplace);
  215. Transformed[S] = Result;
  216. return Result;
  217. }
  218. /// Top level driver for transforming an expression DAG into its requested
  219. /// post-inc form (either "Normalized" or "Denormalized").
  220. const SCEV *llvm::TransformForPostIncUse(TransformKind Kind,
  221. const SCEV *S,
  222. Instruction *User,
  223. Value *OperandValToReplace,
  224. PostIncLoopSet &Loops,
  225. ScalarEvolution &SE,
  226. DominatorTree &DT) {
  227. PostIncTransform Transform(Kind, Loops, SE, DT);
  228. return Transform.TransformSubExpr(S, User, OperandValToReplace);
  229. }