blob: 59901aaa8390f2a9719b3b0b0d4560f3dd0db6e9 [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"
Andrew Trickc5701912011-10-07 23:46:21 +000020#include "llvm/Support/Debug.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000021#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000022#include "llvm/ADT/STLExtras.h"
Andrew Trickd152d032011-07-16 00:59:39 +000023
Nate Begeman36f891b2005-07-30 00:12:19 +000024using namespace llvm;
25
Gabor Greif19e5ada2010-07-09 16:42:04 +000026/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000027/// reusing an existing cast if a suitable one exists, moving an existing
28/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000029/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000030Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000031 Instruction::CastOps Op,
32 BasicBlock::iterator IP) {
33 // Check to see if there is already a cast!
34 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000035 UI != E; ++UI) {
36 User *U = *UI;
37 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000038 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000039 if (CI->getOpcode() == Op) {
40 // If the cast isn't where we want it, fix it.
41 if (BasicBlock::iterator(CI) != IP) {
42 // Create a new cast, and leave the old cast in place in case
43 // it is being used as an insert point. Clear its operand
44 // so that it doesn't hold anything live.
45 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
46 NewCI->takeName(CI);
47 CI->replaceAllUsesWith(NewCI);
48 CI->setOperand(0, UndefValue::get(V->getType()));
49 rememberInstruction(NewCI);
50 return NewCI;
51 }
Dan Gohman6f5fed22010-06-19 22:50:35 +000052 rememberInstruction(CI);
Dan Gohman485c43f2010-06-19 13:25:23 +000053 return CI;
54 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000055 }
Dan Gohman485c43f2010-06-19 13:25:23 +000056
57 // Create a new cast.
58 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
59 rememberInstruction(I);
60 return I;
61}
62
Dan Gohman267a3852009-06-27 21:18:18 +000063/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
64/// which must be possible with a noop cast, doing what we can to share
65/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000066Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000067 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
68 assert((Op == Instruction::BitCast ||
69 Op == Instruction::PtrToInt ||
70 Op == Instruction::IntToPtr) &&
71 "InsertNoopCastOfTo cannot perform non-noop casts!");
72 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
73 "InsertNoopCastOfTo cannot change sizes!");
74
Dan Gohman2d1be872009-04-16 03:18:22 +000075 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000076 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000077 return V;
78
Dan Gohmanf04fa482009-04-16 15:52:57 +000079 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000080 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000081 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000082 if (CastInst *CI = dyn_cast<CastInst>(V))
83 if ((CI->getOpcode() == Instruction::PtrToInt ||
84 CI->getOpcode() == Instruction::IntToPtr) &&
85 SE.getTypeSizeInBits(CI->getType()) ==
86 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
87 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000088 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
89 if ((CE->getOpcode() == Instruction::PtrToInt ||
90 CE->getOpcode() == Instruction::IntToPtr) &&
91 SE.getTypeSizeInBits(CE->getType()) ==
92 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
93 return CE->getOperand(0);
94 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000095
Dan Gohman485c43f2010-06-19 13:25:23 +000096 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000097 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000098 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000099
Dan Gohman485c43f2010-06-19 13:25:23 +0000100 // Cast the argument at the beginning of the entry block, after
101 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000102 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000103 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
104 while ((isa<BitCastInst>(IP) &&
105 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
106 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000107 isa<DbgInfoIntrinsic>(IP) ||
108 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000109 ++IP;
110 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000111 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000112
Dan Gohman485c43f2010-06-19 13:25:23 +0000113 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000114 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000115 BasicBlock::iterator IP = I; ++IP;
116 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
117 IP = II->getNormalDest()->begin();
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000118 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
119 isa<LandingPadInst>(IP))
120 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000121 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000122}
123
Chris Lattner7fec90e2007-04-13 05:04:18 +0000124/// InsertBinop - Insert the specified binary operator, doing a small amount
125/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000126Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
127 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000128 // Fold a binop with constant operands.
129 if (Constant *CLHS = dyn_cast<Constant>(LHS))
130 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000131 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000132
Chris Lattner7fec90e2007-04-13 05:04:18 +0000133 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
134 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000135 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
136 // Scanning starts from the last instruction before the insertion point.
137 BasicBlock::iterator IP = Builder.GetInsertPoint();
138 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000139 --IP;
140 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000141 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
142 // generated code.
143 if (isa<DbgInfoIntrinsic>(IP))
144 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000145 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
146 IP->getOperand(1) == RHS)
147 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000148 if (IP == BlockBegin) break;
149 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000150 }
Dan Gohman267a3852009-06-27 21:18:18 +0000151
Dan Gohman087bd1e2010-03-03 05:29:13 +0000152 // Save the original insertion point so we can restore it when we're done.
153 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
154 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
155
156 // Move the insertion point out of as many loops as we can.
157 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
158 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
159 BasicBlock *Preheader = L->getLoopPreheader();
160 if (!Preheader) break;
161
162 // Ok, move up a level.
163 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
164 }
165
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000166 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000167 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Devang Pateldf3ad662011-06-22 20:56:56 +0000168 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000169 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000170
171 // Restore the original insert point.
172 if (SaveInsertBB)
173 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
174
Dan Gohmancf5ab822009-05-01 17:13:31 +0000175 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000176}
177
Dan Gohman4a4f7672009-05-27 02:00:53 +0000178/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000179/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000180/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000181/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000182/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
183/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
184/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185static bool FactorOutConstant(const SCEV *&S,
186 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000187 const SCEV *Factor,
188 ScalarEvolution &SE,
189 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000190 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000191 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000192 return true;
193
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000194 // x/x == 1.
195 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000196 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000197 return true;
198 }
199
Dan Gohman453aa4f2009-05-24 18:06:31 +0000200 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000201 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000202 // 0/x == 0.
203 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000204 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000205 // Check for divisibility.
206 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
207 ConstantInt *CI =
208 ConstantInt::get(SE.getContext(),
209 C->getValue()->getValue().sdiv(
210 FC->getValue()->getValue()));
211 // If the quotient is zero and the remainder is non-zero, reject
212 // the value at this scale. It will be considered for subsequent
213 // smaller scales.
214 if (!CI->isZero()) {
215 const SCEV *Div = SE.getConstant(CI);
216 S = Div;
217 Remainder =
218 SE.getAddExpr(Remainder,
219 SE.getConstant(C->getValue()->getValue().srem(
220 FC->getValue()->getValue())));
221 return true;
222 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000223 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000224 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000225
226 // In a Mul, check if there is a constant operand which is a multiple
227 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000228 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
229 if (TD) {
230 // With TargetData, the size is known. Check if there is a constant
231 // operand which is a multiple of the given factor. If so, we can
232 // factor it.
233 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
234 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
235 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000236 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000237 NewMulOps[0] =
238 SE.getConstant(C->getValue()->getValue().sdiv(
239 FC->getValue()->getValue()));
240 S = SE.getMulExpr(NewMulOps);
241 return true;
242 }
243 } else {
244 // Without TargetData, check if Factor can be factored out of any of the
245 // Mul's operands. If so, we can just remove it.
246 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
247 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000248 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000249 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
250 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000251 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000252 NewMulOps[i] = SOp;
253 S = SE.getMulExpr(NewMulOps);
254 return true;
255 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000256 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000257 }
258 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000259
260 // In an AddRec, check if both start and step are divisible.
261 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000262 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000263 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000264 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000265 return false;
266 if (!StepRem->isZero())
267 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000268 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000269 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000270 return false;
Andrew Trick3228cc22011-03-14 16:50:06 +0000271 // FIXME: can use A->getNoWrapFlags(FlagNW)
272 S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000273 return true;
274 }
275
276 return false;
277}
278
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000279/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
280/// is the number of SCEVAddRecExprs present, which are kept at the end of
281/// the list.
282///
283static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000284 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000285 ScalarEvolution &SE) {
286 unsigned NumAddRecs = 0;
287 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
288 ++NumAddRecs;
289 // Group Ops into non-addrecs and addrecs.
290 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
291 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
292 // Let ScalarEvolution sort and simplify the non-addrecs list.
293 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000294 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000295 SE.getAddExpr(NoAddRecs);
296 // If it returned an add, use the operands. Otherwise it simplified
297 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000298 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000299 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000300 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000301 else if (!Sum->isZero())
302 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000303 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000304 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000305}
306
307/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
308/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
309/// This helps expose more opportunities for folding parts of the expressions
310/// into GEP indices.
311///
312static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000313 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000314 ScalarEvolution &SE) {
315 // Find the addrecs.
316 SmallVector<const SCEV *, 8> AddRecs;
317 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
318 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
319 const SCEV *Start = A->getStart();
320 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000321 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000322 AddRecs.push_back(SE.getAddRecExpr(Zero,
323 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000324 A->getLoop(),
325 // FIXME: A->getNoWrapFlags(FlagNW)
326 SCEV::FlagAnyWrap));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000327 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
328 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000329 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000330 e += Add->getNumOperands();
331 } else {
332 Ops[i] = Start;
333 }
334 }
335 if (!AddRecs.empty()) {
336 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000337 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000338 // Resort the operand list, moving any constants to the front.
339 SimplifyAddOperands(Ops, Ty, SE);
340 }
341}
342
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000343/// expandAddToGEP - Expand an addition expression with a pointer type into
344/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
345/// BasicAliasAnalysis and other passes analyze the result. See the rules
346/// for getelementptr vs. inttoptr in
347/// http://llvm.org/docs/LangRef.html#pointeraliasing
348/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000349///
Dan Gohman3abf9052010-01-19 22:26:02 +0000350/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000351/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
352/// they may introduce pointer arithmetic which may not be safely converted
353/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000354///
355/// Design note: It might seem desirable for this function to be more
356/// loop-aware. If some of the indices are loop-invariant while others
357/// aren't, it might seem desirable to emit multiple GEPs, keeping the
358/// loop-invariant portions of the overall computation outside the loop.
359/// However, there are a few reasons this is not done here. Hoisting simple
360/// arithmetic is a low-level optimization that often isn't very
361/// important until late in the optimization process. In fact, passes
362/// like InstructionCombining will combine GEPs, even if it means
363/// pushing loop-invariant computation down into loops, so even if the
364/// GEPs were split here, the work would quickly be undone. The
365/// LoopStrengthReduction pass, which is usually run quite late (and
366/// after the last InstructionCombining pass), takes care of hoisting
367/// loop-invariant portions of expressions, after considering what
368/// can be folded using target addressing modes.
369///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000370Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
371 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000372 PointerType *PTy,
373 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000374 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000375 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000376 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000377 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000378 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000379
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000380 // Split AddRecs up into parts as either of the parts may be usable
381 // without the other.
382 SplitAddRecs(Ops, Ty, SE);
383
Bob Wilsoneb356992009-12-04 01:33:04 +0000384 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000385 // operands into GEP indices, at each level. The first index in a GEP
386 // indexes into the array implied by the pointer operand; the rest of
387 // the indices index into the element or field type selected by the
388 // preceding index.
389 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000390 // If the scale size is not 0, attempt to factor out a scale for
391 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000392 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000393 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000394 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000395 if (!ElSize->isZero()) {
396 SmallVector<const SCEV *, 8> NewOps;
397 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
398 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000399 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000400 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
401 // Op now has ElSize factored out.
402 ScaledOps.push_back(Op);
403 if (!Remainder->isZero())
404 NewOps.push_back(Remainder);
405 AnyNonZeroIndices = true;
406 } else {
407 // The operand was not divisible, so add it to the list of operands
408 // we'll scan next iteration.
409 NewOps.push_back(Ops[i]);
410 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000411 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000412 // If we made any changes, update Ops.
413 if (!ScaledOps.empty()) {
414 Ops = NewOps;
415 SimplifyAddOperands(Ops, Ty, SE);
416 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000417 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000418 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000419
420 // Record the scaled array index for this level of the type. If
421 // we didn't find any operands that could be factored, tentatively
422 // assume that element zero was selected (since the zero offset
423 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000424 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000425 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000426 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
427 GepIndices.push_back(Scaled);
428
429 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000430 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000431 bool FoundFieldNo = false;
432 // An empty struct has no fields.
433 if (STy->getNumElements() == 0) break;
434 if (SE.TD) {
435 // With TargetData, field offsets are known. See if a constant offset
436 // falls within any of the struct fields.
437 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000438 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
439 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
440 const StructLayout &SL = *SE.TD->getStructLayout(STy);
441 uint64_t FullOffset = C->getValue()->getZExtValue();
442 if (FullOffset < SL.getSizeInBytes()) {
443 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000444 GepIndices.push_back(
445 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000446 ElTy = STy->getTypeAtIndex(ElIdx);
447 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000448 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000449 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000450 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000451 }
452 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000453 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000454 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000455 // appropriate struct type.
456 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000457 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000458 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000459 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000460 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000461 GepIndices.push_back(FieldNo);
462 ElTy =
463 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000464 Ops[i] = SE.getConstant(Ty, 0);
465 AnyNonZeroIndices = true;
466 FoundFieldNo = true;
467 break;
468 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000469 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000470 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000471 // If no struct field offsets were found, tentatively assume that
472 // field zero was selected (since the zero offset would obviously
473 // be folded away).
474 if (!FoundFieldNo) {
475 ElTy = STy->getTypeAtIndex(0u);
476 GepIndices.push_back(
477 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
478 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000479 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000480
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000481 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000482 ElTy = ATy->getElementType();
483 else
484 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000485 }
486
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000487 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000488 // the base to i8* and do an ugly getelementptr with that. It's still
489 // better than ptrtoint+arithmetic+inttoptr at least.
490 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000491 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000492 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000493 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000494
495 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000496 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000497
498 // Fold a GEP with constant operands.
499 if (Constant *CLHS = dyn_cast<Constant>(V))
500 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000501 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000502
503 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
504 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000505 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
506 // Scanning starts from the last instruction before the insertion point.
507 BasicBlock::iterator IP = Builder.GetInsertPoint();
508 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000509 --IP;
510 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000511 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
512 // generated code.
513 if (isa<DbgInfoIntrinsic>(IP))
514 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000515 if (IP->getOpcode() == Instruction::GetElementPtr &&
516 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
517 return IP;
518 if (IP == BlockBegin) break;
519 }
520 }
521
Dan Gohman087bd1e2010-03-03 05:29:13 +0000522 // Save the original insertion point so we can restore it when we're done.
523 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
524 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
525
526 // Move the insertion point out of as many loops as we can.
527 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
528 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
529 BasicBlock *Preheader = L->getLoopPreheader();
530 if (!Preheader) break;
531
532 // Ok, move up a level.
533 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
534 }
535
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000536 // Emit a GEP.
537 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000538 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000539
540 // Restore the original insert point.
541 if (SaveInsertBB)
542 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
543
Dan Gohman5be18e82009-05-19 02:15:55 +0000544 return GEP;
545 }
546
Dan Gohman087bd1e2010-03-03 05:29:13 +0000547 // Save the original insertion point so we can restore it when we're done.
548 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
549 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
550
551 // Move the insertion point out of as many loops as we can.
552 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
553 if (!L->isLoopInvariant(V)) break;
554
555 bool AnyIndexNotLoopInvariant = false;
556 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
557 E = GepIndices.end(); I != E; ++I)
558 if (!L->isLoopInvariant(*I)) {
559 AnyIndexNotLoopInvariant = true;
560 break;
561 }
562 if (AnyIndexNotLoopInvariant)
563 break;
564
565 BasicBlock *Preheader = L->getLoopPreheader();
566 if (!Preheader) break;
567
568 // Ok, move up a level.
569 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
570 }
571
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000572 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
573 // because ScalarEvolution may have changed the address arithmetic to
574 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000575 Value *Casted = V;
576 if (V->getType() != PTy)
577 Casted = InsertNoopCastOfTo(Casted, PTy);
578 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000579 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000580 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000581 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000582 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000583
584 // Restore the original insert point.
585 if (SaveInsertBB)
586 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
587
Dan Gohman5be18e82009-05-19 02:15:55 +0000588 return expand(SE.getAddExpr(Ops));
589}
590
Dan Gohmana10756e2010-01-21 02:09:26 +0000591/// isNonConstantNegative - Return true if the specified scev is negated, but
592/// not a constant.
593static bool isNonConstantNegative(const SCEV *F) {
594 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
595 if (!Mul) return false;
596
597 // If there is a constant factor, it will be first.
598 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
599 if (!SC) return false;
600
601 // Return true if the value is negative, this matches things like (-42 * V).
602 return SC->getValue()->getValue().isNegative();
603}
604
Dan Gohman087bd1e2010-03-03 05:29:13 +0000605/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
606/// SCEV expansion. If they are nested, this is the most nested. If they are
607/// neighboring, pick the later.
608static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
609 DominatorTree &DT) {
610 if (!A) return B;
611 if (!B) return A;
612 if (A->contains(B)) return B;
613 if (B->contains(A)) return A;
614 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
615 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
616 return A; // Arbitrarily break the tie.
617}
618
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000619/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000620/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000621const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
622 // Test whether we've already computed the most relevant loop for this SCEV.
623 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
624 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
625 if (!Pair.second)
626 return Pair.first->second;
627
Dan Gohman087bd1e2010-03-03 05:29:13 +0000628 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000629 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000630 return 0;
631 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
632 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000633 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
634 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000635 return 0;
636 }
637 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
638 const Loop *L = 0;
639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
640 L = AR->getLoop();
641 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
642 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000643 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
644 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000645 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000646 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
647 const Loop *Result = getRelevantLoop(C->getOperand());
648 return RelevantLoops[C] = Result;
649 }
650 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
651 const Loop *Result =
652 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
653 getRelevantLoop(D->getRHS()),
654 *SE.DT);
655 return RelevantLoops[D] = Result;
656 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000657 llvm_unreachable("Unexpected SCEV type!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000658 return 0;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000659}
660
Dan Gohmanb3579832010-04-15 17:08:50 +0000661namespace {
662
Dan Gohman087bd1e2010-03-03 05:29:13 +0000663/// LoopCompare - Compare loops by PickMostRelevantLoop.
664class LoopCompare {
665 DominatorTree &DT;
666public:
667 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
668
669 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
670 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000671 // Keep pointer operands sorted at the end.
672 if (LHS.second->getType()->isPointerTy() !=
673 RHS.second->getType()->isPointerTy())
674 return LHS.second->getType()->isPointerTy();
675
Dan Gohman087bd1e2010-03-03 05:29:13 +0000676 // Compare loops with PickMostRelevantLoop.
677 if (LHS.first != RHS.first)
678 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
679
680 // If one operand is a non-constant negative and the other is not,
681 // put the non-constant negative on the right so that a sub can
682 // be used instead of a negate and add.
683 if (isNonConstantNegative(LHS.second)) {
684 if (!isNonConstantNegative(RHS.second))
685 return false;
686 } else if (isNonConstantNegative(RHS.second))
687 return true;
688
689 // Otherwise they are equivalent according to this comparison.
690 return false;
691 }
692};
693
Dan Gohmanb3579832010-04-15 17:08:50 +0000694}
695
Dan Gohman890f92b2009-04-18 17:56:28 +0000696Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000697 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000698
Dan Gohman087bd1e2010-03-03 05:29:13 +0000699 // Collect all the add operands in a loop, along with their associated loops.
700 // Iterate in reverse so that constants are emitted last, all else equal, and
701 // so that pointer operands are inserted first, which the code below relies on
702 // to form more involved GEPs.
703 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
704 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
705 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000706 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000707
Dan Gohman087bd1e2010-03-03 05:29:13 +0000708 // Sort by loop. Use a stable sort so that constants follow non-constants and
709 // pointer operands precede non-pointer operands.
710 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000711
Dan Gohman087bd1e2010-03-03 05:29:13 +0000712 // Emit instructions to add all the operands. Hoist as much as possible
713 // out of loops, and form meaningful getelementptrs where possible.
714 Value *Sum = 0;
715 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
716 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
717 const Loop *CurLoop = I->first;
718 const SCEV *Op = I->second;
719 if (!Sum) {
720 // This is the first operand. Just expand it.
721 Sum = expand(Op);
722 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000723 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000724 // The running sum expression is a pointer. Try to form a getelementptr
725 // at this level with that as the base.
726 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000727 for (; I != E && I->first == CurLoop; ++I) {
728 // If the operand is SCEVUnknown and not instructions, peek through
729 // it, to enable more of it to be folded into the GEP.
730 const SCEV *X = I->second;
731 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
732 if (!isa<Instruction>(U->getValue()))
733 X = SE.getSCEV(U->getValue());
734 NewOps.push_back(X);
735 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000736 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000737 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000738 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000739 // Try to form a getelementptr. If the running sum is instructions,
740 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000741 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000742 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
743 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000744 for (++I; I != E && I->first == CurLoop; ++I)
745 NewOps.push_back(I->second);
746 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
747 } else if (isNonConstantNegative(Op)) {
748 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000749 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000750 Sum = InsertNoopCastOfTo(Sum, Ty);
751 Sum = InsertBinop(Instruction::Sub, Sum, W);
752 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000753 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000754 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000755 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000756 Sum = InsertNoopCastOfTo(Sum, Ty);
757 // Canonicalize a constant to the RHS.
758 if (isa<Constant>(Sum)) std::swap(Sum, W);
759 Sum = InsertBinop(Instruction::Add, Sum, W);
760 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000761 }
762 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000763
764 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000765}
Dan Gohman5be18e82009-05-19 02:15:55 +0000766
Dan Gohman890f92b2009-04-18 17:56:28 +0000767Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000768 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000769
Dan Gohman087bd1e2010-03-03 05:29:13 +0000770 // Collect all the mul operands in a loop, along with their associated loops.
771 // Iterate in reverse so that constants are emitted last, all else equal.
772 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
773 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
774 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000775 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000776
Dan Gohman087bd1e2010-03-03 05:29:13 +0000777 // Sort by loop. Use a stable sort so that constants follow non-constants.
778 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
779
780 // Emit instructions to mul all the operands. Hoist as much as possible
781 // out of loops.
782 Value *Prod = 0;
783 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
784 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
785 const SCEV *Op = I->second;
786 if (!Prod) {
787 // This is the first operand. Just expand it.
788 Prod = expand(Op);
789 ++I;
790 } else if (Op->isAllOnesValue()) {
791 // Instead of doing a multiply by negative one, just do a negate.
792 Prod = InsertNoopCastOfTo(Prod, Ty);
793 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
794 ++I;
795 } else {
796 // A simple mul.
797 Value *W = expandCodeFor(Op, Ty);
798 Prod = InsertNoopCastOfTo(Prod, Ty);
799 // Canonicalize a constant to the RHS.
800 if (isa<Constant>(Prod)) std::swap(Prod, W);
801 Prod = InsertBinop(Instruction::Mul, Prod, W);
802 ++I;
803 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000804 }
805
Dan Gohman087bd1e2010-03-03 05:29:13 +0000806 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000807}
808
Dan Gohman890f92b2009-04-18 17:56:28 +0000809Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000810 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000811
Dan Gohman92fcdca2009-06-09 17:18:38 +0000812 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000813 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000814 const APInt &RHS = SC->getValue()->getValue();
815 if (RHS.isPowerOf2())
816 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000817 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000818 }
819
Dan Gohman92fcdca2009-06-09 17:18:38 +0000820 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000821 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000822}
823
Dan Gohman453aa4f2009-05-24 18:06:31 +0000824/// Move parts of Base into Rest to leave Base with the minimal
825/// expression that provides a pointer operand suitable for a
826/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000827static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000828 ScalarEvolution &SE) {
829 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
830 Base = A->getStart();
831 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000832 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000833 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000834 A->getLoop(),
835 // FIXME: A->getNoWrapFlags(FlagNW)
836 SCEV::FlagAnyWrap));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000837 }
838 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
839 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000840 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000841 NewAddOps.back() = Rest;
842 Rest = SE.getAddExpr(NewAddOps);
843 ExposePointerBase(Base, Rest, SE);
844 }
845}
846
Andrew Trickc5701912011-10-07 23:46:21 +0000847/// Determine if this is a well-behaved chain of instructions leading back to
848/// the PHI. If so, it may be reused by expanded expressions.
849bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
850 const Loop *L) {
851 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
852 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
853 return false;
854 // If any of the operands don't dominate the insert position, bail.
855 // Addrec operands are always loop-invariant, so this can only happen
856 // if there are instructions which haven't been hoisted.
857 if (L == IVIncInsertLoop) {
858 for (User::op_iterator OI = IncV->op_begin()+1,
859 OE = IncV->op_end(); OI != OE; ++OI)
860 if (Instruction *OInst = dyn_cast<Instruction>(OI))
861 if (!SE.DT->dominates(OInst, IVIncInsertPos))
862 return false;
863 }
864 // Advance to the next instruction.
865 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
866 if (!IncV)
867 return false;
868
869 if (IncV->mayHaveSideEffects())
870 return false;
871
872 if (IncV != PN)
873 return true;
874
875 return isNormalAddRecExprPHI(PN, IncV, L);
876}
877
878/// Determine if this cyclic phi is in a form that would have been generated by
879/// LSR. We don't care if the phi was actually expanded in this pass, as long
880/// as it is in a low-cost form, for example, no implied multiplication. This
881/// should match any patterns generated by getAddRecExprPHILiterally and
882/// expandAddtoGEP.
883bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +0000884 const Loop *L) {
Andrew Trickc5701912011-10-07 23:46:21 +0000885 switch (IncV->getOpcode()) {
886 // Check for a simple Add/Sub or GEP of a loop invariant step.
887 case Instruction::Add:
888 case Instruction::Sub:
889 return IncV->getOperand(0) == PN
890 && L->isLoopInvariant(IncV->getOperand(1));
891 case Instruction::BitCast:
892 IncV = dyn_cast<GetElementPtrInst>(IncV->getOperand(0));
893 if (!IncV)
894 return false;
895 // fall-thru to GEP handling
896 case Instruction::GetElementPtr: {
897 // This must be a pointer addition of constants (pretty) or some number of
898 // address-size elements (ugly).
899 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
900 I != E; ++I) {
901 if (isa<Constant>(*I))
902 continue;
903 // ugly geps have 2 operands.
904 // i1* is used by the expander to represent an address-size element.
905 if (IncV->getNumOperands() != 2)
906 return false;
Andrew Trick365c9f12011-10-15 06:19:55 +0000907 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
Andrew Trickc5701912011-10-07 23:46:21 +0000908 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
909 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
910 return false;
Andrew Trick94794dd2011-10-08 02:16:39 +0000911 // Ensure the operands dominate the insertion point. I don't know of a
912 // case when this would not be true, so this is somewhat untested.
913 if (L == IVIncInsertLoop) {
914 for (User::op_iterator OI = IncV->op_begin()+1,
915 OE = IncV->op_end(); OI != OE; ++OI)
916 if (Instruction *OInst = dyn_cast<Instruction>(OI))
917 if (!SE.DT->dominates(OInst, IVIncInsertPos))
918 return false;
919 }
Andrew Trickc5701912011-10-07 23:46:21 +0000920 break;
921 }
922 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
923 if (IncV && IncV->getOpcode() == Instruction::BitCast)
924 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
925 return IncV == PN;
926 }
927 default:
928 return false;
929 }
930}
931
Andrew Trick553fe052011-11-30 06:07:54 +0000932/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
933/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
934/// need to materialize IV increments elsewhere to handle difficult situations.
935Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
936 Type *ExpandTy, Type *IntTy,
937 bool useSubtract) {
938 Value *IncV;
939 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
940 if (ExpandTy->isPointerTy()) {
941 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
942 // If the step isn't constant, don't use an implicitly scaled GEP, because
943 // that would require a multiply inside the loop.
944 if (!isa<ConstantInt>(StepV))
945 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
946 GEPPtrTy->getAddressSpace());
947 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
948 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
949 if (IncV->getType() != PN->getType()) {
950 IncV = Builder.CreateBitCast(IncV, PN->getType());
951 rememberInstruction(IncV);
952 }
953 } else {
954 IncV = useSubtract ?
955 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
956 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
957 rememberInstruction(IncV);
958 }
959 return IncV;
960}
961
Dan Gohmana10756e2010-01-21 02:09:26 +0000962/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
963/// the base addrec, which is the addrec without any non-loop-dominating
964/// values, and return the PHI.
965PHINode *
966SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
967 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000968 Type *ExpandTy,
969 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +0000970 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +0000971
Dan Gohmana10756e2010-01-21 02:09:26 +0000972 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +0000973 BasicBlock *LatchBlock = L->getLoopLatch();
974 if (LatchBlock) {
975 for (BasicBlock::iterator I = L->getHeader()->begin();
976 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
977 if (!SE.isSCEVable(PN->getType()) ||
978 (SE.getEffectiveSCEVType(PN->getType()) !=
979 SE.getEffectiveSCEVType(Normalized->getType())) ||
980 SE.getSCEV(PN) != Normalized)
981 continue;
Dan Gohman22e62192010-02-16 00:20:08 +0000982
Andrew Trickc5701912011-10-07 23:46:21 +0000983 Instruction *IncV =
984 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman22e62192010-02-16 00:20:08 +0000985
Andrew Trickc5701912011-10-07 23:46:21 +0000986 if (LSRMode) {
Andrew Trick365c9f12011-10-15 06:19:55 +0000987 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +0000988 continue;
Dan Gohman572645c2010-02-12 10:34:29 +0000989 }
Andrew Trickc5701912011-10-07 23:46:21 +0000990 else {
991 if (!isNormalAddRecExprPHI(PN, IncV, L))
992 continue;
993 }
994 // Ok, the add recurrence looks usable.
995 // Remember this PHI, even in post-inc mode.
996 InsertedValues.insert(PN);
997 // Remember the increment.
998 rememberInstruction(IncV);
999 if (L == IVIncInsertLoop)
1000 do {
1001 if (SE.DT->dominates(IncV, IVIncInsertPos))
1002 break;
1003 // Make sure the increment is where we want it. But don't move it
1004 // down past a potential existing post-inc user.
1005 IncV->moveBefore(IVIncInsertPos);
1006 IVIncInsertPos = IncV;
1007 IncV = cast<Instruction>(IncV->getOperand(0));
1008 } while (IncV != PN);
1009 return PN;
1010 }
1011 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001012
1013 // Save the original insertion point so we can restore it when we're done.
1014 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1015 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1016
1017 // Expand code for the start value.
1018 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1019 L->getHeader()->begin());
1020
Andrew Trickd152d032011-07-16 00:59:39 +00001021 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001022 assert(!isa<Instruction>(StartV) ||
1023 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1024 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001025
Andrew Trick553fe052011-11-30 06:07:54 +00001026 // Expand code for the step value. Do this before creating the PHI so that PHI
1027 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001028 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001029 // If the stride is negative, insert a sub instead of an add for the increment
1030 // (unless it's a constant, because subtracts of constants are canonicalized
1031 // to adds).
1032 bool useSubtract = !ExpandTy->isPointerTy() && isNonConstantNegative(Step);
1033 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001034 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001035 // Expand the step somewhere that dominates the loop header.
Dan Gohmana10756e2010-01-21 02:09:26 +00001036 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1037
1038 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001039 BasicBlock *Header = L->getHeader();
1040 Builder.SetInsertPoint(Header, Header->begin());
1041 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001042 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001043 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001044 rememberInstruction(PN);
1045
1046 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001047 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001048 BasicBlock *Pred = *HPI;
1049
1050 // Add a start value.
1051 if (!L->contains(Pred)) {
1052 PN->addIncoming(StartV, Pred);
1053 continue;
1054 }
1055
Andrew Trick553fe052011-11-30 06:07:54 +00001056 // Create a step value and add it to the PHI.
1057 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1058 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001059 Instruction *InsertPos = L == IVIncInsertLoop ?
1060 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001061 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001062 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1063
Dan Gohmana10756e2010-01-21 02:09:26 +00001064 PN->addIncoming(IncV, Pred);
1065 }
1066
1067 // Restore the original insert point.
1068 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001069 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +00001070
1071 // Remember this PHI, even in post-inc mode.
1072 InsertedValues.insert(PN);
1073
1074 return PN;
1075}
1076
1077Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001078 Type *STy = S->getType();
1079 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001080 const Loop *L = S->getLoop();
1081
1082 // Determine a normalized form of this expression, which is the expression
1083 // before any post-inc adjustment is made.
1084 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001085 if (PostIncLoops.count(L)) {
1086 PostIncLoopSet Loops;
1087 Loops.insert(L);
1088 Normalized =
1089 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1090 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001091 }
1092
1093 // Strip off any non-loop-dominating component from the addrec start.
1094 const SCEV *Start = Normalized->getStart();
1095 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001096 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001097 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001098 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001099 Normalized = cast<SCEVAddRecExpr>(
1100 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1101 Normalized->getLoop(),
1102 // FIXME: Normalized->getNoWrapFlags(FlagNW)
1103 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001104 }
1105
1106 // Strip off any non-loop-dominating component from the addrec step.
1107 const SCEV *Step = Normalized->getStepRecurrence(SE);
1108 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001109 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001110 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001111 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001112 Normalized =
1113 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
Andrew Trick3228cc22011-03-14 16:50:06 +00001114 Normalized->getLoop(),
1115 // FIXME: Normalized
1116 // ->getNoWrapFlags(FlagNW)
1117 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001118 }
1119
1120 // Expand the core addrec. If we need post-loop scaling, force it to
1121 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001122 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001123 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1124
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001125 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001126 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001127 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001128 Result = PN;
1129 else {
1130 // In PostInc mode, use the post-incremented value.
1131 BasicBlock *LatchBlock = L->getLoopLatch();
1132 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1133 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001134
1135 // For an expansion to use the postinc form, the client must call
1136 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1137 // or dominated by IVIncInsertPos.
Andrew Trick553fe052011-11-30 06:07:54 +00001138 if (isa<Instruction>(Result)
1139 && !SE.DT->dominates(cast<Instruction>(Result),
1140 Builder.GetInsertPoint())) {
1141 // The induction variable's postinc expansion does not dominate this use.
1142 // IVUsers tries to prevent this case, so it is rare. However, it can
1143 // happen when an IVUser outside the loop is not dominated by the latch
1144 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1145 // all cases. Consider a phi outide whose operand is replaced during
1146 // expansion with the value of the postinc user. Without fundamentally
1147 // changing the way postinc users are tracked, the only remedy is
1148 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1149 // but hopefully expandCodeFor handles that.
1150 bool useSubtract =
1151 !ExpandTy->isPointerTy() && isNonConstantNegative(Step);
1152 if (useSubtract)
1153 Step = SE.getNegativeSCEV(Step);
1154 // Expand the step somewhere that dominates the loop header.
1155 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1156 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1157 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1158 // Restore the insertion point to the place where the caller has
1159 // determined dominates all uses.
1160 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1161 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1162 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001163 }
1164
1165 // Re-apply any non-loop-dominating scale.
1166 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001167 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001168 Result = Builder.CreateMul(Result,
1169 expandCodeFor(PostLoopScale, IntTy));
1170 rememberInstruction(Result);
1171 }
1172
1173 // Re-apply any non-loop-dominating offset.
1174 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001175 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001176 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1177 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1178 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001179 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001180 Result = Builder.CreateAdd(Result,
1181 expandCodeFor(PostLoopOffset, IntTy));
1182 rememberInstruction(Result);
1183 }
1184 }
1185
1186 return Result;
1187}
1188
Dan Gohman890f92b2009-04-18 17:56:28 +00001189Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001190 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1191
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001192 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001193 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001194
Dan Gohman4d8414f2009-06-13 16:25:49 +00001195 // First check for an existing canonical IV in a suitable type.
1196 PHINode *CanonicalIV = 0;
1197 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001198 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001199 CanonicalIV = PN;
1200
1201 // Rewrite an AddRec in terms of the canonical induction variable, if
1202 // its type is more narrow.
1203 if (CanonicalIV &&
1204 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1205 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001206 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1207 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1208 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001209 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1210 // FIXME: S->getNoWrapFlags(FlagNW)
1211 SCEV::FlagAnyWrap));
Dan Gohman267a3852009-06-27 21:18:18 +00001212 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1213 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001214 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001215 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001216 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1217 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001218 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001219 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1220 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001221 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001222 return V;
1223 }
1224
Nate Begeman36f891b2005-07-30 00:12:19 +00001225 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001226 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001227 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001228 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001229 // FIXME: can use S->getNoWrapFlags()
1230 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001231
1232 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1233 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001234 const SCEV *Base = S->getStart();
1235 const SCEV *RestArray[1] = { Rest };
1236 // Dig into the expression to find the pointer base for a GEP.
1237 ExposePointerBase(Base, RestArray[0], SE);
1238 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001239 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001240 // Make sure the Base isn't something exotic, such as a multiplied
1241 // or divided pointer value. In those cases, the result type isn't
1242 // actually a pointer type.
1243 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1244 Value *StartV = expand(Base);
1245 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1246 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001247 }
1248 }
1249
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001250 // Just do a normal add. Pre-expand the operands to suppress folding.
1251 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1252 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001253 }
1254
Dan Gohman6ebfd722010-07-26 18:28:14 +00001255 // If we don't yet have a canonical IV, create one.
1256 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001257 // Create and insert the PHI node for the induction variable in the
1258 // specified loop.
1259 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001260 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001261 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1262 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001263 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001264
Owen Andersoneed707b2009-07-24 23:12:02 +00001265 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001266 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001267 BasicBlock *HP = *HPI;
1268 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001269 // Insert a unit add instruction right before the terminator
1270 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001271 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1272 "indvar.next",
1273 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001274 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001275 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001276 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001277 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001278 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001279 }
Gabor Greif76560182010-07-09 15:40:10 +00001280 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001281 }
1282
Dan Gohman6ebfd722010-07-26 18:28:14 +00001283 // {0,+,1} --> Insert a canonical induction variable into the loop!
1284 if (S->isAffine() && S->getOperand(1)->isOne()) {
1285 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1286 "IVs with types different from the canonical IV should "
1287 "already have been handled!");
1288 return CanonicalIV;
1289 }
1290
Dan Gohman4d8414f2009-06-13 16:25:49 +00001291 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001292
Chris Lattnerdf14a042005-10-30 06:24:33 +00001293 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001294 if (S->isAffine()) // {0,+,F} --> i*F
1295 return
1296 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001297 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001298 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001299 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001300 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001301
1302 // If this is a chain of recurrences, turn it into a closed form, using the
1303 // folders, then expandCodeFor the closed form. This allows the folders to
1304 // simplify the expression without having to build a bunch of special code
1305 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001306 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001307
Dan Gohman4d8414f2009-06-13 16:25:49 +00001308 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001309 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001310 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001311 if (isa<SCEVAddRecExpr>(Ext))
1312 NewS = Ext;
1313
Dan Gohman0bba49c2009-07-07 17:06:11 +00001314 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001315 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001316
Dan Gohman4d8414f2009-06-13 16:25:49 +00001317 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001318 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001319 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001320}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001321
Dan Gohman890f92b2009-04-18 17:56:28 +00001322Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001323 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001324 Value *V = expandCodeFor(S->getOperand(),
1325 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001326 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001327 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001328 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001329}
1330
Dan Gohman890f92b2009-04-18 17:56:28 +00001331Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001332 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001333 Value *V = expandCodeFor(S->getOperand(),
1334 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001335 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001336 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001337 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001338}
1339
Dan Gohman890f92b2009-04-18 17:56:28 +00001340Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001341 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001342 Value *V = expandCodeFor(S->getOperand(),
1343 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001344 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001345 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001346 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001347}
1348
Dan Gohman890f92b2009-04-18 17:56:28 +00001349Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001350 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001351 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001352 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1353 // In the case of mixed integer and pointer types, do the
1354 // rest of the comparisons as integer.
1355 if (S->getOperand(i)->getType() != Ty) {
1356 Ty = SE.getEffectiveSCEVType(Ty);
1357 LHS = InsertNoopCastOfTo(LHS, Ty);
1358 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001359 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001360 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001361 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001362 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001363 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001364 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001365 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001366 // In the case of mixed integer and pointer types, cast the
1367 // final result back to the pointer type.
1368 if (LHS->getType() != S->getType())
1369 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001370 return LHS;
1371}
1372
Dan Gohman890f92b2009-04-18 17:56:28 +00001373Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001374 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001375 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001376 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1377 // In the case of mixed integer and pointer types, do the
1378 // rest of the comparisons as integer.
1379 if (S->getOperand(i)->getType() != Ty) {
1380 Ty = SE.getEffectiveSCEVType(Ty);
1381 LHS = InsertNoopCastOfTo(LHS, Ty);
1382 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001383 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001384 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001385 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001386 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001387 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001388 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001389 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001390 // In the case of mixed integer and pointer types, cast the
1391 // final result back to the pointer type.
1392 if (LHS->getType() != S->getType())
1393 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001394 return LHS;
1395}
1396
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001397Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001398 Instruction *I) {
1399 BasicBlock::iterator IP = I;
1400 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1401 ++IP;
1402 Builder.SetInsertPoint(IP->getParent(), IP);
1403 return expandCodeFor(SH, Ty);
1404}
1405
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001406Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001407 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001408 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001409 if (Ty) {
1410 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1411 "non-trivial casts should be done with the SCEVs directly!");
1412 V = InsertNoopCastOfTo(V, Ty);
1413 }
1414 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001415}
1416
Dan Gohman890f92b2009-04-18 17:56:28 +00001417Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001418 // Compute an insertion point for this SCEV object. Hoist the instructions
1419 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001420 Instruction *InsertPt = Builder.GetInsertPoint();
1421 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001422 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001423 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001424 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001425 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001426 InsertPt = Preheader->getTerminator();
1427 } else {
1428 // If the SCEV is computable at this level, insert it into the header
1429 // after the PHIs (and after any other instructions that we've inserted
1430 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001431 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1432 InsertPt = L->getHeader()->getFirstInsertionPt();
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001433 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001434 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001435 break;
1436 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001437
Dan Gohman667d7872009-06-26 22:53:46 +00001438 // Check to see if we already expanded this here.
1439 std::map<std::pair<const SCEV *, Instruction *>,
1440 AssertingVH<Value> >::iterator I =
1441 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001442 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001443 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001444
1445 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1446 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1447 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001448
1449 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001450 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001451
Dan Gohman667d7872009-06-26 22:53:46 +00001452 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001453 //
1454 // This is independent of PostIncLoops. The mapped value simply materializes
1455 // the expression at this insertion point. If the mapped value happened to be
1456 // a postinc expansion, it could be reused by a non postinc user, but only if
1457 // its insertion point was already at the head of the loop.
1458 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001459
Dan Gohman45598552010-02-15 00:21:43 +00001460 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001461 return V;
1462}
Dan Gohman1d09de32009-06-05 16:35:53 +00001463
Dan Gohman1d826a72010-02-14 03:12:47 +00001464void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001465 if (!PostIncLoops.empty())
1466 InsertedPostIncValues.insert(I);
1467 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001468 InsertedValues.insert(I);
1469
1470 // If we just claimed an existing instruction and that instruction had
Andrew Trick3228cc22011-03-14 16:50:06 +00001471 // been the insert point, adjust the insert point forward so that
Dan Gohman1d826a72010-02-14 03:12:47 +00001472 // subsequently inserted code will be dominated.
1473 if (Builder.GetInsertPoint() == I) {
1474 BasicBlock::iterator It = cast<Instruction>(I);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001475 do { ++It; } while (isInsertedInstruction(It) ||
1476 isa<DbgInfoIntrinsic>(It));
Dan Gohman1d826a72010-02-14 03:12:47 +00001477 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1478 }
1479}
1480
Dan Gohman45598552010-02-15 00:21:43 +00001481void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001482 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001483 // advance past them.
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001484 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
Dan Gohman45598552010-02-15 00:21:43 +00001485
1486 Builder.SetInsertPoint(BB, I);
1487}
1488
Dan Gohman1d09de32009-06-05 16:35:53 +00001489/// getOrInsertCanonicalInductionVariable - This method returns the
1490/// canonical induction variable of the specified type for the specified
1491/// loop (inserting one if there is none). A canonical induction variable
1492/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001493PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001494SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001495 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001496 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001497
1498 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001499 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001500 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001501 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001502
1503 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001504 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1505 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001506 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001507 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001508 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001509
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001510 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001511}
Andrew Trick20449412011-10-11 02:28:51 +00001512
1513/// hoistStep - Attempt to hoist an IV increment above a potential use.
1514///
1515/// To successfully hoist, two criteria must be met:
1516/// - IncV operands dominate InsertPos and
1517/// - InsertPos dominates IncV
1518///
1519/// Meeting the second condition means that we don't need to check all of IncV's
1520/// existing uses (it's moving up in the domtree).
1521///
1522/// This does not yet recursively hoist the operands, although that would
1523/// not be difficult.
1524///
1525/// This does not require a SCEVExpander instance and could be replaced by a
1526/// general code-insertion helper.
1527bool SCEVExpander::hoistStep(Instruction *IncV, Instruction *InsertPos,
1528 const DominatorTree *DT) {
1529 if (DT->dominates(IncV, InsertPos))
1530 return true;
1531
1532 if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
1533 return false;
1534
1535 if (IncV->mayHaveSideEffects())
1536 return false;
1537
1538 // Attempt to hoist IncV
1539 for (User::op_iterator OI = IncV->op_begin(), OE = IncV->op_end();
1540 OI != OE; ++OI) {
1541 Instruction *OInst = dyn_cast<Instruction>(OI);
1542 if (OInst && !DT->dominates(OInst, InsertPos))
1543 return false;
1544 }
1545 IncV->moveBefore(InsertPos);
1546 return true;
1547}
1548
1549/// replaceCongruentIVs - Check for congruent phis in this loop header and
1550/// replace them with their most canonical representative. Return the number of
1551/// phis eliminated.
1552///
1553/// This does not depend on any SCEVExpander state but should be used in
1554/// the same context that SCEVExpander is used.
1555unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1556 SmallVectorImpl<WeakVH> &DeadInsts) {
1557 unsigned NumElim = 0;
1558 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1559 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1560 PHINode *Phi = cast<PHINode>(I);
1561 if (!SE.isSCEVable(Phi->getType()))
1562 continue;
1563
1564 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1565 if (!OrigPhiRef) {
1566 OrigPhiRef = Phi;
1567 continue;
1568 }
1569
1570 // If one phi derives from the other via GEPs, types may differ.
1571 // We could consider adding a bitcast here to handle it.
1572 if (OrigPhiRef->getType() != Phi->getType())
1573 continue;
1574
1575 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1576 Instruction *OrigInc =
1577 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1578 Instruction *IsomorphicInc =
1579 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1580
1581 // If this phi is more canonical, swap it with the original.
Andrew Trick365c9f12011-10-15 06:19:55 +00001582 if (!isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)
1583 && isExpandedAddRecExprPHI(Phi, IsomorphicInc, L)) {
Andrew Trick20449412011-10-11 02:28:51 +00001584 std::swap(OrigPhiRef, Phi);
1585 std::swap(OrigInc, IsomorphicInc);
1586 }
1587 // Replacing the congruent phi is sufficient because acyclic redundancy
1588 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1589 // that a phi is congruent, it's often the head of an IV user cycle that
1590 // is isomorphic with the original phi. So it's worth eagerly cleaning up
1591 // the common case of a single IV increment.
1592 if (OrigInc != IsomorphicInc &&
1593 OrigInc->getType() == IsomorphicInc->getType() &&
1594 SE.getSCEV(OrigInc) == SE.getSCEV(IsomorphicInc) &&
1595 hoistStep(OrigInc, IsomorphicInc, DT)) {
1596 DEBUG_WITH_TYPE(DebugType, dbgs()
1597 << "INDVARS: Eliminated congruent iv.inc: "
1598 << *IsomorphicInc << '\n');
1599 IsomorphicInc->replaceAllUsesWith(OrigInc);
1600 DeadInsts.push_back(IsomorphicInc);
1601 }
1602 }
1603 DEBUG_WITH_TYPE(DebugType, dbgs()
1604 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1605 ++NumElim;
1606 Phi->replaceAllUsesWith(OrigPhiRef);
1607 DeadInsts.push_back(Phi);
1608 }
1609 return NumElim;
1610}