blob: 47bdda20b6dd6fa149d7392d3185558a6a4c43be [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"
Andrew Trickd152d032011-07-16 00:59:39 +000022
Nate Begeman36f891b2005-07-30 00:12:19 +000023using namespace llvm;
24
Gabor Greif19e5ada2010-07-09 16:42:04 +000025/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000026/// reusing an existing cast if a suitable one exists, moving an existing
27/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000028/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000029Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000030 Instruction::CastOps Op,
31 BasicBlock::iterator IP) {
32 // Check to see if there is already a cast!
33 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000034 UI != E; ++UI) {
35 User *U = *UI;
36 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000037 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000038 if (CI->getOpcode() == Op) {
39 // If the cast isn't where we want it, fix it.
40 if (BasicBlock::iterator(CI) != IP) {
41 // Create a new cast, and leave the old cast in place in case
42 // it is being used as an insert point. Clear its operand
43 // so that it doesn't hold anything live.
44 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
45 NewCI->takeName(CI);
46 CI->replaceAllUsesWith(NewCI);
47 CI->setOperand(0, UndefValue::get(V->getType()));
48 rememberInstruction(NewCI);
49 return NewCI;
50 }
Dan Gohman6f5fed22010-06-19 22:50:35 +000051 rememberInstruction(CI);
Dan Gohman485c43f2010-06-19 13:25:23 +000052 return CI;
53 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000054 }
Dan Gohman485c43f2010-06-19 13:25:23 +000055
56 // Create a new cast.
57 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
58 rememberInstruction(I);
59 return I;
60}
61
Dan Gohman267a3852009-06-27 21:18:18 +000062/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
63/// which must be possible with a noop cast, doing what we can to share
64/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000065Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000066 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
67 assert((Op == Instruction::BitCast ||
68 Op == Instruction::PtrToInt ||
69 Op == Instruction::IntToPtr) &&
70 "InsertNoopCastOfTo cannot perform non-noop casts!");
71 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
72 "InsertNoopCastOfTo cannot change sizes!");
73
Dan Gohman2d1be872009-04-16 03:18:22 +000074 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000075 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000076 return V;
77
Dan Gohmanf04fa482009-04-16 15:52:57 +000078 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000079 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000080 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000081 if (CastInst *CI = dyn_cast<CastInst>(V))
82 if ((CI->getOpcode() == Instruction::PtrToInt ||
83 CI->getOpcode() == Instruction::IntToPtr) &&
84 SE.getTypeSizeInBits(CI->getType()) ==
85 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
86 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000087 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
88 if ((CE->getOpcode() == Instruction::PtrToInt ||
89 CE->getOpcode() == Instruction::IntToPtr) &&
90 SE.getTypeSizeInBits(CE->getType()) ==
91 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
92 return CE->getOperand(0);
93 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000094
Dan Gohman485c43f2010-06-19 13:25:23 +000095 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000096 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000097 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000098
Dan Gohman485c43f2010-06-19 13:25:23 +000099 // Cast the argument at the beginning of the entry block, after
100 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000101 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000102 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
103 while ((isa<BitCastInst>(IP) &&
104 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
105 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000106 isa<DbgInfoIntrinsic>(IP) ||
107 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000108 ++IP;
109 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000110 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000111
Dan Gohman485c43f2010-06-19 13:25:23 +0000112 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000113 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000114 BasicBlock::iterator IP = I; ++IP;
115 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
116 IP = II->getNormalDest()->begin();
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000117 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
118 isa<LandingPadInst>(IP))
119 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000120 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000121}
122
Chris Lattner7fec90e2007-04-13 05:04:18 +0000123/// InsertBinop - Insert the specified binary operator, doing a small amount
124/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000125Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
126 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000127 // Fold a binop with constant operands.
128 if (Constant *CLHS = dyn_cast<Constant>(LHS))
129 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000130 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000131
Chris Lattner7fec90e2007-04-13 05:04:18 +0000132 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
133 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000134 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
135 // Scanning starts from the last instruction before the insertion point.
136 BasicBlock::iterator IP = Builder.GetInsertPoint();
137 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000138 --IP;
139 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000140 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
141 // generated code.
142 if (isa<DbgInfoIntrinsic>(IP))
143 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000144 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
145 IP->getOperand(1) == RHS)
146 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000147 if (IP == BlockBegin) break;
148 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000149 }
Dan Gohman267a3852009-06-27 21:18:18 +0000150
Dan Gohman087bd1e2010-03-03 05:29:13 +0000151 // Save the original insertion point so we can restore it when we're done.
152 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
153 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
154
155 // Move the insertion point out of as many loops as we can.
156 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
157 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
158 BasicBlock *Preheader = L->getLoopPreheader();
159 if (!Preheader) break;
160
161 // Ok, move up a level.
162 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
163 }
164
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000165 // If we haven't found this binop, insert it.
Devang Pateldf3ad662011-06-22 20:56:56 +0000166 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS, "tmp"));
167 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000168 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000169
170 // Restore the original insert point.
171 if (SaveInsertBB)
172 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
173
Dan Gohmancf5ab822009-05-01 17:13:31 +0000174 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000175}
176
Dan Gohman4a4f7672009-05-27 02:00:53 +0000177/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000178/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000179/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000180/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000181/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
182/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
183/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000184static bool FactorOutConstant(const SCEV *&S,
185 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000186 const SCEV *Factor,
187 ScalarEvolution &SE,
188 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000189 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000190 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000191 return true;
192
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000193 // x/x == 1.
194 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000195 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000196 return true;
197 }
198
Dan Gohman453aa4f2009-05-24 18:06:31 +0000199 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000200 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000201 // 0/x == 0.
202 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000203 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000204 // Check for divisibility.
205 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
206 ConstantInt *CI =
207 ConstantInt::get(SE.getContext(),
208 C->getValue()->getValue().sdiv(
209 FC->getValue()->getValue()));
210 // If the quotient is zero and the remainder is non-zero, reject
211 // the value at this scale. It will be considered for subsequent
212 // smaller scales.
213 if (!CI->isZero()) {
214 const SCEV *Div = SE.getConstant(CI);
215 S = Div;
216 Remainder =
217 SE.getAddExpr(Remainder,
218 SE.getConstant(C->getValue()->getValue().srem(
219 FC->getValue()->getValue())));
220 return true;
221 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000222 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000223 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000224
225 // In a Mul, check if there is a constant operand which is a multiple
226 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000227 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
228 if (TD) {
229 // With TargetData, the size is known. Check if there is a constant
230 // operand which is a multiple of the given factor. If so, we can
231 // factor it.
232 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
233 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
234 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000235 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000236 NewMulOps[0] =
237 SE.getConstant(C->getValue()->getValue().sdiv(
238 FC->getValue()->getValue()));
239 S = SE.getMulExpr(NewMulOps);
240 return true;
241 }
242 } else {
243 // Without TargetData, check if Factor can be factored out of any of the
244 // Mul's operands. If so, we can just remove it.
245 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
246 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000247 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000248 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
249 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000250 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000251 NewMulOps[i] = SOp;
252 S = SE.getMulExpr(NewMulOps);
253 return true;
254 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000255 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000256 }
257 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000258
259 // In an AddRec, check if both start and step are divisible.
260 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000261 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000262 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000263 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000264 return false;
265 if (!StepRem->isZero())
266 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000267 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000268 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000269 return false;
Andrew Trick3228cc22011-03-14 16:50:06 +0000270 // FIXME: can use A->getNoWrapFlags(FlagNW)
271 S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000272 return true;
273 }
274
275 return false;
276}
277
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000278/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
279/// is the number of SCEVAddRecExprs present, which are kept at the end of
280/// the list.
281///
282static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000283 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000284 ScalarEvolution &SE) {
285 unsigned NumAddRecs = 0;
286 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
287 ++NumAddRecs;
288 // Group Ops into non-addrecs and addrecs.
289 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
290 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
291 // Let ScalarEvolution sort and simplify the non-addrecs list.
292 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000293 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000294 SE.getAddExpr(NoAddRecs);
295 // If it returned an add, use the operands. Otherwise it simplified
296 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000297 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000298 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000299 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000300 else if (!Sum->isZero())
301 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000302 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000303 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000304}
305
306/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
307/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
308/// This helps expose more opportunities for folding parts of the expressions
309/// into GEP indices.
310///
311static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000312 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000313 ScalarEvolution &SE) {
314 // Find the addrecs.
315 SmallVector<const SCEV *, 8> AddRecs;
316 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
317 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
318 const SCEV *Start = A->getStart();
319 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000320 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000321 AddRecs.push_back(SE.getAddRecExpr(Zero,
322 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000323 A->getLoop(),
324 // FIXME: A->getNoWrapFlags(FlagNW)
325 SCEV::FlagAnyWrap));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000326 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
327 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000328 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000329 e += Add->getNumOperands();
330 } else {
331 Ops[i] = Start;
332 }
333 }
334 if (!AddRecs.empty()) {
335 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000336 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000337 // Resort the operand list, moving any constants to the front.
338 SimplifyAddOperands(Ops, Ty, SE);
339 }
340}
341
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000342/// expandAddToGEP - Expand an addition expression with a pointer type into
343/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
344/// BasicAliasAnalysis and other passes analyze the result. See the rules
345/// for getelementptr vs. inttoptr in
346/// http://llvm.org/docs/LangRef.html#pointeraliasing
347/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000348///
Dan Gohman3abf9052010-01-19 22:26:02 +0000349/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000350/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
351/// they may introduce pointer arithmetic which may not be safely converted
352/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000353///
354/// Design note: It might seem desirable for this function to be more
355/// loop-aware. If some of the indices are loop-invariant while others
356/// aren't, it might seem desirable to emit multiple GEPs, keeping the
357/// loop-invariant portions of the overall computation outside the loop.
358/// However, there are a few reasons this is not done here. Hoisting simple
359/// arithmetic is a low-level optimization that often isn't very
360/// important until late in the optimization process. In fact, passes
361/// like InstructionCombining will combine GEPs, even if it means
362/// pushing loop-invariant computation down into loops, so even if the
363/// GEPs were split here, the work would quickly be undone. The
364/// LoopStrengthReduction pass, which is usually run quite late (and
365/// after the last InstructionCombining pass), takes care of hoisting
366/// loop-invariant portions of expressions, after considering what
367/// can be folded using target addressing modes.
368///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000369Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
370 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000371 PointerType *PTy,
372 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000373 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000374 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000375 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000376 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000377 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000378
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000379 // Split AddRecs up into parts as either of the parts may be usable
380 // without the other.
381 SplitAddRecs(Ops, Ty, SE);
382
Bob Wilsoneb356992009-12-04 01:33:04 +0000383 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000384 // operands into GEP indices, at each level. The first index in a GEP
385 // indexes into the array implied by the pointer operand; the rest of
386 // the indices index into the element or field type selected by the
387 // preceding index.
388 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000389 // If the scale size is not 0, attempt to factor out a scale for
390 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000391 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000392 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000393 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000394 if (!ElSize->isZero()) {
395 SmallVector<const SCEV *, 8> NewOps;
396 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
397 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000398 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000399 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
400 // Op now has ElSize factored out.
401 ScaledOps.push_back(Op);
402 if (!Remainder->isZero())
403 NewOps.push_back(Remainder);
404 AnyNonZeroIndices = true;
405 } else {
406 // The operand was not divisible, so add it to the list of operands
407 // we'll scan next iteration.
408 NewOps.push_back(Ops[i]);
409 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000410 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000411 // If we made any changes, update Ops.
412 if (!ScaledOps.empty()) {
413 Ops = NewOps;
414 SimplifyAddOperands(Ops, Ty, SE);
415 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000416 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000417 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000418
419 // Record the scaled array index for this level of the type. If
420 // we didn't find any operands that could be factored, tentatively
421 // assume that element zero was selected (since the zero offset
422 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000423 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000424 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000425 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
426 GepIndices.push_back(Scaled);
427
428 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000429 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000430 bool FoundFieldNo = false;
431 // An empty struct has no fields.
432 if (STy->getNumElements() == 0) break;
433 if (SE.TD) {
434 // With TargetData, field offsets are known. See if a constant offset
435 // falls within any of the struct fields.
436 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000437 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
438 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
439 const StructLayout &SL = *SE.TD->getStructLayout(STy);
440 uint64_t FullOffset = C->getValue()->getZExtValue();
441 if (FullOffset < SL.getSizeInBytes()) {
442 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000443 GepIndices.push_back(
444 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000445 ElTy = STy->getTypeAtIndex(ElIdx);
446 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000447 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000448 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000449 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000450 }
451 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000452 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000453 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000454 // appropriate struct type.
455 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000456 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000457 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000458 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000459 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000460 GepIndices.push_back(FieldNo);
461 ElTy =
462 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000463 Ops[i] = SE.getConstant(Ty, 0);
464 AnyNonZeroIndices = true;
465 FoundFieldNo = true;
466 break;
467 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000468 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000469 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000470 // If no struct field offsets were found, tentatively assume that
471 // field zero was selected (since the zero offset would obviously
472 // be folded away).
473 if (!FoundFieldNo) {
474 ElTy = STy->getTypeAtIndex(0u);
475 GepIndices.push_back(
476 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
477 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000478 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000479
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000480 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000481 ElTy = ATy->getElementType();
482 else
483 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000484 }
485
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000486 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000487 // the base to i8* and do an ugly getelementptr with that. It's still
488 // better than ptrtoint+arithmetic+inttoptr at least.
489 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000490 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000491 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000492 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000493
494 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000495 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000496
497 // Fold a GEP with constant operands.
498 if (Constant *CLHS = dyn_cast<Constant>(V))
499 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000500 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000501
502 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
503 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000504 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
505 // Scanning starts from the last instruction before the insertion point.
506 BasicBlock::iterator IP = Builder.GetInsertPoint();
507 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000508 --IP;
509 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000510 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
511 // generated code.
512 if (isa<DbgInfoIntrinsic>(IP))
513 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000514 if (IP->getOpcode() == Instruction::GetElementPtr &&
515 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
516 return IP;
517 if (IP == BlockBegin) break;
518 }
519 }
520
Dan Gohman087bd1e2010-03-03 05:29:13 +0000521 // Save the original insertion point so we can restore it when we're done.
522 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
523 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
524
525 // Move the insertion point out of as many loops as we can.
526 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
527 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
528 BasicBlock *Preheader = L->getLoopPreheader();
529 if (!Preheader) break;
530
531 // Ok, move up a level.
532 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
533 }
534
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000535 // Emit a GEP.
536 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000537 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000538
539 // Restore the original insert point.
540 if (SaveInsertBB)
541 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
542
Dan Gohman5be18e82009-05-19 02:15:55 +0000543 return GEP;
544 }
545
Dan Gohman087bd1e2010-03-03 05:29:13 +0000546 // Save the original insertion point so we can restore it when we're done.
547 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
548 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
549
550 // Move the insertion point out of as many loops as we can.
551 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
552 if (!L->isLoopInvariant(V)) break;
553
554 bool AnyIndexNotLoopInvariant = false;
555 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
556 E = GepIndices.end(); I != E; ++I)
557 if (!L->isLoopInvariant(*I)) {
558 AnyIndexNotLoopInvariant = true;
559 break;
560 }
561 if (AnyIndexNotLoopInvariant)
562 break;
563
564 BasicBlock *Preheader = L->getLoopPreheader();
565 if (!Preheader) break;
566
567 // Ok, move up a level.
568 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
569 }
570
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000571 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
572 // because ScalarEvolution may have changed the address arithmetic to
573 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000574 Value *Casted = V;
575 if (V->getType() != PTy)
576 Casted = InsertNoopCastOfTo(Casted, PTy);
577 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000578 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000579 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000580 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000581 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000582
583 // Restore the original insert point.
584 if (SaveInsertBB)
585 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
586
Dan Gohman5be18e82009-05-19 02:15:55 +0000587 return expand(SE.getAddExpr(Ops));
588}
589
Dan Gohmana10756e2010-01-21 02:09:26 +0000590/// isNonConstantNegative - Return true if the specified scev is negated, but
591/// not a constant.
592static bool isNonConstantNegative(const SCEV *F) {
593 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
594 if (!Mul) return false;
595
596 // If there is a constant factor, it will be first.
597 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
598 if (!SC) return false;
599
600 // Return true if the value is negative, this matches things like (-42 * V).
601 return SC->getValue()->getValue().isNegative();
602}
603
Dan Gohman087bd1e2010-03-03 05:29:13 +0000604/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
605/// SCEV expansion. If they are nested, this is the most nested. If they are
606/// neighboring, pick the later.
607static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
608 DominatorTree &DT) {
609 if (!A) return B;
610 if (!B) return A;
611 if (A->contains(B)) return B;
612 if (B->contains(A)) return A;
613 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
614 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
615 return A; // Arbitrarily break the tie.
616}
617
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000618/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000619/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000620const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
621 // Test whether we've already computed the most relevant loop for this SCEV.
622 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
623 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
624 if (!Pair.second)
625 return Pair.first->second;
626
Dan Gohman087bd1e2010-03-03 05:29:13 +0000627 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000628 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000629 return 0;
630 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
631 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000632 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
633 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000634 return 0;
635 }
636 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
637 const Loop *L = 0;
638 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
639 L = AR->getLoop();
640 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
641 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000642 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
643 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000644 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000645 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
646 const Loop *Result = getRelevantLoop(C->getOperand());
647 return RelevantLoops[C] = Result;
648 }
649 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
650 const Loop *Result =
651 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
652 getRelevantLoop(D->getRHS()),
653 *SE.DT);
654 return RelevantLoops[D] = Result;
655 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000656 llvm_unreachable("Unexpected SCEV type!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000657 return 0;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000658}
659
Dan Gohmanb3579832010-04-15 17:08:50 +0000660namespace {
661
Dan Gohman087bd1e2010-03-03 05:29:13 +0000662/// LoopCompare - Compare loops by PickMostRelevantLoop.
663class LoopCompare {
664 DominatorTree &DT;
665public:
666 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
667
668 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
669 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000670 // Keep pointer operands sorted at the end.
671 if (LHS.second->getType()->isPointerTy() !=
672 RHS.second->getType()->isPointerTy())
673 return LHS.second->getType()->isPointerTy();
674
Dan Gohman087bd1e2010-03-03 05:29:13 +0000675 // Compare loops with PickMostRelevantLoop.
676 if (LHS.first != RHS.first)
677 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
678
679 // If one operand is a non-constant negative and the other is not,
680 // put the non-constant negative on the right so that a sub can
681 // be used instead of a negate and add.
682 if (isNonConstantNegative(LHS.second)) {
683 if (!isNonConstantNegative(RHS.second))
684 return false;
685 } else if (isNonConstantNegative(RHS.second))
686 return true;
687
688 // Otherwise they are equivalent according to this comparison.
689 return false;
690 }
691};
692
Dan Gohmanb3579832010-04-15 17:08:50 +0000693}
694
Dan Gohman890f92b2009-04-18 17:56:28 +0000695Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000696 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000697
Dan Gohman087bd1e2010-03-03 05:29:13 +0000698 // Collect all the add operands in a loop, along with their associated loops.
699 // Iterate in reverse so that constants are emitted last, all else equal, and
700 // so that pointer operands are inserted first, which the code below relies on
701 // to form more involved GEPs.
702 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
703 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
704 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000705 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000706
Dan Gohman087bd1e2010-03-03 05:29:13 +0000707 // Sort by loop. Use a stable sort so that constants follow non-constants and
708 // pointer operands precede non-pointer operands.
709 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000710
Dan Gohman087bd1e2010-03-03 05:29:13 +0000711 // Emit instructions to add all the operands. Hoist as much as possible
712 // out of loops, and form meaningful getelementptrs where possible.
713 Value *Sum = 0;
714 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
715 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
716 const Loop *CurLoop = I->first;
717 const SCEV *Op = I->second;
718 if (!Sum) {
719 // This is the first operand. Just expand it.
720 Sum = expand(Op);
721 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000722 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000723 // The running sum expression is a pointer. Try to form a getelementptr
724 // at this level with that as the base.
725 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000726 for (; I != E && I->first == CurLoop; ++I) {
727 // If the operand is SCEVUnknown and not instructions, peek through
728 // it, to enable more of it to be folded into the GEP.
729 const SCEV *X = I->second;
730 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
731 if (!isa<Instruction>(U->getValue()))
732 X = SE.getSCEV(U->getValue());
733 NewOps.push_back(X);
734 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000735 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000736 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000737 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000738 // Try to form a getelementptr. If the running sum is instructions,
739 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000740 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000741 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
742 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000743 for (++I; I != E && I->first == CurLoop; ++I)
744 NewOps.push_back(I->second);
745 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
746 } else if (isNonConstantNegative(Op)) {
747 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000748 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000749 Sum = InsertNoopCastOfTo(Sum, Ty);
750 Sum = InsertBinop(Instruction::Sub, Sum, W);
751 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000752 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000753 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000754 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000755 Sum = InsertNoopCastOfTo(Sum, Ty);
756 // Canonicalize a constant to the RHS.
757 if (isa<Constant>(Sum)) std::swap(Sum, W);
758 Sum = InsertBinop(Instruction::Add, Sum, W);
759 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000760 }
761 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000762
763 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000764}
Dan Gohman5be18e82009-05-19 02:15:55 +0000765
Dan Gohman890f92b2009-04-18 17:56:28 +0000766Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000767 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000768
Dan Gohman087bd1e2010-03-03 05:29:13 +0000769 // Collect all the mul operands in a loop, along with their associated loops.
770 // Iterate in reverse so that constants are emitted last, all else equal.
771 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
772 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
773 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000774 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000775
Dan Gohman087bd1e2010-03-03 05:29:13 +0000776 // Sort by loop. Use a stable sort so that constants follow non-constants.
777 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
778
779 // Emit instructions to mul all the operands. Hoist as much as possible
780 // out of loops.
781 Value *Prod = 0;
782 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
783 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
784 const SCEV *Op = I->second;
785 if (!Prod) {
786 // This is the first operand. Just expand it.
787 Prod = expand(Op);
788 ++I;
789 } else if (Op->isAllOnesValue()) {
790 // Instead of doing a multiply by negative one, just do a negate.
791 Prod = InsertNoopCastOfTo(Prod, Ty);
792 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
793 ++I;
794 } else {
795 // A simple mul.
796 Value *W = expandCodeFor(Op, Ty);
797 Prod = InsertNoopCastOfTo(Prod, Ty);
798 // Canonicalize a constant to the RHS.
799 if (isa<Constant>(Prod)) std::swap(Prod, W);
800 Prod = InsertBinop(Instruction::Mul, Prod, W);
801 ++I;
802 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000803 }
804
Dan Gohman087bd1e2010-03-03 05:29:13 +0000805 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000806}
807
Dan Gohman890f92b2009-04-18 17:56:28 +0000808Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000809 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000810
Dan Gohman92fcdca2009-06-09 17:18:38 +0000811 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000812 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000813 const APInt &RHS = SC->getValue()->getValue();
814 if (RHS.isPowerOf2())
815 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000816 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000817 }
818
Dan Gohman92fcdca2009-06-09 17:18:38 +0000819 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000820 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000821}
822
Dan Gohman453aa4f2009-05-24 18:06:31 +0000823/// Move parts of Base into Rest to leave Base with the minimal
824/// expression that provides a pointer operand suitable for a
825/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000826static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000827 ScalarEvolution &SE) {
828 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
829 Base = A->getStart();
830 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000831 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000832 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000833 A->getLoop(),
834 // FIXME: A->getNoWrapFlags(FlagNW)
835 SCEV::FlagAnyWrap));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000836 }
837 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
838 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000839 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000840 NewAddOps.back() = Rest;
841 Rest = SE.getAddExpr(NewAddOps);
842 ExposePointerBase(Base, Rest, SE);
843 }
844}
845
Dan Gohmana10756e2010-01-21 02:09:26 +0000846/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
847/// the base addrec, which is the addrec without any non-loop-dominating
848/// values, and return the PHI.
849PHINode *
850SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
851 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000852 Type *ExpandTy,
853 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +0000854 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +0000855
Dan Gohmana10756e2010-01-21 02:09:26 +0000856 // Reuse a previously-inserted PHI, if present.
857 for (BasicBlock::iterator I = L->getHeader()->begin();
858 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohman572645c2010-02-12 10:34:29 +0000859 if (SE.isSCEVable(PN->getType()) &&
860 (SE.getEffectiveSCEVType(PN->getType()) ==
861 SE.getEffectiveSCEVType(Normalized->getType())) &&
862 SE.getSCEV(PN) == Normalized)
863 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Dan Gohman572645c2010-02-12 10:34:29 +0000864 Instruction *IncV =
Dan Gohman22e62192010-02-16 00:20:08 +0000865 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
866
867 // Determine if this is a well-behaved chain of instructions leading
868 // back to the PHI. It probably will be, if we're scanning an inner
869 // loop already visited by LSR for example, but it wouldn't have
870 // to be.
871 do {
Dan Gohman0cbe91b2011-03-02 01:34:10 +0000872 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
Dan Gohmana7a841a2011-03-04 20:46:46 +0000873 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV))) {
Dan Gohman22e62192010-02-16 00:20:08 +0000874 IncV = 0;
875 break;
876 }
Dan Gohman9feae9f2010-02-17 02:39:31 +0000877 // If any of the operands don't dominate the insert position, bail.
878 // Addrec operands are always loop-invariant, so this can only happen
879 // if there are instructions which haven't been hoisted.
Andrew Trickd152d032011-07-16 00:59:39 +0000880 if (L == IVIncInsertLoop) {
881 for (User::op_iterator OI = IncV->op_begin()+1,
882 OE = IncV->op_end(); OI != OE; ++OI)
883 if (Instruction *OInst = dyn_cast<Instruction>(OI))
884 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
885 IncV = 0;
886 break;
887 }
888 }
Dan Gohman9feae9f2010-02-17 02:39:31 +0000889 if (!IncV)
890 break;
891 // Advance to the next instruction.
Dan Gohman22e62192010-02-16 00:20:08 +0000892 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
893 if (!IncV)
894 break;
895 if (IncV->mayHaveSideEffects()) {
896 IncV = 0;
897 break;
898 }
899 } while (IncV != PN);
900
901 if (IncV) {
902 // Ok, the add recurrence looks usable.
903 // Remember this PHI, even in post-inc mode.
904 InsertedValues.insert(PN);
905 // Remember the increment.
906 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
907 rememberInstruction(IncV);
908 if (L == IVIncInsertLoop)
909 do {
910 if (SE.DT->dominates(IncV, IVIncInsertPos))
911 break;
912 // Make sure the increment is where we want it. But don't move it
913 // down past a potential existing post-inc user.
914 IncV->moveBefore(IVIncInsertPos);
915 IVIncInsertPos = IncV;
916 IncV = cast<Instruction>(IncV->getOperand(0));
917 } while (IncV != PN);
918 return PN;
919 }
Dan Gohman572645c2010-02-12 10:34:29 +0000920 }
Dan Gohmana10756e2010-01-21 02:09:26 +0000921
922 // Save the original insertion point so we can restore it when we're done.
923 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
924 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
925
926 // Expand code for the start value.
927 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
928 L->getHeader()->begin());
929
Andrew Trickd152d032011-07-16 00:59:39 +0000930 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +0000931 assert(!isa<Instruction>(StartV) ||
932 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
933 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +0000934
Dan Gohmana10756e2010-01-21 02:09:26 +0000935 // Expand code for the step value. Insert instructions right before the
936 // terminator corresponding to the back-edge. Do this before creating the PHI
937 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
938 // negative, insert a sub instead of an add for the increment (unless it's a
939 // constant, because subtracts of constants are canonicalized to adds).
940 const SCEV *Step = Normalized->getStepRecurrence(SE);
Duncan Sands1df98592010-02-16 11:11:14 +0000941 bool isPointer = ExpandTy->isPointerTy();
Dan Gohmana10756e2010-01-21 02:09:26 +0000942 bool isNegative = !isPointer && isNonConstantNegative(Step);
943 if (isNegative)
944 Step = SE.getNegativeSCEV(Step);
945 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
946
947 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +0000948 BasicBlock *Header = L->getHeader();
949 Builder.SetInsertPoint(Header, Header->begin());
950 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +0000951 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +0000952 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +0000953 rememberInstruction(PN);
954
955 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +0000956 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +0000957 BasicBlock *Pred = *HPI;
958
959 // Add a start value.
960 if (!L->contains(Pred)) {
961 PN->addIncoming(StartV, Pred);
962 continue;
963 }
964
965 // Create a step value and add it to the PHI. If IVIncInsertLoop is
966 // non-null and equal to the addrec's loop, insert the instructions
967 // at IVIncInsertPos.
968 Instruction *InsertPos = L == IVIncInsertLoop ?
969 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +0000970 Builder.SetInsertPoint(InsertPos);
Dan Gohmana10756e2010-01-21 02:09:26 +0000971 Value *IncV;
972 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
973 if (isPointer) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000974 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
Dan Gohmana10756e2010-01-21 02:09:26 +0000975 // If the step isn't constant, don't use an implicitly scaled GEP, because
976 // that would require a multiply inside the loop.
977 if (!isa<ConstantInt>(StepV))
978 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
979 GEPPtrTy->getAddressSpace());
980 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
981 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
982 if (IncV->getType() != PN->getType()) {
983 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
984 rememberInstruction(IncV);
985 }
986 } else {
987 IncV = isNegative ?
Andrew Trickdc8e5462011-06-28 05:41:52 +0000988 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
989 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
Dan Gohmana10756e2010-01-21 02:09:26 +0000990 rememberInstruction(IncV);
991 }
992 PN->addIncoming(IncV, Pred);
993 }
994
995 // Restore the original insert point.
996 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +0000997 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +0000998
999 // Remember this PHI, even in post-inc mode.
1000 InsertedValues.insert(PN);
1001
1002 return PN;
1003}
1004
1005Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001006 Type *STy = S->getType();
1007 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001008 const Loop *L = S->getLoop();
1009
1010 // Determine a normalized form of this expression, which is the expression
1011 // before any post-inc adjustment is made.
1012 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001013 if (PostIncLoops.count(L)) {
1014 PostIncLoopSet Loops;
1015 Loops.insert(L);
1016 Normalized =
1017 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1018 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001019 }
1020
1021 // Strip off any non-loop-dominating component from the addrec start.
1022 const SCEV *Start = Normalized->getStart();
1023 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001024 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001025 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001026 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001027 Normalized = cast<SCEVAddRecExpr>(
1028 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1029 Normalized->getLoop(),
1030 // FIXME: Normalized->getNoWrapFlags(FlagNW)
1031 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001032 }
1033
1034 // Strip off any non-loop-dominating component from the addrec step.
1035 const SCEV *Step = Normalized->getStepRecurrence(SE);
1036 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001037 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001038 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001039 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001040 Normalized =
1041 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
Andrew Trick3228cc22011-03-14 16:50:06 +00001042 Normalized->getLoop(),
1043 // FIXME: Normalized
1044 // ->getNoWrapFlags(FlagNW)
1045 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001046 }
1047
1048 // Expand the core addrec. If we need post-loop scaling, force it to
1049 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001050 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001051 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1052
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001053 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001054 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001055 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001056 Result = PN;
1057 else {
1058 // In PostInc mode, use the post-incremented value.
1059 BasicBlock *LatchBlock = L->getLoopLatch();
1060 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1061 Result = PN->getIncomingValueForBlock(LatchBlock);
1062 }
1063
1064 // Re-apply any non-loop-dominating scale.
1065 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001066 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001067 Result = Builder.CreateMul(Result,
1068 expandCodeFor(PostLoopScale, IntTy));
1069 rememberInstruction(Result);
1070 }
1071
1072 // Re-apply any non-loop-dominating offset.
1073 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001074 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001075 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1076 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1077 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001078 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001079 Result = Builder.CreateAdd(Result,
1080 expandCodeFor(PostLoopOffset, IntTy));
1081 rememberInstruction(Result);
1082 }
1083 }
1084
1085 return Result;
1086}
1087
Dan Gohman890f92b2009-04-18 17:56:28 +00001088Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001089 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1090
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001091 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001092 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001093
Dan Gohman4d8414f2009-06-13 16:25:49 +00001094 // First check for an existing canonical IV in a suitable type.
1095 PHINode *CanonicalIV = 0;
1096 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001097 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001098 CanonicalIV = PN;
1099
1100 // Rewrite an AddRec in terms of the canonical induction variable, if
1101 // its type is more narrow.
1102 if (CanonicalIV &&
1103 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1104 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001105 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1106 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1107 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001108 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1109 // FIXME: S->getNoWrapFlags(FlagNW)
1110 SCEV::FlagAnyWrap));
Dan Gohman267a3852009-06-27 21:18:18 +00001111 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1112 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001113 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001114 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001115 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1116 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001117 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001118 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1119 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001120 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001121 return V;
1122 }
1123
Nate Begeman36f891b2005-07-30 00:12:19 +00001124 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001125 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001126 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001127 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001128 // FIXME: can use S->getNoWrapFlags()
1129 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001130
1131 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1132 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001133 const SCEV *Base = S->getStart();
1134 const SCEV *RestArray[1] = { Rest };
1135 // Dig into the expression to find the pointer base for a GEP.
1136 ExposePointerBase(Base, RestArray[0], SE);
1137 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001138 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001139 // Make sure the Base isn't something exotic, such as a multiplied
1140 // or divided pointer value. In those cases, the result type isn't
1141 // actually a pointer type.
1142 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1143 Value *StartV = expand(Base);
1144 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1145 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001146 }
1147 }
1148
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001149 // Just do a normal add. Pre-expand the operands to suppress folding.
1150 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1151 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001152 }
1153
Dan Gohman6ebfd722010-07-26 18:28:14 +00001154 // If we don't yet have a canonical IV, create one.
1155 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001156 // Create and insert the PHI node for the induction variable in the
1157 // specified loop.
1158 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001159 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001160 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1161 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001162 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001163
Owen Andersoneed707b2009-07-24 23:12:02 +00001164 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001165 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001166 BasicBlock *HP = *HPI;
1167 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001168 // Insert a unit add instruction right before the terminator
1169 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001170 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1171 "indvar.next",
1172 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001173 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001174 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001175 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001176 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001177 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001178 }
Gabor Greif76560182010-07-09 15:40:10 +00001179 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001180 }
1181
Dan Gohman6ebfd722010-07-26 18:28:14 +00001182 // {0,+,1} --> Insert a canonical induction variable into the loop!
1183 if (S->isAffine() && S->getOperand(1)->isOne()) {
1184 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1185 "IVs with types different from the canonical IV should "
1186 "already have been handled!");
1187 return CanonicalIV;
1188 }
1189
Dan Gohman4d8414f2009-06-13 16:25:49 +00001190 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001191
Chris Lattnerdf14a042005-10-30 06:24:33 +00001192 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001193 if (S->isAffine()) // {0,+,F} --> i*F
1194 return
1195 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001196 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001197 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001198 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001199 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001200
1201 // If this is a chain of recurrences, turn it into a closed form, using the
1202 // folders, then expandCodeFor the closed form. This allows the folders to
1203 // simplify the expression without having to build a bunch of special code
1204 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001205 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001206
Dan Gohman4d8414f2009-06-13 16:25:49 +00001207 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001208 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001209 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001210 if (isa<SCEVAddRecExpr>(Ext))
1211 NewS = Ext;
1212
Dan Gohman0bba49c2009-07-07 17:06:11 +00001213 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001214 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001215
Dan Gohman4d8414f2009-06-13 16:25:49 +00001216 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001217 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001218 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001219}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001220
Dan Gohman890f92b2009-04-18 17:56:28 +00001221Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001222 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001223 Value *V = expandCodeFor(S->getOperand(),
1224 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001225 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001226 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001227 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001228}
1229
Dan Gohman890f92b2009-04-18 17:56:28 +00001230Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001231 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001232 Value *V = expandCodeFor(S->getOperand(),
1233 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001234 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001235 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001236 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001237}
1238
Dan Gohman890f92b2009-04-18 17:56:28 +00001239Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001240 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001241 Value *V = expandCodeFor(S->getOperand(),
1242 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001243 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001244 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001245 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001246}
1247
Dan Gohman890f92b2009-04-18 17:56:28 +00001248Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001249 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001250 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001251 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1252 // In the case of mixed integer and pointer types, do the
1253 // rest of the comparisons as integer.
1254 if (S->getOperand(i)->getType() != Ty) {
1255 Ty = SE.getEffectiveSCEVType(Ty);
1256 LHS = InsertNoopCastOfTo(LHS, Ty);
1257 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001258 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001259 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001260 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001261 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001262 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001263 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001264 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001265 // In the case of mixed integer and pointer types, cast the
1266 // final result back to the pointer type.
1267 if (LHS->getType() != S->getType())
1268 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001269 return LHS;
1270}
1271
Dan Gohman890f92b2009-04-18 17:56:28 +00001272Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001273 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001274 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001275 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1276 // In the case of mixed integer and pointer types, do the
1277 // rest of the comparisons as integer.
1278 if (S->getOperand(i)->getType() != Ty) {
1279 Ty = SE.getEffectiveSCEVType(Ty);
1280 LHS = InsertNoopCastOfTo(LHS, Ty);
1281 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001282 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001283 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001284 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001285 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001286 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001287 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001288 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001289 // In the case of mixed integer and pointer types, cast the
1290 // final result back to the pointer type.
1291 if (LHS->getType() != S->getType())
1292 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001293 return LHS;
1294}
1295
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001296Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001297 Instruction *I) {
1298 BasicBlock::iterator IP = I;
1299 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1300 ++IP;
1301 Builder.SetInsertPoint(IP->getParent(), IP);
1302 return expandCodeFor(SH, Ty);
1303}
1304
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001305Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001306 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001307 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001308 if (Ty) {
1309 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1310 "non-trivial casts should be done with the SCEVs directly!");
1311 V = InsertNoopCastOfTo(V, Ty);
1312 }
1313 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001314}
1315
Dan Gohman890f92b2009-04-18 17:56:28 +00001316Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001317 // Compute an insertion point for this SCEV object. Hoist the instructions
1318 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001319 Instruction *InsertPt = Builder.GetInsertPoint();
1320 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001321 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001322 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001323 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001324 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001325 InsertPt = Preheader->getTerminator();
1326 } else {
1327 // If the SCEV is computable at this level, insert it into the header
1328 // after the PHIs (and after any other instructions that we've inserted
1329 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001330 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1331 InsertPt = L->getHeader()->getFirstInsertionPt();
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001332 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001333 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001334 break;
1335 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001336
Dan Gohman667d7872009-06-26 22:53:46 +00001337 // Check to see if we already expanded this here.
1338 std::map<std::pair<const SCEV *, Instruction *>,
1339 AssertingVH<Value> >::iterator I =
1340 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001341 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001342 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001343
1344 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1345 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1346 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001347
1348 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001349 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001350
Dan Gohman667d7872009-06-26 22:53:46 +00001351 // Remember the expanded value for this SCEV at this location.
Dan Gohman448db1c2010-04-07 22:27:08 +00001352 if (PostIncLoops.empty())
Dan Gohmana10756e2010-01-21 02:09:26 +00001353 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001354
Dan Gohman45598552010-02-15 00:21:43 +00001355 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001356 return V;
1357}
Dan Gohman1d09de32009-06-05 16:35:53 +00001358
Dan Gohman1d826a72010-02-14 03:12:47 +00001359void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001360 if (!PostIncLoops.empty())
1361 InsertedPostIncValues.insert(I);
1362 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001363 InsertedValues.insert(I);
1364
1365 // If we just claimed an existing instruction and that instruction had
Andrew Trick3228cc22011-03-14 16:50:06 +00001366 // been the insert point, adjust the insert point forward so that
Dan Gohman1d826a72010-02-14 03:12:47 +00001367 // subsequently inserted code will be dominated.
1368 if (Builder.GetInsertPoint() == I) {
1369 BasicBlock::iterator It = cast<Instruction>(I);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001370 do { ++It; } while (isInsertedInstruction(It) ||
1371 isa<DbgInfoIntrinsic>(It));
Dan Gohman1d826a72010-02-14 03:12:47 +00001372 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1373 }
1374}
1375
Dan Gohman45598552010-02-15 00:21:43 +00001376void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001377 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001378 // advance past them.
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001379 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
Dan Gohman45598552010-02-15 00:21:43 +00001380
1381 Builder.SetInsertPoint(BB, I);
1382}
1383
Dan Gohman1d09de32009-06-05 16:35:53 +00001384/// getOrInsertCanonicalInductionVariable - This method returns the
1385/// canonical induction variable of the specified type for the specified
1386/// loop (inserting one if there is none). A canonical induction variable
1387/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001388PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001389SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001390 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001391 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001392
1393 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001394 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001395 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001396 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001397
1398 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001399 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1400 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001401 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001402 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001403 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001404
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001405 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001406}