blob: b5070434d14dbbd7e34b65a6b3a8314b63c3dfe8 [file] [log] [blame]
Nate Begeman2bca4d92005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Begeman2bca4d92005-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 Begeman2bca4d92005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallSet.h"
Bill Wendlingf3baad32006-12-07 01:30:32 +000019#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000020#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/LLVMContext.h"
Andrew Trick7fb669a2011-10-07 23:46:21 +000025#include "llvm/Support/Debug.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000026
Nate Begeman2bca4d92005-07-30 00:12:19 +000027using namespace llvm;
28
Gabor Greif8e66a422010-07-09 16:42:04 +000029/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000030/// reusing an existing cast if a suitable one exists, moving an existing
31/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000032/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000033Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000034 Instruction::CastOps Op,
35 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000036 // This function must be called with the builder having a valid insertion
37 // point. It doesn't need to be the actual IP where the uses of the returned
38 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000039 // We use this precondition to produce a cast that will dominate all its
40 // uses. In particular, this is crucial for the case where the builder's
41 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000042 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000043 // where the uses will be added (only that it dominates it), we are
44 // not allowed to move it.
45 BasicBlock::iterator BIP = Builder.GetInsertPoint();
46
Craig Topper9f008862014-04-15 04:59:12 +000047 Instruction *Ret = nullptr;
Rafael Espindola82d95752012-02-18 17:22:58 +000048
Dan Gohmand2772462010-06-19 13:25:23 +000049 // Check to see if there is already a cast!
Chandler Carruthcdf47882014-03-09 03:16:01 +000050 for (User *U : V->users())
Gabor Greif3b740e92010-07-09 16:39:02 +000051 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000052 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000053 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000054 // If the cast isn't where we want it, create a new cast at IP.
55 // Likewise, do not reuse a cast at BIP because it must dominate
56 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000057 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000058 // Create a new cast, and leave the old cast in place in case
59 // it is being used as an insert point. Clear its operand
60 // so that it doesn't hold anything live.
Rafael Espindola09a42012012-02-27 02:13:03 +000061 Ret = CastInst::Create(Op, V, Ty, "", IP);
62 Ret->takeName(CI);
63 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000064 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000065 break;
Dan Gohmand2772462010-06-19 13:25:23 +000066 }
Rafael Espindola09a42012012-02-27 02:13:03 +000067 Ret = CI;
68 break;
Dan Gohmand2772462010-06-19 13:25:23 +000069 }
70
71 // Create a new cast.
Rafael Espindola09a42012012-02-27 02:13:03 +000072 if (!Ret)
73 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
74
75 // We assert at the end of the function since IP might point to an
76 // instruction with different dominance properties than a cast
77 // (an invoke for example) and not dominate BIP (but the cast does).
78 assert(SE.DT->dominates(Ret, BIP));
79
80 rememberInstruction(Ret);
81 return Ret;
Dan Gohmand2772462010-06-19 13:25:23 +000082}
83
Dan Gohman830fd382009-06-27 21:18:18 +000084/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
85/// which must be possible with a noop cast, doing what we can to share
86/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +000087Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +000088 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
89 assert((Op == Instruction::BitCast ||
90 Op == Instruction::PtrToInt ||
91 Op == Instruction::IntToPtr) &&
92 "InsertNoopCastOfTo cannot perform non-noop casts!");
93 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
94 "InsertNoopCastOfTo cannot change sizes!");
95
Dan Gohman0a40ad92009-04-16 03:18:22 +000096 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +000097 if (Op == Instruction::BitCast) {
98 if (V->getType() == Ty)
99 return V;
100 if (CastInst *CI = dyn_cast<CastInst>(V)) {
101 if (CI->getOperand(0)->getType() == Ty)
102 return CI->getOperand(0);
103 }
104 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000105 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000106 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000107 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000108 if (CastInst *CI = dyn_cast<CastInst>(V))
109 if ((CI->getOpcode() == Instruction::PtrToInt ||
110 CI->getOpcode() == Instruction::IntToPtr) &&
111 SE.getTypeSizeInBits(CI->getType()) ==
112 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
113 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000114 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
115 if ((CE->getOpcode() == Instruction::PtrToInt ||
116 CE->getOpcode() == Instruction::IntToPtr) &&
117 SE.getTypeSizeInBits(CE->getType()) ==
118 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
119 return CE->getOperand(0);
120 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000121
Dan Gohmand2772462010-06-19 13:25:23 +0000122 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000123 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000124 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000125
Dan Gohmand2772462010-06-19 13:25:23 +0000126 // Cast the argument at the beginning of the entry block, after
127 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000128 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000129 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
130 while ((isa<BitCastInst>(IP) &&
131 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
132 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000133 isa<DbgInfoIntrinsic>(IP) ||
134 isa<LandingPadInst>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000135 ++IP;
136 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000137 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000138
Dan Gohmand2772462010-06-19 13:25:23 +0000139 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000140 Instruction *I = cast<Instruction>(V);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000141 BasicBlock::iterator IP = I; ++IP;
142 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
143 IP = II->getNormalDest()->begin();
Rafael Espindola82d95752012-02-18 17:22:58 +0000144 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000145 ++IP;
Dan Gohmand2772462010-06-19 13:25:23 +0000146 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000147}
148
Chris Lattnere71f1442007-04-13 05:04:18 +0000149/// InsertBinop - Insert the specified binary operator, doing a small amount
150/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000151Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
152 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000153 // Fold a binop with constant operands.
154 if (Constant *CLHS = dyn_cast<Constant>(LHS))
155 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000156 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000157
Chris Lattnere71f1442007-04-13 05:04:18 +0000158 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
159 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000160 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
161 // Scanning starts from the last instruction before the insertion point.
162 BasicBlock::iterator IP = Builder.GetInsertPoint();
163 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000164 --IP;
165 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000166 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
167 // generated code.
168 if (isa<DbgInfoIntrinsic>(IP))
169 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000170 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
171 IP->getOperand(1) == RHS)
172 return IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000173 if (IP == BlockBegin) break;
174 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000175 }
Dan Gohman830fd382009-06-27 21:18:18 +0000176
Dan Gohman29707de2010-03-03 05:29:13 +0000177 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000178 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
179 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000180
181 // Move the insertion point out of as many loops as we can.
182 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
183 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
184 BasicBlock *Preheader = L->getLoopPreheader();
185 if (!Preheader) break;
186
187 // Ok, move up a level.
188 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
189 }
190
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000191 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000192 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000193 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000194 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000195
Dan Gohmand195a222009-05-01 17:13:31 +0000196 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000197}
198
Dan Gohman17893622009-05-27 02:00:53 +0000199/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000200/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000201/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000202/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000203/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
204/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
205/// check to see if the divide was folded.
Dan Gohmanaf752342009-07-07 17:06:11 +0000206static bool FactorOutConstant(const SCEV *&S,
207 const SCEV *&Remainder,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000208 const SCEV *Factor,
209 ScalarEvolution &SE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000210 const DataLayout *DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000211 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000212 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000213 return true;
214
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000215 // x/x == 1.
216 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000217 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000218 return true;
219 }
220
Dan Gohman291c2e02009-05-24 18:06:31 +0000221 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000222 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000223 // 0/x == 0.
224 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000225 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000226 // Check for divisibility.
227 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
228 ConstantInt *CI =
229 ConstantInt::get(SE.getContext(),
230 C->getValue()->getValue().sdiv(
231 FC->getValue()->getValue()));
232 // If the quotient is zero and the remainder is non-zero, reject
233 // the value at this scale. It will be considered for subsequent
234 // smaller scales.
235 if (!CI->isZero()) {
236 const SCEV *Div = SE.getConstant(CI);
237 S = Div;
238 Remainder =
239 SE.getAddExpr(Remainder,
240 SE.getConstant(C->getValue()->getValue().srem(
241 FC->getValue()->getValue())));
242 return true;
243 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000244 }
Dan Gohman17893622009-05-27 02:00:53 +0000245 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000246
247 // In a Mul, check if there is a constant operand which is a multiple
248 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000249 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000250 if (DL) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000251 // With DataLayout, the size is known. Check if there is a constant
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000252 // operand which is a multiple of the given factor. If so, we can
253 // factor it.
254 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
255 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
256 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
Dan Gohman00524492010-03-18 01:17:13 +0000257 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000258 NewMulOps[0] =
259 SE.getConstant(C->getValue()->getValue().sdiv(
260 FC->getValue()->getValue()));
261 S = SE.getMulExpr(NewMulOps);
262 return true;
263 }
264 } else {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000265 // Without DataLayout, check if Factor can be factored out of any of the
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000266 // Mul's operands. If so, we can just remove it.
267 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
268 const SCEV *SOp = M->getOperand(i);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000269 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000270 if (FactorOutConstant(SOp, Remainder, Factor, SE, DL) &&
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000271 Remainder->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +0000272 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000273 NewMulOps[i] = SOp;
274 S = SE.getMulExpr(NewMulOps);
275 return true;
276 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000277 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000278 }
279 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000280
281 // In an AddRec, check if both start and step are divisible.
282 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000283 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000284 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000285 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000286 return false;
287 if (!StepRem->isZero())
288 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000289 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000290 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000291 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000292 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
293 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000294 return true;
295 }
296
297 return false;
298}
299
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000300/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
301/// is the number of SCEVAddRecExprs present, which are kept at the end of
302/// the list.
303///
304static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000305 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000306 ScalarEvolution &SE) {
307 unsigned NumAddRecs = 0;
308 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
309 ++NumAddRecs;
310 // Group Ops into non-addrecs and addrecs.
311 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
312 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
313 // Let ScalarEvolution sort and simplify the non-addrecs list.
314 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000315 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000316 SE.getAddExpr(NoAddRecs);
317 // If it returned an add, use the operands. Otherwise it simplified
318 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000319 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000320 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000321 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000322 else if (!Sum->isZero())
323 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000324 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000325 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000326}
327
328/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
329/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
330/// This helps expose more opportunities for folding parts of the expressions
331/// into GEP indices.
332///
333static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000334 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000335 ScalarEvolution &SE) {
336 // Find the addrecs.
337 SmallVector<const SCEV *, 8> AddRecs;
338 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
339 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
340 const SCEV *Start = A->getStart();
341 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000342 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000343 AddRecs.push_back(SE.getAddRecExpr(Zero,
344 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000345 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000346 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000347 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
348 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000349 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000350 e += Add->getNumOperands();
351 } else {
352 Ops[i] = Start;
353 }
354 }
355 if (!AddRecs.empty()) {
356 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000357 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000358 // Resort the operand list, moving any constants to the front.
359 SimplifyAddOperands(Ops, Ty, SE);
360 }
361}
362
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000363/// expandAddToGEP - Expand an addition expression with a pointer type into
364/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
365/// BasicAliasAnalysis and other passes analyze the result. See the rules
366/// for getelementptr vs. inttoptr in
367/// http://llvm.org/docs/LangRef.html#pointeraliasing
368/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000369///
Dan Gohman510bffc2010-01-19 22:26:02 +0000370/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000371/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
372/// they may introduce pointer arithmetic which may not be safely converted
373/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000374///
375/// Design note: It might seem desirable for this function to be more
376/// loop-aware. If some of the indices are loop-invariant while others
377/// aren't, it might seem desirable to emit multiple GEPs, keeping the
378/// loop-invariant portions of the overall computation outside the loop.
379/// However, there are a few reasons this is not done here. Hoisting simple
380/// arithmetic is a low-level optimization that often isn't very
381/// important until late in the optimization process. In fact, passes
382/// like InstructionCombining will combine GEPs, even if it means
383/// pushing loop-invariant computation down into loops, so even if the
384/// GEPs were split here, the work would quickly be undone. The
385/// LoopStrengthReduction pass, which is usually run quite late (and
386/// after the last InstructionCombining pass), takes care of hoisting
387/// loop-invariant portions of expressions, after considering what
388/// can be folded using target addressing modes.
389///
Dan Gohmanaf752342009-07-07 17:06:11 +0000390Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
391 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000392 PointerType *PTy,
393 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000394 Value *V) {
Chris Lattner229907c2011-07-18 04:54:35 +0000395 Type *ElTy = PTy->getElementType();
Dan Gohman26494912009-05-19 02:15:55 +0000396 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000397 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000398 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000399
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000400 // Split AddRecs up into parts as either of the parts may be usable
401 // without the other.
402 SplitAddRecs(Ops, Ty, SE);
403
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000404 Type *IntPtrTy = SE.DL
405 ? SE.DL->getIntPtrType(PTy)
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000406 : Type::getInt64Ty(PTy->getContext());
407
Bob Wilson2107eb72009-12-04 01:33:04 +0000408 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000409 // operands into GEP indices, at each level. The first index in a GEP
410 // indexes into the array implied by the pointer operand; the rest of
411 // the indices index into the element or field type selected by the
412 // preceding index.
413 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000414 // If the scale size is not 0, attempt to factor out a scale for
415 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000416 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000417 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000418 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000419 if (!ElSize->isZero()) {
420 SmallVector<const SCEV *, 8> NewOps;
421 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
422 const SCEV *Op = Ops[i];
Dan Gohman1d2ded72010-05-03 22:09:21 +0000423 const SCEV *Remainder = SE.getConstant(Ty, 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000424 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000425 // Op now has ElSize factored out.
426 ScaledOps.push_back(Op);
427 if (!Remainder->isZero())
428 NewOps.push_back(Remainder);
429 AnyNonZeroIndices = true;
430 } else {
431 // The operand was not divisible, so add it to the list of operands
432 // we'll scan next iteration.
433 NewOps.push_back(Ops[i]);
434 }
Dan Gohman26494912009-05-19 02:15:55 +0000435 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000436 // If we made any changes, update Ops.
437 if (!ScaledOps.empty()) {
438 Ops = NewOps;
439 SimplifyAddOperands(Ops, Ty, SE);
440 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000441 }
Dan Gohman26494912009-05-19 02:15:55 +0000442 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000443
444 // Record the scaled array index for this level of the type. If
445 // we didn't find any operands that could be factored, tentatively
446 // assume that element zero was selected (since the zero offset
447 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000448 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000449 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000450 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
451 GepIndices.push_back(Scaled);
452
453 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000454 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000455 bool FoundFieldNo = false;
456 // An empty struct has no fields.
457 if (STy->getNumElements() == 0) break;
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000458 if (SE.DL) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000459 // With DataLayout, field offsets are known. See if a constant offset
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000460 // falls within any of the struct fields.
461 if (Ops.empty()) break;
Dan Gohman26494912009-05-19 02:15:55 +0000462 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
463 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000464 const StructLayout &SL = *SE.DL->getStructLayout(STy);
Dan Gohman26494912009-05-19 02:15:55 +0000465 uint64_t FullOffset = C->getValue()->getZExtValue();
466 if (FullOffset < SL.getSizeInBytes()) {
467 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
Owen Anderson55f1c092009-08-13 21:58:54 +0000468 GepIndices.push_back(
469 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
Dan Gohman26494912009-05-19 02:15:55 +0000470 ElTy = STy->getTypeAtIndex(ElIdx);
471 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000472 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Dan Gohman26494912009-05-19 02:15:55 +0000473 AnyNonZeroIndices = true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000474 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000475 }
476 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000477 } else {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000478 // Without DataLayout, just check for an offsetof expression of the
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000479 // appropriate struct type.
480 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmancf913832010-01-28 02:15:55 +0000481 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
Chris Lattner229907c2011-07-18 04:54:35 +0000482 Type *CTy;
Dan Gohmancf913832010-01-28 02:15:55 +0000483 Constant *FieldNo;
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000484 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
Dan Gohmancf913832010-01-28 02:15:55 +0000485 GepIndices.push_back(FieldNo);
486 ElTy =
487 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000488 Ops[i] = SE.getConstant(Ty, 0);
489 AnyNonZeroIndices = true;
490 FoundFieldNo = true;
491 break;
492 }
Dan Gohmancf913832010-01-28 02:15:55 +0000493 }
Dan Gohman26494912009-05-19 02:15:55 +0000494 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000495 // If no struct field offsets were found, tentatively assume that
496 // field zero was selected (since the zero offset would obviously
497 // be folded away).
498 if (!FoundFieldNo) {
499 ElTy = STy->getTypeAtIndex(0u);
500 GepIndices.push_back(
501 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
502 }
Dan Gohman26494912009-05-19 02:15:55 +0000503 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000504
Chris Lattner229907c2011-07-18 04:54:35 +0000505 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000506 ElTy = ATy->getElementType();
507 else
508 break;
Dan Gohman26494912009-05-19 02:15:55 +0000509 }
510
Dan Gohman8b0a4192010-03-01 17:49:51 +0000511 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000512 // the base to i8* and do an ugly getelementptr with that. It's still
513 // better than ptrtoint+arithmetic+inttoptr at least.
514 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000515 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000516 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000517 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000518
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000519 assert(!isa<Instruction>(V) ||
Rafael Espindola94df2672012-02-26 02:19:19 +0000520 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000521
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000522 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000523 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000524
525 // Fold a GEP with constant operands.
526 if (Constant *CLHS = dyn_cast<Constant>(V))
527 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaded8db7d2011-07-21 14:31:17 +0000528 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000529
530 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
531 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000532 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
533 // Scanning starts from the last instruction before the insertion point.
534 BasicBlock::iterator IP = Builder.GetInsertPoint();
535 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000536 --IP;
537 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000538 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
539 // generated code.
540 if (isa<DbgInfoIntrinsic>(IP))
541 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000542 if (IP->getOpcode() == Instruction::GetElementPtr &&
543 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
544 return IP;
545 if (IP == BlockBegin) break;
546 }
547 }
548
Dan Gohman29707de2010-03-03 05:29:13 +0000549 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000550 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000551
552 // Move the insertion point out of as many loops as we can.
553 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
554 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
555 BasicBlock *Preheader = L->getLoopPreheader();
556 if (!Preheader) break;
557
558 // Ok, move up a level.
559 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
560 }
561
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000562 // Emit a GEP.
563 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000564 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000565
Dan Gohman26494912009-05-19 02:15:55 +0000566 return GEP;
567 }
568
Dan Gohman29707de2010-03-03 05:29:13 +0000569 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000570 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
Dan Gohman29707de2010-03-03 05:29:13 +0000571
572 // Move the insertion point out of as many loops as we can.
573 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
574 if (!L->isLoopInvariant(V)) break;
575
576 bool AnyIndexNotLoopInvariant = false;
577 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
578 E = GepIndices.end(); I != E; ++I)
579 if (!L->isLoopInvariant(*I)) {
580 AnyIndexNotLoopInvariant = true;
581 break;
582 }
583 if (AnyIndexNotLoopInvariant)
584 break;
585
586 BasicBlock *Preheader = L->getLoopPreheader();
587 if (!Preheader) break;
588
589 // Ok, move up a level.
590 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
591 }
592
Dan Gohman31a9b982009-07-28 01:40:03 +0000593 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
594 // because ScalarEvolution may have changed the address arithmetic to
595 // compute a value which is beyond the end of the allocated object.
Dan Gohman51ad99d2010-01-21 02:09:26 +0000596 Value *Casted = V;
597 if (V->getType() != PTy)
598 Casted = InsertNoopCastOfTo(Casted, PTy);
599 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad040dd822011-07-22 08:16:57 +0000600 GepIndices,
Dan Gohman830fd382009-06-27 21:18:18 +0000601 "scevgep");
Dan Gohman26494912009-05-19 02:15:55 +0000602 Ops.push_back(SE.getUnknown(GEP));
Dan Gohman51ad99d2010-01-21 02:09:26 +0000603 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000604
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000605 // Restore the original insert point.
606 Builder.restoreIP(SaveInsertPt);
607
Dan Gohman26494912009-05-19 02:15:55 +0000608 return expand(SE.getAddExpr(Ops));
609}
610
Dan Gohman29707de2010-03-03 05:29:13 +0000611/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
612/// SCEV expansion. If they are nested, this is the most nested. If they are
613/// neighboring, pick the later.
614static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
615 DominatorTree &DT) {
616 if (!A) return B;
617 if (!B) return A;
618 if (A->contains(B)) return B;
619 if (B->contains(A)) return A;
620 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
621 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
622 return A; // Arbitrarily break the tie.
623}
624
Dan Gohman8ea83d82010-11-18 00:34:22 +0000625/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000626/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000627const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
628 // Test whether we've already computed the most relevant loop for this SCEV.
629 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
Craig Topper9f008862014-04-15 04:59:12 +0000630 RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000631 if (!Pair.second)
632 return Pair.first->second;
633
Dan Gohman29707de2010-03-03 05:29:13 +0000634 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000635 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000636 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000637 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
638 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000639 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
640 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000641 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000642 }
643 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000644 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000645 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
646 L = AR->getLoop();
647 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
648 I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000649 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
650 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000651 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000652 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
653 const Loop *Result = getRelevantLoop(C->getOperand());
654 return RelevantLoops[C] = Result;
655 }
656 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
657 const Loop *Result =
658 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
659 getRelevantLoop(D->getRHS()),
660 *SE.DT);
661 return RelevantLoops[D] = Result;
662 }
Dan Gohman29707de2010-03-03 05:29:13 +0000663 llvm_unreachable("Unexpected SCEV type!");
664}
665
Dan Gohmanb29cda92010-04-15 17:08:50 +0000666namespace {
667
Dan Gohman29707de2010-03-03 05:29:13 +0000668/// LoopCompare - Compare loops by PickMostRelevantLoop.
669class LoopCompare {
670 DominatorTree &DT;
671public:
672 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
673
674 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
675 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000676 // Keep pointer operands sorted at the end.
677 if (LHS.second->getType()->isPointerTy() !=
678 RHS.second->getType()->isPointerTy())
679 return LHS.second->getType()->isPointerTy();
680
Dan Gohman29707de2010-03-03 05:29:13 +0000681 // Compare loops with PickMostRelevantLoop.
682 if (LHS.first != RHS.first)
683 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
684
685 // If one operand is a non-constant negative and the other is not,
686 // put the non-constant negative on the right so that a sub can
687 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000688 if (LHS.second->isNonConstantNegative()) {
689 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000690 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000691 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000692 return true;
693
694 // Otherwise they are equivalent according to this comparison.
695 return false;
696 }
697};
698
Dan Gohmanb29cda92010-04-15 17:08:50 +0000699}
700
Dan Gohman056857a2009-04-18 17:56:28 +0000701Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000702 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000703
Dan Gohman29707de2010-03-03 05:29:13 +0000704 // Collect all the add operands in a loop, along with their associated loops.
705 // Iterate in reverse so that constants are emitted last, all else equal, and
706 // so that pointer operands are inserted first, which the code below relies on
707 // to form more involved GEPs.
708 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
709 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
710 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000711 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000712
Dan Gohman29707de2010-03-03 05:29:13 +0000713 // Sort by loop. Use a stable sort so that constants follow non-constants and
714 // pointer operands precede non-pointer operands.
715 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000716
Dan Gohman29707de2010-03-03 05:29:13 +0000717 // Emit instructions to add all the operands. Hoist as much as possible
718 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000719 Value *Sum = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000720 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
721 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
722 const Loop *CurLoop = I->first;
723 const SCEV *Op = I->second;
724 if (!Sum) {
725 // This is the first operand. Just expand it.
726 Sum = expand(Op);
727 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000728 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000729 // The running sum expression is a pointer. Try to form a getelementptr
730 // at this level with that as the base.
731 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000732 for (; I != E && I->first == CurLoop; ++I) {
733 // If the operand is SCEVUnknown and not instructions, peek through
734 // it, to enable more of it to be folded into the GEP.
735 const SCEV *X = I->second;
736 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
737 if (!isa<Instruction>(U->getValue()))
738 X = SE.getSCEV(U->getValue());
739 NewOps.push_back(X);
740 }
Dan Gohman29707de2010-03-03 05:29:13 +0000741 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000742 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000743 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000744 // Try to form a getelementptr. If the running sum is instructions,
745 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000746 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000747 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
748 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000749 for (++I; I != E && I->first == CurLoop; ++I)
750 NewOps.push_back(I->second);
751 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000752 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000753 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000754 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000755 Sum = InsertNoopCastOfTo(Sum, Ty);
756 Sum = InsertBinop(Instruction::Sub, Sum, W);
757 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000758 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000759 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000760 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000761 Sum = InsertNoopCastOfTo(Sum, Ty);
762 // Canonicalize a constant to the RHS.
763 if (isa<Constant>(Sum)) std::swap(Sum, W);
764 Sum = InsertBinop(Instruction::Add, Sum, W);
765 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000766 }
767 }
Dan Gohman29707de2010-03-03 05:29:13 +0000768
769 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000770}
Dan Gohman26494912009-05-19 02:15:55 +0000771
Dan Gohman056857a2009-04-18 17:56:28 +0000772Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000773 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000774
Dan Gohman29707de2010-03-03 05:29:13 +0000775 // Collect all the mul operands in a loop, along with their associated loops.
776 // Iterate in reverse so that constants are emitted last, all else equal.
777 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
778 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
779 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000780 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000781
Dan Gohman29707de2010-03-03 05:29:13 +0000782 // Sort by loop. Use a stable sort so that constants follow non-constants.
783 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
784
785 // Emit instructions to mul all the operands. Hoist as much as possible
786 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000787 Value *Prod = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000788 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
789 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
790 const SCEV *Op = I->second;
791 if (!Prod) {
792 // This is the first operand. Just expand it.
793 Prod = expand(Op);
794 ++I;
795 } else if (Op->isAllOnesValue()) {
796 // Instead of doing a multiply by negative one, just do a negate.
797 Prod = InsertNoopCastOfTo(Prod, Ty);
798 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
799 ++I;
800 } else {
801 // A simple mul.
802 Value *W = expandCodeFor(Op, Ty);
803 Prod = InsertNoopCastOfTo(Prod, Ty);
804 // Canonicalize a constant to the RHS.
805 if (isa<Constant>(Prod)) std::swap(Prod, W);
806 Prod = InsertBinop(Instruction::Mul, Prod, W);
807 ++I;
808 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000809 }
810
Dan Gohman29707de2010-03-03 05:29:13 +0000811 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000812}
813
Dan Gohman056857a2009-04-18 17:56:28 +0000814Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000815 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000816
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000817 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000818 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky3c947042008-07-08 05:05:37 +0000819 const APInt &RHS = SC->getValue()->getValue();
820 if (RHS.isPowerOf2())
821 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000822 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000823 }
824
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000825 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000826 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000827}
828
Dan Gohman291c2e02009-05-24 18:06:31 +0000829/// Move parts of Base into Rest to leave Base with the minimal
830/// expression that provides a pointer operand suitable for a
831/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000832static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000833 ScalarEvolution &SE) {
834 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
835 Base = A->getStart();
836 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000837 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000838 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000839 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000840 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000841 }
842 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
843 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000844 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000845 NewAddOps.back() = Rest;
846 Rest = SE.getAddExpr(NewAddOps);
847 ExposePointerBase(Base, Rest, SE);
848 }
849}
850
Andrew Trick7fb669a2011-10-07 23:46:21 +0000851/// Determine if this is a well-behaved chain of instructions leading back to
852/// the PHI. If so, it may be reused by expanded expressions.
853bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
854 const Loop *L) {
855 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
856 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
857 return false;
858 // If any of the operands don't dominate the insert position, bail.
859 // Addrec operands are always loop-invariant, so this can only happen
860 // if there are instructions which haven't been hoisted.
861 if (L == IVIncInsertLoop) {
862 for (User::op_iterator OI = IncV->op_begin()+1,
863 OE = IncV->op_end(); OI != OE; ++OI)
864 if (Instruction *OInst = dyn_cast<Instruction>(OI))
865 if (!SE.DT->dominates(OInst, IVIncInsertPos))
866 return false;
867 }
868 // Advance to the next instruction.
869 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
870 if (!IncV)
871 return false;
872
873 if (IncV->mayHaveSideEffects())
874 return false;
875
876 if (IncV != PN)
877 return true;
878
879 return isNormalAddRecExprPHI(PN, IncV, L);
880}
881
Andrew Trickc908b432012-01-20 07:41:13 +0000882/// getIVIncOperand returns an induction variable increment's induction
883/// variable operand.
884///
885/// If allowScale is set, any type of GEP is allowed as long as the nonIV
886/// operands dominate InsertPos.
887///
888/// If allowScale is not set, ensure that a GEP increment conforms to one of the
889/// simple patterns generated by getAddRecExprPHILiterally and
890/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
891Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
892 Instruction *InsertPos,
893 bool allowScale) {
894 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000895 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000896
897 switch (IncV->getOpcode()) {
898 default:
Craig Topper9f008862014-04-15 04:59:12 +0000899 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000900 // Check for a simple Add/Sub or GEP of a loop invariant step.
901 case Instruction::Add:
902 case Instruction::Sub: {
903 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindola94df2672012-02-26 02:19:19 +0000904 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000905 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000906 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000907 }
908 case Instruction::BitCast:
909 return dyn_cast<Instruction>(IncV->getOperand(0));
910 case Instruction::GetElementPtr:
911 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
912 I != E; ++I) {
913 if (isa<Constant>(*I))
914 continue;
915 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000916 if (!SE.DT->dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000917 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000918 }
919 if (allowScale) {
920 // allow any kind of GEP as long as it can be hoisted.
921 continue;
922 }
923 // This must be a pointer addition of constants (pretty), which is already
924 // handled, or some number of address-size elements (ugly). Ugly geps
925 // have 2 operands. i1* is used by the expander to represent an
926 // address-size element.
927 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000928 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000929 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
930 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
931 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000932 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000933 break;
934 }
935 return dyn_cast<Instruction>(IncV->getOperand(0));
936 }
937}
938
939/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
940/// it available to other uses in this loop. Recursively hoist any operands,
941/// until we reach a value that dominates InsertPos.
942bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000943 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000944 return true;
945
946 // InsertPos must itself dominate IncV so that IncV's new position satisfies
947 // its existing users.
Andrew Tricka7a3de12012-05-22 17:39:59 +0000948 if (isa<PHINode>(InsertPos)
949 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000950 return false;
951
952 // Check that the chain of IV operands leading back to Phi can be hoisted.
953 SmallVector<Instruction*, 4> IVIncs;
954 for(;;) {
955 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
956 if (!Oper)
957 return false;
958 // IncV is safe to hoist.
959 IVIncs.push_back(IncV);
960 IncV = Oper;
Rafael Espindola94df2672012-02-26 02:19:19 +0000961 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000962 break;
963 }
964 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
965 E = IVIncs.rend(); I != E; ++I) {
966 (*I)->moveBefore(InsertPos);
967 }
968 return true;
969}
970
Andrew Trick7fb669a2011-10-07 23:46:21 +0000971/// Determine if this cyclic phi is in a form that would have been generated by
972/// LSR. We don't care if the phi was actually expanded in this pass, as long
973/// as it is in a low-cost form, for example, no implied multiplication. This
974/// should match any patterns generated by getAddRecExprPHILiterally and
975/// expandAddtoGEP.
976bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000977 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000978 for(Instruction *IVOper = IncV;
979 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
980 /*allowScale=*/false));) {
981 if (IVOper == PN)
982 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000983 }
Andrew Trickc908b432012-01-20 07:41:13 +0000984 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000985}
986
Andrew Trickceafa2c2011-11-30 06:07:54 +0000987/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
988/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
989/// need to materialize IV increments elsewhere to handle difficult situations.
990Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
991 Type *ExpandTy, Type *IntTy,
992 bool useSubtract) {
993 Value *IncV;
994 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
995 if (ExpandTy->isPointerTy()) {
996 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
997 // If the step isn't constant, don't use an implicitly scaled GEP, because
998 // that would require a multiply inside the loop.
999 if (!isa<ConstantInt>(StepV))
1000 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
1001 GEPPtrTy->getAddressSpace());
1002 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
1003 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
1004 if (IncV->getType() != PN->getType()) {
1005 IncV = Builder.CreateBitCast(IncV, PN->getType());
1006 rememberInstruction(IncV);
1007 }
1008 } else {
1009 IncV = useSubtract ?
1010 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1011 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1012 rememberInstruction(IncV);
1013 }
1014 return IncV;
1015}
1016
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001017/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
1018/// position. This routine assumes that this is possible (has been checked).
1019static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1020 Instruction *Pos, PHINode *LoopPhi) {
1021 do {
1022 if (DT->dominates(InstToHoist, Pos))
1023 break;
1024 // Make sure the increment is where we want it. But don't move it
1025 // down past a potential existing post-inc user.
1026 InstToHoist->moveBefore(Pos);
1027 Pos = InstToHoist;
1028 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1029 } while (InstToHoist != LoopPhi);
1030}
1031
1032/// \brief Check whether we can cheaply express the requested SCEV in terms of
1033/// the available PHI SCEV by truncation and/or invertion of the step.
1034static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1035 const SCEVAddRecExpr *Phi,
1036 const SCEVAddRecExpr *Requested,
1037 bool &InvertStep) {
1038 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1039 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1040
1041 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1042 return false;
1043
1044 // Try truncate it if necessary.
1045 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1046 if (!Phi)
1047 return false;
1048
1049 // Check whether truncation will help.
1050 if (Phi == Requested) {
1051 InvertStep = false;
1052 return true;
1053 }
1054
1055 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1056 if (SE.getAddExpr(Requested->getStart(),
1057 SE.getNegativeSCEV(Requested)) == Phi) {
1058 InvertStep = true;
1059 return true;
1060 }
1061
1062 return false;
1063}
1064
Dan Gohman51ad99d2010-01-21 02:09:26 +00001065/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1066/// the base addrec, which is the addrec without any non-loop-dominating
1067/// values, and return the PHI.
1068PHINode *
1069SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1070 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001071 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001072 Type *IntTy,
1073 Type *&TruncTy,
1074 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001075 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001076
Dan Gohman51ad99d2010-01-21 02:09:26 +00001077 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001078 BasicBlock *LatchBlock = L->getLoopLatch();
1079 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001080 PHINode *AddRecPhiMatch = nullptr;
1081 Instruction *IncV = nullptr;
1082 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001083 InvertStep = false;
1084
1085 // Only try partially matching scevs that need truncation and/or
1086 // step-inversion if we know this loop is outside the current loop.
1087 bool TryNonMatchingSCEV = IVIncInsertLoop &&
1088 SE.DT->properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1089
Andrew Trick7fb669a2011-10-07 23:46:21 +00001090 for (BasicBlock::iterator I = L->getHeader()->begin();
1091 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001092 if (!SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001093 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001094
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001095 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1096 if (!PhiSCEV)
1097 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001098
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001099 bool IsMatchingSCEV = PhiSCEV == Normalized;
1100 // We only handle truncation and inversion of phi recurrences for the
1101 // expanded expression if the expanded expression's loop dominates the
1102 // loop we insert to. Check now, so we can bail out early.
1103 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1104 continue;
1105
1106 Instruction *TempIncV =
1107 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1108
1109 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001110 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001111 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001112 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001113 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1114 continue;
1115 } else {
1116 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001117 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001118 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001119
1120 // Stop if we have found an exact match SCEV.
1121 if (IsMatchingSCEV) {
1122 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001123 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001124 InvertStep = false;
1125 AddRecPhiMatch = PN;
1126 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001127 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001128
1129 // Try whether the phi can be translated into the requested form
1130 // (truncated and/or offset by a constant).
1131 if ((!TruncTy || InvertStep) &&
1132 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1133 // Record the phi node. But don't stop we might find an exact match
1134 // later.
1135 AddRecPhiMatch = PN;
1136 IncV = TempIncV;
1137 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1138 }
1139 }
1140
1141 if (AddRecPhiMatch) {
1142 // Potentially, move the increment. We have made sure in
1143 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1144 if (L == IVIncInsertLoop)
1145 hoistBeforePos(SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1146
Andrew Trick7fb669a2011-10-07 23:46:21 +00001147 // Ok, the add recurrence looks usable.
1148 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001149 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001150 // Remember the increment.
1151 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001152 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001153 }
1154 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001155
1156 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001157 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001158
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001159 // Another AddRec may need to be recursively expanded below. For example, if
1160 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1161 // loop. Remove this loop from the PostIncLoops set before expanding such
1162 // AddRecs. Otherwise, we cannot find a valid position for the step
1163 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1164 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1165 // so it's not worth implementing SmallPtrSet::swap.
1166 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1167 PostIncLoops.clear();
1168
Dan Gohman51ad99d2010-01-21 02:09:26 +00001169 // Expand code for the start value.
1170 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1171 L->getHeader()->begin());
1172
Andrew Trick244e2c32011-07-16 00:59:39 +00001173 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001174 assert(!isa<Instruction>(StartV) ||
1175 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1176 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001177
Andrew Trickceafa2c2011-11-30 06:07:54 +00001178 // Expand code for the step value. Do this before creating the PHI so that PHI
1179 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001180 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001181 // If the stride is negative, insert a sub instead of an add for the increment
1182 // (unless it's a constant, because subtracts of constants are canonicalized
1183 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001184 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001185 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001186 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001187 // Expand the step somewhere that dominates the loop header.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001188 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1189
1190 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001191 BasicBlock *Header = L->getHeader();
1192 Builder.SetInsertPoint(Header, Header->begin());
1193 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001194 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001195 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001196 rememberInstruction(PN);
1197
1198 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001199 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001200 BasicBlock *Pred = *HPI;
1201
1202 // Add a start value.
1203 if (!L->contains(Pred)) {
1204 PN->addIncoming(StartV, Pred);
1205 continue;
1206 }
1207
Andrew Trickceafa2c2011-11-30 06:07:54 +00001208 // Create a step value and add it to the PHI.
1209 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1210 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001211 Instruction *InsertPos = L == IVIncInsertLoop ?
1212 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001213 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001214 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Andrew Trick8eaae282013-07-14 02:50:07 +00001215 if (isa<OverflowingBinaryOperator>(IncV)) {
1216 if (Normalized->getNoWrapFlags(SCEV::FlagNUW))
1217 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1218 if (Normalized->getNoWrapFlags(SCEV::FlagNSW))
1219 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1220 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001221 PN->addIncoming(IncV, Pred);
1222 }
1223
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001224 // After expanding subexpressions, restore the PostIncLoops set so the caller
1225 // can ensure that IVIncrement dominates the current uses.
1226 PostIncLoops = SavedPostIncLoops;
1227
Dan Gohman51ad99d2010-01-21 02:09:26 +00001228 // Remember this PHI, even in post-inc mode.
1229 InsertedValues.insert(PN);
1230
1231 return PN;
1232}
1233
1234Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001235 Type *STy = S->getType();
1236 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001237 const Loop *L = S->getLoop();
1238
1239 // Determine a normalized form of this expression, which is the expression
1240 // before any post-inc adjustment is made.
1241 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001242 if (PostIncLoops.count(L)) {
1243 PostIncLoopSet Loops;
1244 Loops.insert(L);
1245 Normalized =
Craig Topper9f008862014-04-15 04:59:12 +00001246 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
1247 nullptr, Loops, SE, *SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001248 }
1249
1250 // Strip off any non-loop-dominating component from the addrec start.
1251 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001252 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001253 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001254 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001255 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001256 Normalized = cast<SCEVAddRecExpr>(
1257 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1258 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001259 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001260 }
1261
1262 // Strip off any non-loop-dominating component from the addrec step.
1263 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001264 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001265 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001266 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001267 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001268 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001269 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1270 Start, Step, Normalized->getLoop(),
1271 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001272 }
1273
1274 // Expand the core addrec. If we need post-loop scaling, force it to
1275 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001276 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001277 // In some cases, we decide to reuse an existing phi node but need to truncate
1278 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001279 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001280 bool InvertStep = false;
1281 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1282 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001283
Dan Gohman8b0a4192010-03-01 17:49:51 +00001284 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001285 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001286 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001287 Result = PN;
1288 else {
1289 // In PostInc mode, use the post-incremented value.
1290 BasicBlock *LatchBlock = L->getLoopLatch();
1291 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1292 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001293
1294 // For an expansion to use the postinc form, the client must call
1295 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1296 // or dominated by IVIncInsertPos.
Andrew Trickceafa2c2011-11-30 06:07:54 +00001297 if (isa<Instruction>(Result)
1298 && !SE.DT->dominates(cast<Instruction>(Result),
1299 Builder.GetInsertPoint())) {
1300 // The induction variable's postinc expansion does not dominate this use.
1301 // IVUsers tries to prevent this case, so it is rare. However, it can
1302 // happen when an IVUser outside the loop is not dominated by the latch
1303 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1304 // all cases. Consider a phi outide whose operand is replaced during
1305 // expansion with the value of the postinc user. Without fundamentally
1306 // changing the way postinc users are tracked, the only remedy is
1307 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1308 // but hopefully expandCodeFor handles that.
1309 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001310 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001311 if (useSubtract)
1312 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001313 Value *StepV;
1314 {
1315 // Expand the step somewhere that dominates the loop header.
1316 BuilderType::InsertPointGuard Guard(Builder);
1317 StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1318 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001319 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1320 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001321 }
1322
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001323 // We have decided to reuse an induction variable of a dominating loop. Apply
1324 // truncation and/or invertion of the step.
1325 if (TruncTy) {
1326 Type *ResTy = Result->getType();
1327 // Normalize the result type.
1328 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1329 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1330 // Truncate the result.
1331 if (TruncTy != Result->getType()) {
1332 Result = Builder.CreateTrunc(Result, TruncTy);
1333 rememberInstruction(Result);
1334 }
1335 // Invert the result.
1336 if (InvertStep) {
1337 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1338 Result);
1339 rememberInstruction(Result);
1340 }
1341 }
1342
Dan Gohman51ad99d2010-01-21 02:09:26 +00001343 // Re-apply any non-loop-dominating scale.
1344 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001345 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001346 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001347 Result = Builder.CreateMul(Result,
1348 expandCodeFor(PostLoopScale, IntTy));
1349 rememberInstruction(Result);
1350 }
1351
1352 // Re-apply any non-loop-dominating offset.
1353 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001354 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001355 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1356 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1357 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001358 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001359 Result = Builder.CreateAdd(Result,
1360 expandCodeFor(PostLoopOffset, IntTy));
1361 rememberInstruction(Result);
1362 }
1363 }
1364
1365 return Result;
1366}
1367
Dan Gohman056857a2009-04-18 17:56:28 +00001368Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001369 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1370
Chris Lattner229907c2011-07-18 04:54:35 +00001371 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001372 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001373
Dan Gohman426901a2009-06-13 16:25:49 +00001374 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001375 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001376 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001377 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001378 CanonicalIV = PN;
1379
1380 // Rewrite an AddRec in terms of the canonical induction variable, if
1381 // its type is more narrow.
1382 if (CanonicalIV &&
1383 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1384 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001385 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1386 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1387 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001388 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001389 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman426901a2009-06-13 16:25:49 +00001390 BasicBlock::iterator NewInsertPt =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001391 std::next(BasicBlock::iterator(cast<Instruction>(V)));
Benjamin Kramer6e931522013-09-30 15:40:17 +00001392 BuilderType::InsertPointGuard Guard(Builder);
Bill Wendling86c5cbe2011-08-24 21:06:46 +00001393 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1394 isa<LandingPadInst>(NewInsertPt))
Jim Grosbachfd3b4e72010-06-16 21:13:38 +00001395 ++NewInsertPt;
Craig Topper9f008862014-04-15 04:59:12 +00001396 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Dan Gohman426901a2009-06-13 16:25:49 +00001397 NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001398 return V;
1399 }
1400
Nate Begeman2bca4d92005-07-30 00:12:19 +00001401 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001402 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001403 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001404 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001405 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1406 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001407
1408 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1409 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001410 const SCEV *Base = S->getStart();
1411 const SCEV *RestArray[1] = { Rest };
1412 // Dig into the expression to find the pointer base for a GEP.
1413 ExposePointerBase(Base, RestArray[0], SE);
1414 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001415 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001416 // Make sure the Base isn't something exotic, such as a multiplied
1417 // or divided pointer value. In those cases, the result type isn't
1418 // actually a pointer type.
1419 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1420 Value *StartV = expand(Base);
1421 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1422 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001423 }
1424 }
1425
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001426 // Just do a normal add. Pre-expand the operands to suppress folding.
1427 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1428 SE.getUnknown(expand(Rest))));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001429 }
1430
Dan Gohmancd838702010-07-26 18:28:14 +00001431 // If we don't yet have a canonical IV, create one.
1432 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001433 // Create and insert the PHI node for the induction variable in the
1434 // specified loop.
1435 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001436 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001437 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1438 Header->begin());
Dan Gohmancd838702010-07-26 18:28:14 +00001439 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001440
Hal Finkel3f5279c2013-08-18 00:16:23 +00001441 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001442 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001443 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001444 BasicBlock *HP = *HPI;
Hal Finkel3f5279c2013-08-18 00:16:23 +00001445 if (!PredSeen.insert(HP))
1446 continue;
1447
Gabor Greife82532a2010-07-09 15:40:10 +00001448 if (L->contains(HP)) {
Dan Gohman510bffc2010-01-19 22:26:02 +00001449 // Insert a unit add instruction right before the terminator
1450 // corresponding to the back-edge.
Dan Gohmancd838702010-07-26 18:28:14 +00001451 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1452 "indvar.next",
1453 HP->getTerminator());
Devang Patelccf8dbf2011-06-22 20:56:56 +00001454 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
Dan Gohman51ad99d2010-01-21 02:09:26 +00001455 rememberInstruction(Add);
Dan Gohmancd838702010-07-26 18:28:14 +00001456 CanonicalIV->addIncoming(Add, HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001457 } else {
Dan Gohmancd838702010-07-26 18:28:14 +00001458 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
Dan Gohman2aab8672009-09-27 17:46:40 +00001459 }
Gabor Greife82532a2010-07-09 15:40:10 +00001460 }
Nate Begeman2bca4d92005-07-30 00:12:19 +00001461 }
1462
Dan Gohmancd838702010-07-26 18:28:14 +00001463 // {0,+,1} --> Insert a canonical induction variable into the loop!
1464 if (S->isAffine() && S->getOperand(1)->isOne()) {
1465 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1466 "IVs with types different from the canonical IV should "
1467 "already have been handled!");
1468 return CanonicalIV;
1469 }
1470
Dan Gohman426901a2009-06-13 16:25:49 +00001471 // {0,+,F} --> {0,+,1} * F
Nate Begeman2bca4d92005-07-30 00:12:19 +00001472
Chris Lattnerf0b77f92005-10-30 06:24:33 +00001473 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001474 if (S->isAffine()) // {0,+,F} --> i*F
1475 return
1476 expand(SE.getTruncateOrNoop(
Dan Gohmancd838702010-07-26 18:28:14 +00001477 SE.getMulExpr(SE.getUnknown(CanonicalIV),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001478 SE.getNoopOrAnyExtend(S->getOperand(1),
Dan Gohmancd838702010-07-26 18:28:14 +00001479 CanonicalIV->getType())),
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001480 Ty));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001481
1482 // If this is a chain of recurrences, turn it into a closed form, using the
1483 // folders, then expandCodeFor the closed form. This allows the folders to
1484 // simplify the expression without having to build a bunch of special code
1485 // into this folder.
Dan Gohmancd838702010-07-26 18:28:14 +00001486 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
Nate Begeman2bca4d92005-07-30 00:12:19 +00001487
Dan Gohman426901a2009-06-13 16:25:49 +00001488 // Promote S up to the canonical IV type, if the cast is foldable.
Dan Gohmanaf752342009-07-07 17:06:11 +00001489 const SCEV *NewS = S;
Dan Gohmancd838702010-07-26 18:28:14 +00001490 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
Dan Gohman426901a2009-06-13 16:25:49 +00001491 if (isa<SCEVAddRecExpr>(Ext))
1492 NewS = Ext;
1493
Dan Gohmanaf752342009-07-07 17:06:11 +00001494 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
Bill Wendlingf3baad32006-12-07 01:30:32 +00001495 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman2bca4d92005-07-30 00:12:19 +00001496
Dan Gohman426901a2009-06-13 16:25:49 +00001497 // Truncate the result down to the original type, if needed.
Dan Gohmanaf752342009-07-07 17:06:11 +00001498 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
Dan Gohmanfd761132009-06-22 22:08:45 +00001499 return expand(T);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001500}
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001501
Dan Gohman056857a2009-04-18 17:56:28 +00001502Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001503 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001504 Value *V = expandCodeFor(S->getOperand(),
1505 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001506 Value *I = Builder.CreateTrunc(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001507 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001508 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001509}
1510
Dan Gohman056857a2009-04-18 17:56:28 +00001511Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001512 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001513 Value *V = expandCodeFor(S->getOperand(),
1514 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001515 Value *I = Builder.CreateZExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001516 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001517 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001518}
1519
Dan Gohman056857a2009-04-18 17:56:28 +00001520Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001521 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001522 Value *V = expandCodeFor(S->getOperand(),
1523 SE.getEffectiveSCEVType(S->getOperand()->getType()));
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001524 Value *I = Builder.CreateSExt(V, Ty);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001525 rememberInstruction(I);
Dan Gohmand195a222009-05-01 17:13:31 +00001526 return I;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001527}
1528
Dan Gohman056857a2009-04-18 17:56:28 +00001529Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001530 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001531 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001532 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1533 // In the case of mixed integer and pointer types, do the
1534 // rest of the comparisons as integer.
1535 if (S->getOperand(i)->getType() != Ty) {
1536 Ty = SE.getEffectiveSCEVType(Ty);
1537 LHS = InsertNoopCastOfTo(LHS, Ty);
1538 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001539 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001540 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001541 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001542 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001543 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001544 LHS = Sel;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001545 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001546 // In the case of mixed integer and pointer types, cast the
1547 // final result back to the pointer type.
1548 if (LHS->getType() != S->getType())
1549 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00001550 return LHS;
1551}
1552
Dan Gohman056857a2009-04-18 17:56:28 +00001553Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
Dan Gohman92b969b2009-07-14 20:57:04 +00001554 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
Chris Lattner229907c2011-07-18 04:54:35 +00001555 Type *Ty = LHS->getType();
Dan Gohman92b969b2009-07-14 20:57:04 +00001556 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1557 // In the case of mixed integer and pointer types, do the
1558 // rest of the comparisons as integer.
1559 if (S->getOperand(i)->getType() != Ty) {
1560 Ty = SE.getEffectiveSCEVType(Ty);
1561 LHS = InsertNoopCastOfTo(LHS, Ty);
1562 }
Dan Gohmanb8597bd2009-06-09 17:18:38 +00001563 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001564 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001565 rememberInstruction(ICmp);
Dan Gohman830fd382009-06-27 21:18:18 +00001566 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001567 rememberInstruction(Sel);
Dan Gohmand195a222009-05-01 17:13:31 +00001568 LHS = Sel;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001569 }
Dan Gohman92b969b2009-07-14 20:57:04 +00001570 // In the case of mixed integer and pointer types, cast the
1571 // final result back to the pointer type.
1572 if (LHS->getType() != S->getType())
1573 LHS = InsertNoopCastOfTo(LHS, S->getType());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001574 return LHS;
1575}
1576
Chris Lattner229907c2011-07-18 04:54:35 +00001577Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
Andrew Trickc908b432012-01-20 07:41:13 +00001578 Instruction *IP) {
Dan Gohman89d4e3c2010-03-19 21:51:03 +00001579 Builder.SetInsertPoint(IP->getParent(), IP);
1580 return expandCodeFor(SH, Ty);
1581}
1582
Chris Lattner229907c2011-07-18 04:54:35 +00001583Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
Dan Gohman0e4cf892008-06-22 19:09:18 +00001584 // Expand the code for this SCEV.
Dan Gohman0a40ad92009-04-16 03:18:22 +00001585 Value *V = expand(SH);
Dan Gohman26494912009-05-19 02:15:55 +00001586 if (Ty) {
1587 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1588 "non-trivial casts should be done with the SCEVs directly!");
1589 V = InsertNoopCastOfTo(V, Ty);
1590 }
1591 return V;
Dan Gohman0e4cf892008-06-22 19:09:18 +00001592}
1593
Dan Gohman056857a2009-04-18 17:56:28 +00001594Value *SCEVExpander::expand(const SCEV *S) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001595 // Compute an insertion point for this SCEV object. Hoist the instructions
1596 // as far out in the loop nest as possible.
Dan Gohman830fd382009-06-27 21:18:18 +00001597 Instruction *InsertPt = Builder.GetInsertPoint();
1598 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001599 L = L->getParentLoop())
Dan Gohmanafd6db92010-11-17 21:23:15 +00001600 if (SE.isLoopInvariant(S, L)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001601 if (!L) break;
Dan Gohmandcddd572010-03-23 21:53:22 +00001602 if (BasicBlock *Preheader = L->getLoopPreheader())
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001603 InsertPt = Preheader->getTerminator();
Andrew Trickcbcc98f2012-01-02 21:25:10 +00001604 else {
1605 // LSR sets the insertion point for AddRec start/step values to the
1606 // block start to simplify value reuse, even though it's an invalid
1607 // position. SCEVExpander must correct for this in all cases.
1608 InsertPt = L->getHeader()->getFirstInsertionPt();
1609 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001610 } else {
1611 // If the SCEV is computable at this level, insert it into the header
1612 // after the PHIs (and after any other instructions that we've inserted
1613 // there) so that it is guaranteed to dominate any user inside the loop.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001614 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1615 InsertPt = L->getHeader()->getFirstInsertionPt();
Andrew Trickc908b432012-01-20 07:41:13 +00001616 while (InsertPt != Builder.GetInsertPoint()
1617 && (isInsertedInstruction(InsertPt)
1618 || isa<DbgInfoIntrinsic>(InsertPt))) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001619 InsertPt = std::next(BasicBlock::iterator(InsertPt));
Andrew Trickc908b432012-01-20 07:41:13 +00001620 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001621 break;
1622 }
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001623
Dan Gohmandaafbe62009-06-26 22:53:46 +00001624 // Check to see if we already expanded this here.
Andrew Trickd4e1b5e2013-01-14 21:00:37 +00001625 std::map<std::pair<const SCEV *, Instruction *>, TrackingVH<Value> >::iterator
1626 I = InsertedExpressions.find(std::make_pair(S, InsertPt));
Dan Gohman830fd382009-06-27 21:18:18 +00001627 if (I != InsertedExpressions.end())
Dan Gohmandaafbe62009-06-26 22:53:46 +00001628 return I->second;
Dan Gohman830fd382009-06-27 21:18:18 +00001629
Benjamin Kramer6e931522013-09-30 15:40:17 +00001630 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman830fd382009-06-27 21:18:18 +00001631 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
Dan Gohmandaafbe62009-06-26 22:53:46 +00001632
1633 // Expand the expression into instructions.
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001634 Value *V = visit(S);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001635
Dan Gohmandaafbe62009-06-26 22:53:46 +00001636 // Remember the expanded value for this SCEV at this location.
Andrew Trick870c1a32011-10-13 21:55:29 +00001637 //
1638 // This is independent of PostIncLoops. The mapped value simply materializes
1639 // the expression at this insertion point. If the mapped value happened to be
Alp Tokerf907b892013-12-05 05:44:44 +00001640 // a postinc expansion, it could be reused by a non-postinc user, but only if
Andrew Trick870c1a32011-10-13 21:55:29 +00001641 // its insertion point was already at the head of the loop.
1642 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
Anton Korobeynikov5849a622007-08-20 21:17:26 +00001643 return V;
1644}
Dan Gohman63964b52009-06-05 16:35:53 +00001645
Dan Gohman6b751732010-02-14 03:12:47 +00001646void SCEVExpander::rememberInstruction(Value *I) {
Dan Gohmanbbfb6ac2010-06-05 00:33:07 +00001647 if (!PostIncLoops.empty())
1648 InsertedPostIncValues.insert(I);
1649 else
Dan Gohman6b751732010-02-14 03:12:47 +00001650 InsertedValues.insert(I);
Dan Gohman6b751732010-02-14 03:12:47 +00001651}
1652
Dan Gohman63964b52009-06-05 16:35:53 +00001653/// getOrInsertCanonicalInductionVariable - This method returns the
1654/// canonical induction variable of the specified type for the specified
1655/// loop (inserting one if there is none). A canonical induction variable
1656/// starts at zero and steps by one on each iteration.
Dan Gohman4fd92432010-07-20 16:44:52 +00001657PHINode *
Dan Gohman63964b52009-06-05 16:35:53 +00001658SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001659 Type *Ty) {
Duncan Sands9dff9be2010-02-15 16:12:20 +00001660 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
Dan Gohman31158752010-07-20 16:46:58 +00001661
1662 // Build a SCEV for {0,+,1}<L>.
Andrew Trick8b55b732011-03-14 16:50:06 +00001663 // Conservatively use FlagAnyWrap for now.
Dan Gohman1d2ded72010-05-03 22:09:21 +00001664 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
Andrew Trick8b55b732011-03-14 16:50:06 +00001665 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
Dan Gohman31158752010-07-20 16:46:58 +00001666
1667 // Emit code for it.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001668 BuilderType::InsertPointGuard Guard(Builder);
Craig Topper9f008862014-04-15 04:59:12 +00001669 PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
1670 L->getHeader()->begin()));
Dan Gohman31158752010-07-20 16:46:58 +00001671
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001672 return V;
Dan Gohman63964b52009-06-05 16:35:53 +00001673}
Andrew Trickf9201c52011-10-11 02:28:51 +00001674
Andrew Trickf9201c52011-10-11 02:28:51 +00001675/// replaceCongruentIVs - Check for congruent phis in this loop header and
1676/// replace them with their most canonical representative. Return the number of
1677/// phis eliminated.
1678///
1679/// This does not depend on any SCEVExpander state but should be used in
1680/// the same context that SCEVExpander is used.
1681unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001682 SmallVectorImpl<WeakVH> &DeadInsts,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001683 const TargetTransformInfo *TTI) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001684 // Find integer phis in order of increasing width.
1685 SmallVector<PHINode*, 8> Phis;
1686 for (BasicBlock::iterator I = L->getHeader()->begin();
1687 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1688 Phis.push_back(Phi);
1689 }
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001690 if (TTI)
Benjamin Kramerb0f74b22014-03-07 21:35:39 +00001691 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1692 // Put pointers at the back and make sure pointer < pointer = false.
1693 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1694 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1695 return RHS->getType()->getPrimitiveSizeInBits() <
1696 LHS->getType()->getPrimitiveSizeInBits();
1697 });
Andrew Trick5adedf52012-01-07 01:12:09 +00001698
Andrew Trickf9201c52011-10-11 02:28:51 +00001699 unsigned NumElim = 0;
1700 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
Andrew Trick5adedf52012-01-07 01:12:09 +00001701 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1702 // so narrow phis can reuse them.
1703 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1704 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1705 PHINode *Phi = *PIter;
1706
Benjamin Kramera225ed82012-10-19 16:37:30 +00001707 // Fold constant phis. They may be congruent to other constant phis and
1708 // would confuse the logic below that expects proper IVs.
1709 if (Value *V = Phi->hasConstantValue()) {
1710 Phi->replaceAllUsesWith(V);
1711 DeadInsts.push_back(Phi);
1712 ++NumElim;
1713 DEBUG_WITH_TYPE(DebugType, dbgs()
1714 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1715 continue;
1716 }
1717
Andrew Trickf9201c52011-10-11 02:28:51 +00001718 if (!SE.isSCEVable(Phi->getType()))
1719 continue;
1720
1721 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1722 if (!OrigPhiRef) {
1723 OrigPhiRef = Phi;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001724 if (Phi->getType()->isIntegerTy() && TTI
1725 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
Andrew Trick5adedf52012-01-07 01:12:09 +00001726 // This phi can be freely truncated to the narrowest phi type. Map the
1727 // truncated expression to it so it will be reused for narrow types.
1728 const SCEV *TruncExpr =
1729 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1730 ExprToIVMap[TruncExpr] = Phi;
1731 }
Andrew Trickf9201c52011-10-11 02:28:51 +00001732 continue;
1733 }
1734
Andrew Trick5adedf52012-01-07 01:12:09 +00001735 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1736 // sense.
1737 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
Andrew Trickf9201c52011-10-11 02:28:51 +00001738 continue;
1739
1740 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1741 Instruction *OrigInc =
1742 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1743 Instruction *IsomorphicInc =
1744 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1745
Andrew Trick5adedf52012-01-07 01:12:09 +00001746 // If this phi has the same width but is more canonical, replace the
Andrew Trickc908b432012-01-20 07:41:13 +00001747 // original with it. As part of the "more canonical" determination,
1748 // respect a prior decision to use an IV chain.
Andrew Trick5adedf52012-01-07 01:12:09 +00001749 if (OrigPhiRef->getType() == Phi->getType()
Andrew Trickc908b432012-01-20 07:41:13 +00001750 && !(ChainedPhis.count(Phi)
1751 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1752 && (ChainedPhis.count(Phi)
1753 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001754 std::swap(OrigPhiRef, Phi);
1755 std::swap(OrigInc, IsomorphicInc);
1756 }
1757 // Replacing the congruent phi is sufficient because acyclic redundancy
1758 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1759 // that a phi is congruent, it's often the head of an IV user cycle that
Andrew Trickf730f392012-01-07 01:29:21 +00001760 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1761 // common case of a single IV increment so that DeleteDeadPHIs can remove
1762 // cycles that had postinc uses.
Andrew Trick5adedf52012-01-07 01:12:09 +00001763 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1764 IsomorphicInc->getType());
1765 if (OrigInc != IsomorphicInc
Andrew Trickd5d2db92012-01-10 01:45:08 +00001766 && TruncExpr == SE.getSCEV(IsomorphicInc)
Andrew Trickc908b432012-01-20 07:41:13 +00001767 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1768 || hoistIVInc(OrigInc, IsomorphicInc))) {
Andrew Trickf9201c52011-10-11 02:28:51 +00001769 DEBUG_WITH_TYPE(DebugType, dbgs()
1770 << "INDVARS: Eliminated congruent iv.inc: "
1771 << *IsomorphicInc << '\n');
Andrew Trick5adedf52012-01-07 01:12:09 +00001772 Value *NewInc = OrigInc;
1773 if (OrigInc->getType() != IsomorphicInc->getType()) {
Andrew Trick23ef0d62012-01-14 03:17:23 +00001774 Instruction *IP = isa<PHINode>(OrigInc)
1775 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1776 : OrigInc->getNextNode();
1777 IRBuilder<> Builder(IP);
Andrew Trick5adedf52012-01-07 01:12:09 +00001778 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1779 NewInc = Builder.
1780 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1781 }
1782 IsomorphicInc->replaceAllUsesWith(NewInc);
Andrew Trickf9201c52011-10-11 02:28:51 +00001783 DeadInsts.push_back(IsomorphicInc);
1784 }
1785 }
1786 DEBUG_WITH_TYPE(DebugType, dbgs()
1787 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1788 ++NumElim;
Andrew Trick5adedf52012-01-07 01:12:09 +00001789 Value *NewIV = OrigPhiRef;
1790 if (OrigPhiRef->getType() != Phi->getType()) {
1791 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1792 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1793 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1794 }
1795 Phi->replaceAllUsesWith(NewIV);
Andrew Trickf9201c52011-10-11 02:28:51 +00001796 DeadInsts.push_back(Phi);
1797 }
1798 return NumElim;
1799}
Andrew Trick653513b2012-07-13 23:33:10 +00001800
1801namespace {
1802// Search for a SCEV subexpression that is not safe to expand. Any expression
1803// that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1804// UDiv expressions. We don't know if the UDiv is derived from an IR divide
1805// instruction, but the important thing is that we prove the denominator is
1806// nonzero before expansion.
1807//
1808// IVUsers already checks that IV-derived expressions are safe. So this check is
1809// only needed when the expression includes some subexpression that is not IV
1810// derived.
1811//
1812// Currently, we only allow division by a nonzero constant here. If this is
1813// inadequate, we could easily allow division by SCEVUnknown by using
1814// ValueTracking to check isKnownNonZero().
Andrew Trick57243da2013-10-25 21:35:56 +00001815//
1816// We cannot generally expand recurrences unless the step dominates the loop
1817// header. The expander handles the special case of affine recurrences by
1818// scaling the recurrence outside the loop, but this technique isn't generally
1819// applicable. Expanding a nested recurrence outside a loop requires computing
1820// binomial coefficients. This could be done, but the recurrence has to be in a
1821// perfectly reduced form, which can't be guaranteed.
Andrew Trick653513b2012-07-13 23:33:10 +00001822struct SCEVFindUnsafe {
Andrew Trick57243da2013-10-25 21:35:56 +00001823 ScalarEvolution &SE;
Andrew Trick653513b2012-07-13 23:33:10 +00001824 bool IsUnsafe;
1825
Andrew Trick57243da2013-10-25 21:35:56 +00001826 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
Andrew Trick653513b2012-07-13 23:33:10 +00001827
1828 bool follow(const SCEV *S) {
Andrew Trick57243da2013-10-25 21:35:56 +00001829 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
1830 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
1831 if (!SC || SC->getValue()->isZero()) {
1832 IsUnsafe = true;
1833 return false;
1834 }
1835 }
1836 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1837 const SCEV *Step = AR->getStepRecurrence(SE);
1838 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
1839 IsUnsafe = true;
1840 return false;
1841 }
1842 }
1843 return true;
Andrew Trick653513b2012-07-13 23:33:10 +00001844 }
1845 bool isDone() const { return IsUnsafe; }
1846};
1847}
1848
1849namespace llvm {
Andrew Trick57243da2013-10-25 21:35:56 +00001850bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
1851 SCEVFindUnsafe Search(SE);
Andrew Trick653513b2012-07-13 23:33:10 +00001852 visitAll(S, Search);
1853 return !Search.IsUnsafe;
1854}
1855}