blob: f5f10c8961b3085ae248a2646fa85bf325b71cb5 [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"
Owen Anderson76f600b2009-07-06 22:37:39 +000018#include "llvm/LLVMContext.h"
Dan Gohman5be18e82009-05-19 02:15:55 +000019#include "llvm/Target/TargetData.h"
Dan Gohman4d8414f2009-06-13 16:25:49 +000020#include "llvm/ADT/STLExtras.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000021using namespace llvm;
22
Dan Gohman267a3852009-06-27 21:18:18 +000023/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
24/// which must be possible with a noop cast, doing what we can to share
25/// the casts.
26Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
27 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
28 assert((Op == Instruction::BitCast ||
29 Op == Instruction::PtrToInt ||
30 Op == Instruction::IntToPtr) &&
31 "InsertNoopCastOfTo cannot perform non-noop casts!");
32 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
33 "InsertNoopCastOfTo cannot change sizes!");
34
Dan Gohman2d1be872009-04-16 03:18:22 +000035 // Short-circuit unnecessary bitcasts.
Dan Gohman267a3852009-06-27 21:18:18 +000036 if (Op == Instruction::BitCast && V->getType() == Ty)
Dan Gohman2d1be872009-04-16 03:18:22 +000037 return V;
38
Dan Gohmanf04fa482009-04-16 15:52:57 +000039 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman267a3852009-06-27 21:18:18 +000040 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman80dcdee2009-05-01 17:00:00 +000041 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +000042 if (CastInst *CI = dyn_cast<CastInst>(V))
43 if ((CI->getOpcode() == Instruction::PtrToInt ||
44 CI->getOpcode() == Instruction::IntToPtr) &&
45 SE.getTypeSizeInBits(CI->getType()) ==
46 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
47 return CI->getOperand(0);
Dan Gohman80dcdee2009-05-01 17:00:00 +000048 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
49 if ((CE->getOpcode() == Instruction::PtrToInt ||
50 CE->getOpcode() == Instruction::IntToPtr) &&
51 SE.getTypeSizeInBits(CE->getType()) ==
52 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
53 return CE->getOperand(0);
54 }
Dan Gohmanf04fa482009-04-16 15:52:57 +000055
Chris Lattnerca1a4be2006-02-04 09:51:53 +000056 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +000057 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman4c0d5d52009-08-20 16:42:55 +000058
Chris Lattnerca1a4be2006-02-04 09:51:53 +000059 if (Argument *A = dyn_cast<Argument>(V)) {
60 // Check to see if there is already a cast!
61 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
Dan Gohman40a5a1b2009-06-24 01:18:18 +000062 UI != E; ++UI)
Chris Lattnerca1a4be2006-02-04 09:51:53 +000063 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000064 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000065 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000066 // If the cast isn't the first instruction of the function, move it.
Dan Gohman40a5a1b2009-06-24 01:18:18 +000067 if (BasicBlock::iterator(CI) !=
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000068 A->getParent()->getEntryBlock().begin()) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +000069 // Recreate the cast at the beginning of the entry block.
70 // The old cast is left in place in case it is being used
71 // as an insert point.
72 Instruction *NewCI =
Dan Gohman267a3852009-06-27 21:18:18 +000073 CastInst::Create(Op, V, Ty, "",
Dan Gohman40a5a1b2009-06-24 01:18:18 +000074 A->getParent()->getEntryBlock().begin());
75 NewCI->takeName(CI);
76 CI->replaceAllUsesWith(NewCI);
77 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000078 }
79 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000080 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +000081
Dan Gohman267a3852009-06-27 21:18:18 +000082 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
Dan Gohmancf5ab822009-05-01 17:13:31 +000083 A->getParent()->getEntryBlock().begin());
Dan Gohmana10756e2010-01-21 02:09:26 +000084 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +000085 return I;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000086 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000087
Chris Lattnerca1a4be2006-02-04 09:51:53 +000088 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000089
Chris Lattnerca1a4be2006-02-04 09:51:53 +000090 // Check to see if there is already a cast. If there is, use it.
91 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
92 UI != E; ++UI) {
93 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000094 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
Dan Gohman267a3852009-06-27 21:18:18 +000095 if (CI->getOpcode() == Op) {
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000096 BasicBlock::iterator It = I; ++It;
97 if (isa<InvokeInst>(I))
98 It = cast<InvokeInst>(I)->getNormalDest()->begin();
99 while (isa<PHINode>(It)) ++It;
100 if (It != BasicBlock::iterator(CI)) {
Dan Gohmanc37e3d52010-01-21 10:08:42 +0000101 // Recreate the cast after the user.
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000102 // The old cast is left in place in case it is being used
103 // as an insert point.
Dan Gohman267a3852009-06-27 21:18:18 +0000104 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000105 NewCI->takeName(CI);
106 CI->replaceAllUsesWith(NewCI);
Dan Gohmanc37e3d52010-01-21 10:08:42 +0000107 rememberInstruction(NewCI);
Dan Gohman40a5a1b2009-06-24 01:18:18 +0000108 return NewCI;
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000109 }
Dan Gohmanc37e3d52010-01-21 10:08:42 +0000110 rememberInstruction(CI);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +0000111 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000112 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000113 }
114 BasicBlock::iterator IP = I; ++IP;
115 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
116 IP = II->getNormalDest()->begin();
117 while (isa<PHINode>(IP)) ++IP;
Dan Gohman267a3852009-06-27 21:18:18 +0000118 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
Dan Gohmana10756e2010-01-21 02:09:26 +0000119 rememberInstruction(CI);
Dan Gohmancf5ab822009-05-01 17:13:31 +0000120 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +0000121}
122
Chris Lattner7fec90e2007-04-13 05:04:18 +0000123/// InsertBinop - Insert the specified binary operator, doing a small amount
124/// of work to avoid inserting an obviously redundant operation.
Dan Gohman267a3852009-06-27 21:18:18 +0000125Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
126 Value *LHS, Value *RHS) {
Dan Gohman0f0eb182007-06-15 19:21:55 +0000127 // Fold a binop with constant operands.
128 if (Constant *CLHS = dyn_cast<Constant>(LHS))
129 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000130 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman0f0eb182007-06-15 19:21:55 +0000131
Chris Lattner7fec90e2007-04-13 05:04:18 +0000132 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
133 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000134 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
135 // Scanning starts from the last instruction before the insertion point.
136 BasicBlock::iterator IP = Builder.GetInsertPoint();
137 if (IP != BlockBegin) {
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000138 --IP;
139 for (; ScanLimit; --IP, --ScanLimit) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000140 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
141 IP->getOperand(1) == RHS)
142 return IP;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000143 if (IP == BlockBegin) break;
144 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000145 }
Dan Gohman267a3852009-06-27 21:18:18 +0000146
Dan Gohman087bd1e2010-03-03 05:29:13 +0000147 // Save the original insertion point so we can restore it when we're done.
148 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
149 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
150
151 // Move the insertion point out of as many loops as we can.
152 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
153 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
154 BasicBlock *Preheader = L->getLoopPreheader();
155 if (!Preheader) break;
156
157 // Ok, move up a level.
158 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
159 }
160
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000161 // If we haven't found this binop, insert it.
Dan Gohman267a3852009-06-27 21:18:18 +0000162 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +0000163 rememberInstruction(BO);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000164
165 // Restore the original insert point.
166 if (SaveInsertBB)
167 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
168
Dan Gohmancf5ab822009-05-01 17:13:31 +0000169 return BO;
Chris Lattner7fec90e2007-04-13 05:04:18 +0000170}
171
Dan Gohman4a4f7672009-05-27 02:00:53 +0000172/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman453aa4f2009-05-24 18:06:31 +0000173/// division. If so, update S with Factor divided out and return true.
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000174/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman4a4f7672009-05-27 02:00:53 +0000175/// computed.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000176/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
177/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
178/// check to see if the divide was folded.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000179static bool FactorOutConstant(const SCEV *&S,
180 const SCEV *&Remainder,
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000181 const SCEV *Factor,
182 ScalarEvolution &SE,
183 const TargetData *TD) {
Dan Gohman453aa4f2009-05-24 18:06:31 +0000184 // Everything is divisible by one.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000185 if (Factor->isOne())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000186 return true;
187
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000188 // x/x == 1.
189 if (S == Factor) {
190 S = SE.getIntegerSCEV(1, S->getType());
191 return true;
192 }
193
Dan Gohman453aa4f2009-05-24 18:06:31 +0000194 // For a Constant, check for a multiple of the given factor.
Dan Gohman4a4f7672009-05-27 02:00:53 +0000195 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000196 // 0/x == 0.
197 if (C->isZero())
Dan Gohman453aa4f2009-05-24 18:06:31 +0000198 return true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000199 // Check for divisibility.
200 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
201 ConstantInt *CI =
202 ConstantInt::get(SE.getContext(),
203 C->getValue()->getValue().sdiv(
204 FC->getValue()->getValue()));
205 // If the quotient is zero and the remainder is non-zero, reject
206 // the value at this scale. It will be considered for subsequent
207 // smaller scales.
208 if (!CI->isZero()) {
209 const SCEV *Div = SE.getConstant(CI);
210 S = Div;
211 Remainder =
212 SE.getAddExpr(Remainder,
213 SE.getConstant(C->getValue()->getValue().srem(
214 FC->getValue()->getValue())));
215 return true;
216 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000217 }
Dan Gohman4a4f7672009-05-27 02:00:53 +0000218 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000219
220 // In a Mul, check if there is a constant operand which is a multiple
221 // of the given factor.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000222 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
223 if (TD) {
224 // With TargetData, the size is known. Check if there is a constant
225 // operand which is a multiple of the given factor. If so, we can
226 // factor it.
227 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
228 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
229 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
230 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
231 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
232 MOperands.end());
233 NewMulOps[0] =
234 SE.getConstant(C->getValue()->getValue().sdiv(
235 FC->getValue()->getValue()));
236 S = SE.getMulExpr(NewMulOps);
237 return true;
238 }
239 } else {
240 // Without TargetData, check if Factor can be factored out of any of the
241 // Mul's operands. If so, we can just remove it.
242 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
243 const SCEV *SOp = M->getOperand(i);
244 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
245 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
246 Remainder->isZero()) {
247 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
248 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
249 MOperands.end());
250 NewMulOps[i] = SOp;
251 S = SE.getMulExpr(NewMulOps);
252 return true;
253 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000254 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000255 }
256 }
Dan Gohman453aa4f2009-05-24 18:06:31 +0000257
258 // In an AddRec, check if both start and step are divisible.
259 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000260 const SCEV *Step = A->getStepRecurrence(SE);
261 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000262 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
Dan Gohman4a4f7672009-05-27 02:00:53 +0000263 return false;
264 if (!StepRem->isZero())
265 return false;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000266 const SCEV *Start = A->getStart();
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000267 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
Dan Gohman453aa4f2009-05-24 18:06:31 +0000268 return false;
269 S = SE.getAddRecExpr(Start, Step, A->getLoop());
270 return true;
271 }
272
273 return false;
274}
275
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000276/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
277/// is the number of SCEVAddRecExprs present, which are kept at the end of
278/// the list.
279///
280static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
281 const Type *Ty,
282 ScalarEvolution &SE) {
283 unsigned NumAddRecs = 0;
284 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
285 ++NumAddRecs;
286 // Group Ops into non-addrecs and addrecs.
287 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
288 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
289 // Let ScalarEvolution sort and simplify the non-addrecs list.
290 const SCEV *Sum = NoAddRecs.empty() ?
291 SE.getIntegerSCEV(0, Ty) :
292 SE.getAddExpr(NoAddRecs);
293 // If it returned an add, use the operands. Otherwise it simplified
294 // the sum into a single value, so just use that.
295 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
296 Ops = Add->getOperands();
297 else {
298 Ops.clear();
299 if (!Sum->isZero())
300 Ops.push_back(Sum);
301 }
302 // Then append the addrecs.
303 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
304}
305
306/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
307/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
308/// This helps expose more opportunities for folding parts of the expressions
309/// into GEP indices.
310///
311static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
312 const Type *Ty,
313 ScalarEvolution &SE) {
314 // Find the addrecs.
315 SmallVector<const SCEV *, 8> AddRecs;
316 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
317 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
318 const SCEV *Start = A->getStart();
319 if (Start->isZero()) break;
320 const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
321 AddRecs.push_back(SE.getAddRecExpr(Zero,
322 A->getStepRecurrence(SE),
323 A->getLoop()));
324 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
325 Ops[i] = Zero;
326 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
327 e += Add->getNumOperands();
328 } else {
329 Ops[i] = Start;
330 }
331 }
332 if (!AddRecs.empty()) {
333 // Add the addrecs onto the end of the list.
334 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
335 // Resort the operand list, moving any constants to the front.
336 SimplifyAddOperands(Ops, Ty, SE);
337 }
338}
339
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000340/// expandAddToGEP - Expand an addition expression with a pointer type into
341/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
342/// BasicAliasAnalysis and other passes analyze the result. See the rules
343/// for getelementptr vs. inttoptr in
344/// http://llvm.org/docs/LangRef.html#pointeraliasing
345/// for details.
Dan Gohman13c5e352009-07-20 17:44:17 +0000346///
Dan Gohman3abf9052010-01-19 22:26:02 +0000347/// Design note: The correctness of using getelementptr here depends on
Dan Gohman4c0d5d52009-08-20 16:42:55 +0000348/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
349/// they may introduce pointer arithmetic which may not be safely converted
350/// into getelementptr.
Dan Gohman453aa4f2009-05-24 18:06:31 +0000351///
352/// Design note: It might seem desirable for this function to be more
353/// loop-aware. If some of the indices are loop-invariant while others
354/// aren't, it might seem desirable to emit multiple GEPs, keeping the
355/// loop-invariant portions of the overall computation outside the loop.
356/// However, there are a few reasons this is not done here. Hoisting simple
357/// arithmetic is a low-level optimization that often isn't very
358/// important until late in the optimization process. In fact, passes
359/// like InstructionCombining will combine GEPs, even if it means
360/// pushing loop-invariant computation down into loops, so even if the
361/// GEPs were split here, the work would quickly be undone. The
362/// LoopStrengthReduction pass, which is usually run quite late (and
363/// after the last InstructionCombining pass), takes care of hoisting
364/// loop-invariant portions of expressions, after considering what
365/// can be folded using target addressing modes.
366///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000367Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
368 const SCEV *const *op_end,
Dan Gohman5be18e82009-05-19 02:15:55 +0000369 const PointerType *PTy,
370 const Type *Ty,
371 Value *V) {
372 const Type *ElTy = PTy->getElementType();
373 SmallVector<Value *, 4> GepIndices;
Dan Gohman0bba49c2009-07-07 17:06:11 +0000374 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman5be18e82009-05-19 02:15:55 +0000375 bool AnyNonZeroIndices = false;
Dan Gohman5be18e82009-05-19 02:15:55 +0000376
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000377 // Split AddRecs up into parts as either of the parts may be usable
378 // without the other.
379 SplitAddRecs(Ops, Ty, SE);
380
Bob Wilsoneb356992009-12-04 01:33:04 +0000381 // Descend down the pointer's type and attempt to convert the other
Dan Gohman5be18e82009-05-19 02:15:55 +0000382 // operands into GEP indices, at each level. The first index in a GEP
383 // indexes into the array implied by the pointer operand; the rest of
384 // the indices index into the element or field type selected by the
385 // preceding index.
386 for (;;) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000387 // If the scale size is not 0, attempt to factor out a scale for
388 // array indexing.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000389 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman150dfa82010-01-28 06:32:46 +0000390 if (ElTy->isSized()) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000391 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
Dan Gohman150dfa82010-01-28 06:32:46 +0000392 if (!ElSize->isZero()) {
393 SmallVector<const SCEV *, 8> NewOps;
394 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
395 const SCEV *Op = Ops[i];
396 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
397 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
398 // Op now has ElSize factored out.
399 ScaledOps.push_back(Op);
400 if (!Remainder->isZero())
401 NewOps.push_back(Remainder);
402 AnyNonZeroIndices = true;
403 } else {
404 // The operand was not divisible, so add it to the list of operands
405 // we'll scan next iteration.
406 NewOps.push_back(Ops[i]);
407 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000408 }
Dan Gohman150dfa82010-01-28 06:32:46 +0000409 // If we made any changes, update Ops.
410 if (!ScaledOps.empty()) {
411 Ops = NewOps;
412 SimplifyAddOperands(Ops, Ty, SE);
413 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000414 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000415 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000416
417 // Record the scaled array index for this level of the type. If
418 // we didn't find any operands that could be factored, tentatively
419 // assume that element zero was selected (since the zero offset
420 // would obviously be folded away).
Dan Gohman5be18e82009-05-19 02:15:55 +0000421 Value *Scaled = ScaledOps.empty() ?
Owen Andersona7235ea2009-07-31 20:28:14 +0000422 Constant::getNullValue(Ty) :
Dan Gohman5be18e82009-05-19 02:15:55 +0000423 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
424 GepIndices.push_back(Scaled);
425
426 // Collect struct field index operands.
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000427 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
428 bool FoundFieldNo = false;
429 // An empty struct has no fields.
430 if (STy->getNumElements() == 0) break;
431 if (SE.TD) {
432 // With TargetData, field offsets are known. See if a constant offset
433 // falls within any of the struct fields.
434 if (Ops.empty()) break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000435 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
436 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
437 const StructLayout &SL = *SE.TD->getStructLayout(STy);
438 uint64_t FullOffset = C->getValue()->getZExtValue();
439 if (FullOffset < SL.getSizeInBytes()) {
440 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson1d0be152009-08-13 21:58:54 +0000441 GepIndices.push_back(
442 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000443 ElTy = STy->getTypeAtIndex(ElIdx);
444 Ops[0] =
Dan Gohman6de29f82009-06-15 22:12:54 +0000445 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman5be18e82009-05-19 02:15:55 +0000446 AnyNonZeroIndices = true;
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000447 FoundFieldNo = true;
Dan Gohman5be18e82009-05-19 02:15:55 +0000448 }
449 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000450 } else {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000451 // Without TargetData, just check for an offsetof expression of the
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000452 // appropriate struct type.
453 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohman0f5efe52010-01-28 02:15:55 +0000454 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Dan Gohman4f8eea82010-02-01 18:27:38 +0000455 const Type *CTy;
Dan Gohman0f5efe52010-01-28 02:15:55 +0000456 Constant *FieldNo;
Dan Gohman4f8eea82010-02-01 18:27:38 +0000457 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohman0f5efe52010-01-28 02:15:55 +0000458 GepIndices.push_back(FieldNo);
459 ElTy =
460 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000461 Ops[i] = SE.getConstant(Ty, 0);
462 AnyNonZeroIndices = true;
463 FoundFieldNo = true;
464 break;
465 }
Dan Gohman0f5efe52010-01-28 02:15:55 +0000466 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000467 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000468 // If no struct field offsets were found, tentatively assume that
469 // field zero was selected (since the zero offset would obviously
470 // be folded away).
471 if (!FoundFieldNo) {
472 ElTy = STy->getTypeAtIndex(0u);
473 GepIndices.push_back(
474 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
475 }
Dan Gohman5be18e82009-05-19 02:15:55 +0000476 }
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000477
478 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
479 ElTy = ATy->getElementType();
480 else
481 break;
Dan Gohman5be18e82009-05-19 02:15:55 +0000482 }
483
Dan Gohman3f46a3a2010-03-01 17:49:51 +0000484 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman5be18e82009-05-19 02:15:55 +0000485 // the base to i8* and do an ugly getelementptr with that. It's still
486 // better than ptrtoint+arithmetic+inttoptr at least.
487 if (!AnyNonZeroIndices) {
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000488 // Cast the base to i8*.
Dan Gohman5be18e82009-05-19 02:15:55 +0000489 V = InsertNoopCastOfTo(V,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000490 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000491
492 // Expand the operands for a plain byte offset.
Dan Gohman92fcdca2009-06-09 17:18:38 +0000493 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman5be18e82009-05-19 02:15:55 +0000494
495 // Fold a GEP with constant operands.
496 if (Constant *CLHS = dyn_cast<Constant>(V))
497 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000498 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
Dan Gohman5be18e82009-05-19 02:15:55 +0000499
500 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
501 unsigned ScanLimit = 6;
Dan Gohman267a3852009-06-27 21:18:18 +0000502 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
503 // Scanning starts from the last instruction before the insertion point.
504 BasicBlock::iterator IP = Builder.GetInsertPoint();
505 if (IP != BlockBegin) {
Dan Gohman5be18e82009-05-19 02:15:55 +0000506 --IP;
507 for (; ScanLimit; --IP, --ScanLimit) {
508 if (IP->getOpcode() == Instruction::GetElementPtr &&
509 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
510 return IP;
511 if (IP == BlockBegin) break;
512 }
513 }
514
Dan Gohman087bd1e2010-03-03 05:29:13 +0000515 // Save the original insertion point so we can restore it when we're done.
516 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
517 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
518
519 // Move the insertion point out of as many loops as we can.
520 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
521 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
522 BasicBlock *Preheader = L->getLoopPreheader();
523 if (!Preheader) break;
524
525 // Ok, move up a level.
526 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
527 }
528
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000529 // Emit a GEP.
530 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohmana10756e2010-01-21 02:09:26 +0000531 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000532
533 // Restore the original insert point.
534 if (SaveInsertBB)
535 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
536
Dan Gohman5be18e82009-05-19 02:15:55 +0000537 return GEP;
538 }
539
Dan Gohman087bd1e2010-03-03 05:29:13 +0000540 // Save the original insertion point so we can restore it when we're done.
541 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
542 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
543
544 // Move the insertion point out of as many loops as we can.
545 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
546 if (!L->isLoopInvariant(V)) break;
547
548 bool AnyIndexNotLoopInvariant = false;
549 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
550 E = GepIndices.end(); I != E; ++I)
551 if (!L->isLoopInvariant(*I)) {
552 AnyIndexNotLoopInvariant = true;
553 break;
554 }
555 if (AnyIndexNotLoopInvariant)
556 break;
557
558 BasicBlock *Preheader = L->getLoopPreheader();
559 if (!Preheader) break;
560
561 // Ok, move up a level.
562 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
563 }
564
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000565 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
566 // because ScalarEvolution may have changed the address arithmetic to
567 // compute a value which is beyond the end of the allocated object.
Dan Gohmana10756e2010-01-21 02:09:26 +0000568 Value *Casted = V;
569 if (V->getType() != PTy)
570 Casted = InsertNoopCastOfTo(Casted, PTy);
571 Value *GEP = Builder.CreateGEP(Casted,
Dan Gohman267a3852009-06-27 21:18:18 +0000572 GepIndices.begin(),
573 GepIndices.end(),
574 "scevgep");
Dan Gohman5be18e82009-05-19 02:15:55 +0000575 Ops.push_back(SE.getUnknown(GEP));
Dan Gohmana10756e2010-01-21 02:09:26 +0000576 rememberInstruction(GEP);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000577
578 // Restore the original insert point.
579 if (SaveInsertBB)
580 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
581
Dan Gohman5be18e82009-05-19 02:15:55 +0000582 return expand(SE.getAddExpr(Ops));
583}
584
Dan Gohmana10756e2010-01-21 02:09:26 +0000585/// isNonConstantNegative - Return true if the specified scev is negated, but
586/// not a constant.
587static bool isNonConstantNegative(const SCEV *F) {
588 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
589 if (!Mul) return false;
590
591 // If there is a constant factor, it will be first.
592 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
593 if (!SC) return false;
594
595 // Return true if the value is negative, this matches things like (-42 * V).
596 return SC->getValue()->getValue().isNegative();
597}
598
Dan Gohman087bd1e2010-03-03 05:29:13 +0000599/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
600/// SCEV expansion. If they are nested, this is the most nested. If they are
601/// neighboring, pick the later.
602static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
603 DominatorTree &DT) {
604 if (!A) return B;
605 if (!B) return A;
606 if (A->contains(B)) return B;
607 if (B->contains(A)) return A;
608 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
609 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
610 return A; // Arbitrarily break the tie.
611}
612
613/// GetRelevantLoop - Get the most relevant loop associated with the given
614/// expression, according to PickMostRelevantLoop.
615static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
616 DominatorTree &DT) {
617 if (isa<SCEVConstant>(S))
618 return 0;
619 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
620 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
621 return LI.getLoopFor(I->getParent());
622 return 0;
623 }
624 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
625 const Loop *L = 0;
626 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
627 L = AR->getLoop();
628 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
629 I != E; ++I)
630 L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
631 return L;
632 }
633 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
634 return GetRelevantLoop(C->getOperand(), LI, DT);
635 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
636 return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
637 GetRelevantLoop(D->getRHS(), LI, DT),
638 DT);
639 llvm_unreachable("Unexpected SCEV type!");
640}
641
642/// LoopCompare - Compare loops by PickMostRelevantLoop.
643class LoopCompare {
644 DominatorTree &DT;
645public:
646 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
647
648 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
649 std::pair<const Loop *, const SCEV *> RHS) const {
650 // Compare loops with PickMostRelevantLoop.
651 if (LHS.first != RHS.first)
652 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
653
654 // If one operand is a non-constant negative and the other is not,
655 // put the non-constant negative on the right so that a sub can
656 // be used instead of a negate and add.
657 if (isNonConstantNegative(LHS.second)) {
658 if (!isNonConstantNegative(RHS.second))
659 return false;
660 } else if (isNonConstantNegative(RHS.second))
661 return true;
662
663 // Otherwise they are equivalent according to this comparison.
664 return false;
665 }
666};
667
Dan Gohman890f92b2009-04-18 17:56:28 +0000668Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000669 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanc70c3772009-09-26 16:11:57 +0000670
Dan Gohman087bd1e2010-03-03 05:29:13 +0000671 // Collect all the add operands in a loop, along with their associated loops.
672 // Iterate in reverse so that constants are emitted last, all else equal, and
673 // so that pointer operands are inserted first, which the code below relies on
674 // to form more involved GEPs.
675 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
676 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
677 E(S->op_begin()); I != E; ++I)
678 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
679 *I));
Dan Gohmanc70c3772009-09-26 16:11:57 +0000680
Dan Gohman087bd1e2010-03-03 05:29:13 +0000681 // Sort by loop. Use a stable sort so that constants follow non-constants and
682 // pointer operands precede non-pointer operands.
683 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman5be18e82009-05-19 02:15:55 +0000684
Dan Gohman087bd1e2010-03-03 05:29:13 +0000685 // Emit instructions to add all the operands. Hoist as much as possible
686 // out of loops, and form meaningful getelementptrs where possible.
687 Value *Sum = 0;
688 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
689 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
690 const Loop *CurLoop = I->first;
691 const SCEV *Op = I->second;
692 if (!Sum) {
693 // This is the first operand. Just expand it.
694 Sum = expand(Op);
695 ++I;
696 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
697 // The running sum expression is a pointer. Try to form a getelementptr
698 // at this level with that as the base.
699 SmallVector<const SCEV *, 4> NewOps;
700 for (; I != E && I->first == CurLoop; ++I)
701 NewOps.push_back(I->second);
702 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
703 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
704 // The running sum is an integer, and there's a pointer at this level.
705 // Try to form a getelementptr.
706 SmallVector<const SCEV *, 4> NewOps;
707 NewOps.push_back(SE.getUnknown(Sum));
708 for (++I; I != E && I->first == CurLoop; ++I)
709 NewOps.push_back(I->second);
710 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
711 } else if (isNonConstantNegative(Op)) {
712 // Instead of doing a negate and add, just do a subtract.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000713 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000714 Sum = InsertNoopCastOfTo(Sum, Ty);
715 Sum = InsertBinop(Instruction::Sub, Sum, W);
716 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000717 } else {
Dan Gohman087bd1e2010-03-03 05:29:13 +0000718 // A simple add.
Dan Gohmaned78dba2010-03-03 04:36:42 +0000719 Value *W = expandCodeFor(Op, Ty);
Dan Gohman087bd1e2010-03-03 05:29:13 +0000720 Sum = InsertNoopCastOfTo(Sum, Ty);
721 // Canonicalize a constant to the RHS.
722 if (isa<Constant>(Sum)) std::swap(Sum, W);
723 Sum = InsertBinop(Instruction::Add, Sum, W);
724 ++I;
Dan Gohmaned78dba2010-03-03 04:36:42 +0000725 }
726 }
Dan Gohman087bd1e2010-03-03 05:29:13 +0000727
728 return Sum;
Dan Gohmane24fa642008-06-18 16:37:11 +0000729}
Dan Gohman5be18e82009-05-19 02:15:55 +0000730
Dan Gohman890f92b2009-04-18 17:56:28 +0000731Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000732 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000733
Dan Gohman087bd1e2010-03-03 05:29:13 +0000734 // Collect all the mul operands in a loop, along with their associated loops.
735 // Iterate in reverse so that constants are emitted last, all else equal.
736 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
737 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
738 E(S->op_begin()); I != E; ++I)
739 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
740 *I));
Nate Begeman36f891b2005-07-30 00:12:19 +0000741
Dan Gohman087bd1e2010-03-03 05:29:13 +0000742 // Sort by loop. Use a stable sort so that constants follow non-constants.
743 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
744
745 // Emit instructions to mul all the operands. Hoist as much as possible
746 // out of loops.
747 Value *Prod = 0;
748 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
749 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
750 const SCEV *Op = I->second;
751 if (!Prod) {
752 // This is the first operand. Just expand it.
753 Prod = expand(Op);
754 ++I;
755 } else if (Op->isAllOnesValue()) {
756 // Instead of doing a multiply by negative one, just do a negate.
757 Prod = InsertNoopCastOfTo(Prod, Ty);
758 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
759 ++I;
760 } else {
761 // A simple mul.
762 Value *W = expandCodeFor(Op, Ty);
763 Prod = InsertNoopCastOfTo(Prod, Ty);
764 // Canonicalize a constant to the RHS.
765 if (isa<Constant>(Prod)) std::swap(Prod, W);
766 Prod = InsertBinop(Instruction::Mul, Prod, W);
767 ++I;
768 }
Dan Gohman2d1be872009-04-16 03:18:22 +0000769 }
770
Dan Gohman087bd1e2010-03-03 05:29:13 +0000771 return Prod;
Nate Begeman36f891b2005-07-30 00:12:19 +0000772}
773
Dan Gohman890f92b2009-04-18 17:56:28 +0000774Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000775 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman2d1be872009-04-16 03:18:22 +0000776
Dan Gohman92fcdca2009-06-09 17:18:38 +0000777 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman890f92b2009-04-18 17:56:28 +0000778 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky6177fd42008-07-08 05:05:37 +0000779 const APInt &RHS = SC->getValue()->getValue();
780 if (RHS.isPowerOf2())
781 return InsertBinop(Instruction::LShr, LHS,
Owen Andersoneed707b2009-07-24 23:12:02 +0000782 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky6177fd42008-07-08 05:05:37 +0000783 }
784
Dan Gohman92fcdca2009-06-09 17:18:38 +0000785 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +0000786 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000787}
788
Dan Gohman453aa4f2009-05-24 18:06:31 +0000789/// Move parts of Base into Rest to leave Base with the minimal
790/// expression that provides a pointer operand suitable for a
791/// GEP expansion.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000792static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman453aa4f2009-05-24 18:06:31 +0000793 ScalarEvolution &SE) {
794 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
795 Base = A->getStart();
796 Rest = SE.getAddExpr(Rest,
797 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
798 A->getStepRecurrence(SE),
799 A->getLoop()));
800 }
801 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
802 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000803 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman453aa4f2009-05-24 18:06:31 +0000804 NewAddOps.back() = Rest;
805 Rest = SE.getAddExpr(NewAddOps);
806 ExposePointerBase(Base, Rest, SE);
807 }
808}
809
Dan Gohmana10756e2010-01-21 02:09:26 +0000810/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
811/// the base addrec, which is the addrec without any non-loop-dominating
812/// values, and return the PHI.
813PHINode *
814SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
815 const Loop *L,
816 const Type *ExpandTy,
817 const Type *IntTy) {
818 // Reuse a previously-inserted PHI, if present.
819 for (BasicBlock::iterator I = L->getHeader()->begin();
820 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohman572645c2010-02-12 10:34:29 +0000821 if (SE.isSCEVable(PN->getType()) &&
822 (SE.getEffectiveSCEVType(PN->getType()) ==
823 SE.getEffectiveSCEVType(Normalized->getType())) &&
824 SE.getSCEV(PN) == Normalized)
825 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
Dan Gohman572645c2010-02-12 10:34:29 +0000826 Instruction *IncV =
Dan Gohman22e62192010-02-16 00:20:08 +0000827 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
828
829 // Determine if this is a well-behaved chain of instructions leading
830 // back to the PHI. It probably will be, if we're scanning an inner
831 // loop already visited by LSR for example, but it wouldn't have
832 // to be.
833 do {
834 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
835 IncV = 0;
836 break;
837 }
Dan Gohman9feae9f2010-02-17 02:39:31 +0000838 // If any of the operands don't dominate the insert position, bail.
839 // Addrec operands are always loop-invariant, so this can only happen
840 // if there are instructions which haven't been hoisted.
841 for (User::op_iterator OI = IncV->op_begin()+1,
842 OE = IncV->op_end(); OI != OE; ++OI)
843 if (Instruction *OInst = dyn_cast<Instruction>(OI))
844 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
845 IncV = 0;
846 break;
847 }
848 if (!IncV)
849 break;
850 // Advance to the next instruction.
Dan Gohman22e62192010-02-16 00:20:08 +0000851 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
852 if (!IncV)
853 break;
854 if (IncV->mayHaveSideEffects()) {
855 IncV = 0;
856 break;
857 }
858 } while (IncV != PN);
859
860 if (IncV) {
861 // Ok, the add recurrence looks usable.
862 // Remember this PHI, even in post-inc mode.
863 InsertedValues.insert(PN);
864 // Remember the increment.
865 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
866 rememberInstruction(IncV);
867 if (L == IVIncInsertLoop)
868 do {
869 if (SE.DT->dominates(IncV, IVIncInsertPos))
870 break;
871 // Make sure the increment is where we want it. But don't move it
872 // down past a potential existing post-inc user.
873 IncV->moveBefore(IVIncInsertPos);
874 IVIncInsertPos = IncV;
875 IncV = cast<Instruction>(IncV->getOperand(0));
876 } while (IncV != PN);
877 return PN;
878 }
Dan Gohman572645c2010-02-12 10:34:29 +0000879 }
Dan Gohmana10756e2010-01-21 02:09:26 +0000880
881 // Save the original insertion point so we can restore it when we're done.
882 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
883 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
884
885 // Expand code for the start value.
886 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
887 L->getHeader()->begin());
888
889 // Expand code for the step value. Insert instructions right before the
890 // terminator corresponding to the back-edge. Do this before creating the PHI
891 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
892 // negative, insert a sub instead of an add for the increment (unless it's a
893 // constant, because subtracts of constants are canonicalized to adds).
894 const SCEV *Step = Normalized->getStepRecurrence(SE);
Duncan Sands1df98592010-02-16 11:11:14 +0000895 bool isPointer = ExpandTy->isPointerTy();
Dan Gohmana10756e2010-01-21 02:09:26 +0000896 bool isNegative = !isPointer && isNonConstantNegative(Step);
897 if (isNegative)
898 Step = SE.getNegativeSCEV(Step);
899 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
900
901 // Create the PHI.
902 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
903 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
904 rememberInstruction(PN);
905
906 // Create the step instructions and populate the PHI.
907 BasicBlock *Header = L->getHeader();
908 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
909 HPI != HPE; ++HPI) {
910 BasicBlock *Pred = *HPI;
911
912 // Add a start value.
913 if (!L->contains(Pred)) {
914 PN->addIncoming(StartV, Pred);
915 continue;
916 }
917
918 // Create a step value and add it to the PHI. If IVIncInsertLoop is
919 // non-null and equal to the addrec's loop, insert the instructions
920 // at IVIncInsertPos.
921 Instruction *InsertPos = L == IVIncInsertLoop ?
922 IVIncInsertPos : Pred->getTerminator();
923 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
924 Value *IncV;
925 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
926 if (isPointer) {
927 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
928 // If the step isn't constant, don't use an implicitly scaled GEP, because
929 // that would require a multiply inside the loop.
930 if (!isa<ConstantInt>(StepV))
931 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
932 GEPPtrTy->getAddressSpace());
933 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
934 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
935 if (IncV->getType() != PN->getType()) {
936 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
937 rememberInstruction(IncV);
938 }
939 } else {
940 IncV = isNegative ?
941 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
942 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
943 rememberInstruction(IncV);
944 }
945 PN->addIncoming(IncV, Pred);
946 }
947
948 // Restore the original insert point.
949 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +0000950 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohmana10756e2010-01-21 02:09:26 +0000951
952 // Remember this PHI, even in post-inc mode.
953 InsertedValues.insert(PN);
954
955 return PN;
956}
957
958Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
959 const Type *STy = S->getType();
960 const Type *IntTy = SE.getEffectiveSCEVType(STy);
961 const Loop *L = S->getLoop();
962
963 // Determine a normalized form of this expression, which is the expression
964 // before any post-inc adjustment is made.
965 const SCEVAddRecExpr *Normalized = S;
966 if (L == PostIncLoop) {
967 const SCEV *Step = S->getStepRecurrence(SE);
968 Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step));
969 }
970
971 // Strip off any non-loop-dominating component from the addrec start.
972 const SCEV *Start = Normalized->getStart();
973 const SCEV *PostLoopOffset = 0;
974 if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
975 PostLoopOffset = Start;
976 Start = SE.getIntegerSCEV(0, Normalized->getType());
977 Normalized =
978 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
979 Normalized->getStepRecurrence(SE),
980 Normalized->getLoop()));
981 }
982
983 // Strip off any non-loop-dominating component from the addrec step.
984 const SCEV *Step = Normalized->getStepRecurrence(SE);
985 const SCEV *PostLoopScale = 0;
986 if (!Step->hasComputableLoopEvolution(L) &&
987 !Step->dominates(L->getHeader(), SE.DT)) {
988 PostLoopScale = Step;
989 Step = SE.getIntegerSCEV(1, Normalized->getType());
990 Normalized =
991 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
992 Normalized->getLoop()));
993 }
994
995 // Expand the core addrec. If we need post-loop scaling, force it to
996 // expand to an integer type to avoid the need for additional casting.
997 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
998 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
999
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001000 // Accommodate post-inc mode, if necessary.
Dan Gohmana10756e2010-01-21 02:09:26 +00001001 Value *Result;
1002 if (L != PostIncLoop)
1003 Result = PN;
1004 else {
1005 // In PostInc mode, use the post-incremented value.
1006 BasicBlock *LatchBlock = L->getLoopLatch();
1007 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1008 Result = PN->getIncomingValueForBlock(LatchBlock);
1009 }
1010
1011 // Re-apply any non-loop-dominating scale.
1012 if (PostLoopScale) {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001013 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001014 Result = Builder.CreateMul(Result,
1015 expandCodeFor(PostLoopScale, IntTy));
1016 rememberInstruction(Result);
1017 }
1018
1019 // Re-apply any non-loop-dominating offset.
1020 if (PostLoopOffset) {
1021 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1022 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1023 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1024 } else {
Dan Gohman0a799ab2010-02-12 20:39:25 +00001025 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohmana10756e2010-01-21 02:09:26 +00001026 Result = Builder.CreateAdd(Result,
1027 expandCodeFor(PostLoopOffset, IntTy));
1028 rememberInstruction(Result);
1029 }
1030 }
1031
1032 return Result;
1033}
1034
Dan Gohman890f92b2009-04-18 17:56:28 +00001035Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohmana10756e2010-01-21 02:09:26 +00001036 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1037
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001038 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman36f891b2005-07-30 00:12:19 +00001039 const Loop *L = S->getLoop();
Nate Begeman36f891b2005-07-30 00:12:19 +00001040
Dan Gohman4d8414f2009-06-13 16:25:49 +00001041 // First check for an existing canonical IV in a suitable type.
1042 PHINode *CanonicalIV = 0;
1043 if (PHINode *PN = L->getCanonicalInductionVariable())
1044 if (SE.isSCEVable(PN->getType()) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001045 SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
Dan Gohman4d8414f2009-06-13 16:25:49 +00001046 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1047 CanonicalIV = PN;
1048
1049 // Rewrite an AddRec in terms of the canonical induction variable, if
1050 // its type is more narrow.
1051 if (CanonicalIV &&
1052 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1053 SE.getTypeSizeInBits(Ty)) {
Dan Gohmanf3f1be62009-09-28 21:01:47 +00001054 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
1055 SmallVector<const SCEV *, 4> NewOps(Ops.size());
1056 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1057 NewOps[i] = SE.getAnyExtendExpr(Ops[i], CanonicalIV->getType());
1058 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
Dan Gohman267a3852009-06-27 21:18:18 +00001059 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1060 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman4d8414f2009-06-13 16:25:49 +00001061 BasicBlock::iterator NewInsertPt =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001062 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
Dan Gohman4d8414f2009-06-13 16:25:49 +00001063 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
1064 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1065 NewInsertPt);
Dan Gohman45598552010-02-15 00:21:43 +00001066 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman4d8414f2009-06-13 16:25:49 +00001067 return V;
1068 }
1069
Nate Begeman36f891b2005-07-30 00:12:19 +00001070 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001071 if (!S->getStart()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001072 const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
1073 SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
Dan Gohman246b2562007-10-22 18:31:58 +00001074 NewOps[0] = SE.getIntegerSCEV(0, Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001075 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001076
1077 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1078 // comments on expandAddToGEP for details.
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001079 const SCEV *Base = S->getStart();
1080 const SCEV *RestArray[1] = { Rest };
1081 // Dig into the expression to find the pointer base for a GEP.
1082 ExposePointerBase(Base, RestArray[0], SE);
1083 // If we found a pointer, expand the AddRec with a GEP.
1084 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1085 // Make sure the Base isn't something exotic, such as a multiplied
1086 // or divided pointer value. In those cases, the result type isn't
1087 // actually a pointer type.
1088 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1089 Value *StartV = expand(Base);
1090 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1091 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman453aa4f2009-05-24 18:06:31 +00001092 }
1093 }
1094
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001095 // Just do a normal add. Pre-expand the operands to suppress folding.
1096 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1097 SE.getUnknown(expand(Rest))));
Nate Begeman36f891b2005-07-30 00:12:19 +00001098 }
1099
1100 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +00001101 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +00001102 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohman4d8414f2009-06-13 16:25:49 +00001103 // If there's a canonical IV, just use it.
1104 if (CanonicalIV) {
1105 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1106 "IVs with types different from the canonical IV should "
1107 "already have been handled!");
1108 return CanonicalIV;
1109 }
1110
Nate Begeman36f891b2005-07-30 00:12:19 +00001111 // Create and insert the PHI node for the induction variable in the
1112 // specified loop.
1113 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +00001114 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmana10756e2010-01-21 02:09:26 +00001115 rememberInstruction(PN);
Nate Begeman36f891b2005-07-30 00:12:19 +00001116
Owen Andersoneed707b2009-07-24 23:12:02 +00001117 Constant *One = ConstantInt::get(Ty, 1);
Dan Gohman83d57742009-09-27 17:46:40 +00001118 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
1119 HPI != HPE; ++HPI)
1120 if (L->contains(*HPI)) {
Dan Gohman3abf9052010-01-19 22:26:02 +00001121 // Insert a unit add instruction right before the terminator
1122 // corresponding to the back-edge.
Dan Gohman83d57742009-09-27 17:46:40 +00001123 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
1124 (*HPI)->getTerminator());
Dan Gohmana10756e2010-01-21 02:09:26 +00001125 rememberInstruction(Add);
Dan Gohman83d57742009-09-27 17:46:40 +00001126 PN->addIncoming(Add, *HPI);
1127 } else {
1128 PN->addIncoming(Constant::getNullValue(Ty), *HPI);
1129 }
Nate Begeman36f891b2005-07-30 00:12:19 +00001130 }
1131
Dan Gohman4d8414f2009-06-13 16:25:49 +00001132 // {0,+,F} --> {0,+,1} * F
Nate Begeman36f891b2005-07-30 00:12:19 +00001133 // Get the canonical induction variable I for this loop.
Dan Gohman4d8414f2009-06-13 16:25:49 +00001134 Value *I = CanonicalIV ?
1135 CanonicalIV :
1136 getOrInsertCanonicalInductionVariable(L, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +00001137
Chris Lattnerdf14a042005-10-30 06:24:33 +00001138 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001139 if (S->isAffine()) // {0,+,F} --> i*F
1140 return
1141 expand(SE.getTruncateOrNoop(
1142 SE.getMulExpr(SE.getUnknown(I),
1143 SE.getNoopOrAnyExtend(S->getOperand(1),
1144 I->getType())),
1145 Ty));
Nate Begeman36f891b2005-07-30 00:12:19 +00001146
1147 // If this is a chain of recurrences, turn it into a closed form, using the
1148 // folders, then expandCodeFor the closed form. This allows the folders to
1149 // simplify the expression without having to build a bunch of special code
1150 // into this folder.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001151 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +00001152
Dan Gohman4d8414f2009-06-13 16:25:49 +00001153 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001154 const SCEV *NewS = S;
1155 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
Dan Gohman4d8414f2009-06-13 16:25:49 +00001156 if (isa<SCEVAddRecExpr>(Ext))
1157 NewS = Ext;
1158
Dan Gohman0bba49c2009-07-07 17:06:11 +00001159 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +00001160 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +00001161
Dan Gohman4d8414f2009-06-13 16:25:49 +00001162 // Truncate the result down to the original type, if needed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001163 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohman469f3cd2009-06-22 22:08:45 +00001164 return expand(T);
Nate Begeman36f891b2005-07-30 00:12:19 +00001165}
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001166
Dan Gohman890f92b2009-04-18 17:56:28 +00001167Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001168 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001169 Value *V = expandCodeFor(S->getOperand(),
1170 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001171 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001172 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001173 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001174}
1175
Dan Gohman890f92b2009-04-18 17:56:28 +00001176Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001177 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001178 Value *V = expandCodeFor(S->getOperand(),
1179 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001180 Value *I = Builder.CreateZExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001181 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001182 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001183}
1184
Dan Gohman890f92b2009-04-18 17:56:28 +00001185Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001186 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman92fcdca2009-06-09 17:18:38 +00001187 Value *V = expandCodeFor(S->getOperand(),
1188 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Dan Gohman267a3852009-06-27 21:18:18 +00001189 Value *I = Builder.CreateSExt(V, Ty, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001190 rememberInstruction(I);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001191 return I;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001192}
1193
Dan Gohman890f92b2009-04-18 17:56:28 +00001194Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001195 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1196 const Type *Ty = LHS->getType();
1197 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1198 // In the case of mixed integer and pointer types, do the
1199 // rest of the comparisons as integer.
1200 if (S->getOperand(i)->getType() != Ty) {
1201 Ty = SE.getEffectiveSCEVType(Ty);
1202 LHS = InsertNoopCastOfTo(LHS, Ty);
1203 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001204 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001205 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001206 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001207 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001208 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001209 LHS = Sel;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001210 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001211 // In the case of mixed integer and pointer types, cast the
1212 // final result back to the pointer type.
1213 if (LHS->getType() != S->getType())
1214 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001215 return LHS;
1216}
1217
Dan Gohman890f92b2009-04-18 17:56:28 +00001218Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman0196dc52009-07-14 20:57:04 +00001219 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1220 const Type *Ty = LHS->getType();
1221 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1222 // In the case of mixed integer and pointer types, do the
1223 // rest of the comparisons as integer.
1224 if (S->getOperand(i)->getType() != Ty) {
1225 Ty = SE.getEffectiveSCEVType(Ty);
1226 LHS = InsertNoopCastOfTo(LHS, Ty);
1227 }
Dan Gohman92fcdca2009-06-09 17:18:38 +00001228 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Dan Gohman267a3852009-06-27 21:18:18 +00001229 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
Dan Gohmana10756e2010-01-21 02:09:26 +00001230 rememberInstruction(ICmp);
Dan Gohman267a3852009-06-27 21:18:18 +00001231 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohmana10756e2010-01-21 02:09:26 +00001232 rememberInstruction(Sel);
Dan Gohmancf5ab822009-05-01 17:13:31 +00001233 LHS = Sel;
Nick Lewycky3e630762008-02-20 06:48:22 +00001234 }
Dan Gohman0196dc52009-07-14 20:57:04 +00001235 // In the case of mixed integer and pointer types, cast the
1236 // final result back to the pointer type.
1237 if (LHS->getType() != S->getType())
1238 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky3e630762008-02-20 06:48:22 +00001239 return LHS;
1240}
1241
Dan Gohman0bba49c2009-07-07 17:06:11 +00001242Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001243 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +00001244 Value *V = expand(SH);
Dan Gohman5be18e82009-05-19 02:15:55 +00001245 if (Ty) {
1246 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1247 "non-trivial casts should be done with the SCEVs directly!");
1248 V = InsertNoopCastOfTo(V, Ty);
1249 }
1250 return V;
Dan Gohman11f6d3b2008-06-22 19:09:18 +00001251}
1252
Dan Gohman890f92b2009-04-18 17:56:28 +00001253Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001254 // Compute an insertion point for this SCEV object. Hoist the instructions
1255 // as far out in the loop nest as possible.
Dan Gohman267a3852009-06-27 21:18:18 +00001256 Instruction *InsertPt = Builder.GetInsertPoint();
1257 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001258 L = L->getParentLoop())
1259 if (S->isLoopInvariant(L)) {
1260 if (!L) break;
1261 if (BasicBlock *Preheader = L->getLoopPreheader())
1262 InsertPt = Preheader->getTerminator();
1263 } else {
1264 // If the SCEV is computable at this level, insert it into the header
1265 // after the PHIs (and after any other instructions that we've inserted
1266 // there) so that it is guaranteed to dominate any user inside the loop.
Dan Gohman069d6f32010-03-02 01:59:21 +00001267 if (L && S->hasComputableLoopEvolution(L) && L != PostIncLoop)
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001268 InsertPt = L->getHeader()->getFirstNonPHI();
Dan Gohman267a3852009-06-27 21:18:18 +00001269 while (isInsertedInstruction(InsertPt))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001270 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001271 break;
1272 }
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001273
Dan Gohman667d7872009-06-26 22:53:46 +00001274 // Check to see if we already expanded this here.
1275 std::map<std::pair<const SCEV *, Instruction *>,
1276 AssertingVH<Value> >::iterator I =
1277 InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman267a3852009-06-27 21:18:18 +00001278 if (I != InsertedExpressions.end())
Dan Gohman667d7872009-06-26 22:53:46 +00001279 return I->second;
Dan Gohman267a3852009-06-27 21:18:18 +00001280
1281 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1282 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1283 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohman667d7872009-06-26 22:53:46 +00001284
1285 // Expand the expression into instructions.
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001286 Value *V = visit(S);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001287
Dan Gohman667d7872009-06-26 22:53:46 +00001288 // Remember the expanded value for this SCEV at this location.
Dan Gohmana10756e2010-01-21 02:09:26 +00001289 if (!PostIncLoop)
1290 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Dan Gohman667d7872009-06-26 22:53:46 +00001291
Dan Gohman45598552010-02-15 00:21:43 +00001292 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Anton Korobeynikov96fea332007-08-20 21:17:26 +00001293 return V;
1294}
Dan Gohman1d09de32009-06-05 16:35:53 +00001295
Dan Gohman1d826a72010-02-14 03:12:47 +00001296void SCEVExpander::rememberInstruction(Value *I) {
1297 if (!PostIncLoop)
1298 InsertedValues.insert(I);
1299
1300 // If we just claimed an existing instruction and that instruction had
1301 // been the insert point, adjust the insert point forward so that
1302 // subsequently inserted code will be dominated.
1303 if (Builder.GetInsertPoint() == I) {
1304 BasicBlock::iterator It = cast<Instruction>(I);
1305 do { ++It; } while (isInsertedInstruction(It));
1306 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1307 }
1308}
1309
Dan Gohman45598552010-02-15 00:21:43 +00001310void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
Dan Gohman3f46a3a2010-03-01 17:49:51 +00001311 // If we acquired more instructions since the old insert point was saved,
Dan Gohman45598552010-02-15 00:21:43 +00001312 // advance past them.
1313 while (isInsertedInstruction(I)) ++I;
1314
1315 Builder.SetInsertPoint(BB, I);
1316}
1317
Dan Gohman1d09de32009-06-05 16:35:53 +00001318/// getOrInsertCanonicalInductionVariable - This method returns the
1319/// canonical induction variable of the specified type for the specified
1320/// loop (inserting one if there is none). A canonical induction variable
1321/// starts at zero and steps by one on each iteration.
1322Value *
1323SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1324 const Type *Ty) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001325 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman0bba49c2009-07-07 17:06:11 +00001326 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001327 SE.getIntegerSCEV(1, Ty), L);
Dan Gohman267a3852009-06-27 21:18:18 +00001328 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1329 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001330 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
Dan Gohman267a3852009-06-27 21:18:18 +00001331 if (SaveInsertBB)
Dan Gohman45598552010-02-15 00:21:43 +00001332 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00001333 return V;
Dan Gohman1d09de32009-06-05 16:35:53 +00001334}