blob: 76a94ea274673bb816a1c7cec385e649dbdd42d5 [file] [log] [blame]
Nate Begeman36f891b2005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman36f891b2005-07-30 00:12:19 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution expander,
11// which is used to generate the code corresponding to a given scalar evolution
12// expression.
13//
14//===----------------------------------------------------------------------===//
15
Nate Begeman36f891b2005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000017#include "llvm/Analysis/LoopInfo.h"
Dale Johannesen8d50ea72010-03-05 21:12:40 +000018#include "llvm/IntrinsicInst.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000019#include "llvm/LLVMContext.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000020#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000021#include "llvm/ADT/STLExtras.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000022using namespace llvm;
23
Gabor Greif19e5ada2010-07-09 16:42:04 +000024/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000025/// reusing an existing cast if a suitable one exists, moving an existing
26/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000027/// creating a new one.
Dan Gohman485c43f2010-06-19 13:25:23 +000028Value *SCEVExpander::ReuseOrCreateCast(Value *V, const Type *Ty,
29 Instruction::CastOps Op,
30 BasicBlock::iterator IP) {
31 // Check to see if there is already a cast!
32 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000033 UI != E; ++UI) {
34 User *U = *UI;
35 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000036 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000037 if (CI->getOpcode() == Op) {
38 // If the cast isn't where we want it, fix it.
39 if (BasicBlock::iterator(CI) != IP) {
40 // Create a new cast, and leave the old cast in place in case
41 // it is being used as an insert point. Clear its operand
42 // so that it doesn't hold anything live.
43 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
44 NewCI->takeName(CI);
45 CI->replaceAllUsesWith(NewCI);
46 CI->setOperand(0, UndefValue::get(V->getType()));
47 rememberInstruction(NewCI);
48 return NewCI;
49 }
Dan Gohman6f5fed22010-06-19 22:50:35 +000050 rememberInstruction(CI);
Dan Gohman485c43f2010-06-19 13:25:23 +000051 return CI;
52 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000053 }
Dan Gohman485c43f2010-06-19 13:25:23 +000054
55 // Create a new cast.
56 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
57 rememberInstruction(I);
58 return I;
59}
60
Dan Gohman267a3852009-06-27 21:18:18 +000061/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
62/// which must be possible with a noop cast, doing what we can to share
63/// the casts.
64Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
65 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
66 assert((Op == Instruction::BitCast ||
67 Op == Instruction::PtrToInt ||
68 Op == Instruction::IntToPtr) &&
69 "InsertNoopCastOfTo cannot perform non-noop casts!");
70 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
71 "InsertNoopCastOfTo cannot change sizes!");
72
Dan Gohman2d1be872009-04-16 03:18:22 +000073 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000074 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000075 return V;
76
Dan Gohmanf04fa482009-04-16 15:52:57 +000077 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000078 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000079 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000080 if (CastInst *CI = dyn_cast<CastInst>(V))
81 if ((CI->getOpcode() == Instruction::PtrToInt ||
82 CI->getOpcode() == Instruction::IntToPtr) &&
83 SE.getTypeSizeInBits(CI->getType()) ==
84 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
85 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000086 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
87 if ((CE->getOpcode() == Instruction::PtrToInt ||
88 CE->getOpcode() == Instruction::IntToPtr) &&
89 SE.getTypeSizeInBits(CE->getType()) ==
90 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
91 return CE->getOperand(0);
92 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000093
Dan Gohman485c43f2010-06-19 13:25:23 +000094 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000095 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000096 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000097
Dan Gohman485c43f2010-06-19 13:25:23 +000098 // Cast the argument at the beginning of the entry block, after
99 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000100 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000101 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
102 while ((isa<BitCastInst>(IP) &&
103 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
104 cast<BitCastInst>(IP)->getOperand(0) != A) ||
105 isa<DbgInfoIntrinsic>(IP))
106 ++IP;
107 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000108 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000109
Dan Gohman485c43f2010-06-19 13:25:23 +0000110 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000111 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000112 BasicBlock::iterator IP = I; ++IP;
113 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
114 IP = II->getNormalDest()->begin();
Jim Grosbach08f55d02010-06-16 21:13:38 +0000115 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000116 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000117}
118
Chris Lattner7fec90e2007-04-13 05:04:18 +0000119/// InsertBinop - Insert the specified binary operator, doing a small amount
120/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000121Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
122 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000123 // Fold a binop with constant operands.
124 if (Constant *CLHS = dyn_cast<Constant>(LHS))
125 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000126 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000127
Chris Lattner7fec90e2007-04-13 05:04:18 +0000128 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
129 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000130 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
131 // Scanning starts from the last instruction before the insertion point.
132 BasicBlock::iterator IP = Builder.GetInsertPoint();
133 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000134 --IP;
135 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000136 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
137 // generated code.
138 if (isa<DbgInfoIntrinsic>(IP))
139 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000140 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
141 IP->getOperand(1) == RHS)
142 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000143 if (IP == BlockBegin) break;
144 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000145 }
Dan Gohman267a3852009-06-27 21:18:18 +0000146
Dan Gohman087bd1e2010-03-03 05:29:13 +0000147 // Save the original insertion point so we can restore it when we're done.
148 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
149 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
150
151 // Move the insertion point out of as many loops as we can.
152 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
153 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
154 BasicBlock *Preheader = L->getLoopPreheader();
155 if (!Preheader) break;
156
157 // Ok, move up a level.
158 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
159 }
160
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000161 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000162 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000163 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000164
165 // Restore the original insert point.
166 if (SaveInsertBB)
167 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
168
Dan Gohmancf5ab822009-05-01 17:13:31 +0000169 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000170}
171
Dan Gohman4a4f7672009-05-27 02:00:53 +0000172/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000173/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000174/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000175/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000176/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
177/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
178/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000179static bool FactorOutConstant(const SCEV *&S,
180 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000181 const SCEV *Factor,
182 ScalarEvolution &SE,
183 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000184 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000185 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000186 return true;
187
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000188 // x/x == 1.
189 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000190 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000191 return true;
192 }
193
Dan Gohman453aa4f2009-05-24 18:06:31 +0000194 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000195 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000196 // 0/x == 0.
197 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000198 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000199 // Check for divisibility.
200 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
201 ConstantInt *CI =
202 ConstantInt::get(SE.getContext(),
203 C->getValue()->getValue().sdiv(
204 FC->getValue()->getValue()));
205 // If the quotient is zero and the remainder is non-zero, reject
206 // the value at this scale. It will be considered for subsequent
207 // smaller scales.
208 if (!CI->isZero()) {
209 const SCEV *Div = SE.getConstant(CI);
210 S = Div;
211 Remainder =
212 SE.getAddExpr(Remainder,
213 SE.getConstant(C->getValue()->getValue().srem(
214 FC->getValue()->getValue())));
215 return true;
216 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000217 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000218 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000219
220 // In a Mul, check if there is a constant operand which is a multiple
221 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000222 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
223 if (TD) {
224 // With TargetData, the size is known. Check if there is a constant
225 // operand which is a multiple of the given factor. If so, we can
226 // factor it.
227 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
228 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
229 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000230 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000231 NewMulOps[0] =
232 SE.getConstant(C->getValue()->getValue().sdiv(
233 FC->getValue()->getValue()));
234 S = SE.getMulExpr(NewMulOps);
235 return true;
236 }
237 } else {
238 // Without TargetData, check if Factor can be factored out of any of the
239 // Mul's operands. If so, we can just remove it.
240 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
241 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000242 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000243 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
244 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000245 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000246 NewMulOps[i] = SOp;
247 S = SE.getMulExpr(NewMulOps);
248 return true;
249 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000250 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000251 }
252 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000253
254 // In an AddRec, check if both start and step are divisible.
255 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000256 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000257 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000258 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000259 return false;
260 if (!StepRem->isZero())
261 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000262 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000263 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000264 return false;
265 S = SE.getAddRecExpr(Start, Step, A->getLoop());
266 return true;
267 }
268
269 return false;
270}
271
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000272/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
273/// is the number of SCEVAddRecExprs present, which are kept at the end of
274/// the list.
275///
276static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
277 const Type *Ty,
278 ScalarEvolution &SE) {
279 unsigned NumAddRecs = 0;
280 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
281 ++NumAddRecs;
282 // Group Ops into non-addrecs and addrecs.
283 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
284 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
285 // Let ScalarEvolution sort and simplify the non-addrecs list.
286 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000287 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000288 SE.getAddExpr(NoAddRecs);
289 // If it returned an add, use the operands. Otherwise it simplified
290 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000291 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000292 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000293 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000294 else if (!Sum->isZero())
295 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000296 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000297 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000298}
299
300/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
301/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
302/// This helps expose more opportunities for folding parts of the expressions
303/// into GEP indices.
304///
305static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
306 const Type *Ty,
307 ScalarEvolution &SE) {
308 // Find the addrecs.
309 SmallVector<const SCEV *, 8> AddRecs;
310 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
311 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
312 const SCEV *Start = A->getStart();
313 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000314 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000315 AddRecs.push_back(SE.getAddRecExpr(Zero,
316 A->getStepRecurrence(SE),
317 A->getLoop()));
318 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
319 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000320 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000321 e += Add->getNumOperands();
322 } else {
323 Ops[i] = Start;
324 }
325 }
326 if (!AddRecs.empty()) {
327 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000328 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000329 // Resort the operand list, moving any constants to the front.
330 SimplifyAddOperands(Ops, Ty, SE);
331 }
332}
333
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000334/// expandAddToGEP - Expand an addition expression with a pointer type into
335/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
336/// BasicAliasAnalysis and other passes analyze the result. See the rules
337/// for getelementptr vs. inttoptr in
338/// http://llvm.org/docs/LangRef.html#pointeraliasing
339/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000340///
Dan Gohman3abf9052010-01-19 22:26:02 +0000341/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000342/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
343/// they may introduce pointer arithmetic which may not be safely converted
344/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000345///
346/// Design note: It might seem desirable for this function to be more
347/// loop-aware. If some of the indices are loop-invariant while others
348/// aren't, it might seem desirable to emit multiple GEPs, keeping the
349/// loop-invariant portions of the overall computation outside the loop.
350/// However, there are a few reasons this is not done here. Hoisting simple
351/// arithmetic is a low-level optimization that often isn't very
352/// important until late in the optimization process. In fact, passes
353/// like InstructionCombining will combine GEPs, even if it means
354/// pushing loop-invariant computation down into loops, so even if the
355/// GEPs were split here, the work would quickly be undone. The
356/// LoopStrengthReduction pass, which is usually run quite late (and
357/// after the last InstructionCombining pass), takes care of hoisting
358/// loop-invariant portions of expressions, after considering what
359/// can be folded using target addressing modes.
360///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000361Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
362 const SCEV *const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000363 const PointerType *PTy,
364 const Type *Ty,
365 Value *V) {
366 const Type *ElTy = PTy->getElementType();
367 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000368 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000369 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000370
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000371 // Split AddRecs up into parts as either of the parts may be usable
372 // without the other.
373 SplitAddRecs(Ops, Ty, SE);
374
Bob Wilsoneb356992009-12-04 01:33:04 +0000375 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000376 // operands into GEP indices, at each level. The first index in a GEP
377 // indexes into the array implied by the pointer operand; the rest of
378 // the indices index into the element or field type selected by the
379 // preceding index.
380 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000381 // If the scale size is not 0, attempt to factor out a scale for
382 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000383 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000384 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000385 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000386 if (!ElSize->isZero()) {
387 SmallVector<const SCEV *, 8> NewOps;
388 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
389 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000390 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000391 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
392 // Op now has ElSize factored out.
393 ScaledOps.push_back(Op);
394 if (!Remainder->isZero())
395 NewOps.push_back(Remainder);
396 AnyNonZeroIndices = true;
397 } else {
398 // The operand was not divisible, so add it to the list of operands
399 // we'll scan next iteration.
400 NewOps.push_back(Ops[i]);
401 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000402 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000403 // If we made any changes, update Ops.
404 if (!ScaledOps.empty()) {
405 Ops = NewOps;
406 SimplifyAddOperands(Ops, Ty, SE);
407 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000408 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000409 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000410
411 // Record the scaled array index for this level of the type. If
412 // we didn't find any operands that could be factored, tentatively
413 // assume that element zero was selected (since the zero offset
414 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000415 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000416 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000417 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
418 GepIndices.push_back(Scaled);
419
420 // Collect struct field index operands.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000421 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
422 bool FoundFieldNo = false;
423 // An empty struct has no fields.
424 if (STy->getNumElements() == 0) break;
425 if (SE.TD) {
426 // With TargetData, field offsets are known. See if a constant offset
427 // falls within any of the struct fields.
428 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000429 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
430 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
431 const StructLayout &SL = *SE.TD->getStructLayout(STy);
432 uint64_t FullOffset = C->getValue()->getZExtValue();
433 if (FullOffset < SL.getSizeInBytes()) {
434 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000435 GepIndices.push_back(
436 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000437 ElTy = STy->getTypeAtIndex(ElIdx);
438 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000439 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000440 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000441 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000442 }
443 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000444 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000445 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000446 // appropriate struct type.
447 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000448 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000449 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000450 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000451 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000452 GepIndices.push_back(FieldNo);
453 ElTy =
454 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000455 Ops[i] = SE.getConstant(Ty, 0);
456 AnyNonZeroIndices = true;
457 FoundFieldNo = true;
458 break;
459 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000460 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000461 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000462 // If no struct field offsets were found, tentatively assume that
463 // field zero was selected (since the zero offset would obviously
464 // be folded away).
465 if (!FoundFieldNo) {
466 ElTy = STy->getTypeAtIndex(0u);
467 GepIndices.push_back(
468 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
469 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000470 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000471
472 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
473 ElTy = ATy->getElementType();
474 else
475 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000476 }
477
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000478 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000479 // the base to i8* and do an ugly getelementptr with that. It's still
480 // better than ptrtoint+arithmetic+inttoptr at least.
481 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000482 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000483 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000484 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000485
486 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000487 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000488
489 // Fold a GEP with constant operands.
490 if (Constant *CLHS = dyn_cast<Constant>(V))
491 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000492 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000493
494 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
495 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000496 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
497 // Scanning starts from the last instruction before the insertion point.
498 BasicBlock::iterator IP = Builder.GetInsertPoint();
499 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000500 --IP;
501 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000502 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
503 // generated code.
504 if (isa<DbgInfoIntrinsic>(IP))
505 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000506 if (IP->getOpcode() == Instruction::GetElementPtr &&
507 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
508 return IP;
509 if (IP == BlockBegin) break;
510 }
511 }
512
Dan Gohman087bd1e2010-03-03 05:29:13 +0000513 // Save the original insertion point so we can restore it when we're done.
514 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
515 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
516
517 // Move the insertion point out of as many loops as we can.
518 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
519 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
520 BasicBlock *Preheader = L->getLoopPreheader();
521 if (!Preheader) break;
522
523 // Ok, move up a level.
524 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
525 }
526
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000527 // Emit a GEP.
528 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000529 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000530
531 // Restore the original insert point.
532 if (SaveInsertBB)
533 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
534
Dan Gohman5be18e82009-05-19 02:15:55 +0000535 return GEP;
536 }
537
Dan Gohman087bd1e2010-03-03 05:29:13 +0000538 // Save the original insertion point so we can restore it when we're done.
539 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
540 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
541
542 // Move the insertion point out of as many loops as we can.
543 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
544 if (!L->isLoopInvariant(V)) break;
545
546 bool AnyIndexNotLoopInvariant = false;
547 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
548 E = GepIndices.end(); I != E; ++I)
549 if (!L->isLoopInvariant(*I)) {
550 AnyIndexNotLoopInvariant = true;
551 break;
552 }
553 if (AnyIndexNotLoopInvariant)
554 break;
555
556 BasicBlock *Preheader = L->getLoopPreheader();
557 if (!Preheader) break;
558
559 // Ok, move up a level.
560 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
561 }
562
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000563 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
564 // because ScalarEvolution may have changed the address arithmetic to
565 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000566 Value *Casted = V;
567 if (V->getType() != PTy)
568 Casted = InsertNoopCastOfTo(Casted, PTy);
569 Value *GEP = Builder.CreateGEP(Casted,
Dan Gohman267a3852009-06-27 21:18:18 +0000570 GepIndices.begin(),
571 GepIndices.end(),
572 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000573 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000574 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000575
576 // Restore the original insert point.
577 if (SaveInsertBB)
578 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
579
Dan Gohman5be18e82009-05-19 02:15:55 +0000580 return expand(SE.getAddExpr(Ops));
581}
582
Dan Gohmana10756e2010-01-21 02:09:26 +0000583/// isNonConstantNegative - Return true if the specified scev is negated, but
584/// not a constant.
585static bool isNonConstantNegative(const SCEV *F) {
586 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
587 if (!Mul) return false;
588
589 // If there is a constant factor, it will be first.
590 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
591 if (!SC) return false;
592
593 // Return true if the value is negative, this matches things like (-42 * V).
594 return SC->getValue()->getValue().isNegative();
595}
596
Dan Gohman087bd1e2010-03-03 05:29:13 +0000597/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
598/// SCEV expansion. If they are nested, this is the most nested. If they are
599/// neighboring, pick the later.
600static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
601 DominatorTree &DT) {
602 if (!A) return B;
603 if (!B) return A;
604 if (A->contains(B)) return B;
605 if (B->contains(A)) return A;
606 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
607 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
608 return A; // Arbitrarily break the tie.
609}
610
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000611/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000612/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000613const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
614 // Test whether we've already computed the most relevant loop for this SCEV.
615 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
616 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
617 if (!Pair.second)
618 return Pair.first->second;
619
Dan Gohman087bd1e2010-03-03 05:29:13 +0000620 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000621 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000622 return 0;
623 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
624 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000625 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
626 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000627 return 0;
628 }
629 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
630 const Loop *L = 0;
631 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
632 L = AR->getLoop();
633 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
634 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000635 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
636 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000637 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000638 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
639 const Loop *Result = getRelevantLoop(C->getOperand());
640 return RelevantLoops[C] = Result;
641 }
642 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
643 const Loop *Result =
644 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
645 getRelevantLoop(D->getRHS()),
646 *SE.DT);
647 return RelevantLoops[D] = Result;
648 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000649 llvm_unreachable("Unexpected SCEV type!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000650 return 0;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000651}
652
Dan Gohmanb3579832010-04-15 17:08:50 +0000653namespace {
654
Dan Gohman087bd1e2010-03-03 05:29:13 +0000655/// LoopCompare - Compare loops by PickMostRelevantLoop.
656class LoopCompare {
657 DominatorTree &DT;
658public:
659 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
660
661 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
662 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000663 // Keep pointer operands sorted at the end.
664 if (LHS.second->getType()->isPointerTy() !=
665 RHS.second->getType()->isPointerTy())
666 return LHS.second->getType()->isPointerTy();
667
Dan Gohman087bd1e2010-03-03 05:29:13 +0000668 // Compare loops with PickMostRelevantLoop.
669 if (LHS.first != RHS.first)
670 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
671
672 // If one operand is a non-constant negative and the other is not,
673 // put the non-constant negative on the right so that a sub can
674 // be used instead of a negate and add.
675 if (isNonConstantNegative(LHS.second)) {
676 if (!isNonConstantNegative(RHS.second))
677 return false;
678 } else if (isNonConstantNegative(RHS.second))
679 return true;
680
681 // Otherwise they are equivalent according to this comparison.
682 return false;
683 }
684};
685
Dan Gohmanb3579832010-04-15 17:08:50 +0000686}
687
Dan Gohman890f92b2009-04-18 17:56:28 +0000688Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000689 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000690
Dan Gohman087bd1e2010-03-03 05:29:13 +0000691 // Collect all the add operands in a loop, along with their associated loops.
692 // Iterate in reverse so that constants are emitted last, all else equal, and
693 // so that pointer operands are inserted first, which the code below relies on
694 // to form more involved GEPs.
695 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
696 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
697 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000698 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000699
Dan Gohman087bd1e2010-03-03 05:29:13 +0000700 // Sort by loop. Use a stable sort so that constants follow non-constants and
701 // pointer operands precede non-pointer operands.
702 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000703
Dan Gohman087bd1e2010-03-03 05:29:13 +0000704 // Emit instructions to add all the operands. Hoist as much as possible
705 // out of loops, and form meaningful getelementptrs where possible.
706 Value *Sum = 0;
707 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
708 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
709 const Loop *CurLoop = I->first;
710 const SCEV *Op = I->second;
711 if (!Sum) {
712 // This is the first operand. Just expand it.
713 Sum = expand(Op);
714 ++I;
715 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
716 // The running sum expression is a pointer. Try to form a getelementptr
717 // at this level with that as the base.
718 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000719 for (; I != E && I->first == CurLoop; ++I) {
720 // If the operand is SCEVUnknown and not instructions, peek through
721 // it, to enable more of it to be folded into the GEP.
722 const SCEV *X = I->second;
723 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
724 if (!isa<Instruction>(U->getValue()))
725 X = SE.getSCEV(U->getValue());
726 NewOps.push_back(X);
727 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000728 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
729 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
730 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000731 // Try to form a getelementptr. If the running sum is instructions,
732 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000733 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000734 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
735 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000736 for (++I; I != E && I->first == CurLoop; ++I)
737 NewOps.push_back(I->second);
738 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
739 } else if (isNonConstantNegative(Op)) {
740 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000741 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000742 Sum = InsertNoopCastOfTo(Sum, Ty);
743 Sum = InsertBinop(Instruction::Sub, Sum, W);
744 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000745 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000746 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000747 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000748 Sum = InsertNoopCastOfTo(Sum, Ty);
749 // Canonicalize a constant to the RHS.
750 if (isa<Constant>(Sum)) std::swap(Sum, W);
751 Sum = InsertBinop(Instruction::Add, Sum, W);
752 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000753 }
754 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000755
756 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000757}
Dan Gohman5be18e82009-05-19 02:15:55 +0000758
Dan Gohman890f92b2009-04-18 17:56:28 +0000759Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000760 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000761
Dan Gohman087bd1e2010-03-03 05:29:13 +0000762 // Collect all the mul operands in a loop, along with their associated loops.
763 // Iterate in reverse so that constants are emitted last, all else equal.
764 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
765 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
766 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000767 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000768
Dan Gohman087bd1e2010-03-03 05:29:13 +0000769 // Sort by loop. Use a stable sort so that constants follow non-constants.
770 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
771
772 // Emit instructions to mul all the operands. Hoist as much as possible
773 // out of loops.
774 Value *Prod = 0;
775 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
776 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
777 const SCEV *Op = I->second;
778 if (!Prod) {
779 // This is the first operand. Just expand it.
780 Prod = expand(Op);
781 ++I;
782 } else if (Op->isAllOnesValue()) {
783 // Instead of doing a multiply by negative one, just do a negate.
784 Prod = InsertNoopCastOfTo(Prod, Ty);
785 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
786 ++I;
787 } else {
788 // A simple mul.
789 Value *W = expandCodeFor(Op, Ty);
790 Prod = InsertNoopCastOfTo(Prod, Ty);
791 // Canonicalize a constant to the RHS.
792 if (isa<Constant>(Prod)) std::swap(Prod, W);
793 Prod = InsertBinop(Instruction::Mul, Prod, W);
794 ++I;
795 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000796 }
797
Dan Gohman087bd1e2010-03-03 05:29:13 +0000798 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000799}
800
Dan Gohman890f92b2009-04-18 17:56:28 +0000801Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000802 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000803
Dan Gohman92fcdca2009-06-09 17:18:38 +0000804 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000805 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000806 const APInt &RHS = SC->getValue()->getValue();
807 if (RHS.isPowerOf2())
808 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000809 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000810 }
811
Dan Gohman92fcdca2009-06-09 17:18:38 +0000812 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000813 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000814}
815
Dan Gohman453aa4f2009-05-24 18:06:31 +0000816/// Move parts of Base into Rest to leave Base with the minimal
817/// expression that provides a pointer operand suitable for a
818/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000819static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000820 ScalarEvolution &SE) {
821 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
822 Base = A->getStart();
823 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000824 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000825 A->getStepRecurrence(SE),
826 A->getLoop()));
827 }
828 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
829 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000830 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000831 NewAddOps.back() = Rest;
832 Rest = SE.getAddExpr(NewAddOps);
833 ExposePointerBase(Base, Rest, SE);
834 }
835}
836
Dan Gohmana10756e2010-01-21 02:09:26 +0000837/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
838/// the base addrec, which is the addrec without any non-loop-dominating
839/// values, and return the PHI.
840PHINode *
841SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
842 const Loop *L,
843 const Type *ExpandTy,
844 const Type *IntTy) {
845 // Reuse a previously-inserted PHI, if present.
846 for (BasicBlock::iterator I = L->getHeader()->begin();
847 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohman572645c2010-02-12 10:34:29 +0000848 if (SE.isSCEVable(PN->getType()) &&
849 (SE.getEffectiveSCEVType(PN->getType()) ==
850 SE.getEffectiveSCEVType(Normalized->getType())) &&
851 SE.getSCEV(PN) == Normalized)
852 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Dan Gohman572645c2010-02-12 10:34:29 +0000853 Instruction *IncV =
Dan Gohman22e62192010-02-16 00:20:08 +0000854 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
855
856 // Determine if this is a well-behaved chain of instructions leading
857 // back to the PHI. It probably will be, if we're scanning an inner
858 // loop already visited by LSR for example, but it wouldn't have
859 // to be.
860 do {
Dan Gohman0cbe91b2011-03-02 01:34:10 +0000861 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
Dan Gohmana7a841a2011-03-04 20:46:46 +0000862 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV))) {
Dan Gohman22e62192010-02-16 00:20:08 +0000863 IncV = 0;
864 break;
865 }
Dan Gohman9feae9f2010-02-17 02:39:31 +0000866 // If any of the operands don't dominate the insert position, bail.
867 // Addrec operands are always loop-invariant, so this can only happen
868 // if there are instructions which haven't been hoisted.
869 for (User::op_iterator OI = IncV->op_begin()+1,
870 OE = IncV->op_end(); OI != OE; ++OI)
871 if (Instruction *OInst = dyn_cast<Instruction>(OI))
872 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
873 IncV = 0;
874 break;
875 }
876 if (!IncV)
877 break;
878 // Advance to the next instruction.
Dan Gohman22e62192010-02-16 00:20:08 +0000879 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
880 if (!IncV)
881 break;
882 if (IncV->mayHaveSideEffects()) {
883 IncV = 0;
884 break;
885 }
886 } while (IncV != PN);
887
888 if (IncV) {
889 // Ok, the add recurrence looks usable.
890 // Remember this PHI, even in post-inc mode.
891 InsertedValues.insert(PN);
892 // Remember the increment.
893 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
894 rememberInstruction(IncV);
895 if (L == IVIncInsertLoop)
896 do {
897 if (SE.DT->dominates(IncV, IVIncInsertPos))
898 break;
899 // Make sure the increment is where we want it. But don't move it
900 // down past a potential existing post-inc user.
901 IncV->moveBefore(IVIncInsertPos);
902 IVIncInsertPos = IncV;
903 IncV = cast<Instruction>(IncV->getOperand(0));
904 } while (IncV != PN);
905 return PN;
906 }
Dan Gohman572645c2010-02-12 10:34:29 +0000907 }
Dan Gohmana10756e2010-01-21 02:09:26 +0000908
909 // Save the original insertion point so we can restore it when we're done.
910 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
911 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
912
913 // Expand code for the start value.
914 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
915 L->getHeader()->begin());
916
917 // Expand code for the step value. Insert instructions right before the
918 // terminator corresponding to the back-edge. Do this before creating the PHI
919 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
920 // negative, insert a sub instead of an add for the increment (unless it's a
921 // constant, because subtracts of constants are canonicalized to adds).
922 const SCEV *Step = Normalized->getStepRecurrence(SE);
Duncan Sands1df98592010-02-16 11:11:14 +0000923 bool isPointer = ExpandTy->isPointerTy();
Dan Gohmana10756e2010-01-21 02:09:26 +0000924 bool isNegative = !isPointer && isNonConstantNegative(Step);
925 if (isNegative)
926 Step = SE.getNegativeSCEV(Step);
927 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
928
929 // Create the PHI.
930 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
931 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
932 rememberInstruction(PN);
933
934 // Create the step instructions and populate the PHI.
935 BasicBlock *Header = L->getHeader();
936 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
937 HPI != HPE; ++HPI) {
938 BasicBlock *Pred = *HPI;
939
940 // Add a start value.
941 if (!L->contains(Pred)) {
942 PN->addIncoming(StartV, Pred);
943 continue;
944 }
945
946 // Create a step value and add it to the PHI. If IVIncInsertLoop is
947 // non-null and equal to the addrec's loop, insert the instructions
948 // at IVIncInsertPos.
949 Instruction *InsertPos = L == IVIncInsertLoop ?
950 IVIncInsertPos : Pred->getTerminator();
951 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
952 Value *IncV;
953 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
954 if (isPointer) {
955 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
956 // If the step isn't constant, don't use an implicitly scaled GEP, because
957 // that would require a multiply inside the loop.
958 if (!isa<ConstantInt>(StepV))
959 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
960 GEPPtrTy->getAddressSpace());
961 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
962 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
963 if (IncV->getType() != PN->getType()) {
964 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
965 rememberInstruction(IncV);
966 }
967 } else {
968 IncV = isNegative ?
969 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
970 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
971 rememberInstruction(IncV);
972 }
973 PN->addIncoming(IncV, Pred);
974 }
975
976 // Restore the original insert point.
977 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +0000978 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +0000979
980 // Remember this PHI, even in post-inc mode.
981 InsertedValues.insert(PN);
982
983 return PN;
984}
985
986Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
987 const Type *STy = S->getType();
988 const Type *IntTy = SE.getEffectiveSCEVType(STy);
989 const Loop *L = S->getLoop();
990
991 // Determine a normalized form of this expression, which is the expression
992 // before any post-inc adjustment is made.
993 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +0000994 if (PostIncLoops.count(L)) {
995 PostIncLoopSet Loops;
996 Loops.insert(L);
997 Normalized =
998 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
999 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001000 }
1001
1002 // Strip off any non-loop-dominating component from the addrec start.
1003 const SCEV *Start = Normalized->getStart();
1004 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001005 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001006 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001007 Start = SE.getConstant(Normalized->getType(), 0);
Dan Gohmana10756e2010-01-21 02:09:26 +00001008 Normalized =
1009 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
1010 Normalized->getStepRecurrence(SE),
1011 Normalized->getLoop()));
1012 }
1013
1014 // Strip off any non-loop-dominating component from the addrec step.
1015 const SCEV *Step = Normalized->getStepRecurrence(SE);
1016 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001017 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001018 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001019 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001020 Normalized =
1021 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
1022 Normalized->getLoop()));
1023 }
1024
1025 // Expand the core addrec. If we need post-loop scaling, force it to
1026 // expand to an integer type to avoid the need for additional casting.
1027 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1028 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1029
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001030 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001031 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001032 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001033 Result = PN;
1034 else {
1035 // In PostInc mode, use the post-incremented value.
1036 BasicBlock *LatchBlock = L->getLoopLatch();
1037 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1038 Result = PN->getIncomingValueForBlock(LatchBlock);
1039 }
1040
1041 // Re-apply any non-loop-dominating scale.
1042 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001043 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001044 Result = Builder.CreateMul(Result,
1045 expandCodeFor(PostLoopScale, IntTy));
1046 rememberInstruction(Result);
1047 }
1048
1049 // Re-apply any non-loop-dominating offset.
1050 if (PostLoopOffset) {
1051 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1052 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1053 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1054 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001055 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001056 Result = Builder.CreateAdd(Result,
1057 expandCodeFor(PostLoopOffset, IntTy));
1058 rememberInstruction(Result);
1059 }
1060 }
1061
1062 return Result;
1063}
1064
Dan Gohman890f92b2009-04-18 17:56:28 +00001065Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001066 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1067
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001068 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001069 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001070
Dan Gohman4d8414f2009-06-13 16:25:49 +00001071 // First check for an existing canonical IV in a suitable type.
1072 PHINode *CanonicalIV = 0;
1073 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001074 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001075 CanonicalIV = PN;
1076
1077 // Rewrite an AddRec in terms of the canonical induction variable, if
1078 // its type is more narrow.
1079 if (CanonicalIV &&
1080 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1081 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001082 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1083 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1084 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Dan Gohmanf3f1be62009-09-28 21:01:47 +00001085 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +00001086 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1087 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001088 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001089 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Jim Grosbach08f55d02010-06-16 21:13:38 +00001090 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt))
1091 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001092 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1093 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001094 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001095 return V;
1096 }
1097
Nate Begeman36f891b2005-07-30 00:12:19 +00001098 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001099 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001100 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001101 NewOps[0] = SE.getConstant(Ty, 0);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001102 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001103
1104 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1105 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001106 const SCEV *Base = S->getStart();
1107 const SCEV *RestArray[1] = { Rest };
1108 // Dig into the expression to find the pointer base for a GEP.
1109 ExposePointerBase(Base, RestArray[0], SE);
1110 // If we found a pointer, expand the AddRec with a GEP.
1111 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1112 // Make sure the Base isn't something exotic, such as a multiplied
1113 // or divided pointer value. In those cases, the result type isn't
1114 // actually a pointer type.
1115 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1116 Value *StartV = expand(Base);
1117 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1118 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001119 }
1120 }
1121
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001122 // Just do a normal add. Pre-expand the operands to suppress folding.
1123 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1124 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001125 }
1126
Dan Gohman6ebfd722010-07-26 18:28:14 +00001127 // If we don't yet have a canonical IV, create one.
1128 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001129 // Create and insert the PHI node for the induction variable in the
1130 // specified loop.
1131 BasicBlock *Header = L->getHeader();
Dan Gohman6ebfd722010-07-26 18:28:14 +00001132 CanonicalIV = PHINode::Create(Ty, "indvar", Header->begin());
1133 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001134
Owen Andersoneed707b2009-07-24 23:12:02 +00001135 Constant *One = ConstantInt::get(Ty, 1);
Dan Gohman83d57742009-09-27 17:46:40 +00001136 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
Gabor Greif76560182010-07-09 15:40:10 +00001137 HPI != HPE; ++HPI) {
1138 BasicBlock *HP = *HPI;
1139 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001140 // Insert a unit add instruction right before the terminator
1141 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001142 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1143 "indvar.next",
1144 HP->getTerminator());
Dan Gohmana10756e2010-01-21 02:09:26 +00001145 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001146 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001147 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001148 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001149 }
Gabor Greif76560182010-07-09 15:40:10 +00001150 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001151 }
1152
Dan Gohman6ebfd722010-07-26 18:28:14 +00001153 // {0,+,1} --> Insert a canonical induction variable into the loop!
1154 if (S->isAffine() && S->getOperand(1)->isOne()) {
1155 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1156 "IVs with types different from the canonical IV should "
1157 "already have been handled!");
1158 return CanonicalIV;
1159 }
1160
Dan Gohman4d8414f2009-06-13 16:25:49 +00001161 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001162
Chris Lattnerdf14a042005-10-30 06:24:33 +00001163 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001164 if (S->isAffine()) // {0,+,F} --> i*F
1165 return
1166 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001167 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001168 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001169 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001170 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001171
1172 // If this is a chain of recurrences, turn it into a closed form, using the
1173 // folders, then expandCodeFor the closed form. This allows the folders to
1174 // simplify the expression without having to build a bunch of special code
1175 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001176 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001177
Dan Gohman4d8414f2009-06-13 16:25:49 +00001178 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001179 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001180 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001181 if (isa<SCEVAddRecExpr>(Ext))
1182 NewS = Ext;
1183
Dan Gohman0bba49c2009-07-07 17:06:11 +00001184 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001185 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001186
Dan Gohman4d8414f2009-06-13 16:25:49 +00001187 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001188 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001189 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001190}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001191
Dan Gohman890f92b2009-04-18 17:56:28 +00001192Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001193 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001194 Value *V = expandCodeFor(S->getOperand(),
1195 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001196 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001197 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001198 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001199}
1200
Dan Gohman890f92b2009-04-18 17:56:28 +00001201Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001202 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001203 Value *V = expandCodeFor(S->getOperand(),
1204 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001205 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001206 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001207 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001208}
1209
Dan Gohman890f92b2009-04-18 17:56:28 +00001210Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001211 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001212 Value *V = expandCodeFor(S->getOperand(),
1213 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001214 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001215 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001216 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001217}
1218
Dan Gohman890f92b2009-04-18 17:56:28 +00001219Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001220 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1221 const Type *Ty = LHS->getType();
1222 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1223 // In the case of mixed integer and pointer types, do the
1224 // rest of the comparisons as integer.
1225 if (S->getOperand(i)->getType() != Ty) {
1226 Ty = SE.getEffectiveSCEVType(Ty);
1227 LHS = InsertNoopCastOfTo(LHS, Ty);
1228 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001229 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001230 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001231 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001232 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001233 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001234 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001235 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001236 // In the case of mixed integer and pointer types, cast the
1237 // final result back to the pointer type.
1238 if (LHS->getType() != S->getType())
1239 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001240 return LHS;
1241}
1242
Dan Gohman890f92b2009-04-18 17:56:28 +00001243Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001244 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1245 const Type *Ty = LHS->getType();
1246 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1247 // In the case of mixed integer and pointer types, do the
1248 // rest of the comparisons as integer.
1249 if (S->getOperand(i)->getType() != Ty) {
1250 Ty = SE.getEffectiveSCEVType(Ty);
1251 LHS = InsertNoopCastOfTo(LHS, Ty);
1252 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001253 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001254 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001255 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001256 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001257 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001258 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001259 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001260 // In the case of mixed integer and pointer types, cast the
1261 // final result back to the pointer type.
1262 if (LHS->getType() != S->getType())
1263 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001264 return LHS;
1265}
1266
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001267Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
1268 Instruction *I) {
1269 BasicBlock::iterator IP = I;
1270 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1271 ++IP;
1272 Builder.SetInsertPoint(IP->getParent(), IP);
1273 return expandCodeFor(SH, Ty);
1274}
1275
Dan Gohman0bba49c2009-07-07 17:06:11 +00001276Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001277 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001278 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001279 if (Ty) {
1280 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1281 "non-trivial casts should be done with the SCEVs directly!");
1282 V = InsertNoopCastOfTo(V, Ty);
1283 }
1284 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001285}
1286
Dan Gohman890f92b2009-04-18 17:56:28 +00001287Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001288 // Compute an insertion point for this SCEV object. Hoist the instructions
1289 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001290 Instruction *InsertPt = Builder.GetInsertPoint();
1291 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001292 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001293 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001294 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001295 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001296 InsertPt = Preheader->getTerminator();
1297 } else {
1298 // If the SCEV is computable at this level, insert it into the header
1299 // after the PHIs (and after any other instructions that we've inserted
1300 // there) so that it is guaranteed to dominate any user inside the loop.
Dan Gohman17ead4f2010-11-17 21:23:15 +00001301 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001302 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001303 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001304 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001305 break;
1306 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001307
Dan Gohman667d7872009-06-26 22:53:46 +00001308 // Check to see if we already expanded this here.
1309 std::map<std::pair<const SCEV *, Instruction *>,
1310 AssertingVH<Value> >::iterator I =
1311 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001312 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001313 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001314
1315 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1316 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1317 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001318
1319 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001320 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001321
Dan Gohman667d7872009-06-26 22:53:46 +00001322 // Remember the expanded value for this SCEV at this location.
Dan Gohman448db1c2010-04-07 22:27:08 +00001323 if (PostIncLoops.empty())
Dan Gohmana10756e2010-01-21 02:09:26 +00001324 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001325
Dan Gohman45598552010-02-15 00:21:43 +00001326 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001327 return V;
1328}
Dan Gohman1d09de32009-06-05 16:35:53 +00001329
Dan Gohman1d826a72010-02-14 03:12:47 +00001330void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001331 if (!PostIncLoops.empty())
1332 InsertedPostIncValues.insert(I);
1333 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001334 InsertedValues.insert(I);
1335
1336 // If we just claimed an existing instruction and that instruction had
1337 // been the insert point, adjust the insert point forward so that
1338 // subsequently inserted code will be dominated.
1339 if (Builder.GetInsertPoint() == I) {
1340 BasicBlock::iterator It = cast<Instruction>(I);
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001341 do { ++It; } while (isInsertedInstruction(It) ||
1342 isa<DbgInfoIntrinsic>(It));
Dan Gohman1d826a72010-02-14 03:12:47 +00001343 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1344 }
1345}
1346
Dan Gohman45598552010-02-15 00:21:43 +00001347void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001348 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001349 // advance past them.
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001350 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
Dan Gohman45598552010-02-15 00:21:43 +00001351
1352 Builder.SetInsertPoint(BB, I);
1353}
1354
Dan Gohman1d09de32009-06-05 16:35:53 +00001355/// getOrInsertCanonicalInductionVariable - This method returns the
1356/// canonical induction variable of the specified type for the specified
1357/// loop (inserting one if there is none). A canonical induction variable
1358/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001359PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001360SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1361 const Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001362 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001363
1364 // Build a SCEV for {0,+,1}<L>.
Dan Gohmandeff6212010-05-03 22:09:21 +00001365 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1366 SE.getConstant(Ty, 1), L);
Dan Gohman133e2952010-07-20 16:46:58 +00001367
1368 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001369 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1370 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001371 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001372 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001373 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001374
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001375 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001376}