blob: 0f7475673a47ab6043555cc6736d5f399f999acb [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) {
34 // Check to see if there is already a cast!
35 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Gabor Greiff64f9cf2010-07-09 16:39:02 +000036 UI != E; ++UI) {
37 User *U = *UI;
38 if (U->getType() == Ty)
Gabor Greif19e5ada2010-07-09 16:42:04 +000039 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohman485c43f2010-06-19 13:25:23 +000040 if (CI->getOpcode() == Op) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +000041 // If the cast isn't where we want it, fix it. All new or reused
42 // instructions must strictly dominate the Builder's InsertPt to
43 // ensure that the expression's expansion dominates its uses.
44 if (BasicBlock::iterator(CI) != IP
45 || IP == Builder.GetInsertPoint()) {
Dan Gohman485c43f2010-06-19 13:25:23 +000046 // Create a new cast, and leave the old cast in place in case
47 // it is being used as an insert point. Clear its operand
48 // so that it doesn't hold anything live.
49 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
50 NewCI->takeName(CI);
51 CI->replaceAllUsesWith(NewCI);
52 CI->setOperand(0, UndefValue::get(V->getType()));
53 rememberInstruction(NewCI);
54 return NewCI;
55 }
Dan Gohman6f5fed22010-06-19 22:50:35 +000056 rememberInstruction(CI);
Dan Gohman485c43f2010-06-19 13:25:23 +000057 return CI;
58 }
Gabor Greiff64f9cf2010-07-09 16:39:02 +000059 }
Dan Gohman485c43f2010-06-19 13:25:23 +000060
61 // Create a new cast.
62 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
63 rememberInstruction(I);
64 return I;
65}
66
Dan Gohman267a3852009-06-27 21:18:18 +000067/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
68/// which must be possible with a noop cast, doing what we can to share
69/// the casts.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000070Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman267a3852009-06-27 21:18:18 +000071 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
72 assert((Op == Instruction::BitCast ||
73 Op == Instruction::PtrToInt ||
74 Op == Instruction::IntToPtr) &&
75 "InsertNoopCastOfTo cannot perform non-noop casts!");
76 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
77 "InsertNoopCastOfTo cannot change sizes!");
78
Dan Gohman2d1be872009-04-16 03:18:22 +000079 // Short-circuit unnecessary bitcasts.
Andrew Trick19154f42011-12-14 22:07:19 +000080 if (Op == Instruction::BitCast) {
81 if (V->getType() == Ty)
82 return V;
83 if (CastInst *CI = dyn_cast<CastInst>(V)) {
84 if (CI->getOperand(0)->getType() == Ty)
85 return CI->getOperand(0);
86 }
87 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000088 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000089 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000090 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000091 if (CastInst *CI = dyn_cast<CastInst>(V))
92 if ((CI->getOpcode() == Instruction::PtrToInt ||
93 CI->getOpcode() == Instruction::IntToPtr) &&
94 SE.getTypeSizeInBits(CI->getType()) ==
95 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
96 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000097 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
98 if ((CE->getOpcode() == Instruction::PtrToInt ||
99 CE->getOpcode() == Instruction::IntToPtr) &&
100 SE.getTypeSizeInBits(CE->getType()) ==
101 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
102 return CE->getOperand(0);
103 }
Dan Gohmanf04fa482009-04-16 15:52:57 +0000104
Dan Gohman485c43f2010-06-19 13:25:23 +0000105 // Fold a cast of a constant.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000106 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000107 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000108
Dan Gohman485c43f2010-06-19 13:25:23 +0000109 // Cast the argument at the beginning of the entry block, after
110 // any bitcasts of other arguments.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000111 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohman485c43f2010-06-19 13:25:23 +0000112 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
113 while ((isa<BitCastInst>(IP) &&
114 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
115 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000116 isa<DbgInfoIntrinsic>(IP) ||
117 isa<LandingPadInst>(IP))
Dan Gohman485c43f2010-06-19 13:25:23 +0000118 ++IP;
119 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000120 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000121
Dan Gohman485c43f2010-06-19 13:25:23 +0000122 // Cast the instruction immediately after the instruction.
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000123 Instruction *I = cast<Instruction>(V);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000124 BasicBlock::iterator IP = I; ++IP;
125 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
126 IP = II->getNormalDest()->begin();
Bill Wendlinga4c86ab2011-08-24 21:06:46 +0000127 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
128 isa<LandingPadInst>(IP))
129 ++IP;
Dan Gohman485c43f2010-06-19 13:25:23 +0000130 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000131}
132
Chris Lattner7fec90e2007-04-13 05:04:18 +0000133/// InsertBinop - Insert the specified binary operator, doing a small amount
134/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000135Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
136 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000137 // Fold a binop with constant operands.
138 if (Constant *CLHS = dyn_cast<Constant>(LHS))
139 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000140 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000141
Chris Lattner7fec90e2007-04-13 05:04:18 +0000142 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
143 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000144 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
145 // Scanning starts from the last instruction before the insertion point.
146 BasicBlock::iterator IP = Builder.GetInsertPoint();
147 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000148 --IP;
149 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000150 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
151 // generated code.
152 if (isa<DbgInfoIntrinsic>(IP))
153 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000154 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
155 IP->getOperand(1) == RHS)
156 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000157 if (IP == BlockBegin) break;
158 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000159 }
Dan Gohman267a3852009-06-27 21:18:18 +0000160
Dan Gohman087bd1e2010-03-03 05:29:13 +0000161 // Save the original insertion point so we can restore it when we're done.
162 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
163 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
164
165 // Move the insertion point out of as many loops as we can.
166 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
167 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
168 BasicBlock *Preheader = L->getLoopPreheader();
169 if (!Preheader) break;
170
171 // Ok, move up a level.
172 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
173 }
174
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000175 // If we haven't found this binop, insert it.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000176 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Devang Pateldf3ad662011-06-22 20:56:56 +0000177 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +0000178 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000179
180 // Restore the original insert point.
181 if (SaveInsertBB)
182 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
183
Dan Gohmancf5ab822009-05-01 17:13:31 +0000184 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000185}
186
Dan Gohman4a4f7672009-05-27 02:00:53 +0000187/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000188/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000189/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000190/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000191/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
192/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
193/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000194static bool FactorOutConstant(const SCEV *&S,
195 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000196 const SCEV *Factor,
197 ScalarEvolution &SE,
198 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000199 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000200 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000201 return true;
202
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000203 // x/x == 1.
204 if (S == Factor) {
Dan Gohmandeff6212010-05-03 22:09:21 +0000205 S = SE.getConstant(S->getType(), 1);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000206 return true;
207 }
208
Dan Gohman453aa4f2009-05-24 18:06:31 +0000209 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000210 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000211 // 0/x == 0.
212 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000213 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000214 // Check for divisibility.
215 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
216 ConstantInt *CI =
217 ConstantInt::get(SE.getContext(),
218 C->getValue()->getValue().sdiv(
219 FC->getValue()->getValue()));
220 // If the quotient is zero and the remainder is non-zero, reject
221 // the value at this scale. It will be considered for subsequent
222 // smaller scales.
223 if (!CI->isZero()) {
224 const SCEV *Div = SE.getConstant(CI);
225 S = Div;
226 Remainder =
227 SE.getAddExpr(Remainder,
228 SE.getConstant(C->getValue()->getValue().srem(
229 FC->getValue()->getValue())));
230 return true;
231 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000232 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000233 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000234
235 // In a Mul, check if there is a constant operand which is a multiple
236 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000237 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
238 if (TD) {
239 // With TargetData, the size is known. Check if there is a constant
240 // operand which is a multiple of the given factor. If so, we can
241 // factor it.
242 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
243 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
244 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000245 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000246 NewMulOps[0] =
247 SE.getConstant(C->getValue()->getValue().sdiv(
248 FC->getValue()->getValue()));
249 S = SE.getMulExpr(NewMulOps);
250 return true;
251 }
252 } else {
253 // Without TargetData, check if Factor can be factored out of any of the
254 // Mul's operands. If so, we can just remove it.
255 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
256 const SCEV *SOp = M->getOperand(i);
Dan Gohmandeff6212010-05-03 22:09:21 +0000257 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000258 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
259 Remainder->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +0000260 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000261 NewMulOps[i] = SOp;
262 S = SE.getMulExpr(NewMulOps);
263 return true;
264 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000265 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000266 }
267 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000268
269 // In an AddRec, check if both start and step are divisible.
270 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000271 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohmandeff6212010-05-03 22:09:21 +0000272 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000273 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000274 return false;
275 if (!StepRem->isZero())
276 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000277 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000278 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000279 return false;
Andrew Trick3228cc22011-03-14 16:50:06 +0000280 // FIXME: can use A->getNoWrapFlags(FlagNW)
281 S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +0000282 return true;
283 }
284
285 return false;
286}
287
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000288/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
289/// is the number of SCEVAddRecExprs present, which are kept at the end of
290/// the list.
291///
292static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000293 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000294 ScalarEvolution &SE) {
295 unsigned NumAddRecs = 0;
296 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
297 ++NumAddRecs;
298 // Group Ops into non-addrecs and addrecs.
299 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
300 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
301 // Let ScalarEvolution sort and simplify the non-addrecs list.
302 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohmandeff6212010-05-03 22:09:21 +0000303 SE.getConstant(Ty, 0) :
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000304 SE.getAddExpr(NoAddRecs);
305 // If it returned an add, use the operands. Otherwise it simplified
306 // the sum into a single value, so just use that.
Dan Gohmanf9e64722010-03-18 01:17:13 +0000307 Ops.clear();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000308 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohman403a8cd2010-06-21 19:47:52 +0000309 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanf9e64722010-03-18 01:17:13 +0000310 else if (!Sum->isZero())
311 Ops.push_back(Sum);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000312 // Then append the addrecs.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000313 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000314}
315
316/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
317/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
318/// This helps expose more opportunities for folding parts of the expressions
319/// into GEP indices.
320///
321static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000322 Type *Ty,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000323 ScalarEvolution &SE) {
324 // Find the addrecs.
325 SmallVector<const SCEV *, 8> AddRecs;
326 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
327 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
328 const SCEV *Start = A->getStart();
329 if (Start->isZero()) break;
Dan Gohmandeff6212010-05-03 22:09:21 +0000330 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000331 AddRecs.push_back(SE.getAddRecExpr(Zero,
332 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000333 A->getLoop(),
334 // FIXME: A->getNoWrapFlags(FlagNW)
335 SCEV::FlagAnyWrap));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000336 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
337 Ops[i] = Zero;
Dan Gohman403a8cd2010-06-21 19:47:52 +0000338 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000339 e += Add->getNumOperands();
340 } else {
341 Ops[i] = Start;
342 }
343 }
344 if (!AddRecs.empty()) {
345 // Add the addrecs onto the end of the list.
Dan Gohman403a8cd2010-06-21 19:47:52 +0000346 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000347 // Resort the operand list, moving any constants to the front.
348 SimplifyAddOperands(Ops, Ty, SE);
349 }
350}
351
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000352/// expandAddToGEP - Expand an addition expression with a pointer type into
353/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
354/// BasicAliasAnalysis and other passes analyze the result. See the rules
355/// for getelementptr vs. inttoptr in
356/// http://llvm.org/docs/LangRef.html#pointeraliasing
357/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000358///
Dan Gohman3abf9052010-01-19 22:26:02 +0000359/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000360/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
361/// they may introduce pointer arithmetic which may not be safely converted
362/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000363///
364/// Design note: It might seem desirable for this function to be more
365/// loop-aware. If some of the indices are loop-invariant while others
366/// aren't, it might seem desirable to emit multiple GEPs, keeping the
367/// loop-invariant portions of the overall computation outside the loop.
368/// However, there are a few reasons this is not done here. Hoisting simple
369/// arithmetic is a low-level optimization that often isn't very
370/// important until late in the optimization process. In fact, passes
371/// like InstructionCombining will combine GEPs, even if it means
372/// pushing loop-invariant computation down into loops, so even if the
373/// GEPs were split here, the work would quickly be undone. The
374/// LoopStrengthReduction pass, which is usually run quite late (and
375/// after the last InstructionCombining pass), takes care of hoisting
376/// loop-invariant portions of expressions, after considering what
377/// can be folded using target addressing modes.
378///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000379Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
380 const SCEV *const *op_end,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000381 PointerType *PTy,
382 Type *Ty,
Dan Gohman5be18e82009-05-19 02:15:55 +0000383 Value *V) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000384 Type *ElTy = PTy->getElementType();
Dan Gohman5be18e82009-05-19 02:15:55 +0000385 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000386 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000387 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000388
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000389 // Split AddRecs up into parts as either of the parts may be usable
390 // without the other.
391 SplitAddRecs(Ops, Ty, SE);
392
Bob Wilsoneb356992009-12-04 01:33:04 +0000393 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000394 // operands into GEP indices, at each level. The first index in a GEP
395 // indexes into the array implied by the pointer operand; the rest of
396 // the indices index into the element or field type selected by the
397 // preceding index.
398 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000399 // If the scale size is not 0, attempt to factor out a scale for
400 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000401 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000402 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000403 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000404 if (!ElSize->isZero()) {
405 SmallVector<const SCEV *, 8> NewOps;
406 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
407 const SCEV *Op = Ops[i];
Dan Gohmandeff6212010-05-03 22:09:21 +0000408 const SCEV *Remainder = SE.getConstant(Ty, 0);
Dan Gohman150dfa82010-01-28 06:32:46 +0000409 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
410 // Op now has ElSize factored out.
411 ScaledOps.push_back(Op);
412 if (!Remainder->isZero())
413 NewOps.push_back(Remainder);
414 AnyNonZeroIndices = true;
415 } else {
416 // The operand was not divisible, so add it to the list of operands
417 // we'll scan next iteration.
418 NewOps.push_back(Ops[i]);
419 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000420 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000421 // If we made any changes, update Ops.
422 if (!ScaledOps.empty()) {
423 Ops = NewOps;
424 SimplifyAddOperands(Ops, Ty, SE);
425 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000426 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000427 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000428
429 // Record the scaled array index for this level of the type. If
430 // we didn't find any operands that could be factored, tentatively
431 // assume that element zero was selected (since the zero offset
432 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000433 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000434 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000435 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
436 GepIndices.push_back(Scaled);
437
438 // Collect struct field index operands.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000439 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000440 bool FoundFieldNo = false;
441 // An empty struct has no fields.
442 if (STy->getNumElements() == 0) break;
443 if (SE.TD) {
444 // With TargetData, field offsets are known. See if a constant offset
445 // falls within any of the struct fields.
446 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000447 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
448 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
449 const StructLayout &SL = *SE.TD->getStructLayout(STy);
450 uint64_t FullOffset = C->getValue()->getZExtValue();
451 if (FullOffset < SL.getSizeInBytes()) {
452 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000453 GepIndices.push_back(
454 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000455 ElTy = STy->getTypeAtIndex(ElIdx);
456 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000457 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000458 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000459 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000460 }
461 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000462 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000463 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000464 // appropriate struct type.
465 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000466 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000467 Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000468 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000469 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000470 GepIndices.push_back(FieldNo);
471 ElTy =
472 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000473 Ops[i] = SE.getConstant(Ty, 0);
474 AnyNonZeroIndices = true;
475 FoundFieldNo = true;
476 break;
477 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000478 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000479 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000480 // If no struct field offsets were found, tentatively assume that
481 // field zero was selected (since the zero offset would obviously
482 // be folded away).
483 if (!FoundFieldNo) {
484 ElTy = STy->getTypeAtIndex(0u);
485 GepIndices.push_back(
486 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
487 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000488 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000489
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000490 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000491 ElTy = ATy->getElementType();
492 else
493 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000494 }
495
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000496 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000497 // the base to i8* and do an ugly getelementptr with that. It's still
498 // better than ptrtoint+arithmetic+inttoptr at least.
499 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000500 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000501 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000502 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000503
504 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000505 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000506
507 // Fold a GEP with constant operands.
508 if (Constant *CLHS = dyn_cast<Constant>(V))
509 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaddab3d292011-07-21 14:31:17 +0000510 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman5be18e82009-05-19 02:15:55 +0000511
512 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
513 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000514 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
515 // Scanning starts from the last instruction before the insertion point.
516 BasicBlock::iterator IP = Builder.GetInsertPoint();
517 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000518 --IP;
519 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesen8d50ea72010-03-05 21:12:40 +0000520 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
521 // generated code.
522 if (isa<DbgInfoIntrinsic>(IP))
523 ScanLimit++;
Dan Gohman5be18e82009-05-19 02:15:55 +0000524 if (IP->getOpcode() == Instruction::GetElementPtr &&
525 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
526 return IP;
527 if (IP == BlockBegin) break;
528 }
529 }
530
Dan Gohman087bd1e2010-03-03 05:29:13 +0000531 // Save the original insertion point so we can restore it when we're done.
532 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
533 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
534
535 // Move the insertion point out of as many loops as we can.
536 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
537 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
538 BasicBlock *Preheader = L->getLoopPreheader();
539 if (!Preheader) break;
540
541 // Ok, move up a level.
542 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
543 }
544
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000545 // Emit a GEP.
546 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000547 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000548
549 // Restore the original insert point.
550 if (SaveInsertBB)
551 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
552
Dan Gohman5be18e82009-05-19 02:15:55 +0000553 return GEP;
554 }
555
Dan Gohman087bd1e2010-03-03 05:29:13 +0000556 // Save the original insertion point so we can restore it when we're done.
557 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
558 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
559
560 // Move the insertion point out of as many loops as we can.
561 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
562 if (!L->isLoopInvariant(V)) break;
563
564 bool AnyIndexNotLoopInvariant = false;
565 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
566 E = GepIndices.end(); I != E; ++I)
567 if (!L->isLoopInvariant(*I)) {
568 AnyIndexNotLoopInvariant = true;
569 break;
570 }
571 if (AnyIndexNotLoopInvariant)
572 break;
573
574 BasicBlock *Preheader = L->getLoopPreheader();
575 if (!Preheader) break;
576
577 // Ok, move up a level.
578 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
579 }
580
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000581 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
582 // because ScalarEvolution may have changed the address arithmetic to
583 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000584 Value *Casted = V;
585 if (V->getType() != PTy)
586 Casted = InsertNoopCastOfTo(Casted, PTy);
587 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad0a2a60a2011-07-22 08:16:57 +0000588 GepIndices,
Dan Gohman267a3852009-06-27 21:18:18 +0000589 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000590 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000591 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000592
593 // Restore the original insert point.
594 if (SaveInsertBB)
595 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
596
Dan Gohman5be18e82009-05-19 02:15:55 +0000597 return expand(SE.getAddExpr(Ops));
598}
599
Dan Gohman087bd1e2010-03-03 05:29:13 +0000600/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
601/// SCEV expansion. If they are nested, this is the most nested. If they are
602/// neighboring, pick the later.
603static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
604 DominatorTree &DT) {
605 if (!A) return B;
606 if (!B) return A;
607 if (A->contains(B)) return B;
608 if (B->contains(A)) return A;
609 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
610 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
611 return A; // Arbitrarily break the tie.
612}
613
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000614/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman087bd1e2010-03-03 05:29:13 +0000615/// expression, according to PickMostRelevantLoop.
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000616const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
617 // Test whether we've already computed the most relevant loop for this SCEV.
618 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
619 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
620 if (!Pair.second)
621 return Pair.first->second;
622
Dan Gohman087bd1e2010-03-03 05:29:13 +0000623 if (isa<SCEVConstant>(S))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000624 // A constant has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000625 return 0;
626 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
627 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000628 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
629 // A non-instruction has no relevant loops.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000630 return 0;
631 }
632 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
633 const Loop *L = 0;
634 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
635 L = AR->getLoop();
636 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
637 I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000638 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
639 return RelevantLoops[N] = L;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000640 }
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000641 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
642 const Loop *Result = getRelevantLoop(C->getOperand());
643 return RelevantLoops[C] = Result;
644 }
645 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
646 const Loop *Result =
647 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
648 getRelevantLoop(D->getRHS()),
649 *SE.DT);
650 return RelevantLoops[D] = Result;
651 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000652 llvm_unreachable("Unexpected SCEV type!");
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000653 return 0;
Dan Gohman087bd1e2010-03-03 05:29:13 +0000654}
655
Dan Gohmanb3579832010-04-15 17:08:50 +0000656namespace {
657
Dan Gohman087bd1e2010-03-03 05:29:13 +0000658/// LoopCompare - Compare loops by PickMostRelevantLoop.
659class LoopCompare {
660 DominatorTree &DT;
661public:
662 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
663
664 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
665 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000666 // Keep pointer operands sorted at the end.
667 if (LHS.second->getType()->isPointerTy() !=
668 RHS.second->getType()->isPointerTy())
669 return LHS.second->getType()->isPointerTy();
670
Dan Gohman087bd1e2010-03-03 05:29:13 +0000671 // Compare loops with PickMostRelevantLoop.
672 if (LHS.first != RHS.first)
673 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
674
675 // If one operand is a non-constant negative and the other is not,
676 // put the non-constant negative on the right so that a sub can
677 // be used instead of a negate and add.
Andrew Trickf8fd8412012-01-07 00:27:31 +0000678 if (LHS.second->isNonConstantNegative()) {
679 if (!RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000680 return false;
Andrew Trickf8fd8412012-01-07 00:27:31 +0000681 } else if (RHS.second->isNonConstantNegative())
Dan Gohman087bd1e2010-03-03 05:29:13 +0000682 return true;
683
684 // Otherwise they are equivalent according to this comparison.
685 return false;
686 }
687};
688
Dan Gohmanb3579832010-04-15 17:08:50 +0000689}
690
Dan Gohman890f92b2009-04-18 17:56:28 +0000691Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000692 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000693
Dan Gohman087bd1e2010-03-03 05:29:13 +0000694 // Collect all the add operands in a loop, along with their associated loops.
695 // Iterate in reverse so that constants are emitted last, all else equal, and
696 // so that pointer operands are inserted first, which the code below relies on
697 // to form more involved GEPs.
698 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
699 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
700 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000701 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000702
Dan Gohman087bd1e2010-03-03 05:29:13 +0000703 // Sort by loop. Use a stable sort so that constants follow non-constants and
704 // pointer operands precede non-pointer operands.
705 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000706
Dan Gohman087bd1e2010-03-03 05:29:13 +0000707 // Emit instructions to add all the operands. Hoist as much as possible
708 // out of loops, and form meaningful getelementptrs where possible.
709 Value *Sum = 0;
710 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
711 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
712 const Loop *CurLoop = I->first;
713 const SCEV *Op = I->second;
714 if (!Sum) {
715 // This is the first operand. Just expand it.
716 Sum = expand(Op);
717 ++I;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000718 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000719 // The running sum expression is a pointer. Try to form a getelementptr
720 // at this level with that as the base.
721 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanbb5d9272010-07-15 23:38:13 +0000722 for (; I != E && I->first == CurLoop; ++I) {
723 // If the operand is SCEVUnknown and not instructions, peek through
724 // it, to enable more of it to be folded into the GEP.
725 const SCEV *X = I->second;
726 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
727 if (!isa<Instruction>(U->getValue()))
728 X = SE.getSCEV(U->getValue());
729 NewOps.push_back(X);
730 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000731 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000732 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000733 // The running sum is an integer, and there's a pointer at this level.
Dan Gohmanf8d05782010-04-09 19:14:31 +0000734 // Try to form a getelementptr. If the running sum is instructions,
735 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman087bd1e2010-03-03 05:29:13 +0000736 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanf8d05782010-04-09 19:14:31 +0000737 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
738 SE.getSCEV(Sum));
Dan Gohman087bd1e2010-03-03 05:29:13 +0000739 for (++I; I != E && I->first == CurLoop; ++I)
740 NewOps.push_back(I->second);
741 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trickf8fd8412012-01-07 00:27:31 +0000742 } else if (Op->isNonConstantNegative()) {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000743 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000744 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000745 Sum = InsertNoopCastOfTo(Sum, Ty);
746 Sum = InsertBinop(Instruction::Sub, Sum, W);
747 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000748 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000749 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000750 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000751 Sum = InsertNoopCastOfTo(Sum, Ty);
752 // Canonicalize a constant to the RHS.
753 if (isa<Constant>(Sum)) std::swap(Sum, W);
754 Sum = InsertBinop(Instruction::Add, Sum, W);
755 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000756 }
757 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000758
759 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000760}
Dan Gohman5be18e82009-05-19 02:15:55 +0000761
Dan Gohman890f92b2009-04-18 17:56:28 +0000762Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000763 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000764
Dan Gohman087bd1e2010-03-03 05:29:13 +0000765 // Collect all the mul operands in a loop, along with their associated loops.
766 // Iterate in reverse so that constants are emitted last, all else equal.
767 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
768 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
769 E(S->op_begin()); I != E; ++I)
Dan Gohman9c9fcfc2010-11-18 00:34:22 +0000770 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000771
Dan Gohman087bd1e2010-03-03 05:29:13 +0000772 // Sort by loop. Use a stable sort so that constants follow non-constants.
773 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
774
775 // Emit instructions to mul all the operands. Hoist as much as possible
776 // out of loops.
777 Value *Prod = 0;
778 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
779 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
780 const SCEV *Op = I->second;
781 if (!Prod) {
782 // This is the first operand. Just expand it.
783 Prod = expand(Op);
784 ++I;
785 } else if (Op->isAllOnesValue()) {
786 // Instead of doing a multiply by negative one, just do a negate.
787 Prod = InsertNoopCastOfTo(Prod, Ty);
788 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
789 ++I;
790 } else {
791 // A simple mul.
792 Value *W = expandCodeFor(Op, Ty);
793 Prod = InsertNoopCastOfTo(Prod, Ty);
794 // Canonicalize a constant to the RHS.
795 if (isa<Constant>(Prod)) std::swap(Prod, W);
796 Prod = InsertBinop(Instruction::Mul, Prod, W);
797 ++I;
798 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000799 }
800
Dan Gohman087bd1e2010-03-03 05:29:13 +0000801 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000802}
803
Dan Gohman890f92b2009-04-18 17:56:28 +0000804Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000805 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000806
Dan Gohman92fcdca2009-06-09 17:18:38 +0000807 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000808 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000809 const APInt &RHS = SC->getValue()->getValue();
810 if (RHS.isPowerOf2())
811 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000812 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000813 }
814
Dan Gohman92fcdca2009-06-09 17:18:38 +0000815 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000816 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000817}
818
Dan Gohman453aa4f2009-05-24 18:06:31 +0000819/// Move parts of Base into Rest to leave Base with the minimal
820/// expression that provides a pointer operand suitable for a
821/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000822static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000823 ScalarEvolution &SE) {
824 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
825 Base = A->getStart();
826 Rest = SE.getAddExpr(Rest,
Dan Gohmandeff6212010-05-03 22:09:21 +0000827 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman453aa4f2009-05-24 18:06:31 +0000828 A->getStepRecurrence(SE),
Andrew Trick3228cc22011-03-14 16:50:06 +0000829 A->getLoop(),
830 // FIXME: A->getNoWrapFlags(FlagNW)
831 SCEV::FlagAnyWrap));
Dan Gohman453aa4f2009-05-24 18:06:31 +0000832 }
833 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
834 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000835 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000836 NewAddOps.back() = Rest;
837 Rest = SE.getAddExpr(NewAddOps);
838 ExposePointerBase(Base, Rest, SE);
839 }
840}
841
Andrew Trickc5701912011-10-07 23:46:21 +0000842/// Determine if this is a well-behaved chain of instructions leading back to
843/// the PHI. If so, it may be reused by expanded expressions.
844bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
845 const Loop *L) {
846 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
847 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
848 return false;
849 // If any of the operands don't dominate the insert position, bail.
850 // Addrec operands are always loop-invariant, so this can only happen
851 // if there are instructions which haven't been hoisted.
852 if (L == IVIncInsertLoop) {
853 for (User::op_iterator OI = IncV->op_begin()+1,
854 OE = IncV->op_end(); OI != OE; ++OI)
855 if (Instruction *OInst = dyn_cast<Instruction>(OI))
856 if (!SE.DT->dominates(OInst, IVIncInsertPos))
857 return false;
858 }
859 // Advance to the next instruction.
860 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
861 if (!IncV)
862 return false;
863
864 if (IncV->mayHaveSideEffects())
865 return false;
866
867 if (IncV != PN)
868 return true;
869
870 return isNormalAddRecExprPHI(PN, IncV, L);
871}
872
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000873/// getIVIncOperand returns an induction variable increment's induction
874/// variable operand.
875///
876/// If allowScale is set, any type of GEP is allowed as long as the nonIV
877/// operands dominate InsertPos.
878///
879/// If allowScale is not set, ensure that a GEP increment conforms to one of the
880/// simple patterns generated by getAddRecExprPHILiterally and
881/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
882Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
883 Instruction *InsertPos,
884 bool allowScale) {
885 if (IncV == InsertPos)
886 return NULL;
887
888 switch (IncV->getOpcode()) {
889 default:
890 return NULL;
891 // Check for a simple Add/Sub or GEP of a loop invariant step.
892 case Instruction::Add:
893 case Instruction::Sub: {
894 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
895 if (!OInst || SE.DT->properlyDominates(OInst, InsertPos))
896 return dyn_cast<Instruction>(IncV->getOperand(0));
897 return NULL;
898 }
899 case Instruction::BitCast:
900 return dyn_cast<Instruction>(IncV->getOperand(0));
901 case Instruction::GetElementPtr:
902 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
903 I != E; ++I) {
904 if (isa<Constant>(*I))
905 continue;
906 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
907 if (!SE.DT->properlyDominates(OInst, InsertPos))
908 return NULL;
909 }
910 if (allowScale) {
911 // allow any kind of GEP as long as it can be hoisted.
912 continue;
913 }
914 // This must be a pointer addition of constants (pretty), which is already
915 // handled, or some number of address-size elements (ugly). Ugly geps
916 // have 2 operands. i1* is used by the expander to represent an
917 // address-size element.
918 if (IncV->getNumOperands() != 2)
919 return NULL;
920 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
921 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
922 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
923 return NULL;
924 break;
925 }
926 return dyn_cast<Instruction>(IncV->getOperand(0));
927 }
928}
929
930/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
931/// it available to other uses in this loop. Recursively hoist any operands,
932/// until we reach a value that dominates InsertPos.
933bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
934 if (SE.DT->properlyDominates(IncV, InsertPos))
935 return true;
936
937 // InsertPos must itself dominate IncV so that IncV's new position satisfies
938 // its existing users.
939 if (!SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
940 return false;
941
942 // Check that the chain of IV operands leading back to Phi can be hoisted.
943 SmallVector<Instruction*, 4> IVIncs;
944 for(;;) {
945 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
946 if (!Oper)
947 return false;
948 // IncV is safe to hoist.
949 IVIncs.push_back(IncV);
950 IncV = Oper;
951 if (SE.DT->properlyDominates(IncV, InsertPos))
952 break;
953 }
954 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
955 E = IVIncs.rend(); I != E; ++I) {
956 (*I)->moveBefore(InsertPos);
957 }
958 return true;
959}
960
Andrew Trickc5701912011-10-07 23:46:21 +0000961/// Determine if this cyclic phi is in a form that would have been generated by
962/// LSR. We don't care if the phi was actually expanded in this pass, as long
963/// as it is in a low-cost form, for example, no implied multiplication. This
964/// should match any patterns generated by getAddRecExprPHILiterally and
965/// expandAddtoGEP.
966bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trick365c9f12011-10-15 06:19:55 +0000967 const Loop *L) {
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000968 for(Instruction *IVOper = IncV;
969 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
970 /*allowScale=*/false));) {
971 if (IVOper == PN)
972 return true;
Andrew Trickc5701912011-10-07 23:46:21 +0000973 }
Andrew Trickb5c26ef2012-01-20 07:41:13 +0000974 return false;
Andrew Trickc5701912011-10-07 23:46:21 +0000975}
976
Andrew Trick553fe052011-11-30 06:07:54 +0000977/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
978/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
979/// need to materialize IV increments elsewhere to handle difficult situations.
980Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
981 Type *ExpandTy, Type *IntTy,
982 bool useSubtract) {
983 Value *IncV;
984 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
985 if (ExpandTy->isPointerTy()) {
986 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
987 // If the step isn't constant, don't use an implicitly scaled GEP, because
988 // that would require a multiply inside the loop.
989 if (!isa<ConstantInt>(StepV))
990 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
991 GEPPtrTy->getAddressSpace());
992 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
993 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
994 if (IncV->getType() != PN->getType()) {
995 IncV = Builder.CreateBitCast(IncV, PN->getType());
996 rememberInstruction(IncV);
997 }
998 } else {
999 IncV = useSubtract ?
1000 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1001 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1002 rememberInstruction(IncV);
1003 }
1004 return IncV;
1005}
1006
Dan Gohmana10756e2010-01-21 02:09:26 +00001007/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1008/// the base addrec, which is the addrec without any non-loop-dominating
1009/// values, and return the PHI.
1010PHINode *
1011SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1012 const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001013 Type *ExpandTy,
1014 Type *IntTy) {
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001015 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trickd152d032011-07-16 00:59:39 +00001016
Dan Gohmana10756e2010-01-21 02:09:26 +00001017 // Reuse a previously-inserted PHI, if present.
Andrew Trickc5701912011-10-07 23:46:21 +00001018 BasicBlock *LatchBlock = L->getLoopLatch();
1019 if (LatchBlock) {
1020 for (BasicBlock::iterator I = L->getHeader()->begin();
1021 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1022 if (!SE.isSCEVable(PN->getType()) ||
1023 (SE.getEffectiveSCEVType(PN->getType()) !=
1024 SE.getEffectiveSCEVType(Normalized->getType())) ||
1025 SE.getSCEV(PN) != Normalized)
1026 continue;
Dan Gohman22e62192010-02-16 00:20:08 +00001027
Andrew Trickc5701912011-10-07 23:46:21 +00001028 Instruction *IncV =
1029 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
Dan Gohman22e62192010-02-16 00:20:08 +00001030
Andrew Trickc5701912011-10-07 23:46:21 +00001031 if (LSRMode) {
Andrew Trick365c9f12011-10-15 06:19:55 +00001032 if (!isExpandedAddRecExprPHI(PN, IncV, L))
Andrew Trickc5701912011-10-07 23:46:21 +00001033 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001034 if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1035 continue;
Dan Gohman572645c2010-02-12 10:34:29 +00001036 }
Andrew Trickc5701912011-10-07 23:46:21 +00001037 else {
1038 if (!isNormalAddRecExprPHI(PN, IncV, L))
1039 continue;
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001040 if (L == IVIncInsertLoop)
1041 do {
1042 if (SE.DT->dominates(IncV, IVIncInsertPos))
1043 break;
1044 // Make sure the increment is where we want it. But don't move it
1045 // down past a potential existing post-inc user.
1046 IncV->moveBefore(IVIncInsertPos);
1047 IVIncInsertPos = IncV;
1048 IncV = cast<Instruction>(IncV->getOperand(0));
1049 } while (IncV != PN);
Andrew Trickc5701912011-10-07 23:46:21 +00001050 }
1051 // Ok, the add recurrence looks usable.
1052 // Remember this PHI, even in post-inc mode.
1053 InsertedValues.insert(PN);
1054 // Remember the increment.
1055 rememberInstruction(IncV);
Andrew Trickc5701912011-10-07 23:46:21 +00001056 return PN;
1057 }
1058 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001059
1060 // Save the original insertion point so we can restore it when we're done.
1061 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1062 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1063
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001064 // Another AddRec may need to be recursively expanded below. For example, if
1065 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1066 // loop. Remove this loop from the PostIncLoops set before expanding such
1067 // AddRecs. Otherwise, we cannot find a valid position for the step
1068 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1069 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1070 // so it's not worth implementing SmallPtrSet::swap.
1071 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1072 PostIncLoops.clear();
1073
Dan Gohmana10756e2010-01-21 02:09:26 +00001074 // Expand code for the start value.
1075 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1076 L->getHeader()->begin());
1077
Andrew Trickd152d032011-07-16 00:59:39 +00001078 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramer93a896e2011-07-16 22:26:27 +00001079 assert(!isa<Instruction>(StartV) ||
1080 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1081 L->getHeader()));
Andrew Trickd152d032011-07-16 00:59:39 +00001082
Andrew Trick553fe052011-11-30 06:07:54 +00001083 // Expand code for the step value. Do this before creating the PHI so that PHI
1084 // reuse code doesn't see an incomplete PHI.
Dan Gohmana10756e2010-01-21 02:09:26 +00001085 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trick553fe052011-11-30 06:07:54 +00001086 // If the stride is negative, insert a sub instead of an add for the increment
1087 // (unless it's a constant, because subtracts of constants are canonicalized
1088 // to adds).
Andrew Trickf8fd8412012-01-07 00:27:31 +00001089 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001090 if (useSubtract)
Dan Gohmana10756e2010-01-21 02:09:26 +00001091 Step = SE.getNegativeSCEV(Step);
Andrew Trick553fe052011-11-30 06:07:54 +00001092 // Expand the step somewhere that dominates the loop header.
Dan Gohmana10756e2010-01-21 02:09:26 +00001093 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1094
1095 // Create the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001096 BasicBlock *Header = L->getHeader();
1097 Builder.SetInsertPoint(Header, Header->begin());
1098 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick5e7645b2011-06-28 05:07:32 +00001099 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trickdc8e5462011-06-28 05:41:52 +00001100 Twine(IVName) + ".iv");
Dan Gohmana10756e2010-01-21 02:09:26 +00001101 rememberInstruction(PN);
1102
1103 // Create the step instructions and populate the PHI.
Jay Foadd8b4fb42011-03-30 11:19:20 +00001104 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001105 BasicBlock *Pred = *HPI;
1106
1107 // Add a start value.
1108 if (!L->contains(Pred)) {
1109 PN->addIncoming(StartV, Pred);
1110 continue;
1111 }
1112
Andrew Trick553fe052011-11-30 06:07:54 +00001113 // Create a step value and add it to the PHI.
1114 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1115 // instructions at IVIncInsertPos.
Dan Gohmana10756e2010-01-21 02:09:26 +00001116 Instruction *InsertPos = L == IVIncInsertLoop ?
1117 IVIncInsertPos : Pred->getTerminator();
Devang Patelc5ecbdc2011-07-05 21:48:22 +00001118 Builder.SetInsertPoint(InsertPos);
Andrew Trick553fe052011-11-30 06:07:54 +00001119 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1120
Dan Gohmana10756e2010-01-21 02:09:26 +00001121 PN->addIncoming(IncV, Pred);
1122 }
1123
1124 // Restore the original insert point.
1125 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001126 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +00001127
Andrew Trickba3c0bc2011-12-20 01:42:24 +00001128 // After expanding subexpressions, restore the PostIncLoops set so the caller
1129 // can ensure that IVIncrement dominates the current uses.
1130 PostIncLoops = SavedPostIncLoops;
1131
Dan Gohmana10756e2010-01-21 02:09:26 +00001132 // Remember this PHI, even in post-inc mode.
1133 InsertedValues.insert(PN);
1134
1135 return PN;
1136}
1137
1138Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001139 Type *STy = S->getType();
1140 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001141 const Loop *L = S->getLoop();
1142
1143 // Determine a normalized form of this expression, which is the expression
1144 // before any post-inc adjustment is made.
1145 const SCEVAddRecExpr *Normalized = S;
Dan Gohman448db1c2010-04-07 22:27:08 +00001146 if (PostIncLoops.count(L)) {
1147 PostIncLoopSet Loops;
1148 Loops.insert(L);
1149 Normalized =
1150 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1151 Loops, SE, *SE.DT));
Dan Gohmana10756e2010-01-21 02:09:26 +00001152 }
1153
1154 // Strip off any non-loop-dominating component from the addrec start.
1155 const SCEV *Start = Normalized->getStart();
1156 const SCEV *PostLoopOffset = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001157 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001158 PostLoopOffset = Start;
Dan Gohmandeff6212010-05-03 22:09:21 +00001159 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001160 Normalized = cast<SCEVAddRecExpr>(
1161 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1162 Normalized->getLoop(),
1163 // FIXME: Normalized->getNoWrapFlags(FlagNW)
1164 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001165 }
1166
1167 // Strip off any non-loop-dominating component from the addrec step.
1168 const SCEV *Step = Normalized->getStepRecurrence(SE);
1169 const SCEV *PostLoopScale = 0;
Dan Gohmandc0e8fb2010-11-17 21:41:58 +00001170 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001171 PostLoopScale = Step;
Dan Gohmandeff6212010-05-03 22:09:21 +00001172 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohmana10756e2010-01-21 02:09:26 +00001173 Normalized =
1174 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
Andrew Trick3228cc22011-03-14 16:50:06 +00001175 Normalized->getLoop(),
1176 // FIXME: Normalized
1177 // ->getNoWrapFlags(FlagNW)
1178 SCEV::FlagAnyWrap));
Dan Gohmana10756e2010-01-21 02:09:26 +00001179 }
1180
1181 // Expand the core addrec. If we need post-loop scaling, force it to
1182 // expand to an integer type to avoid the need for additional casting.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001183 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Dan Gohmana10756e2010-01-21 02:09:26 +00001184 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1185
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001186 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001187 Value *Result;
Dan Gohman448db1c2010-04-07 22:27:08 +00001188 if (!PostIncLoops.count(L))
Dan Gohmana10756e2010-01-21 02:09:26 +00001189 Result = PN;
1190 else {
1191 // In PostInc mode, use the post-incremented value.
1192 BasicBlock *LatchBlock = L->getLoopLatch();
1193 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1194 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick48ba0e42011-10-13 21:55:29 +00001195
1196 // For an expansion to use the postinc form, the client must call
1197 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1198 // or dominated by IVIncInsertPos.
Andrew Trick553fe052011-11-30 06:07:54 +00001199 if (isa<Instruction>(Result)
1200 && !SE.DT->dominates(cast<Instruction>(Result),
1201 Builder.GetInsertPoint())) {
1202 // The induction variable's postinc expansion does not dominate this use.
1203 // IVUsers tries to prevent this case, so it is rare. However, it can
1204 // happen when an IVUser outside the loop is not dominated by the latch
1205 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1206 // all cases. Consider a phi outide whose operand is replaced during
1207 // expansion with the value of the postinc user. Without fundamentally
1208 // changing the way postinc users are tracked, the only remedy is
1209 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1210 // but hopefully expandCodeFor handles that.
1211 bool useSubtract =
Andrew Trickf8fd8412012-01-07 00:27:31 +00001212 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trick553fe052011-11-30 06:07:54 +00001213 if (useSubtract)
1214 Step = SE.getNegativeSCEV(Step);
1215 // Expand the step somewhere that dominates the loop header.
1216 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1217 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1218 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1219 // Restore the insertion point to the place where the caller has
1220 // determined dominates all uses.
1221 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1222 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1223 }
Dan Gohmana10756e2010-01-21 02:09:26 +00001224 }
1225
1226 // Re-apply any non-loop-dominating scale.
1227 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001228 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001229 Result = Builder.CreateMul(Result,
1230 expandCodeFor(PostLoopScale, IntTy));
1231 rememberInstruction(Result);
1232 }
1233
1234 // Re-apply any non-loop-dominating offset.
1235 if (PostLoopOffset) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001236 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001237 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1238 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1239 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001240 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001241 Result = Builder.CreateAdd(Result,
1242 expandCodeFor(PostLoopOffset, IntTy));
1243 rememberInstruction(Result);
1244 }
1245 }
1246
1247 return Result;
1248}
1249
Dan Gohman890f92b2009-04-18 17:56:28 +00001250Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001251 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1252
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001253 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001254 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001255
Dan Gohman4d8414f2009-06-13 16:25:49 +00001256 // First check for an existing canonical IV in a suitable type.
1257 PHINode *CanonicalIV = 0;
1258 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman133e2952010-07-20 16:46:58 +00001259 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman4d8414f2009-06-13 16:25:49 +00001260 CanonicalIV = PN;
1261
1262 // Rewrite an AddRec in terms of the canonical induction variable, if
1263 // its type is more narrow.
1264 if (CanonicalIV &&
1265 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1266 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001267 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1268 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1269 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick3228cc22011-03-14 16:50:06 +00001270 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1271 // FIXME: S->getNoWrapFlags(FlagNW)
1272 SCEV::FlagAnyWrap));
Dan Gohman267a3852009-06-27 21:18:18 +00001273 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1274 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001275 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001276 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Bill Wendlinga4c86ab2011-08-24 21:06:46 +00001277 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1278 isa<LandingPadInst>(NewInsertPt))
Jim Grosbach08f55d02010-06-16 21:13:38 +00001279 ++NewInsertPt;
Dan Gohman4d8414f2009-06-13 16:25:49 +00001280 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1281 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001282 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001283 return V;
1284 }
1285
Nate Begeman36f891b2005-07-30 00:12:19 +00001286 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001287 if (!S->getStart()->isZero()) {
Dan Gohmanf9e64722010-03-18 01:17:13 +00001288 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohmandeff6212010-05-03 22:09:21 +00001289 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trick3228cc22011-03-14 16:50:06 +00001290 // FIXME: can use S->getNoWrapFlags()
1291 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001292
1293 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1294 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001295 const SCEV *Base = S->getStart();
1296 const SCEV *RestArray[1] = { Rest };
1297 // Dig into the expression to find the pointer base for a GEP.
1298 ExposePointerBase(Base, RestArray[0], SE);
1299 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001300 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001301 // Make sure the Base isn't something exotic, such as a multiplied
1302 // or divided pointer value. In those cases, the result type isn't
1303 // actually a pointer type.
1304 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1305 Value *StartV = expand(Base);
1306 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1307 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001308 }
1309 }
1310
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001311 // Just do a normal add. Pre-expand the operands to suppress folding.
1312 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1313 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001314 }
1315
Dan Gohman6ebfd722010-07-26 18:28:14 +00001316 // If we don't yet have a canonical IV, create one.
1317 if (!CanonicalIV) {
Nate Begeman36f891b2005-07-30 00:12:19 +00001318 // Create and insert the PHI node for the induction variable in the
1319 // specified loop.
1320 BasicBlock *Header = L->getHeader();
Jay Foadd8b4fb42011-03-30 11:19:20 +00001321 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad3ecfc862011-03-30 11:28:46 +00001322 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1323 Header->begin());
Dan Gohman6ebfd722010-07-26 18:28:14 +00001324 rememberInstruction(CanonicalIV);
Nate Begeman36f891b2005-07-30 00:12:19 +00001325
Owen Andersoneed707b2009-07-24 23:12:02 +00001326 Constant *One = ConstantInt::get(Ty, 1);
Jay Foadd8b4fb42011-03-30 11:19:20 +00001327 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greif76560182010-07-09 15:40:10 +00001328 BasicBlock *HP = *HPI;
1329 if (L->contains(HP)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001330 // Insert a unit add instruction right before the terminator
1331 // corresponding to the back-edge.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001332 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1333 "indvar.next",
1334 HP->getTerminator());
Devang Pateldf3ad662011-06-22 20:56:56 +00001335 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohmana10756e2010-01-21 02:09:26 +00001336 rememberInstruction(Add);
Dan Gohman6ebfd722010-07-26 18:28:14 +00001337 CanonicalIV->addIncoming(Add, HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001338 } else {
Dan Gohman6ebfd722010-07-26 18:28:14 +00001339 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman83d57742009-09-27 17:46:40 +00001340 }
Gabor Greif76560182010-07-09 15:40:10 +00001341 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001342 }
1343
Dan Gohman6ebfd722010-07-26 18:28:14 +00001344 // {0,+,1} --> Insert a canonical induction variable into the loop!
1345 if (S->isAffine() && S->getOperand(1)->isOne()) {
1346 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1347 "IVs with types different from the canonical IV should "
1348 "already have been handled!");
1349 return CanonicalIV;
1350 }
1351
Dan Gohman4d8414f2009-06-13 16:25:49 +00001352 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001353
Chris Lattnerdf14a042005-10-30 06:24:33 +00001354 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001355 if (S->isAffine()) // {0,+,F} --> i*F
1356 return
1357 expand(SE.getTruncateOrNoop(
Dan Gohman6ebfd722010-07-26 18:28:14 +00001358 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001359 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohman6ebfd722010-07-26 18:28:14 +00001360 CanonicalIV->getType())),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001361 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001362
1363 // If this is a chain of recurrences, turn it into a closed form, using the
1364 // folders, then expandCodeFor the closed form. This allows the folders to
1365 // simplify the expression without having to build a bunch of special code
1366 // into this folder.
Dan Gohman6ebfd722010-07-26 18:28:14 +00001367 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001368
Dan Gohman4d8414f2009-06-13 16:25:49 +00001369 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001370 const SCEV *NewS = S;
Dan Gohman6ebfd722010-07-26 18:28:14 +00001371 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001372 if (isa<SCEVAddRecExpr>(Ext))
1373 NewS = Ext;
1374
Dan Gohman0bba49c2009-07-07 17:06:11 +00001375 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001376 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001377
Dan Gohman4d8414f2009-06-13 16:25:49 +00001378 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001379 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001380 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001381}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001382
Dan Gohman890f92b2009-04-18 17:56:28 +00001383Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001384 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001385 Value *V = expandCodeFor(S->getOperand(),
1386 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001387 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001388 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001389 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001390}
1391
Dan Gohman890f92b2009-04-18 17:56:28 +00001392Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001393 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001394 Value *V = expandCodeFor(S->getOperand(),
1395 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001396 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001397 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001398 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001399}
1400
Dan Gohman890f92b2009-04-18 17:56:28 +00001401Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001402 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001403 Value *V = expandCodeFor(S->getOperand(),
1404 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramera9390a42011-09-27 20:39:19 +00001405 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohmana10756e2010-01-21 02:09:26 +00001406 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001407 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001408}
1409
Dan Gohman890f92b2009-04-18 17:56:28 +00001410Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001411 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001412 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001413 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1414 // In the case of mixed integer and pointer types, do the
1415 // rest of the comparisons as integer.
1416 if (S->getOperand(i)->getType() != Ty) {
1417 Ty = SE.getEffectiveSCEVType(Ty);
1418 LHS = InsertNoopCastOfTo(LHS, Ty);
1419 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001420 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001421 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001422 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001423 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001424 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001425 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001426 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001427 // In the case of mixed integer and pointer types, cast the
1428 // final result back to the pointer type.
1429 if (LHS->getType() != S->getType())
1430 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001431 return LHS;
1432}
1433
Dan Gohman890f92b2009-04-18 17:56:28 +00001434Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001435 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001436 Type *Ty = LHS->getType();
Dan Gohman0196dc52009-07-14 20:57:04 +00001437 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1438 // In the case of mixed integer and pointer types, do the
1439 // rest of the comparisons as integer.
1440 if (S->getOperand(i)->getType() != Ty) {
1441 Ty = SE.getEffectiveSCEVType(Ty);
1442 LHS = InsertNoopCastOfTo(LHS, Ty);
1443 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001444 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001445 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohmana10756e2010-01-21 02:09:26 +00001446 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001447 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001448 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001449 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001450 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001451 // In the case of mixed integer and pointer types, cast the
1452 // final result back to the pointer type.
1453 if (LHS->getType() != S->getType())
1454 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001455 return LHS;
1456}
1457
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001458Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001459 Instruction *IP) {
Dan Gohman6c7ed6b2010-03-19 21:51:03 +00001460 Builder.SetInsertPoint(IP->getParent(), IP);
1461 return expandCodeFor(SH, Ty);
1462}
1463
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001464Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001465 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001466 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001467 if (Ty) {
1468 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1469 "non-trivial casts should be done with the SCEVs directly!");
1470 V = InsertNoopCastOfTo(V, Ty);
1471 }
1472 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001473}
1474
Dan Gohman890f92b2009-04-18 17:56:28 +00001475Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001476 // Compute an insertion point for this SCEV object. Hoist the instructions
1477 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001478 Instruction *InsertPt = Builder.GetInsertPoint();
1479 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001480 L = L->getParentLoop())
Dan Gohman17ead4f2010-11-17 21:23:15 +00001481 if (SE.isLoopInvariant(S, L)) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001482 if (!L) break;
Dan Gohmane059ee82010-03-23 21:53:22 +00001483 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001484 InsertPt = Preheader->getTerminator();
Andrew Trick0f8cd562012-01-02 21:25:10 +00001485 else {
1486 // LSR sets the insertion point for AddRec start/step values to the
1487 // block start to simplify value reuse, even though it's an invalid
1488 // position. SCEVExpander must correct for this in all cases.
1489 InsertPt = L->getHeader()->getFirstInsertionPt();
1490 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001491 } else {
1492 // If the SCEV is computable at this level, insert it into the header
1493 // after the PHIs (and after any other instructions that we've inserted
1494 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001495 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1496 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001497 while (InsertPt != Builder.GetInsertPoint()
1498 && (isInsertedInstruction(InsertPt)
1499 || isa<DbgInfoIntrinsic>(InsertPt))) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001500 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001501 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001502 break;
1503 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001504
Dan Gohman667d7872009-06-26 22:53:46 +00001505 // Check to see if we already expanded this here.
1506 std::map<std::pair<const SCEV *, Instruction *>,
1507 AssertingVH<Value> >::iterator I =
1508 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001509 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001510 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001511
1512 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1513 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1514 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001515
1516 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001517 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001518
Dan Gohman667d7872009-06-26 22:53:46 +00001519 // Remember the expanded value for this SCEV at this location.
Andrew Trick48ba0e42011-10-13 21:55:29 +00001520 //
1521 // This is independent of PostIncLoops. The mapped value simply materializes
1522 // the expression at this insertion point. If the mapped value happened to be
1523 // a postinc expansion, it could be reused by a non postinc user, but only if
1524 // its insertion point was already at the head of the loop.
1525 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001526
Dan Gohman45598552010-02-15 00:21:43 +00001527 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001528 return V;
1529}
Dan Gohman1d09de32009-06-05 16:35:53 +00001530
Dan Gohman1d826a72010-02-14 03:12:47 +00001531void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohman25fcaff2010-06-05 00:33:07 +00001532 if (!PostIncLoops.empty())
1533 InsertedPostIncValues.insert(I);
1534 else
Dan Gohman1d826a72010-02-14 03:12:47 +00001535 InsertedValues.insert(I);
Dan Gohman1d826a72010-02-14 03:12:47 +00001536}
1537
Dan Gohman45598552010-02-15 00:21:43 +00001538void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman45598552010-02-15 00:21:43 +00001539 Builder.SetInsertPoint(BB, I);
1540}
1541
Dan Gohman1d09de32009-06-05 16:35:53 +00001542/// getOrInsertCanonicalInductionVariable - This method returns the
1543/// canonical induction variable of the specified type for the specified
1544/// loop (inserting one if there is none). A canonical induction variable
1545/// starts at zero and steps by one on each iteration.
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001546PHINode *
Dan Gohman1d09de32009-06-05 16:35:53 +00001547SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001548 Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001549 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman133e2952010-07-20 16:46:58 +00001550
1551 // Build a SCEV for {0,+,1}<L>.
Andrew Trick3228cc22011-03-14 16:50:06 +00001552 // Conservatively use FlagAnyWrap for now.
Dan Gohmandeff6212010-05-03 22:09:21 +00001553 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick3228cc22011-03-14 16:50:06 +00001554 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman133e2952010-07-20 16:46:58 +00001555
1556 // Emit code for it.
Dan Gohman267a3852009-06-27 21:18:18 +00001557 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1558 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman7c58dbd2010-07-20 16:44:52 +00001559 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
Dan Gohman267a3852009-06-27 21:18:18 +00001560 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001561 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman133e2952010-07-20 16:46:58 +00001562
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001563 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001564}
Andrew Trick20449412011-10-11 02:28:51 +00001565
Andrew Trick139f3332012-01-07 01:29:21 +00001566/// Sort values by integer width for replaceCongruentIVs.
1567static bool width_descending(Value *lhs, Value *rhs) {
Andrew Trickee98aa82012-01-07 01:12:09 +00001568 // Put pointers at the back and make sure pointer < pointer = false.
1569 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1570 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1571 return rhs->getType()->getPrimitiveSizeInBits()
1572 < lhs->getType()->getPrimitiveSizeInBits();
1573}
1574
Andrew Trick20449412011-10-11 02:28:51 +00001575/// replaceCongruentIVs - Check for congruent phis in this loop header and
1576/// replace them with their most canonical representative. Return the number of
1577/// phis eliminated.
1578///
1579/// This does not depend on any SCEVExpander state but should be used in
1580/// the same context that SCEVExpander is used.
1581unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Andrew Trickee98aa82012-01-07 01:12:09 +00001582 SmallVectorImpl<WeakVH> &DeadInsts,
1583 const TargetLowering *TLI) {
1584 // Find integer phis in order of increasing width.
1585 SmallVector<PHINode*, 8> Phis;
1586 for (BasicBlock::iterator I = L->getHeader()->begin();
1587 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1588 Phis.push_back(Phi);
1589 }
1590 if (TLI)
1591 std::sort(Phis.begin(), Phis.end(), width_descending);
1592
Andrew Trick20449412011-10-11 02:28:51 +00001593 unsigned NumElim = 0;
1594 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trickee98aa82012-01-07 01:12:09 +00001595 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1596 // so narrow phis can reuse them.
1597 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1598 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1599 PHINode *Phi = *PIter;
1600
Andrew Trick20449412011-10-11 02:28:51 +00001601 if (!SE.isSCEVable(Phi->getType()))
1602 continue;
1603
1604 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1605 if (!OrigPhiRef) {
1606 OrigPhiRef = Phi;
Andrew Trickee98aa82012-01-07 01:12:09 +00001607 if (Phi->getType()->isIntegerTy() && TLI
1608 && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1609 // This phi can be freely truncated to the narrowest phi type. Map the
1610 // truncated expression to it so it will be reused for narrow types.
1611 const SCEV *TruncExpr =
1612 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1613 ExprToIVMap[TruncExpr] = Phi;
1614 }
Andrew Trick20449412011-10-11 02:28:51 +00001615 continue;
1616 }
1617
Andrew Trickee98aa82012-01-07 01:12:09 +00001618 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1619 // sense.
1620 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trick20449412011-10-11 02:28:51 +00001621 continue;
1622
1623 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1624 Instruction *OrigInc =
1625 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1626 Instruction *IsomorphicInc =
1627 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1628
Andrew Trickee98aa82012-01-07 01:12:09 +00001629 // If this phi has the same width but is more canonical, replace the
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001630 // original with it. As part of the "more canonical" determination,
1631 // respect a prior decision to use an IV chain.
Andrew Trickee98aa82012-01-07 01:12:09 +00001632 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001633 && !(ChainedPhis.count(Phi)
1634 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1635 && (ChainedPhis.count(Phi)
1636 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trick20449412011-10-11 02:28:51 +00001637 std::swap(OrigPhiRef, Phi);
1638 std::swap(OrigInc, IsomorphicInc);
1639 }
1640 // Replacing the congruent phi is sufficient because acyclic redundancy
1641 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1642 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trick139f3332012-01-07 01:29:21 +00001643 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1644 // common case of a single IV increment so that DeleteDeadPHIs can remove
1645 // cycles that had postinc uses.
Andrew Trickee98aa82012-01-07 01:12:09 +00001646 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1647 IsomorphicInc->getType());
1648 if (OrigInc != IsomorphicInc
Andrew Trick64925c52012-01-10 01:45:08 +00001649 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickb5c26ef2012-01-20 07:41:13 +00001650 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1651 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trick20449412011-10-11 02:28:51 +00001652 DEBUG_WITH_TYPE(DebugType, dbgs()
1653 << "INDVARS: Eliminated congruent iv.inc: "
1654 << *IsomorphicInc << '\n');
Andrew Trickee98aa82012-01-07 01:12:09 +00001655 Value *NewInc = OrigInc;
1656 if (OrigInc->getType() != IsomorphicInc->getType()) {
Andrew Trickdd1f22f2012-01-14 03:17:23 +00001657 Instruction *IP = isa<PHINode>(OrigInc)
1658 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1659 : OrigInc->getNextNode();
1660 IRBuilder<> Builder(IP);
Andrew Trickee98aa82012-01-07 01:12:09 +00001661 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1662 NewInc = Builder.
1663 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1664 }
1665 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trick20449412011-10-11 02:28:51 +00001666 DeadInsts.push_back(IsomorphicInc);
1667 }
1668 }
1669 DEBUG_WITH_TYPE(DebugType, dbgs()
1670 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1671 ++NumElim;
Andrew Trickee98aa82012-01-07 01:12:09 +00001672 Value *NewIV = OrigPhiRef;
1673 if (OrigPhiRef->getType() != Phi->getType()) {
1674 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1675 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1676 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1677 }
1678 Phi->replaceAllUsesWith(NewIV);
Andrew Trick20449412011-10-11 02:28:51 +00001679 DeadInsts.push_back(Phi);
1680 }
1681 return NumElim;
1682}