blob: e7bc3f25d1435256b00a670d2323a8b0404f9064 [file] [log] [blame]
Nate Begeman36f891b2005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman36f891b2005-07-30 00:12:19 +00007//
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
Nate Begeman36f891b2005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000017#include "llvm/Analysis/LoopInfo.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000018using namespace llvm;
19
Chris Lattnerca1a4be2006-02-04 09:51:53 +000020/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21/// we can to share the casts.
Reid Spencer3ba68b92006-12-13 08:06:42 +000022Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
23 const Type *Ty) {
Chris Lattnerca1a4be2006-02-04 09:51:53 +000024 // FIXME: keep track of the cast instruction.
25 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000026 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000027
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)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000033 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
34 if (CI->getOpcode() == opcode) {
35 // If the cast isn't the first instruction of the function, move it.
36 if (BasicBlock::iterator(CI) !=
37 A->getParent()->getEntryBlock().begin()) {
38 CI->moveBefore(A->getParent()->getEntryBlock().begin());
39 }
40 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000041 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000042 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +000043 return CastInst::Create(opcode, V, Ty, V->getName(),
Reid Spencerd977d862006-12-12 23:36:14 +000044 A->getParent()->getEntryBlock().begin());
Chris Lattnerca1a4be2006-02-04 09:51:53 +000045 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000046
Chris Lattnerca1a4be2006-02-04 09:51:53 +000047 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000048
Chris Lattnerca1a4be2006-02-04 09:51:53 +000049 // Check to see if there is already a cast. If there is, use it.
50 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
51 UI != E; ++UI) {
52 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000053 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
54 if (CI->getOpcode() == opcode) {
55 BasicBlock::iterator It = I; ++It;
56 if (isa<InvokeInst>(I))
57 It = cast<InvokeInst>(I)->getNormalDest()->begin();
58 while (isa<PHINode>(It)) ++It;
59 if (It != BasicBlock::iterator(CI)) {
60 // Splice the cast immediately after the operand in question.
61 CI->moveBefore(It);
62 }
63 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000064 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000065 }
66 BasicBlock::iterator IP = I; ++IP;
67 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
68 IP = II->getNormalDest()->begin();
69 while (isa<PHINode>(IP)) ++IP;
Gabor Greif7cbd8a32008-05-16 19:29:10 +000070 return CastInst::Create(opcode, V, Ty, V->getName(), IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000071}
72
Chris Lattner7fec90e2007-04-13 05:04:18 +000073/// InsertBinop - Insert the specified binary operator, doing a small amount
74/// of work to avoid inserting an obviously redundant operation.
75Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +000076 Value *RHS, Instruction *InsertPt) {
Dan Gohman0f0eb182007-06-15 19:21:55 +000077 // Fold a binop with constant operands.
78 if (Constant *CLHS = dyn_cast<Constant>(LHS))
79 if (Constant *CRHS = dyn_cast<Constant>(RHS))
80 return ConstantExpr::get(Opcode, CLHS, CRHS);
81
Chris Lattner7fec90e2007-04-13 05:04:18 +000082 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
83 unsigned ScanLimit = 6;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +000084 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
85 if (InsertPt != BlockBegin) {
86 // Scanning starts from the last instruction before InsertPt.
87 BasicBlock::iterator IP = InsertPt;
88 --IP;
89 for (; ScanLimit; --IP, --ScanLimit) {
90 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
91 if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
92 BinOp->getOperand(1) == RHS)
93 return BinOp;
94 if (IP == BlockBegin) break;
95 }
Chris Lattner7fec90e2007-04-13 05:04:18 +000096 }
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +000097
98 // If we haven't found this binop, insert it.
Gabor Greif7cbd8a32008-05-16 19:29:10 +000099 return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
Chris Lattner7fec90e2007-04-13 05:04:18 +0000100}
101
Nate Begeman36f891b2005-07-30 00:12:19 +0000102Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000103 int FirstOp = 0; // Set if we should emit a subtract.
104 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
105 if (SC->getValue()->isAllOnesValue())
106 FirstOp = 1;
107
108 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000109 Value *V = expand(S->getOperand(i+1));
Nate Begeman36f891b2005-07-30 00:12:19 +0000110
111 // Emit a bunch of multiply instructions
112 for (; i >= FirstOp; --i)
Dan Gohmand19534a2007-06-15 14:38:12 +0000113 V = InsertBinop(Instruction::Mul, V, expand(S->getOperand(i)),
Chris Lattner7fec90e2007-04-13 05:04:18 +0000114 InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000115 // -1 * ... ---> 0 - ...
116 if (FirstOp == 1)
Chris Lattner7fec90e2007-04-13 05:04:18 +0000117 V = InsertBinop(Instruction::Sub, Constant::getNullValue(V->getType()), V,
118 InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000119 return V;
120}
121
122Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
123 const Type *Ty = S->getType();
124 const Loop *L = S->getLoop();
125 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
Chris Lattner42a75512007-01-15 02:27:26 +0000126 assert(Ty->isInteger() && "Cannot expand fp recurrences yet!");
Nate Begeman36f891b2005-07-30 00:12:19 +0000127
128 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000129 if (!S->getStart()->isZero()) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000130 Value *Start = expand(S->getStart());
Nate Begeman36f891b2005-07-30 00:12:19 +0000131 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000132 NewOps[0] = SE.getIntegerSCEV(0, Ty);
133 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
Nate Begeman36f891b2005-07-30 00:12:19 +0000134
135 // FIXME: look for an existing add to use.
Chris Lattner7fec90e2007-04-13 05:04:18 +0000136 return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000137 }
138
139 // {0,+,1} --> Insert a canonical induction variable into the loop!
140 if (S->getNumOperands() == 2 &&
Dan Gohman246b2562007-10-22 18:31:58 +0000141 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000142 // Create and insert the PHI node for the induction variable in the
143 // specified loop.
144 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000145 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Nate Begeman36f891b2005-07-30 00:12:19 +0000146 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
147
148 pred_iterator HPI = pred_begin(Header);
149 assert(HPI != pred_end(Header) && "Loop with zero preds???");
150 if (!L->contains(*HPI)) ++HPI;
151 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
152 "No backedge in loop?");
153
154 // Insert a unit add instruction right before the terminator corresponding
155 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000156 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000157 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000158 (*HPI)->getTerminator());
159
160 pred_iterator PI = pred_begin(Header);
161 if (*PI == L->getLoopPreheader())
162 ++PI;
163 PN->addIncoming(Add, *PI);
164 return PN;
165 }
166
167 // Get the canonical induction variable I for this loop.
168 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
169
Chris Lattnerdf14a042005-10-30 06:24:33 +0000170 // If this is a simple linear addrec, emit it now as a special case.
Nate Begeman36f891b2005-07-30 00:12:19 +0000171 if (S->getNumOperands() == 2) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000172 Value *F = expand(S->getOperand(1));
Chris Lattnerdf14a042005-10-30 06:24:33 +0000173
174 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000175 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000176 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000177 return I;
178
179 // If the insert point is directly inside of the loop, emit the multiply at
180 // the insert point. Otherwise, L is a loop that is a parent of the insert
181 // point loop. If we can, move the multiply to the outer most loop that it
182 // is safe to be in.
183 Instruction *MulInsertPt = InsertPt;
184 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
185 if (InsertPtLoop != L && InsertPtLoop &&
186 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000187 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000188 // If we cannot hoist the multiply out of this loop, don't.
189 if (!InsertPtLoop->isLoopInvariant(F)) break;
190
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000191 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
192
193 // If this loop hasn't got a preheader, we aren't able to hoist the
194 // multiply.
195 if (!InsertPtLoopPH)
196 break;
197
198 // Otherwise, move the insert point to the preheader.
199 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000200 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000201 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000202 }
203
Chris Lattner7fec90e2007-04-13 05:04:18 +0000204 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000205 }
206
207 // If this is a chain of recurrences, turn it into a closed form, using the
208 // folders, then expandCodeFor the closed form. This allows the folders to
209 // simplify the expression without having to build a bunch of special code
210 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000211 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000212
Dan Gohman246b2562007-10-22 18:31:58 +0000213 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000214 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000215
Dan Gohmand19534a2007-06-15 14:38:12 +0000216 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000217}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000218
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000219Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
220 Value *LHS = expand(S->getOperand(0));
221 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
222 Value *RHS = expand(S->getOperand(i));
223 Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
Gabor Greif051a9502008-04-06 20:25:17 +0000224 LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000225 }
226 return LHS;
227}
228
Nick Lewycky3e630762008-02-20 06:48:22 +0000229Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
230 Value *LHS = expand(S->getOperand(0));
231 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
232 Value *RHS = expand(S->getOperand(i));
233 Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
Gabor Greif051a9502008-04-06 20:25:17 +0000234 LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
Nick Lewycky3e630762008-02-20 06:48:22 +0000235 }
236 return LHS;
237}
238
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000239Value *SCEVExpander::expand(SCEV *S) {
240 // Check to see if we already expanded this.
241 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
242 if (I != InsertedExpressions.end())
243 return I->second;
244
245 Value *V = visit(S);
246 InsertedExpressions[S] = V;
247 return V;
248}