blob: 5228f067ae1f9ecf08da5d64b28e63c3937b0e41 [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/LoopInfo.h"
21#include "llvm/Analysis/LoopPass.h"
22#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000025#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
Andrew Trick0ba77a02013-12-23 23:31:49 +000027#include "llvm/IR/IntrinsicInst.h"
David Greenb26a0a42017-07-05 13:25:58 +000028#include "llvm/IR/PatternMatch.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000031
32using namespace llvm;
33
Chandler Carruth964daaa2014-04-22 02:55:47 +000034#define DEBUG_TYPE "indvars"
35
Andrew Trick3ec331e2011-08-10 03:46:27 +000036STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
37STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
38STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000039STATISTIC(
40 NumSimplifiedSDiv,
41 "Number of IV signed division operations converted to unsigned division");
Hongbin Zhengf0093e42017-09-25 17:39:40 +000042STATISTIC(
43 NumSimplifiedSRem,
44 "Number of IV signed remainder operations converted to unsigned remainder");
Andrew Trick3ec331e2011-08-10 03:46:27 +000045STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
46
47namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000048 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000049 /// based on ScalarEvolution. It is the primary instrument of the
50 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
51 /// other loop passes that preserve SCEV.
52 class SimplifyIndvar {
53 Loop *L;
54 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000055 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000056 DominatorTree *DT;
Andrew Trick3ec331e2011-08-10 03:46:27 +000057
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000058 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000059
60 bool Changed;
61
62 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000063 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000064 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead)
Sanjoy Das5c8bead2015-10-06 21:44:49 +000065 : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000066 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000067 }
68
69 bool hasChanged() const { return Changed; }
70
71 /// Iteratively perform simplification on a worklist of users of the
72 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000073 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000074 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000075
Andrew Trick74664d52011-08-10 04:01:31 +000076 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000077
Sanjoy Das088bb0e2015-10-06 21:44:39 +000078 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
79
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000080 bool eliminateOverflowIntrinsic(CallInst *CI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000081 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
82 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000083 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
84 bool IsSigned);
85 void replaceRemWithNumerator(BinaryOperator *Rem);
86 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
87 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000088 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000089 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000090 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000091 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000092}
Andrew Trick3ec331e2011-08-10 03:46:27 +000093
Sanjay Patel7777b502014-11-12 18:07:42 +000094/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000095/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000096///
Andrew Trick7251e412011-09-19 17:54:39 +000097/// IVOperand is guaranteed SCEVable, but UseInst may not be.
98///
Andrew Trick74664d52011-08-10 04:01:31 +000099/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000100/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000101/// Otherwise return null.
102Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000103 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000104 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000105 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000106 switch (UseInst->getOpcode()) {
107 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000108 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000109 case Instruction::UDiv:
110 case Instruction::LShr:
111 // We're only interested in the case where we know something about
112 // the numerator and have a constant denominator.
113 if (IVOperand != UseInst->getOperand(OperIdx) ||
114 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000115 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000116
117 // Attempt to fold a binary operator with constant operand.
118 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000119 if (!isa<BinaryOperator>(IVOperand)
120 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000121 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000122
123 IVSrc = IVOperand->getOperand(0);
124 // IVSrc must be the (SCEVable) IV, since the other operand is const.
125 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
126
127 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
128 if (UseInst->getOpcode() == Instruction::LShr) {
129 // Get a constant for the divisor. See createSCEV.
130 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
131 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000132 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000133
134 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000135 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136 }
137 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
138 }
139 // We have something that might fold it's operand. Compare SCEVs.
140 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000141 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000142
143 // Bypass the operand if SCEV can prove it has no effect.
144 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000145 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000146
147 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
148 << " -> " << *UseInst << '\n');
149
150 UseInst->setOperand(OperIdx, IVSrc);
151 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
152
153 ++NumElimOperand;
154 Changed = true;
155 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000156 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000157 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000158}
159
Sanjay Patel7777b502014-11-12 18:07:42 +0000160/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000161/// comparisons against an induction variable.
162void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
163 unsigned IVOperIdx = 0;
164 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000165 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000166 if (IVOperand != ICmp->getOperand(0)) {
167 // Swapped
168 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
169 IVOperIdx = 1;
170 Pred = ICmpInst::getSwappedPredicate(Pred);
171 }
172
173 // Get the SCEVs for the ICmp operands.
174 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
175 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
176
177 // Simplify unnecessary loops away.
178 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
179 S = SE->getSCEVAtScope(S, ICmpLoop);
180 X = SE->getSCEVAtScope(X, ICmpLoop);
181
Sanjoy Das5dab2052015-07-27 21:42:49 +0000182 ICmpInst::Predicate InvariantPredicate;
183 const SCEV *InvariantLHS, *InvariantRHS;
184
Andrew Trick3ec331e2011-08-10 03:46:27 +0000185 // If the condition is always true or always false, replace it with
186 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000187 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000188 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000189 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000190 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000191 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000192 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000193 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000194 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000195 } else if (isa<PHINode>(IVOperand) &&
Sanjoy Das60fb8992016-03-18 20:37:07 +0000196 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
197 InvariantLHS, InvariantRHS)) {
Sanjoy Das5dab2052015-07-27 21:42:49 +0000198
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000199 // Rewrite the comparison to a loop invariant comparison if it can be done
Sanjoy Das5dab2052015-07-27 21:42:49 +0000200 // cheaply, where cheaply means "we don't need to emit any new
201 // instructions".
202
203 Value *NewLHS = nullptr, *NewRHS = nullptr;
204
205 if (S == InvariantLHS || X == InvariantLHS)
206 NewLHS =
207 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
208
209 if (S == InvariantRHS || X == InvariantRHS)
210 NewRHS =
211 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
212
Sanjoy Das74af78e32016-03-18 20:37:11 +0000213 auto *PN = cast<PHINode>(IVOperand);
214 for (unsigned i = 0, e = PN->getNumIncomingValues();
215 i != e && (!NewLHS || !NewRHS);
216 ++i) {
217
218 // If this is a value incoming from the backedge, then it cannot be a loop
219 // invariant value (since we know that IVOperand is an induction variable).
220 if (L->contains(PN->getIncomingBlock(i)))
221 continue;
222
223 // NB! This following assert does not fundamentally have to be true, but
224 // it is true today given how SCEV analyzes induction variables.
225 // Specifically, today SCEV will *not* recognize %iv as an induction
226 // variable in the following case:
227 //
228 // define void @f(i32 %k) {
229 // entry:
230 // br i1 undef, label %r, label %l
231 //
232 // l:
233 // %k.inc.l = add i32 %k, 1
234 // br label %loop
235 //
236 // r:
237 // %k.inc.r = add i32 %k, 1
238 // br label %loop
239 //
240 // loop:
241 // %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
242 // %iv.inc = add i32 %iv, 1
243 // br label %loop
244 // }
245 //
246 // but if it starts to, at some point, then the assertion below will have
247 // to be changed to a runtime check.
248
249 Value *Incoming = PN->getIncomingValue(i);
250
251#ifndef NDEBUG
252 if (auto *I = dyn_cast<Instruction>(Incoming))
253 assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
254#endif
Sanjoy Das5dab2052015-07-27 21:42:49 +0000255
256 const SCEV *IncomingS = SE->getSCEV(Incoming);
257
258 if (!NewLHS && IncomingS == InvariantLHS)
259 NewLHS = Incoming;
260 if (!NewRHS && IncomingS == InvariantRHS)
261 NewRHS = Incoming;
262 }
263
264 if (!NewLHS || !NewRHS)
265 // We could not find an existing value to replace either LHS or RHS.
266 // Generating new instructions has subtler tradeoffs, so avoid doing that
267 // for now.
268 return;
269
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000270 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000271 ICmp->setPredicate(InvariantPredicate);
272 ICmp->setOperand(0, NewLHS);
273 ICmp->setOperand(1, NewRHS);
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000274 } else if (ICmpInst::isSigned(OriginalPred) &&
275 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
276 // If we were unable to make anything above, all we can is to canonicalize
277 // the comparison hoping that it will open the doors for other
278 // optimizations. If we find out that we compare two non-negative values,
279 // we turn the instruction's predicate to its unsigned version. Note that
280 // we cannot rely on Pred here unless we check if we have swapped it.
281 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
282 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
283 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000284 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000285 return;
286
Andrew Trick3ec331e2011-08-10 03:46:27 +0000287 ++NumElimCmp;
288 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000289}
290
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000291bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
292 // Get the SCEVs for the ICmp operands.
293 auto *N = SE->getSCEV(SDiv->getOperand(0));
294 auto *D = SE->getSCEV(SDiv->getOperand(1));
295
296 // Simplify unnecessary loops away.
297 const Loop *L = LI->getLoopFor(SDiv->getParent());
298 N = SE->getSCEVAtScope(N, L);
299 D = SE->getSCEVAtScope(D, L);
300
301 // Replace sdiv by udiv if both of the operands are non-negative
302 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
303 auto *UDiv = BinaryOperator::Create(
304 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
305 SDiv->getName() + ".udiv", SDiv);
306 UDiv->setIsExact(SDiv->isExact());
307 SDiv->replaceAllUsesWith(UDiv);
308 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
309 ++NumSimplifiedSDiv;
310 Changed = true;
311 DeadInsts.push_back(SDiv);
312 return true;
313 }
314
315 return false;
316}
317
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000318// i %s n -> i %u n if i >= 0 and n >= 0
319void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
320 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
321 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
322 Rem->getName() + ".urem", Rem);
323 Rem->replaceAllUsesWith(URem);
324 DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
325 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000326 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000327 DeadInsts.emplace_back(Rem);
328}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000329
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000330// i % n --> i if i is in [0,n).
331void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
332 Rem->replaceAllUsesWith(Rem->getOperand(0));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000333 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
334 ++NumElimRem;
335 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000336 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000337}
338
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000339// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
340void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
341 auto *T = Rem->getType();
342 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
343 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
344 SelectInst *Sel =
345 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
346 Rem->replaceAllUsesWith(Sel);
347 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
348 ++NumElimRem;
349 Changed = true;
350 DeadInsts.emplace_back(Rem);
351}
352
353/// SimplifyIVUsers helper for eliminating useless remainder operations
354/// operating on an induction variable or replacing srem by urem.
355void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
356 bool IsSigned) {
357 auto *NValue = Rem->getOperand(0);
358 auto *DValue = Rem->getOperand(1);
359 // We're only interested in the case where we know something about
360 // the numerator, unless it is a srem, because we want to replace srem by urem
361 // in general.
362 bool UsedAsNumerator = IVOperand == NValue;
363 if (!UsedAsNumerator && !IsSigned)
364 return;
365
366 const SCEV *N = SE->getSCEV(NValue);
367
368 // Simplify unnecessary loops away.
369 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
370 N = SE->getSCEVAtScope(N, ICmpLoop);
371
372 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
373
374 // Do not proceed if the Numerator may be negative
375 if (!IsNumeratorNonNegative)
376 return;
377
378 const SCEV *D = SE->getSCEV(DValue);
379 D = SE->getSCEVAtScope(D, ICmpLoop);
380
381 if (UsedAsNumerator) {
382 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
383 if (SE->isKnownPredicate(LT, N, D)) {
384 replaceRemWithNumerator(Rem);
385 return;
386 }
387
388 auto *T = Rem->getType();
389 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
390 if (SE->isKnownPredicate(LT, NLessOne, D)) {
391 replaceRemWithNumeratorOrZero(Rem);
392 return;
393 }
394 }
395
396 // Try to replace SRem with URem, if both N and D are known non-negative.
397 // Since we had already check N, we only need to check D now
398 if (!IsSigned || !SE->isKnownNonNegative(D))
399 return;
400
401 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000402}
403
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000404bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
405 auto *F = CI->getCalledFunction();
406 if (!F)
407 return false;
408
409 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000410 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000411 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000412 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000413
414 OperationFunctionTy Operation;
415 ExtensionFunctionTy Extension;
416
417 Instruction::BinaryOps RawOp;
418
419 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
420 // have nuw.
421 bool NoSignedOverflow;
422
423 switch (F->getIntrinsicID()) {
424 default:
425 return false;
426
427 case Intrinsic::sadd_with_overflow:
428 Operation = &ScalarEvolution::getAddExpr;
429 Extension = &ScalarEvolution::getSignExtendExpr;
430 RawOp = Instruction::Add;
431 NoSignedOverflow = true;
432 break;
433
434 case Intrinsic::uadd_with_overflow:
435 Operation = &ScalarEvolution::getAddExpr;
436 Extension = &ScalarEvolution::getZeroExtendExpr;
437 RawOp = Instruction::Add;
438 NoSignedOverflow = false;
439 break;
440
441 case Intrinsic::ssub_with_overflow:
442 Operation = &ScalarEvolution::getMinusSCEV;
443 Extension = &ScalarEvolution::getSignExtendExpr;
444 RawOp = Instruction::Sub;
445 NoSignedOverflow = true;
446 break;
447
448 case Intrinsic::usub_with_overflow:
449 Operation = &ScalarEvolution::getMinusSCEV;
450 Extension = &ScalarEvolution::getZeroExtendExpr;
451 RawOp = Instruction::Sub;
452 NoSignedOverflow = false;
453 break;
454 }
455
456 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
457 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
458
459 auto *NarrowTy = cast<IntegerType>(LHS->getType());
460 auto *WideTy =
461 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
462
463 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000464 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
465 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000466 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000467 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
468 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000469
470 if (A != B)
471 return false;
472
473 // Proved no overflow, nuke the overflow check and, if possible, the overflow
474 // intrinsic as well.
475
476 BinaryOperator *NewResult = BinaryOperator::Create(
477 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
478
479 if (NoSignedOverflow)
480 NewResult->setHasNoSignedWrap(true);
481 else
482 NewResult->setHasNoUnsignedWrap(true);
483
484 SmallVector<ExtractValueInst *, 4> ToDelete;
485
486 for (auto *U : CI->users()) {
487 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
488 if (EVI->getIndices()[0] == 1)
489 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
490 else {
491 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
492 EVI->replaceAllUsesWith(NewResult);
493 }
494 ToDelete.push_back(EVI);
495 }
496 }
497
498 for (auto *EVI : ToDelete)
499 EVI->eraseFromParent();
500
501 if (CI->use_empty())
502 CI->eraseFromParent();
503
504 return true;
505}
506
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000507/// Eliminate an operation that consumes a simple IV and has no observable
508/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
509/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000510bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
511 Instruction *IVOperand) {
512 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
513 eliminateIVComparison(ICmp, IVOperand);
514 return true;
515 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000516 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
517 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
518 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000519 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000520 return true;
521 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000522
523 if (Bin->getOpcode() == Instruction::SDiv)
524 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000525 }
526
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000527 if (auto *CI = dyn_cast<CallInst>(UseInst))
528 if (eliminateOverflowIntrinsic(CI))
529 return true;
530
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000531 if (eliminateIdentitySCEV(UseInst, IVOperand))
532 return true;
533
534 return false;
535}
536
537/// Eliminate any operation that SCEV can prove is an identity function.
538bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
539 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000540 if (!SE->isSCEVable(UseInst->getType()) ||
541 (UseInst->getType() != IVOperand->getType()) ||
542 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
543 return false;
544
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000545 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
546 // dominator tree, even if X is an operand to Y. For instance, in
547 //
548 // %iv = phi i32 {0,+,1}
549 // br %cond, label %left, label %merge
550 //
551 // left:
552 // %X = add i32 %iv, 0
553 // br label %merge
554 //
555 // merge:
556 // %M = phi (%X, %iv)
557 //
558 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
559 // %M.replaceAllUsesWith(%X) would be incorrect.
560
561 if (isa<PHINode>(UseInst))
562 // If UseInst is not a PHI node then we know that IVOperand dominates
563 // UseInst directly from the legality of SSA.
564 if (!DT || !DT->dominates(IVOperand, UseInst))
565 return false;
566
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000567 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
568 return false;
569
Andrew Trick3ec331e2011-08-10 03:46:27 +0000570 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
571
572 UseInst->replaceAllUsesWith(IVOperand);
573 ++NumElimIdentity;
574 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000575 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000576 return true;
577}
578
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000579/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
580/// unsigned-overflow. Returns true if anything changed, false otherwise.
581bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
582 Value *IVOperand) {
583
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000584 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000585 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
586 return false;
587
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000588 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000589 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000590 switch (BO->getOpcode()) {
591 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000592 return false;
593
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000594 case Instruction::Add:
595 GetExprForBO = &ScalarEvolution::getAddExpr;
596 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000597
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000598 case Instruction::Sub:
599 GetExprForBO = &ScalarEvolution::getMinusSCEV;
600 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000601
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000602 case Instruction::Mul:
603 GetExprForBO = &ScalarEvolution::getMulExpr;
604 break;
605 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000606
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000607 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
608 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
609 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
610 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000611
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000612 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000613
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000614 if (!BO->hasNoUnsignedWrap()) {
615 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
616 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
617 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000618 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000619 if (ExtendAfterOp == OpAfterExtend) {
620 BO->setHasNoUnsignedWrap();
621 SE->forgetValue(BO);
622 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000623 }
624 }
625
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000626 if (!BO->hasNoSignedWrap()) {
627 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
628 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
629 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000630 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000631 if (ExtendAfterOp == OpAfterExtend) {
632 BO->setHasNoSignedWrap();
633 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000634 Changed = true;
635 }
636 }
637
638 return Changed;
639}
640
David Greenb26a0a42017-07-05 13:25:58 +0000641/// Annotate the Shr in (X << IVOperand) >> C as exact using the
642/// information from the IV's range. Returns true if anything changed, false
643/// otherwise.
644bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
645 Value *IVOperand) {
646 using namespace llvm::PatternMatch;
647
648 if (BO->getOpcode() == Instruction::Shl) {
649 bool Changed = false;
650 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
651 for (auto *U : BO->users()) {
652 const APInt *C;
653 if (match(U,
654 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
655 match(U,
656 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
657 BinaryOperator *Shr = cast<BinaryOperator>(U);
658 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
659 Shr->setIsExact(true);
660 Changed = true;
661 }
662 }
663 }
664 return Changed;
665 }
666
667 return false;
668}
669
Sanjay Patel7777b502014-11-12 18:07:42 +0000670/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000671static void pushIVUsers(
672 Instruction *Def,
673 SmallPtrSet<Instruction*,16> &Simplified,
674 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
675
Chandler Carruthcdf47882014-03-09 03:16:01 +0000676 for (User *U : Def->users()) {
677 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000678
679 // Avoid infinite or exponential worklist processing.
680 // Also ensure unique worklist users.
681 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
682 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000683 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000684 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000685 }
686}
687
Sanjay Patel7777b502014-11-12 18:07:42 +0000688/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000689/// expression in terms of that IV.
690///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000691/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000692/// non-recursively when the operand is already known to be a simpleIVUser.
693///
694static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
695 if (!SE->isSCEVable(I->getType()))
696 return false;
697
698 // Get the symbolic expression for this instruction.
699 const SCEV *S = SE->getSCEV(I);
700
701 // Only consider affine recurrences.
702 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
703 if (AR && AR->getLoop() == L)
704 return true;
705
706 return false;
707}
708
Sanjay Patel7777b502014-11-12 18:07:42 +0000709/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000710/// of the specified induction variable. Each successive simplification may push
711/// more users which may themselves be candidates for simplification.
712///
713/// This algorithm does not require IVUsers analysis. Instead, it simplifies
714/// instructions in-place during analysis. Rather than rewriting induction
715/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000716/// top-down, updating the IR only when it encounters a clear optimization
717/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000718///
719/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
720///
721void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000722 if (!SE->isSCEVable(CurrIV->getType()))
723 return;
724
Andrew Trick3ec331e2011-08-10 03:46:27 +0000725 // Instructions processed by SimplifyIndvar for CurrIV.
726 SmallPtrSet<Instruction*,16> Simplified;
727
728 // Use-def pairs if IV users waiting to be processed for CurrIV.
729 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
730
731 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
732 // called multiple times for the same LoopPhi. This is the proper thing to
733 // do for loop header phis that use each other.
734 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
735
736 while (!SimpleIVUsers.empty()) {
737 std::pair<Instruction*, Instruction*> UseOper =
738 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000739 Instruction *UseInst = UseOper.first;
740
Andrew Trick3ec331e2011-08-10 03:46:27 +0000741 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000742 if (UseInst == CurrIV) continue;
743
Andrew Trick74664d52011-08-10 04:01:31 +0000744 Instruction *IVOperand = UseOper.second;
745 for (unsigned N = 0; IVOperand; ++N) {
746 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000747
Andrew Trick74664d52011-08-10 04:01:31 +0000748 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
749 if (!NewOper)
750 break; // done folding
751 IVOperand = dyn_cast<Instruction>(NewOper);
752 }
753 if (!IVOperand)
754 continue;
755
756 if (eliminateIVUser(UseOper.first, IVOperand)) {
757 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000758 continue;
759 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000760
761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000762 if ((isa<OverflowingBinaryOperator>(BO) &&
763 strengthenOverflowingOperation(BO, IVOperand)) ||
764 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000765 // re-queue uses of the now modified binary operator and fall
766 // through to the checks that remain.
767 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
768 }
769 }
770
Andrew Trick3ec331e2011-08-10 03:46:27 +0000771 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
772 if (V && Cast) {
773 V->visitCast(Cast);
774 continue;
775 }
776 if (isSimpleIVUser(UseOper.first, L, SE)) {
777 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
778 }
779 }
780}
781
782namespace llvm {
783
David Blaikiea379b1812011-12-20 02:50:00 +0000784void IVVisitor::anchor() { }
785
Sanjay Patel7777b502014-11-12 18:07:42 +0000786/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000787/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000788bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000789 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Justin Bogner843fb202015-12-15 19:40:57 +0000790 IVVisitor *V) {
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000791 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000792 SIV.simplifyUsers(CurrIV, V);
793 return SIV.hasChanged();
794}
795
Sanjay Patel7777b502014-11-12 18:07:42 +0000796/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000797/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000798bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000799 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000800 bool Changed = false;
801 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Justin Bogner843fb202015-12-15 19:40:57 +0000802 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000803 }
804 return Changed;
805}
806
Andrew Trick3ec331e2011-08-10 03:46:27 +0000807} // namespace llvm