ScalarEvolutionExpander.h revision 8f9f0d3a34ebbcd6d075fbb1250dc74f36579d50
1//===---- llvm/Analysis/ScalarEvolutionExpander.h - SCEV Exprs --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/BasicBlock.h"
18#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
20#include "llvm/Type.h"
21#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/Analysis/ScalarEvolutionExpressions.h"
23#include "llvm/Support/CFG.h"
24
25namespace llvm {
26  /// SCEVExpander - 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 destroying it when finished to allow the release of the associated
31  /// memory.
32  struct SCEVExpander : public SCEVVisitor<SCEVExpander, Value*> {
33    ScalarEvolution &SE;
34    LoopInfo &LI;
35    std::map<SCEVHandle, Value*> InsertedExpressions;
36    std::set<Instruction*> InsertedInstructions;
37
38    Instruction *InsertPt;
39
40    friend struct SCEVVisitor<SCEVExpander, Value*>;
41  public:
42    SCEVExpander(ScalarEvolution &se, LoopInfo &li) : SE(se), LI(li) {}
43
44    LoopInfo &getLoopInfo() const { return LI; }
45
46    /// clear - Erase the contents of the InsertedExpressions map so that users
47    /// trying to expand the same expression into multiple BasicBlocks or
48    /// different places within the same BasicBlock can do so.
49    void clear() { InsertedExpressions.clear(); }
50
51    /// isInsertedInstruction - Return true if the specified instruction was
52    /// inserted by the code rewriter.  If so, the client should not modify the
53    /// instruction.
54    bool isInsertedInstruction(Instruction *I) const {
55      return InsertedInstructions.count(I);
56    }
57
58    /// getOrInsertCanonicalInductionVariable - This method returns the
59    /// canonical induction variable of the specified type for the specified
60    /// loop (inserting one if there is none).  A canonical induction variable
61    /// starts at zero and steps by one on each iteration.
62    Value *getOrInsertCanonicalInductionVariable(const Loop *L, const Type *Ty){
63      assert((Ty->isInteger() || Ty->isFloatingPoint()) &&
64             "Can only insert integer or floating point induction variables!");
65      SCEVHandle H = SCEVAddRecExpr::get(SCEVUnknown::getIntegerSCEV(0, Ty),
66                                         SCEVUnknown::getIntegerSCEV(1, Ty), L);
67      return expand(H);
68    }
69
70    /// addInsertedValue - Remember the specified instruction as being the
71    /// canonical form for the specified SCEV.
72    void addInsertedValue(Instruction *I, SCEV *S) {
73      InsertedExpressions[S] = (Value*)I;
74      InsertedInstructions.insert(I);
75    }
76
77    /// expandCodeFor - Insert code to directly compute the specified SCEV
78    /// expression into the program.  The inserted code is inserted into the
79    /// specified block.
80    ///
81    /// If a particular value sign is required, a type may be specified for the
82    /// result.
83    Value *expandCodeFor(SCEVHandle SH, Instruction *IP, const Type *Ty = 0) {
84      // Expand the code for this SCEV.
85      this->InsertPt = IP;
86      return expandInTy(SH, Ty);
87    }
88
89  protected:
90    Value *expand(SCEV *S) {
91      // Check to see if we already expanded this.
92      std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
93      if (I != InsertedExpressions.end())
94        return I->second;
95
96      Value *V = visit(S);
97      InsertedExpressions[S] = V;
98      return V;
99    }
100
101    Value *expandInTy(SCEV *S, const Type *Ty) {
102      Value *V = expand(S);
103      if (Ty && V->getType() != Ty) {
104        // FIXME: keep track of the cast instruction.
105        if (Constant *C = dyn_cast<Constant>(V))
106          return ConstantExpr::getCast(C, Ty);
107        else if (Instruction *I = dyn_cast<Instruction>(V)) {
108          // Check to see if there is already a cast.  If there is, use it.
109          for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
110               UI != E; ++UI) {
111            if ((*UI)->getType() == Ty)
112              if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
113                BasicBlock::iterator It = I; ++It;
114                if (isa<InvokeInst>(I))
115                  It = cast<InvokeInst>(I)->getNormalDest()->begin();
116                while (isa<PHINode>(It)) ++It;
117                if (It != BasicBlock::iterator(CI)) {
118                  // Splice the cast immediately after the operand in question.
119                  BasicBlock::InstListType &InstList =
120                    It->getParent()->getInstList();
121                  InstList.splice(It, CI->getParent()->getInstList(), CI);
122                }
123                return CI;
124              }
125          }
126          BasicBlock::iterator IP = I; ++IP;
127          if (InvokeInst *II = dyn_cast<InvokeInst>(I))
128            IP = II->getNormalDest()->begin();
129          while (isa<PHINode>(IP)) ++IP;
130          return new CastInst(V, Ty, V->getName(), IP);
131        } else {
132          // FIXME: check to see if there is already a cast!
133          return new CastInst(V, Ty, V->getName(), InsertPt);
134        }
135      }
136      return V;
137    }
138
139    Value *visitConstant(SCEVConstant *S) {
140      return S->getValue();
141    }
142
143    Value *visitTruncateExpr(SCEVTruncateExpr *S) {
144      Value *V = expand(S->getOperand());
145      return new CastInst(V, S->getType(), "tmp.", InsertPt);
146    }
147
148    Value *visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
149      Value *V = expandInTy(S->getOperand(),S->getType()->getUnsignedVersion());
150      return new CastInst(V, S->getType(), "tmp.", InsertPt);
151    }
152
153    Value *visitAddExpr(SCEVAddExpr *S) {
154      const Type *Ty = S->getType();
155      Value *V = expandInTy(S->getOperand(S->getNumOperands()-1), Ty);
156
157      // Emit a bunch of add instructions
158      for (int i = S->getNumOperands()-2; i >= 0; --i)
159        V = BinaryOperator::createAdd(V, expandInTy(S->getOperand(i), Ty),
160                                      "tmp.", InsertPt);
161      return V;
162    }
163
164    Value *visitMulExpr(SCEVMulExpr *S);
165
166    Value *visitUDivExpr(SCEVUDivExpr *S) {
167      const Type *Ty = S->getType();
168      Value *LHS = expandInTy(S->getLHS(), Ty);
169      Value *RHS = expandInTy(S->getRHS(), Ty);
170      return BinaryOperator::createDiv(LHS, RHS, "tmp.", InsertPt);
171    }
172
173    Value *visitAddRecExpr(SCEVAddRecExpr *S);
174
175    Value *visitUnknown(SCEVUnknown *S) {
176      return S->getValue();
177    }
178  };
179}
180
181#endif
182
183