blob: ad1faea0a7ae4eef66473cfa4582eb62c4115080 [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"
Hongbin Zhengd36f20302017-10-12 02:54:11 +000021#include "llvm/Analysis/ScalarEvolutionExpander.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 Carruth8a8cd2b2014-01-07 11:48:04 +000024#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instructions.h"
David Greenb26a0a42017-07-05 13:25:58 +000026#include "llvm/IR/PatternMatch.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000029
30using namespace llvm;
31
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "indvars"
33
Andrew Trick3ec331e2011-08-10 03:46:27 +000034STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
35STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +000036STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
Andrew Trick3ec331e2011-08-10 03:46:27 +000037STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000038STATISTIC(
39 NumSimplifiedSDiv,
40 "Number of IV signed division operations converted to unsigned division");
Hongbin Zhengf0093e42017-09-25 17:39:40 +000041STATISTIC(
42 NumSimplifiedSRem,
43 "Number of IV signed remainder operations converted to unsigned remainder");
Andrew Trick3ec331e2011-08-10 03:46:27 +000044STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
45
46namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000047 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000048 /// based on ScalarEvolution. It is the primary instrument of the
49 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
50 /// other loop passes that preserve SCEV.
51 class SimplifyIndvar {
52 Loop *L;
53 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000054 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000055 DominatorTree *DT;
Hongbin Zhengd36f20302017-10-12 02:54:11 +000056 SCEVExpander &Rewriter;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000057 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000058
59 bool Changed;
60
61 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000062 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Hongbin Zhengd36f20302017-10-12 02:54:11 +000063 LoopInfo *LI, SCEVExpander &Rewriter,
64 SmallVectorImpl<WeakTrackingVH> &Dead)
65 : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
66 Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000067 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000068 }
69
70 bool hasChanged() const { return Changed; }
71
72 /// Iteratively perform simplification on a worklist of users of the
73 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000074 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000075 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000076
Andrew Trick74664d52011-08-10 04:01:31 +000077 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000078
Sanjoy Das088bb0e2015-10-06 21:44:39 +000079 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
Hongbin Zhengd36f20302017-10-12 02:54:11 +000080 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
Sanjoy Das088bb0e2015-10-06 21:44:39 +000081
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000082 bool eliminateOverflowIntrinsic(CallInst *CI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000083 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Philip Reames7b861f02017-11-01 19:49:20 +000084 bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000085 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000086 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
87 bool IsSigned);
88 void replaceRemWithNumerator(BinaryOperator *Rem);
89 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
90 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000091 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000092 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000093 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000094 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000095}
Andrew Trick3ec331e2011-08-10 03:46:27 +000096
Sanjay Patel7777b502014-11-12 18:07:42 +000097/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000098/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000099///
Andrew Trick7251e412011-09-19 17:54:39 +0000100/// IVOperand is guaranteed SCEVable, but UseInst may not be.
101///
Andrew Trick74664d52011-08-10 04:01:31 +0000102/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000103/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000104/// Otherwise return null.
105Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000106 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000107 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000108 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000109 switch (UseInst->getOpcode()) {
110 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000111 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000112 case Instruction::UDiv:
113 case Instruction::LShr:
114 // We're only interested in the case where we know something about
115 // the numerator and have a constant denominator.
116 if (IVOperand != UseInst->getOperand(OperIdx) ||
117 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000118 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000119
120 // Attempt to fold a binary operator with constant operand.
121 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000122 if (!isa<BinaryOperator>(IVOperand)
123 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000124 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000125
126 IVSrc = IVOperand->getOperand(0);
127 // IVSrc must be the (SCEVable) IV, since the other operand is const.
128 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
129
130 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
131 if (UseInst->getOpcode() == Instruction::LShr) {
132 // Get a constant for the divisor. See createSCEV.
133 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
134 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136
137 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000138 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000139 }
140 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
141 }
142 // We have something that might fold it's operand. Compare SCEVs.
143 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000144 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000145
146 // Bypass the operand if SCEV can prove it has no effect.
147 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000148 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000149
150 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
151 << " -> " << *UseInst << '\n');
152
153 UseInst->setOperand(OperIdx, IVSrc);
154 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
155
156 ++NumElimOperand;
157 Changed = true;
158 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000159 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000160 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000161}
162
Philip Reames7b861f02017-11-01 19:49:20 +0000163bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
164 Value *IVOperand) {
165 unsigned IVOperIdx = 0;
166 ICmpInst::Predicate Pred = ICmp->getPredicate();
167 if (IVOperand != ICmp->getOperand(0)) {
168 // Swapped
169 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
170 IVOperIdx = 1;
171 Pred = ICmpInst::getSwappedPredicate(Pred);
172 }
Philip Reamesdc417a92017-10-31 18:04:57 +0000173
Philip Reames7b861f02017-11-01 19:49:20 +0000174 // Get the SCEVs for the ICmp operands (in the specific context of the
175 // current loop)
176 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
177 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
178 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
179
180 ICmpInst::Predicate InvariantPredicate;
Philip Reamesdc417a92017-10-31 18:04:57 +0000181 const SCEV *InvariantLHS, *InvariantRHS;
Philip Reames7b861f02017-11-01 19:49:20 +0000182
183 auto *PN = dyn_cast<PHINode>(IVOperand);
184 if (!PN)
185 return false;
186 if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
Philip Reamesdc417a92017-10-31 18:04:57 +0000187 InvariantLHS, InvariantRHS))
188 return false;
189
190 // Rewrite the comparison to a loop invariant comparison if it can be done
191 // cheaply, where cheaply means "we don't need to emit any new
192 // instructions".
Philip Reamesdc417a92017-10-31 18:04:57 +0000193
Philip Reames7b861f02017-11-01 19:49:20 +0000194 SmallDenseMap<const SCEV*, Value*> CheapExpansions;
195 CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
196 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
197
198 // TODO: Support multiple entry loops? (We currently bail out of these in
199 // the IndVarSimplify pass)
200 if (auto *BB = L->getLoopPredecessor()) {
Philip Reames6260cf72017-12-01 20:57:19 +0000201 const int Idx = PN->getBasicBlockIndex(BB);
202 if (Idx >= 0) {
203 Value *Incoming = PN->getIncomingValue(Idx);
204 const SCEV *IncomingS = SE->getSCEV(Incoming);
205 CheapExpansions[IncomingS] = Incoming;
206 }
Philip Reames7b861f02017-11-01 19:49:20 +0000207 }
208 Value *NewLHS = CheapExpansions[InvariantLHS];
209 Value *NewRHS = CheapExpansions[InvariantRHS];
210
Philip Reames6260cf72017-12-01 20:57:19 +0000211 if (!NewLHS)
212 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
213 NewLHS = ConstLHS->getValue();
214 if (!NewRHS)
215 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
216 NewRHS = ConstRHS->getValue();
217
Philip Reames7b861f02017-11-01 19:49:20 +0000218 if (!NewLHS || !NewRHS)
219 // We could not find an existing value to replace either LHS or RHS.
220 // Generating new instructions has subtler tradeoffs, so avoid doing that
221 // for now.
222 return false;
223
224 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
225 ICmp->setPredicate(InvariantPredicate);
226 ICmp->setOperand(0, NewLHS);
227 ICmp->setOperand(1, NewRHS);
228 return true;
Philip Reamesdc417a92017-10-31 18:04:57 +0000229}
230
Sanjay Patel7777b502014-11-12 18:07:42 +0000231/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000232/// comparisons against an induction variable.
233void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
234 unsigned IVOperIdx = 0;
235 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000236 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000237 if (IVOperand != ICmp->getOperand(0)) {
238 // Swapped
239 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
240 IVOperIdx = 1;
241 Pred = ICmpInst::getSwappedPredicate(Pred);
242 }
243
Philip Reames29dd40b2017-10-26 22:02:16 +0000244 // Get the SCEVs for the ICmp operands (in the specific context of the
245 // current loop)
Andrew Trick3ec331e2011-08-10 03:46:27 +0000246 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
Philip Reames29dd40b2017-10-26 22:02:16 +0000247 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
248 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000249
250 // If the condition is always true or always false, replace it with
251 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000252 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000253 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000254 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000255 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000256 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000257 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000258 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000259 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000260 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
261 // fallthrough to end of function
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000262 } else if (ICmpInst::isSigned(OriginalPred) &&
263 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
264 // If we were unable to make anything above, all we can is to canonicalize
265 // the comparison hoping that it will open the doors for other
266 // optimizations. If we find out that we compare two non-negative values,
267 // we turn the instruction's predicate to its unsigned version. Note that
268 // we cannot rely on Pred here unless we check if we have swapped it.
269 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
270 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
271 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000272 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000273 return;
274
Andrew Trick3ec331e2011-08-10 03:46:27 +0000275 ++NumElimCmp;
276 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000277}
278
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000279bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
280 // Get the SCEVs for the ICmp operands.
281 auto *N = SE->getSCEV(SDiv->getOperand(0));
282 auto *D = SE->getSCEV(SDiv->getOperand(1));
283
284 // Simplify unnecessary loops away.
285 const Loop *L = LI->getLoopFor(SDiv->getParent());
286 N = SE->getSCEVAtScope(N, L);
287 D = SE->getSCEVAtScope(D, L);
288
289 // Replace sdiv by udiv if both of the operands are non-negative
290 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
291 auto *UDiv = BinaryOperator::Create(
292 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
293 SDiv->getName() + ".udiv", SDiv);
294 UDiv->setIsExact(SDiv->isExact());
295 SDiv->replaceAllUsesWith(UDiv);
296 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
297 ++NumSimplifiedSDiv;
298 Changed = true;
299 DeadInsts.push_back(SDiv);
300 return true;
301 }
302
303 return false;
304}
305
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000306// i %s n -> i %u n if i >= 0 and n >= 0
307void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
308 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
309 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
310 Rem->getName() + ".urem", Rem);
311 Rem->replaceAllUsesWith(URem);
312 DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
313 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000314 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000315 DeadInsts.emplace_back(Rem);
316}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000317
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000318// i % n --> i if i is in [0,n).
319void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
320 Rem->replaceAllUsesWith(Rem->getOperand(0));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000321 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
322 ++NumElimRem;
323 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000324 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000325}
326
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000327// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
328void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
329 auto *T = Rem->getType();
330 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
331 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
332 SelectInst *Sel =
333 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
334 Rem->replaceAllUsesWith(Sel);
335 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
336 ++NumElimRem;
337 Changed = true;
338 DeadInsts.emplace_back(Rem);
339}
340
341/// SimplifyIVUsers helper for eliminating useless remainder operations
342/// operating on an induction variable or replacing srem by urem.
343void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
344 bool IsSigned) {
345 auto *NValue = Rem->getOperand(0);
346 auto *DValue = Rem->getOperand(1);
347 // We're only interested in the case where we know something about
348 // the numerator, unless it is a srem, because we want to replace srem by urem
349 // in general.
350 bool UsedAsNumerator = IVOperand == NValue;
351 if (!UsedAsNumerator && !IsSigned)
352 return;
353
354 const SCEV *N = SE->getSCEV(NValue);
355
356 // Simplify unnecessary loops away.
357 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
358 N = SE->getSCEVAtScope(N, ICmpLoop);
359
360 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
361
362 // Do not proceed if the Numerator may be negative
363 if (!IsNumeratorNonNegative)
364 return;
365
366 const SCEV *D = SE->getSCEV(DValue);
367 D = SE->getSCEVAtScope(D, ICmpLoop);
368
369 if (UsedAsNumerator) {
370 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
371 if (SE->isKnownPredicate(LT, N, D)) {
372 replaceRemWithNumerator(Rem);
373 return;
374 }
375
376 auto *T = Rem->getType();
377 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
378 if (SE->isKnownPredicate(LT, NLessOne, D)) {
379 replaceRemWithNumeratorOrZero(Rem);
380 return;
381 }
382 }
383
384 // Try to replace SRem with URem, if both N and D are known non-negative.
385 // Since we had already check N, we only need to check D now
386 if (!IsSigned || !SE->isKnownNonNegative(D))
387 return;
388
389 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000390}
391
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000392bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
393 auto *F = CI->getCalledFunction();
394 if (!F)
395 return false;
396
397 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000398 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000399 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000400 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000401
402 OperationFunctionTy Operation;
403 ExtensionFunctionTy Extension;
404
405 Instruction::BinaryOps RawOp;
406
407 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
408 // have nuw.
409 bool NoSignedOverflow;
410
411 switch (F->getIntrinsicID()) {
412 default:
413 return false;
414
415 case Intrinsic::sadd_with_overflow:
416 Operation = &ScalarEvolution::getAddExpr;
417 Extension = &ScalarEvolution::getSignExtendExpr;
418 RawOp = Instruction::Add;
419 NoSignedOverflow = true;
420 break;
421
422 case Intrinsic::uadd_with_overflow:
423 Operation = &ScalarEvolution::getAddExpr;
424 Extension = &ScalarEvolution::getZeroExtendExpr;
425 RawOp = Instruction::Add;
426 NoSignedOverflow = false;
427 break;
428
429 case Intrinsic::ssub_with_overflow:
430 Operation = &ScalarEvolution::getMinusSCEV;
431 Extension = &ScalarEvolution::getSignExtendExpr;
432 RawOp = Instruction::Sub;
433 NoSignedOverflow = true;
434 break;
435
436 case Intrinsic::usub_with_overflow:
437 Operation = &ScalarEvolution::getMinusSCEV;
438 Extension = &ScalarEvolution::getZeroExtendExpr;
439 RawOp = Instruction::Sub;
440 NoSignedOverflow = false;
441 break;
442 }
443
444 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
445 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
446
447 auto *NarrowTy = cast<IntegerType>(LHS->getType());
448 auto *WideTy =
449 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
450
451 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000452 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
453 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000454 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000455 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
456 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000457
458 if (A != B)
459 return false;
460
461 // Proved no overflow, nuke the overflow check and, if possible, the overflow
462 // intrinsic as well.
463
464 BinaryOperator *NewResult = BinaryOperator::Create(
465 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
466
467 if (NoSignedOverflow)
468 NewResult->setHasNoSignedWrap(true);
469 else
470 NewResult->setHasNoUnsignedWrap(true);
471
472 SmallVector<ExtractValueInst *, 4> ToDelete;
473
474 for (auto *U : CI->users()) {
475 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
476 if (EVI->getIndices()[0] == 1)
477 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
478 else {
479 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
480 EVI->replaceAllUsesWith(NewResult);
481 }
482 ToDelete.push_back(EVI);
483 }
484 }
485
486 for (auto *EVI : ToDelete)
487 EVI->eraseFromParent();
488
489 if (CI->use_empty())
490 CI->eraseFromParent();
491
492 return true;
493}
494
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000495/// Eliminate an operation that consumes a simple IV and has no observable
496/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
497/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000498bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
499 Instruction *IVOperand) {
500 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
501 eliminateIVComparison(ICmp, IVOperand);
502 return true;
503 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000504 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
505 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
506 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000507 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000508 return true;
509 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000510
511 if (Bin->getOpcode() == Instruction::SDiv)
512 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000513 }
514
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000515 if (auto *CI = dyn_cast<CallInst>(UseInst))
516 if (eliminateOverflowIntrinsic(CI))
517 return true;
518
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000519 if (eliminateIdentitySCEV(UseInst, IVOperand))
520 return true;
521
522 return false;
523}
524
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000525static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
526 if (auto *BB = L->getLoopPreheader())
527 return BB->getTerminator();
528
529 return Hint;
530}
531
532/// Replace the UseInst with a constant if possible.
533bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000534 if (!SE->isSCEVable(I->getType()))
535 return false;
536
537 // Get the symbolic expression for this instruction.
538 const SCEV *S = SE->getSCEV(I);
539
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000540 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000541 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000542
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000543 // Do not generate something ridiculous even if S is loop invariant.
544 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000545 return false;
546
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000547 auto *IP = GetLoopInvariantInsertPosition(L, I);
548 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
549
550 I->replaceAllUsesWith(Invariant);
551 DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
552 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000553 ++NumFoldedUser;
554 Changed = true;
555 DeadInsts.emplace_back(I);
556 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000557}
558
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000559/// Eliminate any operation that SCEV can prove is an identity function.
560bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
561 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000562 if (!SE->isSCEVable(UseInst->getType()) ||
563 (UseInst->getType() != IVOperand->getType()) ||
564 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
565 return false;
566
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000567 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
568 // dominator tree, even if X is an operand to Y. For instance, in
569 //
570 // %iv = phi i32 {0,+,1}
571 // br %cond, label %left, label %merge
572 //
573 // left:
574 // %X = add i32 %iv, 0
575 // br label %merge
576 //
577 // merge:
578 // %M = phi (%X, %iv)
579 //
580 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
581 // %M.replaceAllUsesWith(%X) would be incorrect.
582
583 if (isa<PHINode>(UseInst))
584 // If UseInst is not a PHI node then we know that IVOperand dominates
585 // UseInst directly from the legality of SSA.
586 if (!DT || !DT->dominates(IVOperand, UseInst))
587 return false;
588
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000589 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
590 return false;
591
Andrew Trick3ec331e2011-08-10 03:46:27 +0000592 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
593
594 UseInst->replaceAllUsesWith(IVOperand);
595 ++NumElimIdentity;
596 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000597 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000598 return true;
599}
600
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000601/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
602/// unsigned-overflow. Returns true if anything changed, false otherwise.
603bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
604 Value *IVOperand) {
605
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000606 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000607 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
608 return false;
609
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000610 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000611 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000612 switch (BO->getOpcode()) {
613 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000614 return false;
615
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000616 case Instruction::Add:
617 GetExprForBO = &ScalarEvolution::getAddExpr;
618 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000619
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000620 case Instruction::Sub:
621 GetExprForBO = &ScalarEvolution::getMinusSCEV;
622 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000623
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000624 case Instruction::Mul:
625 GetExprForBO = &ScalarEvolution::getMulExpr;
626 break;
627 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000628
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000629 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
630 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
631 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
632 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000633
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000634 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000635
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000636 if (!BO->hasNoUnsignedWrap()) {
637 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
638 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
639 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000640 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000641 if (ExtendAfterOp == OpAfterExtend) {
642 BO->setHasNoUnsignedWrap();
643 SE->forgetValue(BO);
644 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000645 }
646 }
647
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000648 if (!BO->hasNoSignedWrap()) {
649 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
650 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
651 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000652 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000653 if (ExtendAfterOp == OpAfterExtend) {
654 BO->setHasNoSignedWrap();
655 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000656 Changed = true;
657 }
658 }
659
660 return Changed;
661}
662
David Greenb26a0a42017-07-05 13:25:58 +0000663/// Annotate the Shr in (X << IVOperand) >> C as exact using the
664/// information from the IV's range. Returns true if anything changed, false
665/// otherwise.
666bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
667 Value *IVOperand) {
668 using namespace llvm::PatternMatch;
669
670 if (BO->getOpcode() == Instruction::Shl) {
671 bool Changed = false;
672 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
673 for (auto *U : BO->users()) {
674 const APInt *C;
675 if (match(U,
676 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
677 match(U,
678 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
679 BinaryOperator *Shr = cast<BinaryOperator>(U);
680 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
681 Shr->setIsExact(true);
682 Changed = true;
683 }
684 }
685 }
686 return Changed;
687 }
688
689 return false;
690}
691
Sanjay Patel7777b502014-11-12 18:07:42 +0000692/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000693static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000694 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000695 SmallPtrSet<Instruction*,16> &Simplified,
696 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
697
Chandler Carruthcdf47882014-03-09 03:16:01 +0000698 for (User *U : Def->users()) {
699 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000700
701 // Avoid infinite or exponential worklist processing.
702 // Also ensure unique worklist users.
703 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
704 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000705 if (UI == Def)
706 continue;
707
708 // Only change the current Loop, do not change the other parts (e.g. other
709 // Loops).
710 if (!L->contains(UI))
711 continue;
712
713 // Do not push the same instruction more than once.
714 if (!Simplified.insert(UI).second)
715 continue;
716
717 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000718 }
719}
720
Sanjay Patel7777b502014-11-12 18:07:42 +0000721/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000722/// expression in terms of that IV.
723///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000724/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000725/// non-recursively when the operand is already known to be a simpleIVUser.
726///
727static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
728 if (!SE->isSCEVable(I->getType()))
729 return false;
730
731 // Get the symbolic expression for this instruction.
732 const SCEV *S = SE->getSCEV(I);
733
734 // Only consider affine recurrences.
735 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
736 if (AR && AR->getLoop() == L)
737 return true;
738
739 return false;
740}
741
Sanjay Patel7777b502014-11-12 18:07:42 +0000742/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000743/// of the specified induction variable. Each successive simplification may push
744/// more users which may themselves be candidates for simplification.
745///
746/// This algorithm does not require IVUsers analysis. Instead, it simplifies
747/// instructions in-place during analysis. Rather than rewriting induction
748/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000749/// top-down, updating the IR only when it encounters a clear optimization
750/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000751///
752/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
753///
754void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000755 if (!SE->isSCEVable(CurrIV->getType()))
756 return;
757
Andrew Trick3ec331e2011-08-10 03:46:27 +0000758 // Instructions processed by SimplifyIndvar for CurrIV.
759 SmallPtrSet<Instruction*,16> Simplified;
760
761 // Use-def pairs if IV users waiting to be processed for CurrIV.
762 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
763
764 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
765 // called multiple times for the same LoopPhi. This is the proper thing to
766 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000767 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000768
769 while (!SimpleIVUsers.empty()) {
770 std::pair<Instruction*, Instruction*> UseOper =
771 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000772 Instruction *UseInst = UseOper.first;
773
Andrew Trick3ec331e2011-08-10 03:46:27 +0000774 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000775 if (UseInst == CurrIV) continue;
776
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000777 // Try to replace UseInst with a loop invariant before any other
778 // simplifications.
779 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000780 continue;
781
Andrew Trick74664d52011-08-10 04:01:31 +0000782 Instruction *IVOperand = UseOper.second;
783 for (unsigned N = 0; IVOperand; ++N) {
784 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000785
Andrew Trick74664d52011-08-10 04:01:31 +0000786 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
787 if (!NewOper)
788 break; // done folding
789 IVOperand = dyn_cast<Instruction>(NewOper);
790 }
791 if (!IVOperand)
792 continue;
793
794 if (eliminateIVUser(UseOper.first, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000795 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000796 continue;
797 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000798
799 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000800 if ((isa<OverflowingBinaryOperator>(BO) &&
801 strengthenOverflowingOperation(BO, IVOperand)) ||
802 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000803 // re-queue uses of the now modified binary operator and fall
804 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000805 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000806 }
807 }
808
Andrew Trick3ec331e2011-08-10 03:46:27 +0000809 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
810 if (V && Cast) {
811 V->visitCast(Cast);
812 continue;
813 }
814 if (isSimpleIVUser(UseOper.first, L, SE)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000815 pushIVUsers(UseOper.first, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000816 }
817 }
818}
819
820namespace llvm {
821
David Blaikiea379b1812011-12-20 02:50:00 +0000822void IVVisitor::anchor() { }
823
Sanjay Patel7777b502014-11-12 18:07:42 +0000824/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000825/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000826bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000827 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000828 SCEVExpander &Rewriter, IVVisitor *V) {
829 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
830 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000831 SIV.simplifyUsers(CurrIV, V);
832 return SIV.hasChanged();
833}
834
Sanjay Patel7777b502014-11-12 18:07:42 +0000835/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000836/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000837bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000838 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000839 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
840#ifndef NDEBUG
841 Rewriter.setDebugType(DEBUG_TYPE);
842#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000843 bool Changed = false;
844 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000845 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000846 }
847 return Changed;
848}
849
Andrew Trick3ec331e2011-08-10 03:46:27 +0000850} // namespace llvm