1 //===---- llvm/Analysis/ScalarEvolutionExpander.h - SCEV Exprs --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the classes used to generate code from scalar expressions.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
15 #define LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
17 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
18 #include "llvm/Analysis/ScalarEvolutionNormalization.h"
19 #include "llvm/Analysis/TargetFolder.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/ValueHandle.h"
25 class TargetTransformInfo;
27 /// Return true if the given expression is safe to expand in the sense that
28 /// all materialized values are safe to speculate.
29 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE);
31 /// This class uses information about analyze scalars to
32 /// rewrite expressions in canonical form.
34 /// Clients should create an instance of this class when rewriting is needed,
35 /// and destroy it when finished to allow the release of the associated
37 class SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
41 // New instructions receive a name to identifies them with the current pass.
44 // InsertedExpressions caches Values for reuse, so must track RAUW.
45 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >
47 // InsertedValues only flags inserted instructions so needs no RAUW.
48 std::set<AssertingVH<Value> > InsertedValues;
49 std::set<AssertingVH<Value> > InsertedPostIncValues;
51 /// A memoization of the "relevant" loop for a given SCEV.
52 DenseMap<const SCEV *, const Loop *> RelevantLoops;
54 /// \brief Addrecs referring to any of the given loops are expanded
55 /// in post-inc mode. For example, expanding {1,+,1}<L> in post-inc mode
56 /// returns the add instruction that adds one to the phi for {0,+,1}<L>,
57 /// as opposed to a new phi starting at 1. This is only supported in
58 /// non-canonical mode.
59 PostIncLoopSet PostIncLoops;
61 /// \brief When this is non-null, addrecs expanded in the loop it indicates
62 /// should be inserted with increments at IVIncInsertPos.
63 const Loop *IVIncInsertLoop;
65 /// \brief When expanding addrecs in the IVIncInsertLoop loop, insert the IV
66 /// increment at this position.
67 Instruction *IVIncInsertPos;
69 /// \brief Phis that complete an IV chain. Reuse
70 std::set<AssertingVH<PHINode> > ChainedPhis;
72 /// \brief When true, expressions are expanded in "canonical" form. In
73 /// particular, addrecs are expanded as arithmetic based on a canonical
74 /// induction variable. When false, expression are expanded in a more
78 /// \brief When invoked from LSR, the expander is in "strength reduction"
79 /// mode. The only difference is that phi's are only reused if they are
80 /// already in "expanded" form.
83 typedef IRBuilder<true, TargetFolder> BuilderType;
87 const char *DebugType;
90 friend struct SCEVVisitor<SCEVExpander, Value*>;
93 /// \brief Construct a SCEVExpander in "canonical" mode.
94 explicit SCEVExpander(ScalarEvolution &se, const DataLayout &DL,
96 : SE(se), DL(DL), IVName(name), IVIncInsertLoop(nullptr),
97 IVIncInsertPos(nullptr), CanonicalMode(true), LSRMode(false),
98 Builder(se.getContext(), TargetFolder(DL)) {
105 void setDebugType(const char* s) { DebugType = s; }
108 /// \brief Erase the contents of the InsertedExpressions map so that users
109 /// trying to expand the same expression into multiple BasicBlocks or
110 /// different places within the same BasicBlock can do so.
112 InsertedExpressions.clear();
113 InsertedValues.clear();
114 InsertedPostIncValues.clear();
118 /// \brief Return true for expressions that may incur non-trivial cost to
119 /// evaluate at runtime.
121 /// At is an optional parameter which specifies point in code where user is
122 /// going to expand this expression. Sometimes this knowledge can lead to a
123 /// more accurate cost estimation.
124 bool isHighCostExpansion(const SCEV *Expr, Loop *L,
125 const Instruction *At = nullptr) {
126 SmallPtrSet<const SCEV *, 8> Processed;
127 return isHighCostExpansionHelper(Expr, L, At, Processed);
130 /// \brief This method returns the canonical induction variable of the
131 /// specified type for the specified loop (inserting one if there is none).
132 /// A canonical induction variable starts at zero and steps by one on each
134 PHINode *getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty);
136 /// \brief Return the induction variable increment's IV operand.
137 Instruction *getIVIncOperand(Instruction *IncV, Instruction *InsertPos,
140 /// \brief Utility for hoisting an IV increment.
141 bool hoistIVInc(Instruction *IncV, Instruction *InsertPos);
143 /// \brief replace congruent phis with their most canonical
144 /// representative. Return the number of phis eliminated.
145 unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
146 SmallVectorImpl<WeakVH> &DeadInsts,
147 const TargetTransformInfo *TTI = nullptr);
149 /// \brief Insert code to directly compute the specified SCEV expression
150 /// into the program. The inserted code is inserted into the specified
152 Value *expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I);
154 /// \brief Generates a code sequence that evaluates this predicate.
155 /// The inserted instructions will be at position \p Loc.
156 /// The result will be of type i1 and will have a value of 0 when the
157 /// predicate is false and 1 otherwise.
158 Value *expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc);
160 /// \brief A specialized variant of expandCodeForPredicate, handling the
161 /// case when we are expanding code for a SCEVEqualPredicate.
162 Value *expandEqualPredicate(const SCEVEqualPredicate *Pred,
165 /// \brief A specialized variant of expandCodeForPredicate, handling the
166 /// case when we are expanding code for a SCEVUnionPredicate.
167 Value *expandUnionPredicate(const SCEVUnionPredicate *Pred,
170 /// \brief Set the current IV increment loop and position.
171 void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
172 assert(!CanonicalMode &&
173 "IV increment positions are not supported in CanonicalMode");
175 IVIncInsertPos = Pos;
178 /// \brief Enable post-inc expansion for addrecs referring to the given
179 /// loops. Post-inc expansion is only supported in non-canonical mode.
180 void setPostInc(const PostIncLoopSet &L) {
181 assert(!CanonicalMode &&
182 "Post-inc expansion is not supported in CanonicalMode");
186 /// \brief Disable all post-inc expansion.
187 void clearPostInc() {
188 PostIncLoops.clear();
190 // When we change the post-inc loop set, cached expansions may no
192 InsertedPostIncValues.clear();
195 /// \brief Disable the behavior of expanding expressions in canonical form
196 /// rather than in a more literal form. Non-canonical mode is useful for
197 /// late optimization passes.
198 void disableCanonicalMode() { CanonicalMode = false; }
200 void enableLSRMode() { LSRMode = true; }
202 /// \brief Clear the current insertion point. This is useful if the
203 /// instruction that had been serving as the insertion point may have been
205 void clearInsertPoint() {
206 Builder.ClearInsertionPoint();
209 /// \brief Return true if the specified instruction was inserted by the code
210 /// rewriter. If so, the client should not modify the instruction.
211 bool isInsertedInstruction(Instruction *I) const {
212 return InsertedValues.count(I) || InsertedPostIncValues.count(I);
215 void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
217 /// \brief Try to find LLVM IR value for S available at the point At.
219 /// L is a hint which tells in which loop to look for the suitable value.
220 /// On success return value which is equivalent to the expanded S at point
221 /// At. Return nullptr if value was not found.
223 /// Note that this function does not perform an exhaustive search. I.e if it
224 /// didn't find any value it does not mean that there is no such value.
225 Value *findExistingExpansion(const SCEV *S, const Instruction *At, Loop *L);
228 LLVMContext &getContext() const { return SE.getContext(); }
230 /// \brief Recursive helper function for isHighCostExpansion.
231 bool isHighCostExpansionHelper(const SCEV *S, Loop *L,
232 const Instruction *At,
233 SmallPtrSetImpl<const SCEV *> &Processed);
235 /// \brief Insert the specified binary operator, doing a small amount
236 /// of work to avoid inserting an obviously redundant operation.
237 Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS);
239 /// \brief Arrange for there to be a cast of V to Ty at IP, reusing an
240 /// existing cast if a suitable one exists, moving an existing cast if a
241 /// suitable one exists but isn't in the right place, or or creating a new
243 Value *ReuseOrCreateCast(Value *V, Type *Ty,
244 Instruction::CastOps Op,
245 BasicBlock::iterator IP);
247 /// \brief Insert a cast of V to the specified type, which must be possible
248 /// with a noop cast, doing what we can to share the casts.
249 Value *InsertNoopCastOfTo(Value *V, Type *Ty);
251 /// \brief Expand a SCEVAddExpr with a pointer type into a GEP
252 /// instead of using ptrtoint+arithmetic+inttoptr.
253 Value *expandAddToGEP(const SCEV *const *op_begin,
254 const SCEV *const *op_end,
255 PointerType *PTy, Type *Ty, Value *V);
257 Value *expand(const SCEV *S);
259 /// \brief Insert code to directly compute the specified SCEV expression
260 /// into the program. The inserted code is inserted into the SCEVExpander's
261 /// current insertion point. If a type is specified, the result will be
262 /// expanded to have that type, with a cast if necessary.
263 Value *expandCodeFor(const SCEV *SH, Type *Ty = nullptr);
265 /// \brief Determine the most "relevant" loop for the given SCEV.
266 const Loop *getRelevantLoop(const SCEV *);
268 Value *visitConstant(const SCEVConstant *S) {
269 return S->getValue();
272 Value *visitTruncateExpr(const SCEVTruncateExpr *S);
274 Value *visitZeroExtendExpr(const SCEVZeroExtendExpr *S);
276 Value *visitSignExtendExpr(const SCEVSignExtendExpr *S);
278 Value *visitAddExpr(const SCEVAddExpr *S);
280 Value *visitMulExpr(const SCEVMulExpr *S);
282 Value *visitUDivExpr(const SCEVUDivExpr *S);
284 Value *visitAddRecExpr(const SCEVAddRecExpr *S);
286 Value *visitSMaxExpr(const SCEVSMaxExpr *S);
288 Value *visitUMaxExpr(const SCEVUMaxExpr *S);
290 Value *visitUnknown(const SCEVUnknown *S) {
291 return S->getValue();
294 void rememberInstruction(Value *I);
296 bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
298 bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
300 Value *expandAddRecExprLiterally(const SCEVAddRecExpr *);
301 PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
307 Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
308 Type *ExpandTy, Type *IntTy, bool useSubtract);