blob: c47b33900e5ebb424f710a6ca4942799c5113ba3 [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"
Dale Johannesen8d50ea72010-03-05 21:12:40 +000018#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000019#include "llvm/LLVMContext.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000020#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000021#include "llvm/ADT/STLExtras.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000022using namespace llvm;
23
Dan Gohman485c43f2010-06-19 13:25:23 +000024/// ReuseOrCreateCast - Arange for there to be a cast of V to Ty at IP,
25/// reusing an existing cast if a suitable one exists, moving an existing
26/// cast if a suitable one exists but isn't in the right place, or
27/// or creating a new one.
28Value *SCEVExpander::ReuseOrCreateCast(Value *V, const Type *Ty,
29 Instruction::CastOps Op,
30 BasicBlock::iterator IP) {
31 // Check to see if there is already a cast!
32 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
33 UI != E; ++UI)
34 if ((*UI)->getType() == Ty)
35 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
36 if (CI->getOpcode() == Op) {
37 // If the cast isn't where we want it, fix it.
38 if (BasicBlock::iterator(CI) != IP) {
39 // Create a new cast, and leave the old cast in place in case
40 // it is being used as an insert point. Clear its operand
41 // so that it doesn't hold anything live.
42 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
43 NewCI->takeName(CI);
44 CI->replaceAllUsesWith(NewCI);
45 CI->setOperand(0, UndefValue::get(V->getType()));
46 rememberInstruction(NewCI);
47 return NewCI;
48 }
49 return CI;
50 }
51
52 // Create a new cast.
53 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
54 rememberInstruction(I);
55 return I;
56}
57
Dan Gohman267a3852009-06-27 21:18:18 +000058/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
59/// which must be possible with a noop cast, doing what we can to share
60/// the casts.
61Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
62 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
63 assert((Op == Instruction::BitCast ||
64 Op == Instruction::PtrToInt ||
65 Op == Instruction::IntToPtr) &&
66 "InsertNoopCastOfTo cannot perform non-noop casts!");
67 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
68 "InsertNoopCastOfTo cannot change sizes!");
69
Dan Gohman2d1be872009-04-16 03:18:22 +000070 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000071 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000072 return V;
73
Dan Gohmanf04fa482009-04-16 15:52:57 +000074 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000075 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000076 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000077 if (CastInst *CI = dyn_cast<CastInst>(V))
78 if ((CI->getOpcode() == Instruction::PtrToInt ||
79 CI->getOpcode() == Instruction::IntToPtr) &&
80 SE.getTypeSizeInBits(CI->getType()) ==
81 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
82 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000083 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
84 if ((CE->getOpcode() == Instruction::PtrToInt ||
85 CE->getOpcode() == Instruction::IntToPtr) &&
86 SE.getTypeSizeInBits(CE->getType()) ==
87 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
88 return CE->getOperand(0);
89 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000090
Dan Gohman485c43f2010-06-19 13:25:23 +000091 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000092 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000093 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000094
Dan Gohman485c43f2010-06-19 13:25:23 +000095 // Cast the argument at the beginning of the entry block, after
96 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000097 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +000098 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
99 while ((isa<BitCastInst>(IP) &&
100 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
101 cast<BitCastInst>(IP)->getOperand(0) != A) ||
102 isa<DbgInfoIntrinsic>(IP))
103 ++IP;
104 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000105 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000106
Dan Gohman485c43f2010-06-19 13:25:23 +0000107 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000108 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000109 BasicBlock::iterator IP = I; ++IP;
110 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
111 IP = II->getNormalDest()->begin();
Jim Grosbach08f55d02010-06-16 21:13:38 +0000112 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000113 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000114}
115
Chris Lattner7fec90e2007-04-13 05:04:18 +0000116/// InsertBinop - Insert the specified binary operator, doing a small amount
117/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000118Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
119 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000120 // Fold a binop with constant operands.
121 if (Constant *CLHS = dyn_cast<Constant>(LHS))
122 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000123 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000124
Chris Lattner7fec90e2007-04-13 05:04:18 +0000125 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
126 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000127 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
128 // Scanning starts from the last instruction before the insertion point.
129 BasicBlock::iterator IP = Builder.GetInsertPoint();
130 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000131 --IP;
132 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000133 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
134 // generated code.
135 if (isa<DbgInfoIntrinsic>(IP))
136 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000137 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
138 IP->getOperand(1) == RHS)
139 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000140 if (IP == BlockBegin) break;
141 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000142 }
Dan Gohman267a3852009-06-27 21:18:18 +0000143
Dan Gohman087bd1e2010-03-03 05:29:13 +0000144 // Save the original insertion point so we can restore it when we're done.
145 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
146 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
147
148 // Move the insertion point out of as many loops as we can.
149 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
150 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
151 BasicBlock *Preheader = L->getLoopPreheader();
152 if (!Preheader) break;
153
154 // Ok, move up a level.
155 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
156 }
157
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000158 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000159 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000160 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000161
162 // Restore the original insert point.
163 if (SaveInsertBB)
164 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
165
Dan Gohmancf5ab822009-05-01 17:13:31 +0000166 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000167}
168
Dan Gohman4a4f7672009-05-27 02:00:53 +0000169/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000170/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000171/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000172/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000173/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
174/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
175/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000176static bool FactorOutConstant(const SCEV *&S,
177 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000178 const SCEV *Factor,
179 ScalarEvolution &SE,
180 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000181 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000182 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000183 return true;
184
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000185 // x/x == 1.
186 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000187 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000188 return true;
189 }
190
Dan Gohman453aa4f2009-05-24 18:06:31 +0000191 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000192 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000193 // 0/x == 0.
194 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000195 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000196 // Check for divisibility.
197 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
198 ConstantInt *CI =
199 ConstantInt::get(SE.getContext(),
200 C->getValue()->getValue().sdiv(
201 FC->getValue()->getValue()));
202 // If the quotient is zero and the remainder is non-zero, reject
203 // the value at this scale. It will be considered for subsequent
204 // smaller scales.
205 if (!CI->isZero()) {
206 const SCEV *Div = SE.getConstant(CI);
207 S = Div;
208 Remainder =
209 SE.getAddExpr(Remainder,
210 SE.getConstant(C->getValue()->getValue().srem(
211 FC->getValue()->getValue())));
212 return true;
213 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000214 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000215 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000216
217 // In a Mul, check if there is a constant operand which is a multiple
218 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000219 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
220 if (TD) {
221 // With TargetData, the size is known. Check if there is a constant
222 // operand which is a multiple of the given factor. If so, we can
223 // factor it.
224 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
225 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
226 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000227 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000228 NewMulOps[0] =
229 SE.getConstant(C->getValue()->getValue().sdiv(
230 FC->getValue()->getValue()));
231 S = SE.getMulExpr(NewMulOps);
232 return true;
233 }
234 } else {
235 // Without TargetData, check if Factor can be factored out of any of the
236 // Mul's operands. If so, we can just remove it.
237 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
238 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000239 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000240 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
241 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000242 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000243 NewMulOps[i] = SOp;
244 S = SE.getMulExpr(NewMulOps);
245 return true;
246 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000247 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000248 }
249 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000250
251 // In an AddRec, check if both start and step are divisible.
252 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000253 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000254 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000255 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000256 return false;
257 if (!StepRem->isZero())
258 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000259 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000260 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000261 return false;
262 S = SE.getAddRecExpr(Start, Step, A->getLoop());
263 return true;
264 }
265
266 return false;
267}
268
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000269/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
270/// is the number of SCEVAddRecExprs present, which are kept at the end of
271/// the list.
272///
273static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
274 const Type *Ty,
275 ScalarEvolution &SE) {
276 unsigned NumAddRecs = 0;
277 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
278 ++NumAddRecs;
279 // Group Ops into non-addrecs and addrecs.
280 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
281 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
282 // Let ScalarEvolution sort and simplify the non-addrecs list.
283 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000284 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000285 SE.getAddExpr(NoAddRecs);
286 // If it returned an add, use the operands. Otherwise it simplified
287 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000288 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000289 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmanf9e64722010-03-18 01:17:13 +0000290 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
291 else if (!Sum->isZero())
292 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000293 // Then append the addrecs.
294 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
295}
296
297/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
298/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
299/// This helps expose more opportunities for folding parts of the expressions
300/// into GEP indices.
301///
302static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
303 const Type *Ty,
304 ScalarEvolution &SE) {
305 // Find the addrecs.
306 SmallVector<const SCEV *, 8> AddRecs;
307 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
308 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
309 const SCEV *Start = A->getStart();
310 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000311 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000312 AddRecs.push_back(SE.getAddRecExpr(Zero,
313 A->getStepRecurrence(SE),
314 A->getLoop()));
315 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
316 Ops[i] = Zero;
317 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
318 e += Add->getNumOperands();
319 } else {
320 Ops[i] = Start;
321 }
322 }
323 if (!AddRecs.empty()) {
324 // Add the addrecs onto the end of the list.
325 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
326 // Resort the operand list, moving any constants to the front.
327 SimplifyAddOperands(Ops, Ty, SE);
328 }
329}
330
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000331/// expandAddToGEP - Expand an addition expression with a pointer type into
332/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
333/// BasicAliasAnalysis and other passes analyze the result. See the rules
334/// for getelementptr vs. inttoptr in
335/// http://llvm.org/docs/LangRef.html#pointeraliasing
336/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000337///
Dan Gohman3abf9052010-01-19 22:26:02 +0000338/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000339/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
340/// they may introduce pointer arithmetic which may not be safely converted
341/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000342///
343/// Design note: It might seem desirable for this function to be more
344/// loop-aware. If some of the indices are loop-invariant while others
345/// aren't, it might seem desirable to emit multiple GEPs, keeping the
346/// loop-invariant portions of the overall computation outside the loop.
347/// However, there are a few reasons this is not done here. Hoisting simple
348/// arithmetic is a low-level optimization that often isn't very
349/// important until late in the optimization process. In fact, passes
350/// like InstructionCombining will combine GEPs, even if it means
351/// pushing loop-invariant computation down into loops, so even if the
352/// GEPs were split here, the work would quickly be undone. The
353/// LoopStrengthReduction pass, which is usually run quite late (and
354/// after the last InstructionCombining pass), takes care of hoisting
355/// loop-invariant portions of expressions, after considering what
356/// can be folded using target addressing modes.
357///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000358Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
359 const SCEV *const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000360 const PointerType *PTy,
361 const Type *Ty,
362 Value *V) {
363 const Type *ElTy = PTy->getElementType();
364 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000365 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000366 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000367
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000368 // Split AddRecs up into parts as either of the parts may be usable
369 // without the other.
370 SplitAddRecs(Ops, Ty, SE);
371
Bob Wilsoneb356992009-12-04 01:33:04 +0000372 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000373 // operands into GEP indices, at each level. The first index in a GEP
374 // indexes into the array implied by the pointer operand; the rest of
375 // the indices index into the element or field type selected by the
376 // preceding index.
377 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000378 // If the scale size is not 0, attempt to factor out a scale for
379 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000380 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000381 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000382 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000383 if (!ElSize->isZero()) {
384 SmallVector<const SCEV *, 8> NewOps;
385 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
386 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000387 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000388 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
389 // Op now has ElSize factored out.
390 ScaledOps.push_back(Op);
391 if (!Remainder->isZero())
392 NewOps.push_back(Remainder);
393 AnyNonZeroIndices = true;
394 } else {
395 // The operand was not divisible, so add it to the list of operands
396 // we'll scan next iteration.
397 NewOps.push_back(Ops[i]);
398 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000399 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000400 // If we made any changes, update Ops.
401 if (!ScaledOps.empty()) {
402 Ops = NewOps;
403 SimplifyAddOperands(Ops, Ty, SE);
404 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000405 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000406 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000407
408 // Record the scaled array index for this level of the type. If
409 // we didn't find any operands that could be factored, tentatively
410 // assume that element zero was selected (since the zero offset
411 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000412 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000413 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000414 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
415 GepIndices.push_back(Scaled);
416
417 // Collect struct field index operands.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000418 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
419 bool FoundFieldNo = false;
420 // An empty struct has no fields.
421 if (STy->getNumElements() == 0) break;
422 if (SE.TD) {
423 // With TargetData, field offsets are known. See if a constant offset
424 // falls within any of the struct fields.
425 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000426 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
427 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
428 const StructLayout &SL = *SE.TD->getStructLayout(STy);
429 uint64_t FullOffset = C->getValue()->getZExtValue();
430 if (FullOffset < SL.getSizeInBytes()) {
431 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000432 GepIndices.push_back(
433 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000434 ElTy = STy->getTypeAtIndex(ElIdx);
435 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000436 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000437 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000438 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000439 }
440 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000441 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000442 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000443 // appropriate struct type.
444 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000445 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000446 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000447 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000448 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000449 GepIndices.push_back(FieldNo);
450 ElTy =
451 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000452 Ops[i] = SE.getConstant(Ty, 0);
453 AnyNonZeroIndices = true;
454 FoundFieldNo = true;
455 break;
456 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000457 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000458 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000459 // If no struct field offsets were found, tentatively assume that
460 // field zero was selected (since the zero offset would obviously
461 // be folded away).
462 if (!FoundFieldNo) {
463 ElTy = STy->getTypeAtIndex(0u);
464 GepIndices.push_back(
465 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
466 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000467 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000468
469 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
470 ElTy = ATy->getElementType();
471 else
472 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000473 }
474
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000475 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000476 // the base to i8* and do an ugly getelementptr with that. It's still
477 // better than ptrtoint+arithmetic+inttoptr at least.
478 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000479 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000480 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000481 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000482
483 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000484 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000485
486 // Fold a GEP with constant operands.
487 if (Constant *CLHS = dyn_cast<Constant>(V))
488 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000489 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000490
491 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
492 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000493 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
494 // Scanning starts from the last instruction before the insertion point.
495 BasicBlock::iterator IP = Builder.GetInsertPoint();
496 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000497 --IP;
498 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000499 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
500 // generated code.
501 if (isa<DbgInfoIntrinsic>(IP))
502 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000503 if (IP->getOpcode() == Instruction::GetElementPtr &&
504 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
505 return IP;
506 if (IP == BlockBegin) break;
507 }
508 }
509
Dan Gohman087bd1e2010-03-03 05:29:13 +0000510 // Save the original insertion point so we can restore it when we're done.
511 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
512 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
513
514 // Move the insertion point out of as many loops as we can.
515 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
516 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
517 BasicBlock *Preheader = L->getLoopPreheader();
518 if (!Preheader) break;
519
520 // Ok, move up a level.
521 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
522 }
523
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000524 // Emit a GEP.
525 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000526 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000527
528 // Restore the original insert point.
529 if (SaveInsertBB)
530 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
531
Dan Gohman5be18e82009-05-19 02:15:55 +0000532 return GEP;
533 }
534
Dan Gohman087bd1e2010-03-03 05:29:13 +0000535 // Save the original insertion point so we can restore it when we're done.
536 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
537 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
538
539 // Move the insertion point out of as many loops as we can.
540 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
541 if (!L->isLoopInvariant(V)) break;
542
543 bool AnyIndexNotLoopInvariant = false;
544 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
545 E = GepIndices.end(); I != E; ++I)
546 if (!L->isLoopInvariant(*I)) {
547 AnyIndexNotLoopInvariant = true;
548 break;
549 }
550 if (AnyIndexNotLoopInvariant)
551 break;
552
553 BasicBlock *Preheader = L->getLoopPreheader();
554 if (!Preheader) break;
555
556 // Ok, move up a level.
557 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
558 }
559
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000560 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
561 // because ScalarEvolution may have changed the address arithmetic to
562 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000563 Value *Casted = V;
564 if (V->getType() != PTy)
565 Casted = InsertNoopCastOfTo(Casted, PTy);
566 Value *GEP = Builder.CreateGEP(Casted,
Dan Gohman267a3852009-06-27 21:18:18 +0000567 GepIndices.begin(),
568 GepIndices.end(),
569 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000570 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000571 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000572
573 // Restore the original insert point.
574 if (SaveInsertBB)
575 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
576
Dan Gohman5be18e82009-05-19 02:15:55 +0000577 return expand(SE.getAddExpr(Ops));
578}
579
Dan Gohmana10756e2010-01-21 02:09:26 +0000580/// isNonConstantNegative - Return true if the specified scev is negated, but
581/// not a constant.
582static bool isNonConstantNegative(const SCEV *F) {
583 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
584 if (!Mul) return false;
585
586 // If there is a constant factor, it will be first.
587 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
588 if (!SC) return false;
589
590 // Return true if the value is negative, this matches things like (-42 * V).
591 return SC->getValue()->getValue().isNegative();
592}
593
Dan Gohman087bd1e2010-03-03 05:29:13 +0000594/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
595/// SCEV expansion. If they are nested, this is the most nested. If they are
596/// neighboring, pick the later.
597static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
598 DominatorTree &DT) {
599 if (!A) return B;
600 if (!B) return A;
601 if (A->contains(B)) return B;
602 if (B->contains(A)) return A;
603 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
604 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
605 return A; // Arbitrarily break the tie.
606}
607
608/// GetRelevantLoop - Get the most relevant loop associated with the given
609/// expression, according to PickMostRelevantLoop.
610static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
611 DominatorTree &DT) {
612 if (isa<SCEVConstant>(S))
613 return 0;
614 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
615 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
616 return LI.getLoopFor(I->getParent());
617 return 0;
618 }
619 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
620 const Loop *L = 0;
621 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
622 L = AR->getLoop();
623 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
624 I != E; ++I)
625 L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
626 return L;
627 }
628 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
629 return GetRelevantLoop(C->getOperand(), LI, DT);
630 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
631 return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
632 GetRelevantLoop(D->getRHS(), LI, DT),
633 DT);
634 llvm_unreachable("Unexpected SCEV type!");
635}
636
Dan Gohmanb3579832010-04-15 17:08:50 +0000637namespace {
638
Dan Gohman087bd1e2010-03-03 05:29:13 +0000639/// LoopCompare - Compare loops by PickMostRelevantLoop.
640class LoopCompare {
641 DominatorTree &DT;
642public:
643 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
644
645 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
646 std::pair<const Loop *, const SCEV *> RHS) const {
647 // Compare loops with PickMostRelevantLoop.
648 if (LHS.first != RHS.first)
649 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
650
651 // If one operand is a non-constant negative and the other is not,
652 // put the non-constant negative on the right so that a sub can
653 // be used instead of a negate and add.
654 if (isNonConstantNegative(LHS.second)) {
655 if (!isNonConstantNegative(RHS.second))
656 return false;
657 } else if (isNonConstantNegative(RHS.second))
658 return true;
659
660 // Otherwise they are equivalent according to this comparison.
661 return false;
662 }
663};
664
Dan Gohmanb3579832010-04-15 17:08:50 +0000665}
666
Dan Gohman890f92b2009-04-18 17:56:28 +0000667Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000668 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000669
Dan Gohman087bd1e2010-03-03 05:29:13 +0000670 // Collect all the add operands in a loop, along with their associated loops.
671 // Iterate in reverse so that constants are emitted last, all else equal, and
672 // so that pointer operands are inserted first, which the code below relies on
673 // to form more involved GEPs.
674 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
675 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
676 E(S->op_begin()); I != E; ++I)
677 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
678 *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000679
Dan Gohman087bd1e2010-03-03 05:29:13 +0000680 // Sort by loop. Use a stable sort so that constants follow non-constants and
681 // pointer operands precede non-pointer operands.
682 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000683
Dan Gohman087bd1e2010-03-03 05:29:13 +0000684 // Emit instructions to add all the operands. Hoist as much as possible
685 // out of loops, and form meaningful getelementptrs where possible.
686 Value *Sum = 0;
687 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
688 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
689 const Loop *CurLoop = I->first;
690 const SCEV *Op = I->second;
691 if (!Sum) {
692 // This is the first operand. Just expand it.
693 Sum = expand(Op);
694 ++I;
695 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
696 // The running sum expression is a pointer. Try to form a getelementptr
697 // at this level with that as the base.
698 SmallVector<const SCEV *, 4> NewOps;
699 for (; I != E && I->first == CurLoop; ++I)
700 NewOps.push_back(I->second);
701 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
702 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
703 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000704 // Try to form a getelementptr. If the running sum is instructions,
705 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000706 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000707 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
708 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000709 for (++I; I != E && I->first == CurLoop; ++I)
710 NewOps.push_back(I->second);
711 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
712 } else if (isNonConstantNegative(Op)) {
713 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000714 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000715 Sum = InsertNoopCastOfTo(Sum, Ty);
716 Sum = InsertBinop(Instruction::Sub, Sum, W);
717 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000718 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000719 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000720 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000721 Sum = InsertNoopCastOfTo(Sum, Ty);
722 // Canonicalize a constant to the RHS.
723 if (isa<Constant>(Sum)) std::swap(Sum, W);
724 Sum = InsertBinop(Instruction::Add, Sum, W);
725 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000726 }
727 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000728
729 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000730}
Dan Gohman5be18e82009-05-19 02:15:55 +0000731
Dan Gohman890f92b2009-04-18 17:56:28 +0000732Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000733 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000734
Dan Gohman087bd1e2010-03-03 05:29:13 +0000735 // Collect all the mul operands in a loop, along with their associated loops.
736 // Iterate in reverse so that constants are emitted last, all else equal.
737 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
738 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
739 E(S->op_begin()); I != E; ++I)
740 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
741 *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000742
Dan Gohman087bd1e2010-03-03 05:29:13 +0000743 // Sort by loop. Use a stable sort so that constants follow non-constants.
744 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
745
746 // Emit instructions to mul all the operands. Hoist as much as possible
747 // out of loops.
748 Value *Prod = 0;
749 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
750 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
751 const SCEV *Op = I->second;
752 if (!Prod) {
753 // This is the first operand. Just expand it.
754 Prod = expand(Op);
755 ++I;
756 } else if (Op->isAllOnesValue()) {
757 // Instead of doing a multiply by negative one, just do a negate.
758 Prod = InsertNoopCastOfTo(Prod, Ty);
759 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
760 ++I;
761 } else {
762 // A simple mul.
763 Value *W = expandCodeFor(Op, Ty);
764 Prod = InsertNoopCastOfTo(Prod, Ty);
765 // Canonicalize a constant to the RHS.
766 if (isa<Constant>(Prod)) std::swap(Prod, W);
767 Prod = InsertBinop(Instruction::Mul, Prod, W);
768 ++I;
769 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000770 }
771
Dan Gohman087bd1e2010-03-03 05:29:13 +0000772 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000773}
774
Dan Gohman890f92b2009-04-18 17:56:28 +0000775Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000776 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000777
Dan Gohman92fcdca2009-06-09 17:18:38 +0000778 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000779 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000780 const APInt &RHS = SC->getValue()->getValue();
781 if (RHS.isPowerOf2())
782 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000783 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000784 }
785
Dan Gohman92fcdca2009-06-09 17:18:38 +0000786 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000787 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000788}
789
Dan Gohman453aa4f2009-05-24 18:06:31 +0000790/// Move parts of Base into Rest to leave Base with the minimal
791/// expression that provides a pointer operand suitable for a
792/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000793static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000794 ScalarEvolution &SE) {
795 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
796 Base = A->getStart();
797 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000798 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000799 A->getStepRecurrence(SE),
800 A->getLoop()));
801 }
802 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
803 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000804 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000805 NewAddOps.back() = Rest;
806 Rest = SE.getAddExpr(NewAddOps);
807 ExposePointerBase(Base, Rest, SE);
808 }
809}
810
Dan Gohmana10756e2010-01-21 02:09:26 +0000811/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
812/// the base addrec, which is the addrec without any non-loop-dominating
813/// values, and return the PHI.
814PHINode *
815SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
816 const Loop *L,
817 const Type *ExpandTy,
818 const Type *IntTy) {
819 // Reuse a previously-inserted PHI, if present.
820 for (BasicBlock::iterator I = L->getHeader()->begin();
821 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohman572645c2010-02-12 10:34:29 +0000822 if (SE.isSCEVable(PN->getType()) &&
823 (SE.getEffectiveSCEVType(PN->getType()) ==
824 SE.getEffectiveSCEVType(Normalized->getType())) &&
825 SE.getSCEV(PN) == Normalized)
826 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Dan Gohman572645c2010-02-12 10:34:29 +0000827 Instruction *IncV =
Dan Gohman22e62192010-02-16 00:20:08 +0000828 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
829
830 // Determine if this is a well-behaved chain of instructions leading
831 // back to the PHI. It probably will be, if we're scanning an inner
832 // loop already visited by LSR for example, but it wouldn't have
833 // to be.
834 do {
835 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
836 IncV = 0;
837 break;
838 }
Dan Gohman9feae9f2010-02-17 02:39:31 +0000839 // If any of the operands don't dominate the insert position, bail.
840 // Addrec operands are always loop-invariant, so this can only happen
841 // if there are instructions which haven't been hoisted.
842 for (User::op_iterator OI = IncV->op_begin()+1,
843 OE = IncV->op_end(); OI != OE; ++OI)
844 if (Instruction *OInst = dyn_cast<Instruction>(OI))
845 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
846 IncV = 0;
847 break;
848 }
849 if (!IncV)
850 break;
851 // Advance to the next instruction.
Dan Gohman22e62192010-02-16 00:20:08 +0000852 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
853 if (!IncV)
854 break;
855 if (IncV->mayHaveSideEffects()) {
856 IncV = 0;
857 break;
858 }
859 } while (IncV != PN);
860
861 if (IncV) {
862 // Ok, the add recurrence looks usable.
863 // Remember this PHI, even in post-inc mode.
864 InsertedValues.insert(PN);
865 // Remember the increment.
866 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
867 rememberInstruction(IncV);
868 if (L == IVIncInsertLoop)
869 do {
870 if (SE.DT->dominates(IncV, IVIncInsertPos))
871 break;
872 // Make sure the increment is where we want it. But don't move it
873 // down past a potential existing post-inc user.
874 IncV->moveBefore(IVIncInsertPos);
875 IVIncInsertPos = IncV;
876 IncV = cast<Instruction>(IncV->getOperand(0));
877 } while (IncV != PN);
878 return PN;
879 }
Dan Gohman572645c2010-02-12 10:34:29 +0000880 }
Dan Gohmana10756e2010-01-21 02:09:26 +0000881
882 // Save the original insertion point so we can restore it when we're done.
883 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
884 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
885
886 // Expand code for the start value.
887 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
888 L->getHeader()->begin());
889
890 // Expand code for the step value. Insert instructions right before the
891 // terminator corresponding to the back-edge. Do this before creating the PHI
892 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
893 // negative, insert a sub instead of an add for the increment (unless it's a
894 // constant, because subtracts of constants are canonicalized to adds).
895 const SCEV *Step = Normalized->getStepRecurrence(SE);
Duncan Sands1df98592010-02-16 11:11:14 +0000896 bool isPointer = ExpandTy->isPointerTy();
Dan Gohmana10756e2010-01-21 02:09:26 +0000897 bool isNegative = !isPointer && isNonConstantNegative(Step);
898 if (isNegative)
899 Step = SE.getNegativeSCEV(Step);
900 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
901
902 // Create the PHI.
903 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
904 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
905 rememberInstruction(PN);
906
907 // Create the step instructions and populate the PHI.
908 BasicBlock *Header = L->getHeader();
909 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
910 HPI != HPE; ++HPI) {
911 BasicBlock *Pred = *HPI;
912
913 // Add a start value.
914 if (!L->contains(Pred)) {
915 PN->addIncoming(StartV, Pred);
916 continue;
917 }
918
919 // Create a step value and add it to the PHI. If IVIncInsertLoop is
920 // non-null and equal to the addrec's loop, insert the instructions
921 // at IVIncInsertPos.
922 Instruction *InsertPos = L == IVIncInsertLoop ?
923 IVIncInsertPos : Pred->getTerminator();
924 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
925 Value *IncV;
926 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
927 if (isPointer) {
928 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
929 // If the step isn't constant, don't use an implicitly scaled GEP, because
930 // that would require a multiply inside the loop.
931 if (!isa<ConstantInt>(StepV))
932 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
933 GEPPtrTy->getAddressSpace());
934 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
935 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
936 if (IncV->getType() != PN->getType()) {
937 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
938 rememberInstruction(IncV);
939 }
940 } else {
941 IncV = isNegative ?
942 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
943 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
944 rememberInstruction(IncV);
945 }
946 PN->addIncoming(IncV, Pred);
947 }
948
949 // Restore the original insert point.
950 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +0000951 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +0000952
953 // Remember this PHI, even in post-inc mode.
954 InsertedValues.insert(PN);
955
956 return PN;
957}
958
959Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
960 const Type *STy = S->getType();
961 const Type *IntTy = SE.getEffectiveSCEVType(STy);
962 const Loop *L = S->getLoop();
963
964 // Determine a normalized form of this expression, which is the expression
965 // before any post-inc adjustment is made.
966 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +0000967 if (PostIncLoops.count(L)) {
968 PostIncLoopSet Loops;
969 Loops.insert(L);
970 Normalized =
971 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
972 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +0000973 }
974
975 // Strip off any non-loop-dominating component from the addrec start.
976 const SCEV *Start = Normalized->getStart();
977 const SCEV *PostLoopOffset = 0;
978 if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
979 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +0000980 Start = SE.getConstant(Normalized->getType(), 0);
Dan Gohmana10756e2010-01-21 02:09:26 +0000981 Normalized =
982 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
983 Normalized->getStepRecurrence(SE),
984 Normalized->getLoop()));
985 }
986
987 // Strip off any non-loop-dominating component from the addrec step.
988 const SCEV *Step = Normalized->getStepRecurrence(SE);
989 const SCEV *PostLoopScale = 0;
Dan Gohman948c8a32010-04-26 21:46:36 +0000990 if (!Step->dominates(L->getHeader(), SE.DT)) {
Dan Gohmana10756e2010-01-21 02:09:26 +0000991 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +0000992 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +0000993 Normalized =
994 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
995 Normalized->getLoop()));
996 }
997
998 // Expand the core addrec. If we need post-loop scaling, force it to
999 // expand to an integer type to avoid the need for additional casting.
1000 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1001 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1002
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001003 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001004 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001005 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001006 Result = PN;
1007 else {
1008 // In PostInc mode, use the post-incremented value.
1009 BasicBlock *LatchBlock = L->getLoopLatch();
1010 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1011 Result = PN->getIncomingValueForBlock(LatchBlock);
1012 }
1013
1014 // Re-apply any non-loop-dominating scale.
1015 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001016 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001017 Result = Builder.CreateMul(Result,
1018 expandCodeFor(PostLoopScale, IntTy));
1019 rememberInstruction(Result);
1020 }
1021
1022 // Re-apply any non-loop-dominating offset.
1023 if (PostLoopOffset) {
1024 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1025 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1026 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1027 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001028 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001029 Result = Builder.CreateAdd(Result,
1030 expandCodeFor(PostLoopOffset, IntTy));
1031 rememberInstruction(Result);
1032 }
1033 }
1034
1035 return Result;
1036}
1037
Dan Gohman890f92b2009-04-18 17:56:28 +00001038Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001039 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1040
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001041 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001042 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001043
Dan Gohman4d8414f2009-06-13 16:25:49 +00001044 // First check for an existing canonical IV in a suitable type.
1045 PHINode *CanonicalIV = 0;
1046 if (PHINode *PN = L->getCanonicalInductionVariable())
1047 if (SE.isSCEVable(PN->getType()) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001048 SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
Dan Gohman4d8414f2009-06-13 16:25:49 +00001049 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1050 CanonicalIV = PN;
1051
1052 // Rewrite an AddRec in terms of the canonical induction variable, if
1053 // its type is more narrow.
1054 if (CanonicalIV &&
1055 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1056 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001057 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1058 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1059 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Dan Gohmanf3f1be62009-09-28 21:01:47 +00001060 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +00001061 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1062 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001063 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001064 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Jim Grosbach08f55d02010-06-16 21:13:38 +00001065 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt))
1066 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001067 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1068 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001069 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001070 return V;
1071 }
1072
Nate Begeman36f891b2005-07-30 00:12:19 +00001073 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001074 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001075 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001076 NewOps[0] = SE.getConstant(Ty, 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001077 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001078
1079 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1080 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001081 const SCEV *Base = S->getStart();
1082 const SCEV *RestArray[1] = { Rest };
1083 // Dig into the expression to find the pointer base for a GEP.
1084 ExposePointerBase(Base, RestArray[0], SE);
1085 // If we found a pointer, expand the AddRec with a GEP.
1086 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1087 // Make sure the Base isn't something exotic, such as a multiplied
1088 // or divided pointer value. In those cases, the result type isn't
1089 // actually a pointer type.
1090 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1091 Value *StartV = expand(Base);
1092 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1093 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001094 }
1095 }
1096
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001097 // Just do a normal add. Pre-expand the operands to suppress folding.
1098 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1099 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001100 }
1101
1102 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +00001103 if (S->isAffine() &&
Dan Gohmandeff6212010-05-03 22:09:21 +00001104 S->getOperand(1) == SE.getConstant(Ty, 1)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001105 // If there's a canonical IV, just use it.
1106 if (CanonicalIV) {
1107 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1108 "IVs with types different from the canonical IV should "
1109 "already have been handled!");
1110 return CanonicalIV;
1111 }
1112
Nate Begeman36f891b2005-07-30 00:12:19 +00001113 // Create and insert the PHI node for the induction variable in the
1114 // specified loop.
1115 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +00001116 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmana10756e2010-01-21 02:09:26 +00001117 rememberInstruction(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +00001118
Owen Andersoneed707b2009-07-24 23:12:02 +00001119 Constant *One = ConstantInt::get(Ty, 1);
Dan Gohman83d57742009-09-27 17:46:40 +00001120 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
1121 HPI != HPE; ++HPI)
1122 if (L->contains(*HPI)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001123 // Insert a unit add instruction right before the terminator
1124 // corresponding to the back-edge.
Dan Gohman83d57742009-09-27 17:46:40 +00001125 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
1126 (*HPI)->getTerminator());
Dan Gohmana10756e2010-01-21 02:09:26 +00001127 rememberInstruction(Add);
Dan Gohman83d57742009-09-27 17:46:40 +00001128 PN->addIncoming(Add, *HPI);
1129 } else {
1130 PN->addIncoming(Constant::getNullValue(Ty), *HPI);
1131 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001132 }
1133
Dan Gohman4d8414f2009-06-13 16:25:49 +00001134 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001135 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +00001136 Value *I = CanonicalIV ?
1137 CanonicalIV :
1138 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +00001139
Chris Lattnerdf14a042005-10-30 06:24:33 +00001140 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001141 if (S->isAffine()) // {0,+,F} --> i*F
1142 return
1143 expand(SE.getTruncateOrNoop(
1144 SE.getMulExpr(SE.getUnknown(I),
1145 SE.getNoopOrAnyExtend(S->getOperand(1),
1146 I->getType())),
1147 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001148
1149 // If this is a chain of recurrences, turn it into a closed form, using the
1150 // folders, then expandCodeFor the closed form. This allows the folders to
1151 // simplify the expression without having to build a bunch of special code
1152 // into this folder.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001153 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001154
Dan Gohman4d8414f2009-06-13 16:25:49 +00001155 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001156 const SCEV *NewS = S;
1157 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001158 if (isa<SCEVAddRecExpr>(Ext))
1159 NewS = Ext;
1160
Dan Gohman0bba49c2009-07-07 17:06:11 +00001161 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001162 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001163
Dan Gohman4d8414f2009-06-13 16:25:49 +00001164 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001165 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001166 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001167}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001168
Dan Gohman890f92b2009-04-18 17:56:28 +00001169Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001170 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001171 Value *V = expandCodeFor(S->getOperand(),
1172 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001173 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001174 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001175 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001176}
1177
Dan Gohman890f92b2009-04-18 17:56:28 +00001178Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001179 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001180 Value *V = expandCodeFor(S->getOperand(),
1181 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001182 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001183 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001184 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001185}
1186
Dan Gohman890f92b2009-04-18 17:56:28 +00001187Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001188 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001189 Value *V = expandCodeFor(S->getOperand(),
1190 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001191 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001192 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001193 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001194}
1195
Dan Gohman890f92b2009-04-18 17:56:28 +00001196Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001197 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1198 const Type *Ty = LHS->getType();
1199 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1200 // In the case of mixed integer and pointer types, do the
1201 // rest of the comparisons as integer.
1202 if (S->getOperand(i)->getType() != Ty) {
1203 Ty = SE.getEffectiveSCEVType(Ty);
1204 LHS = InsertNoopCastOfTo(LHS, Ty);
1205 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001206 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001207 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001208 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001209 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001210 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001211 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001212 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001213 // In the case of mixed integer and pointer types, cast the
1214 // final result back to the pointer type.
1215 if (LHS->getType() != S->getType())
1216 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001217 return LHS;
1218}
1219
Dan Gohman890f92b2009-04-18 17:56:28 +00001220Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001221 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1222 const Type *Ty = LHS->getType();
1223 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1224 // In the case of mixed integer and pointer types, do the
1225 // rest of the comparisons as integer.
1226 if (S->getOperand(i)->getType() != Ty) {
1227 Ty = SE.getEffectiveSCEVType(Ty);
1228 LHS = InsertNoopCastOfTo(LHS, Ty);
1229 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001230 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001231 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001232 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001233 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001234 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001235 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001236 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001237 // In the case of mixed integer and pointer types, cast the
1238 // final result back to the pointer type.
1239 if (LHS->getType() != S->getType())
1240 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001241 return LHS;
1242}
1243
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001244Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
1245 Instruction *I) {
1246 BasicBlock::iterator IP = I;
1247 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1248 ++IP;
1249 Builder.SetInsertPoint(IP->getParent(), IP);
1250 return expandCodeFor(SH, Ty);
1251}
1252
Dan Gohman0bba49c2009-07-07 17:06:11 +00001253Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001254 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001255 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001256 if (Ty) {
1257 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1258 "non-trivial casts should be done with the SCEVs directly!");
1259 V = InsertNoopCastOfTo(V, Ty);
1260 }
1261 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001262}
1263
Dan Gohman890f92b2009-04-18 17:56:28 +00001264Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001265 // Compute an insertion point for this SCEV object. Hoist the instructions
1266 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001267 Instruction *InsertPt = Builder.GetInsertPoint();
1268 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001269 L = L->getParentLoop())
1270 if (S->isLoopInvariant(L)) {
1271 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001272 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001273 InsertPt = Preheader->getTerminator();
1274 } else {
1275 // If the SCEV is computable at this level, insert it into the header
1276 // after the PHIs (and after any other instructions that we've inserted
1277 // there) so that it is guaranteed to dominate any user inside the loop.
Dan Gohman448db1c2010-04-07 22:27:08 +00001278 if (L && S->hasComputableLoopEvolution(L) && !PostIncLoops.count(L))
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001279 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001280 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001281 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001282 break;
1283 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001284
Dan Gohman667d7872009-06-26 22:53:46 +00001285 // Check to see if we already expanded this here.
1286 std::map<std::pair<const SCEV *, Instruction *>,
1287 AssertingVH<Value> >::iterator I =
1288 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001289 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001290 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001291
1292 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1293 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1294 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001295
1296 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001297 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001298
Dan Gohman667d7872009-06-26 22:53:46 +00001299 // Remember the expanded value for this SCEV at this location.
Dan Gohman448db1c2010-04-07 22:27:08 +00001300 if (PostIncLoops.empty())
Dan Gohmana10756e2010-01-21 02:09:26 +00001301 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001302
Dan Gohman45598552010-02-15 00:21:43 +00001303 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001304 return V;
1305}
Dan Gohman1d09de32009-06-05 16:35:53 +00001306
Dan Gohman1d826a72010-02-14 03:12:47 +00001307void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001308 if (!PostIncLoops.empty())
1309 InsertedPostIncValues.insert(I);
1310 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001311 InsertedValues.insert(I);
1312
1313 // If we just claimed an existing instruction and that instruction had
1314 // been the insert point, adjust the insert point forward so that
1315 // subsequently inserted code will be dominated.
1316 if (Builder.GetInsertPoint() == I) {
1317 BasicBlock::iterator It = cast<Instruction>(I);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001318 do { ++It; } while (isInsertedInstruction(It) ||
1319 isa<DbgInfoIntrinsic>(It));
Dan Gohman1d826a72010-02-14 03:12:47 +00001320 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1321 }
1322}
1323
Dan Gohman45598552010-02-15 00:21:43 +00001324void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001325 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001326 // advance past them.
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001327 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
Dan Gohman45598552010-02-15 00:21:43 +00001328
1329 Builder.SetInsertPoint(BB, I);
1330}
1331
Dan Gohman1d09de32009-06-05 16:35:53 +00001332/// getOrInsertCanonicalInductionVariable - This method returns the
1333/// canonical induction variable of the specified type for the specified
1334/// loop (inserting one if there is none). A canonical induction variable
1335/// starts at zero and steps by one on each iteration.
1336Value *
1337SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1338 const Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001339 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohmandeff6212010-05-03 22:09:21 +00001340 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1341 SE.getConstant(Ty, 1), L);
Dan Gohman267a3852009-06-27 21:18:18 +00001342 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1343 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001344 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +00001345 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001346 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001347 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001348}