d91061b2b3a7cec2de5f48abec35a3a37609d732
[oota-llvm.git] / lib / Analysis / ScalarEvolutionExpander.cpp
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- 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 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 #include "llvm/Target/TargetData.h"
19 using namespace llvm;
20
21 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22 /// we can to share the casts.
23 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V, 
24                                     const Type *Ty) {
25   // Short-circuit unnecessary bitcasts.
26   if (opcode == Instruction::BitCast && V->getType() == Ty)
27     return V;
28
29   // FIXME: keep track of the cast instruction.
30   if (Constant *C = dyn_cast<Constant>(V))
31     return ConstantExpr::getCast(opcode, C, Ty);
32   
33   if (Argument *A = dyn_cast<Argument>(V)) {
34     // Check to see if there is already a cast!
35     for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
36          UI != E; ++UI) {
37       if ((*UI)->getType() == Ty)
38         if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
39           if (CI->getOpcode() == opcode) {
40             // If the cast isn't the first instruction of the function, move it.
41             if (BasicBlock::iterator(CI) != 
42                 A->getParent()->getEntryBlock().begin()) {
43               CI->moveBefore(A->getParent()->getEntryBlock().begin());
44             }
45             return CI;
46           }
47     }
48     return CastInst::Create(opcode, V, Ty, V->getName(), 
49                             A->getParent()->getEntryBlock().begin());
50   }
51
52   Instruction *I = cast<Instruction>(V);
53
54   // Check to see if there is already a cast.  If there is, use it.
55   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
56        UI != E; ++UI) {
57     if ((*UI)->getType() == Ty)
58       if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
59         if (CI->getOpcode() == opcode) {
60           BasicBlock::iterator It = I; ++It;
61           if (isa<InvokeInst>(I))
62             It = cast<InvokeInst>(I)->getNormalDest()->begin();
63           while (isa<PHINode>(It)) ++It;
64           if (It != BasicBlock::iterator(CI)) {
65             // Splice the cast immediately after the operand in question.
66             CI->moveBefore(It);
67           }
68           return CI;
69         }
70   }
71   BasicBlock::iterator IP = I; ++IP;
72   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
73     IP = II->getNormalDest()->begin();
74   while (isa<PHINode>(IP)) ++IP;
75   return CastInst::Create(opcode, V, Ty, V->getName(), IP);
76 }
77
78 /// InsertBinop - Insert the specified binary operator, doing a small amount
79 /// of work to avoid inserting an obviously redundant operation.
80 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
81                                  Value *RHS, Instruction *InsertPt) {
82   // Fold a binop with constant operands.
83   if (Constant *CLHS = dyn_cast<Constant>(LHS))
84     if (Constant *CRHS = dyn_cast<Constant>(RHS))
85       return ConstantExpr::get(Opcode, CLHS, CRHS);
86
87   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
88   unsigned ScanLimit = 6;
89   BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
90   if (InsertPt != BlockBegin) {
91     // Scanning starts from the last instruction before InsertPt.
92     BasicBlock::iterator IP = InsertPt;
93     --IP;
94     for (; ScanLimit; --IP, --ScanLimit) {
95       if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
96         if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
97             BinOp->getOperand(1) == RHS)
98           return BinOp;
99       if (IP == BlockBegin) break;
100     }
101   }
102   
103   // If we haven't found this binop, insert it.
104   return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
105 }
106
107 Value *SCEVExpander::visitAddExpr(SCEVAddExpr *S) {
108   const Type *Ty = S->getType();
109   if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
110   Value *V = expand(S->getOperand(S->getNumOperands()-1));
111   V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
112
113   // Emit a bunch of add instructions
114   for (int i = S->getNumOperands()-2; i >= 0; --i) {
115     Value *W = expand(S->getOperand(i));
116     W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
117     V = InsertBinop(Instruction::Add, V, W, InsertPt);
118   }
119   return V;
120 }
121     
122 Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
123   const Type *Ty = S->getType();
124   if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
125   int FirstOp = 0;  // Set if we should emit a subtract.
126   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
127     if (SC->getValue()->isAllOnesValue())
128       FirstOp = 1;
129
130   int i = S->getNumOperands()-2;
131   Value *V = expand(S->getOperand(i+1));
132   V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
133
134   // Emit a bunch of multiply instructions
135   for (; i >= FirstOp; --i) {
136     Value *W = expand(S->getOperand(i));
137     W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
138     V = InsertBinop(Instruction::Mul, V, W, InsertPt);
139   }
140
141   // -1 * ...  --->  0 - ...
142   if (FirstOp == 1)
143     V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
144   return V;
145 }
146
147 Value *SCEVExpander::visitUDivExpr(SCEVUDivExpr *S) {
148   const Type *Ty = S->getType();
149   if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
150
151   Value *LHS = expand(S->getLHS());
152   LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
153   if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
154     const APInt &RHS = SC->getValue()->getValue();
155     if (RHS.isPowerOf2())
156       return InsertBinop(Instruction::LShr, LHS,
157                          ConstantInt::get(Ty, RHS.logBase2()),
158                          InsertPt);
159   }
160
161   Value *RHS = expand(S->getRHS());
162   RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false), RHS, Ty);
163   return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
164 }
165
166 Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
167   const Type *Ty = S->getType();
168   const Loop *L = S->getLoop();
169   // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
170   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
171          "Cannot expand fp recurrences yet!");
172
173   // {X,+,F} --> X + {0,+,F}
174   if (!S->getStart()->isZero()) {
175     Value *Start = expand(S->getStart());
176     if (isa<PointerType>(Start->getType()))
177       Start = InsertCastOfTo(Instruction::PtrToInt, Start, TD.getIntPtrType());
178     std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
179     NewOps[0] = SE.getIntegerSCEV(0, Ty);
180     Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
181     if (isa<PointerType>(Rest->getType()))
182       Rest = InsertCastOfTo(Instruction::PtrToInt, Rest, TD.getIntPtrType());
183
184     // FIXME: look for an existing add to use.
185     return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
186   }
187
188   // {0,+,1} --> Insert a canonical induction variable into the loop!
189   if (S->isAffine() &&
190       S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
191     // Create and insert the PHI node for the induction variable in the
192     // specified loop.
193     BasicBlock *Header = L->getHeader();
194     PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
195     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
196
197     pred_iterator HPI = pred_begin(Header);
198     assert(HPI != pred_end(Header) && "Loop with zero preds???");
199     if (!L->contains(*HPI)) ++HPI;
200     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
201            "No backedge in loop?");
202
203     // Insert a unit add instruction right before the terminator corresponding
204     // to the back-edge.
205     Constant *One = ConstantInt::get(Ty, 1);
206     Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
207                                                  (*HPI)->getTerminator());
208
209     pred_iterator PI = pred_begin(Header);
210     if (*PI == L->getLoopPreheader())
211       ++PI;
212     PN->addIncoming(Add, *PI);
213     return PN;
214   }
215
216   // Get the canonical induction variable I for this loop.
217   Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
218
219   // If this is a simple linear addrec, emit it now as a special case.
220   if (S->isAffine()) {   // {0,+,F} --> i*F
221     Value *F = expand(S->getOperand(1));
222     
223     // IF the step is by one, just return the inserted IV.
224     if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
225       if (CI->getValue() == 1)
226         return I;
227     
228     // If the insert point is directly inside of the loop, emit the multiply at
229     // the insert point.  Otherwise, L is a loop that is a parent of the insert
230     // point loop.  If we can, move the multiply to the outer most loop that it
231     // is safe to be in.
232     Instruction *MulInsertPt = InsertPt;
233     Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
234     if (InsertPtLoop != L && InsertPtLoop &&
235         L->contains(InsertPtLoop->getHeader())) {
236       do {
237         // If we cannot hoist the multiply out of this loop, don't.
238         if (!InsertPtLoop->isLoopInvariant(F)) break;
239
240         BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
241
242         // If this loop hasn't got a preheader, we aren't able to hoist the
243         // multiply.
244         if (!InsertPtLoopPH)
245           break;
246
247         // Otherwise, move the insert point to the preheader.
248         MulInsertPt = InsertPtLoopPH->getTerminator();
249         InsertPtLoop = InsertPtLoop->getParentLoop();
250       } while (InsertPtLoop != L);
251     }
252     
253     return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
254   }
255
256   // If this is a chain of recurrences, turn it into a closed form, using the
257   // folders, then expandCodeFor the closed form.  This allows the folders to
258   // simplify the expression without having to build a bunch of special code
259   // into this folder.
260   SCEVHandle IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
261
262   SCEVHandle V = S->evaluateAtIteration(IH, SE);
263   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
264
265   return expand(V);
266 }
267
268 Value *SCEVExpander::visitTruncateExpr(SCEVTruncateExpr *S) {
269   Value *V = expand(S->getOperand());
270   if (isa<PointerType>(V->getType()))
271     V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
272   return CastInst::CreateTruncOrBitCast(V, S->getType(), "tmp.", InsertPt);
273 }
274
275 Value *SCEVExpander::visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
276   Value *V = expand(S->getOperand());
277   if (isa<PointerType>(V->getType()))
278     V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
279   return CastInst::CreateZExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
280 }
281
282 Value *SCEVExpander::visitSignExtendExpr(SCEVSignExtendExpr *S) {
283   Value *V = expand(S->getOperand());
284   if (isa<PointerType>(V->getType()))
285     V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
286   return CastInst::CreateSExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
287 }
288
289 Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
290   Value *LHS = expand(S->getOperand(0));
291   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
292     Value *RHS = expand(S->getOperand(i));
293     Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
294     LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
295   }
296   return LHS;
297 }
298
299 Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
300   Value *LHS = expand(S->getOperand(0));
301   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
302     Value *RHS = expand(S->getOperand(i));
303     Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
304     LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
305   }
306   return LHS;
307 }
308
309 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty,
310                                    Instruction *IP) {
311   // Expand the code for this SCEV.
312   assert(TD.getTypeSizeInBits(Ty) == TD.getTypeSizeInBits(SH->getType()) &&
313          "non-trivial casts should be done with the SCEVs directly!");
314   this->InsertPt = IP;
315   Value *V = expand(SH);
316   return InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
317 }
318
319 Value *SCEVExpander::expand(SCEV *S) {
320   // Check to see if we already expanded this.
321   std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
322   if (I != InsertedExpressions.end())
323     return I->second;
324   
325   Value *V = visit(S);
326   InsertedExpressions[S] = V;
327   return V;
328 }