blob: e3e0c2fc6f3be647ee68978cf0086624a2292d89 [file] [log] [blame]
Andrew Trick3ec331e2011-08-10 03:46:27 +00001//===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements induction variable simplification. It does
11// not define any actual pass or policy, but provides a single function to
12// simplify a loop's induction variables based on ScalarEvolution.
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000020#include "llvm/Analysis/IVUsers.h"
21#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000026#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
Andrew Trick0ba77a02013-12-23 23:31:49 +000028#include "llvm/IR/IntrinsicInst.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000032
33using namespace llvm;
34
Chandler Carruth964daaa2014-04-22 02:55:47 +000035#define DEBUG_TYPE "indvars"
36
Andrew Trick3ec331e2011-08-10 03:46:27 +000037STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
38STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
39STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
40STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
41
42namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000043 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000044 /// based on ScalarEvolution. It is the primary instrument of the
45 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
46 /// other loop passes that preserve SCEV.
47 class SimplifyIndvar {
48 Loop *L;
49 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000050 ScalarEvolution *SE;
Rafael Espindola37dc9e12014-02-21 00:06:31 +000051 const DataLayout *DL; // May be NULL
Andrew Trick3ec331e2011-08-10 03:46:27 +000052
53 SmallVectorImpl<WeakVH> &DeadInsts;
54
55 bool Changed;
56
57 public:
Chandler Carruth4f8f3072015-01-17 14:16:18 +000058 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LoopInfo *LI,
59 const DataLayout *DL, SmallVectorImpl<WeakVH> &Dead,
60 IVUsers *IVU = nullptr)
61 : L(Loop), LI(LI), SE(SE), DL(DL), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000062 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000063 }
64
65 bool hasChanged() const { return Changed; }
66
67 /// Iteratively perform simplification on a worklist of users of the
68 /// specified induction variable. This is the top-level driver that applies
69 /// all simplicitions to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000070 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000071
Andrew Trick74664d52011-08-10 04:01:31 +000072 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000073
74 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
75 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
76 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
77 bool IsSigned);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000078 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
Andrew Trick0ba77a02013-12-23 23:31:49 +000079
80 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
81 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000082 };
83}
84
Sanjay Patel7777b502014-11-12 18:07:42 +000085/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000086/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000087///
Andrew Trick7251e412011-09-19 17:54:39 +000088/// IVOperand is guaranteed SCEVable, but UseInst may not be.
89///
Andrew Trick74664d52011-08-10 04:01:31 +000090/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000091/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000092/// Otherwise return null.
93Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000094 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000095 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000096 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000097 switch (UseInst->getOpcode()) {
98 default:
Craig Topperf40110f2014-04-25 05:29:35 +000099 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000100 case Instruction::UDiv:
101 case Instruction::LShr:
102 // We're only interested in the case where we know something about
103 // the numerator and have a constant denominator.
104 if (IVOperand != UseInst->getOperand(OperIdx) ||
105 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000106 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000107
108 // Attempt to fold a binary operator with constant operand.
109 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000110 if (!isa<BinaryOperator>(IVOperand)
111 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000113
114 IVSrc = IVOperand->getOperand(0);
115 // IVSrc must be the (SCEVable) IV, since the other operand is const.
116 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
117
118 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
119 if (UseInst->getOpcode() == Instruction::LShr) {
120 // Get a constant for the divisor. See createSCEV.
121 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
122 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000123 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000124
125 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000126 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000127 }
128 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
129 }
130 // We have something that might fold it's operand. Compare SCEVs.
131 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000132 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000133
134 // Bypass the operand if SCEV can prove it has no effect.
135 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000137
138 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
139 << " -> " << *UseInst << '\n');
140
141 UseInst->setOperand(OperIdx, IVSrc);
142 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
143
144 ++NumElimOperand;
145 Changed = true;
146 if (IVOperand->use_empty())
147 DeadInsts.push_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000148 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000149}
150
Sanjay Patel7777b502014-11-12 18:07:42 +0000151/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000152/// comparisons against an induction variable.
153void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
154 unsigned IVOperIdx = 0;
155 ICmpInst::Predicate Pred = ICmp->getPredicate();
156 if (IVOperand != ICmp->getOperand(0)) {
157 // Swapped
158 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
159 IVOperIdx = 1;
160 Pred = ICmpInst::getSwappedPredicate(Pred);
161 }
162
163 // Get the SCEVs for the ICmp operands.
164 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
165 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
166
167 // Simplify unnecessary loops away.
168 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
169 S = SE->getSCEVAtScope(S, ICmpLoop);
170 X = SE->getSCEVAtScope(X, ICmpLoop);
171
172 // If the condition is always true or always false, replace it with
173 // a constant value.
174 if (SE->isKnownPredicate(Pred, S, X))
175 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
176 else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
177 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
178 else
179 return;
180
181 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
182 ++NumElimCmp;
183 Changed = true;
184 DeadInsts.push_back(ICmp);
185}
186
Sanjay Patel7777b502014-11-12 18:07:42 +0000187/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000188/// remainder operations operating on an induction variable.
189void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
190 Value *IVOperand,
191 bool IsSigned) {
192 // We're only interested in the case where we know something about
193 // the numerator.
194 if (IVOperand != Rem->getOperand(0))
195 return;
196
197 // Get the SCEVs for the ICmp operands.
198 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
199 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
200
201 // Simplify unnecessary loops away.
202 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
203 S = SE->getSCEVAtScope(S, ICmpLoop);
204 X = SE->getSCEVAtScope(X, ICmpLoop);
205
206 // i % n --> i if i is in [0,n).
207 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
208 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
209 S, X))
210 Rem->replaceAllUsesWith(Rem->getOperand(0));
211 else {
212 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
213 const SCEV *LessOne =
214 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
215 if (IsSigned && !SE->isKnownNonNegative(LessOne))
216 return;
217
218 if (!SE->isKnownPredicate(IsSigned ?
219 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
220 LessOne, X))
221 return;
222
223 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000224 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000225 SelectInst *Sel =
226 SelectInst::Create(ICmp,
227 ConstantInt::get(Rem->getType(), 0),
228 Rem->getOperand(0), "tmp", Rem);
229 Rem->replaceAllUsesWith(Sel);
230 }
231
Andrew Trick3ec331e2011-08-10 03:46:27 +0000232 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
233 ++NumElimRem;
234 Changed = true;
235 DeadInsts.push_back(Rem);
236}
237
Sanjay Patel7777b502014-11-12 18:07:42 +0000238/// Eliminate an operation that consumes a simple IV and has
Andrew Trick3ec331e2011-08-10 03:46:27 +0000239/// no observable side-effect given the range of IV values.
Andrew Trick7251e412011-09-19 17:54:39 +0000240/// IVOperand is guaranteed SCEVable, but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000241bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
242 Instruction *IVOperand) {
243 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
244 eliminateIVComparison(ICmp, IVOperand);
245 return true;
246 }
247 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
248 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
249 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
250 eliminateIVRemainder(Rem, IVOperand, IsSigned);
251 return true;
252 }
253 }
254
255 // Eliminate any operation that SCEV can prove is an identity function.
256 if (!SE->isSCEVable(UseInst->getType()) ||
257 (UseInst->getType() != IVOperand->getType()) ||
258 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
259 return false;
260
261 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
262
263 UseInst->replaceAllUsesWith(IVOperand);
264 ++NumElimIdentity;
265 Changed = true;
266 DeadInsts.push_back(UseInst);
267 return true;
268}
269
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000270/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
271/// unsigned-overflow. Returns true if anything changed, false otherwise.
272bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
273 Value *IVOperand) {
274
275 // Currently we only handle instructions of the form "add <indvar> <value>"
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000276 unsigned Op = BO->getOpcode();
Sanjoy Das8c252bd2015-01-15 01:46:09 +0000277 if (Op != Instruction::Add)
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000278 return false;
279
280 // If BO is already both nuw and nsw then there is nothing left to do
281 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
282 return false;
283
284 IntegerType *IT = cast<IntegerType>(IVOperand->getType());
285 Value *OtherOperand = nullptr;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000286 if (BO->getOperand(0) == IVOperand) {
287 OtherOperand = BO->getOperand(1);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000288 } else {
289 assert(BO->getOperand(1) == IVOperand && "only other use!");
290 OtherOperand = BO->getOperand(0);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000291 }
292
293 bool Changed = false;
294 const SCEV *OtherOpSCEV = SE->getSCEV(OtherOperand);
295 if (OtherOpSCEV == SE->getCouldNotCompute())
296 return false;
297
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000298 const SCEV *IVOpSCEV = SE->getSCEV(IVOperand);
299 const SCEV *ZeroSCEV = SE->getConstant(IVOpSCEV->getType(), 0);
300
301 if (!BO->hasNoSignedWrap()) {
302 // Upgrade the add to an "add nsw" if we can prove that it will never
303 // sign-overflow or sign-underflow.
304
305 const SCEV *SignedMax =
306 SE->getConstant(APInt::getSignedMaxValue(IT->getBitWidth()));
307 const SCEV *SignedMin =
308 SE->getConstant(APInt::getSignedMinValue(IT->getBitWidth()));
309
310 // The addition "IVOperand + OtherOp" does not sign-overflow if the result
311 // is sign-representable in 2's complement in the given bit-width.
312 //
313 // If OtherOp is SLT 0, then for an IVOperand in [SignedMin - OtherOp,
314 // SignedMax], "IVOperand + OtherOp" is in [SignedMin, SignedMax + OtherOp].
315 // Everything in [SignedMin, SignedMax + OtherOp] is representable since
316 // SignedMax + OtherOp is at least -1.
317 //
318 // If OtherOp is SGE 0, then for an IVOperand in [SignedMin, SignedMax -
319 // OtherOp], "IVOperand + OtherOp" is in [SignedMin + OtherOp, SignedMax].
320 // Everything in [SignedMin + OtherOp, SignedMax] is representable since
321 // SignedMin + OtherOp is at most -1.
322 //
323 // It follows that for all values of IVOperand in [SignedMin - smin(0,
324 // OtherOp), SignedMax - smax(0, OtherOp)] the result of the add is
325 // representable (i.e. there is no sign-overflow).
326
327 const SCEV *UpperDelta = SE->getSMaxExpr(ZeroSCEV, OtherOpSCEV);
328 const SCEV *UpperLimit = SE->getMinusSCEV(SignedMax, UpperDelta);
329
330 bool NeverSignedOverflows =
331 SE->isKnownPredicate(ICmpInst::ICMP_SLE, IVOpSCEV, UpperLimit);
332
333 if (NeverSignedOverflows) {
334 const SCEV *LowerDelta = SE->getSMinExpr(ZeroSCEV, OtherOpSCEV);
335 const SCEV *LowerLimit = SE->getMinusSCEV(SignedMin, LowerDelta);
336
337 bool NeverSignedUnderflows =
338 SE->isKnownPredicate(ICmpInst::ICMP_SGE, IVOpSCEV, LowerLimit);
339 if (NeverSignedUnderflows) {
340 BO->setHasNoSignedWrap(true);
341 Changed = true;
342 }
343 }
344 }
345
346 if (!BO->hasNoUnsignedWrap()) {
347 // Upgrade the add computing "IVOperand + OtherOp" to an "add nuw" if we can
348 // prove that it will never unsigned-overflow (i.e. the result will always
349 // be representable in the given bit-width).
350 //
351 // "IVOperand + OtherOp" is unsigned-representable in 2's complement iff it
352 // does not produce a carry. "IVOperand + OtherOp" produces no carry iff
353 // IVOperand ULE (UnsignedMax - OtherOp).
354
355 const SCEV *UnsignedMax =
356 SE->getConstant(APInt::getMaxValue(IT->getBitWidth()));
357 const SCEV *UpperLimit = SE->getMinusSCEV(UnsignedMax, OtherOpSCEV);
358
359 bool NeverUnsignedOverflows =
360 SE->isKnownPredicate(ICmpInst::ICMP_ULE, IVOpSCEV, UpperLimit);
361
362 if (NeverUnsignedOverflows) {
363 BO->setHasNoUnsignedWrap(true);
364 Changed = true;
365 }
366 }
367
368 return Changed;
369}
370
Andrew Trick0ba77a02013-12-23 23:31:49 +0000371/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
372/// analysis and optimization.
373///
374/// \return A new value representing the non-overflowing add if possible,
375/// otherwise return the original value.
376Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
377 const DominatorTree *DT) {
378 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
379 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
380 return IVUser;
381
382 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000383 BranchInst *Branch = nullptr;
384 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000385 for (User *U : II->users()) {
386 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000387 if (ExtractInst->getNumIndices() != 1)
388 continue;
389 if (ExtractInst->getIndices()[0] == 0)
390 AddVal = ExtractInst;
391 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000392 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000393 }
394 }
395 if (!AddVal || !Branch)
396 return IVUser;
397
398 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000399 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000400 return IVUser;
401
402 // Check if all users of the add are provably NSW.
403 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000404 for (Use &U : AddVal->uses()) {
405 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000406 BasicBlock *UseBB = UseInst->getParent();
407 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000408 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000409 if (!DT->dominates(ContinueBB, UseBB)) {
410 AllNSW = false;
411 break;
412 }
413 }
414 }
415 if (!AllNSW)
416 return IVUser;
417
418 // Go for it...
419 IRBuilder<> Builder(IVUser);
420 Instruction *AddInst = dyn_cast<Instruction>(
421 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
422
423 // The caller expects the new add to have the same form as the intrinsic. The
424 // IV operand position must be the same.
425 assert((AddInst->getOpcode() == Instruction::Add &&
426 AddInst->getOperand(0) == II->getOperand(0)) &&
427 "Bad add instruction created from overflow intrinsic.");
428
429 AddVal->replaceAllUsesWith(AddInst);
430 DeadInsts.push_back(AddVal);
431 return AddInst;
432}
433
Sanjay Patel7777b502014-11-12 18:07:42 +0000434/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000435static void pushIVUsers(
436 Instruction *Def,
437 SmallPtrSet<Instruction*,16> &Simplified,
438 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
439
Chandler Carruthcdf47882014-03-09 03:16:01 +0000440 for (User *U : Def->users()) {
441 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000442
443 // Avoid infinite or exponential worklist processing.
444 // Also ensure unique worklist users.
445 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
446 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000447 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000448 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000449 }
450}
451
Sanjay Patel7777b502014-11-12 18:07:42 +0000452/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000453/// expression in terms of that IV.
454///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000455/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000456/// non-recursively when the operand is already known to be a simpleIVUser.
457///
458static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
459 if (!SE->isSCEVable(I->getType()))
460 return false;
461
462 // Get the symbolic expression for this instruction.
463 const SCEV *S = SE->getSCEV(I);
464
465 // Only consider affine recurrences.
466 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
467 if (AR && AR->getLoop() == L)
468 return true;
469
470 return false;
471}
472
Sanjay Patel7777b502014-11-12 18:07:42 +0000473/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000474/// of the specified induction variable. Each successive simplification may push
475/// more users which may themselves be candidates for simplification.
476///
477/// This algorithm does not require IVUsers analysis. Instead, it simplifies
478/// instructions in-place during analysis. Rather than rewriting induction
479/// variables bottom-up from their users, it transforms a chain of IVUsers
480/// top-down, updating the IR only when it encouters a clear optimization
481/// opportunitiy.
482///
483/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
484///
485void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000486 if (!SE->isSCEVable(CurrIV->getType()))
487 return;
488
Andrew Trick3ec331e2011-08-10 03:46:27 +0000489 // Instructions processed by SimplifyIndvar for CurrIV.
490 SmallPtrSet<Instruction*,16> Simplified;
491
492 // Use-def pairs if IV users waiting to be processed for CurrIV.
493 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
494
495 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
496 // called multiple times for the same LoopPhi. This is the proper thing to
497 // do for loop header phis that use each other.
498 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
499
500 while (!SimpleIVUsers.empty()) {
501 std::pair<Instruction*, Instruction*> UseOper =
502 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000503 Instruction *UseInst = UseOper.first;
504
Andrew Trick3ec331e2011-08-10 03:46:27 +0000505 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000506 if (UseInst == CurrIV) continue;
507
508 if (V && V->shouldSplitOverflowInstrinsics()) {
509 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
510 if (!UseInst)
511 continue;
512 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000513
Andrew Trick74664d52011-08-10 04:01:31 +0000514 Instruction *IVOperand = UseOper.second;
515 for (unsigned N = 0; IVOperand; ++N) {
516 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000517
Andrew Trick74664d52011-08-10 04:01:31 +0000518 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
519 if (!NewOper)
520 break; // done folding
521 IVOperand = dyn_cast<Instruction>(NewOper);
522 }
523 if (!IVOperand)
524 continue;
525
526 if (eliminateIVUser(UseOper.first, IVOperand)) {
527 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000528 continue;
529 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000530
531 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
532 if (isa<OverflowingBinaryOperator>(BO) &&
533 strengthenOverflowingOperation(BO, IVOperand)) {
534 // re-queue uses of the now modified binary operator and fall
535 // through to the checks that remain.
536 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
537 }
538 }
539
Andrew Trick3ec331e2011-08-10 03:46:27 +0000540 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
541 if (V && Cast) {
542 V->visitCast(Cast);
543 continue;
544 }
545 if (isSimpleIVUser(UseOper.first, L, SE)) {
546 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
547 }
548 }
549}
550
551namespace llvm {
552
David Blaikiea379b1812011-12-20 02:50:00 +0000553void IVVisitor::anchor() { }
554
Sanjay Patel7777b502014-11-12 18:07:42 +0000555/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000556/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Tricke629d002011-08-10 04:22:26 +0000557bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000558 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
559{
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000560 DataLayoutPass *DLP = LPM->getAnalysisIfAvailable<DataLayoutPass>();
561 LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
562 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI,
563 DLP ? &DLP->getDataLayout() : nullptr, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000564 SIV.simplifyUsers(CurrIV, V);
565 return SIV.hasChanged();
566}
567
Sanjay Patel7777b502014-11-12 18:07:42 +0000568/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000569/// loop. This does not actually change or add IVs.
Andrew Tricke629d002011-08-10 04:22:26 +0000570bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000571 SmallVectorImpl<WeakVH> &Dead) {
572 bool Changed = false;
573 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Tricke629d002011-08-10 04:22:26 +0000574 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000575 }
576 return Changed;
577}
578
Andrew Trick3ec331e2011-08-10 03:46:27 +0000579} // namespace llvm