blob: 6d90e6b48358a1a9439c0562a61939864fdd2704 [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");
Andrew Trick3ec331e2011-08-10 03:46:27 +000042STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
43
44namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000045 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000046 /// based on ScalarEvolution. It is the primary instrument of the
47 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
48 /// other loop passes that preserve SCEV.
49 class SimplifyIndvar {
50 Loop *L;
51 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000052 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000053 DominatorTree *DT;
Andrew Trick3ec331e2011-08-10 03:46:27 +000054
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000055 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000056
57 bool Changed;
58
59 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000060 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000061 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead)
Sanjoy Das5c8bead2015-10-06 21:44:49 +000062 : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000063 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000064 }
65
66 bool hasChanged() const { return Changed; }
67
68 /// Iteratively perform simplification on a worklist of users of the
69 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000070 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000071 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000072
Andrew Trick74664d52011-08-10 04:01:31 +000073 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000074
Sanjoy Das088bb0e2015-10-06 21:44:39 +000075 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
76
Sanjoy Dasae09b3c2016-05-29 00:36:25 +000077 bool eliminateOverflowIntrinsic(CallInst *CI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000078 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
79 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
80 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
81 bool IsSigned);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000082 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000083 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000084 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000085 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000086}
Andrew Trick3ec331e2011-08-10 03:46:27 +000087
Sanjay Patel7777b502014-11-12 18:07:42 +000088/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000089/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000090///
Andrew Trick7251e412011-09-19 17:54:39 +000091/// IVOperand is guaranteed SCEVable, but UseInst may not be.
92///
Andrew Trick74664d52011-08-10 04:01:31 +000093/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000094/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000095/// Otherwise return null.
96Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000097 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000098 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000099 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000100 switch (UseInst->getOpcode()) {
101 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000102 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000103 case Instruction::UDiv:
104 case Instruction::LShr:
105 // We're only interested in the case where we know something about
106 // the numerator and have a constant denominator.
107 if (IVOperand != UseInst->getOperand(OperIdx) ||
108 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000109 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000110
111 // Attempt to fold a binary operator with constant operand.
112 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000113 if (!isa<BinaryOperator>(IVOperand)
114 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000115 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000116
117 IVSrc = IVOperand->getOperand(0);
118 // IVSrc must be the (SCEVable) IV, since the other operand is const.
119 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
120
121 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
122 if (UseInst->getOpcode() == Instruction::LShr) {
123 // Get a constant for the divisor. See createSCEV.
124 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
125 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000126 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000127
128 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000129 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000130 }
131 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
132 }
133 // We have something that might fold it's operand. Compare SCEVs.
134 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136
137 // Bypass the operand if SCEV can prove it has no effect.
138 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000139 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000140
141 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
142 << " -> " << *UseInst << '\n');
143
144 UseInst->setOperand(OperIdx, IVSrc);
145 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
146
147 ++NumElimOperand;
148 Changed = true;
149 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000150 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000151 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000152}
153
Sanjay Patel7777b502014-11-12 18:07:42 +0000154/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000155/// comparisons against an induction variable.
156void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
157 unsigned IVOperIdx = 0;
158 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000159 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000160 if (IVOperand != ICmp->getOperand(0)) {
161 // Swapped
162 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
163 IVOperIdx = 1;
164 Pred = ICmpInst::getSwappedPredicate(Pred);
165 }
166
167 // Get the SCEVs for the ICmp operands.
168 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
169 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
170
171 // Simplify unnecessary loops away.
172 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
173 S = SE->getSCEVAtScope(S, ICmpLoop);
174 X = SE->getSCEVAtScope(X, ICmpLoop);
175
Sanjoy Das5dab2052015-07-27 21:42:49 +0000176 ICmpInst::Predicate InvariantPredicate;
177 const SCEV *InvariantLHS, *InvariantRHS;
178
Andrew Trick3ec331e2011-08-10 03:46:27 +0000179 // If the condition is always true or always false, replace it with
180 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000181 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000182 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000183 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000184 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000185 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000186 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000187 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000188 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000189 } else if (isa<PHINode>(IVOperand) &&
Sanjoy Das60fb8992016-03-18 20:37:07 +0000190 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
191 InvariantLHS, InvariantRHS)) {
Sanjoy Das5dab2052015-07-27 21:42:49 +0000192
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000193 // Rewrite the comparison to a loop invariant comparison if it can be done
Sanjoy Das5dab2052015-07-27 21:42:49 +0000194 // cheaply, where cheaply means "we don't need to emit any new
195 // instructions".
196
197 Value *NewLHS = nullptr, *NewRHS = nullptr;
198
199 if (S == InvariantLHS || X == InvariantLHS)
200 NewLHS =
201 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
202
203 if (S == InvariantRHS || X == InvariantRHS)
204 NewRHS =
205 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
206
Sanjoy Das74af78e32016-03-18 20:37:11 +0000207 auto *PN = cast<PHINode>(IVOperand);
208 for (unsigned i = 0, e = PN->getNumIncomingValues();
209 i != e && (!NewLHS || !NewRHS);
210 ++i) {
211
212 // If this is a value incoming from the backedge, then it cannot be a loop
213 // invariant value (since we know that IVOperand is an induction variable).
214 if (L->contains(PN->getIncomingBlock(i)))
215 continue;
216
217 // NB! This following assert does not fundamentally have to be true, but
218 // it is true today given how SCEV analyzes induction variables.
219 // Specifically, today SCEV will *not* recognize %iv as an induction
220 // variable in the following case:
221 //
222 // define void @f(i32 %k) {
223 // entry:
224 // br i1 undef, label %r, label %l
225 //
226 // l:
227 // %k.inc.l = add i32 %k, 1
228 // br label %loop
229 //
230 // r:
231 // %k.inc.r = add i32 %k, 1
232 // br label %loop
233 //
234 // loop:
235 // %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
236 // %iv.inc = add i32 %iv, 1
237 // br label %loop
238 // }
239 //
240 // but if it starts to, at some point, then the assertion below will have
241 // to be changed to a runtime check.
242
243 Value *Incoming = PN->getIncomingValue(i);
244
245#ifndef NDEBUG
246 if (auto *I = dyn_cast<Instruction>(Incoming))
247 assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
248#endif
Sanjoy Das5dab2052015-07-27 21:42:49 +0000249
250 const SCEV *IncomingS = SE->getSCEV(Incoming);
251
252 if (!NewLHS && IncomingS == InvariantLHS)
253 NewLHS = Incoming;
254 if (!NewRHS && IncomingS == InvariantRHS)
255 NewRHS = Incoming;
256 }
257
258 if (!NewLHS || !NewRHS)
259 // We could not find an existing value to replace either LHS or RHS.
260 // Generating new instructions has subtler tradeoffs, so avoid doing that
261 // for now.
262 return;
263
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000264 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000265 ICmp->setPredicate(InvariantPredicate);
266 ICmp->setOperand(0, NewLHS);
267 ICmp->setOperand(1, NewRHS);
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000268 } else if (ICmpInst::isSigned(OriginalPred) &&
269 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
270 // If we were unable to make anything above, all we can is to canonicalize
271 // the comparison hoping that it will open the doors for other
272 // optimizations. If we find out that we compare two non-negative values,
273 // we turn the instruction's predicate to its unsigned version. Note that
274 // we cannot rely on Pred here unless we check if we have swapped it.
275 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
276 DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
277 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000278 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000279 return;
280
Andrew Trick3ec331e2011-08-10 03:46:27 +0000281 ++NumElimCmp;
282 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000283}
284
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000285bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
286 // Get the SCEVs for the ICmp operands.
287 auto *N = SE->getSCEV(SDiv->getOperand(0));
288 auto *D = SE->getSCEV(SDiv->getOperand(1));
289
290 // Simplify unnecessary loops away.
291 const Loop *L = LI->getLoopFor(SDiv->getParent());
292 N = SE->getSCEVAtScope(N, L);
293 D = SE->getSCEVAtScope(D, L);
294
295 // Replace sdiv by udiv if both of the operands are non-negative
296 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
297 auto *UDiv = BinaryOperator::Create(
298 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
299 SDiv->getName() + ".udiv", SDiv);
300 UDiv->setIsExact(SDiv->isExact());
301 SDiv->replaceAllUsesWith(UDiv);
302 DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
303 ++NumSimplifiedSDiv;
304 Changed = true;
305 DeadInsts.push_back(SDiv);
306 return true;
307 }
308
309 return false;
310}
311
Sanjay Patel7777b502014-11-12 18:07:42 +0000312/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000313/// remainder operations operating on an induction variable.
314void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
315 Value *IVOperand,
316 bool IsSigned) {
317 // We're only interested in the case where we know something about
318 // the numerator.
319 if (IVOperand != Rem->getOperand(0))
320 return;
321
322 // Get the SCEVs for the ICmp operands.
323 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
324 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
325
326 // Simplify unnecessary loops away.
327 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
328 S = SE->getSCEVAtScope(S, ICmpLoop);
329 X = SE->getSCEVAtScope(X, ICmpLoop);
330
331 // i % n --> i if i is in [0,n).
332 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
333 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
334 S, X))
335 Rem->replaceAllUsesWith(Rem->getOperand(0));
336 else {
337 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000338 const SCEV *LessOne = SE->getMinusSCEV(S, SE->getOne(S->getType()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000339 if (IsSigned && !SE->isKnownNonNegative(LessOne))
340 return;
341
342 if (!SE->isKnownPredicate(IsSigned ?
343 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
344 LessOne, X))
345 return;
346
347 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000348 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000349 SelectInst *Sel =
350 SelectInst::Create(ICmp,
351 ConstantInt::get(Rem->getType(), 0),
352 Rem->getOperand(0), "tmp", Rem);
353 Rem->replaceAllUsesWith(Sel);
354 }
355
Andrew Trick3ec331e2011-08-10 03:46:27 +0000356 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
357 ++NumElimRem;
358 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000359 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000360}
361
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000362bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
363 auto *F = CI->getCalledFunction();
364 if (!F)
365 return false;
366
367 typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
Max Kazantsevdc803662017-06-15 11:48:21 +0000368 const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000369 typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000370 const SCEV *, Type *, unsigned);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000371
372 OperationFunctionTy Operation;
373 ExtensionFunctionTy Extension;
374
375 Instruction::BinaryOps RawOp;
376
377 // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we
378 // have nuw.
379 bool NoSignedOverflow;
380
381 switch (F->getIntrinsicID()) {
382 default:
383 return false;
384
385 case Intrinsic::sadd_with_overflow:
386 Operation = &ScalarEvolution::getAddExpr;
387 Extension = &ScalarEvolution::getSignExtendExpr;
388 RawOp = Instruction::Add;
389 NoSignedOverflow = true;
390 break;
391
392 case Intrinsic::uadd_with_overflow:
393 Operation = &ScalarEvolution::getAddExpr;
394 Extension = &ScalarEvolution::getZeroExtendExpr;
395 RawOp = Instruction::Add;
396 NoSignedOverflow = false;
397 break;
398
399 case Intrinsic::ssub_with_overflow:
400 Operation = &ScalarEvolution::getMinusSCEV;
401 Extension = &ScalarEvolution::getSignExtendExpr;
402 RawOp = Instruction::Sub;
403 NoSignedOverflow = true;
404 break;
405
406 case Intrinsic::usub_with_overflow:
407 Operation = &ScalarEvolution::getMinusSCEV;
408 Extension = &ScalarEvolution::getZeroExtendExpr;
409 RawOp = Instruction::Sub;
410 NoSignedOverflow = false;
411 break;
412 }
413
414 const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
415 const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
416
417 auto *NarrowTy = cast<IntegerType>(LHS->getType());
418 auto *WideTy =
419 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
420
421 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000422 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
423 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000424 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000425 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
426 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000427
428 if (A != B)
429 return false;
430
431 // Proved no overflow, nuke the overflow check and, if possible, the overflow
432 // intrinsic as well.
433
434 BinaryOperator *NewResult = BinaryOperator::Create(
435 RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
436
437 if (NoSignedOverflow)
438 NewResult->setHasNoSignedWrap(true);
439 else
440 NewResult->setHasNoUnsignedWrap(true);
441
442 SmallVector<ExtractValueInst *, 4> ToDelete;
443
444 for (auto *U : CI->users()) {
445 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
446 if (EVI->getIndices()[0] == 1)
447 EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
448 else {
449 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
450 EVI->replaceAllUsesWith(NewResult);
451 }
452 ToDelete.push_back(EVI);
453 }
454 }
455
456 for (auto *EVI : ToDelete)
457 EVI->eraseFromParent();
458
459 if (CI->use_empty())
460 CI->eraseFromParent();
461
462 return true;
463}
464
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000465/// Eliminate an operation that consumes a simple IV and has no observable
466/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
467/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000468bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
469 Instruction *IVOperand) {
470 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
471 eliminateIVComparison(ICmp, IVOperand);
472 return true;
473 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000474 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
475 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
476 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
477 eliminateIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000478 return true;
479 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000480
481 if (Bin->getOpcode() == Instruction::SDiv)
482 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000483 }
484
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000485 if (auto *CI = dyn_cast<CallInst>(UseInst))
486 if (eliminateOverflowIntrinsic(CI))
487 return true;
488
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000489 if (eliminateIdentitySCEV(UseInst, IVOperand))
490 return true;
491
492 return false;
493}
494
495/// Eliminate any operation that SCEV can prove is an identity function.
496bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
497 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000498 if (!SE->isSCEVable(UseInst->getType()) ||
499 (UseInst->getType() != IVOperand->getType()) ||
500 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
501 return false;
502
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000503 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
504 // dominator tree, even if X is an operand to Y. For instance, in
505 //
506 // %iv = phi i32 {0,+,1}
507 // br %cond, label %left, label %merge
508 //
509 // left:
510 // %X = add i32 %iv, 0
511 // br label %merge
512 //
513 // merge:
514 // %M = phi (%X, %iv)
515 //
516 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
517 // %M.replaceAllUsesWith(%X) would be incorrect.
518
519 if (isa<PHINode>(UseInst))
520 // If UseInst is not a PHI node then we know that IVOperand dominates
521 // UseInst directly from the legality of SSA.
522 if (!DT || !DT->dominates(IVOperand, UseInst))
523 return false;
524
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000525 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
526 return false;
527
Andrew Trick3ec331e2011-08-10 03:46:27 +0000528 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
529
530 UseInst->replaceAllUsesWith(IVOperand);
531 ++NumElimIdentity;
532 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000533 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000534 return true;
535}
536
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000537/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
538/// unsigned-overflow. Returns true if anything changed, false otherwise.
539bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
540 Value *IVOperand) {
541
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000542 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000543 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
544 return false;
545
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000546 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
Max Kazantsevdc803662017-06-15 11:48:21 +0000547 SCEV::NoWrapFlags, unsigned);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000548 switch (BO->getOpcode()) {
549 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000550 return false;
551
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000552 case Instruction::Add:
553 GetExprForBO = &ScalarEvolution::getAddExpr;
554 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000555
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000556 case Instruction::Sub:
557 GetExprForBO = &ScalarEvolution::getMinusSCEV;
558 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000559
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000560 case Instruction::Mul:
561 GetExprForBO = &ScalarEvolution::getMulExpr;
562 break;
563 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000564
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000565 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
566 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
567 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
568 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000569
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000570 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000571
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000572 if (!BO->hasNoUnsignedWrap()) {
573 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
574 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
575 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000576 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000577 if (ExtendAfterOp == OpAfterExtend) {
578 BO->setHasNoUnsignedWrap();
579 SE->forgetValue(BO);
580 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000581 }
582 }
583
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000584 if (!BO->hasNoSignedWrap()) {
585 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
586 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
587 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
Max Kazantsevdc803662017-06-15 11:48:21 +0000588 SCEV::FlagAnyWrap, 0u);
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000589 if (ExtendAfterOp == OpAfterExtend) {
590 BO->setHasNoSignedWrap();
591 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000592 Changed = true;
593 }
594 }
595
596 return Changed;
597}
598
David Greenb26a0a42017-07-05 13:25:58 +0000599/// Annotate the Shr in (X << IVOperand) >> C as exact using the
600/// information from the IV's range. Returns true if anything changed, false
601/// otherwise.
602bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
603 Value *IVOperand) {
604 using namespace llvm::PatternMatch;
605
606 if (BO->getOpcode() == Instruction::Shl) {
607 bool Changed = false;
608 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
609 for (auto *U : BO->users()) {
610 const APInt *C;
611 if (match(U,
612 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
613 match(U,
614 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
615 BinaryOperator *Shr = cast<BinaryOperator>(U);
616 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
617 Shr->setIsExact(true);
618 Changed = true;
619 }
620 }
621 }
622 return Changed;
623 }
624
625 return false;
626}
627
Sanjay Patel7777b502014-11-12 18:07:42 +0000628/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000629static void pushIVUsers(
630 Instruction *Def,
631 SmallPtrSet<Instruction*,16> &Simplified,
632 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
633
Chandler Carruthcdf47882014-03-09 03:16:01 +0000634 for (User *U : Def->users()) {
635 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000636
637 // Avoid infinite or exponential worklist processing.
638 // Also ensure unique worklist users.
639 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
640 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000641 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000642 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000643 }
644}
645
Sanjay Patel7777b502014-11-12 18:07:42 +0000646/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000647/// expression in terms of that IV.
648///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000649/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000650/// non-recursively when the operand is already known to be a simpleIVUser.
651///
652static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
653 if (!SE->isSCEVable(I->getType()))
654 return false;
655
656 // Get the symbolic expression for this instruction.
657 const SCEV *S = SE->getSCEV(I);
658
659 // Only consider affine recurrences.
660 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
661 if (AR && AR->getLoop() == L)
662 return true;
663
664 return false;
665}
666
Sanjay Patel7777b502014-11-12 18:07:42 +0000667/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000668/// of the specified induction variable. Each successive simplification may push
669/// more users which may themselves be candidates for simplification.
670///
671/// This algorithm does not require IVUsers analysis. Instead, it simplifies
672/// instructions in-place during analysis. Rather than rewriting induction
673/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000674/// top-down, updating the IR only when it encounters a clear optimization
675/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000676///
677/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
678///
679void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000680 if (!SE->isSCEVable(CurrIV->getType()))
681 return;
682
Andrew Trick3ec331e2011-08-10 03:46:27 +0000683 // Instructions processed by SimplifyIndvar for CurrIV.
684 SmallPtrSet<Instruction*,16> Simplified;
685
686 // Use-def pairs if IV users waiting to be processed for CurrIV.
687 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
688
689 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
690 // called multiple times for the same LoopPhi. This is the proper thing to
691 // do for loop header phis that use each other.
692 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
693
694 while (!SimpleIVUsers.empty()) {
695 std::pair<Instruction*, Instruction*> UseOper =
696 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000697 Instruction *UseInst = UseOper.first;
698
Andrew Trick3ec331e2011-08-10 03:46:27 +0000699 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000700 if (UseInst == CurrIV) continue;
701
Andrew Trick74664d52011-08-10 04:01:31 +0000702 Instruction *IVOperand = UseOper.second;
703 for (unsigned N = 0; IVOperand; ++N) {
704 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000705
Andrew Trick74664d52011-08-10 04:01:31 +0000706 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
707 if (!NewOper)
708 break; // done folding
709 IVOperand = dyn_cast<Instruction>(NewOper);
710 }
711 if (!IVOperand)
712 continue;
713
714 if (eliminateIVUser(UseOper.first, IVOperand)) {
715 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000716 continue;
717 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000718
719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
David Greenb26a0a42017-07-05 13:25:58 +0000720 if ((isa<OverflowingBinaryOperator>(BO) &&
721 strengthenOverflowingOperation(BO, IVOperand)) ||
722 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000723 // re-queue uses of the now modified binary operator and fall
724 // through to the checks that remain.
725 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
726 }
727 }
728
Andrew Trick3ec331e2011-08-10 03:46:27 +0000729 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
730 if (V && Cast) {
731 V->visitCast(Cast);
732 continue;
733 }
734 if (isSimpleIVUser(UseOper.first, L, SE)) {
735 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
736 }
737 }
738}
739
740namespace llvm {
741
David Blaikiea379b1812011-12-20 02:50:00 +0000742void IVVisitor::anchor() { }
743
Sanjay Patel7777b502014-11-12 18:07:42 +0000744/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000745/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000746bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000747 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Justin Bogner843fb202015-12-15 19:40:57 +0000748 IVVisitor *V) {
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000749 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000750 SIV.simplifyUsers(CurrIV, V);
751 return SIV.hasChanged();
752}
753
Sanjay Patel7777b502014-11-12 18:07:42 +0000754/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000755/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000756bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000757 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000758 bool Changed = false;
759 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Justin Bogner843fb202015-12-15 19:40:57 +0000760 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000761 }
762 return Changed;
763}
764
Andrew Trick3ec331e2011-08-10 03:46:27 +0000765} // namespace llvm