ScalarEvolutionExpander.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. //===---- llvm/Analysis/ScalarEvolutionExpander.h - SCEV Exprs --*- 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 defines the classes used to generate code from scalar expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
  14. #define LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
  15. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  16. #include "llvm/Analysis/ScalarEvolutionNormalization.h"
  17. #include "llvm/Analysis/TargetFolder.h"
  18. #include "llvm/IR/IRBuilder.h"
  19. #include "llvm/IR/ValueHandle.h"
  20. #include <set>
  21. namespace llvm {
  22. class TargetTransformInfo;
  23. /// Return true if the given expression is safe to expand in the sense that
  24. /// all materialized values are safe to speculate.
  25. bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE);
  26. /// This class uses information about analyze scalars to
  27. /// rewrite expressions in canonical form.
  28. ///
  29. /// Clients should create an instance of this class when rewriting is needed,
  30. /// and destroy it when finished to allow the release of the associated
  31. /// memory.
  32. class SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
  33. ScalarEvolution &SE;
  34. const DataLayout &DL;
  35. // New instructions receive a name to identifies them with the current pass.
  36. const char* IVName;
  37. // InsertedExpressions caches Values for reuse, so must track RAUW.
  38. std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >
  39. InsertedExpressions;
  40. // InsertedValues only flags inserted instructions so needs no RAUW.
  41. std::set<AssertingVH<Value> > InsertedValues;
  42. std::set<AssertingVH<Value> > InsertedPostIncValues;
  43. /// A memoization of the "relevant" loop for a given SCEV.
  44. DenseMap<const SCEV *, const Loop *> RelevantLoops;
  45. /// \brief Addrecs referring to any of the given loops are expanded
  46. /// in post-inc mode. For example, expanding {1,+,1}<L> in post-inc mode
  47. /// returns the add instruction that adds one to the phi for {0,+,1}<L>,
  48. /// as opposed to a new phi starting at 1. This is only supported in
  49. /// non-canonical mode.
  50. PostIncLoopSet PostIncLoops;
  51. /// \brief When this is non-null, addrecs expanded in the loop it indicates
  52. /// should be inserted with increments at IVIncInsertPos.
  53. const Loop *IVIncInsertLoop;
  54. /// \brief When expanding addrecs in the IVIncInsertLoop loop, insert the IV
  55. /// increment at this position.
  56. Instruction *IVIncInsertPos;
  57. /// \brief Phis that complete an IV chain. Reuse
  58. std::set<AssertingVH<PHINode> > ChainedPhis;
  59. /// \brief When true, expressions are expanded in "canonical" form. In
  60. /// particular, addrecs are expanded as arithmetic based on a canonical
  61. /// induction variable. When false, expression are expanded in a more
  62. /// literal form.
  63. bool CanonicalMode;
  64. /// \brief When invoked from LSR, the expander is in "strength reduction"
  65. /// mode. The only difference is that phi's are only reused if they are
  66. /// already in "expanded" form.
  67. bool LSRMode;
  68. typedef IRBuilder<true, TargetFolder> BuilderType;
  69. BuilderType Builder;
  70. #ifndef NDEBUG
  71. const char *DebugType;
  72. #endif
  73. friend struct SCEVVisitor<SCEVExpander, Value*>;
  74. public:
  75. /// \brief Construct a SCEVExpander in "canonical" mode.
  76. explicit SCEVExpander(ScalarEvolution &se, const DataLayout &DL,
  77. const char *name)
  78. : SE(se), DL(DL), IVName(name), IVIncInsertLoop(nullptr),
  79. IVIncInsertPos(nullptr), CanonicalMode(true), LSRMode(false),
  80. Builder(se.getContext(), TargetFolder(DL)) {
  81. #ifndef NDEBUG
  82. DebugType = "";
  83. #endif
  84. }
  85. #ifndef NDEBUG
  86. void setDebugType(const char* s) { DebugType = s; }
  87. #endif
  88. /// \brief Erase the contents of the InsertedExpressions map so that users
  89. /// trying to expand the same expression into multiple BasicBlocks or
  90. /// different places within the same BasicBlock can do so.
  91. void clear() {
  92. InsertedExpressions.clear();
  93. InsertedValues.clear();
  94. InsertedPostIncValues.clear();
  95. ChainedPhis.clear();
  96. }
  97. /// \brief Return true for expressions that may incur non-trivial cost to
  98. /// evaluate at runtime.
  99. bool isHighCostExpansion(const SCEV *Expr, Loop *L) {
  100. SmallPtrSet<const SCEV *, 8> Processed;
  101. return isHighCostExpansionHelper(Expr, L, Processed);
  102. }
  103. /// \brief This method returns the canonical induction variable of the
  104. /// specified type for the specified loop (inserting one if there is none).
  105. /// A canonical induction variable starts at zero and steps by one on each
  106. /// iteration.
  107. PHINode *getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty);
  108. /// \brief Return the induction variable increment's IV operand.
  109. Instruction *getIVIncOperand(Instruction *IncV, Instruction *InsertPos,
  110. bool allowScale);
  111. /// \brief Utility for hoisting an IV increment.
  112. bool hoistIVInc(Instruction *IncV, Instruction *InsertPos);
  113. /// \brief replace congruent phis with their most canonical
  114. /// representative. Return the number of phis eliminated.
  115. unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
  116. SmallVectorImpl<WeakVH> &DeadInsts,
  117. const TargetTransformInfo *TTI = nullptr);
  118. /// \brief Insert code to directly compute the specified SCEV expression
  119. /// into the program. The inserted code is inserted into the specified
  120. /// block.
  121. Value *expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I);
  122. /// \brief Set the current IV increment loop and position.
  123. void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
  124. assert(!CanonicalMode &&
  125. "IV increment positions are not supported in CanonicalMode");
  126. IVIncInsertLoop = L;
  127. IVIncInsertPos = Pos;
  128. }
  129. /// \brief Enable post-inc expansion for addrecs referring to the given
  130. /// loops. Post-inc expansion is only supported in non-canonical mode.
  131. void setPostInc(const PostIncLoopSet &L) {
  132. assert(!CanonicalMode &&
  133. "Post-inc expansion is not supported in CanonicalMode");
  134. PostIncLoops = L;
  135. }
  136. /// \brief Disable all post-inc expansion.
  137. void clearPostInc() {
  138. PostIncLoops.clear();
  139. // When we change the post-inc loop set, cached expansions may no
  140. // longer be valid.
  141. InsertedPostIncValues.clear();
  142. }
  143. /// \brief Disable the behavior of expanding expressions in canonical form
  144. /// rather than in a more literal form. Non-canonical mode is useful for
  145. /// late optimization passes.
  146. void disableCanonicalMode() { CanonicalMode = false; }
  147. void enableLSRMode() { LSRMode = true; }
  148. /// \brief Clear the current insertion point. This is useful if the
  149. /// instruction that had been serving as the insertion point may have been
  150. /// deleted.
  151. void clearInsertPoint() {
  152. Builder.ClearInsertionPoint();
  153. }
  154. /// \brief Return true if the specified instruction was inserted by the code
  155. /// rewriter. If so, the client should not modify the instruction.
  156. bool isInsertedInstruction(Instruction *I) const {
  157. return InsertedValues.count(I) || InsertedPostIncValues.count(I);
  158. }
  159. void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
  160. private:
  161. LLVMContext &getContext() const { return SE.getContext(); }
  162. /// \brief Recursive helper function for isHighCostExpansion.
  163. bool isHighCostExpansionHelper(const SCEV *S, Loop *L,
  164. SmallPtrSetImpl<const SCEV *> &Processed);
  165. /// \brief Insert the specified binary operator, doing a small amount
  166. /// of work to avoid inserting an obviously redundant operation.
  167. Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS);
  168. /// \brief Arrange for there to be a cast of V to Ty at IP, reusing an
  169. /// existing cast if a suitable one exists, moving an existing cast if a
  170. /// suitable one exists but isn't in the right place, or or creating a new
  171. /// one.
  172. Value *ReuseOrCreateCast(Value *V, Type *Ty,
  173. Instruction::CastOps Op,
  174. BasicBlock::iterator IP);
  175. /// \brief Insert a cast of V to the specified type, which must be possible
  176. /// with a noop cast, doing what we can to share the casts.
  177. Value *InsertNoopCastOfTo(Value *V, Type *Ty);
  178. /// \brief Expand a SCEVAddExpr with a pointer type into a GEP
  179. /// instead of using ptrtoint+arithmetic+inttoptr.
  180. Value *expandAddToGEP(const SCEV *const *op_begin,
  181. const SCEV *const *op_end,
  182. PointerType *PTy, Type *Ty, Value *V);
  183. Value *expand(const SCEV *S);
  184. /// \brief Insert code to directly compute the specified SCEV expression
  185. /// into the program. The inserted code is inserted into the SCEVExpander's
  186. /// current insertion point. If a type is specified, the result will be
  187. /// expanded to have that type, with a cast if necessary.
  188. Value *expandCodeFor(const SCEV *SH, Type *Ty = nullptr);
  189. /// \brief Determine the most "relevant" loop for the given SCEV.
  190. const Loop *getRelevantLoop(const SCEV *);
  191. Value *visitConstant(const SCEVConstant *S) {
  192. return S->getValue();
  193. }
  194. Value *visitTruncateExpr(const SCEVTruncateExpr *S);
  195. Value *visitZeroExtendExpr(const SCEVZeroExtendExpr *S);
  196. Value *visitSignExtendExpr(const SCEVSignExtendExpr *S);
  197. Value *visitAddExpr(const SCEVAddExpr *S);
  198. Value *visitMulExpr(const SCEVMulExpr *S);
  199. Value *visitUDivExpr(const SCEVUDivExpr *S);
  200. Value *visitAddRecExpr(const SCEVAddRecExpr *S);
  201. Value *visitSMaxExpr(const SCEVSMaxExpr *S);
  202. Value *visitUMaxExpr(const SCEVUMaxExpr *S);
  203. Value *visitUnknown(const SCEVUnknown *S) {
  204. return S->getValue();
  205. }
  206. void rememberInstruction(Value *I);
  207. bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
  208. bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
  209. Value *expandAddRecExprLiterally(const SCEVAddRecExpr *);
  210. PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
  211. const Loop *L,
  212. Type *ExpandTy,
  213. Type *IntTy,
  214. Type *&TruncTy,
  215. bool &InvertStep);
  216. Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
  217. Type *ExpandTy, Type *IntTy, bool useSubtract);
  218. };
  219. }
  220. #endif