blob: a417b037314c96f847e38d0a37d674e359d24859 [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"
Max Kazantsev0ed79622018-06-13 02:25:32 +000029#include "llvm/Transforms/Utils/Local.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000030
31using namespace llvm;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "indvars"
34
Andrew Trick3ec331e2011-08-10 03:46:27 +000035STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
36STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +000037STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
Andrew Trick3ec331e2011-08-10 03:46:27 +000038STATISTIC(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;
Hongbin Zhengd36f20302017-10-12 02:54:11 +000057 SCEVExpander &Rewriter;
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,
Hongbin Zhengd36f20302017-10-12 02:54:11 +000064 LoopInfo *LI, SCEVExpander &Rewriter,
65 SmallVectorImpl<WeakTrackingVH> &Dead)
66 : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
67 Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000068 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000069 }
70
71 bool hasChanged() const { return Changed; }
72
73 /// Iteratively perform simplification on a worklist of users of the
74 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000075 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000076 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000077
Andrew Trick74664d52011-08-10 04:01:31 +000078 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000079
Sanjoy Das088bb0e2015-10-06 21:44:39 +000080 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
Hongbin Zhengd36f20302017-10-12 02:54:11 +000081 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
Sanjoy Das088bb0e2015-10-06 21:44:39 +000082
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000083 bool eliminateOverflowIntrinsic(CallInst *CI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000084 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Philip Reames7b861f02017-11-01 19:49:20 +000085 bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000086 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000087 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
88 bool IsSigned);
89 void replaceRemWithNumerator(BinaryOperator *Rem);
90 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
91 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000092 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000093 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000094 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000095 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000096}
Andrew Trick3ec331e2011-08-10 03:46:27 +000097
Sanjay Patel7777b502014-11-12 18:07:42 +000098/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000099/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +0000100///
Andrew Trick7251e412011-09-19 17:54:39 +0000101/// IVOperand is guaranteed SCEVable, but UseInst may not be.
102///
Andrew Trick74664d52011-08-10 04:01:31 +0000103/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000104/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000105/// Otherwise return null.
106Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000107 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000108 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000109 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000110 switch (UseInst->getOpcode()) {
111 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000113 case Instruction::UDiv:
114 case Instruction::LShr:
115 // We're only interested in the case where we know something about
116 // the numerator and have a constant denominator.
117 if (IVOperand != UseInst->getOperand(OperIdx) ||
118 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000120
121 // Attempt to fold a binary operator with constant operand.
122 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000123 if (!isa<BinaryOperator>(IVOperand)
124 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000125 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000126
127 IVSrc = IVOperand->getOperand(0);
128 // IVSrc must be the (SCEVable) IV, since the other operand is const.
129 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
130
131 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
132 if (UseInst->getOpcode() == Instruction::LShr) {
133 // Get a constant for the divisor. See createSCEV.
134 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
135 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000137
138 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000139 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000140 }
141 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
142 }
143 // We have something that might fold it's operand. Compare SCEVs.
144 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000145 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000146
147 // Bypass the operand if SCEV can prove it has no effect.
148 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000149 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000150
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000151 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
152 << " -> " << *UseInst << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000153
154 UseInst->setOperand(OperIdx, IVSrc);
155 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
156
157 ++NumElimOperand;
158 Changed = true;
159 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000160 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000161 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000162}
163
Philip Reames7b861f02017-11-01 19:49:20 +0000164bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
165 Value *IVOperand) {
166 unsigned IVOperIdx = 0;
167 ICmpInst::Predicate Pred = ICmp->getPredicate();
168 if (IVOperand != ICmp->getOperand(0)) {
169 // Swapped
170 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
171 IVOperIdx = 1;
172 Pred = ICmpInst::getSwappedPredicate(Pred);
173 }
Philip Reamesdc417a92017-10-31 18:04:57 +0000174
Philip Reames7b861f02017-11-01 19:49:20 +0000175 // Get the SCEVs for the ICmp operands (in the specific context of the
176 // current loop)
177 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
178 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
179 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
180
181 ICmpInst::Predicate InvariantPredicate;
Philip Reamesdc417a92017-10-31 18:04:57 +0000182 const SCEV *InvariantLHS, *InvariantRHS;
Philip Reames7b861f02017-11-01 19:49:20 +0000183
184 auto *PN = dyn_cast<PHINode>(IVOperand);
185 if (!PN)
186 return false;
187 if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
Philip Reamesdc417a92017-10-31 18:04:57 +0000188 InvariantLHS, InvariantRHS))
189 return false;
190
191 // Rewrite the comparison to a loop invariant comparison if it can be done
192 // cheaply, where cheaply means "we don't need to emit any new
193 // instructions".
Philip Reamesdc417a92017-10-31 18:04:57 +0000194
Philip Reames7b861f02017-11-01 19:49:20 +0000195 SmallDenseMap<const SCEV*, Value*> CheapExpansions;
196 CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
197 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
198
199 // TODO: Support multiple entry loops? (We currently bail out of these in
200 // the IndVarSimplify pass)
201 if (auto *BB = L->getLoopPredecessor()) {
Philip Reames6260cf72017-12-01 20:57:19 +0000202 const int Idx = PN->getBasicBlockIndex(BB);
203 if (Idx >= 0) {
204 Value *Incoming = PN->getIncomingValue(Idx);
205 const SCEV *IncomingS = SE->getSCEV(Incoming);
206 CheapExpansions[IncomingS] = Incoming;
207 }
Philip Reames7b861f02017-11-01 19:49:20 +0000208 }
209 Value *NewLHS = CheapExpansions[InvariantLHS];
210 Value *NewRHS = CheapExpansions[InvariantRHS];
211
Philip Reames6260cf72017-12-01 20:57:19 +0000212 if (!NewLHS)
213 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
214 NewLHS = ConstLHS->getValue();
215 if (!NewRHS)
216 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
217 NewRHS = ConstRHS->getValue();
218
Philip Reames7b861f02017-11-01 19:49:20 +0000219 if (!NewLHS || !NewRHS)
220 // We could not find an existing value to replace either LHS or RHS.
221 // Generating new instructions has subtler tradeoffs, so avoid doing that
222 // for now.
223 return false;
224
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000225 LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000226 ICmp->setPredicate(InvariantPredicate);
227 ICmp->setOperand(0, NewLHS);
228 ICmp->setOperand(1, NewRHS);
229 return true;
Philip Reamesdc417a92017-10-31 18:04:57 +0000230}
231
Sanjay Patel7777b502014-11-12 18:07:42 +0000232/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000233/// comparisons against an induction variable.
234void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
235 unsigned IVOperIdx = 0;
236 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000237 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000238 if (IVOperand != ICmp->getOperand(0)) {
239 // Swapped
240 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
241 IVOperIdx = 1;
242 Pred = ICmpInst::getSwappedPredicate(Pred);
243 }
244
Philip Reames29dd40b2017-10-26 22:02:16 +0000245 // Get the SCEVs for the ICmp operands (in the specific context of the
246 // current loop)
Andrew Trick3ec331e2011-08-10 03:46:27 +0000247 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
Philip Reames29dd40b2017-10-26 22:02:16 +0000248 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
249 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000250
251 // If the condition is always true or always false, replace it with
252 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000253 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000254 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000255 DeadInsts.emplace_back(ICmp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000256 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000257 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000258 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000259 DeadInsts.emplace_back(ICmp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000260 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000261 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
262 // fallthrough to end of function
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000263 } else if (ICmpInst::isSigned(OriginalPred) &&
264 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
265 // If we were unable to make anything above, all we can is to canonicalize
266 // the comparison hoping that it will open the doors for other
267 // optimizations. If we find out that we compare two non-negative values,
268 // we turn the instruction's predicate to its unsigned version. Note that
269 // we cannot rely on Pred here unless we check if we have swapped it.
270 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000271 LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
272 << '\n');
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000273 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000274 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000275 return;
276
Andrew Trick3ec331e2011-08-10 03:46:27 +0000277 ++NumElimCmp;
278 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000279}
280
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000281bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
282 // Get the SCEVs for the ICmp operands.
283 auto *N = SE->getSCEV(SDiv->getOperand(0));
284 auto *D = SE->getSCEV(SDiv->getOperand(1));
285
286 // Simplify unnecessary loops away.
287 const Loop *L = LI->getLoopFor(SDiv->getParent());
288 N = SE->getSCEVAtScope(N, L);
289 D = SE->getSCEVAtScope(D, L);
290
291 // Replace sdiv by udiv if both of the operands are non-negative
292 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
293 auto *UDiv = BinaryOperator::Create(
294 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
295 SDiv->getName() + ".udiv", SDiv);
296 UDiv->setIsExact(SDiv->isExact());
297 SDiv->replaceAllUsesWith(UDiv);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000298 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000299 ++NumSimplifiedSDiv;
300 Changed = true;
301 DeadInsts.push_back(SDiv);
302 return true;
303 }
304
305 return false;
306}
307
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000308// i %s n -> i %u n if i >= 0 and n >= 0
309void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
310 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
311 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
312 Rem->getName() + ".urem", Rem);
313 Rem->replaceAllUsesWith(URem);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000314 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000315 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000316 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000317 DeadInsts.emplace_back(Rem);
318}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000319
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000320// i % n --> i if i is in [0,n).
321void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
322 Rem->replaceAllUsesWith(Rem->getOperand(0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000323 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000324 ++NumElimRem;
325 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000326 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000327}
328
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000329// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
330void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
331 auto *T = Rem->getType();
332 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
333 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
334 SelectInst *Sel =
335 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
336 Rem->replaceAllUsesWith(Sel);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000337 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000338 ++NumElimRem;
339 Changed = true;
340 DeadInsts.emplace_back(Rem);
341}
342
343/// SimplifyIVUsers helper for eliminating useless remainder operations
344/// operating on an induction variable or replacing srem by urem.
345void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
346 bool IsSigned) {
347 auto *NValue = Rem->getOperand(0);
348 auto *DValue = Rem->getOperand(1);
349 // We're only interested in the case where we know something about
350 // the numerator, unless it is a srem, because we want to replace srem by urem
351 // in general.
352 bool UsedAsNumerator = IVOperand == NValue;
353 if (!UsedAsNumerator && !IsSigned)
354 return;
355
356 const SCEV *N = SE->getSCEV(NValue);
357
358 // Simplify unnecessary loops away.
359 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
360 N = SE->getSCEVAtScope(N, ICmpLoop);
361
362 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
363
364 // Do not proceed if the Numerator may be negative
365 if (!IsNumeratorNonNegative)
366 return;
367
368 const SCEV *D = SE->getSCEV(DValue);
369 D = SE->getSCEVAtScope(D, ICmpLoop);
370
371 if (UsedAsNumerator) {
372 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
373 if (SE->isKnownPredicate(LT, N, D)) {
374 replaceRemWithNumerator(Rem);
375 return;
376 }
377
378 auto *T = Rem->getType();
379 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
380 if (SE->isKnownPredicate(LT, NLessOne, D)) {
381 replaceRemWithNumeratorOrZero(Rem);
382 return;
383 }
384 }
385
386 // Try to replace SRem with URem, if both N and D are known non-negative.
387 // Since we had already check N, we only need to check D now
388 if (!IsSigned || !SE->isKnownNonNegative(D))
389 return;
390
391 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000392}
393
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000394bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
395 auto *F = CI->getCalledFunction();
396 if (!F)
397 return false;
398
399 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000400 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000401 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000402 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000403
404 OperationFunctionTy Operation;
405 ExtensionFunctionTy Extension;
406
407 Instruction::BinaryOps RawOp;
408
409 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
410 // have nuw.
411 bool NoSignedOverflow;
412
413 switch (F->getIntrinsicID()) {
414 default:
415 return false;
416
417 case Intrinsic::sadd_with_overflow:
418 Operation = &ScalarEvolution::getAddExpr;
419 Extension = &ScalarEvolution::getSignExtendExpr;
420 RawOp = Instruction::Add;
421 NoSignedOverflow = true;
422 break;
423
424 case Intrinsic::uadd_with_overflow:
425 Operation = &ScalarEvolution::getAddExpr;
426 Extension = &ScalarEvolution::getZeroExtendExpr;
427 RawOp = Instruction::Add;
428 NoSignedOverflow = false;
429 break;
430
431 case Intrinsic::ssub_with_overflow:
432 Operation = &ScalarEvolution::getMinusSCEV;
433 Extension = &ScalarEvolution::getSignExtendExpr;
434 RawOp = Instruction::Sub;
435 NoSignedOverflow = true;
436 break;
437
438 case Intrinsic::usub_with_overflow:
439 Operation = &ScalarEvolution::getMinusSCEV;
440 Extension = &ScalarEvolution::getZeroExtendExpr;
441 RawOp = Instruction::Sub;
442 NoSignedOverflow = false;
443 break;
444 }
445
446 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
447 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
448
449 auto *NarrowTy = cast<IntegerType>(LHS->getType());
450 auto *WideTy =
451 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
452
453 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000454 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
455 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000456 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000457 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
458 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000459
460 if (A != B)
461 return false;
462
463 // Proved no overflow, nuke the overflow check and, if possible, the overflow
464 // intrinsic as well.
465
466 BinaryOperator *NewResult = BinaryOperator::Create(
467 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
468
469 if (NoSignedOverflow)
470 NewResult->setHasNoSignedWrap(true);
471 else
472 NewResult->setHasNoUnsignedWrap(true);
473
474 SmallVector<ExtractValueInst *, 4> ToDelete;
475
476 for (auto *U : CI->users()) {
477 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
478 if (EVI->getIndices()[0] == 1)
479 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
480 else {
481 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
482 EVI->replaceAllUsesWith(NewResult);
483 }
484 ToDelete.push_back(EVI);
485 }
486 }
487
488 for (auto *EVI : ToDelete)
489 EVI->eraseFromParent();
490
491 if (CI->use_empty())
492 CI->eraseFromParent();
493
494 return true;
495}
496
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000497/// Eliminate an operation that consumes a simple IV and has no observable
498/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
499/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000500bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
501 Instruction *IVOperand) {
502 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
503 eliminateIVComparison(ICmp, IVOperand);
504 return true;
505 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000506 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
507 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
508 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000509 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000510 return true;
511 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000512
513 if (Bin->getOpcode() == Instruction::SDiv)
514 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000515 }
516
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000517 if (auto *CI = dyn_cast<CallInst>(UseInst))
518 if (eliminateOverflowIntrinsic(CI))
519 return true;
520
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000521 if (eliminateIdentitySCEV(UseInst, IVOperand))
522 return true;
523
524 return false;
525}
526
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000527static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
528 if (auto *BB = L->getLoopPreheader())
529 return BB->getTerminator();
530
531 return Hint;
532}
533
534/// Replace the UseInst with a constant if possible.
535bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000536 if (!SE->isSCEVable(I->getType()))
537 return false;
538
539 // Get the symbolic expression for this instruction.
540 const SCEV *S = SE->getSCEV(I);
541
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000542 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000543 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000544
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000545 // Do not generate something ridiculous even if S is loop invariant.
546 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000547 return false;
548
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000549 auto *IP = GetLoopInvariantInsertPosition(L, I);
550 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
551
552 I->replaceAllUsesWith(Invariant);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000553 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
554 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000555 ++NumFoldedUser;
556 Changed = true;
557 DeadInsts.emplace_back(I);
558 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000559}
560
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000561/// Eliminate any operation that SCEV can prove is an identity function.
562bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
563 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000564 if (!SE->isSCEVable(UseInst->getType()) ||
565 (UseInst->getType() != IVOperand->getType()) ||
566 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
567 return false;
568
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000569 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
570 // dominator tree, even if X is an operand to Y. For instance, in
571 //
572 // %iv = phi i32 {0,+,1}
573 // br %cond, label %left, label %merge
574 //
575 // left:
576 // %X = add i32 %iv, 0
577 // br label %merge
578 //
579 // merge:
580 // %M = phi (%X, %iv)
581 //
582 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
583 // %M.replaceAllUsesWith(%X) would be incorrect.
584
585 if (isa<PHINode>(UseInst))
586 // If UseInst is not a PHI node then we know that IVOperand dominates
587 // UseInst directly from the legality of SSA.
588 if (!DT || !DT->dominates(IVOperand, UseInst))
589 return false;
590
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000591 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
592 return false;
593
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000594 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000595
596 UseInst->replaceAllUsesWith(IVOperand);
597 ++NumElimIdentity;
598 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000599 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000600 return true;
601}
602
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000603/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
604/// unsigned-overflow. Returns true if anything changed, false otherwise.
605bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
606 Value *IVOperand) {
607
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000608 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000609 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
610 return false;
611
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000612 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000613 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000614 switch (BO->getOpcode()) {
615 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000616 return false;
617
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000618 case Instruction::Add:
619 GetExprForBO = &ScalarEvolution::getAddExpr;
620 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000621
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000622 case Instruction::Sub:
623 GetExprForBO = &ScalarEvolution::getMinusSCEV;
624 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000625
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000626 case Instruction::Mul:
627 GetExprForBO = &ScalarEvolution::getMulExpr;
628 break;
629 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000630
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000631 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
632 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
633 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
634 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000635
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000636 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000637
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000638 if (!BO->hasNoUnsignedWrap()) {
639 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
640 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
641 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000642 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000643 if (ExtendAfterOp == OpAfterExtend) {
644 BO->setHasNoUnsignedWrap();
645 SE->forgetValue(BO);
646 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000647 }
648 }
649
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000650 if (!BO->hasNoSignedWrap()) {
651 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
652 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
653 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000654 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000655 if (ExtendAfterOp == OpAfterExtend) {
656 BO->setHasNoSignedWrap();
657 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000658 Changed = true;
659 }
660 }
661
662 return Changed;
663}
664
David Greenb26a0a42017-07-05 13:25:58 +0000665/// Annotate the Shr in (X << IVOperand) >> C as exact using the
666/// information from the IV's range. Returns true if anything changed, false
667/// otherwise.
668bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
669 Value *IVOperand) {
670 using namespace llvm::PatternMatch;
671
672 if (BO->getOpcode() == Instruction::Shl) {
673 bool Changed = false;
674 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
675 for (auto *U : BO->users()) {
676 const APInt *C;
677 if (match(U,
678 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
679 match(U,
680 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
681 BinaryOperator *Shr = cast<BinaryOperator>(U);
682 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
683 Shr->setIsExact(true);
684 Changed = true;
685 }
686 }
687 }
688 return Changed;
689 }
690
691 return false;
692}
693
Sanjay Patel7777b502014-11-12 18:07:42 +0000694/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000695static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000696 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000697 SmallPtrSet<Instruction*,16> &Simplified,
698 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
699
Chandler Carruthcdf47882014-03-09 03:16:01 +0000700 for (User *U : Def->users()) {
701 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000702
703 // Avoid infinite or exponential worklist processing.
704 // Also ensure unique worklist users.
705 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
706 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000707 if (UI == Def)
708 continue;
709
710 // Only change the current Loop, do not change the other parts (e.g. other
711 // Loops).
712 if (!L->contains(UI))
713 continue;
714
715 // Do not push the same instruction more than once.
716 if (!Simplified.insert(UI).second)
717 continue;
718
719 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000720 }
721}
722
Sanjay Patel7777b502014-11-12 18:07:42 +0000723/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000724/// expression in terms of that IV.
725///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000726/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000727/// non-recursively when the operand is already known to be a simpleIVUser.
728///
729static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
730 if (!SE->isSCEVable(I->getType()))
731 return false;
732
733 // Get the symbolic expression for this instruction.
734 const SCEV *S = SE->getSCEV(I);
735
736 // Only consider affine recurrences.
737 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
738 if (AR && AR->getLoop() == L)
739 return true;
740
741 return false;
742}
743
Sanjay Patel7777b502014-11-12 18:07:42 +0000744/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000745/// of the specified induction variable. Each successive simplification may push
746/// more users which may themselves be candidates for simplification.
747///
748/// This algorithm does not require IVUsers analysis. Instead, it simplifies
749/// instructions in-place during analysis. Rather than rewriting induction
750/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000751/// top-down, updating the IR only when it encounters a clear optimization
752/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000753///
754/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
755///
756void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000757 if (!SE->isSCEVable(CurrIV->getType()))
758 return;
759
Andrew Trick3ec331e2011-08-10 03:46:27 +0000760 // Instructions processed by SimplifyIndvar for CurrIV.
761 SmallPtrSet<Instruction*,16> Simplified;
762
763 // Use-def pairs if IV users waiting to be processed for CurrIV.
764 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
765
766 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
767 // called multiple times for the same LoopPhi. This is the proper thing to
768 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000769 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000770
771 while (!SimpleIVUsers.empty()) {
772 std::pair<Instruction*, Instruction*> UseOper =
773 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000774 Instruction *UseInst = UseOper.first;
775
Max Kazantsev0ed79622018-06-13 02:25:32 +0000776 // If a user of the IndVar is trivially dead, we prefer just to mark it dead
777 // rather than try to do some complex analysis or transformation (such as
778 // widening) basing on it.
779 // TODO: Propagate TLI and pass it here to handle more cases.
780 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
781 DeadInsts.emplace_back(UseInst);
782 continue;
783 }
784
Andrew Trick3ec331e2011-08-10 03:46:27 +0000785 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000786 if (UseInst == CurrIV) continue;
787
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000788 // Try to replace UseInst with a loop invariant before any other
789 // simplifications.
790 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000791 continue;
792
Andrew Trick74664d52011-08-10 04:01:31 +0000793 Instruction *IVOperand = UseOper.second;
794 for (unsigned N = 0; IVOperand; ++N) {
795 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000796
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000797 Value *NewOper = foldIVUser(UseInst, IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000798 if (!NewOper)
799 break; // done folding
800 IVOperand = dyn_cast<Instruction>(NewOper);
801 }
802 if (!IVOperand)
803 continue;
804
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000805 if (eliminateIVUser(UseInst, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000806 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000807 continue;
808 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000809
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
David Greenb26a0a42017-07-05 13:25:58 +0000811 if ((isa<OverflowingBinaryOperator>(BO) &&
812 strengthenOverflowingOperation(BO, IVOperand)) ||
813 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000814 // re-queue uses of the now modified binary operator and fall
815 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000816 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000817 }
818 }
819
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000820 CastInst *Cast = dyn_cast<CastInst>(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000821 if (V && Cast) {
822 V->visitCast(Cast);
823 continue;
824 }
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000825 if (isSimpleIVUser(UseInst, L, SE)) {
826 pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000827 }
828 }
829}
830
831namespace llvm {
832
David Blaikiea379b1812011-12-20 02:50:00 +0000833void IVVisitor::anchor() { }
834
Sanjay Patel7777b502014-11-12 18:07:42 +0000835/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000836/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000837bool simplifyUsersOfIV(PHINode *CurrIV, 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, IVVisitor *V) {
840 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
841 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000842 SIV.simplifyUsers(CurrIV, V);
843 return SIV.hasChanged();
844}
845
Sanjay Patel7777b502014-11-12 18:07:42 +0000846/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000847/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000848bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000849 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000850 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
851#ifndef NDEBUG
852 Rewriter.setDebugType(DEBUG_TYPE);
853#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000854 bool Changed = false;
855 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000856 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000857 }
858 return Changed;
859}
860
Andrew Trick3ec331e2011-08-10 03:46:27 +0000861} // namespace llvm