blob: abfe94dc80bba34e09339c8698981247cbaf3f6d [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
Chris Lattnerca1a4be2006-02-04 09:51:53 +000022/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
23/// we can to share the casts.
Reid Spencer3ba68b92006-12-13 08:06:42 +000024Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
25 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +000026 // Short-circuit unnecessary bitcasts.
27 if (opcode == Instruction::BitCast && V->getType() == Ty)
28 return V;
29
Dan Gohmanf04fa482009-04-16 15:52:57 +000030 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohmanaf79fb52009-04-21 01:07:12 +000031 if ((opcode == Instruction::PtrToInt || opcode == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000032 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000033 if (CastInst *CI = dyn_cast<CastInst>(V))
34 if ((CI->getOpcode() == Instruction::PtrToInt ||
35 CI->getOpcode() == Instruction::IntToPtr) &&
36 SE.getTypeSizeInBits(CI->getType()) ==
37 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
38 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000039 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
40 if ((CE->getOpcode() == Instruction::PtrToInt ||
41 CE->getOpcode() == Instruction::IntToPtr) &&
42 SE.getTypeSizeInBits(CE->getType()) ==
43 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
44 return CE->getOperand(0);
45 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000046
Chris Lattnerca1a4be2006-02-04 09:51:53 +000047 // FIXME: keep track of the cast instruction.
48 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000049 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000050
51 if (Argument *A = dyn_cast<Argument>(V)) {
52 // Check to see if there is already a cast!
53 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
54 UI != E; ++UI) {
55 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000056 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
57 if (CI->getOpcode() == opcode) {
58 // If the cast isn't the first instruction of the function, move it.
59 if (BasicBlock::iterator(CI) !=
60 A->getParent()->getEntryBlock().begin()) {
Dan Gohmanaabb04f2009-04-22 16:11:16 +000061 // If the CastInst is the insert point, change the insert point.
62 if (CI == InsertPt) ++InsertPt;
63 // Splice the cast at the beginning of the entry block.
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000064 CI->moveBefore(A->getParent()->getEntryBlock().begin());
65 }
66 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000067 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000068 }
Dan Gohmancf5ab822009-05-01 17:13:31 +000069 Instruction *I = CastInst::Create(opcode, V, Ty, V->getName(),
70 A->getParent()->getEntryBlock().begin());
71 InsertedValues.insert(I);
72 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000073 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000074
Chris Lattnerca1a4be2006-02-04 09:51:53 +000075 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000076
Chris Lattnerca1a4be2006-02-04 09:51:53 +000077 // Check to see if there is already a cast. If there is, use it.
78 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
79 UI != E; ++UI) {
80 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000081 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
82 if (CI->getOpcode() == opcode) {
83 BasicBlock::iterator It = I; ++It;
84 if (isa<InvokeInst>(I))
85 It = cast<InvokeInst>(I)->getNormalDest()->begin();
86 while (isa<PHINode>(It)) ++It;
87 if (It != BasicBlock::iterator(CI)) {
Dan Gohmanaabb04f2009-04-22 16:11:16 +000088 // If the CastInst is the insert point, change the insert point.
89 if (CI == InsertPt) ++InsertPt;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000090 // Splice the cast immediately after the operand in question.
91 CI->moveBefore(It);
92 }
93 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000094 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000095 }
96 BasicBlock::iterator IP = I; ++IP;
97 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
98 IP = II->getNormalDest()->begin();
99 while (isa<PHINode>(IP)) ++IP;
Dan Gohmancf5ab822009-05-01 17:13:31 +0000100 Instruction *CI = CastInst::Create(opcode, V, Ty, V->getName(), IP);
101 InsertedValues.insert(CI);
102 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000103}
104
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000105/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
106/// which must be possible with a noop cast.
107Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
108 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
109 assert((Op == Instruction::BitCast ||
Devang Patele2a17462009-04-22 18:51:05 +0000110 Op == Instruction::PtrToInt ||
111 Op == Instruction::IntToPtr) &&
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000112 "InsertNoopCastOfTo cannot perform non-noop casts!");
113 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
114 "InsertNoopCastOfTo cannot change sizes!");
115 return InsertCastOfTo(Op, V, Ty);
116}
117
Chris Lattner7fec90e2007-04-13 05:04:18 +0000118/// InsertBinop - Insert the specified binary operator, doing a small amount
119/// of work to avoid inserting an obviously redundant operation.
120Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Dan Gohman6cdc7272009-04-22 16:05:50 +0000121 Value *RHS, BasicBlock::iterator InsertPt) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000122 // Fold a binop with constant operands.
123 if (Constant *CLHS = dyn_cast<Constant>(LHS))
124 if (Constant *CRHS = dyn_cast<Constant>(RHS))
125 return ConstantExpr::get(Opcode, CLHS, CRHS);
126
Chris Lattner7fec90e2007-04-13 05:04:18 +0000127 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
128 unsigned ScanLimit = 6;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000129 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
130 if (InsertPt != BlockBegin) {
131 // Scanning starts from the last instruction before InsertPt.
132 BasicBlock::iterator IP = InsertPt;
133 --IP;
134 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000135 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
136 IP->getOperand(1) == RHS)
137 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000138 if (IP == BlockBegin) break;
139 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000140 }
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000141
142 // If we haven't found this binop, insert it.
Dan Gohmancf5ab822009-05-01 17:13:31 +0000143 Instruction *BO = BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
144 InsertedValues.insert(BO);
145 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000146}
147
Dan Gohman4a4f7672009-05-27 02:00:53 +0000148/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000149/// division. If so, update S with Factor divided out and return true.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000150/// S need not be evenly divisble if a reasonable remainder can be
151/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000152/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
153/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
154/// check to see if the divide was folded.
155static bool FactorOutConstant(SCEVHandle &S,
Dan Gohman4a4f7672009-05-27 02:00:53 +0000156 SCEVHandle &Remainder,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000157 const APInt &Factor,
158 ScalarEvolution &SE) {
159 // Everything is divisible by one.
160 if (Factor == 1)
161 return true;
162
163 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000164 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
165 ConstantInt *CI =
166 ConstantInt::get(C->getValue()->getValue().sdiv(Factor));
167 // If the quotient is zero and the remainder is non-zero, reject
168 // the value at this scale. It will be considered for subsequent
169 // smaller scales.
170 if (C->isZero() || !CI->isZero()) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000171 SCEVHandle Div = SE.getConstant(CI);
172 S = Div;
Dan Gohman4a4f7672009-05-27 02:00:53 +0000173 Remainder =
174 SE.getAddExpr(Remainder,
175 SE.getConstant(C->getValue()->getValue().srem(Factor)));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000176 return true;
177 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000178 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000179
180 // In a Mul, check if there is a constant operand which is a multiple
181 // of the given factor.
182 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
183 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
184 if (!C->getValue()->getValue().srem(Factor)) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000185 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
186 SmallVector<SCEVHandle, 4> NewMulOps(MOperands.begin(), MOperands.end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000187 NewMulOps[0] =
188 SE.getConstant(C->getValue()->getValue().sdiv(Factor));
189 S = SE.getMulExpr(NewMulOps);
190 return true;
191 }
192
193 // In an AddRec, check if both start and step are divisible.
194 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000195 SCEVHandle Step = A->getStepRecurrence(SE);
Dan Gohman4a4f7672009-05-27 02:00:53 +0000196 SCEVHandle StepRem = SE.getIntegerSCEV(0, Step->getType());
197 if (!FactorOutConstant(Step, StepRem, Factor, SE))
198 return false;
199 if (!StepRem->isZero())
200 return false;
201 SCEVHandle Start = A->getStart();
202 if (!FactorOutConstant(Start, Remainder, Factor, SE))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000203 return false;
204 S = SE.getAddRecExpr(Start, Step, A->getLoop());
205 return true;
206 }
207
208 return false;
209}
210
Dan Gohman5be18e82009-05-19 02:15:55 +0000211/// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
Dan Gohman453aa4f2009-05-24 18:06:31 +0000212/// instead of using ptrtoint+arithmetic+inttoptr. This helps
213/// BasicAliasAnalysis analyze the result. However, it suffers from the
214/// underlying bug described in PR2831. Addition in LLVM currently always
215/// has two's complement wrapping guaranteed. However, the semantics for
216/// getelementptr overflow are ambiguous. In the common case though, this
217/// expansion gets used when a GEP in the original code has been converted
218/// into integer arithmetic, in which case the resulting code will be no
219/// more undefined than it was originally.
220///
221/// Design note: It might seem desirable for this function to be more
222/// loop-aware. If some of the indices are loop-invariant while others
223/// aren't, it might seem desirable to emit multiple GEPs, keeping the
224/// loop-invariant portions of the overall computation outside the loop.
225/// However, there are a few reasons this is not done here. Hoisting simple
226/// arithmetic is a low-level optimization that often isn't very
227/// important until late in the optimization process. In fact, passes
228/// like InstructionCombining will combine GEPs, even if it means
229/// pushing loop-invariant computation down into loops, so even if the
230/// GEPs were split here, the work would quickly be undone. The
231/// LoopStrengthReduction pass, which is usually run quite late (and
232/// after the last InstructionCombining pass), takes care of hoisting
233/// loop-invariant portions of expressions, after considering what
234/// can be folded using target addressing modes.
235///
236Value *SCEVExpander::expandAddToGEP(const SCEVHandle *op_begin,
237 const SCEVHandle *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000238 const PointerType *PTy,
239 const Type *Ty,
240 Value *V) {
241 const Type *ElTy = PTy->getElementType();
242 SmallVector<Value *, 4> GepIndices;
Dan Gohmana82752c2009-06-14 22:47:23 +0000243 SmallVector<SCEVHandle, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000244 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000245
246 // Decend down the pointer's type and attempt to convert the other
247 // operands into GEP indices, at each level. The first index in a GEP
248 // indexes into the array implied by the pointer operand; the rest of
249 // the indices index into the element or field type selected by the
250 // preceding index.
251 for (;;) {
252 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
253 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
Dan Gohmana82752c2009-06-14 22:47:23 +0000254 SmallVector<SCEVHandle, 8> NewOps;
255 SmallVector<SCEVHandle, 8> ScaledOps;
Dan Gohman5be18e82009-05-19 02:15:55 +0000256 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000257 // Split AddRecs up into parts as either of the parts may be usable
258 // without the other.
259 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
260 if (!A->getStart()->isZero()) {
261 SCEVHandle Start = A->getStart();
262 Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
263 A->getStepRecurrence(SE),
264 A->getLoop()));
265 Ops[i] = Start;
266 ++e;
267 }
268 // If the scale size is not 0, attempt to factor out a scale.
Dan Gohman5be18e82009-05-19 02:15:55 +0000269 if (ElSize != 0) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000270 SCEVHandle Op = Ops[i];
Dan Gohman4a4f7672009-05-27 02:00:53 +0000271 SCEVHandle Remainder = SE.getIntegerSCEV(0, Op->getType());
272 if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000273 ScaledOps.push_back(Op); // Op now has ElSize factored out.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000274 NewOps.push_back(Remainder);
Dan Gohman5be18e82009-05-19 02:15:55 +0000275 continue;
276 }
277 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000278 // If the operand was not divisible, add it to the list of operands
279 // we'll scan next iteration.
Dan Gohman5be18e82009-05-19 02:15:55 +0000280 NewOps.push_back(Ops[i]);
281 }
282 Ops = NewOps;
283 AnyNonZeroIndices |= !ScaledOps.empty();
284 Value *Scaled = ScaledOps.empty() ?
285 Constant::getNullValue(Ty) :
286 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
287 GepIndices.push_back(Scaled);
288
289 // Collect struct field index operands.
290 if (!Ops.empty())
291 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
292 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
293 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
294 const StructLayout &SL = *SE.TD->getStructLayout(STy);
295 uint64_t FullOffset = C->getValue()->getZExtValue();
296 if (FullOffset < SL.getSizeInBytes()) {
297 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
298 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
299 ElTy = STy->getTypeAtIndex(ElIdx);
300 Ops[0] =
301 SE.getConstant(ConstantInt::get(Ty,
302 FullOffset -
303 SL.getElementOffset(ElIdx)));
304 AnyNonZeroIndices = true;
305 continue;
306 }
307 }
308 break;
309 }
310
311 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
312 ElTy = ATy->getElementType();
313 continue;
314 }
315 break;
316 }
317
318 // If none of the operands were convertable to proper GEP indices, cast
319 // the base to i8* and do an ugly getelementptr with that. It's still
320 // better than ptrtoint+arithmetic+inttoptr at least.
321 if (!AnyNonZeroIndices) {
322 V = InsertNoopCastOfTo(V,
323 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
Dan Gohman92fcdca2009-06-09 17:18:38 +0000324 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000325
326 // Fold a GEP with constant operands.
327 if (Constant *CLHS = dyn_cast<Constant>(V))
328 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Dan Gohman278b49a2009-05-19 19:18:01 +0000329 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000330
331 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
332 unsigned ScanLimit = 6;
333 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
334 if (InsertPt != BlockBegin) {
335 // Scanning starts from the last instruction before InsertPt.
336 BasicBlock::iterator IP = InsertPt;
337 --IP;
338 for (; ScanLimit; --IP, --ScanLimit) {
339 if (IP->getOpcode() == Instruction::GetElementPtr &&
340 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
341 return IP;
342 if (IP == BlockBegin) break;
343 }
344 }
345
346 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
347 InsertedValues.insert(GEP);
348 return GEP;
349 }
350
351 // Insert a pretty getelementptr.
352 Value *GEP = GetElementPtrInst::Create(V,
353 GepIndices.begin(),
354 GepIndices.end(),
355 "scevgep", InsertPt);
356 Ops.push_back(SE.getUnknown(GEP));
357 InsertedValues.insert(GEP);
358 return expand(SE.getAddExpr(Ops));
359}
360
Dan Gohman890f92b2009-04-18 17:56:28 +0000361Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000362 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmane24fa642008-06-18 16:37:11 +0000363 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman5be18e82009-05-19 02:15:55 +0000364
Dan Gohman453aa4f2009-05-24 18:06:31 +0000365 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
366 // comments on expandAddToGEP for details.
Dan Gohman5be18e82009-05-19 02:15:55 +0000367 if (SE.TD)
Dan Gohman453aa4f2009-05-24 18:06:31 +0000368 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000369 const SmallVectorImpl<SCEVHandle> &Ops = S->getOperands();
Dan Gohmanfb5a3412009-05-24 19:02:45 +0000370 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1],
Dan Gohman453aa4f2009-05-24 18:06:31 +0000371 PTy, Ty, V);
372 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000373
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000374 V = InsertNoopCastOfTo(V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000375
376 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000377 for (int i = S->getNumOperands()-2; i >= 0; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000378 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000379 V = InsertBinop(Instruction::Add, V, W, InsertPt);
380 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000381 return V;
382}
Dan Gohman5be18e82009-05-19 02:15:55 +0000383
Dan Gohman890f92b2009-04-18 17:56:28 +0000384Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000385 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000386 int FirstOp = 0; // Set if we should emit a subtract.
Dan Gohman890f92b2009-04-18 17:56:28 +0000387 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
Nate Begeman36f891b2005-07-30 00:12:19 +0000388 if (SC->getValue()->isAllOnesValue())
389 FirstOp = 1;
390
391 int i = S->getNumOperands()-2;
Dan Gohman92fcdca2009-06-09 17:18:38 +0000392 Value *V = expandCodeFor(S->getOperand(i+1), Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000393
394 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000395 for (; i >= FirstOp; --i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000396 Value *W = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000397 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
398 }
399
Nate Begeman36f891b2005-07-30 00:12:19 +0000400 // -1 * ... ---> 0 - ...
401 if (FirstOp == 1)
Dan Gohman2d1be872009-04-16 03:18:22 +0000402 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000403 return V;
404}
405
Dan Gohman890f92b2009-04-18 17:56:28 +0000406Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000407 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000408
Dan Gohman92fcdca2009-06-09 17:18:38 +0000409 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000410 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000411 const APInt &RHS = SC->getValue()->getValue();
412 if (RHS.isPowerOf2())
413 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman2d1be872009-04-16 03:18:22 +0000414 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky6177fd42008-07-08 05:05:37 +0000415 InsertPt);
416 }
417
Dan Gohman92fcdca2009-06-09 17:18:38 +0000418 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000419 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
420}
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.
425static void ExposePointerBase(SCEVHandle &Base, SCEVHandle &Rest,
426 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);
Dan Gohmana82752c2009-06-14 22:47:23 +0000436 SmallVector<SCEVHandle, 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)) {
460 SCEVHandle Start = SE.getAnyExtendExpr(S->getStart(),
461 CanonicalIV->getType());
462 SCEVHandle Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
463 CanonicalIV->getType());
464 Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
465 BasicBlock::iterator SaveInsertPt = getInsertionPoint();
466 BasicBlock::iterator NewInsertPt =
467 next(BasicBlock::iterator(cast<Instruction>(V)));
468 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
469 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
470 NewInsertPt);
471 setInsertionPoint(SaveInsertPt);
472 return V;
473 }
474
Nate Begeman36f891b2005-07-30 00:12:19 +0000475 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000476 if (!S->getStart()->isZero()) {
Dan Gohmana82752c2009-06-14 22:47:23 +0000477 const SmallVectorImpl<SCEVHandle> &SOperands = S->getOperands();
478 SmallVector<SCEVHandle, 4> NewOps(SOperands.begin(), SOperands.end());
Dan Gohman246b2562007-10-22 18:31:58 +0000479 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000480 SCEVHandle Rest = SE.getAddRecExpr(NewOps, L);
481
482 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
483 // comments on expandAddToGEP for details.
484 if (SE.TD) {
485 SCEVHandle Base = S->getStart();
Dan Gohmanf1a80482009-05-27 02:07:15 +0000486 SCEVHandle RestArray[1] = { Rest };
Dan Gohman453aa4f2009-05-24 18:06:31 +0000487 // Dig into the expression to find the pointer base for a GEP.
488 ExposePointerBase(Base, RestArray[0], SE);
489 // If we found a pointer, expand the AddRec with a GEP.
490 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanf876ad02009-05-26 17:41:16 +0000491 // Make sure the Base isn't something exotic, such as a multiplied
492 // or divided pointer value. In those cases, the result type isn't
493 // actually a pointer type.
494 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
495 Value *StartV = expand(Base);
496 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
497 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
498 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000499 }
500 }
501
502 Value *RestV = expand(Rest);
503 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(RestV)));
Nate Begeman36f891b2005-07-30 00:12:19 +0000504 }
505
506 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000507 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000508 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +0000509 // If there's a canonical IV, just use it.
510 if (CanonicalIV) {
511 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
512 "IVs with types different from the canonical IV should "
513 "already have been handled!");
514 return CanonicalIV;
515 }
516
Nate Begeman36f891b2005-07-30 00:12:19 +0000517 // Create and insert the PHI node for the induction variable in the
518 // specified loop.
519 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000520 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000521 InsertedValues.insert(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +0000522 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
523
524 pred_iterator HPI = pred_begin(Header);
525 assert(HPI != pred_end(Header) && "Loop with zero preds???");
526 if (!L->contains(*HPI)) ++HPI;
527 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
528 "No backedge in loop?");
529
530 // Insert a unit add instruction right before the terminator corresponding
531 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000532 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000533 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000534 (*HPI)->getTerminator());
Dan Gohmancf5ab822009-05-01 17:13:31 +0000535 InsertedValues.insert(Add);
Nate Begeman36f891b2005-07-30 00:12:19 +0000536
537 pred_iterator PI = pred_begin(Header);
538 if (*PI == L->getLoopPreheader())
539 ++PI;
540 PN->addIncoming(Add, *PI);
541 return PN;
542 }
543
Dan Gohman4d8414f2009-06-13 16:25:49 +0000544 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +0000545 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +0000546 Value *I = CanonicalIV ?
547 CanonicalIV :
548 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000549
Chris Lattnerdf14a042005-10-30 06:24:33 +0000550 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman17f19722008-06-22 19:23:09 +0000551 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohman92fcdca2009-06-09 17:18:38 +0000552 Value *F = expandCodeFor(S->getOperand(1), Ty);
Dan Gohman4d8414f2009-06-13 16:25:49 +0000553
Chris Lattnerdf14a042005-10-30 06:24:33 +0000554 // If the insert point is directly inside of the loop, emit the multiply at
555 // the insert point. Otherwise, L is a loop that is a parent of the insert
556 // point loop. If we can, move the multiply to the outer most loop that it
557 // is safe to be in.
Dan Gohman6cdc7272009-04-22 16:05:50 +0000558 BasicBlock::iterator MulInsertPt = getInsertionPoint();
Dan Gohman5be18e82009-05-19 02:15:55 +0000559 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
Chris Lattnerdf14a042005-10-30 06:24:33 +0000560 if (InsertPtLoop != L && InsertPtLoop &&
561 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000562 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000563 // If we cannot hoist the multiply out of this loop, don't.
564 if (!InsertPtLoop->isLoopInvariant(F)) break;
565
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000566 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
567
568 // If this loop hasn't got a preheader, we aren't able to hoist the
569 // multiply.
570 if (!InsertPtLoopPH)
571 break;
572
573 // Otherwise, move the insert point to the preheader.
574 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000575 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000576 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000577 }
578
Chris Lattner7fec90e2007-04-13 05:04:18 +0000579 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000580 }
581
582 // If this is a chain of recurrences, turn it into a closed form, using the
583 // folders, then expandCodeFor the closed form. This allows the folders to
584 // simplify the expression without having to build a bunch of special code
585 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000586 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000587
Dan Gohman4d8414f2009-06-13 16:25:49 +0000588 // Promote S up to the canonical IV type, if the cast is foldable.
589 SCEVHandle NewS = S;
590 SCEVHandle Ext = SE.getNoopOrAnyExtend(S, I->getType());
591 if (isa<SCEVAddRecExpr>(Ext))
592 NewS = Ext;
593
594 SCEVHandle V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000595 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000596
Dan Gohman4d8414f2009-06-13 16:25:49 +0000597 // Truncate the result down to the original type, if needed.
598 SCEVHandle T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmand19534a2007-06-15 14:38:12 +0000599 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000600}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000601
Dan Gohman890f92b2009-04-18 17:56:28 +0000602Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000603 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000604 Value *V = expandCodeFor(S->getOperand(),
605 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000606 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
607 InsertedValues.insert(I);
608 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000609}
610
Dan Gohman890f92b2009-04-18 17:56:28 +0000611Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000612 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000613 Value *V = expandCodeFor(S->getOperand(),
614 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000615 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
616 InsertedValues.insert(I);
617 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000618}
619
Dan Gohman890f92b2009-04-18 17:56:28 +0000620Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000621 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000622 Value *V = expandCodeFor(S->getOperand(),
623 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohmancf5ab822009-05-01 17:13:31 +0000624 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
625 InsertedValues.insert(I);
626 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000627}
628
Dan Gohman890f92b2009-04-18 17:56:28 +0000629Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000630 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000631 Value *LHS = expandCodeFor(S->getOperand(0), Ty);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000632 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000633 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000634 Instruction *ICmp =
635 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
636 InsertedValues.insert(ICmp);
637 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
638 InsertedValues.insert(Sel);
639 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000640 }
641 return LHS;
642}
643
Dan Gohman890f92b2009-04-18 17:56:28 +0000644Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000645 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +0000646 Value *LHS = expandCodeFor(S->getOperand(0), Ty);
Nick Lewycky3e630762008-02-20 06:48:22 +0000647 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
Dan Gohman92fcdca2009-06-09 17:18:38 +0000648 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000649 Instruction *ICmp =
650 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
651 InsertedValues.insert(ICmp);
652 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
653 InsertedValues.insert(Sel);
654 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +0000655 }
656 return LHS;
657}
658
Dan Gohman752ec7d2009-04-23 15:16:49 +0000659Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000660 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000661 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +0000662 if (Ty) {
663 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
664 "non-trivial casts should be done with the SCEVs directly!");
665 V = InsertNoopCastOfTo(V, Ty);
666 }
667 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000668}
669
Dan Gohman890f92b2009-04-18 17:56:28 +0000670Value *SCEVExpander::expand(const SCEV *S) {
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000671 // Check to see if we already expanded this.
Torok Edwin3790fb02009-05-24 19:36:09 +0000672 std::map<SCEVHandle, AssertingVH<Value> >::iterator I =
673 InsertedExpressions.find(S);
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000674 if (I != InsertedExpressions.end())
675 return I->second;
676
677 Value *V = visit(S);
678 InsertedExpressions[S] = V;
679 return V;
680}
Dan Gohman1d09de32009-06-05 16:35:53 +0000681
682/// getOrInsertCanonicalInductionVariable - This method returns the
683/// canonical induction variable of the specified type for the specified
684/// loop (inserting one if there is none). A canonical induction variable
685/// starts at zero and steps by one on each iteration.
686Value *
687SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
688 const Type *Ty) {
689 assert(Ty->isInteger() && "Can only insert integer induction variables!");
690 SCEVHandle H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
691 SE.getIntegerSCEV(1, Ty), L);
692 return expand(H);
693}