blob: a7ec937e5bcae56ad2f7c35627b46cdb2dce3c2c [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"
Benjamin Kramer8dd637a2014-06-21 11:47:18 +000019#include "llvm/Analysis/InstructionSimplify.h"
Bill Wendlingf3baad32006-12-07 01:30:32 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000021#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/IntrinsicInst.h"
25#include "llvm/IR/LLVMContext.h"
Andrew Trick7fb669a2011-10-07 23:46:21 +000026#include "llvm/Support/Debug.h"
Andrew Trick244e2c32011-07-16 00:59:39 +000027
Nate Begeman2bca4d92005-07-30 00:12:19 +000028using namespace llvm;
29
Gabor Greif8e66a422010-07-09 16:42:04 +000030/// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
Dan Gohmand2772462010-06-19 13:25:23 +000031/// reusing an existing cast if a suitable one exists, moving an existing
32/// cast if a suitable one exists but isn't in the right place, or
Gabor Greif8e66a422010-07-09 16:42:04 +000033/// creating a new one.
Chris Lattner229907c2011-07-18 04:54:35 +000034Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
Dan Gohmand2772462010-06-19 13:25:23 +000035 Instruction::CastOps Op,
36 BasicBlock::iterator IP) {
Rafael Espindolacd06b482012-02-22 03:21:39 +000037 // This function must be called with the builder having a valid insertion
38 // point. It doesn't need to be the actual IP where the uses of the returned
39 // cast will be added, but it must dominate such IP.
Rafael Espindola09a42012012-02-27 02:13:03 +000040 // We use this precondition to produce a cast that will dominate all its
41 // uses. In particular, this is crucial for the case where the builder's
42 // insertion point *is* the point where we were asked to put the cast.
Sylvestre Ledru35521e22012-07-23 08:51:15 +000043 // Since we don't know the builder's insertion point is actually
Rafael Espindolacd06b482012-02-22 03:21:39 +000044 // where the uses will be added (only that it dominates it), we are
45 // not allowed to move it.
46 BasicBlock::iterator BIP = Builder.GetInsertPoint();
47
Craig Topper9f008862014-04-15 04:59:12 +000048 Instruction *Ret = nullptr;
Rafael Espindola82d95752012-02-18 17:22:58 +000049
Dan Gohmand2772462010-06-19 13:25:23 +000050 // Check to see if there is already a cast!
Chandler Carruthcdf47882014-03-09 03:16:01 +000051 for (User *U : V->users())
Gabor Greif3b740e92010-07-09 16:39:02 +000052 if (U->getType() == Ty)
Gabor Greif8e66a422010-07-09 16:42:04 +000053 if (CastInst *CI = dyn_cast<CastInst>(U))
Dan Gohmand2772462010-06-19 13:25:23 +000054 if (CI->getOpcode() == Op) {
Rafael Espindola337cfaf2012-02-22 03:44:46 +000055 // If the cast isn't where we want it, create a new cast at IP.
56 // Likewise, do not reuse a cast at BIP because it must dominate
57 // instructions that might be inserted before BIP.
Rafael Espindolacd06b482012-02-22 03:21:39 +000058 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
Dan Gohmand2772462010-06-19 13:25:23 +000059 // Create a new cast, and leave the old cast in place in case
60 // it is being used as an insert point. Clear its operand
61 // so that it doesn't hold anything live.
Rafael Espindola09a42012012-02-27 02:13:03 +000062 Ret = CastInst::Create(Op, V, Ty, "", IP);
63 Ret->takeName(CI);
64 CI->replaceAllUsesWith(Ret);
Dan Gohmand2772462010-06-19 13:25:23 +000065 CI->setOperand(0, UndefValue::get(V->getType()));
Rafael Espindola09a42012012-02-27 02:13:03 +000066 break;
Dan Gohmand2772462010-06-19 13:25:23 +000067 }
Rafael Espindola09a42012012-02-27 02:13:03 +000068 Ret = CI;
69 break;
Dan Gohmand2772462010-06-19 13:25:23 +000070 }
71
72 // Create a new cast.
Rafael Espindola09a42012012-02-27 02:13:03 +000073 if (!Ret)
74 Ret = CastInst::Create(Op, V, Ty, V->getName(), IP);
75
76 // We assert at the end of the function since IP might point to an
77 // instruction with different dominance properties than a cast
78 // (an invoke for example) and not dominate BIP (but the cast does).
79 assert(SE.DT->dominates(Ret, BIP));
80
81 rememberInstruction(Ret);
82 return Ret;
Dan Gohmand2772462010-06-19 13:25:23 +000083}
84
Dan Gohman830fd382009-06-27 21:18:18 +000085/// InsertNoopCastOfTo - Insert a cast of V to the specified type,
86/// which must be possible with a noop cast, doing what we can to share
87/// the casts.
Chris Lattner229907c2011-07-18 04:54:35 +000088Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
Dan Gohman830fd382009-06-27 21:18:18 +000089 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
90 assert((Op == Instruction::BitCast ||
91 Op == Instruction::PtrToInt ||
92 Op == Instruction::IntToPtr) &&
93 "InsertNoopCastOfTo cannot perform non-noop casts!");
94 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
95 "InsertNoopCastOfTo cannot change sizes!");
96
Dan Gohman0a40ad92009-04-16 03:18:22 +000097 // Short-circuit unnecessary bitcasts.
Andrew Tricke0ced622011-12-14 22:07:19 +000098 if (Op == Instruction::BitCast) {
99 if (V->getType() == Ty)
100 return V;
101 if (CastInst *CI = dyn_cast<CastInst>(V)) {
102 if (CI->getOperand(0)->getType() == Ty)
103 return CI->getOperand(0);
104 }
105 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000106 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
Dan Gohman830fd382009-06-27 21:18:18 +0000107 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
Dan Gohman150b4c32009-05-01 17:00:00 +0000108 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000109 if (CastInst *CI = dyn_cast<CastInst>(V))
110 if ((CI->getOpcode() == Instruction::PtrToInt ||
111 CI->getOpcode() == Instruction::IntToPtr) &&
112 SE.getTypeSizeInBits(CI->getType()) ==
113 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
114 return CI->getOperand(0);
Dan Gohman150b4c32009-05-01 17:00:00 +0000115 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
116 if ((CE->getOpcode() == Instruction::PtrToInt ||
117 CE->getOpcode() == Instruction::IntToPtr) &&
118 SE.getTypeSizeInBits(CE->getType()) ==
119 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
120 return CE->getOperand(0);
121 }
Dan Gohman66e038a2009-04-16 15:52:57 +0000122
Dan Gohmand2772462010-06-19 13:25:23 +0000123 // Fold a cast of a constant.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000124 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000125 return ConstantExpr::getCast(Op, C, Ty);
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000126
Dan Gohmand2772462010-06-19 13:25:23 +0000127 // Cast the argument at the beginning of the entry block, after
128 // any bitcasts of other arguments.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000129 if (Argument *A = dyn_cast<Argument>(V)) {
Dan Gohmand2772462010-06-19 13:25:23 +0000130 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
131 while ((isa<BitCastInst>(IP) &&
132 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
133 cast<BitCastInst>(IP)->getOperand(0) != A) ||
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000134 isa<DbgInfoIntrinsic>(IP) ||
135 isa<LandingPadInst>(IP))
Dan Gohmand2772462010-06-19 13:25:23 +0000136 ++IP;
137 return ReuseOrCreateCast(A, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000138 }
Wojciech Matyjewicz784d071e12008-02-09 18:30:13 +0000139
Dan Gohmand2772462010-06-19 13:25:23 +0000140 // Cast the instruction immediately after the instruction.
Chris Lattnera6da69c2006-02-04 09:51:53 +0000141 Instruction *I = cast<Instruction>(V);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000142 BasicBlock::iterator IP = I; ++IP;
143 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
144 IP = II->getNormalDest()->begin();
Rafael Espindola82d95752012-02-18 17:22:58 +0000145 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
Bill Wendling86c5cbe2011-08-24 21:06:46 +0000146 ++IP;
Dan Gohmand2772462010-06-19 13:25:23 +0000147 return ReuseOrCreateCast(I, Ty, Op, IP);
Chris Lattnera6da69c2006-02-04 09:51:53 +0000148}
149
Chris Lattnere71f1442007-04-13 05:04:18 +0000150/// InsertBinop - Insert the specified binary operator, doing a small amount
151/// of work to avoid inserting an obviously redundant operation.
Dan Gohman830fd382009-06-27 21:18:18 +0000152Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
153 Value *LHS, Value *RHS) {
Dan Gohman00cb1172007-06-15 19:21:55 +0000154 // Fold a binop with constant operands.
155 if (Constant *CLHS = dyn_cast<Constant>(LHS))
156 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Owen Anderson487375e2009-07-29 18:55:55 +0000157 return ConstantExpr::get(Opcode, CLHS, CRHS);
Dan Gohman00cb1172007-06-15 19:21:55 +0000158
Chris Lattnere71f1442007-04-13 05:04:18 +0000159 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
160 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000161 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
162 // Scanning starts from the last instruction before the insertion point.
163 BasicBlock::iterator IP = Builder.GetInsertPoint();
164 if (IP != BlockBegin) {
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000165 --IP;
166 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000167 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
168 // generated code.
169 if (isa<DbgInfoIntrinsic>(IP))
170 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000171 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
172 IP->getOperand(1) == RHS)
173 return IP;
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000174 if (IP == BlockBegin) break;
175 }
Chris Lattnere71f1442007-04-13 05:04:18 +0000176 }
Dan Gohman830fd382009-06-27 21:18:18 +0000177
Dan Gohman29707de2010-03-03 05:29:13 +0000178 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000179 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
180 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000181
182 // Move the insertion point out of as many loops as we can.
183 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
184 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
185 BasicBlock *Preheader = L->getLoopPreheader();
186 if (!Preheader) break;
187
188 // Ok, move up a level.
189 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
190 }
191
Wojciech Matyjewiczae9753b22008-06-15 19:07:39 +0000192 // If we haven't found this binop, insert it.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000193 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
Benjamin Kramer6e931522013-09-30 15:40:17 +0000194 BO->setDebugLoc(Loc);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000195 rememberInstruction(BO);
Dan Gohman29707de2010-03-03 05:29:13 +0000196
Dan Gohmand195a222009-05-01 17:13:31 +0000197 return BO;
Chris Lattnere71f1442007-04-13 05:04:18 +0000198}
199
Dan Gohman17893622009-05-27 02:00:53 +0000200/// FactorOutConstant - Test if S is divisible by Factor, using signed
Dan Gohman291c2e02009-05-24 18:06:31 +0000201/// division. If so, update S with Factor divided out and return true.
Dan Gohman8b0a4192010-03-01 17:49:51 +0000202/// S need not be evenly divisible if a reasonable remainder can be
Dan Gohman17893622009-05-27 02:00:53 +0000203/// computed.
Dan Gohman291c2e02009-05-24 18:06:31 +0000204/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
205/// unnecessary; in its place, just signed-divide Ops[i] by the scale and
206/// check to see if the divide was folded.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000207static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
208 const SCEV *Factor, ScalarEvolution &SE,
209 const DataLayout &DL) {
Dan Gohman291c2e02009-05-24 18:06:31 +0000210 // Everything is divisible by one.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000211 if (Factor->isOne())
Dan Gohman291c2e02009-05-24 18:06:31 +0000212 return true;
213
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000214 // x/x == 1.
215 if (S == Factor) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000216 S = SE.getConstant(S->getType(), 1);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000217 return true;
218 }
219
Dan Gohman291c2e02009-05-24 18:06:31 +0000220 // For a Constant, check for a multiple of the given factor.
Dan Gohman17893622009-05-27 02:00:53 +0000221 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000222 // 0/x == 0.
223 if (C->isZero())
Dan Gohman291c2e02009-05-24 18:06:31 +0000224 return true;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000225 // Check for divisibility.
226 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
227 ConstantInt *CI =
228 ConstantInt::get(SE.getContext(),
229 C->getValue()->getValue().sdiv(
230 FC->getValue()->getValue()));
231 // If the quotient is zero and the remainder is non-zero, reject
232 // the value at this scale. It will be considered for subsequent
233 // smaller scales.
234 if (!CI->isZero()) {
235 const SCEV *Div = SE.getConstant(CI);
236 S = Div;
237 Remainder =
238 SE.getAddExpr(Remainder,
239 SE.getConstant(C->getValue()->getValue().srem(
240 FC->getValue()->getValue())));
241 return true;
242 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000243 }
Dan Gohman17893622009-05-27 02:00:53 +0000244 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000245
246 // In a Mul, check if there is a constant operand which is a multiple
247 // of the given factor.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000248 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000249 // Size is known, check if there is a constant operand which is a multiple
250 // of the given factor. If so, we can factor it.
251 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
252 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
253 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
254 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
255 NewMulOps[0] = SE.getConstant(
256 C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
257 S = SE.getMulExpr(NewMulOps);
258 return true;
Dan Gohman291c2e02009-05-24 18:06:31 +0000259 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000260 }
Dan Gohman291c2e02009-05-24 18:06:31 +0000261
262 // In an AddRec, check if both start and step are divisible.
263 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohmanaf752342009-07-07 17:06:11 +0000264 const SCEV *Step = A->getStepRecurrence(SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000265 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000266 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
Dan Gohman17893622009-05-27 02:00:53 +0000267 return false;
268 if (!StepRem->isZero())
269 return false;
Dan Gohmanaf752342009-07-07 17:06:11 +0000270 const SCEV *Start = A->getStart();
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000271 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
Dan Gohman291c2e02009-05-24 18:06:31 +0000272 return false;
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000273 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
274 A->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +0000275 return true;
276 }
277
278 return false;
279}
280
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000281/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
282/// is the number of SCEVAddRecExprs present, which are kept at the end of
283/// the list.
284///
285static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000286 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000287 ScalarEvolution &SE) {
288 unsigned NumAddRecs = 0;
289 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
290 ++NumAddRecs;
291 // Group Ops into non-addrecs and addrecs.
292 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
293 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
294 // Let ScalarEvolution sort and simplify the non-addrecs list.
295 const SCEV *Sum = NoAddRecs.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +0000296 SE.getConstant(Ty, 0) :
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000297 SE.getAddExpr(NoAddRecs);
298 // If it returned an add, use the operands. Otherwise it simplified
299 // the sum into a single value, so just use that.
Dan Gohman00524492010-03-18 01:17:13 +0000300 Ops.clear();
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000301 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
Dan Gohmandd41bba2010-06-21 19:47:52 +0000302 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohman00524492010-03-18 01:17:13 +0000303 else if (!Sum->isZero())
304 Ops.push_back(Sum);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000305 // Then append the addrecs.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000306 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000307}
308
309/// SplitAddRecs - Flatten a list of add operands, moving addrec start values
310/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
311/// This helps expose more opportunities for folding parts of the expressions
312/// into GEP indices.
313///
314static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
Chris Lattner229907c2011-07-18 04:54:35 +0000315 Type *Ty,
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000316 ScalarEvolution &SE) {
317 // Find the addrecs.
318 SmallVector<const SCEV *, 8> AddRecs;
319 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
320 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
321 const SCEV *Start = A->getStart();
322 if (Start->isZero()) break;
Dan Gohman1d2ded72010-05-03 22:09:21 +0000323 const SCEV *Zero = SE.getConstant(Ty, 0);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000324 AddRecs.push_back(SE.getAddRecExpr(Zero,
325 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000326 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000327 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000328 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
329 Ops[i] = Zero;
Dan Gohmandd41bba2010-06-21 19:47:52 +0000330 Ops.append(Add->op_begin(), Add->op_end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000331 e += Add->getNumOperands();
332 } else {
333 Ops[i] = Start;
334 }
335 }
336 if (!AddRecs.empty()) {
337 // Add the addrecs onto the end of the list.
Dan Gohmandd41bba2010-06-21 19:47:52 +0000338 Ops.append(AddRecs.begin(), AddRecs.end());
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000339 // Resort the operand list, moving any constants to the front.
340 SimplifyAddOperands(Ops, Ty, SE);
341 }
342}
343
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000344/// expandAddToGEP - Expand an addition expression with a pointer type into
345/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
346/// BasicAliasAnalysis and other passes analyze the result. See the rules
347/// for getelementptr vs. inttoptr in
348/// http://llvm.org/docs/LangRef.html#pointeraliasing
349/// for details.
Dan Gohman16e96c02009-07-20 17:44:17 +0000350///
Dan Gohman510bffc2010-01-19 22:26:02 +0000351/// Design note: The correctness of using getelementptr here depends on
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000352/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
353/// they may introduce pointer arithmetic which may not be safely converted
354/// into getelementptr.
Dan Gohman291c2e02009-05-24 18:06:31 +0000355///
356/// Design note: It might seem desirable for this function to be more
357/// loop-aware. If some of the indices are loop-invariant while others
358/// aren't, it might seem desirable to emit multiple GEPs, keeping the
359/// loop-invariant portions of the overall computation outside the loop.
360/// However, there are a few reasons this is not done here. Hoisting simple
361/// arithmetic is a low-level optimization that often isn't very
362/// important until late in the optimization process. In fact, passes
363/// like InstructionCombining will combine GEPs, even if it means
364/// pushing loop-invariant computation down into loops, so even if the
365/// GEPs were split here, the work would quickly be undone. The
366/// LoopStrengthReduction pass, which is usually run quite late (and
367/// after the last InstructionCombining pass), takes care of hoisting
368/// loop-invariant portions of expressions, after considering what
369/// can be folded using target addressing modes.
370///
Dan Gohmanaf752342009-07-07 17:06:11 +0000371Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
372 const SCEV *const *op_end,
Chris Lattner229907c2011-07-18 04:54:35 +0000373 PointerType *PTy,
374 Type *Ty,
Dan Gohman26494912009-05-19 02:15:55 +0000375 Value *V) {
Chris Lattner229907c2011-07-18 04:54:35 +0000376 Type *ElTy = PTy->getElementType();
Dan Gohman26494912009-05-19 02:15:55 +0000377 SmallVector<Value *, 4> GepIndices;
Dan Gohmanaf752342009-07-07 17:06:11 +0000378 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
Dan Gohman26494912009-05-19 02:15:55 +0000379 bool AnyNonZeroIndices = false;
Dan Gohman26494912009-05-19 02:15:55 +0000380
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000381 // Split AddRecs up into parts as either of the parts may be usable
382 // without the other.
383 SplitAddRecs(Ops, Ty, SE);
384
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000385 Type *IntPtrTy = DL.getIntPtrType(PTy);
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000386
Bob Wilson2107eb72009-12-04 01:33:04 +0000387 // Descend down the pointer's type and attempt to convert the other
Dan Gohman26494912009-05-19 02:15:55 +0000388 // operands into GEP indices, at each level. The first index in a GEP
389 // indexes into the array implied by the pointer operand; the rest of
390 // the indices index into the element or field type selected by the
391 // preceding index.
392 for (;;) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000393 // If the scale size is not 0, attempt to factor out a scale for
394 // array indexing.
Dan Gohmanaf752342009-07-07 17:06:11 +0000395 SmallVector<const SCEV *, 8> ScaledOps;
Dan Gohman9f4ea222010-01-28 06:32:46 +0000396 if (ElTy->isSized()) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +0000397 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
Dan Gohman9f4ea222010-01-28 06:32:46 +0000398 if (!ElSize->isZero()) {
399 SmallVector<const SCEV *, 8> NewOps;
400 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
401 const SCEV *Op = Ops[i];
Dan Gohman1d2ded72010-05-03 22:09:21 +0000402 const SCEV *Remainder = SE.getConstant(Ty, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000403 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
Dan Gohman9f4ea222010-01-28 06:32:46 +0000404 // Op now has ElSize factored out.
405 ScaledOps.push_back(Op);
406 if (!Remainder->isZero())
407 NewOps.push_back(Remainder);
408 AnyNonZeroIndices = true;
409 } else {
410 // The operand was not divisible, so add it to the list of operands
411 // we'll scan next iteration.
412 NewOps.push_back(Ops[i]);
413 }
Dan Gohman26494912009-05-19 02:15:55 +0000414 }
Dan Gohman9f4ea222010-01-28 06:32:46 +0000415 // If we made any changes, update Ops.
416 if (!ScaledOps.empty()) {
417 Ops = NewOps;
418 SimplifyAddOperands(Ops, Ty, SE);
419 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000420 }
Dan Gohman26494912009-05-19 02:15:55 +0000421 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000422
423 // Record the scaled array index for this level of the type. If
424 // we didn't find any operands that could be factored, tentatively
425 // assume that element zero was selected (since the zero offset
426 // would obviously be folded away).
Dan Gohman26494912009-05-19 02:15:55 +0000427 Value *Scaled = ScaledOps.empty() ?
Owen Anderson5a1acd92009-07-31 20:28:14 +0000428 Constant::getNullValue(Ty) :
Dan Gohman26494912009-05-19 02:15:55 +0000429 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
430 GepIndices.push_back(Scaled);
431
432 // Collect struct field index operands.
Chris Lattner229907c2011-07-18 04:54:35 +0000433 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000434 bool FoundFieldNo = false;
435 // An empty struct has no fields.
436 if (STy->getNumElements() == 0) break;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000437 // Field offsets are known. See if a constant offset falls within any of
438 // the struct fields.
439 if (Ops.empty())
440 break;
441 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
442 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
443 const StructLayout &SL = *DL.getStructLayout(STy);
444 uint64_t FullOffset = C->getValue()->getZExtValue();
445 if (FullOffset < SL.getSizeInBytes()) {
446 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
447 GepIndices.push_back(
448 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
449 ElTy = STy->getTypeAtIndex(ElIdx);
450 Ops[0] =
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000451 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000452 AnyNonZeroIndices = true;
453 FoundFieldNo = true;
Dan Gohman26494912009-05-19 02:15:55 +0000454 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000455 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000456 // If no struct field offsets were found, tentatively assume that
457 // field zero was selected (since the zero offset would obviously
458 // be folded away).
459 if (!FoundFieldNo) {
460 ElTy = STy->getTypeAtIndex(0u);
461 GepIndices.push_back(
462 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
463 }
Dan Gohman26494912009-05-19 02:15:55 +0000464 }
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000465
Chris Lattner229907c2011-07-18 04:54:35 +0000466 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000467 ElTy = ATy->getElementType();
468 else
469 break;
Dan Gohman26494912009-05-19 02:15:55 +0000470 }
471
Dan Gohman8b0a4192010-03-01 17:49:51 +0000472 // If none of the operands were convertible to proper GEP indices, cast
Dan Gohman26494912009-05-19 02:15:55 +0000473 // the base to i8* and do an ugly getelementptr with that. It's still
474 // better than ptrtoint+arithmetic+inttoptr at least.
475 if (!AnyNonZeroIndices) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000476 // Cast the base to i8*.
Dan Gohman26494912009-05-19 02:15:55 +0000477 V = InsertNoopCastOfTo(V,
Duncan Sands9ed7b162009-10-06 15:40:36 +0000478 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000479
Rafael Espindola729e3aa2012-02-21 03:51:14 +0000480 assert(!isa<Instruction>(V) ||
Rafael Espindola94df2672012-02-26 02:19:19 +0000481 SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()));
Rafael Espindola7d445e92012-02-21 01:19:51 +0000482
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000483 // Expand the operands for a plain byte offset.
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000484 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
Dan Gohman26494912009-05-19 02:15:55 +0000485
486 // Fold a GEP with constant operands.
487 if (Constant *CLHS = dyn_cast<Constant>(V))
488 if (Constant *CRHS = dyn_cast<Constant>(Idx))
Jay Foaded8db7d2011-07-21 14:31:17 +0000489 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
Dan Gohman26494912009-05-19 02:15:55 +0000490
491 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
492 unsigned ScanLimit = 6;
Dan Gohman830fd382009-06-27 21:18:18 +0000493 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
494 // Scanning starts from the last instruction before the insertion point.
495 BasicBlock::iterator IP = Builder.GetInsertPoint();
496 if (IP != BlockBegin) {
Dan Gohman26494912009-05-19 02:15:55 +0000497 --IP;
498 for (; ScanLimit; --IP, --ScanLimit) {
Dale Johannesenf5cc1cd2010-03-05 21:12:40 +0000499 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
500 // generated code.
501 if (isa<DbgInfoIntrinsic>(IP))
502 ScanLimit++;
Dan Gohman26494912009-05-19 02:15:55 +0000503 if (IP->getOpcode() == Instruction::GetElementPtr &&
504 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
505 return IP;
506 if (IP == BlockBegin) break;
507 }
508 }
509
Dan Gohman29707de2010-03-03 05:29:13 +0000510 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +0000511 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman29707de2010-03-03 05:29:13 +0000512
513 // Move the insertion point out of as many loops as we can.
514 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
515 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
516 BasicBlock *Preheader = L->getLoopPreheader();
517 if (!Preheader) break;
518
519 // Ok, move up a level.
520 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
521 }
522
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +0000523 // Emit a GEP.
524 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
Dan Gohman51ad99d2010-01-21 02:09:26 +0000525 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000526
Dan Gohman26494912009-05-19 02:15:55 +0000527 return GEP;
528 }
529
Dan Gohman29707de2010-03-03 05:29:13 +0000530 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000531 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
Dan Gohman29707de2010-03-03 05:29:13 +0000532
533 // Move the insertion point out of as many loops as we can.
534 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
535 if (!L->isLoopInvariant(V)) break;
536
537 bool AnyIndexNotLoopInvariant = false;
538 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
539 E = GepIndices.end(); I != E; ++I)
540 if (!L->isLoopInvariant(*I)) {
541 AnyIndexNotLoopInvariant = true;
542 break;
543 }
544 if (AnyIndexNotLoopInvariant)
545 break;
546
547 BasicBlock *Preheader = L->getLoopPreheader();
548 if (!Preheader) break;
549
550 // Ok, move up a level.
551 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
552 }
553
Dan Gohman31a9b982009-07-28 01:40:03 +0000554 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
555 // because ScalarEvolution may have changed the address arithmetic to
556 // compute a value which is beyond the end of the allocated object.
Dan Gohman51ad99d2010-01-21 02:09:26 +0000557 Value *Casted = V;
558 if (V->getType() != PTy)
559 Casted = InsertNoopCastOfTo(Casted, PTy);
560 Value *GEP = Builder.CreateGEP(Casted,
Jay Foad040dd822011-07-22 08:16:57 +0000561 GepIndices,
Dan Gohman830fd382009-06-27 21:18:18 +0000562 "scevgep");
Dan Gohman26494912009-05-19 02:15:55 +0000563 Ops.push_back(SE.getUnknown(GEP));
Dan Gohman51ad99d2010-01-21 02:09:26 +0000564 rememberInstruction(GEP);
Dan Gohman29707de2010-03-03 05:29:13 +0000565
Benjamin Kramer58f1ced2013-10-01 12:17:11 +0000566 // Restore the original insert point.
567 Builder.restoreIP(SaveInsertPt);
568
Dan Gohman26494912009-05-19 02:15:55 +0000569 return expand(SE.getAddExpr(Ops));
570}
571
Dan Gohman29707de2010-03-03 05:29:13 +0000572/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
573/// SCEV expansion. If they are nested, this is the most nested. If they are
574/// neighboring, pick the later.
575static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
576 DominatorTree &DT) {
577 if (!A) return B;
578 if (!B) return A;
579 if (A->contains(B)) return B;
580 if (B->contains(A)) return A;
581 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
582 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
583 return A; // Arbitrarily break the tie.
584}
585
Dan Gohman8ea83d82010-11-18 00:34:22 +0000586/// getRelevantLoop - Get the most relevant loop associated with the given
Dan Gohman29707de2010-03-03 05:29:13 +0000587/// expression, according to PickMostRelevantLoop.
Dan Gohman8ea83d82010-11-18 00:34:22 +0000588const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
589 // Test whether we've already computed the most relevant loop for this SCEV.
590 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
Craig Topper9f008862014-04-15 04:59:12 +0000591 RelevantLoops.insert(std::make_pair(S, nullptr));
Dan Gohman8ea83d82010-11-18 00:34:22 +0000592 if (!Pair.second)
593 return Pair.first->second;
594
Dan Gohman29707de2010-03-03 05:29:13 +0000595 if (isa<SCEVConstant>(S))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000596 // A constant has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000597 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000598 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
599 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
Dan Gohman8ea83d82010-11-18 00:34:22 +0000600 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
601 // A non-instruction has no relevant loops.
Craig Topper9f008862014-04-15 04:59:12 +0000602 return nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000603 }
604 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
Craig Topper9f008862014-04-15 04:59:12 +0000605 const Loop *L = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000606 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
607 L = AR->getLoop();
608 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
609 I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000610 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
611 return RelevantLoops[N] = L;
Dan Gohman29707de2010-03-03 05:29:13 +0000612 }
Dan Gohman8ea83d82010-11-18 00:34:22 +0000613 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
614 const Loop *Result = getRelevantLoop(C->getOperand());
615 return RelevantLoops[C] = Result;
616 }
617 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
618 const Loop *Result =
619 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
620 getRelevantLoop(D->getRHS()),
621 *SE.DT);
622 return RelevantLoops[D] = Result;
623 }
Dan Gohman29707de2010-03-03 05:29:13 +0000624 llvm_unreachable("Unexpected SCEV type!");
625}
626
Dan Gohmanb29cda92010-04-15 17:08:50 +0000627namespace {
628
Dan Gohman29707de2010-03-03 05:29:13 +0000629/// LoopCompare - Compare loops by PickMostRelevantLoop.
630class LoopCompare {
631 DominatorTree &DT;
632public:
633 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
634
635 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
636 std::pair<const Loop *, const SCEV *> RHS) const {
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000637 // Keep pointer operands sorted at the end.
638 if (LHS.second->getType()->isPointerTy() !=
639 RHS.second->getType()->isPointerTy())
640 return LHS.second->getType()->isPointerTy();
641
Dan Gohman29707de2010-03-03 05:29:13 +0000642 // Compare loops with PickMostRelevantLoop.
643 if (LHS.first != RHS.first)
644 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
645
646 // If one operand is a non-constant negative and the other is not,
647 // put the non-constant negative on the right so that a sub can
648 // be used instead of a negate and add.
Andrew Trick881a7762012-01-07 00:27:31 +0000649 if (LHS.second->isNonConstantNegative()) {
650 if (!RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000651 return false;
Andrew Trick881a7762012-01-07 00:27:31 +0000652 } else if (RHS.second->isNonConstantNegative())
Dan Gohman29707de2010-03-03 05:29:13 +0000653 return true;
654
655 // Otherwise they are equivalent according to this comparison.
656 return false;
657 }
658};
659
Dan Gohmanb29cda92010-04-15 17:08:50 +0000660}
661
Dan Gohman056857a2009-04-18 17:56:28 +0000662Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000663 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman5bafe382009-09-26 16:11:57 +0000664
Dan Gohman29707de2010-03-03 05:29:13 +0000665 // Collect all the add operands in a loop, along with their associated loops.
666 // Iterate in reverse so that constants are emitted last, all else equal, and
667 // so that pointer operands are inserted first, which the code below relies on
668 // to form more involved GEPs.
669 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
670 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
671 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000672 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Dan Gohman5bafe382009-09-26 16:11:57 +0000673
Dan Gohman29707de2010-03-03 05:29:13 +0000674 // Sort by loop. Use a stable sort so that constants follow non-constants and
675 // pointer operands precede non-pointer operands.
676 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
Dan Gohman26494912009-05-19 02:15:55 +0000677
Dan Gohman29707de2010-03-03 05:29:13 +0000678 // Emit instructions to add all the operands. Hoist as much as possible
679 // out of loops, and form meaningful getelementptrs where possible.
Craig Topper9f008862014-04-15 04:59:12 +0000680 Value *Sum = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000681 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
682 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
683 const Loop *CurLoop = I->first;
684 const SCEV *Op = I->second;
685 if (!Sum) {
686 // This is the first operand. Just expand it.
687 Sum = expand(Op);
688 ++I;
Chris Lattner229907c2011-07-18 04:54:35 +0000689 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000690 // The running sum expression is a pointer. Try to form a getelementptr
691 // at this level with that as the base.
692 SmallVector<const SCEV *, 4> NewOps;
Dan Gohmanfbbdfca2010-07-15 23:38:13 +0000693 for (; I != E && I->first == CurLoop; ++I) {
694 // If the operand is SCEVUnknown and not instructions, peek through
695 // it, to enable more of it to be folded into the GEP.
696 const SCEV *X = I->second;
697 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
698 if (!isa<Instruction>(U->getValue()))
699 X = SE.getSCEV(U->getValue());
700 NewOps.push_back(X);
701 }
Dan Gohman29707de2010-03-03 05:29:13 +0000702 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
Chris Lattner229907c2011-07-18 04:54:35 +0000703 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
Dan Gohman29707de2010-03-03 05:29:13 +0000704 // The running sum is an integer, and there's a pointer at this level.
Dan Gohman3295a6e2010-04-09 19:14:31 +0000705 // Try to form a getelementptr. If the running sum is instructions,
706 // use a SCEVUnknown to avoid re-analyzing them.
Dan Gohman29707de2010-03-03 05:29:13 +0000707 SmallVector<const SCEV *, 4> NewOps;
Dan Gohman3295a6e2010-04-09 19:14:31 +0000708 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
709 SE.getSCEV(Sum));
Dan Gohman29707de2010-03-03 05:29:13 +0000710 for (++I; I != E && I->first == CurLoop; ++I)
711 NewOps.push_back(I->second);
712 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
Andrew Trick881a7762012-01-07 00:27:31 +0000713 } else if (Op->isNonConstantNegative()) {
Dan Gohman29707de2010-03-03 05:29:13 +0000714 // Instead of doing a negate and add, just do a subtract.
Dan Gohman2850b412010-03-03 04:36:42 +0000715 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000716 Sum = InsertNoopCastOfTo(Sum, Ty);
717 Sum = InsertBinop(Instruction::Sub, Sum, W);
718 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000719 } else {
Dan Gohman29707de2010-03-03 05:29:13 +0000720 // A simple add.
Dan Gohman2850b412010-03-03 04:36:42 +0000721 Value *W = expandCodeFor(Op, Ty);
Dan Gohman29707de2010-03-03 05:29:13 +0000722 Sum = InsertNoopCastOfTo(Sum, Ty);
723 // Canonicalize a constant to the RHS.
724 if (isa<Constant>(Sum)) std::swap(Sum, W);
725 Sum = InsertBinop(Instruction::Add, Sum, W);
726 ++I;
Dan Gohman2850b412010-03-03 04:36:42 +0000727 }
728 }
Dan Gohman29707de2010-03-03 05:29:13 +0000729
730 return Sum;
Dan Gohman095ca742008-06-18 16:37:11 +0000731}
Dan Gohman26494912009-05-19 02:15:55 +0000732
Dan Gohman056857a2009-04-18 17:56:28 +0000733Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000734 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +0000735
Dan Gohman29707de2010-03-03 05:29:13 +0000736 // Collect all the mul operands in a loop, along with their associated loops.
737 // Iterate in reverse so that constants are emitted last, all else equal.
738 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
739 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
740 E(S->op_begin()); I != E; ++I)
Dan Gohman8ea83d82010-11-18 00:34:22 +0000741 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
Nate Begeman2bca4d92005-07-30 00:12:19 +0000742
Dan Gohman29707de2010-03-03 05:29:13 +0000743 // Sort by loop. Use a stable sort so that constants follow non-constants.
744 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
745
746 // Emit instructions to mul all the operands. Hoist as much as possible
747 // out of loops.
Craig Topper9f008862014-04-15 04:59:12 +0000748 Value *Prod = nullptr;
Dan Gohman29707de2010-03-03 05:29:13 +0000749 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
750 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
751 const SCEV *Op = I->second;
752 if (!Prod) {
753 // This is the first operand. Just expand it.
754 Prod = expand(Op);
755 ++I;
756 } else if (Op->isAllOnesValue()) {
757 // Instead of doing a multiply by negative one, just do a negate.
758 Prod = InsertNoopCastOfTo(Prod, Ty);
759 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
760 ++I;
761 } else {
762 // A simple mul.
763 Value *W = expandCodeFor(Op, Ty);
764 Prod = InsertNoopCastOfTo(Prod, Ty);
765 // Canonicalize a constant to the RHS.
766 if (isa<Constant>(Prod)) std::swap(Prod, W);
767 Prod = InsertBinop(Instruction::Mul, Prod, W);
768 ++I;
769 }
Dan Gohman0a40ad92009-04-16 03:18:22 +0000770 }
771
Dan Gohman29707de2010-03-03 05:29:13 +0000772 return Prod;
Nate Begeman2bca4d92005-07-30 00:12:19 +0000773}
774
Dan Gohman056857a2009-04-18 17:56:28 +0000775Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +0000776 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +0000777
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000778 Value *LHS = expandCodeFor(S->getLHS(), Ty);
Dan Gohman056857a2009-04-18 17:56:28 +0000779 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
Nick Lewycky3c947042008-07-08 05:05:37 +0000780 const APInt &RHS = SC->getValue()->getValue();
781 if (RHS.isPowerOf2())
782 return InsertBinop(Instruction::LShr, LHS,
Owen Andersonedb4a702009-07-24 23:12:02 +0000783 ConstantInt::get(Ty, RHS.logBase2()));
Nick Lewycky3c947042008-07-08 05:05:37 +0000784 }
785
Dan Gohmanb8597bd2009-06-09 17:18:38 +0000786 Value *RHS = expandCodeFor(S->getRHS(), Ty);
Dan Gohman830fd382009-06-27 21:18:18 +0000787 return InsertBinop(Instruction::UDiv, LHS, RHS);
Nick Lewycky3c947042008-07-08 05:05:37 +0000788}
789
Dan Gohman291c2e02009-05-24 18:06:31 +0000790/// Move parts of Base into Rest to leave Base with the minimal
791/// expression that provides a pointer operand suitable for a
792/// GEP expansion.
Dan Gohmanaf752342009-07-07 17:06:11 +0000793static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
Dan Gohman291c2e02009-05-24 18:06:31 +0000794 ScalarEvolution &SE) {
795 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
796 Base = A->getStart();
797 Rest = SE.getAddExpr(Rest,
Dan Gohman1d2ded72010-05-03 22:09:21 +0000798 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
Dan Gohman291c2e02009-05-24 18:06:31 +0000799 A->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000800 A->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +0000801 A->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman291c2e02009-05-24 18:06:31 +0000802 }
803 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
804 Base = A->getOperand(A->getNumOperands()-1);
Dan Gohmanaf752342009-07-07 17:06:11 +0000805 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
Dan Gohman291c2e02009-05-24 18:06:31 +0000806 NewAddOps.back() = Rest;
807 Rest = SE.getAddExpr(NewAddOps);
808 ExposePointerBase(Base, Rest, SE);
809 }
810}
811
Andrew Trick7fb669a2011-10-07 23:46:21 +0000812/// Determine if this is a well-behaved chain of instructions leading back to
813/// the PHI. If so, it may be reused by expanded expressions.
814bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
815 const Loop *L) {
816 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
817 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
818 return false;
819 // If any of the operands don't dominate the insert position, bail.
820 // Addrec operands are always loop-invariant, so this can only happen
821 // if there are instructions which haven't been hoisted.
822 if (L == IVIncInsertLoop) {
823 for (User::op_iterator OI = IncV->op_begin()+1,
824 OE = IncV->op_end(); OI != OE; ++OI)
825 if (Instruction *OInst = dyn_cast<Instruction>(OI))
826 if (!SE.DT->dominates(OInst, IVIncInsertPos))
827 return false;
828 }
829 // Advance to the next instruction.
830 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
831 if (!IncV)
832 return false;
833
834 if (IncV->mayHaveSideEffects())
835 return false;
836
837 if (IncV != PN)
838 return true;
839
840 return isNormalAddRecExprPHI(PN, IncV, L);
841}
842
Andrew Trickc908b432012-01-20 07:41:13 +0000843/// getIVIncOperand returns an induction variable increment's induction
844/// variable operand.
845///
846/// If allowScale is set, any type of GEP is allowed as long as the nonIV
847/// operands dominate InsertPos.
848///
849/// If allowScale is not set, ensure that a GEP increment conforms to one of the
850/// simple patterns generated by getAddRecExprPHILiterally and
851/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
852Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
853 Instruction *InsertPos,
854 bool allowScale) {
855 if (IncV == InsertPos)
Craig Topper9f008862014-04-15 04:59:12 +0000856 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000857
858 switch (IncV->getOpcode()) {
859 default:
Craig Topper9f008862014-04-15 04:59:12 +0000860 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000861 // Check for a simple Add/Sub or GEP of a loop invariant step.
862 case Instruction::Add:
863 case Instruction::Sub: {
864 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
Rafael Espindola94df2672012-02-26 02:19:19 +0000865 if (!OInst || SE.DT->dominates(OInst, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000866 return dyn_cast<Instruction>(IncV->getOperand(0));
Craig Topper9f008862014-04-15 04:59:12 +0000867 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000868 }
869 case Instruction::BitCast:
870 return dyn_cast<Instruction>(IncV->getOperand(0));
871 case Instruction::GetElementPtr:
872 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
873 I != E; ++I) {
874 if (isa<Constant>(*I))
875 continue;
876 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000877 if (!SE.DT->dominates(OInst, InsertPos))
Craig Topper9f008862014-04-15 04:59:12 +0000878 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000879 }
880 if (allowScale) {
881 // allow any kind of GEP as long as it can be hoisted.
882 continue;
883 }
884 // This must be a pointer addition of constants (pretty), which is already
885 // handled, or some number of address-size elements (ugly). Ugly geps
886 // have 2 operands. i1* is used by the expander to represent an
887 // address-size element.
888 if (IncV->getNumOperands() != 2)
Craig Topper9f008862014-04-15 04:59:12 +0000889 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000890 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
891 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
892 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
Craig Topper9f008862014-04-15 04:59:12 +0000893 return nullptr;
Andrew Trickc908b432012-01-20 07:41:13 +0000894 break;
895 }
896 return dyn_cast<Instruction>(IncV->getOperand(0));
897 }
898}
899
900/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
901/// it available to other uses in this loop. Recursively hoist any operands,
902/// until we reach a value that dominates InsertPos.
903bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
Rafael Espindola94df2672012-02-26 02:19:19 +0000904 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000905 return true;
906
907 // InsertPos must itself dominate IncV so that IncV's new position satisfies
908 // its existing users.
Andrew Tricka7a3de12012-05-22 17:39:59 +0000909 if (isa<PHINode>(InsertPos)
910 || !SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
Andrew Trickc908b432012-01-20 07:41:13 +0000911 return false;
912
913 // Check that the chain of IV operands leading back to Phi can be hoisted.
914 SmallVector<Instruction*, 4> IVIncs;
915 for(;;) {
916 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
917 if (!Oper)
918 return false;
919 // IncV is safe to hoist.
920 IVIncs.push_back(IncV);
921 IncV = Oper;
Rafael Espindola94df2672012-02-26 02:19:19 +0000922 if (SE.DT->dominates(IncV, InsertPos))
Andrew Trickc908b432012-01-20 07:41:13 +0000923 break;
924 }
925 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
926 E = IVIncs.rend(); I != E; ++I) {
927 (*I)->moveBefore(InsertPos);
928 }
929 return true;
930}
931
Andrew Trick7fb669a2011-10-07 23:46:21 +0000932/// Determine if this cyclic phi is in a form that would have been generated by
933/// LSR. We don't care if the phi was actually expanded in this pass, as long
934/// as it is in a low-cost form, for example, no implied multiplication. This
935/// should match any patterns generated by getAddRecExprPHILiterally and
936/// expandAddtoGEP.
937bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
Andrew Trickfd4ca0f2011-10-15 06:19:55 +0000938 const Loop *L) {
Andrew Trickc908b432012-01-20 07:41:13 +0000939 for(Instruction *IVOper = IncV;
940 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
941 /*allowScale=*/false));) {
942 if (IVOper == PN)
943 return true;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000944 }
Andrew Trickc908b432012-01-20 07:41:13 +0000945 return false;
Andrew Trick7fb669a2011-10-07 23:46:21 +0000946}
947
Andrew Trickceafa2c2011-11-30 06:07:54 +0000948/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
949/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
950/// need to materialize IV increments elsewhere to handle difficult situations.
951Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
952 Type *ExpandTy, Type *IntTy,
953 bool useSubtract) {
954 Value *IncV;
955 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
956 if (ExpandTy->isPointerTy()) {
957 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
958 // If the step isn't constant, don't use an implicitly scaled GEP, because
959 // that would require a multiply inside the loop.
960 if (!isa<ConstantInt>(StepV))
961 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
962 GEPPtrTy->getAddressSpace());
963 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
964 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
965 if (IncV->getType() != PN->getType()) {
966 IncV = Builder.CreateBitCast(IncV, PN->getType());
967 rememberInstruction(IncV);
968 }
969 } else {
970 IncV = useSubtract ?
971 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
972 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
973 rememberInstruction(IncV);
974 }
975 return IncV;
976}
977
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +0000978/// \brief Hoist the addrec instruction chain rooted in the loop phi above the
979/// position. This routine assumes that this is possible (has been checked).
980static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
981 Instruction *Pos, PHINode *LoopPhi) {
982 do {
983 if (DT->dominates(InstToHoist, Pos))
984 break;
985 // Make sure the increment is where we want it. But don't move it
986 // down past a potential existing post-inc user.
987 InstToHoist->moveBefore(Pos);
988 Pos = InstToHoist;
989 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
990 } while (InstToHoist != LoopPhi);
991}
992
993/// \brief Check whether we can cheaply express the requested SCEV in terms of
994/// the available PHI SCEV by truncation and/or invertion of the step.
995static bool canBeCheaplyTransformed(ScalarEvolution &SE,
996 const SCEVAddRecExpr *Phi,
997 const SCEVAddRecExpr *Requested,
998 bool &InvertStep) {
999 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1000 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1001
1002 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1003 return false;
1004
1005 // Try truncate it if necessary.
1006 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1007 if (!Phi)
1008 return false;
1009
1010 // Check whether truncation will help.
1011 if (Phi == Requested) {
1012 InvertStep = false;
1013 return true;
1014 }
1015
1016 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1017 if (SE.getAddExpr(Requested->getStart(),
1018 SE.getNegativeSCEV(Requested)) == Phi) {
1019 InvertStep = true;
1020 return true;
1021 }
1022
1023 return false;
1024}
1025
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001026static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1027 if (!isa<IntegerType>(AR->getType()))
1028 return false;
1029
1030 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1031 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1032 const SCEV *Step = AR->getStepRecurrence(SE);
1033 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1034 SE.getSignExtendExpr(AR, WideTy));
1035 const SCEV *ExtendAfterOp =
1036 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1037 return ExtendAfterOp == OpAfterExtend;
1038}
1039
1040static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1041 if (!isa<IntegerType>(AR->getType()))
1042 return false;
1043
1044 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1045 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1046 const SCEV *Step = AR->getStepRecurrence(SE);
1047 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1048 SE.getZeroExtendExpr(AR, WideTy));
1049 const SCEV *ExtendAfterOp =
1050 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1051 return ExtendAfterOp == OpAfterExtend;
1052}
1053
Dan Gohman51ad99d2010-01-21 02:09:26 +00001054/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1055/// the base addrec, which is the addrec without any non-loop-dominating
1056/// values, and return the PHI.
1057PHINode *
1058SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1059 const Loop *L,
Chris Lattner229907c2011-07-18 04:54:35 +00001060 Type *ExpandTy,
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001061 Type *IntTy,
1062 Type *&TruncTy,
1063 bool &InvertStep) {
Benjamin Kramera7606b992011-07-16 22:26:27 +00001064 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
Andrew Trick244e2c32011-07-16 00:59:39 +00001065
Dan Gohman51ad99d2010-01-21 02:09:26 +00001066 // Reuse a previously-inserted PHI, if present.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001067 BasicBlock *LatchBlock = L->getLoopLatch();
1068 if (LatchBlock) {
Craig Topper9f008862014-04-15 04:59:12 +00001069 PHINode *AddRecPhiMatch = nullptr;
1070 Instruction *IncV = nullptr;
1071 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001072 InvertStep = false;
1073
1074 // Only try partially matching scevs that need truncation and/or
1075 // step-inversion if we know this loop is outside the current loop.
1076 bool TryNonMatchingSCEV = IVIncInsertLoop &&
1077 SE.DT->properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1078
Andrew Trick7fb669a2011-10-07 23:46:21 +00001079 for (BasicBlock::iterator I = L->getHeader()->begin();
1080 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001081 if (!SE.isSCEVable(PN->getType()))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001082 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001083
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001084 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1085 if (!PhiSCEV)
1086 continue;
Dan Gohman148a9722010-02-16 00:20:08 +00001087
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001088 bool IsMatchingSCEV = PhiSCEV == Normalized;
1089 // We only handle truncation and inversion of phi recurrences for the
1090 // expanded expression if the expanded expression's loop dominates the
1091 // loop we insert to. Check now, so we can bail out early.
1092 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1093 continue;
1094
1095 Instruction *TempIncV =
1096 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1097
1098 // Check whether we can reuse this PHI node.
Andrew Trick7fb669a2011-10-07 23:46:21 +00001099 if (LSRMode) {
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001100 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
Andrew Trick7fb669a2011-10-07 23:46:21 +00001101 continue;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001102 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1103 continue;
1104 } else {
1105 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
Andrew Trickc908b432012-01-20 07:41:13 +00001106 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001107 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001108
1109 // Stop if we have found an exact match SCEV.
1110 if (IsMatchingSCEV) {
1111 IncV = TempIncV;
Craig Topper9f008862014-04-15 04:59:12 +00001112 TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001113 InvertStep = false;
1114 AddRecPhiMatch = PN;
1115 break;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001116 }
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001117
1118 // Try whether the phi can be translated into the requested form
1119 // (truncated and/or offset by a constant).
1120 if ((!TruncTy || InvertStep) &&
1121 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1122 // Record the phi node. But don't stop we might find an exact match
1123 // later.
1124 AddRecPhiMatch = PN;
1125 IncV = TempIncV;
1126 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1127 }
1128 }
1129
1130 if (AddRecPhiMatch) {
1131 // Potentially, move the increment. We have made sure in
1132 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1133 if (L == IVIncInsertLoop)
1134 hoistBeforePos(SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1135
Andrew Trick7fb669a2011-10-07 23:46:21 +00001136 // Ok, the add recurrence looks usable.
1137 // Remember this PHI, even in post-inc mode.
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001138 InsertedValues.insert(AddRecPhiMatch);
Andrew Trick7fb669a2011-10-07 23:46:21 +00001139 // Remember the increment.
1140 rememberInstruction(IncV);
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001141 return AddRecPhiMatch;
Andrew Trick7fb669a2011-10-07 23:46:21 +00001142 }
1143 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001144
1145 // Save the original insertion point so we can restore it when we're done.
Benjamin Kramer6e931522013-09-30 15:40:17 +00001146 BuilderType::InsertPointGuard Guard(Builder);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001147
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001148 // Another AddRec may need to be recursively expanded below. For example, if
1149 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1150 // loop. Remove this loop from the PostIncLoops set before expanding such
1151 // AddRecs. Otherwise, we cannot find a valid position for the step
1152 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1153 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1154 // so it's not worth implementing SmallPtrSet::swap.
1155 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1156 PostIncLoops.clear();
1157
Dan Gohman51ad99d2010-01-21 02:09:26 +00001158 // Expand code for the start value.
1159 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1160 L->getHeader()->begin());
1161
Andrew Trick244e2c32011-07-16 00:59:39 +00001162 // StartV must be hoisted into L's preheader to dominate the new phi.
Benjamin Kramera7606b992011-07-16 22:26:27 +00001163 assert(!isa<Instruction>(StartV) ||
1164 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1165 L->getHeader()));
Andrew Trick244e2c32011-07-16 00:59:39 +00001166
Andrew Trickceafa2c2011-11-30 06:07:54 +00001167 // Expand code for the step value. Do this before creating the PHI so that PHI
1168 // reuse code doesn't see an incomplete PHI.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001169 const SCEV *Step = Normalized->getStepRecurrence(SE);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001170 // If the stride is negative, insert a sub instead of an add for the increment
1171 // (unless it's a constant, because subtracts of constants are canonicalized
1172 // to adds).
Andrew Trick881a7762012-01-07 00:27:31 +00001173 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001174 if (useSubtract)
Dan Gohman51ad99d2010-01-21 02:09:26 +00001175 Step = SE.getNegativeSCEV(Step);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001176 // Expand the step somewhere that dominates the loop header.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001177 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1178
Sanjoy Das54ef8952015-02-26 19:51:35 +00001179 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1180 // we actually do emit an addition. It does not apply if we emit a
1181 // subtraction.
1182 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1183 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1184
Dan Gohman51ad99d2010-01-21 02:09:26 +00001185 // Create the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001186 BasicBlock *Header = L->getHeader();
1187 Builder.SetInsertPoint(Header, Header->begin());
1188 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Andrew Trick411daa52011-06-28 05:07:32 +00001189 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
Andrew Trick154d78a2011-06-28 05:41:52 +00001190 Twine(IVName) + ".iv");
Dan Gohman51ad99d2010-01-21 02:09:26 +00001191 rememberInstruction(PN);
1192
1193 // Create the step instructions and populate the PHI.
Jay Foade0938d82011-03-30 11:19:20 +00001194 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001195 BasicBlock *Pred = *HPI;
1196
1197 // Add a start value.
1198 if (!L->contains(Pred)) {
1199 PN->addIncoming(StartV, Pred);
1200 continue;
1201 }
1202
Andrew Trickceafa2c2011-11-30 06:07:54 +00001203 // Create a step value and add it to the PHI.
1204 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1205 // instructions at IVIncInsertPos.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001206 Instruction *InsertPos = L == IVIncInsertLoop ?
1207 IVIncInsertPos : Pred->getTerminator();
Devang Patelc3239d32011-07-05 21:48:22 +00001208 Builder.SetInsertPoint(InsertPos);
Andrew Trickceafa2c2011-11-30 06:07:54 +00001209 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001210
Andrew Trick8eaae282013-07-14 02:50:07 +00001211 if (isa<OverflowingBinaryOperator>(IncV)) {
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001212 if (IncrementIsNUW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001213 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
Sanjoy Dasdcc84db2015-02-25 20:02:59 +00001214 if (IncrementIsNSW)
Andrew Trick8eaae282013-07-14 02:50:07 +00001215 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1216 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001217 PN->addIncoming(IncV, Pred);
1218 }
1219
Andrew Trickb9aa26f2011-12-20 01:42:24 +00001220 // After expanding subexpressions, restore the PostIncLoops set so the caller
1221 // can ensure that IVIncrement dominates the current uses.
1222 PostIncLoops = SavedPostIncLoops;
1223
Dan Gohman51ad99d2010-01-21 02:09:26 +00001224 // Remember this PHI, even in post-inc mode.
1225 InsertedValues.insert(PN);
1226
1227 return PN;
1228}
1229
1230Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
Chris Lattner229907c2011-07-18 04:54:35 +00001231 Type *STy = S->getType();
1232 Type *IntTy = SE.getEffectiveSCEVType(STy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001233 const Loop *L = S->getLoop();
1234
1235 // Determine a normalized form of this expression, which is the expression
1236 // before any post-inc adjustment is made.
1237 const SCEVAddRecExpr *Normalized = S;
Dan Gohmand006ab92010-04-07 22:27:08 +00001238 if (PostIncLoops.count(L)) {
1239 PostIncLoopSet Loops;
1240 Loops.insert(L);
1241 Normalized =
Craig Topper9f008862014-04-15 04:59:12 +00001242 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
1243 nullptr, Loops, SE, *SE.DT));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001244 }
1245
1246 // Strip off any non-loop-dominating component from the addrec start.
1247 const SCEV *Start = Normalized->getStart();
Craig Topper9f008862014-04-15 04:59:12 +00001248 const SCEV *PostLoopOffset = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001249 if (!SE.properlyDominates(Start, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001250 PostLoopOffset = Start;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001251 Start = SE.getConstant(Normalized->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00001252 Normalized = cast<SCEVAddRecExpr>(
1253 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1254 Normalized->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001255 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001256 }
1257
1258 // Strip off any non-loop-dominating component from the addrec step.
1259 const SCEV *Step = Normalized->getStepRecurrence(SE);
Craig Topper9f008862014-04-15 04:59:12 +00001260 const SCEV *PostLoopScale = nullptr;
Dan Gohman20d9ce22010-11-17 21:41:58 +00001261 if (!SE.dominates(Step, L->getHeader())) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001262 PostLoopScale = Step;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001263 Step = SE.getConstant(Normalized->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001264 Normalized =
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001265 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1266 Start, Step, Normalized->getLoop(),
1267 Normalized->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00001268 }
1269
1270 // Expand the core addrec. If we need post-loop scaling, force it to
1271 // expand to an integer type to avoid the need for additional casting.
Chris Lattner229907c2011-07-18 04:54:35 +00001272 Type *ExpandTy = PostLoopScale ? IntTy : STy;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001273 // In some cases, we decide to reuse an existing phi node but need to truncate
1274 // it and/or invert the step.
Craig Topper9f008862014-04-15 04:59:12 +00001275 Type *TruncTy = nullptr;
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001276 bool InvertStep = false;
1277 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1278 TruncTy, InvertStep);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001279
Dan Gohman8b0a4192010-03-01 17:49:51 +00001280 // Accommodate post-inc mode, if necessary.
Dan Gohman51ad99d2010-01-21 02:09:26 +00001281 Value *Result;
Dan Gohmand006ab92010-04-07 22:27:08 +00001282 if (!PostIncLoops.count(L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00001283 Result = PN;
1284 else {
1285 // In PostInc mode, use the post-incremented value.
1286 BasicBlock *LatchBlock = L->getLoopLatch();
1287 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1288 Result = PN->getIncomingValueForBlock(LatchBlock);
Andrew Trick870c1a32011-10-13 21:55:29 +00001289
1290 // For an expansion to use the postinc form, the client must call
1291 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1292 // or dominated by IVIncInsertPos.
Andrew Trickceafa2c2011-11-30 06:07:54 +00001293 if (isa<Instruction>(Result)
1294 && !SE.DT->dominates(cast<Instruction>(Result),
1295 Builder.GetInsertPoint())) {
1296 // The induction variable's postinc expansion does not dominate this use.
1297 // IVUsers tries to prevent this case, so it is rare. However, it can
1298 // happen when an IVUser outside the loop is not dominated by the latch
1299 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1300 // all cases. Consider a phi outide whose operand is replaced during
1301 // expansion with the value of the postinc user. Without fundamentally
1302 // changing the way postinc users are tracked, the only remedy is
1303 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1304 // but hopefully expandCodeFor handles that.
1305 bool useSubtract =
Andrew Trick881a7762012-01-07 00:27:31 +00001306 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
Andrew Trickceafa2c2011-11-30 06:07:54 +00001307 if (useSubtract)
1308 Step = SE.getNegativeSCEV(Step);
Benjamin Kramer6e931522013-09-30 15:40:17 +00001309 Value *StepV;
1310 {
1311 // Expand the step somewhere that dominates the loop header.
1312 BuilderType::InsertPointGuard Guard(Builder);
1313 StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1314 }
Andrew Trickceafa2c2011-11-30 06:07:54 +00001315 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1316 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00001317 }
1318
Arnold Schwaighofer26f567d2014-02-16 15:49:50 +00001319 // We have decided to reuse an induction variable of a dominating loop. Apply
1320 // truncation and/or invertion of the step.
1321 if (TruncTy) {
1322 Type *ResTy = Result->getType();
1323 // Normalize the result type.
1324 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1325 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1326 // Truncate the result.
1327 if (TruncTy != Result->getType()) {
1328 Result = Builder.CreateTrunc(Result, TruncTy);
1329 rememberInstruction(Result);
1330 }
1331 // Invert the result.
1332 if (InvertStep) {
1333 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1334 Result);
1335 rememberInstruction(Result);
1336 }
1337 }
1338
Dan Gohman51ad99d2010-01-21 02:09:26 +00001339 // Re-apply any non-loop-dominating scale.
1340 if (PostLoopScale) {
Andrew Trick57243da2013-10-25 21:35:56 +00001341 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
Dan Gohman1a8674e2010-02-12 20:39:25 +00001342 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001343 Result = Builder.CreateMul(Result,
1344 expandCodeFor(PostLoopScale, IntTy));
1345 rememberInstruction(Result);
1346 }
1347
1348 // Re-apply any non-loop-dominating offset.
1349 if (PostLoopOffset) {
Chris Lattner229907c2011-07-18 04:54:35 +00001350 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001351 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1352 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1353 } else {
Dan Gohman1a8674e2010-02-12 20:39:25 +00001354 Result = InsertNoopCastOfTo(Result, IntTy);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001355 Result = Builder.CreateAdd(Result,
1356 expandCodeFor(PostLoopOffset, IntTy));
1357 rememberInstruction(Result);
1358 }
1359 }
1360
1361 return Result;
1362}
1363
Dan Gohman056857a2009-04-18 17:56:28 +00001364Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001365 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1366
Chris Lattner229907c2011-07-18 04:54:35 +00001367 Type *Ty = SE.getEffectiveSCEVType(S->getType());
Nate Begeman2bca4d92005-07-30 00:12:19 +00001368 const Loop *L = S->getLoop();
Nate Begeman2bca4d92005-07-30 00:12:19 +00001369
Dan Gohman426901a2009-06-13 16:25:49 +00001370 // First check for an existing canonical IV in a suitable type.
Craig Topper9f008862014-04-15 04:59:12 +00001371 PHINode *CanonicalIV = nullptr;
Dan Gohman426901a2009-06-13 16:25:49 +00001372 if (PHINode *PN = L->getCanonicalInductionVariable())
Dan Gohman31158752010-07-20 16:46:58 +00001373 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
Dan Gohman426901a2009-06-13 16:25:49 +00001374 CanonicalIV = PN;
1375
1376 // Rewrite an AddRec in terms of the canonical induction variable, if
1377 // its type is more narrow.
1378 if (CanonicalIV &&
1379 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1380 SE.getTypeSizeInBits(Ty)) {
Dan Gohman00524492010-03-18 01:17:13 +00001381 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1382 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1383 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00001384 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001385 S->getNoWrapFlags(SCEV::FlagNW)));
Dan Gohman426901a2009-06-13 16:25:49 +00001386 BasicBlock::iterator NewInsertPt =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001387 std::next(BasicBlock::iterator(cast<Instruction>(V)));
Benjamin Kramer6e931522013-09-30 15:40:17 +00001388 BuilderType::InsertPointGuard Guard(Builder);
Bill Wendling86c5cbe2011-08-24 21:06:46 +00001389 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1390 isa<LandingPadInst>(NewInsertPt))
Jim Grosbachfd3b4e72010-06-16 21:13:38 +00001391 ++NewInsertPt;
Craig Topper9f008862014-04-15 04:59:12 +00001392 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
Dan Gohman426901a2009-06-13 16:25:49 +00001393 NewInsertPt);
Dan Gohman426901a2009-06-13 16:25:49 +00001394 return V;
1395 }
1396
Nate Begeman2bca4d92005-07-30 00:12:19 +00001397 // {X,+,F} --> X + {0,+,F}
Dan Gohmanbe928e32008-06-18 16:23:07 +00001398 if (!S->getStart()->isZero()) {
Dan Gohman00524492010-03-18 01:17:13 +00001399 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00001400 NewOps[0] = SE.getConstant(Ty, 0);
Andrew Trickaa8ceba2013-07-14 03:10:08 +00001401 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1402 S->getNoWrapFlags(SCEV::FlagNW));
Dan Gohman291c2e02009-05-24 18:06:31 +00001403
1404 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1405 // comments on expandAddToGEP for details.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001406 const SCEV *Base = S->getStart();
1407 const SCEV *RestArray[1] = { Rest };
1408 // Dig into the expression to find the pointer base for a GEP.
1409 ExposePointerBase(Base, RestArray[0], SE);
1410 // If we found a pointer, expand the AddRec with a GEP.
Chris Lattner229907c2011-07-18 04:54:35 +00001411 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00001412 // Make sure the Base isn't something exotic, such as a multiplied
1413 // or divided pointer value. In those cases, the result type isn't
1414 // actually a pointer type.
1415 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1416 Value *StartV = expand(Base);
1417 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1418 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
Dan Gohman291c2e02009-05-24 18:06:31 +00001419 }
1420 }
1421
Dan Gohmanf19aeec2009-06-24 01:18:18 +00001422 // Just do a normal add. Pre-expand the operands to suppress folding.
1423 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1424 SE.getUnknown(expand(Rest))));
Nate Begeman2bca4d92005-07-30 00:12:19 +00001425 }
1426
Dan Gohmancd838702010-07-26 18:28:14 +00001427 // If we don't yet have a canonical IV, create one.
1428 if (!CanonicalIV) {
Nate Begeman2bca4d92005-07-30 00:12:19 +00001429 // Create and insert the PHI node for the induction variable in the
1430 // specified loop.
1431 BasicBlock *Header = L->getHeader();
Jay Foade0938d82011-03-30 11:19:20 +00001432 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
Jay Foad52131342011-03-30 11:28:46 +00001433 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1434 Header->begin());
Dan Gohmancd838702010-07-26 18:28:14 +00001435 rememberInstruction(CanonicalIV);
Nate Begeman2bca4d92005-07-30 00:12:19 +00001436
Hal Finkel3f5279c2013-08-18 00:16:23 +00001437 SmallSet<BasicBlock *, 4> PredSeen;
Owen Andersonedb4a702009-07-24 23:12:02 +00001438 Constant *One = ConstantInt::get(Ty, 1);
Jay Foade0938d82011-03-30 11:19:20 +00001439 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
Gabor Greife82532a2010-07-09 15:40:10 +00001440 BasicBlock *HP = *HPI;
David Blaikie70573dc2014-11-19 07:49:26 +00001441 if (!PredSeen.insert(HP).second) {
Hal Finkel36eff0f2014-07-31 19:13:38 +00001442 // There must be an incoming value for each predecessor, even the
1443 // duplicates!
1444 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
Hal Finkel3f5279c2013-08-18 00:16:23 +00001445 continue;
Hal Finkel36eff0f2014-07-31 19:13:38 +00001446 }
Hal Finkel3f5279c2013-08-18 00:16:23 +00001447
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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001709 if (Value *V = SimplifyInstruction(Phi, DL, SE.TLI, SE.DT, SE.AC)) {
Benjamin Kramera225ed82012-10-19 16:37:30 +00001710 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}