blob: fa0459f62c94bba8c1eafe3f88f9940e6633c898 [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"
Andrew Trick3ec331e2011-08-10 03:46:27 +000028#include "llvm/Support/CommandLine.h"
29#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");
39STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
40
41namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000042 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000043 /// based on ScalarEvolution. It is the primary instrument of the
44 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
45 /// other loop passes that preserve SCEV.
46 class SimplifyIndvar {
47 Loop *L;
48 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000049 ScalarEvolution *SE;
Andrew Trick3ec331e2011-08-10 03:46:27 +000050
51 SmallVectorImpl<WeakVH> &DeadInsts;
52
53 bool Changed;
54
55 public:
Chandler Carruth4f8f3072015-01-17 14:16:18 +000056 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, LoopInfo *LI,
Andrew Trick018e55a2015-05-18 16:49:31 +000057 SmallVectorImpl<WeakVH> &Dead)
Chandler Carruth24fd0292015-01-17 14:31:35 +000058 : L(Loop), LI(LI), SE(SE), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000059 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000060 }
61
62 bool hasChanged() const { return Changed; }
63
64 /// Iteratively perform simplification on a worklist of users of the
65 /// specified induction variable. This is the top-level driver that applies
66 /// all simplicitions to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000067 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000068
Andrew Trick74664d52011-08-10 04:01:31 +000069 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000070
71 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
72 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
73 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
74 bool IsSigned);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000075 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
Andrew Trick0ba77a02013-12-23 23:31:49 +000076
77 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
78 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000079 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000080}
Andrew Trick3ec331e2011-08-10 03:46:27 +000081
Sanjay Patel7777b502014-11-12 18:07:42 +000082/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000083/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000084///
Andrew Trick7251e412011-09-19 17:54:39 +000085/// IVOperand is guaranteed SCEVable, but UseInst may not be.
86///
Andrew Trick74664d52011-08-10 04:01:31 +000087/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000088/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000089/// Otherwise return null.
90Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000091 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000092 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000093 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000094 switch (UseInst->getOpcode()) {
95 default:
Craig Topperf40110f2014-04-25 05:29:35 +000096 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000097 case Instruction::UDiv:
98 case Instruction::LShr:
99 // We're only interested in the case where we know something about
100 // the numerator and have a constant denominator.
101 if (IVOperand != UseInst->getOperand(OperIdx) ||
102 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000103 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000104
105 // Attempt to fold a binary operator with constant operand.
106 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000107 if (!isa<BinaryOperator>(IVOperand)
108 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000109 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000110
111 IVSrc = IVOperand->getOperand(0);
112 // IVSrc must be the (SCEVable) IV, since the other operand is const.
113 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
114
115 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
116 if (UseInst->getOpcode() == Instruction::LShr) {
117 // Get a constant for the divisor. See createSCEV.
118 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
119 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000120 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000121
122 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000123 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000124 }
125 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
126 }
127 // We have something that might fold it's operand. Compare SCEVs.
128 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000129 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000130
131 // Bypass the operand if SCEV can prove it has no effect.
132 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000133 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000134
135 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
136 << " -> " << *UseInst << '\n');
137
138 UseInst->setOperand(OperIdx, IVSrc);
139 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
140
141 ++NumElimOperand;
142 Changed = true;
143 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000144 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000145 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000146}
147
Sanjay Patel7777b502014-11-12 18:07:42 +0000148/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000149/// comparisons against an induction variable.
150void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
151 unsigned IVOperIdx = 0;
152 ICmpInst::Predicate Pred = ICmp->getPredicate();
153 if (IVOperand != ICmp->getOperand(0)) {
154 // Swapped
155 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
156 IVOperIdx = 1;
157 Pred = ICmpInst::getSwappedPredicate(Pred);
158 }
159
160 // Get the SCEVs for the ICmp operands.
161 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
162 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
163
164 // Simplify unnecessary loops away.
165 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
166 S = SE->getSCEVAtScope(S, ICmpLoop);
167 X = SE->getSCEVAtScope(X, ICmpLoop);
168
Sanjoy Das5dab2052015-07-27 21:42:49 +0000169 ICmpInst::Predicate InvariantPredicate;
170 const SCEV *InvariantLHS, *InvariantRHS;
171
Andrew Trick3ec331e2011-08-10 03:46:27 +0000172 // If the condition is always true or always false, replace it with
173 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000174 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000175 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000176 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000177 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000178 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000179 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000180 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000181 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000182 } else if (isa<PHINode>(IVOperand) &&
183 SE->isLoopInvariantPredicate(Pred, S, X, ICmpLoop,
184 InvariantPredicate, InvariantLHS,
185 InvariantRHS)) {
186
187 // Rewrite the comparision to a loop invariant comparision if it can be done
188 // cheaply, where cheaply means "we don't need to emit any new
189 // instructions".
190
191 Value *NewLHS = nullptr, *NewRHS = nullptr;
192
193 if (S == InvariantLHS || X == InvariantLHS)
194 NewLHS =
195 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
196
197 if (S == InvariantRHS || X == InvariantRHS)
198 NewRHS =
199 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
200
201 for (Value *Incoming : cast<PHINode>(IVOperand)->incoming_values()) {
202 if (NewLHS && NewRHS)
203 break;
204
205 const SCEV *IncomingS = SE->getSCEV(Incoming);
206
207 if (!NewLHS && IncomingS == InvariantLHS)
208 NewLHS = Incoming;
209 if (!NewRHS && IncomingS == InvariantRHS)
210 NewRHS = Incoming;
211 }
212
213 if (!NewLHS || !NewRHS)
214 // We could not find an existing value to replace either LHS or RHS.
215 // Generating new instructions has subtler tradeoffs, so avoid doing that
216 // for now.
217 return;
218
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000219 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000220 ICmp->setPredicate(InvariantPredicate);
221 ICmp->setOperand(0, NewLHS);
222 ICmp->setOperand(1, NewRHS);
223 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000224 return;
225
Andrew Trick3ec331e2011-08-10 03:46:27 +0000226 ++NumElimCmp;
227 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000228}
229
Sanjay Patel7777b502014-11-12 18:07:42 +0000230/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000231/// remainder operations operating on an induction variable.
232void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
233 Value *IVOperand,
234 bool IsSigned) {
235 // We're only interested in the case where we know something about
236 // the numerator.
237 if (IVOperand != Rem->getOperand(0))
238 return;
239
240 // Get the SCEVs for the ICmp operands.
241 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
242 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
243
244 // Simplify unnecessary loops away.
245 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
246 S = SE->getSCEVAtScope(S, ICmpLoop);
247 X = SE->getSCEVAtScope(X, ICmpLoop);
248
249 // i % n --> i if i is in [0,n).
250 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
251 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
252 S, X))
253 Rem->replaceAllUsesWith(Rem->getOperand(0));
254 else {
255 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
256 const SCEV *LessOne =
257 SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
258 if (IsSigned && !SE->isKnownNonNegative(LessOne))
259 return;
260
261 if (!SE->isKnownPredicate(IsSigned ?
262 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
263 LessOne, X))
264 return;
265
266 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000267 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000268 SelectInst *Sel =
269 SelectInst::Create(ICmp,
270 ConstantInt::get(Rem->getType(), 0),
271 Rem->getOperand(0), "tmp", Rem);
272 Rem->replaceAllUsesWith(Sel);
273 }
274
Andrew Trick3ec331e2011-08-10 03:46:27 +0000275 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
276 ++NumElimRem;
277 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000278 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000279}
280
Sanjay Patel7777b502014-11-12 18:07:42 +0000281/// Eliminate an operation that consumes a simple IV and has
Andrew Trick3ec331e2011-08-10 03:46:27 +0000282/// no observable side-effect given the range of IV values.
Andrew Trick7251e412011-09-19 17:54:39 +0000283/// IVOperand is guaranteed SCEVable, but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000284bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
285 Instruction *IVOperand) {
286 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
287 eliminateIVComparison(ICmp, IVOperand);
288 return true;
289 }
290 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
291 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
292 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
293 eliminateIVRemainder(Rem, IVOperand, IsSigned);
294 return true;
295 }
296 }
297
298 // Eliminate any operation that SCEV can prove is an identity function.
299 if (!SE->isSCEVable(UseInst->getType()) ||
300 (UseInst->getType() != IVOperand->getType()) ||
301 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
302 return false;
303
304 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
305
306 UseInst->replaceAllUsesWith(IVOperand);
307 ++NumElimIdentity;
308 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000309 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000310 return true;
311}
312
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000313/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
314/// unsigned-overflow. Returns true if anything changed, false otherwise.
315bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
316 Value *IVOperand) {
317
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000318 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000319 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
320 return false;
321
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000322 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
323 SCEV::NoWrapFlags);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000324
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000325 switch (BO->getOpcode()) {
326 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000327 return false;
328
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000329 case Instruction::Add:
330 GetExprForBO = &ScalarEvolution::getAddExpr;
331 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000332
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000333 case Instruction::Sub:
334 GetExprForBO = &ScalarEvolution::getMinusSCEV;
335 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000336
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000337 case Instruction::Mul:
338 GetExprForBO = &ScalarEvolution::getMulExpr;
339 break;
340 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000341
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000342 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
343 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
344 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
345 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000346
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000347 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000348
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000349 if (!BO->hasNoUnsignedWrap()) {
350 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
351 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
352 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
353 SCEV::FlagAnyWrap);
354 if (ExtendAfterOp == OpAfterExtend) {
355 BO->setHasNoUnsignedWrap();
356 SE->forgetValue(BO);
357 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000358 }
359 }
360
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000361 if (!BO->hasNoSignedWrap()) {
362 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
363 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
364 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
365 SCEV::FlagAnyWrap);
366 if (ExtendAfterOp == OpAfterExtend) {
367 BO->setHasNoSignedWrap();
368 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000369 Changed = true;
370 }
371 }
372
373 return Changed;
374}
375
Andrew Trick0ba77a02013-12-23 23:31:49 +0000376/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
377/// analysis and optimization.
378///
379/// \return A new value representing the non-overflowing add if possible,
380/// otherwise return the original value.
381Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
382 const DominatorTree *DT) {
383 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
384 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
385 return IVUser;
386
387 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000388 BranchInst *Branch = nullptr;
389 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000390 for (User *U : II->users()) {
391 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000392 if (ExtractInst->getNumIndices() != 1)
393 continue;
394 if (ExtractInst->getIndices()[0] == 0)
395 AddVal = ExtractInst;
396 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000397 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000398 }
399 }
400 if (!AddVal || !Branch)
401 return IVUser;
402
403 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000404 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000405 return IVUser;
406
407 // Check if all users of the add are provably NSW.
408 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000409 for (Use &U : AddVal->uses()) {
410 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000411 BasicBlock *UseBB = UseInst->getParent();
412 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000413 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000414 if (!DT->dominates(ContinueBB, UseBB)) {
415 AllNSW = false;
416 break;
417 }
418 }
419 }
420 if (!AllNSW)
421 return IVUser;
422
423 // Go for it...
424 IRBuilder<> Builder(IVUser);
425 Instruction *AddInst = dyn_cast<Instruction>(
426 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
427
428 // The caller expects the new add to have the same form as the intrinsic. The
429 // IV operand position must be the same.
430 assert((AddInst->getOpcode() == Instruction::Add &&
431 AddInst->getOperand(0) == II->getOperand(0)) &&
432 "Bad add instruction created from overflow intrinsic.");
433
434 AddVal->replaceAllUsesWith(AddInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000435 DeadInsts.emplace_back(AddVal);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000436 return AddInst;
437}
438
Sanjay Patel7777b502014-11-12 18:07:42 +0000439/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000440static void pushIVUsers(
441 Instruction *Def,
442 SmallPtrSet<Instruction*,16> &Simplified,
443 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
444
Chandler Carruthcdf47882014-03-09 03:16:01 +0000445 for (User *U : Def->users()) {
446 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000447
448 // Avoid infinite or exponential worklist processing.
449 // Also ensure unique worklist users.
450 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
451 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000452 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000454 }
455}
456
Sanjay Patel7777b502014-11-12 18:07:42 +0000457/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000458/// expression in terms of that IV.
459///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000460/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000461/// non-recursively when the operand is already known to be a simpleIVUser.
462///
463static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
464 if (!SE->isSCEVable(I->getType()))
465 return false;
466
467 // Get the symbolic expression for this instruction.
468 const SCEV *S = SE->getSCEV(I);
469
470 // Only consider affine recurrences.
471 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
472 if (AR && AR->getLoop() == L)
473 return true;
474
475 return false;
476}
477
Sanjay Patel7777b502014-11-12 18:07:42 +0000478/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000479/// of the specified induction variable. Each successive simplification may push
480/// more users which may themselves be candidates for simplification.
481///
482/// This algorithm does not require IVUsers analysis. Instead, it simplifies
483/// instructions in-place during analysis. Rather than rewriting induction
484/// variables bottom-up from their users, it transforms a chain of IVUsers
485/// top-down, updating the IR only when it encouters a clear optimization
486/// opportunitiy.
487///
488/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
489///
490void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000491 if (!SE->isSCEVable(CurrIV->getType()))
492 return;
493
Andrew Trick3ec331e2011-08-10 03:46:27 +0000494 // Instructions processed by SimplifyIndvar for CurrIV.
495 SmallPtrSet<Instruction*,16> Simplified;
496
497 // Use-def pairs if IV users waiting to be processed for CurrIV.
498 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
499
500 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
501 // called multiple times for the same LoopPhi. This is the proper thing to
502 // do for loop header phis that use each other.
503 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
504
505 while (!SimpleIVUsers.empty()) {
506 std::pair<Instruction*, Instruction*> UseOper =
507 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000508 Instruction *UseInst = UseOper.first;
509
Andrew Trick3ec331e2011-08-10 03:46:27 +0000510 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000511 if (UseInst == CurrIV) continue;
512
513 if (V && V->shouldSplitOverflowInstrinsics()) {
514 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
515 if (!UseInst)
516 continue;
517 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000518
Andrew Trick74664d52011-08-10 04:01:31 +0000519 Instruction *IVOperand = UseOper.second;
520 for (unsigned N = 0; IVOperand; ++N) {
521 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000522
Andrew Trick74664d52011-08-10 04:01:31 +0000523 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
524 if (!NewOper)
525 break; // done folding
526 IVOperand = dyn_cast<Instruction>(NewOper);
527 }
528 if (!IVOperand)
529 continue;
530
531 if (eliminateIVUser(UseOper.first, IVOperand)) {
532 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000533 continue;
534 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000535
536 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
537 if (isa<OverflowingBinaryOperator>(BO) &&
538 strengthenOverflowingOperation(BO, IVOperand)) {
539 // re-queue uses of the now modified binary operator and fall
540 // through to the checks that remain.
541 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
542 }
543 }
544
Andrew Trick3ec331e2011-08-10 03:46:27 +0000545 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
546 if (V && Cast) {
547 V->visitCast(Cast);
548 continue;
549 }
550 if (isSimpleIVUser(UseOper.first, L, SE)) {
551 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
552 }
553 }
554}
555
556namespace llvm {
557
David Blaikiea379b1812011-12-20 02:50:00 +0000558void IVVisitor::anchor() { }
559
Sanjay Patel7777b502014-11-12 18:07:42 +0000560/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000561/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Tricke629d002011-08-10 04:22:26 +0000562bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000563 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
564{
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000565 LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth24fd0292015-01-17 14:31:35 +0000566 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000567 SIV.simplifyUsers(CurrIV, V);
568 return SIV.hasChanged();
569}
570
Sanjay Patel7777b502014-11-12 18:07:42 +0000571/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000572/// loop. This does not actually change or add IVs.
Andrew Tricke629d002011-08-10 04:22:26 +0000573bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000574 SmallVectorImpl<WeakVH> &Dead) {
575 bool Changed = false;
576 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Tricke629d002011-08-10 04:22:26 +0000577 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000578 }
579 return Changed;
580}
581
Andrew Trick3ec331e2011-08-10 03:46:27 +0000582} // namespace llvm