blob: cbb114f9a47aabba188ba9051d2ce0b9d74e3d63 [file] [log] [blame]
Andrew Trick3ec331e2011-08-10 03:46:27 +00001//===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Trick3ec331e2011-08-10 03:46:27 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements induction variable simplification. It does
10// not define any actual pass or policy, but provides a single function to
11// simplify a loop's induction variables based on ScalarEvolution.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000019#include "llvm/Analysis/LoopInfo.h"
Hongbin Zhengd36f20302017-10-12 02:54:11 +000020#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000023#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Instructions.h"
Nikita Popov900578d2019-06-01 20:21:53 +000025#include "llvm/IR/IntrinsicInst.h"
David Greenb26a0a42017-07-05 13:25:58 +000026#include "llvm/IR/PatternMatch.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
Max Kazantsev0ed79622018-06-13 02:25:32 +000029#include "llvm/Transforms/Utils/Local.h"
Andrew Trick3ec331e2011-08-10 03:46:27 +000030
31using namespace llvm;
32
Chandler Carruth964daaa2014-04-22 02:55:47 +000033#define DEBUG_TYPE "indvars"
34
Andrew Trick3ec331e2011-08-10 03:46:27 +000035STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
36STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +000037STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
Andrew Trick3ec331e2011-08-10 03:46:27 +000038STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000039STATISTIC(
40 NumSimplifiedSDiv,
41 "Number of IV signed division operations converted to unsigned division");
Hongbin Zhengf0093e42017-09-25 17:39:40 +000042STATISTIC(
43 NumSimplifiedSRem,
44 "Number of IV signed remainder operations converted to unsigned remainder");
Andrew Trick3ec331e2011-08-10 03:46:27 +000045STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
46
47namespace {
Sanjay Patel7777b502014-11-12 18:07:42 +000048 /// This is a utility for simplifying induction variables
Andrew Trick3ec331e2011-08-10 03:46:27 +000049 /// based on ScalarEvolution. It is the primary instrument of the
50 /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
51 /// other loop passes that preserve SCEV.
52 class SimplifyIndvar {
53 Loop *L;
54 LoopInfo *LI;
Andrew Trick3ec331e2011-08-10 03:46:27 +000055 ScalarEvolution *SE;
Sanjoy Das5c8bead2015-10-06 21:44:49 +000056 DominatorTree *DT;
Hongbin Zhengd36f20302017-10-12 02:54:11 +000057 SCEVExpander &Rewriter;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000058 SmallVectorImpl<WeakTrackingVH> &DeadInsts;
Andrew Trick3ec331e2011-08-10 03:46:27 +000059
60 bool Changed;
61
62 public:
Sanjoy Das5c8bead2015-10-06 21:44:49 +000063 SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
Hongbin Zhengd36f20302017-10-12 02:54:11 +000064 LoopInfo *LI, SCEVExpander &Rewriter,
65 SmallVectorImpl<WeakTrackingVH> &Dead)
66 : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
67 Changed(false) {
Andrew Tricke629d002011-08-10 04:22:26 +000068 assert(LI && "IV simplification requires LoopInfo");
Andrew Trick3ec331e2011-08-10 03:46:27 +000069 }
70
71 bool hasChanged() const { return Changed; }
72
73 /// Iteratively perform simplification on a worklist of users of the
74 /// specified induction variable. This is the top-level driver that applies
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000075 /// all simplifications to users of an IV.
Craig Topperf40110f2014-04-25 05:29:35 +000076 void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Andrew Trick3ec331e2011-08-10 03:46:27 +000077
Andrew Trick74664d52011-08-10 04:01:31 +000078 Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000079
Sanjoy Das088bb0e2015-10-06 21:44:39 +000080 bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
Hongbin Zhengd36f20302017-10-12 02:54:11 +000081 bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
Sanjoy Das088bb0e2015-10-06 21:44:39 +000082
Nikita Popov900578d2019-06-01 20:21:53 +000083 bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
Nikita Popov91455622019-06-15 08:48:52 +000084 bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
Max Kazantsev37da4332018-06-19 04:48:34 +000085 bool eliminateTrunc(TruncInst *TI);
Andrew Trick3ec331e2011-08-10 03:46:27 +000086 bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
Philip Reames7b861f02017-11-01 19:49:20 +000087 bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000088 void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
Hongbin Zhengf0093e42017-09-25 17:39:40 +000089 void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
90 bool IsSigned);
91 void replaceRemWithNumerator(BinaryOperator *Rem);
92 void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
93 void replaceSRemWithURem(BinaryOperator *Rem);
Hongbin Zhengbfd7c382017-03-30 21:56:56 +000094 bool eliminateSDiv(BinaryOperator *SDiv);
Sanjoy Das7c0ce262015-01-06 19:02:56 +000095 bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
David Greenb26a0a42017-07-05 13:25:58 +000096 bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
Andrew Trick3ec331e2011-08-10 03:46:27 +000097 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000098}
Andrew Trick3ec331e2011-08-10 03:46:27 +000099
Sanjay Patel7777b502014-11-12 18:07:42 +0000100/// Fold an IV operand into its use. This removes increments of an
Andrew Trick3ec331e2011-08-10 03:46:27 +0000101/// aligned IV when used by a instruction that ignores the low bits.
Andrew Trick74664d52011-08-10 04:01:31 +0000102///
Andrew Trick7251e412011-09-19 17:54:39 +0000103/// IVOperand is guaranteed SCEVable, but UseInst may not be.
104///
Andrew Trick74664d52011-08-10 04:01:31 +0000105/// Return the operand of IVOperand for this induction variable if IVOperand can
Andrew Trick6dbb0602011-08-10 18:07:05 +0000106/// be folded (in case more folding opportunities have been exposed).
Andrew Trick74664d52011-08-10 04:01:31 +0000107/// Otherwise return null.
108Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Craig Topperf40110f2014-04-25 05:29:35 +0000109 Value *IVSrc = nullptr;
Max Kazantsev1d893bf2018-10-10 04:19:38 +0000110 const unsigned OperIdx = 0;
Craig Topperf40110f2014-04-25 05:29:35 +0000111 const SCEV *FoldedExpr = nullptr;
Max Kazantsevb2e51092018-10-11 07:22:26 +0000112 bool MustDropExactFlag = false;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000113 switch (UseInst->getOpcode()) {
114 default:
Craig Topperf40110f2014-04-25 05:29:35 +0000115 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000116 case Instruction::UDiv:
117 case Instruction::LShr:
118 // We're only interested in the case where we know something about
119 // the numerator and have a constant denominator.
120 if (IVOperand != UseInst->getOperand(OperIdx) ||
121 !isa<ConstantInt>(UseInst->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000122 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000123
124 // Attempt to fold a binary operator with constant operand.
125 // e.g. ((I + 1) >> 2) => I >> 2
Andrew Trick94904582011-11-17 23:36:35 +0000126 if (!isa<BinaryOperator>(IVOperand)
127 || !isa<ConstantInt>(IVOperand->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000128 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000129
130 IVSrc = IVOperand->getOperand(0);
131 // IVSrc must be the (SCEVable) IV, since the other operand is const.
132 assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
133
134 ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
135 if (UseInst->getOpcode() == Instruction::LShr) {
136 // Get a constant for the divisor. See createSCEV.
137 uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
138 if (D->getValue().uge(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000139 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000140
141 D = ConstantInt::get(UseInst->getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +0000142 APInt::getOneBitSet(BitWidth, D->getZExtValue()));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000143 }
144 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
Max Kazantsevb2e51092018-10-11 07:22:26 +0000145 // We might have 'exact' flag set at this point which will no longer be
146 // correct after we make the replacement.
147 if (UseInst->isExact() &&
148 SE->getSCEV(IVSrc) != SE->getMulExpr(FoldedExpr, SE->getSCEV(D)))
149 MustDropExactFlag = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000150 }
151 // We have something that might fold it's operand. Compare SCEVs.
152 if (!SE->isSCEVable(UseInst->getType()))
Craig Topperf40110f2014-04-25 05:29:35 +0000153 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000154
155 // Bypass the operand if SCEV can prove it has no effect.
156 if (SE->getSCEV(UseInst) != FoldedExpr)
Craig Topperf40110f2014-04-25 05:29:35 +0000157 return nullptr;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000158
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000159 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
160 << " -> " << *UseInst << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000161
162 UseInst->setOperand(OperIdx, IVSrc);
163 assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
164
Max Kazantsevb2e51092018-10-11 07:22:26 +0000165 if (MustDropExactFlag)
166 UseInst->dropPoisonGeneratingFlags();
167
Andrew Trick3ec331e2011-08-10 03:46:27 +0000168 ++NumElimOperand;
169 Changed = true;
170 if (IVOperand->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000171 DeadInsts.emplace_back(IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000172 return IVSrc;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000173}
174
Philip Reames7b861f02017-11-01 19:49:20 +0000175bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
176 Value *IVOperand) {
177 unsigned IVOperIdx = 0;
178 ICmpInst::Predicate Pred = ICmp->getPredicate();
179 if (IVOperand != ICmp->getOperand(0)) {
180 // Swapped
181 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
182 IVOperIdx = 1;
183 Pred = ICmpInst::getSwappedPredicate(Pred);
184 }
Philip Reamesdc417a92017-10-31 18:04:57 +0000185
Philip Reames7b861f02017-11-01 19:49:20 +0000186 // Get the SCEVs for the ICmp operands (in the specific context of the
187 // current loop)
188 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
189 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
190 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
191
192 ICmpInst::Predicate InvariantPredicate;
Philip Reamesdc417a92017-10-31 18:04:57 +0000193 const SCEV *InvariantLHS, *InvariantRHS;
Philip Reames7b861f02017-11-01 19:49:20 +0000194
195 auto *PN = dyn_cast<PHINode>(IVOperand);
196 if (!PN)
197 return false;
198 if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
Philip Reamesdc417a92017-10-31 18:04:57 +0000199 InvariantLHS, InvariantRHS))
200 return false;
201
202 // Rewrite the comparison to a loop invariant comparison if it can be done
203 // cheaply, where cheaply means "we don't need to emit any new
204 // instructions".
Philip Reamesdc417a92017-10-31 18:04:57 +0000205
Philip Reames7b861f02017-11-01 19:49:20 +0000206 SmallDenseMap<const SCEV*, Value*> CheapExpansions;
207 CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
208 CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
Fangrui Songf78650a2018-07-30 19:41:25 +0000209
Philip Reames7b861f02017-11-01 19:49:20 +0000210 // TODO: Support multiple entry loops? (We currently bail out of these in
211 // the IndVarSimplify pass)
212 if (auto *BB = L->getLoopPredecessor()) {
Philip Reames6260cf72017-12-01 20:57:19 +0000213 const int Idx = PN->getBasicBlockIndex(BB);
214 if (Idx >= 0) {
215 Value *Incoming = PN->getIncomingValue(Idx);
216 const SCEV *IncomingS = SE->getSCEV(Incoming);
217 CheapExpansions[IncomingS] = Incoming;
218 }
Philip Reames7b861f02017-11-01 19:49:20 +0000219 }
220 Value *NewLHS = CheapExpansions[InvariantLHS];
221 Value *NewRHS = CheapExpansions[InvariantRHS];
222
Philip Reames6260cf72017-12-01 20:57:19 +0000223 if (!NewLHS)
224 if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
225 NewLHS = ConstLHS->getValue();
226 if (!NewRHS)
227 if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
228 NewRHS = ConstRHS->getValue();
229
Philip Reames7b861f02017-11-01 19:49:20 +0000230 if (!NewLHS || !NewRHS)
231 // We could not find an existing value to replace either LHS or RHS.
232 // Generating new instructions has subtler tradeoffs, so avoid doing that
233 // for now.
234 return false;
235
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000236 LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000237 ICmp->setPredicate(InvariantPredicate);
238 ICmp->setOperand(0, NewLHS);
239 ICmp->setOperand(1, NewRHS);
240 return true;
Philip Reamesdc417a92017-10-31 18:04:57 +0000241}
242
Sanjay Patel7777b502014-11-12 18:07:42 +0000243/// SimplifyIVUsers helper for eliminating useless
Andrew Trick3ec331e2011-08-10 03:46:27 +0000244/// comparisons against an induction variable.
245void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
246 unsigned IVOperIdx = 0;
247 ICmpInst::Predicate Pred = ICmp->getPredicate();
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000248 ICmpInst::Predicate OriginalPred = Pred;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000249 if (IVOperand != ICmp->getOperand(0)) {
250 // Swapped
251 assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
252 IVOperIdx = 1;
253 Pred = ICmpInst::getSwappedPredicate(Pred);
254 }
255
Philip Reames29dd40b2017-10-26 22:02:16 +0000256 // Get the SCEVs for the ICmp operands (in the specific context of the
257 // current loop)
Andrew Trick3ec331e2011-08-10 03:46:27 +0000258 const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
Philip Reames29dd40b2017-10-26 22:02:16 +0000259 const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
260 const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000261
262 // If the condition is always true or always false, replace it with
263 // a constant value.
Sanjoy Das5dab2052015-07-27 21:42:49 +0000264 if (SE->isKnownPredicate(Pred, S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000265 ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000266 DeadInsts.emplace_back(ICmp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000267 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Sanjoy Das5dab2052015-07-27 21:42:49 +0000268 } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000269 ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000270 DeadInsts.emplace_back(ICmp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000271 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
Philip Reames7b861f02017-11-01 19:49:20 +0000272 } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
273 // fallthrough to end of function
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000274 } else if (ICmpInst::isSigned(OriginalPred) &&
275 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
276 // If we were unable to make anything above, all we can is to canonicalize
277 // the comparison hoping that it will open the doors for other
278 // optimizations. If we find out that we compare two non-negative values,
279 // we turn the instruction's predicate to its unsigned version. Note that
280 // we cannot rely on Pred here unless we check if we have swapped it.
281 assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000282 LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
283 << '\n');
Max Kazantsevb9edcbc2017-07-08 17:17:30 +0000284 ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
Sanjoy Das5dab2052015-07-27 21:42:49 +0000285 } else
Andrew Trick3ec331e2011-08-10 03:46:27 +0000286 return;
287
Andrew Trick3ec331e2011-08-10 03:46:27 +0000288 ++NumElimCmp;
289 Changed = true;
Andrew Trick3ec331e2011-08-10 03:46:27 +0000290}
291
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000292bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
293 // Get the SCEVs for the ICmp operands.
294 auto *N = SE->getSCEV(SDiv->getOperand(0));
295 auto *D = SE->getSCEV(SDiv->getOperand(1));
296
297 // Simplify unnecessary loops away.
298 const Loop *L = LI->getLoopFor(SDiv->getParent());
299 N = SE->getSCEVAtScope(N, L);
300 D = SE->getSCEVAtScope(D, L);
301
302 // Replace sdiv by udiv if both of the operands are non-negative
303 if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
304 auto *UDiv = BinaryOperator::Create(
305 BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
306 SDiv->getName() + ".udiv", SDiv);
307 UDiv->setIsExact(SDiv->isExact());
308 SDiv->replaceAllUsesWith(UDiv);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000309 LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000310 ++NumSimplifiedSDiv;
311 Changed = true;
312 DeadInsts.push_back(SDiv);
313 return true;
314 }
315
316 return false;
317}
318
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000319// i %s n -> i %u n if i >= 0 and n >= 0
320void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
321 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
322 auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
323 Rem->getName() + ".urem", Rem);
324 Rem->replaceAllUsesWith(URem);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000325 LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000326 ++NumSimplifiedSRem;
Hongbin Zhengbbe448a2017-09-25 18:10:36 +0000327 Changed = true;
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000328 DeadInsts.emplace_back(Rem);
329}
Andrew Trick3ec331e2011-08-10 03:46:27 +0000330
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000331// i % n --> i if i is in [0,n).
332void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
333 Rem->replaceAllUsesWith(Rem->getOperand(0));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000334 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000335 ++NumElimRem;
336 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000337 DeadInsts.emplace_back(Rem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000338}
339
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000340// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
341void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
342 auto *T = Rem->getType();
343 auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
344 ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
345 SelectInst *Sel =
346 SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
347 Rem->replaceAllUsesWith(Sel);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000348 LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000349 ++NumElimRem;
350 Changed = true;
351 DeadInsts.emplace_back(Rem);
352}
353
354/// SimplifyIVUsers helper for eliminating useless remainder operations
355/// operating on an induction variable or replacing srem by urem.
356void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
357 bool IsSigned) {
358 auto *NValue = Rem->getOperand(0);
359 auto *DValue = Rem->getOperand(1);
360 // We're only interested in the case where we know something about
361 // the numerator, unless it is a srem, because we want to replace srem by urem
362 // in general.
363 bool UsedAsNumerator = IVOperand == NValue;
364 if (!UsedAsNumerator && !IsSigned)
365 return;
366
367 const SCEV *N = SE->getSCEV(NValue);
368
369 // Simplify unnecessary loops away.
370 const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
371 N = SE->getSCEVAtScope(N, ICmpLoop);
372
373 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
374
375 // Do not proceed if the Numerator may be negative
376 if (!IsNumeratorNonNegative)
377 return;
378
379 const SCEV *D = SE->getSCEV(DValue);
380 D = SE->getSCEVAtScope(D, ICmpLoop);
381
382 if (UsedAsNumerator) {
383 auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
384 if (SE->isKnownPredicate(LT, N, D)) {
385 replaceRemWithNumerator(Rem);
386 return;
387 }
388
389 auto *T = Rem->getType();
390 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
391 if (SE->isKnownPredicate(LT, NLessOne, D)) {
392 replaceRemWithNumeratorOrZero(Rem);
393 return;
394 }
395 }
396
397 // Try to replace SRem with URem, if both N and D are known non-negative.
398 // Since we had already check N, we only need to check D now
399 if (!IsSigned || !SE->isKnownNonNegative(D))
400 return;
401
402 replaceSRemWithURem(Rem);
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000403}
404
Nikita Popov900578d2019-06-01 20:21:53 +0000405static bool willNotOverflow(ScalarEvolution *SE, Instruction::BinaryOps BinOp,
406 bool Signed, const SCEV *LHS, const SCEV *RHS) {
407 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
408 SCEV::NoWrapFlags, unsigned);
409 switch (BinOp) {
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000410 default:
Nikita Popov900578d2019-06-01 20:21:53 +0000411 llvm_unreachable("Unsupported binary op");
412 case Instruction::Add:
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000413 Operation = &ScalarEvolution::getAddExpr;
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000414 break;
Nikita Popov900578d2019-06-01 20:21:53 +0000415 case Instruction::Sub:
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000416 Operation = &ScalarEvolution::getMinusSCEV;
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000417 break;
Nikita Popov900578d2019-06-01 20:21:53 +0000418 case Instruction::Mul:
419 Operation = &ScalarEvolution::getMulExpr;
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000420 break;
421 }
422
Nikita Popov900578d2019-06-01 20:21:53 +0000423 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
424 Signed ? &ScalarEvolution::getSignExtendExpr
425 : &ScalarEvolution::getZeroExtendExpr;
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000426
Nikita Popov900578d2019-06-01 20:21:53 +0000427 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000428 auto *NarrowTy = cast<IntegerType>(LHS->getType());
429 auto *WideTy =
430 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
431
432 const SCEV *A =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000433 (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
434 WideTy, 0);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000435 const SCEV *B =
Max Kazantsev8d0322e2017-06-30 05:04:09 +0000436 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
437 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
Nikita Popov900578d2019-06-01 20:21:53 +0000438 return A == B;
439}
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000440
Nikita Popov900578d2019-06-01 20:21:53 +0000441bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
442 const SCEV *LHS = SE->getSCEV(WO->getLHS());
443 const SCEV *RHS = SE->getSCEV(WO->getRHS());
444 if (!willNotOverflow(SE, WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000445 return false;
446
447 // Proved no overflow, nuke the overflow check and, if possible, the overflow
448 // intrinsic as well.
449
450 BinaryOperator *NewResult = BinaryOperator::Create(
Nikita Popov900578d2019-06-01 20:21:53 +0000451 WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO);
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000452
Nikita Popov900578d2019-06-01 20:21:53 +0000453 if (WO->isSigned())
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000454 NewResult->setHasNoSignedWrap(true);
455 else
456 NewResult->setHasNoUnsignedWrap(true);
457
458 SmallVector<ExtractValueInst *, 4> ToDelete;
459
Nikita Popov900578d2019-06-01 20:21:53 +0000460 for (auto *U : WO->users()) {
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000461 if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
462 if (EVI->getIndices()[0] == 1)
Nikita Popov900578d2019-06-01 20:21:53 +0000463 EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000464 else {
465 assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
466 EVI->replaceAllUsesWith(NewResult);
467 }
468 ToDelete.push_back(EVI);
469 }
470 }
471
472 for (auto *EVI : ToDelete)
473 EVI->eraseFromParent();
474
Nikita Popov900578d2019-06-01 20:21:53 +0000475 if (WO->use_empty())
476 WO->eraseFromParent();
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000477
478 return true;
479}
480
Nikita Popov91455622019-06-15 08:48:52 +0000481bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
482 const SCEV *LHS = SE->getSCEV(SI->getLHS());
483 const SCEV *RHS = SE->getSCEV(SI->getRHS());
484 if (!willNotOverflow(SE, SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
485 return false;
486
487 BinaryOperator *BO = BinaryOperator::Create(
488 SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI);
489 if (SI->isSigned())
490 BO->setHasNoSignedWrap();
491 else
492 BO->setHasNoUnsignedWrap();
493
494 SI->replaceAllUsesWith(BO);
495 DeadInsts.emplace_back(SI);
496 Changed = true;
497 return true;
498}
499
Max Kazantsev37da4332018-06-19 04:48:34 +0000500bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
501 // It is always legal to replace
502 // icmp <pred> i32 trunc(iv), n
503 // with
504 // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
505 // Or with
506 // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
507 // Or with either of these if pred is an equality predicate.
508 //
509 // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
510 // every comparison which uses trunc, it means that we can replace each of
511 // them with comparison of iv against sext/zext(n). We no longer need trunc
512 // after that.
513 //
514 // TODO: Should we do this if we can widen *some* comparisons, but not all
515 // of them? Sometimes it is enough to enable other optimizations, but the
516 // trunc instruction will stay in the loop.
517 Value *IV = TI->getOperand(0);
518 Type *IVTy = IV->getType();
519 const SCEV *IVSCEV = SE->getSCEV(IV);
520 const SCEV *TISCEV = SE->getSCEV(TI);
521
522 // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
523 // get rid of trunc
524 bool DoesSExtCollapse = false;
525 bool DoesZExtCollapse = false;
526 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
527 DoesSExtCollapse = true;
528 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
529 DoesZExtCollapse = true;
530
531 // If neither sext nor zext does collapse, it is not profitable to do any
532 // transform. Bail.
533 if (!DoesSExtCollapse && !DoesZExtCollapse)
534 return false;
535
536 // Collect users of the trunc that look like comparisons against invariants.
537 // Bail if we find something different.
538 SmallVector<ICmpInst *, 4> ICmpUsers;
539 for (auto *U : TI->users()) {
Max Kazantsevf5ba3712018-06-28 08:20:03 +0000540 // We don't care about users in unreachable blocks.
541 if (isa<Instruction>(U) &&
542 !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
543 continue;
Philip Reames082cd302019-06-11 22:43:25 +0000544 ICmpInst *ICI = dyn_cast<ICmpInst>(U);
545 if (!ICI) return false;
546 assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
547 if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
548 !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
Max Kazantsev37da4332018-06-19 04:48:34 +0000549 return false;
Philip Reames082cd302019-06-11 22:43:25 +0000550 // If we cannot get rid of trunc, bail.
551 if (ICI->isSigned() && !DoesSExtCollapse)
552 return false;
553 if (ICI->isUnsigned() && !DoesZExtCollapse)
554 return false;
555 // For equality, either signed or unsigned works.
556 ICmpUsers.push_back(ICI);
Max Kazantsev37da4332018-06-19 04:48:34 +0000557 }
558
Max Kazantsev4d980512018-07-27 09:43:39 +0000559 auto CanUseZExt = [&](ICmpInst *ICI) {
560 // Unsigned comparison can be widened as unsigned.
561 if (ICI->isUnsigned())
562 return true;
563 // Is it profitable to do zext?
564 if (!DoesZExtCollapse)
565 return false;
566 // For equality, we can safely zext both parts.
567 if (ICI->isEquality())
568 return true;
569 // Otherwise we can only use zext when comparing two non-negative or two
570 // negative values. But in practice, we will never pass DoesZExtCollapse
571 // check for a negative value, because zext(trunc(x)) is non-negative. So
572 // it only make sense to check for non-negativity here.
573 const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
574 const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
575 return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
576 };
Max Kazantsev37da4332018-06-19 04:48:34 +0000577 // Replace all comparisons against trunc with comparisons against IV.
578 for (auto *ICI : ICmpUsers) {
Philip Reames082cd302019-06-11 22:43:25 +0000579 bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
580 auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
Max Kazantsev37da4332018-06-19 04:48:34 +0000581 Instruction *Ext = nullptr;
582 // For signed/unsigned predicate, replace the old comparison with comparison
583 // of immediate IV against sext/zext of the invariant argument. If we can
584 // use either sext or zext (i.e. we are dealing with equality predicate),
585 // then prefer zext as a more canonical form.
586 // TODO: If we see a signed comparison which can be turned into unsigned,
587 // we can do it here for canonicalization purposes.
Max Kazantsev4d980512018-07-27 09:43:39 +0000588 ICmpInst::Predicate Pred = ICI->getPredicate();
Philip Reames082cd302019-06-11 22:43:25 +0000589 if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
Max Kazantsev4d980512018-07-27 09:43:39 +0000590 if (CanUseZExt(ICI)) {
Max Kazantsev37da4332018-06-19 04:48:34 +0000591 assert(DoesZExtCollapse && "Unprofitable zext?");
592 Ext = new ZExtInst(Op1, IVTy, "zext", ICI);
Max Kazantsev4d980512018-07-27 09:43:39 +0000593 Pred = ICmpInst::getUnsignedPredicate(Pred);
Max Kazantsev37da4332018-06-19 04:48:34 +0000594 } else {
595 assert(DoesSExtCollapse && "Unprofitable sext?");
596 Ext = new SExtInst(Op1, IVTy, "sext", ICI);
Max Kazantsev4d980512018-07-27 09:43:39 +0000597 assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
Max Kazantsev37da4332018-06-19 04:48:34 +0000598 }
599 bool Changed;
600 L->makeLoopInvariant(Ext, Changed);
601 (void)Changed;
Max Kazantsev4d980512018-07-27 09:43:39 +0000602 ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext);
Max Kazantsev37da4332018-06-19 04:48:34 +0000603 ICI->replaceAllUsesWith(NewICI);
604 DeadInsts.emplace_back(ICI);
605 }
606
607 // Trunc no longer needed.
608 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
609 DeadInsts.emplace_back(TI);
610 return true;
611}
612
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000613/// Eliminate an operation that consumes a simple IV and has no observable
614/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
615/// but UseInst may not be.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000616bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
617 Instruction *IVOperand) {
618 if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
619 eliminateIVComparison(ICmp, IVOperand);
620 return true;
621 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000622 if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
623 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
624 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
Hongbin Zhengf0093e42017-09-25 17:39:40 +0000625 simplifyIVRemainder(Bin, IVOperand, IsSRem);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000626 return true;
627 }
Hongbin Zhengbfd7c382017-03-30 21:56:56 +0000628
629 if (Bin->getOpcode() == Instruction::SDiv)
630 return eliminateSDiv(Bin);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000631 }
632
Nikita Popov900578d2019-06-01 20:21:53 +0000633 if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
634 if (eliminateOverflowIntrinsic(WO))
Sanjoy Dasae09b3c2016-05-29 00:36:25 +0000635 return true;
636
Nikita Popov91455622019-06-15 08:48:52 +0000637 if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
638 if (eliminateSaturatingIntrinsic(SI))
639 return true;
640
Max Kazantsev37da4332018-06-19 04:48:34 +0000641 if (auto *TI = dyn_cast<TruncInst>(UseInst))
642 if (eliminateTrunc(TI))
643 return true;
644
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000645 if (eliminateIdentitySCEV(UseInst, IVOperand))
646 return true;
647
648 return false;
649}
650
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000651static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
652 if (auto *BB = L->getLoopPreheader())
653 return BB->getTerminator();
654
655 return Hint;
656}
657
658/// Replace the UseInst with a constant if possible.
659bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000660 if (!SE->isSCEVable(I->getType()))
661 return false;
662
663 // Get the symbolic expression for this instruction.
664 const SCEV *S = SE->getSCEV(I);
665
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000666 if (!SE->isLoopInvariant(S, L))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000667 return false;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000668
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000669 // Do not generate something ridiculous even if S is loop invariant.
670 if (Rewriter.isHighCostExpansion(S, L, I))
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000671 return false;
672
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000673 auto *IP = GetLoopInvariantInsertPosition(L, I);
674 auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
675
676 I->replaceAllUsesWith(Invariant);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000677 LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
678 << " with loop invariant: " << *S << '\n');
Hongbin Zhengc8abdf52017-09-29 16:32:12 +0000679 ++NumFoldedUser;
680 Changed = true;
681 DeadInsts.emplace_back(I);
682 return true;
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000683}
684
Sanjoy Das088bb0e2015-10-06 21:44:39 +0000685/// Eliminate any operation that SCEV can prove is an identity function.
686bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
687 Instruction *IVOperand) {
Andrew Trick3ec331e2011-08-10 03:46:27 +0000688 if (!SE->isSCEVable(UseInst->getType()) ||
689 (UseInst->getType() != IVOperand->getType()) ||
690 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
691 return false;
692
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000693 // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
694 // dominator tree, even if X is an operand to Y. For instance, in
695 //
696 // %iv = phi i32 {0,+,1}
697 // br %cond, label %left, label %merge
698 //
699 // left:
700 // %X = add i32 %iv, 0
701 // br label %merge
702 //
703 // merge:
704 // %M = phi (%X, %iv)
705 //
706 // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
707 // %M.replaceAllUsesWith(%X) would be incorrect.
708
709 if (isa<PHINode>(UseInst))
710 // If UseInst is not a PHI node then we know that IVOperand dominates
711 // UseInst directly from the legality of SSA.
712 if (!DT || !DT->dominates(IVOperand, UseInst))
713 return false;
714
Sanjoy Das0015e5a2015-10-07 17:38:31 +0000715 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
716 return false;
717
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000718 LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
Andrew Trick3ec331e2011-08-10 03:46:27 +0000719
720 UseInst->replaceAllUsesWith(IVOperand);
721 ++NumElimIdentity;
722 Changed = true;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000723 DeadInsts.emplace_back(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000724 return true;
725}
726
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000727/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
728/// unsigned-overflow. Returns true if anything changed, false otherwise.
729bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
730 Value *IVOperand) {
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000731 // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000732 if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
733 return false;
734
Nikita Popov900578d2019-06-01 20:21:53 +0000735 if (BO->getOpcode() != Instruction::Add &&
736 BO->getOpcode() != Instruction::Sub &&
737 BO->getOpcode() != Instruction::Mul)
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000738 return false;
739
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000740 const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
741 const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
Sanjoy Dasa5397c02015-03-04 22:24:23 +0000742 bool Changed = false;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000743
Nikita Popov900578d2019-06-01 20:21:53 +0000744 if (!BO->hasNoUnsignedWrap() &&
745 willNotOverflow(SE, BO->getOpcode(), /* Signed */ false, LHS, RHS)) {
746 BO->setHasNoUnsignedWrap();
747 SE->forgetValue(BO);
748 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000749 }
750
Nikita Popov900578d2019-06-01 20:21:53 +0000751 if (!BO->hasNoSignedWrap() &&
752 willNotOverflow(SE, BO->getOpcode(), /* Signed */ true, LHS, RHS)) {
753 BO->setHasNoSignedWrap();
754 SE->forgetValue(BO);
755 Changed = true;
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000756 }
757
758 return Changed;
759}
760
David Greenb26a0a42017-07-05 13:25:58 +0000761/// Annotate the Shr in (X << IVOperand) >> C as exact using the
762/// information from the IV's range. Returns true if anything changed, false
763/// otherwise.
764bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
765 Value *IVOperand) {
766 using namespace llvm::PatternMatch;
767
768 if (BO->getOpcode() == Instruction::Shl) {
769 bool Changed = false;
770 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
771 for (auto *U : BO->users()) {
772 const APInt *C;
773 if (match(U,
774 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
775 match(U,
776 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
777 BinaryOperator *Shr = cast<BinaryOperator>(U);
778 if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
779 Shr->setIsExact(true);
780 Changed = true;
781 }
782 }
783 }
784 return Changed;
785 }
786
787 return false;
788}
789
Sanjay Patel7777b502014-11-12 18:07:42 +0000790/// Add all uses of Def to the current IV's worklist.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000791static void pushIVUsers(
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000792 Instruction *Def, Loop *L,
Andrew Trick3ec331e2011-08-10 03:46:27 +0000793 SmallPtrSet<Instruction*,16> &Simplified,
794 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
795
Chandler Carruthcdf47882014-03-09 03:16:01 +0000796 for (User *U : Def->users()) {
797 Instruction *UI = cast<Instruction>(U);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000798
799 // Avoid infinite or exponential worklist processing.
800 // Also ensure unique worklist users.
801 // If Def is a LoopPhi, it may not be in the Simplified set, so check for
802 // self edges first.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000803 if (UI == Def)
804 continue;
805
806 // Only change the current Loop, do not change the other parts (e.g. other
807 // Loops).
808 if (!L->contains(UI))
809 continue;
810
811 // Do not push the same instruction more than once.
812 if (!Simplified.insert(UI).second)
813 continue;
814
815 SimpleIVUsers.push_back(std::make_pair(UI, Def));
Andrew Trick3ec331e2011-08-10 03:46:27 +0000816 }
817}
818
Sanjay Patel7777b502014-11-12 18:07:42 +0000819/// Return true if this instruction generates a simple SCEV
Andrew Trick3ec331e2011-08-10 03:46:27 +0000820/// expression in terms of that IV.
821///
Andrew Trick6dbb0602011-08-10 18:07:05 +0000822/// This is similar to IVUsers' isInteresting() but processes each instruction
Andrew Trick3ec331e2011-08-10 03:46:27 +0000823/// non-recursively when the operand is already known to be a simpleIVUser.
824///
825static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
826 if (!SE->isSCEVable(I->getType()))
827 return false;
828
829 // Get the symbolic expression for this instruction.
830 const SCEV *S = SE->getSCEV(I);
831
832 // Only consider affine recurrences.
833 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
834 if (AR && AR->getLoop() == L)
835 return true;
836
837 return false;
838}
839
Sanjay Patel7777b502014-11-12 18:07:42 +0000840/// Iteratively perform simplification on a worklist of users
Andrew Trick3ec331e2011-08-10 03:46:27 +0000841/// of the specified induction variable. Each successive simplification may push
842/// more users which may themselves be candidates for simplification.
843///
844/// This algorithm does not require IVUsers analysis. Instead, it simplifies
845/// instructions in-place during analysis. Rather than rewriting induction
846/// variables bottom-up from their users, it transforms a chain of IVUsers
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000847/// top-down, updating the IR only when it encounters a clear optimization
848/// opportunity.
Andrew Trick3ec331e2011-08-10 03:46:27 +0000849///
850/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
851///
852void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
Andrew Trick7251e412011-09-19 17:54:39 +0000853 if (!SE->isSCEVable(CurrIV->getType()))
854 return;
855
Andrew Trick3ec331e2011-08-10 03:46:27 +0000856 // Instructions processed by SimplifyIndvar for CurrIV.
857 SmallPtrSet<Instruction*,16> Simplified;
858
859 // Use-def pairs if IV users waiting to be processed for CurrIV.
860 SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
861
862 // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
863 // called multiple times for the same LoopPhi. This is the proper thing to
864 // do for loop header phis that use each other.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000865 pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000866
867 while (!SimpleIVUsers.empty()) {
868 std::pair<Instruction*, Instruction*> UseOper =
869 SimpleIVUsers.pop_back_val();
Andrew Trick0ba77a02013-12-23 23:31:49 +0000870 Instruction *UseInst = UseOper.first;
871
Max Kazantsev0ed79622018-06-13 02:25:32 +0000872 // If a user of the IndVar is trivially dead, we prefer just to mark it dead
873 // rather than try to do some complex analysis or transformation (such as
874 // widening) basing on it.
875 // TODO: Propagate TLI and pass it here to handle more cases.
876 if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
877 DeadInsts.emplace_back(UseInst);
878 continue;
879 }
880
Andrew Trick3ec331e2011-08-10 03:46:27 +0000881 // Bypass back edges to avoid extra work.
Andrew Trick0ba77a02013-12-23 23:31:49 +0000882 if (UseInst == CurrIV) continue;
883
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000884 // Try to replace UseInst with a loop invariant before any other
885 // simplifications.
886 if (replaceIVUserWithLoopInvariant(UseInst))
Hongbin Zhengd1b7b2e2017-09-27 03:11:46 +0000887 continue;
888
Andrew Trick74664d52011-08-10 04:01:31 +0000889 Instruction *IVOperand = UseOper.second;
890 for (unsigned N = 0; IVOperand; ++N) {
891 assert(N <= Simplified.size() && "runaway iteration");
Andrew Trick3ec331e2011-08-10 03:46:27 +0000892
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000893 Value *NewOper = foldIVUser(UseInst, IVOperand);
Andrew Trick74664d52011-08-10 04:01:31 +0000894 if (!NewOper)
895 break; // done folding
896 IVOperand = dyn_cast<Instruction>(NewOper);
897 }
898 if (!IVOperand)
899 continue;
900
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000901 if (eliminateIVUser(UseInst, IVOperand)) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000902 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000903 continue;
904 }
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000905
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000906 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
David Greenb26a0a42017-07-05 13:25:58 +0000907 if ((isa<OverflowingBinaryOperator>(BO) &&
908 strengthenOverflowingOperation(BO, IVOperand)) ||
909 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000910 // re-queue uses of the now modified binary operator and fall
911 // through to the checks that remain.
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000912 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
Sanjoy Das7c0ce262015-01-06 19:02:56 +0000913 }
914 }
915
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000916 CastInst *Cast = dyn_cast<CastInst>(UseInst);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000917 if (V && Cast) {
918 V->visitCast(Cast);
919 continue;
920 }
Max Kazantsevb4b2cce2018-06-07 08:47:19 +0000921 if (isSimpleIVUser(UseInst, L, SE)) {
922 pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000923 }
924 }
925}
926
927namespace llvm {
928
David Blaikiea379b1812011-12-20 02:50:00 +0000929void IVVisitor::anchor() { }
930
Sanjay Patel7777b502014-11-12 18:07:42 +0000931/// Simplify instructions that use this induction variable
Andrew Trick3ec331e2011-08-10 03:46:27 +0000932/// by using ScalarEvolution to analyze the IV's recurrence.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000933bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000934 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000935 SCEVExpander &Rewriter, IVVisitor *V) {
936 SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter,
937 Dead);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000938 SIV.simplifyUsers(CurrIV, V);
939 return SIV.hasChanged();
940}
941
Sanjay Patel7777b502014-11-12 18:07:42 +0000942/// Simplify users of induction variables within this
Andrew Trick3ec331e2011-08-10 03:46:27 +0000943/// loop. This does not actually change or add IVs.
Sanjoy Das5c8bead2015-10-06 21:44:49 +0000944bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000945 LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000946 SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
947#ifndef NDEBUG
948 Rewriter.setDebugType(DEBUG_TYPE);
949#endif
Andrew Trick3ec331e2011-08-10 03:46:27 +0000950 bool Changed = false;
951 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Hongbin Zhengd36f20302017-10-12 02:54:11 +0000952 Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter);
Andrew Trick3ec331e2011-08-10 03:46:27 +0000953 }
954 return Changed;
955}
956
Andrew Trick3ec331e2011-08-10 03:46:27 +0000957} // namespace llvm