blob: 729a0c325448967d793392a80e806f1ead969ce9 [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"
Dan Gohman5be18e82009-05-19 02:15:55 +000018#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000019#include "llvm/ADT/STLExtras.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000020using namespace llvm;
21
Dan Gohman267a3852009-06-27 21:18:18 +000022/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
23/// which must be possible with a noop cast, doing what we can to share
24/// the casts.
25Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
26 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
27 assert((Op == Instruction::BitCast ||
28 Op == Instruction::PtrToInt ||
29 Op == Instruction::IntToPtr) &&
30 "InsertNoopCastOfTo cannot perform non-noop casts!");
31 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
32 "InsertNoopCastOfTo cannot change sizes!");
33
Dan Gohman2d1be872009-04-16 03:18:22 +000034 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000035 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000036 return V;
37
Dan Gohmanf04fa482009-04-16 15:52:57 +000038 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000039 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000040 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000041 if (CastInst *CI = dyn_cast<CastInst>(V))
42 if ((CI->getOpcode() == Instruction::PtrToInt ||
43 CI->getOpcode() == Instruction::IntToPtr) &&
44 SE.getTypeSizeInBits(CI->getType()) ==
45 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
46 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000047 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
48 if ((CE->getOpcode() == Instruction::PtrToInt ||
49 CE->getOpcode() == Instruction::IntToPtr) &&
50 SE.getTypeSizeInBits(CE->getType()) ==
51 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
52 return CE->getOperand(0);
53 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000054
Chris Lattnerca1a4be2006-02-04 09:51:53 +000055 // FIXME: keep track of the cast instruction.
56 if (Constant *C = dyn_cast<Constant>(V))
Dan Gohman267a3852009-06-27 21:18:18 +000057 return ConstantExpr::getCast(Op, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000058
59 if (Argument *A = dyn_cast<Argument>(V)) {
60 // Check to see if there is already a cast!
61 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
Dan Gohman40a5a1b2009-06-24 01:18:18 +000062 UI != E; ++UI)
Chris Lattnerca1a4be2006-02-04 09:51:53 +000063 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000064 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000065 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000066 // If the cast isn't the first instruction of the function, move it.
Dan Gohman40a5a1b2009-06-24 01:18:18 +000067 if (BasicBlock::iterator(CI) !=
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000068 A->getParent()->getEntryBlock().begin()) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +000069 // Recreate the cast at the beginning of the entry block.
70 // The old cast is left in place in case it is being used
71 // as an insert point.
72 Instruction *NewCI =
Dan Gohman267a3852009-06-27 21:18:18 +000073 CastInst::Create(Op, V, Ty, "",
Dan Gohman40a5a1b2009-06-24 01:18:18 +000074 A->getParent()->getEntryBlock().begin());
75 NewCI->takeName(CI);
76 CI->replaceAllUsesWith(NewCI);
77 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000078 }
79 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000080 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +000081
Dan Gohman267a3852009-06-27 21:18:18 +000082 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
Dan Gohmancf5ab822009-05-01 17:13:31 +000083 A->getParent()->getEntryBlock().begin());
84 InsertedValues.insert(I);
85 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000086 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000087
Chris Lattnerca1a4be2006-02-04 09:51:53 +000088 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000089
Chris Lattnerca1a4be2006-02-04 09:51:53 +000090 // Check to see if there is already a cast. If there is, use it.
91 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
92 UI != E; ++UI) {
93 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000094 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000095 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000096 BasicBlock::iterator It = I; ++It;
97 if (isa<InvokeInst>(I))
98 It = cast<InvokeInst>(I)->getNormalDest()->begin();
99 while (isa<PHINode>(It)) ++It;
100 if (It != BasicBlock::iterator(CI)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000101 // Recreate the cast at the beginning of the entry block.
102 // The old cast is left in place in case it is being used
103 // as an insert point.
Dan Gohman267a3852009-06-27 21:18:18 +0000104 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000105 NewCI->takeName(CI);
106 CI->replaceAllUsesWith(NewCI);
107 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000108 }
109 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000110 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000111 }
112 BasicBlock::iterator IP = I; ++IP;
113 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
114 IP = II->getNormalDest()->begin();
115 while (isa<PHINode>(IP)) ++IP;
Dan Gohman267a3852009-06-27 21:18:18 +0000116 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000117 InsertedValues.insert(CI);
118 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000119}
120
Chris Lattner7fec90e2007-04-13 05:04:18 +0000121/// InsertBinop - Insert the specified binary operator, doing a small amount
122/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000123Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
124 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000125 // Fold a binop with constant operands.
126 if (Constant *CLHS = dyn_cast<Constant>(LHS))
127 if (Constant *CRHS = dyn_cast<Constant>(RHS))
128 return ConstantExpr::get(Opcode, CLHS, CRHS);
129
Chris Lattner7fec90e2007-04-13 05:04:18 +0000130 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
131 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000132 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
133 // Scanning starts from the last instruction before the insertion point.
134 BasicBlock::iterator IP = Builder.GetInsertPoint();
135 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000136 --IP;
137 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000138 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
139 IP->getOperand(1) == RHS)
140 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000141 if (IP == BlockBegin) break;
142 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000143 }
Dan Gohman267a3852009-06-27 21:18:18 +0000144
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000145 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000146 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000147 InsertedValues.insert(BO);
148 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000149}
150
Dan Gohman4a4f7672009-05-27 02:00:53 +0000151/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000152/// division. If so, update S with Factor divided out and return true.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000153/// S need not be evenly divisble if a reasonable remainder can be
154/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000155/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
156/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
157/// check to see if the divide was folded.
Owen Anderson372b46c2009-06-22 21:39:50 +0000158static bool FactorOutConstant(const SCEV* &S,
159 const SCEV* &Remainder,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000160 const APInt &Factor,
161 ScalarEvolution &SE) {
162 // Everything is divisible by one.
163 if (Factor == 1)
164 return true;
165
166 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000167 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
168 ConstantInt *CI =
169 ConstantInt::get(C->getValue()->getValue().sdiv(Factor));
170 // If the quotient is zero and the remainder is non-zero, reject
171 // the value at this scale. It will be considered for subsequent
172 // smaller scales.
173 if (C->isZero() || !CI->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000174 const SCEV* Div = SE.getConstant(CI);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000175 S = Div;
Dan Gohman4a4f7672009-05-27 02:00:53 +0000176 Remainder =
177 SE.getAddExpr(Remainder,
178 SE.getConstant(C->getValue()->getValue().srem(Factor)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000179 return true;
180 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000181 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000182
183 // In a Mul, check if there is a constant operand which is a multiple
184 // of the given factor.
185 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
186 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
187 if (!C->getValue()->getValue().srem(Factor)) {
Dan Gohman5001c212009-06-30 01:25:30 +0000188 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
189 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
190 MOperands.end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000191 NewMulOps[0] =
192 SE.getConstant(C->getValue()->getValue().sdiv(Factor));
193 S = SE.getMulExpr(NewMulOps);
194 return true;
195 }
196
197 // In an AddRec, check if both start and step are divisible.
198 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000199 const SCEV* Step = A->getStepRecurrence(SE);
200 const SCEV* StepRem = SE.getIntegerSCEV(0, Step->getType());
Dan Gohman4a4f7672009-05-27 02:00:53 +0000201 if (!FactorOutConstant(Step, StepRem, Factor, SE))
202 return false;
203 if (!StepRem->isZero())
204 return false;
Owen Anderson372b46c2009-06-22 21:39:50 +0000205 const SCEV* Start = A->getStart();
Dan Gohman4a4f7672009-05-27 02:00:53 +0000206 if (!FactorOutConstant(Start, Remainder, Factor, SE))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000207 return false;
208 S = SE.getAddRecExpr(Start, Step, A->getLoop());
209 return true;
210 }
211
212 return false;
213}
214
Dan Gohman5be18e82009-05-19 02:15:55 +0000215/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
Dan Gohman453aa4f2009-05-24 18:06:31 +0000216/// instead of using ptrtoint+arithmetic+inttoptr. This helps
217/// BasicAliasAnalysis analyze the result. However, it suffers from the
218/// underlying bug described in PR2831. Addition in LLVM currently always
219/// has two's complement wrapping guaranteed. However, the semantics for
220/// getelementptr overflow are ambiguous. In the common case though, this
221/// expansion gets used when a GEP in the original code has been converted
222/// into integer arithmetic, in which case the resulting code will be no
223/// more undefined than it was originally.
224///
225/// Design note: It might seem desirable for this function to be more
226/// loop-aware. If some of the indices are loop-invariant while others
227/// aren't, it might seem desirable to emit multiple GEPs, keeping the
228/// loop-invariant portions of the overall computation outside the loop.
229/// However, there are a few reasons this is not done here. Hoisting simple
230/// arithmetic is a low-level optimization that often isn't very
231/// important until late in the optimization process. In fact, passes
232/// like InstructionCombining will combine GEPs, even if it means
233/// pushing loop-invariant computation down into loops, so even if the
234/// GEPs were split here, the work would quickly be undone. The
235/// LoopStrengthReduction pass, which is usually run quite late (and
236/// after the last InstructionCombining pass), takes care of hoisting
237/// loop-invariant portions of expressions, after considering what
238/// can be folded using target addressing modes.
239///
Owen Anderson372b46c2009-06-22 21:39:50 +0000240Value *SCEVExpander::expandAddToGEP(const SCEV* const *op_begin,
241 const SCEV* const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000242 const PointerType *PTy,
243 const Type *Ty,
244 Value *V) {
245 const Type *ElTy = PTy->getElementType();
246 SmallVector<Value *, 4> GepIndices;
Owen Anderson372b46c2009-06-22 21:39:50 +0000247 SmallVector<const SCEV*, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000248 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000249
250 // Decend down the pointer's type and attempt to convert the other
251 // operands into GEP indices, at each level. The first index in a GEP
252 // indexes into the array implied by the pointer operand; the rest of
253 // the indices index into the element or field type selected by the
254 // preceding index.
255 for (;;) {
256 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
257 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
Owen Anderson372b46c2009-06-22 21:39:50 +0000258 SmallVector<const SCEV*, 8> NewOps;
259 SmallVector<const SCEV*, 8> ScaledOps;
Dan Gohman5be18e82009-05-19 02:15:55 +0000260 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000261 // Split AddRecs up into parts as either of the parts may be usable
262 // without the other.
263 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
264 if (!A->getStart()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000265 const SCEV* Start = A->getStart();
Dan Gohman453aa4f2009-05-24 18:06:31 +0000266 Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
267 A->getStepRecurrence(SE),
268 A->getLoop()));
269 Ops[i] = Start;
270 ++e;
271 }
272 // If the scale size is not 0, attempt to factor out a scale.
Dan Gohman5be18e82009-05-19 02:15:55 +0000273 if (ElSize != 0) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000274 const SCEV* Op = Ops[i];
275 const SCEV* Remainder = SE.getIntegerSCEV(0, Op->getType());
Dan Gohman4a4f7672009-05-27 02:00:53 +0000276 if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000277 ScaledOps.push_back(Op); // Op now has ElSize factored out.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000278 NewOps.push_back(Remainder);
Dan Gohman5be18e82009-05-19 02:15:55 +0000279 continue;
280 }
281 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000282 // If the operand was not divisible, add it to the list of operands
283 // we'll scan next iteration.
Dan Gohman5be18e82009-05-19 02:15:55 +0000284 NewOps.push_back(Ops[i]);
285 }
286 Ops = NewOps;
287 AnyNonZeroIndices |= !ScaledOps.empty();
288 Value *Scaled = ScaledOps.empty() ?
289 Constant::getNullValue(Ty) :
290 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
291 GepIndices.push_back(Scaled);
292
293 // Collect struct field index operands.
294 if (!Ops.empty())
295 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
296 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
297 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
298 const StructLayout &SL = *SE.TD->getStructLayout(STy);
299 uint64_t FullOffset = C->getValue()->getZExtValue();
300 if (FullOffset < SL.getSizeInBytes()) {
301 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
302 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
303 ElTy = STy->getTypeAtIndex(ElIdx);
304 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000305 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000306 AnyNonZeroIndices = true;
307 continue;
308 }
309 }
310 break;
311 }
312
313 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
314 ElTy = ATy->getElementType();
315 continue;
316 }
317 break;
318 }
319
320 // If none of the operands were convertable to proper GEP indices, cast
321 // the base to i8* and do an ugly getelementptr with that. It's still
322 // better than ptrtoint+arithmetic+inttoptr at least.
323 if (!AnyNonZeroIndices) {
324 V = InsertNoopCastOfTo(V,
325 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
Dan Gohman92fcdca2009-06-09 17:18:38 +0000326 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000327
328 // Fold a GEP with constant operands.
329 if (Constant *CLHS = dyn_cast<Constant>(V))
330 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Dan Gohman278b49a2009-05-19 19:18:01 +0000331 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000332
333 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
334 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000335 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
336 // Scanning starts from the last instruction before the insertion point.
337 BasicBlock::iterator IP = Builder.GetInsertPoint();
338 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000339 --IP;
340 for (; ScanLimit; --IP, --ScanLimit) {
341 if (IP->getOpcode() == Instruction::GetElementPtr &&
342 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
343 return IP;
344 if (IP == BlockBegin) break;
345 }
346 }
347
Dan Gohman267a3852009-06-27 21:18:18 +0000348 Value *GEP = Builder.CreateGEP(V, Idx, "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000349 InsertedValues.insert(GEP);
350 return GEP;
351 }
352
353 // Insert a pretty getelementptr.
Dan Gohman267a3852009-06-27 21:18:18 +0000354 Value *GEP = Builder.CreateGEP(V,
355 GepIndices.begin(),
356 GepIndices.end(),
357 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000358 Ops.push_back(SE.getUnknown(GEP));
359 InsertedValues.insert(GEP);
360 return expand(SE.getAddExpr(Ops));
361}
362
Dan Gohman890f92b2009-04-18 17:56:28 +0000363Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000364 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000365 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000366
Dan Gohman453aa4f2009-05-24 18:06:31 +0000367 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
368 // comments on expandAddToGEP for details.
Dan Gohman5be18e82009-05-19 02:15:55 +0000369 if (SE.TD)
Dan Gohman453aa4f2009-05-24 18:06:31 +0000370 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000371 const SmallVectorImpl<const SCEV*> &Ops = S->getOperands();
Dan Gohman5001c212009-06-30 01:25:30 +0000372 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000373 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000374
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000375 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000376
377 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000378 for (int i = S->getNumOperands()-2; i >= 0; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000379 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000380 V = InsertBinop(Instruction::Add, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000381 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000382 return V;
383}
Dan Gohman5be18e82009-05-19 02:15:55 +0000384
Dan Gohman890f92b2009-04-18 17:56:28 +0000385Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000386 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000387 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000388 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000389 if (SC->getValue()->isAllOnesValue())
390 FirstOp = 1;
391
392 int i = S->getNumOperands()-2;
Dan Gohman92fcdca2009-06-09 17:18:38 +0000393 Value *V = expandCodeFor(S->getOperand(i+1), Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000394
395 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000396 for (; i >= FirstOp; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000397 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000398 V = InsertBinop(Instruction::Mul, V, W);
Dan Gohman2d1be872009-04-16 03:18:22 +0000399 }
400
Nate Begeman36f891b2005-07-30 00:12:19 +0000401 // -1 * ... ---> 0 - ...
402 if (FirstOp == 1)
Dan Gohman267a3852009-06-27 21:18:18 +0000403 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000404 return V;
405}
406
Dan Gohman890f92b2009-04-18 17:56:28 +0000407Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000408 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000409
Dan Gohman92fcdca2009-06-09 17:18:38 +0000410 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000411 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000412 const APInt &RHS = SC->getValue()->getValue();
413 if (RHS.isPowerOf2())
414 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman267a3852009-06-27 21:18:18 +0000415 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000416 }
417
Dan Gohman92fcdca2009-06-09 17:18:38 +0000418 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000419 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000420}
421
Dan Gohman453aa4f2009-05-24 18:06:31 +0000422/// Move parts of Base into Rest to leave Base with the minimal
423/// expression that provides a pointer operand suitable for a
424/// GEP expansion.
Owen Anderson372b46c2009-06-22 21:39:50 +0000425static void ExposePointerBase(const SCEV* &Base, const SCEV* &Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000426 ScalarEvolution &SE) {
427 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
428 Base = A->getStart();
429 Rest = SE.getAddExpr(Rest,
430 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
431 A->getStepRecurrence(SE),
432 A->getLoop()));
433 }
434 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
435 Base = A->getOperand(A->getNumOperands()-1);
Owen Anderson372b46c2009-06-22 21:39:50 +0000436 SmallVector<const SCEV*, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000437 NewAddOps.back() = Rest;
438 Rest = SE.getAddExpr(NewAddOps);
439 ExposePointerBase(Base, Rest, SE);
440 }
441}
442
Dan Gohman890f92b2009-04-18 17:56:28 +0000443Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000444 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000445 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +0000446
Dan Gohman4d8414f2009-06-13 16:25:49 +0000447 // First check for an existing canonical IV in a suitable type.
448 PHINode *CanonicalIV = 0;
449 if (PHINode *PN = L->getCanonicalInductionVariable())
450 if (SE.isSCEVable(PN->getType()) &&
451 isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
452 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
453 CanonicalIV = PN;
454
455 // Rewrite an AddRec in terms of the canonical induction variable, if
456 // its type is more narrow.
457 if (CanonicalIV &&
458 SE.getTypeSizeInBits(CanonicalIV->getType()) >
459 SE.getTypeSizeInBits(Ty)) {
Dan Gohman5001c212009-06-30 01:25:30 +0000460 const SCEV *Start = SE.getAnyExtendExpr(S->getStart(),
461 CanonicalIV->getType());
462 const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
Dan Gohman4d8414f2009-06-13 16:25:49 +0000463 CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000464 Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +0000465 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
466 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +0000467 BasicBlock::iterator NewInsertPt =
468 next(BasicBlock::iterator(cast<Instruction>(V)));
469 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
470 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
471 NewInsertPt);
Dan Gohman267a3852009-06-27 21:18:18 +0000472 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000473 return V;
474 }
475
Nate Begeman36f891b2005-07-30 00:12:19 +0000476 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000477 if (!S->getStart()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000478 const SmallVectorImpl<const SCEV*> &SOperands = S->getOperands();
479 SmallVector<const SCEV*, 4> NewOps(SOperands.begin(), SOperands.end());
Dan Gohman246b2562007-10-22 18:31:58 +0000480 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +0000481 const SCEV* Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000482
483 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
484 // comments on expandAddToGEP for details.
485 if (SE.TD) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000486 const SCEV* Base = S->getStart();
487 const SCEV* RestArray[1] = { Rest };
Dan Gohman453aa4f2009-05-24 18:06:31 +0000488 // Dig into the expression to find the pointer base for a GEP.
489 ExposePointerBase(Base, RestArray[0], SE);
490 // If we found a pointer, expand the AddRec with a GEP.
491 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanf876ad02009-05-26 17:41:16 +0000492 // Make sure the Base isn't something exotic, such as a multiplied
493 // or divided pointer value. In those cases, the result type isn't
494 // actually a pointer type.
495 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
496 Value *StartV = expand(Base);
497 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
498 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
499 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000500 }
501 }
502
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000503 // Just do a normal add. Pre-expand the operands to suppress folding.
504 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
505 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +0000506 }
507
508 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000509 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000510 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000511 // If there's a canonical IV, just use it.
512 if (CanonicalIV) {
513 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
514 "IVs with types different from the canonical IV should "
515 "already have been handled!");
516 return CanonicalIV;
517 }
518
Nate Begeman36f891b2005-07-30 00:12:19 +0000519 // Create and insert the PHI node for the induction variable in the
520 // specified loop.
521 BasicBlock *Header = L->getHeader();
Dan Gohman267a3852009-06-27 21:18:18 +0000522 BasicBlock *Preheader = L->getLoopPreheader();
Gabor Greif051a9502008-04-06 20:25:17 +0000523 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000524 InsertedValues.insert(PN);
Dan Gohman267a3852009-06-27 21:18:18 +0000525 PN->addIncoming(Constant::getNullValue(Ty), Preheader);
Nate Begeman36f891b2005-07-30 00:12:19 +0000526
527 pred_iterator HPI = pred_begin(Header);
528 assert(HPI != pred_end(Header) && "Loop with zero preds???");
529 if (!L->contains(*HPI)) ++HPI;
530 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
531 "No backedge in loop?");
532
533 // Insert a unit add instruction right before the terminator corresponding
534 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000535 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000536 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000537 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000538 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000539
540 pred_iterator PI = pred_begin(Header);
Dan Gohman267a3852009-06-27 21:18:18 +0000541 if (*PI == Preheader)
Nate Begeman36f891b2005-07-30 00:12:19 +0000542 ++PI;
543 PN->addIncoming(Add, *PI);
544 return PN;
545 }
546
Dan Gohman4d8414f2009-06-13 16:25:49 +0000547 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +0000548 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +0000549 Value *I = CanonicalIV ?
550 CanonicalIV :
551 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000552
Chris Lattnerdf14a042005-10-30 06:24:33 +0000553 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000554 if (S->isAffine()) // {0,+,F} --> i*F
555 return
556 expand(SE.getTruncateOrNoop(
557 SE.getMulExpr(SE.getUnknown(I),
558 SE.getNoopOrAnyExtend(S->getOperand(1),
559 I->getType())),
560 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +0000561
562 // If this is a chain of recurrences, turn it into a closed form, using the
563 // folders, then expandCodeFor the closed form. This allows the folders to
564 // simplify the expression without having to build a bunch of special code
565 // into this folder.
Owen Anderson372b46c2009-06-22 21:39:50 +0000566 const SCEV* IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000567
Dan Gohman4d8414f2009-06-13 16:25:49 +0000568 // Promote S up to the canonical IV type, if the cast is foldable.
Owen Anderson372b46c2009-06-22 21:39:50 +0000569 const SCEV* NewS = S;
570 const SCEV* Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +0000571 if (isa<SCEVAddRecExpr>(Ext))
572 NewS = Ext;
573
Owen Anderson372b46c2009-06-22 21:39:50 +0000574 const SCEV* V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000575 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000576
Dan Gohman4d8414f2009-06-13 16:25:49 +0000577 // Truncate the result down to the original type, if needed.
Owen Anderson372b46c2009-06-22 21:39:50 +0000578 const SCEV* T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +0000579 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +0000580}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000581
Dan Gohman890f92b2009-04-18 17:56:28 +0000582Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000583 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000584 Value *V = expandCodeFor(S->getOperand(),
585 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000586 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000587 InsertedValues.insert(I);
588 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000589}
590
Dan Gohman890f92b2009-04-18 17:56:28 +0000591Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000592 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000593 Value *V = expandCodeFor(S->getOperand(),
594 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000595 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000596 InsertedValues.insert(I);
597 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000598}
599
Dan Gohman890f92b2009-04-18 17:56:28 +0000600Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000601 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000602 Value *V = expandCodeFor(S->getOperand(),
603 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +0000604 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000605 InsertedValues.insert(I);
606 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000607}
608
Dan Gohman890f92b2009-04-18 17:56:28 +0000609Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000610 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000611 Value *LHS = expandCodeFor(S->getOperand(0), Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000612 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000613 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000614 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000615 InsertedValues.insert(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000616 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000617 InsertedValues.insert(Sel);
618 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000619 }
620 return LHS;
621}
622
Dan Gohman890f92b2009-04-18 17:56:28 +0000623Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000624 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000625 Value *LHS = expandCodeFor(S->getOperand(0), Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000626 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000627 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000628 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000629 InsertedValues.insert(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +0000630 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmancf5ab822009-05-01 17:13:31 +0000631 InsertedValues.insert(Sel);
632 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000633 }
634 return LHS;
635}
636
Owen Anderson372b46c2009-06-22 21:39:50 +0000637Value *SCEVExpander::expandCodeFor(const SCEV* SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000638 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000639 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000640 if (Ty) {
641 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
642 "non-trivial casts should be done with the SCEVs directly!");
643 V = InsertNoopCastOfTo(V, Ty);
644 }
645 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000646}
647
Dan Gohman890f92b2009-04-18 17:56:28 +0000648Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000649 // Compute an insertion point for this SCEV object. Hoist the instructions
650 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +0000651 Instruction *InsertPt = Builder.GetInsertPoint();
652 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000653 L = L->getParentLoop())
654 if (S->isLoopInvariant(L)) {
655 if (!L) break;
656 if (BasicBlock *Preheader = L->getLoopPreheader())
657 InsertPt = Preheader->getTerminator();
658 } else {
659 // If the SCEV is computable at this level, insert it into the header
660 // after the PHIs (and after any other instructions that we've inserted
661 // there) so that it is guaranteed to dominate any user inside the loop.
662 if (L && S->hasComputableLoopEvolution(L))
663 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman267a3852009-06-27 21:18:18 +0000664 while (isInsertedInstruction(InsertPt))
665 InsertPt = next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000666 break;
667 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000668
Dan Gohman667d7872009-06-26 22:53:46 +0000669 // Check to see if we already expanded this here.
670 std::map<std::pair<const SCEV *, Instruction *>,
671 AssertingVH<Value> >::iterator I =
672 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +0000673 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +0000674 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +0000675
676 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
677 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
678 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +0000679
680 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000681 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000682
Dan Gohman667d7872009-06-26 22:53:46 +0000683 // Remember the expanded value for this SCEV at this location.
684 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
685
Dan Gohman267a3852009-06-27 21:18:18 +0000686 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000687 return V;
688}
Dan Gohman1d09de32009-06-05 16:35:53 +0000689
690/// getOrInsertCanonicalInductionVariable - This method returns the
691/// canonical induction variable of the specified type for the specified
692/// loop (inserting one if there is none). A canonical induction variable
693/// starts at zero and steps by one on each iteration.
694Value *
695SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
696 const Type *Ty) {
697 assert(Ty->isInteger() && "Can only insert integer induction variables!");
Owen Anderson372b46c2009-06-22 21:39:50 +0000698 const SCEV* H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000699 SE.getIntegerSCEV(1, Ty), L);
Dan Gohman267a3852009-06-27 21:18:18 +0000700 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
701 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000702 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +0000703 if (SaveInsertBB)
704 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000705 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +0000706}