[IndVarSimplify] Make cost estimation in RewriteLoopExitValues smarter
[oota-llvm.git] / include / llvm / Analysis / ScalarEvolutionExpander.h
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
14 #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
15 #define LLVM_ANALYSIS_SCALAREVOLUTIONEXPANDER_H
16
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"
22 #include <set>
23
24 namespace llvm {
25   class TargetTransformInfo;
26
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);
30
31   /// This class uses information about analyze scalars to
32   /// rewrite expressions in canonical form.
33   ///
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
36   /// memory.
37   class SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
38     ScalarEvolution &SE;
39     const DataLayout &DL;
40
41     // New instructions receive a name to identifies them with the current pass.
42     const char* IVName;
43
44     // InsertedExpressions caches Values for reuse, so must track RAUW.
45     std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >
46       InsertedExpressions;
47     // InsertedValues only flags inserted instructions so needs no RAUW.
48     std::set<AssertingVH<Value> > InsertedValues;
49     std::set<AssertingVH<Value> > InsertedPostIncValues;
50
51     /// A memoization of the "relevant" loop for a given SCEV.
52     DenseMap<const SCEV *, const Loop *> RelevantLoops;
53
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;
60
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;
64
65     /// \brief When expanding addrecs in the IVIncInsertLoop loop, insert the IV
66     /// increment at this position.
67     Instruction *IVIncInsertPos;
68
69     /// \brief Phis that complete an IV chain. Reuse
70     std::set<AssertingVH<PHINode> > ChainedPhis;
71
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
75     /// literal form.
76     bool CanonicalMode;
77
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.
81     bool LSRMode;
82
83     typedef IRBuilder<true, TargetFolder> BuilderType;
84     BuilderType Builder;
85
86 #ifndef NDEBUG
87     const char *DebugType;
88 #endif
89
90     friend struct SCEVVisitor<SCEVExpander, Value*>;
91
92   public:
93     /// \brief Construct a SCEVExpander in "canonical" mode.
94     explicit SCEVExpander(ScalarEvolution &se, const DataLayout &DL,
95                           const char *name)
96         : SE(se), DL(DL), IVName(name), IVIncInsertLoop(nullptr),
97           IVIncInsertPos(nullptr), CanonicalMode(true), LSRMode(false),
98           Builder(se.getContext(), TargetFolder(DL)) {
99 #ifndef NDEBUG
100       DebugType = "";
101 #endif
102     }
103
104 #ifndef NDEBUG
105     void setDebugType(const char* s) { DebugType = s; }
106 #endif
107
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.
111     void clear() {
112       InsertedExpressions.clear();
113       InsertedValues.clear();
114       InsertedPostIncValues.clear();
115       ChainedPhis.clear();
116     }
117
118     /// \brief Return true for expressions that may incur non-trivial cost to
119     /// evaluate at runtime.
120     /// 'At' is an optional parameter which specifies point in code where user
121     /// is going to expand this expression. Sometimes this knowledge can lead to
122     /// a more accurate cost estimation.
123     bool isHighCostExpansion(const SCEV *Expr, Loop *L,
124                              const Instruction *At = nullptr) {
125       SmallPtrSet<const SCEV *, 8> Processed;
126       return isHighCostExpansionHelper(Expr, L, At, Processed);
127     }
128
129     /// \brief This method returns the canonical induction variable of the
130     /// specified type for the specified loop (inserting one if there is none).
131     /// A canonical induction variable starts at zero and steps by one on each
132     /// iteration.
133     PHINode *getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty);
134
135     /// \brief Return the induction variable increment's IV operand.
136     Instruction *getIVIncOperand(Instruction *IncV, Instruction *InsertPos,
137                                  bool allowScale);
138
139     /// \brief Utility for hoisting an IV increment.
140     bool hoistIVInc(Instruction *IncV, Instruction *InsertPos);
141
142     /// \brief replace congruent phis with their most canonical
143     /// representative. Return the number of phis eliminated.
144     unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
145                                  SmallVectorImpl<WeakVH> &DeadInsts,
146                                  const TargetTransformInfo *TTI = nullptr);
147
148     /// \brief Insert code to directly compute the specified SCEV expression
149     /// into the program.  The inserted code is inserted into the specified
150     /// block.
151     Value *expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I);
152
153     /// \brief Set the current IV increment loop and position.
154     void setIVIncInsertPos(const Loop *L, Instruction *Pos) {
155       assert(!CanonicalMode &&
156              "IV increment positions are not supported in CanonicalMode");
157       IVIncInsertLoop = L;
158       IVIncInsertPos = Pos;
159     }
160
161     /// \brief Enable post-inc expansion for addrecs referring to the given
162     /// loops. Post-inc expansion is only supported in non-canonical mode.
163     void setPostInc(const PostIncLoopSet &L) {
164       assert(!CanonicalMode &&
165              "Post-inc expansion is not supported in CanonicalMode");
166       PostIncLoops = L;
167     }
168
169     /// \brief Disable all post-inc expansion.
170     void clearPostInc() {
171       PostIncLoops.clear();
172
173       // When we change the post-inc loop set, cached expansions may no
174       // longer be valid.
175       InsertedPostIncValues.clear();
176     }
177
178     /// \brief Disable the behavior of expanding expressions in canonical form
179     /// rather than in a more literal form. Non-canonical mode is useful for
180     /// late optimization passes.
181     void disableCanonicalMode() { CanonicalMode = false; }
182
183     void enableLSRMode() { LSRMode = true; }
184
185     /// \brief Clear the current insertion point. This is useful if the
186     /// instruction that had been serving as the insertion point may have been
187     /// deleted.
188     void clearInsertPoint() {
189       Builder.ClearInsertionPoint();
190     }
191
192     /// \brief Return true if the specified instruction was inserted by the code
193     /// rewriter.  If so, the client should not modify the instruction.
194     bool isInsertedInstruction(Instruction *I) const {
195       return InsertedValues.count(I) || InsertedPostIncValues.count(I);
196     }
197
198     void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
199
200     /// \brief Try to find LLVM IR value for 'S' available at the point 'At'.
201     // 'L' is a hint which tells in which loop to look for the suitable value.
202     // On success return value which is equivalent to the expanded 'S' at point
203     // 'At'. Return nullptr if value was not found.
204     // Note that this function does not perform exhaustive search. I.e if it
205     // didn't find any value it does not mean that there is no such value.
206     Value *findExistingExpansion(const SCEV *S, const Instruction *At, Loop *L);
207
208   private:
209     LLVMContext &getContext() const { return SE.getContext(); }
210
211     /// \brief Recursive helper function for isHighCostExpansion.
212     bool isHighCostExpansionHelper(const SCEV *S, Loop *L,
213                                    const Instruction *At,
214                                    SmallPtrSetImpl<const SCEV *> &Processed);
215
216     /// \brief Insert the specified binary operator, doing a small amount
217     /// of work to avoid inserting an obviously redundant operation.
218     Value *InsertBinop(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS);
219
220     /// \brief Arrange for there to be a cast of V to Ty at IP, reusing an
221     /// existing cast if a suitable one exists, moving an existing cast if a
222     /// suitable one exists but isn't in the right place, or or creating a new
223     /// one.
224     Value *ReuseOrCreateCast(Value *V, Type *Ty,
225                              Instruction::CastOps Op,
226                              BasicBlock::iterator IP);
227
228     /// \brief Insert a cast of V to the specified type, which must be possible
229     /// with a noop cast, doing what we can to share the casts.
230     Value *InsertNoopCastOfTo(Value *V, Type *Ty);
231
232     /// \brief Expand a SCEVAddExpr with a pointer type into a GEP
233     /// instead of using ptrtoint+arithmetic+inttoptr.
234     Value *expandAddToGEP(const SCEV *const *op_begin,
235                           const SCEV *const *op_end,
236                           PointerType *PTy, Type *Ty, Value *V);
237
238     Value *expand(const SCEV *S);
239
240     /// \brief Insert code to directly compute the specified SCEV expression
241     /// into the program.  The inserted code is inserted into the SCEVExpander's
242     /// current insertion point. If a type is specified, the result will be
243     /// expanded to have that type, with a cast if necessary.
244     Value *expandCodeFor(const SCEV *SH, Type *Ty = nullptr);
245
246     /// \brief Determine the most "relevant" loop for the given SCEV.
247     const Loop *getRelevantLoop(const SCEV *);
248
249     Value *visitConstant(const SCEVConstant *S) {
250       return S->getValue();
251     }
252
253     Value *visitTruncateExpr(const SCEVTruncateExpr *S);
254
255     Value *visitZeroExtendExpr(const SCEVZeroExtendExpr *S);
256
257     Value *visitSignExtendExpr(const SCEVSignExtendExpr *S);
258
259     Value *visitAddExpr(const SCEVAddExpr *S);
260
261     Value *visitMulExpr(const SCEVMulExpr *S);
262
263     Value *visitUDivExpr(const SCEVUDivExpr *S);
264
265     Value *visitAddRecExpr(const SCEVAddRecExpr *S);
266
267     Value *visitSMaxExpr(const SCEVSMaxExpr *S);
268
269     Value *visitUMaxExpr(const SCEVUMaxExpr *S);
270
271     Value *visitUnknown(const SCEVUnknown *S) {
272       return S->getValue();
273     }
274
275     void rememberInstruction(Value *I);
276
277     bool isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
278
279     bool isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV, const Loop *L);
280
281     Value *expandAddRecExprLiterally(const SCEVAddRecExpr *);
282     PHINode *getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
283                                        const Loop *L,
284                                        Type *ExpandTy,
285                                        Type *IntTy,
286                                        Type *&TruncTy,
287                                        bool &InvertStep);
288     Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
289                        Type *ExpandTy, Type *IntTy, bool useSubtract);
290   };
291 }
292
293 #endif