Jeff's fix was fine
[oota-llvm.git] / lib / Analysis / ScalarEvolutionExpander.cpp
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- 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 contains the implementation of the scalar evolution expander,
11 // which is used to generate the code corresponding to a given scalar evolution
12 // expression.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 using namespace llvm;
19
20 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21 /// we can to share the casts.
22 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V, 
23                                     const Type *Ty) {
24   // FIXME: keep track of the cast instruction.
25   if (Constant *C = dyn_cast<Constant>(V))
26     return ConstantExpr::getCast(opcode, C, Ty);
27   
28   if (Argument *A = dyn_cast<Argument>(V)) {
29     // Check to see if there is already a cast!
30     for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
31          UI != E; ++UI) {
32       if ((*UI)->getType() == Ty)
33         if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
34           // If the cast isn't the first instruction of the function, move it.
35           if (BasicBlock::iterator(CI) != 
36               A->getParent()->getEntryBlock().begin()) {
37             CI->moveBefore(A->getParent()->getEntryBlock().begin());
38           }
39           return CI;
40         }
41     }
42     return CastInst::create(opcode, V, Ty, V->getName(), 
43                             A->getParent()->getEntryBlock().begin());
44   }
45     
46   Instruction *I = cast<Instruction>(V);
47   
48   // Check to see if there is already a cast.  If there is, use it.
49   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
50        UI != E; ++UI) {
51     if ((*UI)->getType() == Ty)
52       if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
53         BasicBlock::iterator It = I; ++It;
54         if (isa<InvokeInst>(I))
55           It = cast<InvokeInst>(I)->getNormalDest()->begin();
56         while (isa<PHINode>(It)) ++It;
57         if (It != BasicBlock::iterator(CI)) {
58           // Splice the cast immediately after the operand in question.
59           CI->moveBefore(It);
60         }
61         return CI;
62       }
63   }
64   BasicBlock::iterator IP = I; ++IP;
65   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
66     IP = II->getNormalDest()->begin();
67   while (isa<PHINode>(IP)) ++IP;
68   return CastInst::create(opcode, V, Ty, V->getName(), IP);
69 }
70
71 /// InsertBinop - Insert the specified binary operator, doing a small amount
72 /// of work to avoid inserting an obviously redundant operation.
73 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
74                                  Value *RHS, Instruction *&InsertPt) {
75   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
76   unsigned ScanLimit = 6;
77   for (BasicBlock::iterator IP = InsertPt, E = InsertPt->getParent()->begin();
78        ScanLimit; --IP, --ScanLimit) {
79     if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
80       if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
81           BinOp->getOperand(1) == RHS) {
82         // If we found the instruction *at* the insert point, insert later
83         // instructions after it.
84         if (BinOp == InsertPt)
85           InsertPt = ++IP;
86         return BinOp;
87       }
88     if (IP == E) break;
89   }
90
91   // If we don't have 
92   return BinaryOperator::create(Opcode, LHS, RHS, "tmp.", InsertPt);
93 }
94
95 Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
96   const Type *Ty = S->getType();
97   int FirstOp = 0;  // Set if we should emit a subtract.
98   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
99     if (SC->getValue()->isAllOnesValue())
100       FirstOp = 1;
101
102   int i = S->getNumOperands()-2;
103   Value *V = expandInTy(S->getOperand(i+1), Ty);
104
105   // Emit a bunch of multiply instructions
106   for (; i >= FirstOp; --i)
107     V = InsertBinop(Instruction::Mul, V, expandInTy(S->getOperand(i), Ty),
108                     InsertPt);
109   // -1 * ...  --->  0 - ...
110   if (FirstOp == 1)
111     V = InsertBinop(Instruction::Sub, Constant::getNullValue(V->getType()), V,
112                     InsertPt);
113   return V;
114 }
115
116 Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
117   const Type *Ty = S->getType();
118   const Loop *L = S->getLoop();
119   // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
120   assert(Ty->isInteger() && "Cannot expand fp recurrences yet!");
121
122   // {X,+,F} --> X + {0,+,F}
123   if (!isa<SCEVConstant>(S->getStart()) ||
124       !cast<SCEVConstant>(S->getStart())->getValue()->isZero()) {
125     Value *Start = expandInTy(S->getStart(), Ty);
126     std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
127     NewOps[0] = SCEVUnknown::getIntegerSCEV(0, Ty);
128     Value *Rest = expandInTy(SCEVAddRecExpr::get(NewOps, L), Ty);
129
130     // FIXME: look for an existing add to use.
131     return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
132   }
133
134   // {0,+,1} --> Insert a canonical induction variable into the loop!
135   if (S->getNumOperands() == 2 &&
136       S->getOperand(1) == SCEVUnknown::getIntegerSCEV(1, Ty)) {
137     // Create and insert the PHI node for the induction variable in the
138     // specified loop.
139     BasicBlock *Header = L->getHeader();
140     PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
141     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
142
143     pred_iterator HPI = pred_begin(Header);
144     assert(HPI != pred_end(Header) && "Loop with zero preds???");
145     if (!L->contains(*HPI)) ++HPI;
146     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
147            "No backedge in loop?");
148
149     // Insert a unit add instruction right before the terminator corresponding
150     // to the back-edge.
151     Constant *One = ConstantInt::get(Ty, 1);
152     Instruction *Add = BinaryOperator::createAdd(PN, One, "indvar.next",
153                                                  (*HPI)->getTerminator());
154
155     pred_iterator PI = pred_begin(Header);
156     if (*PI == L->getLoopPreheader())
157       ++PI;
158     PN->addIncoming(Add, *PI);
159     return PN;
160   }
161
162   // Get the canonical induction variable I for this loop.
163   Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
164
165   // If this is a simple linear addrec, emit it now as a special case.
166   if (S->getNumOperands() == 2) {   // {0,+,F} --> i*F
167     Value *F = expandInTy(S->getOperand(1), Ty);
168     
169     // IF the step is by one, just return the inserted IV.
170     if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
171       if (CI->getValue() == 1)
172         return I;
173     
174     // If the insert point is directly inside of the loop, emit the multiply at
175     // the insert point.  Otherwise, L is a loop that is a parent of the insert
176     // point loop.  If we can, move the multiply to the outer most loop that it
177     // is safe to be in.
178     Instruction *MulInsertPt = InsertPt;
179     Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
180     if (InsertPtLoop != L && InsertPtLoop &&
181         L->contains(InsertPtLoop->getHeader())) {
182       while (InsertPtLoop != L) {
183         // If we cannot hoist the multiply out of this loop, don't.
184         if (!InsertPtLoop->isLoopInvariant(F)) break;
185
186         // Otherwise, move the insert point to the preheader of the loop.
187         MulInsertPt = InsertPtLoop->getLoopPreheader()->getTerminator();
188         InsertPtLoop = InsertPtLoop->getParentLoop();
189       }
190     }
191     
192     return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
193   }
194
195   // If this is a chain of recurrences, turn it into a closed form, using the
196   // folders, then expandCodeFor the closed form.  This allows the folders to
197   // simplify the expression without having to build a bunch of special code
198   // into this folder.
199   SCEVHandle IH = SCEVUnknown::get(I);   // Get I as a "symbolic" SCEV.
200
201   SCEVHandle V = S->evaluateAtIteration(IH);
202   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
203
204   return expandInTy(V, Ty);
205 }