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