blob: b85dd5d5f9dafcdd1e6403c7c461f24774df0e3c [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
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000066 /// all simplifications 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
Sanjoy Das088bb0e2015-10-06 21:44:39 +000071 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
72
Andrew Trick3ec331e2011-08-10 03:46:27 +000073 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
74 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
75 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
76 bool IsSigned);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000077 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
Andrew Trick0ba77a02013-12-23 23:31:49 +000078
79 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
80 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000081 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000082}
Andrew Trick3ec331e2011-08-10 03:46:27 +000083
Sanjay Patel7777b502014-11-12 18:07:42 +000084/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000085/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000086///
Andrew Trick7251e412011-09-19 17:54:39 +000087/// IVOperand is guaranteed SCEVable, but UseInst may not be.
88///
Andrew Trick74664d52011-08-10 04:01:31 +000089/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000090/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000091/// Otherwise return null.
92Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000093 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000094 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000095 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000096 switch (UseInst->getOpcode()) {
97 default:
Craig Topperf40110f2014-04-25 05:29:35 +000098 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000099 case Instruction::UDiv:
100 case Instruction::LShr:
101 // We're only interested in the case where we know something about
102 // the numerator and have a constant denominator.
103 if (IVOperand != UseInst->getOperand(OperIdx) ||
104 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000105 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000106
107 // Attempt to fold a binary operator with constant operand.
108 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000109 if (!isa<BinaryOperator>(IVOperand)
110 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000111 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000112
113 IVSrc = IVOperand->getOperand(0);
114 // IVSrc must be the (SCEVable) IV, since the other operand is const.
115 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
116
117 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
118 if (UseInst->getOpcode() == Instruction::LShr) {
119 // Get a constant for the divisor. See createSCEV.
120 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
121 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000122 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000123
124 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000125 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000126 }
127 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
128 }
129 // We have something that might fold it's operand. Compare SCEVs.
130 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000131 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000132
133 // Bypass the operand if SCEV can prove it has no effect.
134 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000136
137 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
138 << " -> " << *UseInst << '\n');
139
140 UseInst->setOperand(OperIdx, IVSrc);
141 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
142
143 ++NumElimOperand;
144 Changed = true;
145 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000146 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000147 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000148}
149
Sanjay Patel7777b502014-11-12 18:07:42 +0000150/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000151/// comparisons against an induction variable.
152void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
153 unsigned IVOperIdx = 0;
154 ICmpInst::Predicate Pred = ICmp->getPredicate();
155 if (IVOperand != ICmp->getOperand(0)) {
156 // Swapped
157 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
158 IVOperIdx = 1;
159 Pred = ICmpInst::getSwappedPredicate(Pred);
160 }
161
162 // Get the SCEVs for the ICmp operands.
163 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
164 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
165
166 // Simplify unnecessary loops away.
167 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
168 S = SE->getSCEVAtScope(S, ICmpLoop);
169 X = SE->getSCEVAtScope(X, ICmpLoop);
170
Sanjoy Das5dab2052015-07-27 21:42:49 +0000171 ICmpInst::Predicate InvariantPredicate;
172 const SCEV *InvariantLHS, *InvariantRHS;
173
Andrew Trick3ec331e2011-08-10 03:46:27 +0000174 // If the condition is always true or always false, replace it with
175 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000176 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000177 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000178 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000179 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000180 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000181 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000182 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000183 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000184 } else if (isa<PHINode>(IVOperand) &&
185 SE->isLoopInvariantPredicate(Pred, S, X, ICmpLoop,
186 InvariantPredicate, InvariantLHS,
187 InvariantRHS)) {
188
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000189 // Rewrite the comparison to a loop invariant comparison if it can be done
Sanjoy Das5dab2052015-07-27 21:42:49 +0000190 // cheaply, where cheaply means "we don't need to emit any new
191 // instructions".
192
193 Value *NewLHS = nullptr, *NewRHS = nullptr;
194
195 if (S == InvariantLHS || X == InvariantLHS)
196 NewLHS =
197 ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
198
199 if (S == InvariantRHS || X == InvariantRHS)
200 NewRHS =
201 ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
202
203 for (Value *Incoming : cast<PHINode>(IVOperand)->incoming_values()) {
204 if (NewLHS && NewRHS)
205 break;
206
207 const SCEV *IncomingS = SE->getSCEV(Incoming);
208
209 if (!NewLHS && IncomingS == InvariantLHS)
210 NewLHS = Incoming;
211 if (!NewRHS && IncomingS == InvariantRHS)
212 NewRHS = Incoming;
213 }
214
215 if (!NewLHS || !NewRHS)
216 // We could not find an existing value to replace either LHS or RHS.
217 // Generating new instructions has subtler tradeoffs, so avoid doing that
218 // for now.
219 return;
220
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000221 DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000222 ICmp->setPredicate(InvariantPredicate);
223 ICmp->setOperand(0, NewLHS);
224 ICmp->setOperand(1, NewRHS);
225 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000226 return;
227
Andrew Trick3ec331e2011-08-10 03:46:27 +0000228 ++NumElimCmp;
229 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000230}
231
Sanjay Patel7777b502014-11-12 18:07:42 +0000232/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000233/// remainder operations operating on an induction variable.
234void SimplifyIndvar::eliminateIVRemainder(BinaryOperator *Rem,
235 Value *IVOperand,
236 bool IsSigned) {
237 // We're only interested in the case where we know something about
238 // the numerator.
239 if (IVOperand != Rem->getOperand(0))
240 return;
241
242 // Get the SCEVs for the ICmp operands.
243 const SCEV *S = SE->getSCEV(Rem->getOperand(0));
244 const SCEV *X = SE->getSCEV(Rem->getOperand(1));
245
246 // Simplify unnecessary loops away.
247 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
248 S = SE->getSCEVAtScope(S, ICmpLoop);
249 X = SE->getSCEVAtScope(X, ICmpLoop);
250
251 // i % n --> i if i is in [0,n).
252 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
253 SE->isKnownPredicate(IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
254 S, X))
255 Rem->replaceAllUsesWith(Rem->getOperand(0));
256 else {
257 // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000258 const SCEV *LessOne = SE->getMinusSCEV(S, SE->getOne(S->getType()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000259 if (IsSigned && !SE->isKnownNonNegative(LessOne))
260 return;
261
262 if (!SE->isKnownPredicate(IsSigned ?
263 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
264 LessOne, X))
265 return;
266
267 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000268 Rem->getOperand(0), Rem->getOperand(1));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000269 SelectInst *Sel =
270 SelectInst::Create(ICmp,
271 ConstantInt::get(Rem->getType(), 0),
272 Rem->getOperand(0), "tmp", Rem);
273 Rem->replaceAllUsesWith(Sel);
274 }
275
Andrew Trick3ec331e2011-08-10 03:46:27 +0000276 DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
277 ++NumElimRem;
278 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000279 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000280}
281
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000282/// Eliminate an operation that consumes a simple IV and has no observable
283/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
284/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000285bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
286 Instruction *IVOperand) {
287 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
288 eliminateIVComparison(ICmp, IVOperand);
289 return true;
290 }
291 if (BinaryOperator *Rem = dyn_cast<BinaryOperator>(UseInst)) {
292 bool IsSigned = Rem->getOpcode() == Instruction::SRem;
293 if (IsSigned || Rem->getOpcode() == Instruction::URem) {
294 eliminateIVRemainder(Rem, IVOperand, IsSigned);
295 return true;
296 }
297 }
298
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000299 if (eliminateIdentitySCEV(UseInst, IVOperand))
300 return true;
301
302 return false;
303}
304
305/// Eliminate any operation that SCEV can prove is an identity function.
306bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
307 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000308 if (!SE->isSCEVable(UseInst->getType()) ||
309 (UseInst->getType() != IVOperand->getType()) ||
310 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
311 return false;
312
313 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
314
315 UseInst->replaceAllUsesWith(IVOperand);
316 ++NumElimIdentity;
317 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000318 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000319 return true;
320}
321
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000322/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
323/// unsigned-overflow. Returns true if anything changed, false otherwise.
324bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
325 Value *IVOperand) {
326
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000327 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000328 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
329 return false;
330
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000331 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
332 SCEV::NoWrapFlags);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000333
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000334 switch (BO->getOpcode()) {
335 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000336 return false;
337
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000338 case Instruction::Add:
339 GetExprForBO = &ScalarEvolution::getAddExpr;
340 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000341
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000342 case Instruction::Sub:
343 GetExprForBO = &ScalarEvolution::getMinusSCEV;
344 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000345
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000346 case Instruction::Mul:
347 GetExprForBO = &ScalarEvolution::getMulExpr;
348 break;
349 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000350
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000351 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
352 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
353 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
354 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000355
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000356 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000357
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000358 if (!BO->hasNoUnsignedWrap()) {
359 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
360 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
361 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
362 SCEV::FlagAnyWrap);
363 if (ExtendAfterOp == OpAfterExtend) {
364 BO->setHasNoUnsignedWrap();
365 SE->forgetValue(BO);
366 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000367 }
368 }
369
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000370 if (!BO->hasNoSignedWrap()) {
371 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
372 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
373 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
374 SCEV::FlagAnyWrap);
375 if (ExtendAfterOp == OpAfterExtend) {
376 BO->setHasNoSignedWrap();
377 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000378 Changed = true;
379 }
380 }
381
382 return Changed;
383}
384
Andrew Trick0ba77a02013-12-23 23:31:49 +0000385/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
386/// analysis and optimization.
387///
388/// \return A new value representing the non-overflowing add if possible,
389/// otherwise return the original value.
390Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
391 const DominatorTree *DT) {
392 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
393 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
394 return IVUser;
395
396 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000397 BranchInst *Branch = nullptr;
398 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000399 for (User *U : II->users()) {
400 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000401 if (ExtractInst->getNumIndices() != 1)
402 continue;
403 if (ExtractInst->getIndices()[0] == 0)
404 AddVal = ExtractInst;
405 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000406 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000407 }
408 }
409 if (!AddVal || !Branch)
410 return IVUser;
411
412 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000413 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000414 return IVUser;
415
416 // Check if all users of the add are provably NSW.
417 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000418 for (Use &U : AddVal->uses()) {
419 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000420 BasicBlock *UseBB = UseInst->getParent();
421 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000422 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000423 if (!DT->dominates(ContinueBB, UseBB)) {
424 AllNSW = false;
425 break;
426 }
427 }
428 }
429 if (!AllNSW)
430 return IVUser;
431
432 // Go for it...
433 IRBuilder<> Builder(IVUser);
434 Instruction *AddInst = dyn_cast<Instruction>(
435 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
436
437 // The caller expects the new add to have the same form as the intrinsic. The
438 // IV operand position must be the same.
439 assert((AddInst->getOpcode() == Instruction::Add &&
440 AddInst->getOperand(0) == II->getOperand(0)) &&
441 "Bad add instruction created from overflow intrinsic.");
442
443 AddVal->replaceAllUsesWith(AddInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000444 DeadInsts.emplace_back(AddVal);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000445 return AddInst;
446}
447
Sanjay Patel7777b502014-11-12 18:07:42 +0000448/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000449static void pushIVUsers(
450 Instruction *Def,
451 SmallPtrSet<Instruction*,16> &Simplified,
452 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
453
Chandler Carruthcdf47882014-03-09 03:16:01 +0000454 for (User *U : Def->users()) {
455 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000456
457 // Avoid infinite or exponential worklist processing.
458 // Also ensure unique worklist users.
459 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
460 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000461 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000462 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000463 }
464}
465
Sanjay Patel7777b502014-11-12 18:07:42 +0000466/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000467/// expression in terms of that IV.
468///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000469/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000470/// non-recursively when the operand is already known to be a simpleIVUser.
471///
472static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
473 if (!SE->isSCEVable(I->getType()))
474 return false;
475
476 // Get the symbolic expression for this instruction.
477 const SCEV *S = SE->getSCEV(I);
478
479 // Only consider affine recurrences.
480 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
481 if (AR && AR->getLoop() == L)
482 return true;
483
484 return false;
485}
486
Sanjay Patel7777b502014-11-12 18:07:42 +0000487/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000488/// of the specified induction variable. Each successive simplification may push
489/// more users which may themselves be candidates for simplification.
490///
491/// This algorithm does not require IVUsers analysis. Instead, it simplifies
492/// instructions in-place during analysis. Rather than rewriting induction
493/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000494/// top-down, updating the IR only when it encounters a clear optimization
495/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000496///
497/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
498///
499void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000500 if (!SE->isSCEVable(CurrIV->getType()))
501 return;
502
Andrew Trick3ec331e2011-08-10 03:46:27 +0000503 // Instructions processed by SimplifyIndvar for CurrIV.
504 SmallPtrSet<Instruction*,16> Simplified;
505
506 // Use-def pairs if IV users waiting to be processed for CurrIV.
507 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
508
509 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
510 // called multiple times for the same LoopPhi. This is the proper thing to
511 // do for loop header phis that use each other.
512 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
513
514 while (!SimpleIVUsers.empty()) {
515 std::pair<Instruction*, Instruction*> UseOper =
516 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000517 Instruction *UseInst = UseOper.first;
518
Andrew Trick3ec331e2011-08-10 03:46:27 +0000519 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000520 if (UseInst == CurrIV) continue;
521
522 if (V && V->shouldSplitOverflowInstrinsics()) {
523 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
524 if (!UseInst)
525 continue;
526 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000527
Andrew Trick74664d52011-08-10 04:01:31 +0000528 Instruction *IVOperand = UseOper.second;
529 for (unsigned N = 0; IVOperand; ++N) {
530 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000531
Andrew Trick74664d52011-08-10 04:01:31 +0000532 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
533 if (!NewOper)
534 break; // done folding
535 IVOperand = dyn_cast<Instruction>(NewOper);
536 }
537 if (!IVOperand)
538 continue;
539
540 if (eliminateIVUser(UseOper.first, IVOperand)) {
541 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000542 continue;
543 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000544
545 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
546 if (isa<OverflowingBinaryOperator>(BO) &&
547 strengthenOverflowingOperation(BO, IVOperand)) {
548 // re-queue uses of the now modified binary operator and fall
549 // through to the checks that remain.
550 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
551 }
552 }
553
Andrew Trick3ec331e2011-08-10 03:46:27 +0000554 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
555 if (V && Cast) {
556 V->visitCast(Cast);
557 continue;
558 }
559 if (isSimpleIVUser(UseOper.first, L, SE)) {
560 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
561 }
562 }
563}
564
565namespace llvm {
566
David Blaikiea379b1812011-12-20 02:50:00 +0000567void IVVisitor::anchor() { }
568
Sanjay Patel7777b502014-11-12 18:07:42 +0000569/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000570/// by using ScalarEvolution to analyze the IV's recurrence.
Andrew Tricke629d002011-08-10 04:22:26 +0000571bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000572 SmallVectorImpl<WeakVH> &Dead, IVVisitor *V)
573{
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000574 LoopInfo *LI = &LPM->getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth24fd0292015-01-17 14:31:35 +0000575 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000576 SIV.simplifyUsers(CurrIV, V);
577 return SIV.hasChanged();
578}
579
Sanjay Patel7777b502014-11-12 18:07:42 +0000580/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000581/// loop. This does not actually change or add IVs.
Andrew Tricke629d002011-08-10 04:22:26 +0000582bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000583 SmallVectorImpl<WeakVH> &Dead) {
584 bool Changed = false;
585 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Andrew Tricke629d002011-08-10 04:22:26 +0000586 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, LPM, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000587 }
588 return Changed;
589}
590
Andrew Trick3ec331e2011-08-10 03:46:27 +0000591} // namespace llvm