blob: fe5d8e49fc9fa8b17ff75e31046bbb7ea0669e71 [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;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000050 DominatorTree *DT;
Andrew Trick3ec331e2011-08-10 03:46:27 +000051
52 SmallVectorImpl<WeakVH> &DeadInsts;
53
54 bool Changed;
55
56 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000057 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
58 LoopInfo *LI,SmallVectorImpl<WeakVH> &Dead)
59 : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000060 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000061 }
62
63 bool hasChanged() const { return Changed; }
64
65 /// Iteratively perform simplification on a worklist of users of the
66 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000067 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000068 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000069
Andrew Trick74664d52011-08-10 04:01:31 +000070 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000071
Sanjoy Das088bb0e2015-10-06 21:44:39 +000072 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
73
Andrew Trick3ec331e2011-08-10 03:46:27 +000074 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
75 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
76 void eliminateIVRemainder(BinaryOperator *Rem, Value *IVOperand,
77 bool IsSigned);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000078 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
Andrew Trick0ba77a02013-12-23 23:31:49 +000079
80 Instruction *splitOverflowIntrinsic(Instruction *IVUser,
81 const DominatorTree *DT);
Andrew Trick3ec331e2011-08-10 03:46:27 +000082 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000083}
Andrew Trick3ec331e2011-08-10 03:46:27 +000084
Sanjay Patel7777b502014-11-12 18:07:42 +000085/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +000086/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +000087///
Andrew Trick7251e412011-09-19 17:54:39 +000088/// IVOperand is guaranteed SCEVable, but UseInst may not be.
89///
Andrew Trick74664d52011-08-10 04:01:31 +000090/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +000091/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +000092/// Otherwise return null.
93Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +000094 Value *IVSrc = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000095 unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +000096 const SCEV *FoldedExpr = nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +000097 switch (UseInst->getOpcode()) {
98 default:
Craig Topperf40110f2014-04-25 05:29:35 +000099 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000100 case Instruction::UDiv:
101 case Instruction::LShr:
102 // We're only interested in the case where we know something about
103 // the numerator and have a constant denominator.
104 if (IVOperand != UseInst->getOperand(OperIdx) ||
105 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000106 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000107
108 // Attempt to fold a binary operator with constant operand.
109 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000110 if (!isa<BinaryOperator>(IVOperand)
111 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000113
114 IVSrc = IVOperand->getOperand(0);
115 // IVSrc must be the (SCEVable) IV, since the other operand is const.
116 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
117
118 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
119 if (UseInst->getOpcode() == Instruction::LShr) {
120 // Get a constant for the divisor. See createSCEV.
121 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
122 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000123 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000124
125 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000126 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000127 }
128 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
129 }
130 // We have something that might fold it's operand. Compare SCEVs.
131 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000132 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000133
134 // Bypass the operand if SCEV can prove it has no effect.
135 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000136 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000137
138 DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
139 << " -> " << *UseInst << '\n');
140
141 UseInst->setOperand(OperIdx, IVSrc);
142 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
143
144 ++NumElimOperand;
145 Changed = true;
146 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000147 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000148 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000149}
150
Sanjay Patel7777b502014-11-12 18:07:42 +0000151/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000152/// comparisons against an induction variable.
153void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
154 unsigned IVOperIdx = 0;
155 ICmpInst::Predicate Pred = ICmp->getPredicate();
156 if (IVOperand != ICmp->getOperand(0)) {
157 // Swapped
158 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
159 IVOperIdx = 1;
160 Pred = ICmpInst::getSwappedPredicate(Pred);
161 }
162
163 // Get the SCEVs for the ICmp operands.
164 const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
165 const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
166
167 // Simplify unnecessary loops away.
168 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
169 S = SE->getSCEVAtScope(S, ICmpLoop);
170 X = SE->getSCEVAtScope(X, ICmpLoop);
171
Sanjoy Das5dab2052015-07-27 21:42:49 +0000172 ICmpInst::Predicate InvariantPredicate;
173 const SCEV *InvariantLHS, *InvariantRHS;
174
Andrew Trick3ec331e2011-08-10 03:46:27 +0000175 // If the condition is always true or always false, replace it with
176 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000177 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000178 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000179 DeadInsts.emplace_back(ICmp);
Sanjoy Dasc18115d2015-08-06 20:43:28 +0000180 DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000181 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000182 ICmp->replaceAllUsesWith(ConstantInt::getFalse(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 (isa<PHINode>(IVOperand) &&
Sanjoy Das60fb8992016-03-18 20:37:07 +0000186 SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
187 InvariantLHS, InvariantRHS)) {
Sanjoy Das5dab2052015-07-27 21:42:49 +0000188
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
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000313 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
314 // dominator tree, even if X is an operand to Y. For instance, in
315 //
316 // %iv = phi i32 {0,+,1}
317 // br %cond, label %left, label %merge
318 //
319 // left:
320 // %X = add i32 %iv, 0
321 // br label %merge
322 //
323 // merge:
324 // %M = phi (%X, %iv)
325 //
326 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
327 // %M.replaceAllUsesWith(%X) would be incorrect.
328
329 if (isa<PHINode>(UseInst))
330 // If UseInst is not a PHI node then we know that IVOperand dominates
331 // UseInst directly from the legality of SSA.
332 if (!DT || !DT->dominates(IVOperand, UseInst))
333 return false;
334
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000335 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
336 return false;
337
Andrew Trick3ec331e2011-08-10 03:46:27 +0000338 DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
339
340 UseInst->replaceAllUsesWith(IVOperand);
341 ++NumElimIdentity;
342 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000343 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000344 return true;
345}
346
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000347/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
348/// unsigned-overflow. Returns true if anything changed, false otherwise.
349bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
350 Value *IVOperand) {
351
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000352 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000353 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
354 return false;
355
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000356 const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
357 SCEV::NoWrapFlags);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000358
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000359 switch (BO->getOpcode()) {
360 default:
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000361 return false;
362
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000363 case Instruction::Add:
364 GetExprForBO = &ScalarEvolution::getAddExpr;
365 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000366
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000367 case Instruction::Sub:
368 GetExprForBO = &ScalarEvolution::getMinusSCEV;
369 break;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000370
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000371 case Instruction::Mul:
372 GetExprForBO = &ScalarEvolution::getMulExpr;
373 break;
374 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000375
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000376 unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
377 Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
378 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
379 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000380
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000381 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000382
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000383 if (!BO->hasNoUnsignedWrap()) {
384 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
385 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
386 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
387 SCEV::FlagAnyWrap);
388 if (ExtendAfterOp == OpAfterExtend) {
389 BO->setHasNoUnsignedWrap();
390 SE->forgetValue(BO);
391 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000392 }
393 }
394
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000395 if (!BO->hasNoSignedWrap()) {
396 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
397 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
398 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
399 SCEV::FlagAnyWrap);
400 if (ExtendAfterOp == OpAfterExtend) {
401 BO->setHasNoSignedWrap();
402 SE->forgetValue(BO);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000403 Changed = true;
404 }
405 }
406
407 return Changed;
408}
409
Andrew Trick0ba77a02013-12-23 23:31:49 +0000410/// \brief Split sadd.with.overflow into add + sadd.with.overflow to allow
411/// analysis and optimization.
412///
413/// \return A new value representing the non-overflowing add if possible,
414/// otherwise return the original value.
415Instruction *SimplifyIndvar::splitOverflowIntrinsic(Instruction *IVUser,
416 const DominatorTree *DT) {
417 IntrinsicInst *II = dyn_cast<IntrinsicInst>(IVUser);
418 if (!II || II->getIntrinsicID() != Intrinsic::sadd_with_overflow)
419 return IVUser;
420
421 // Find a branch guarded by the overflow check.
Craig Topperf40110f2014-04-25 05:29:35 +0000422 BranchInst *Branch = nullptr;
423 Instruction *AddVal = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000424 for (User *U : II->users()) {
425 if (ExtractValueInst *ExtractInst = dyn_cast<ExtractValueInst>(U)) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000426 if (ExtractInst->getNumIndices() != 1)
427 continue;
428 if (ExtractInst->getIndices()[0] == 0)
429 AddVal = ExtractInst;
430 else if (ExtractInst->getIndices()[0] == 1 && ExtractInst->hasOneUse())
Chandler Carruthcdf47882014-03-09 03:16:01 +0000431 Branch = dyn_cast<BranchInst>(ExtractInst->user_back());
Andrew Trick0ba77a02013-12-23 23:31:49 +0000432 }
433 }
434 if (!AddVal || !Branch)
435 return IVUser;
436
437 BasicBlock *ContinueBB = Branch->getSuccessor(1);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000438 if (std::next(pred_begin(ContinueBB)) != pred_end(ContinueBB))
Andrew Trick0ba77a02013-12-23 23:31:49 +0000439 return IVUser;
440
441 // Check if all users of the add are provably NSW.
442 bool AllNSW = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000443 for (Use &U : AddVal->uses()) {
444 if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser())) {
Andrew Trick0ba77a02013-12-23 23:31:49 +0000445 BasicBlock *UseBB = UseInst->getParent();
446 if (PHINode *PHI = dyn_cast<PHINode>(UseInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000447 UseBB = PHI->getIncomingBlock(U);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000448 if (!DT->dominates(ContinueBB, UseBB)) {
449 AllNSW = false;
450 break;
451 }
452 }
453 }
454 if (!AllNSW)
455 return IVUser;
456
457 // Go for it...
458 IRBuilder<> Builder(IVUser);
459 Instruction *AddInst = dyn_cast<Instruction>(
460 Builder.CreateNSWAdd(II->getOperand(0), II->getOperand(1)));
461
462 // The caller expects the new add to have the same form as the intrinsic. The
463 // IV operand position must be the same.
464 assert((AddInst->getOpcode() == Instruction::Add &&
465 AddInst->getOperand(0) == II->getOperand(0)) &&
466 "Bad add instruction created from overflow intrinsic.");
467
468 AddVal->replaceAllUsesWith(AddInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000469 DeadInsts.emplace_back(AddVal);
Andrew Trick0ba77a02013-12-23 23:31:49 +0000470 return AddInst;
471}
472
Sanjay Patel7777b502014-11-12 18:07:42 +0000473/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000474static void pushIVUsers(
475 Instruction *Def,
476 SmallPtrSet<Instruction*,16> &Simplified,
477 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
478
Chandler Carruthcdf47882014-03-09 03:16:01 +0000479 for (User *U : Def->users()) {
480 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000481
482 // Avoid infinite or exponential worklist processing.
483 // Also ensure unique worklist users.
484 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
485 // self edges first.
David Blaikie70573dc2014-11-19 07:49:26 +0000486 if (UI != Def && Simplified.insert(UI).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000487 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000488 }
489}
490
Sanjay Patel7777b502014-11-12 18:07:42 +0000491/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000492/// expression in terms of that IV.
493///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000494/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000495/// non-recursively when the operand is already known to be a simpleIVUser.
496///
497static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
498 if (!SE->isSCEVable(I->getType()))
499 return false;
500
501 // Get the symbolic expression for this instruction.
502 const SCEV *S = SE->getSCEV(I);
503
504 // Only consider affine recurrences.
505 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
506 if (AR && AR->getLoop() == L)
507 return true;
508
509 return false;
510}
511
Sanjay Patel7777b502014-11-12 18:07:42 +0000512/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000513/// of the specified induction variable. Each successive simplification may push
514/// more users which may themselves be candidates for simplification.
515///
516/// This algorithm does not require IVUsers analysis. Instead, it simplifies
517/// instructions in-place during analysis. Rather than rewriting induction
518/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000519/// top-down, updating the IR only when it encounters a clear optimization
520/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000521///
522/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
523///
524void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000525 if (!SE->isSCEVable(CurrIV->getType()))
526 return;
527
Andrew Trick3ec331e2011-08-10 03:46:27 +0000528 // Instructions processed by SimplifyIndvar for CurrIV.
529 SmallPtrSet<Instruction*,16> Simplified;
530
531 // Use-def pairs if IV users waiting to be processed for CurrIV.
532 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
533
534 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
535 // called multiple times for the same LoopPhi. This is the proper thing to
536 // do for loop header phis that use each other.
537 pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
538
539 while (!SimpleIVUsers.empty()) {
540 std::pair<Instruction*, Instruction*> UseOper =
541 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000542 Instruction *UseInst = UseOper.first;
543
Andrew Trick3ec331e2011-08-10 03:46:27 +0000544 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000545 if (UseInst == CurrIV) continue;
546
547 if (V && V->shouldSplitOverflowInstrinsics()) {
548 UseInst = splitOverflowIntrinsic(UseInst, V->getDomTree());
549 if (!UseInst)
550 continue;
551 }
Andrew Trick3ec331e2011-08-10 03:46:27 +0000552
Andrew Trick74664d52011-08-10 04:01:31 +0000553 Instruction *IVOperand = UseOper.second;
554 for (unsigned N = 0; IVOperand; ++N) {
555 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000556
Andrew Trick74664d52011-08-10 04:01:31 +0000557 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
558 if (!NewOper)
559 break; // done folding
560 IVOperand = dyn_cast<Instruction>(NewOper);
561 }
562 if (!IVOperand)
563 continue;
564
565 if (eliminateIVUser(UseOper.first, IVOperand)) {
566 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000567 continue;
568 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000569
570 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
571 if (isa<OverflowingBinaryOperator>(BO) &&
572 strengthenOverflowingOperation(BO, IVOperand)) {
573 // re-queue uses of the now modified binary operator and fall
574 // through to the checks that remain.
575 pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
576 }
577 }
578
Andrew Trick3ec331e2011-08-10 03:46:27 +0000579 CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
580 if (V && Cast) {
581 V->visitCast(Cast);
582 continue;
583 }
584 if (isSimpleIVUser(UseOper.first, L, SE)) {
585 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
586 }
587 }
588}
589
590namespace llvm {
591
David Blaikiea379b1812011-12-20 02:50:00 +0000592void IVVisitor::anchor() { }
593
Sanjay Patel7777b502014-11-12 18:07:42 +0000594/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000595/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000596bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000597 LoopInfo *LI, SmallVectorImpl<WeakVH> &Dead,
598 IVVisitor *V) {
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000599 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000600 SIV.simplifyUsers(CurrIV, V);
601 return SIV.hasChanged();
602}
603
Sanjay Patel7777b502014-11-12 18:07:42 +0000604/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000605/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000606bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Justin Bogner843fb202015-12-15 19:40:57 +0000607 LoopInfo *LI, SmallVectorImpl<WeakVH> &Dead) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000608 bool Changed = false;
609 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Justin Bogner843fb202015-12-15 19:40:57 +0000610 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000611 }
612 return Changed;
613}
614
Andrew Trick3ec331e2011-08-10 03:46:27 +0000615} // namespace llvm