blob: 0f2a634a20684ae05839c0a6e75d1a8a50bb005b [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"
Andrew Trickee98aa82012-01-07 01:12:09 +000022#include "llvm/Target/TargetLowering.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000023#include "llvm/ADT/STLExtras.h"
Andrew Trickd152d032011-07-16 00:59:39 +000024
Nate Begeman36f891b2005-07-30 00:12:19 +000025using namespace llvm;
26
Gabor Greif19e5ada2010-07-09 16:42:04 +000027/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohman485c43f2010-06-19 13:25:23 +000028/// reusing an existing cast if a suitable one exists, moving an existing
29/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif19e5ada2010-07-09 16:42:04 +000030/// creating a new one.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000031Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohman485c43f2010-06-19 13:25:23 +000032 Instruction::CastOps Op,
33 BasicBlock::iterator IP) {
Rafael Espindola4b045782012-02-21 01:19:51 +000034 // All new or reused instructions must strictly dominate their uses.
35 // It would be nice to assert this here, but we don't always know where
36 // the next instructions will be added as the the caller can move the
37 // Builder's InsertPt before creating them and we might be called with
38 // an invalid InsertPt.
Rafael Espindolaef4c80e2012-02-18 17:22:58 +000039
Dan Gohman485c43f2010-06-19 13:25:23 +000040 // Check to see if there is already a cast!
41 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000042 UI != E; ++UI) {
43 User *U = *UI;
44 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000045 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000046 if (CI->getOpcode() == Op) {
Rafael Espindolaef4c80e2012-02-18 17:22:58 +000047 // If the cast isn't where we want it, fix it.
Rafael Espindola4b045782012-02-21 01:19:51 +000048 if (BasicBlock::iterator(CI) != IP) {
Dan Gohman485c43f2010-06-19 13:25:23 +000049 // Create a new cast, and leave the old cast in place in case
50 // it is being used as an insert point. Clear its operand
51 // so that it doesn't hold anything live.
52 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
53 NewCI->takeName(CI);
54 CI->replaceAllUsesWith(NewCI);
55 CI->setOperand(0, UndefValue::get(V->getType()));
56 rememberInstruction(NewCI);
57 return NewCI;
58 }
Dan Gohman6f5fed22010-06-19 22:50:35 +000059 rememberInstruction(CI);
Dan Gohman485c43f2010-06-19 13:25:23 +000060 return CI;
61 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000062 }
Dan Gohman485c43f2010-06-19 13:25:23 +000063
64 // Create a new cast.
65 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
66 rememberInstruction(I);
67 return I;
68}
69
Dan Gohman267a3852009-06-27 21:18:18 +000070/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
71/// which must be possible with a noop cast, doing what we can to share
72/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000073Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000074 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
75 assert((Op == Instruction::BitCast ||
76 Op == Instruction::PtrToInt ||
77 Op == Instruction::IntToPtr) &&
78 "InsertNoopCastOfTo cannot perform non-noop casts!");
79 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
80 "InsertNoopCastOfTo cannot change sizes!");
81
Dan Gohman2d1be872009-04-16 03:18:22 +000082 // Short-circuit unnecessary bitcasts.
Andrew Trick19154f42011-12-14 22:07:19 +000083 if (Op == Instruction::BitCast) {
84 if (V->getType() == Ty)
85 return V;
86 if (CastInst *CI = dyn_cast<CastInst>(V)) {
87 if (CI->getOperand(0)->getType() == Ty)
88 return CI->getOperand(0);
89 }
90 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000091 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000092 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000093 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000094 if (CastInst *CI = dyn_cast<CastInst>(V))
95 if ((CI->getOpcode() == Instruction::PtrToInt ||
96 CI->getOpcode() == Instruction::IntToPtr) &&
97 SE.getTypeSizeInBits(CI->getType()) ==
98 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
99 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +0000100 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
101 if ((CE->getOpcode() == Instruction::PtrToInt ||
102 CE->getOpcode() == Instruction::IntToPtr) &&
103 SE.getTypeSizeInBits(CE->getType()) ==
104 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
105 return CE->getOperand(0);
106 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000107
Dan Gohman485c43f2010-06-19 13:25:23 +0000108 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000109 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000110 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000111
Dan Gohman485c43f2010-06-19 13:25:23 +0000112 // Cast the argument at the beginning of the entry block, after
113 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000114 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000115 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
116 while ((isa<BitCastInst>(IP) &&
117 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
118 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000119 isa<DbgInfoIntrinsic>(IP) ||
120 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000121 ++IP;
122 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000123 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000124
Dan Gohman485c43f2010-06-19 13:25:23 +0000125 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000126 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000127 BasicBlock::iterator IP = I; ++IP;
128 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
129 IP = II->getNormalDest()->begin();
Rafael Espindolaef4c80e2012-02-18 17:22:58 +0000130 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000131 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000132 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000133}
134
Chris Lattner7fec90e2007-04-13 05:04:18 +0000135/// InsertBinop - Insert the specified binary operator, doing a small amount
136/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000137Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
138 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000139 // Fold a binop with constant operands.
140 if (Constant *CLHS = dyn_cast<Constant>(LHS))
141 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000142 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000143
Chris Lattner7fec90e2007-04-13 05:04:18 +0000144 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
145 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000146 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
147 // Scanning starts from the last instruction before the insertion point.
148 BasicBlock::iterator IP = Builder.GetInsertPoint();
149 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000150 --IP;
151 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000152 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
153 // generated code.
154 if (isa<DbgInfoIntrinsic>(IP))
155 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000156 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
157 IP->getOperand(1) == RHS)
158 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000159 if (IP == BlockBegin) break;
160 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000161 }
Dan Gohman267a3852009-06-27 21:18:18 +0000162
Dan Gohman087bd1e2010-03-03 05:29:13 +0000163 // Save the original insertion point so we can restore it when we're done.
164 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
165 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
166
167 // Move the insertion point out of as many loops as we can.
168 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
169 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
170 BasicBlock *Preheader = L->getLoopPreheader();
171 if (!Preheader) break;
172
173 // Ok, move up a level.
174 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
175 }
176
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000177 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000178 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Devang Pateldf3ad662011-06-22 20:56:56 +0000179 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000180 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000181
182 // Restore the original insert point.
183 if (SaveInsertBB)
184 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
185
Dan Gohmancf5ab822009-05-01 17:13:31 +0000186 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000187}
188
Dan Gohman4a4f7672009-05-27 02:00:53 +0000189/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000190/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000191/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000192/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000193/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
194/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
195/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000196static bool FactorOutConstant(const SCEV *&S,
197 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000198 const SCEV *Factor,
199 ScalarEvolution &SE,
200 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000201 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000202 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000203 return true;
204
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000205 // x/x == 1.
206 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000207 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000208 return true;
209 }
210
Dan Gohman453aa4f2009-05-24 18:06:31 +0000211 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000212 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000213 // 0/x == 0.
214 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000215 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000216 // Check for divisibility.
217 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
218 ConstantInt *CI =
219 ConstantInt::get(SE.getContext(),
220 C->getValue()->getValue().sdiv(
221 FC->getValue()->getValue()));
222 // If the quotient is zero and the remainder is non-zero, reject
223 // the value at this scale. It will be considered for subsequent
224 // smaller scales.
225 if (!CI->isZero()) {
226 const SCEV *Div = SE.getConstant(CI);
227 S = Div;
228 Remainder =
229 SE.getAddExpr(Remainder,
230 SE.getConstant(C->getValue()->getValue().srem(
231 FC->getValue()->getValue())));
232 return true;
233 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000234 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000235 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000236
237 // In a Mul, check if there is a constant operand which is a multiple
238 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000239 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
240 if (TD) {
241 // With TargetData, the size is known. Check if there is a constant
242 // operand which is a multiple of the given factor. If so, we can
243 // factor it.
244 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
245 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
246 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000247 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000248 NewMulOps[0] =
249 SE.getConstant(C->getValue()->getValue().sdiv(
250 FC->getValue()->getValue()));
251 S = SE.getMulExpr(NewMulOps);
252 return true;
253 }
254 } else {
255 // Without TargetData, check if Factor can be factored out of any of the
256 // Mul's operands. If so, we can just remove it.
257 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
258 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000259 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000260 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
261 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000262 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000263 NewMulOps[i] = SOp;
264 S = SE.getMulExpr(NewMulOps);
265 return true;
266 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000267 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000268 }
269 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000270
271 // In an AddRec, check if both start and step are divisible.
272 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000273 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000274 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000275 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000276 return false;
277 if (!StepRem->isZero())
278 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000279 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000280 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000281 return false;
Andrew Trick3228cc22011-03-14 16:50:06 +0000282 // FIXME: can use A->getNoWrapFlags(FlagNW)
283 S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000284 return true;
285 }
286
287 return false;
288}
289
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000290/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
291/// is the number of SCEVAddRecExprs present, which are kept at the end of
292/// the list.
293///
294static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000295 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000296 ScalarEvolution &SE) {
297 unsigned NumAddRecs = 0;
298 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
299 ++NumAddRecs;
300 // Group Ops into non-addrecs and addrecs.
301 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
302 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
303 // Let ScalarEvolution sort and simplify the non-addrecs list.
304 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000305 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000306 SE.getAddExpr(NoAddRecs);
307 // If it returned an add, use the operands. Otherwise it simplified
308 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000309 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000310 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000311 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000312 else if (!Sum->isZero())
313 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000314 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000315 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000316}
317
318/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
319/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
320/// This helps expose more opportunities for folding parts of the expressions
321/// into GEP indices.
322///
323static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000324 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000325 ScalarEvolution &SE) {
326 // Find the addrecs.
327 SmallVector<const SCEV *, 8> AddRecs;
328 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
329 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
330 const SCEV *Start = A->getStart();
331 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000332 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000333 AddRecs.push_back(SE.getAddRecExpr(Zero,
334 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000335 A->getLoop(),
336 // FIXME: A->getNoWrapFlags(FlagNW)
337 SCEV::FlagAnyWrap));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000338 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
339 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000340 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000341 e += Add->getNumOperands();
342 } else {
343 Ops[i] = Start;
344 }
345 }
346 if (!AddRecs.empty()) {
347 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000348 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000349 // Resort the operand list, moving any constants to the front.
350 SimplifyAddOperands(Ops, Ty, SE);
351 }
352}
353
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000354/// expandAddToGEP - Expand an addition expression with a pointer type into
355/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
356/// BasicAliasAnalysis and other passes analyze the result. See the rules
357/// for getelementptr vs. inttoptr in
358/// http://llvm.org/docs/LangRef.html#pointeraliasing
359/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000360///
Dan Gohman3abf9052010-01-19 22:26:02 +0000361/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000362/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
363/// they may introduce pointer arithmetic which may not be safely converted
364/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000365///
366/// Design note: It might seem desirable for this function to be more
367/// loop-aware. If some of the indices are loop-invariant while others
368/// aren't, it might seem desirable to emit multiple GEPs, keeping the
369/// loop-invariant portions of the overall computation outside the loop.
370/// However, there are a few reasons this is not done here. Hoisting simple
371/// arithmetic is a low-level optimization that often isn't very
372/// important until late in the optimization process. In fact, passes
373/// like InstructionCombining will combine GEPs, even if it means
374/// pushing loop-invariant computation down into loops, so even if the
375/// GEPs were split here, the work would quickly be undone. The
376/// LoopStrengthReduction pass, which is usually run quite late (and
377/// after the last InstructionCombining pass), takes care of hoisting
378/// loop-invariant portions of expressions, after considering what
379/// can be folded using target addressing modes.
380///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000381Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
382 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000383 PointerType *PTy,
384 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000385 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000386 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000387 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000388 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000389 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000390
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000391 // Split AddRecs up into parts as either of the parts may be usable
392 // without the other.
393 SplitAddRecs(Ops, Ty, SE);
394
Bob Wilsoneb356992009-12-04 01:33:04 +0000395 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000396 // operands into GEP indices, at each level. The first index in a GEP
397 // indexes into the array implied by the pointer operand; the rest of
398 // the indices index into the element or field type selected by the
399 // preceding index.
400 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000401 // If the scale size is not 0, attempt to factor out a scale for
402 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000403 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000404 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000405 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000406 if (!ElSize->isZero()) {
407 SmallVector<const SCEV *, 8> NewOps;
408 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
409 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000410 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000411 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
412 // Op now has ElSize factored out.
413 ScaledOps.push_back(Op);
414 if (!Remainder->isZero())
415 NewOps.push_back(Remainder);
416 AnyNonZeroIndices = true;
417 } else {
418 // The operand was not divisible, so add it to the list of operands
419 // we'll scan next iteration.
420 NewOps.push_back(Ops[i]);
421 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000422 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000423 // If we made any changes, update Ops.
424 if (!ScaledOps.empty()) {
425 Ops = NewOps;
426 SimplifyAddOperands(Ops, Ty, SE);
427 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000428 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000429 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000430
431 // Record the scaled array index for this level of the type. If
432 // we didn't find any operands that could be factored, tentatively
433 // assume that element zero was selected (since the zero offset
434 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000435 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000436 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000437 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
438 GepIndices.push_back(Scaled);
439
440 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000441 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000442 bool FoundFieldNo = false;
443 // An empty struct has no fields.
444 if (STy->getNumElements() == 0) break;
445 if (SE.TD) {
446 // With TargetData, field offsets are known. See if a constant offset
447 // falls within any of the struct fields.
448 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000449 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
450 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
451 const StructLayout &SL = *SE.TD->getStructLayout(STy);
452 uint64_t FullOffset = C->getValue()->getZExtValue();
453 if (FullOffset < SL.getSizeInBytes()) {
454 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000455 GepIndices.push_back(
456 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000457 ElTy = STy->getTypeAtIndex(ElIdx);
458 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000459 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000460 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000461 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000462 }
463 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000464 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000465 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000466 // appropriate struct type.
467 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000468 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000469 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000470 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000471 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000472 GepIndices.push_back(FieldNo);
473 ElTy =
474 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000475 Ops[i] = SE.getConstant(Ty, 0);
476 AnyNonZeroIndices = true;
477 FoundFieldNo = true;
478 break;
479 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000480 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000481 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000482 // If no struct field offsets were found, tentatively assume that
483 // field zero was selected (since the zero offset would obviously
484 // be folded away).
485 if (!FoundFieldNo) {
486 ElTy = STy->getTypeAtIndex(0u);
487 GepIndices.push_back(
488 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
489 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000490 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000491
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000492 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000493 ElTy = ATy->getElementType();
494 else
495 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000496 }
497
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000498 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000499 // the base to i8* and do an ugly getelementptr with that. It's still
500 // better than ptrtoint+arithmetic+inttoptr at least.
501 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000502 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000503 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000504 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000505
Rafael Espindola705b48d2012-02-21 03:51:14 +0000506 assert(!isa<Instruction>(V) ||
507 SE.DT->properlyDominates(cast<Instruction>(V),
Rafael Espindola161fb5d2012-02-21 03:48:30 +0000508 Builder.GetInsertPoint()));
Rafael Espindola4b045782012-02-21 01:19:51 +0000509
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000510 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000511 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000512
513 // Fold a GEP with constant operands.
514 if (Constant *CLHS = dyn_cast<Constant>(V))
515 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000516 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000517
518 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
519 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000520 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
521 // Scanning starts from the last instruction before the insertion point.
522 BasicBlock::iterator IP = Builder.GetInsertPoint();
523 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000524 --IP;
525 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000526 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
527 // generated code.
528 if (isa<DbgInfoIntrinsic>(IP))
529 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000530 if (IP->getOpcode() == Instruction::GetElementPtr &&
531 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
532 return IP;
533 if (IP == BlockBegin) break;
534 }
535 }
536
Dan Gohman087bd1e2010-03-03 05:29:13 +0000537 // Save the original insertion point so we can restore it when we're done.
538 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
539 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
540
541 // Move the insertion point out of as many loops as we can.
542 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
543 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
544 BasicBlock *Preheader = L->getLoopPreheader();
545 if (!Preheader) break;
546
547 // Ok, move up a level.
548 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
549 }
550
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000551 // Emit a GEP.
552 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000553 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000554
555 // Restore the original insert point.
556 if (SaveInsertBB)
557 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
558
Dan Gohman5be18e82009-05-19 02:15:55 +0000559 return GEP;
560 }
561
Dan Gohman087bd1e2010-03-03 05:29:13 +0000562 // Save the original insertion point so we can restore it when we're done.
563 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
564 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
565
566 // Move the insertion point out of as many loops as we can.
567 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
568 if (!L->isLoopInvariant(V)) break;
569
570 bool AnyIndexNotLoopInvariant = false;
571 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
572 E = GepIndices.end(); I != E; ++I)
573 if (!L->isLoopInvariant(*I)) {
574 AnyIndexNotLoopInvariant = true;
575 break;
576 }
577 if (AnyIndexNotLoopInvariant)
578 break;
579
580 BasicBlock *Preheader = L->getLoopPreheader();
581 if (!Preheader) break;
582
583 // Ok, move up a level.
584 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
585 }
586
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000587 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
588 // because ScalarEvolution may have changed the address arithmetic to
589 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000590 Value *Casted = V;
591 if (V->getType() != PTy)
592 Casted = InsertNoopCastOfTo(Casted, PTy);
593 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000594 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000595 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000596 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000597 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000598
599 // Restore the original insert point.
600 if (SaveInsertBB)
601 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
602
Dan Gohman5be18e82009-05-19 02:15:55 +0000603 return expand(SE.getAddExpr(Ops));
604}
605
Dan Gohman087bd1e2010-03-03 05:29:13 +0000606/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
607/// SCEV expansion. If they are nested, this is the most nested. If they are
608/// neighboring, pick the later.
609static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
610 DominatorTree &DT) {
611 if (!A) return B;
612 if (!B) return A;
613 if (A->contains(B)) return B;
614 if (B->contains(A)) return A;
615 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
616 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
617 return A; // Arbitrarily break the tie.
618}
619
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000620/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000621/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000622const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
623 // Test whether we've already computed the most relevant loop for this SCEV.
624 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
625 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
626 if (!Pair.second)
627 return Pair.first->second;
628
Dan Gohman087bd1e2010-03-03 05:29:13 +0000629 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000630 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000631 return 0;
632 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
633 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000634 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
635 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000636 return 0;
637 }
638 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
639 const Loop *L = 0;
640 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
641 L = AR->getLoop();
642 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
643 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000644 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
645 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000646 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000647 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
648 const Loop *Result = getRelevantLoop(C->getOperand());
649 return RelevantLoops[C] = Result;
650 }
651 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
652 const Loop *Result =
653 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
654 getRelevantLoop(D->getRHS()),
655 *SE.DT);
656 return RelevantLoops[D] = Result;
657 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000658 llvm_unreachable("Unexpected SCEV type!");
659}
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.
Andrew Trickf8fd8412012-01-07 00:27:31 +0000683 if (LHS.second->isNonConstantNegative()) {
684 if (!RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000685 return false;
Andrew Trickf8fd8412012-01-07 00:27:31 +0000686 } else if (RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000687 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));
Andrew Trickf8fd8412012-01-07 00:27:31 +0000747 } else if (Op->isNonConstantNegative()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000748 // 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
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000878/// getIVIncOperand returns an induction variable increment's induction
879/// variable operand.
880///
881/// If allowScale is set, any type of GEP is allowed as long as the nonIV
882/// operands dominate InsertPos.
883///
884/// If allowScale is not set, ensure that a GEP increment conforms to one of the
885/// simple patterns generated by getAddRecExprPHILiterally and
886/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
887Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
888 Instruction *InsertPos,
889 bool allowScale) {
890 if (IncV == InsertPos)
891 return NULL;
892
893 switch (IncV->getOpcode()) {
894 default:
895 return NULL;
896 // Check for a simple Add/Sub or GEP of a loop invariant step.
897 case Instruction::Add:
898 case Instruction::Sub: {
899 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
900 if (!OInst || SE.DT->properlyDominates(OInst, InsertPos))
901 return dyn_cast<Instruction>(IncV->getOperand(0));
902 return NULL;
903 }
904 case Instruction::BitCast:
905 return dyn_cast<Instruction>(IncV->getOperand(0));
906 case Instruction::GetElementPtr:
907 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
908 I != E; ++I) {
909 if (isa<Constant>(*I))
910 continue;
911 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
912 if (!SE.DT->properlyDominates(OInst, InsertPos))
913 return NULL;
914 }
915 if (allowScale) {
916 // allow any kind of GEP as long as it can be hoisted.
917 continue;
918 }
919 // This must be a pointer addition of constants (pretty), which is already
920 // handled, or some number of address-size elements (ugly). Ugly geps
921 // have 2 operands. i1* is used by the expander to represent an
922 // address-size element.
923 if (IncV->getNumOperands() != 2)
924 return NULL;
925 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
926 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
927 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
928 return NULL;
929 break;
930 }
931 return dyn_cast<Instruction>(IncV->getOperand(0));
932 }
933}
934
935/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
936/// it available to other uses in this loop. Recursively hoist any operands,
937/// until we reach a value that dominates InsertPos.
938bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
939 if (SE.DT->properlyDominates(IncV, InsertPos))
940 return true;
941
942 // InsertPos must itself dominate IncV so that IncV's new position satisfies
943 // its existing users.
944 if (!SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
945 return false;
946
947 // Check that the chain of IV operands leading back to Phi can be hoisted.
948 SmallVector<Instruction*, 4> IVIncs;
949 for(;;) {
950 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
951 if (!Oper)
952 return false;
953 // IncV is safe to hoist.
954 IVIncs.push_back(IncV);
955 IncV = Oper;
956 if (SE.DT->properlyDominates(IncV, InsertPos))
957 break;
958 }
959 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
960 E = IVIncs.rend(); I != E; ++I) {
961 (*I)->moveBefore(InsertPos);
962 }
963 return true;
964}
965
Andrew Trickc5701912011-10-07 23:46:21 +0000966/// Determine if this cyclic phi is in a form that would have been generated by
967/// LSR. We don't care if the phi was actually expanded in this pass, as long
968/// as it is in a low-cost form, for example, no implied multiplication. This
969/// should match any patterns generated by getAddRecExprPHILiterally and
970/// expandAddtoGEP.
971bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +0000972 const Loop *L) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000973 for(Instruction *IVOper = IncV;
974 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
975 /*allowScale=*/false));) {
976 if (IVOper == PN)
977 return true;
Andrew Trickc5701912011-10-07 23:46:21 +0000978 }
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000979 return false;
Andrew Trickc5701912011-10-07 23:46:21 +0000980}
981
Andrew Trick553fe052011-11-30 06:07:54 +0000982/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
983/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
984/// need to materialize IV increments elsewhere to handle difficult situations.
985Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
986 Type *ExpandTy, Type *IntTy,
987 bool useSubtract) {
988 Value *IncV;
989 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
990 if (ExpandTy->isPointerTy()) {
991 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
992 // If the step isn't constant, don't use an implicitly scaled GEP, because
993 // that would require a multiply inside the loop.
994 if (!isa<ConstantInt>(StepV))
995 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
996 GEPPtrTy->getAddressSpace());
997 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
998 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
999 if (IncV->getType() != PN->getType()) {
1000 IncV = Builder.CreateBitCast(IncV, PN->getType());
1001 rememberInstruction(IncV);
1002 }
1003 } else {
1004 IncV = useSubtract ?
1005 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1006 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1007 rememberInstruction(IncV);
1008 }
1009 return IncV;
1010}
1011
Dan Gohmana10756e2010-01-21 02:09:26 +00001012/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1013/// the base addrec, which is the addrec without any non-loop-dominating
1014/// values, and return the PHI.
1015PHINode *
1016SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1017 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001018 Type *ExpandTy,
1019 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001020 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +00001021
Dan Gohmana10756e2010-01-21 02:09:26 +00001022 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +00001023 BasicBlock *LatchBlock = L->getLoopLatch();
1024 if (LatchBlock) {
1025 for (BasicBlock::iterator I = L->getHeader()->begin();
1026 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1027 if (!SE.isSCEVable(PN->getType()) ||
1028 (SE.getEffectiveSCEVType(PN->getType()) !=
1029 SE.getEffectiveSCEVType(Normalized->getType())) ||
1030 SE.getSCEV(PN) != Normalized)
1031 continue;
Dan Gohman22e62192010-02-16 00:20:08 +00001032
Andrew Trickc5701912011-10-07 23:46:21 +00001033 Instruction *IncV =
1034 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman22e62192010-02-16 00:20:08 +00001035
Andrew Trickc5701912011-10-07 23:46:21 +00001036 if (LSRMode) {
Andrew Trick365c9f12011-10-15 06:19:55 +00001037 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +00001038 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001039 if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1040 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001041 }
Andrew Trickc5701912011-10-07 23:46:21 +00001042 else {
1043 if (!isNormalAddRecExprPHI(PN, IncV, L))
1044 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001045 if (L == IVIncInsertLoop)
1046 do {
1047 if (SE.DT->dominates(IncV, IVIncInsertPos))
1048 break;
1049 // Make sure the increment is where we want it. But don't move it
1050 // down past a potential existing post-inc user.
1051 IncV->moveBefore(IVIncInsertPos);
1052 IVIncInsertPos = IncV;
1053 IncV = cast<Instruction>(IncV->getOperand(0));
1054 } while (IncV != PN);
Andrew Trickc5701912011-10-07 23:46:21 +00001055 }
1056 // Ok, the add recurrence looks usable.
1057 // Remember this PHI, even in post-inc mode.
1058 InsertedValues.insert(PN);
1059 // Remember the increment.
1060 rememberInstruction(IncV);
Andrew Trickc5701912011-10-07 23:46:21 +00001061 return PN;
1062 }
1063 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001064
1065 // Save the original insertion point so we can restore it when we're done.
1066 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1067 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1068
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001069 // Another AddRec may need to be recursively expanded below. For example, if
1070 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1071 // loop. Remove this loop from the PostIncLoops set before expanding such
1072 // AddRecs. Otherwise, we cannot find a valid position for the step
1073 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1074 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1075 // so it's not worth implementing SmallPtrSet::swap.
1076 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1077 PostIncLoops.clear();
1078
Dan Gohmana10756e2010-01-21 02:09:26 +00001079 // Expand code for the start value.
1080 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1081 L->getHeader()->begin());
1082
Andrew Trickd152d032011-07-16 00:59:39 +00001083 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001084 assert(!isa<Instruction>(StartV) ||
1085 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1086 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001087
Andrew Trick553fe052011-11-30 06:07:54 +00001088 // Expand code for the step value. Do this before creating the PHI so that PHI
1089 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001090 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001091 // If the stride is negative, insert a sub instead of an add for the increment
1092 // (unless it's a constant, because subtracts of constants are canonicalized
1093 // to adds).
Andrew Trickf8fd8412012-01-07 00:27:31 +00001094 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001095 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001096 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001097 // Expand the step somewhere that dominates the loop header.
Dan Gohmana10756e2010-01-21 02:09:26 +00001098 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1099
1100 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001101 BasicBlock *Header = L->getHeader();
1102 Builder.SetInsertPoint(Header, Header->begin());
1103 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001104 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001105 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001106 rememberInstruction(PN);
1107
1108 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001109 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001110 BasicBlock *Pred = *HPI;
1111
1112 // Add a start value.
1113 if (!L->contains(Pred)) {
1114 PN->addIncoming(StartV, Pred);
1115 continue;
1116 }
1117
Andrew Trick553fe052011-11-30 06:07:54 +00001118 // Create a step value and add it to the PHI.
1119 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1120 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001121 Instruction *InsertPos = L == IVIncInsertLoop ?
1122 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001123 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001124 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1125
Dan Gohmana10756e2010-01-21 02:09:26 +00001126 PN->addIncoming(IncV, Pred);
1127 }
1128
1129 // Restore the original insert point.
1130 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001131 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +00001132
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001133 // After expanding subexpressions, restore the PostIncLoops set so the caller
1134 // can ensure that IVIncrement dominates the current uses.
1135 PostIncLoops = SavedPostIncLoops;
1136
Dan Gohmana10756e2010-01-21 02:09:26 +00001137 // Remember this PHI, even in post-inc mode.
1138 InsertedValues.insert(PN);
1139
1140 return PN;
1141}
1142
1143Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001144 Type *STy = S->getType();
1145 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001146 const Loop *L = S->getLoop();
1147
1148 // Determine a normalized form of this expression, which is the expression
1149 // before any post-inc adjustment is made.
1150 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001151 if (PostIncLoops.count(L)) {
1152 PostIncLoopSet Loops;
1153 Loops.insert(L);
1154 Normalized =
1155 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1156 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001157 }
1158
1159 // Strip off any non-loop-dominating component from the addrec start.
1160 const SCEV *Start = Normalized->getStart();
1161 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001162 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001163 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001164 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001165 Normalized = cast<SCEVAddRecExpr>(
1166 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1167 Normalized->getLoop(),
1168 // FIXME: Normalized->getNoWrapFlags(FlagNW)
1169 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001170 }
1171
1172 // Strip off any non-loop-dominating component from the addrec step.
1173 const SCEV *Step = Normalized->getStepRecurrence(SE);
1174 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001175 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001176 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001177 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001178 Normalized =
1179 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
Andrew Trick3228cc22011-03-14 16:50:06 +00001180 Normalized->getLoop(),
1181 // FIXME: Normalized
1182 // ->getNoWrapFlags(FlagNW)
1183 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001184 }
1185
1186 // Expand the core addrec. If we need post-loop scaling, force it to
1187 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001188 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001189 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1190
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001191 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001192 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001193 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001194 Result = PN;
1195 else {
1196 // In PostInc mode, use the post-incremented value.
1197 BasicBlock *LatchBlock = L->getLoopLatch();
1198 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1199 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001200
1201 // For an expansion to use the postinc form, the client must call
1202 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1203 // or dominated by IVIncInsertPos.
Andrew Trick553fe052011-11-30 06:07:54 +00001204 if (isa<Instruction>(Result)
1205 && !SE.DT->dominates(cast<Instruction>(Result),
1206 Builder.GetInsertPoint())) {
1207 // The induction variable's postinc expansion does not dominate this use.
1208 // IVUsers tries to prevent this case, so it is rare. However, it can
1209 // happen when an IVUser outside the loop is not dominated by the latch
1210 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1211 // all cases. Consider a phi outide whose operand is replaced during
1212 // expansion with the value of the postinc user. Without fundamentally
1213 // changing the way postinc users are tracked, the only remedy is
1214 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1215 // but hopefully expandCodeFor handles that.
1216 bool useSubtract =
Andrew Trickf8fd8412012-01-07 00:27:31 +00001217 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001218 if (useSubtract)
1219 Step = SE.getNegativeSCEV(Step);
1220 // Expand the step somewhere that dominates the loop header.
1221 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1222 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1223 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1224 // Restore the insertion point to the place where the caller has
1225 // determined dominates all uses.
1226 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1227 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1228 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001229 }
1230
1231 // Re-apply any non-loop-dominating scale.
1232 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001233 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001234 Result = Builder.CreateMul(Result,
1235 expandCodeFor(PostLoopScale, IntTy));
1236 rememberInstruction(Result);
1237 }
1238
1239 // Re-apply any non-loop-dominating offset.
1240 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001241 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001242 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1243 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1244 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001245 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001246 Result = Builder.CreateAdd(Result,
1247 expandCodeFor(PostLoopOffset, IntTy));
1248 rememberInstruction(Result);
1249 }
1250 }
1251
1252 return Result;
1253}
1254
Dan Gohman890f92b2009-04-18 17:56:28 +00001255Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001256 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1257
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001258 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001259 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001260
Dan Gohman4d8414f2009-06-13 16:25:49 +00001261 // First check for an existing canonical IV in a suitable type.
1262 PHINode *CanonicalIV = 0;
1263 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001264 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001265 CanonicalIV = PN;
1266
1267 // Rewrite an AddRec in terms of the canonical induction variable, if
1268 // its type is more narrow.
1269 if (CanonicalIV &&
1270 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1271 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001272 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1273 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1274 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001275 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1276 // FIXME: S->getNoWrapFlags(FlagNW)
1277 SCEV::FlagAnyWrap));
Dan Gohman267a3852009-06-27 21:18:18 +00001278 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1279 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001280 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001281 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001282 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1283 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001284 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001285 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1286 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001287 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001288 return V;
1289 }
1290
Nate Begeman36f891b2005-07-30 00:12:19 +00001291 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001292 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001293 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001294 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001295 // FIXME: can use S->getNoWrapFlags()
1296 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001297
1298 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1299 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001300 const SCEV *Base = S->getStart();
1301 const SCEV *RestArray[1] = { Rest };
1302 // Dig into the expression to find the pointer base for a GEP.
1303 ExposePointerBase(Base, RestArray[0], SE);
1304 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001305 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001306 // Make sure the Base isn't something exotic, such as a multiplied
1307 // or divided pointer value. In those cases, the result type isn't
1308 // actually a pointer type.
1309 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1310 Value *StartV = expand(Base);
1311 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1312 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001313 }
1314 }
1315
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001316 // Just do a normal add. Pre-expand the operands to suppress folding.
1317 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1318 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001319 }
1320
Dan Gohman6ebfd722010-07-26 18:28:14 +00001321 // If we don't yet have a canonical IV, create one.
1322 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001323 // Create and insert the PHI node for the induction variable in the
1324 // specified loop.
1325 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001326 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001327 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1328 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001329 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001330
Owen Andersoneed707b2009-07-24 23:12:02 +00001331 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001332 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001333 BasicBlock *HP = *HPI;
1334 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001335 // Insert a unit add instruction right before the terminator
1336 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001337 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1338 "indvar.next",
1339 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001340 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001341 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001342 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001343 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001344 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001345 }
Gabor Greif76560182010-07-09 15:40:10 +00001346 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001347 }
1348
Dan Gohman6ebfd722010-07-26 18:28:14 +00001349 // {0,+,1} --> Insert a canonical induction variable into the loop!
1350 if (S->isAffine() && S->getOperand(1)->isOne()) {
1351 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1352 "IVs with types different from the canonical IV should "
1353 "already have been handled!");
1354 return CanonicalIV;
1355 }
1356
Dan Gohman4d8414f2009-06-13 16:25:49 +00001357 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001358
Chris Lattnerdf14a042005-10-30 06:24:33 +00001359 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001360 if (S->isAffine()) // {0,+,F} --> i*F
1361 return
1362 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001363 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001364 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001365 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001366 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001367
1368 // If this is a chain of recurrences, turn it into a closed form, using the
1369 // folders, then expandCodeFor the closed form. This allows the folders to
1370 // simplify the expression without having to build a bunch of special code
1371 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001372 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001373
Dan Gohman4d8414f2009-06-13 16:25:49 +00001374 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001375 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001376 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001377 if (isa<SCEVAddRecExpr>(Ext))
1378 NewS = Ext;
1379
Dan Gohman0bba49c2009-07-07 17:06:11 +00001380 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001381 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001382
Dan Gohman4d8414f2009-06-13 16:25:49 +00001383 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001384 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001385 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001386}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001387
Dan Gohman890f92b2009-04-18 17:56:28 +00001388Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001389 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001390 Value *V = expandCodeFor(S->getOperand(),
1391 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001392 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001393 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001394 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001395}
1396
Dan Gohman890f92b2009-04-18 17:56:28 +00001397Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001398 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001399 Value *V = expandCodeFor(S->getOperand(),
1400 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001401 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001402 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001403 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001404}
1405
Dan Gohman890f92b2009-04-18 17:56:28 +00001406Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001407 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001408 Value *V = expandCodeFor(S->getOperand(),
1409 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001410 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001411 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001412 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001413}
1414
Dan Gohman890f92b2009-04-18 17:56:28 +00001415Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001416 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001417 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001418 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1419 // In the case of mixed integer and pointer types, do the
1420 // rest of the comparisons as integer.
1421 if (S->getOperand(i)->getType() != Ty) {
1422 Ty = SE.getEffectiveSCEVType(Ty);
1423 LHS = InsertNoopCastOfTo(LHS, Ty);
1424 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001425 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001426 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001427 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001428 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001429 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001430 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001431 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001432 // In the case of mixed integer and pointer types, cast the
1433 // final result back to the pointer type.
1434 if (LHS->getType() != S->getType())
1435 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001436 return LHS;
1437}
1438
Dan Gohman890f92b2009-04-18 17:56:28 +00001439Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001440 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001441 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001442 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1443 // In the case of mixed integer and pointer types, do the
1444 // rest of the comparisons as integer.
1445 if (S->getOperand(i)->getType() != Ty) {
1446 Ty = SE.getEffectiveSCEVType(Ty);
1447 LHS = InsertNoopCastOfTo(LHS, Ty);
1448 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001449 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001450 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001451 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001452 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001453 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001454 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001455 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001456 // In the case of mixed integer and pointer types, cast the
1457 // final result back to the pointer type.
1458 if (LHS->getType() != S->getType())
1459 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001460 return LHS;
1461}
1462
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001463Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001464 Instruction *IP) {
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001465 Builder.SetInsertPoint(IP->getParent(), IP);
1466 return expandCodeFor(SH, Ty);
1467}
1468
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001469Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001470 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001471 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001472 if (Ty) {
1473 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1474 "non-trivial casts should be done with the SCEVs directly!");
1475 V = InsertNoopCastOfTo(V, Ty);
1476 }
1477 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001478}
1479
Dan Gohman890f92b2009-04-18 17:56:28 +00001480Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001481 // Compute an insertion point for this SCEV object. Hoist the instructions
1482 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001483 Instruction *InsertPt = Builder.GetInsertPoint();
1484 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001485 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001486 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001487 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001488 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001489 InsertPt = Preheader->getTerminator();
Andrew Trick0f8cd562012-01-02 21:25:10 +00001490 else {
1491 // LSR sets the insertion point for AddRec start/step values to the
1492 // block start to simplify value reuse, even though it's an invalid
1493 // position. SCEVExpander must correct for this in all cases.
1494 InsertPt = L->getHeader()->getFirstInsertionPt();
1495 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001496 } else {
1497 // If the SCEV is computable at this level, insert it into the header
1498 // after the PHIs (and after any other instructions that we've inserted
1499 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001500 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1501 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001502 while (InsertPt != Builder.GetInsertPoint()
1503 && (isInsertedInstruction(InsertPt)
1504 || isa<DbgInfoIntrinsic>(InsertPt))) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001505 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001506 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001507 break;
1508 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001509
Dan Gohman667d7872009-06-26 22:53:46 +00001510 // Check to see if we already expanded this here.
1511 std::map<std::pair<const SCEV *, Instruction *>,
1512 AssertingVH<Value> >::iterator I =
1513 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001514 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001515 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001516
1517 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1518 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1519 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001520
1521 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001522 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001523
Dan Gohman667d7872009-06-26 22:53:46 +00001524 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001525 //
1526 // This is independent of PostIncLoops. The mapped value simply materializes
1527 // the expression at this insertion point. If the mapped value happened to be
1528 // a postinc expansion, it could be reused by a non postinc user, but only if
1529 // its insertion point was already at the head of the loop.
1530 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001531
Dan Gohman45598552010-02-15 00:21:43 +00001532 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001533 return V;
1534}
Dan Gohman1d09de32009-06-05 16:35:53 +00001535
Dan Gohman1d826a72010-02-14 03:12:47 +00001536void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001537 if (!PostIncLoops.empty())
1538 InsertedPostIncValues.insert(I);
1539 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001540 InsertedValues.insert(I);
Dan Gohman1d826a72010-02-14 03:12:47 +00001541}
1542
Dan Gohman45598552010-02-15 00:21:43 +00001543void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman45598552010-02-15 00:21:43 +00001544 Builder.SetInsertPoint(BB, I);
1545}
1546
Dan Gohman1d09de32009-06-05 16:35:53 +00001547/// getOrInsertCanonicalInductionVariable - This method returns the
1548/// canonical induction variable of the specified type for the specified
1549/// loop (inserting one if there is none). A canonical induction variable
1550/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001551PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001552SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001553 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001554 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001555
1556 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001557 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001558 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001559 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001560
1561 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001562 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1563 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001564 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001565 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001566 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001567
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001568 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001569}
Andrew Trick20449412011-10-11 02:28:51 +00001570
Andrew Trick139f3332012-01-07 01:29:21 +00001571/// Sort values by integer width for replaceCongruentIVs.
1572static bool width_descending(Value *lhs, Value *rhs) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001573 // Put pointers at the back and make sure pointer < pointer = false.
1574 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1575 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1576 return rhs->getType()->getPrimitiveSizeInBits()
1577 < lhs->getType()->getPrimitiveSizeInBits();
1578}
1579
Andrew Trick20449412011-10-11 02:28:51 +00001580/// replaceCongruentIVs - Check for congruent phis in this loop header and
1581/// replace them with their most canonical representative. Return the number of
1582/// phis eliminated.
1583///
1584/// This does not depend on any SCEVExpander state but should be used in
1585/// the same context that SCEVExpander is used.
1586unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Andrew Trickee98aa82012-01-07 01:12:09 +00001587 SmallVectorImpl<WeakVH> &DeadInsts,
1588 const TargetLowering *TLI) {
1589 // Find integer phis in order of increasing width.
1590 SmallVector<PHINode*, 8> Phis;
1591 for (BasicBlock::iterator I = L->getHeader()->begin();
1592 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1593 Phis.push_back(Phi);
1594 }
1595 if (TLI)
1596 std::sort(Phis.begin(), Phis.end(), width_descending);
1597
Andrew Trick20449412011-10-11 02:28:51 +00001598 unsigned NumElim = 0;
1599 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trickee98aa82012-01-07 01:12:09 +00001600 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1601 // so narrow phis can reuse them.
1602 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1603 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1604 PHINode *Phi = *PIter;
1605
Andrew Trick20449412011-10-11 02:28:51 +00001606 if (!SE.isSCEVable(Phi->getType()))
1607 continue;
1608
1609 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1610 if (!OrigPhiRef) {
1611 OrigPhiRef = Phi;
Andrew Trickee98aa82012-01-07 01:12:09 +00001612 if (Phi->getType()->isIntegerTy() && TLI
1613 && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1614 // This phi can be freely truncated to the narrowest phi type. Map the
1615 // truncated expression to it so it will be reused for narrow types.
1616 const SCEV *TruncExpr =
1617 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1618 ExprToIVMap[TruncExpr] = Phi;
1619 }
Andrew Trick20449412011-10-11 02:28:51 +00001620 continue;
1621 }
1622
Andrew Trickee98aa82012-01-07 01:12:09 +00001623 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1624 // sense.
1625 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trick20449412011-10-11 02:28:51 +00001626 continue;
1627
1628 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1629 Instruction *OrigInc =
1630 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1631 Instruction *IsomorphicInc =
1632 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1633
Andrew Trickee98aa82012-01-07 01:12:09 +00001634 // If this phi has the same width but is more canonical, replace the
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001635 // original with it. As part of the "more canonical" determination,
1636 // respect a prior decision to use an IV chain.
Andrew Trickee98aa82012-01-07 01:12:09 +00001637 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001638 && !(ChainedPhis.count(Phi)
1639 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1640 && (ChainedPhis.count(Phi)
1641 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trick20449412011-10-11 02:28:51 +00001642 std::swap(OrigPhiRef, Phi);
1643 std::swap(OrigInc, IsomorphicInc);
1644 }
1645 // Replacing the congruent phi is sufficient because acyclic redundancy
1646 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1647 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trick139f3332012-01-07 01:29:21 +00001648 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1649 // common case of a single IV increment so that DeleteDeadPHIs can remove
1650 // cycles that had postinc uses.
Andrew Trickee98aa82012-01-07 01:12:09 +00001651 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1652 IsomorphicInc->getType());
1653 if (OrigInc != IsomorphicInc
Andrew Trick64925c52012-01-10 01:45:08 +00001654 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001655 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1656 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trick20449412011-10-11 02:28:51 +00001657 DEBUG_WITH_TYPE(DebugType, dbgs()
1658 << "INDVARS: Eliminated congruent iv.inc: "
1659 << *IsomorphicInc << '\n');
Andrew Trickee98aa82012-01-07 01:12:09 +00001660 Value *NewInc = OrigInc;
1661 if (OrigInc->getType() != IsomorphicInc->getType()) {
Andrew Trickdd1f22f2012-01-14 03:17:23 +00001662 Instruction *IP = isa<PHINode>(OrigInc)
1663 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1664 : OrigInc->getNextNode();
1665 IRBuilder<> Builder(IP);
Andrew Trickee98aa82012-01-07 01:12:09 +00001666 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1667 NewInc = Builder.
1668 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1669 }
1670 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trick20449412011-10-11 02:28:51 +00001671 DeadInsts.push_back(IsomorphicInc);
1672 }
1673 }
1674 DEBUG_WITH_TYPE(DebugType, dbgs()
1675 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1676 ++NumElim;
Andrew Trickee98aa82012-01-07 01:12:09 +00001677 Value *NewIV = OrigPhiRef;
1678 if (OrigPhiRef->getType() != Phi->getType()) {
1679 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1680 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1681 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1682 }
1683 Phi->replaceAllUsesWith(NewIV);
Andrew Trick20449412011-10-11 02:28:51 +00001684 DeadInsts.push_back(Phi);
1685 }
1686 return NumElim;
1687}