1 //===-- 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 
16 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "indvars"
35 
36 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
37 STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
38 STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
39 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
40 STATISTIC(
41     NumSimplifiedSDiv,
42     "Number of IV signed division operations converted to unsigned division");
43 STATISTIC(
44     NumSimplifiedSRem,
45     "Number of IV signed remainder operations converted to unsigned remainder");
46 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
47 
48 namespace {
49   /// This is a utility for simplifying induction variables
50   /// based on ScalarEvolution. It is the primary instrument of the
51   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
52   /// other loop passes that preserve SCEV.
53   class SimplifyIndvar {
54     Loop             *L;
55     LoopInfo         *LI;
56     ScalarEvolution  *SE;
57     DominatorTree    *DT;
58 
59     SmallVectorImpl<WeakTrackingVH> &DeadInsts;
60 
61     bool Changed;
62 
63   public:
64     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
65                    LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead)
66         : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
67       assert(LI && "IV simplification requires LoopInfo");
68     }
69 
70     bool hasChanged() const { return Changed; }
71 
72     /// Iteratively perform simplification on a worklist of users of the
73     /// specified induction variable. This is the top-level driver that applies
74     /// all simplifications to users of an IV.
75     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
76 
77     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
78 
79     bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
80     bool foldConstantSCEV(Instruction *UseInst);
81 
82     bool eliminateOverflowIntrinsic(CallInst *CI);
83     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
84     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
85     void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
86                              bool IsSigned);
87     void replaceRemWithNumerator(BinaryOperator *Rem);
88     void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
89     void replaceSRemWithURem(BinaryOperator *Rem);
90     bool eliminateSDiv(BinaryOperator *SDiv);
91     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
92     bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
93   };
94 }
95 
96 /// Fold an IV operand into its use.  This removes increments of an
97 /// aligned IV when used by a instruction that ignores the low bits.
98 ///
99 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
100 ///
101 /// Return the operand of IVOperand for this induction variable if IVOperand can
102 /// be folded (in case more folding opportunities have been exposed).
103 /// Otherwise return null.
104 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
105   Value *IVSrc = nullptr;
106   unsigned OperIdx = 0;
107   const SCEV *FoldedExpr = nullptr;
108   switch (UseInst->getOpcode()) {
109   default:
110     return nullptr;
111   case Instruction::UDiv:
112   case Instruction::LShr:
113     // We're only interested in the case where we know something about
114     // the numerator and have a constant denominator.
115     if (IVOperand != UseInst->getOperand(OperIdx) ||
116         !isa<ConstantInt>(UseInst->getOperand(1)))
117       return nullptr;
118 
119     // Attempt to fold a binary operator with constant operand.
120     // e.g. ((I + 1) >> 2) => I >> 2
121     if (!isa<BinaryOperator>(IVOperand)
122         || !isa<ConstantInt>(IVOperand->getOperand(1)))
123       return nullptr;
124 
125     IVSrc = IVOperand->getOperand(0);
126     // IVSrc must be the (SCEVable) IV, since the other operand is const.
127     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
128 
129     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
130     if (UseInst->getOpcode() == Instruction::LShr) {
131       // Get a constant for the divisor. See createSCEV.
132       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
133       if (D->getValue().uge(BitWidth))
134         return nullptr;
135 
136       D = ConstantInt::get(UseInst->getContext(),
137                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
138     }
139     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
140   }
141   // We have something that might fold it's operand. Compare SCEVs.
142   if (!SE->isSCEVable(UseInst->getType()))
143     return nullptr;
144 
145   // Bypass the operand if SCEV can prove it has no effect.
146   if (SE->getSCEV(UseInst) != FoldedExpr)
147     return nullptr;
148 
149   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
150         << " -> " << *UseInst << '\n');
151 
152   UseInst->setOperand(OperIdx, IVSrc);
153   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
154 
155   ++NumElimOperand;
156   Changed = true;
157   if (IVOperand->use_empty())
158     DeadInsts.emplace_back(IVOperand);
159   return IVSrc;
160 }
161 
162 /// SimplifyIVUsers helper for eliminating useless
163 /// comparisons against an induction variable.
164 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
165   unsigned IVOperIdx = 0;
166   ICmpInst::Predicate Pred = ICmp->getPredicate();
167   ICmpInst::Predicate OriginalPred = Pred;
168   if (IVOperand != ICmp->getOperand(0)) {
169     // Swapped
170     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
171     IVOperIdx = 1;
172     Pred = ICmpInst::getSwappedPredicate(Pred);
173   }
174 
175   // Get the SCEVs for the ICmp operands.
176   const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
177   const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
178 
179   // Simplify unnecessary loops away.
180   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
181   S = SE->getSCEVAtScope(S, ICmpLoop);
182   X = SE->getSCEVAtScope(X, ICmpLoop);
183 
184   ICmpInst::Predicate InvariantPredicate;
185   const SCEV *InvariantLHS, *InvariantRHS;
186 
187   // If the condition is always true or always false, replace it with
188   // a constant value.
189   if (SE->isKnownPredicate(Pred, S, X)) {
190     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
191     DeadInsts.emplace_back(ICmp);
192     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
193   } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
194     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
195     DeadInsts.emplace_back(ICmp);
196     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
197   } else if (isa<PHINode>(IVOperand) &&
198              SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
199                                           InvariantLHS, InvariantRHS)) {
200 
201     // Rewrite the comparison to a loop invariant comparison if it can be done
202     // cheaply, where cheaply means "we don't need to emit any new
203     // instructions".
204 
205     Value *NewLHS = nullptr, *NewRHS = nullptr;
206 
207     if (S == InvariantLHS || X == InvariantLHS)
208       NewLHS =
209           ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
210 
211     if (S == InvariantRHS || X == InvariantRHS)
212       NewRHS =
213           ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
214 
215     auto *PN = cast<PHINode>(IVOperand);
216     for (unsigned i = 0, e = PN->getNumIncomingValues();
217          i != e && (!NewLHS || !NewRHS);
218          ++i) {
219 
220       // If this is a value incoming from the backedge, then it cannot be a loop
221       // invariant value (since we know that IVOperand is an induction variable).
222       if (L->contains(PN->getIncomingBlock(i)))
223         continue;
224 
225       // NB! This following assert does not fundamentally have to be true, but
226       // it is true today given how SCEV analyzes induction variables.
227       // Specifically, today SCEV will *not* recognize %iv as an induction
228       // variable in the following case:
229       //
230       // define void @f(i32 %k) {
231       // entry:
232       //   br i1 undef, label %r, label %l
233       //
234       // l:
235       //   %k.inc.l = add i32 %k, 1
236       //   br label %loop
237       //
238       // r:
239       //   %k.inc.r = add i32 %k, 1
240       //   br label %loop
241       //
242       // loop:
243       //   %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
244       //   %iv.inc = add i32 %iv, 1
245       //   br label %loop
246       // }
247       //
248       // but if it starts to, at some point, then the assertion below will have
249       // to be changed to a runtime check.
250 
251       Value *Incoming = PN->getIncomingValue(i);
252 
253 #ifndef NDEBUG
254       if (auto *I = dyn_cast<Instruction>(Incoming))
255         assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
256 #endif
257 
258       const SCEV *IncomingS = SE->getSCEV(Incoming);
259 
260       if (!NewLHS && IncomingS == InvariantLHS)
261         NewLHS = Incoming;
262       if (!NewRHS && IncomingS == InvariantRHS)
263         NewRHS = Incoming;
264     }
265 
266     if (!NewLHS || !NewRHS)
267       // We could not find an existing value to replace either LHS or RHS.
268       // Generating new instructions has subtler tradeoffs, so avoid doing that
269       // for now.
270       return;
271 
272     DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
273     ICmp->setPredicate(InvariantPredicate);
274     ICmp->setOperand(0, NewLHS);
275     ICmp->setOperand(1, NewRHS);
276   } else if (ICmpInst::isSigned(OriginalPred) &&
277              SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
278     // If we were unable to make anything above, all we can is to canonicalize
279     // the comparison hoping that it will open the doors for other
280     // optimizations. If we find out that we compare two non-negative values,
281     // we turn the instruction's predicate to its unsigned version. Note that
282     // we cannot rely on Pred here unless we check if we have swapped it.
283     assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
284     DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
285     ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
286   } else
287     return;
288 
289   ++NumElimCmp;
290   Changed = true;
291 }
292 
293 bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
294   // Get the SCEVs for the ICmp operands.
295   auto *N = SE->getSCEV(SDiv->getOperand(0));
296   auto *D = SE->getSCEV(SDiv->getOperand(1));
297 
298   // Simplify unnecessary loops away.
299   const Loop *L = LI->getLoopFor(SDiv->getParent());
300   N = SE->getSCEVAtScope(N, L);
301   D = SE->getSCEVAtScope(D, L);
302 
303   // Replace sdiv by udiv if both of the operands are non-negative
304   if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
305     auto *UDiv = BinaryOperator::Create(
306         BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
307         SDiv->getName() + ".udiv", SDiv);
308     UDiv->setIsExact(SDiv->isExact());
309     SDiv->replaceAllUsesWith(UDiv);
310     DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
311     ++NumSimplifiedSDiv;
312     Changed = true;
313     DeadInsts.push_back(SDiv);
314     return true;
315   }
316 
317   return false;
318 }
319 
320 // i %s n -> i %u n if i >= 0 and n >= 0
321 void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
322   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
323   auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
324                                       Rem->getName() + ".urem", Rem);
325   Rem->replaceAllUsesWith(URem);
326   DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
327   ++NumSimplifiedSRem;
328   Changed = true;
329   DeadInsts.emplace_back(Rem);
330 }
331 
332 // i % n  -->  i  if i is in [0,n).
333 void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
334   Rem->replaceAllUsesWith(Rem->getOperand(0));
335   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
336   ++NumElimRem;
337   Changed = true;
338   DeadInsts.emplace_back(Rem);
339 }
340 
341 // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
342 void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
343   auto *T = Rem->getType();
344   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
345   ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
346   SelectInst *Sel =
347       SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
348   Rem->replaceAllUsesWith(Sel);
349   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
350   ++NumElimRem;
351   Changed = true;
352   DeadInsts.emplace_back(Rem);
353 }
354 
355 /// SimplifyIVUsers helper for eliminating useless remainder operations
356 /// operating on an induction variable or replacing srem by urem.
357 void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
358                                          bool IsSigned) {
359   auto *NValue = Rem->getOperand(0);
360   auto *DValue = Rem->getOperand(1);
361   // We're only interested in the case where we know something about
362   // the numerator, unless it is a srem, because we want to replace srem by urem
363   // in general.
364   bool UsedAsNumerator = IVOperand == NValue;
365   if (!UsedAsNumerator && !IsSigned)
366     return;
367 
368   const SCEV *N = SE->getSCEV(NValue);
369 
370   // Simplify unnecessary loops away.
371   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
372   N = SE->getSCEVAtScope(N, ICmpLoop);
373 
374   bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
375 
376   // Do not proceed if the Numerator may be negative
377   if (!IsNumeratorNonNegative)
378     return;
379 
380   const SCEV *D = SE->getSCEV(DValue);
381   D = SE->getSCEVAtScope(D, ICmpLoop);
382 
383   if (UsedAsNumerator) {
384     auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
385     if (SE->isKnownPredicate(LT, N, D)) {
386       replaceRemWithNumerator(Rem);
387       return;
388     }
389 
390     auto *T = Rem->getType();
391     const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
392     if (SE->isKnownPredicate(LT, NLessOne, D)) {
393       replaceRemWithNumeratorOrZero(Rem);
394       return;
395     }
396   }
397 
398   // Try to replace SRem with URem, if both N and D are known non-negative.
399   // Since we had already check N, we only need to check D now
400   if (!IsSigned || !SE->isKnownNonNegative(D))
401     return;
402 
403   replaceSRemWithURem(Rem);
404 }
405 
406 bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
407   auto *F = CI->getCalledFunction();
408   if (!F)
409     return false;
410 
411   typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
412       const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
413   typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
414       const SCEV *, Type *, unsigned);
415 
416   OperationFunctionTy Operation;
417   ExtensionFunctionTy Extension;
418 
419   Instruction::BinaryOps RawOp;
420 
421   // We always have exactly one of nsw or nuw.  If NoSignedOverflow is false, we
422   // have nuw.
423   bool NoSignedOverflow;
424 
425   switch (F->getIntrinsicID()) {
426   default:
427     return false;
428 
429   case Intrinsic::sadd_with_overflow:
430     Operation = &ScalarEvolution::getAddExpr;
431     Extension = &ScalarEvolution::getSignExtendExpr;
432     RawOp = Instruction::Add;
433     NoSignedOverflow = true;
434     break;
435 
436   case Intrinsic::uadd_with_overflow:
437     Operation = &ScalarEvolution::getAddExpr;
438     Extension = &ScalarEvolution::getZeroExtendExpr;
439     RawOp = Instruction::Add;
440     NoSignedOverflow = false;
441     break;
442 
443   case Intrinsic::ssub_with_overflow:
444     Operation = &ScalarEvolution::getMinusSCEV;
445     Extension = &ScalarEvolution::getSignExtendExpr;
446     RawOp = Instruction::Sub;
447     NoSignedOverflow = true;
448     break;
449 
450   case Intrinsic::usub_with_overflow:
451     Operation = &ScalarEvolution::getMinusSCEV;
452     Extension = &ScalarEvolution::getZeroExtendExpr;
453     RawOp = Instruction::Sub;
454     NoSignedOverflow = false;
455     break;
456   }
457 
458   const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
459   const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
460 
461   auto *NarrowTy = cast<IntegerType>(LHS->getType());
462   auto *WideTy =
463     IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
464 
465   const SCEV *A =
466       (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
467                        WideTy, 0);
468   const SCEV *B =
469       (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
470                        (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
471 
472   if (A != B)
473     return false;
474 
475   // Proved no overflow, nuke the overflow check and, if possible, the overflow
476   // intrinsic as well.
477 
478   BinaryOperator *NewResult = BinaryOperator::Create(
479       RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
480 
481   if (NoSignedOverflow)
482     NewResult->setHasNoSignedWrap(true);
483   else
484     NewResult->setHasNoUnsignedWrap(true);
485 
486   SmallVector<ExtractValueInst *, 4> ToDelete;
487 
488   for (auto *U : CI->users()) {
489     if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
490       if (EVI->getIndices()[0] == 1)
491         EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
492       else {
493         assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
494         EVI->replaceAllUsesWith(NewResult);
495       }
496       ToDelete.push_back(EVI);
497     }
498   }
499 
500   for (auto *EVI : ToDelete)
501     EVI->eraseFromParent();
502 
503   if (CI->use_empty())
504     CI->eraseFromParent();
505 
506   return true;
507 }
508 
509 /// Eliminate an operation that consumes a simple IV and has no observable
510 /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
511 /// but UseInst may not be.
512 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
513                                      Instruction *IVOperand) {
514   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
515     eliminateIVComparison(ICmp, IVOperand);
516     return true;
517   }
518   if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
519     bool IsSRem = Bin->getOpcode() == Instruction::SRem;
520     if (IsSRem || Bin->getOpcode() == Instruction::URem) {
521       simplifyIVRemainder(Bin, IVOperand, IsSRem);
522       return true;
523     }
524 
525     if (Bin->getOpcode() == Instruction::SDiv)
526       return eliminateSDiv(Bin);
527   }
528 
529   if (auto *CI = dyn_cast<CallInst>(UseInst))
530     if (eliminateOverflowIntrinsic(CI))
531       return true;
532 
533   if (eliminateIdentitySCEV(UseInst, IVOperand))
534     return true;
535 
536   return false;
537 }
538 
539 /// Replace the UseInst with a constant if possible
540 bool SimplifyIndvar::foldConstantSCEV(Instruction *I) {
541   if (!SE->isSCEVable(I->getType()))
542     return false;
543 
544   // Get the symbolic expression for this instruction.
545   const SCEV *S = SE->getSCEV(I);
546 
547   const Loop *L = LI->getLoopFor(I->getParent());
548   S = SE->getSCEVAtScope(S, L);
549   auto *C = dyn_cast<SCEVConstant>(S);
550 
551   if (!C)
552     return false;
553 
554   Constant *V = C->getValue();
555   // The SCEV will have a different type than the instruction if the instruction
556   // has a pointer type. Skip the replacement
557   // TODO: Replace ConstantInt Zero by ConstantPointerNull
558   if (V->getType() != I->getType())
559     return false;
560 
561   I->replaceAllUsesWith(V);
562   DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I << " with constant: " << *C
563                << '\n');
564   ++NumFoldedUser;
565   Changed = true;
566   DeadInsts.emplace_back(I);
567   return true;
568 }
569 
570 /// Eliminate any operation that SCEV can prove is an identity function.
571 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
572                                            Instruction *IVOperand) {
573   if (!SE->isSCEVable(UseInst->getType()) ||
574       (UseInst->getType() != IVOperand->getType()) ||
575       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
576     return false;
577 
578   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
579   // dominator tree, even if X is an operand to Y.  For instance, in
580   //
581   //     %iv = phi i32 {0,+,1}
582   //     br %cond, label %left, label %merge
583   //
584   //   left:
585   //     %X = add i32 %iv, 0
586   //     br label %merge
587   //
588   //   merge:
589   //     %M = phi (%X, %iv)
590   //
591   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
592   // %M.replaceAllUsesWith(%X) would be incorrect.
593 
594   if (isa<PHINode>(UseInst))
595     // If UseInst is not a PHI node then we know that IVOperand dominates
596     // UseInst directly from the legality of SSA.
597     if (!DT || !DT->dominates(IVOperand, UseInst))
598       return false;
599 
600   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
601     return false;
602 
603   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
604 
605   UseInst->replaceAllUsesWith(IVOperand);
606   ++NumElimIdentity;
607   Changed = true;
608   DeadInsts.emplace_back(UseInst);
609   return true;
610 }
611 
612 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
613 /// unsigned-overflow.  Returns true if anything changed, false otherwise.
614 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
615                                                     Value *IVOperand) {
616 
617   // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
618   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
619     return false;
620 
621   const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
622                                                SCEV::NoWrapFlags, unsigned);
623   switch (BO->getOpcode()) {
624   default:
625     return false;
626 
627   case Instruction::Add:
628     GetExprForBO = &ScalarEvolution::getAddExpr;
629     break;
630 
631   case Instruction::Sub:
632     GetExprForBO = &ScalarEvolution::getMinusSCEV;
633     break;
634 
635   case Instruction::Mul:
636     GetExprForBO = &ScalarEvolution::getMulExpr;
637     break;
638   }
639 
640   unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
641   Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
642   const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
643   const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
644 
645   bool Changed = false;
646 
647   if (!BO->hasNoUnsignedWrap()) {
648     const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
649     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
650       SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
651       SCEV::FlagAnyWrap, 0u);
652     if (ExtendAfterOp == OpAfterExtend) {
653       BO->setHasNoUnsignedWrap();
654       SE->forgetValue(BO);
655       Changed = true;
656     }
657   }
658 
659   if (!BO->hasNoSignedWrap()) {
660     const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
661     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
662       SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
663       SCEV::FlagAnyWrap, 0u);
664     if (ExtendAfterOp == OpAfterExtend) {
665       BO->setHasNoSignedWrap();
666       SE->forgetValue(BO);
667       Changed = true;
668     }
669   }
670 
671   return Changed;
672 }
673 
674 /// Annotate the Shr in (X << IVOperand) >> C as exact using the
675 /// information from the IV's range. Returns true if anything changed, false
676 /// otherwise.
677 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
678                                           Value *IVOperand) {
679   using namespace llvm::PatternMatch;
680 
681   if (BO->getOpcode() == Instruction::Shl) {
682     bool Changed = false;
683     ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
684     for (auto *U : BO->users()) {
685       const APInt *C;
686       if (match(U,
687                 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
688           match(U,
689                 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
690         BinaryOperator *Shr = cast<BinaryOperator>(U);
691         if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
692           Shr->setIsExact(true);
693           Changed = true;
694         }
695       }
696     }
697     return Changed;
698   }
699 
700   return false;
701 }
702 
703 /// Add all uses of Def to the current IV's worklist.
704 static void pushIVUsers(
705   Instruction *Def,
706   SmallPtrSet<Instruction*,16> &Simplified,
707   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
708 
709   for (User *U : Def->users()) {
710     Instruction *UI = cast<Instruction>(U);
711 
712     // Avoid infinite or exponential worklist processing.
713     // Also ensure unique worklist users.
714     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
715     // self edges first.
716     if (UI != Def && Simplified.insert(UI).second)
717       SimpleIVUsers.push_back(std::make_pair(UI, Def));
718   }
719 }
720 
721 /// Return true if this instruction generates a simple SCEV
722 /// expression in terms of that IV.
723 ///
724 /// This is similar to IVUsers' isInteresting() but processes each instruction
725 /// non-recursively when the operand is already known to be a simpleIVUser.
726 ///
727 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
728   if (!SE->isSCEVable(I->getType()))
729     return false;
730 
731   // Get the symbolic expression for this instruction.
732   const SCEV *S = SE->getSCEV(I);
733 
734   // Only consider affine recurrences.
735   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
736   if (AR && AR->getLoop() == L)
737     return true;
738 
739   return false;
740 }
741 
742 /// Iteratively perform simplification on a worklist of users
743 /// of the specified induction variable. Each successive simplification may push
744 /// more users which may themselves be candidates for simplification.
745 ///
746 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
747 /// instructions in-place during analysis. Rather than rewriting induction
748 /// variables bottom-up from their users, it transforms a chain of IVUsers
749 /// top-down, updating the IR only when it encounters a clear optimization
750 /// opportunity.
751 ///
752 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
753 ///
754 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
755   if (!SE->isSCEVable(CurrIV->getType()))
756     return;
757 
758   // Instructions processed by SimplifyIndvar for CurrIV.
759   SmallPtrSet<Instruction*,16> Simplified;
760 
761   // Use-def pairs if IV users waiting to be processed for CurrIV.
762   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
763 
764   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
765   // called multiple times for the same LoopPhi. This is the proper thing to
766   // do for loop header phis that use each other.
767   pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
768 
769   while (!SimpleIVUsers.empty()) {
770     std::pair<Instruction*, Instruction*> UseOper =
771       SimpleIVUsers.pop_back_val();
772     Instruction *UseInst = UseOper.first;
773 
774     // Bypass back edges to avoid extra work.
775     if (UseInst == CurrIV) continue;
776 
777     // Try to replace UseInst with a constant before any other simplifications
778     if (foldConstantSCEV(UseInst))
779       continue;
780 
781     Instruction *IVOperand = UseOper.second;
782     for (unsigned N = 0; IVOperand; ++N) {
783       assert(N <= Simplified.size() && "runaway iteration");
784 
785       Value *NewOper = foldIVUser(UseOper.first, IVOperand);
786       if (!NewOper)
787         break; // done folding
788       IVOperand = dyn_cast<Instruction>(NewOper);
789     }
790     if (!IVOperand)
791       continue;
792 
793     if (eliminateIVUser(UseOper.first, IVOperand)) {
794       pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
795       continue;
796     }
797 
798     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
799       if ((isa<OverflowingBinaryOperator>(BO) &&
800            strengthenOverflowingOperation(BO, IVOperand)) ||
801           (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
802         // re-queue uses of the now modified binary operator and fall
803         // through to the checks that remain.
804         pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
805       }
806     }
807 
808     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
809     if (V && Cast) {
810       V->visitCast(Cast);
811       continue;
812     }
813     if (isSimpleIVUser(UseOper.first, L, SE)) {
814       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
815     }
816   }
817 }
818 
819 namespace llvm {
820 
821 void IVVisitor::anchor() { }
822 
823 /// Simplify instructions that use this induction variable
824 /// by using ScalarEvolution to analyze the IV's recurrence.
825 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
826                        LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
827                        IVVisitor *V) {
828   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
829   SIV.simplifyUsers(CurrIV, V);
830   return SIV.hasChanged();
831 }
832 
833 /// Simplify users of induction variables within this
834 /// loop. This does not actually change or add IVs.
835 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
836                      LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
837   bool Changed = false;
838   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
839     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
840   }
841   return Changed;
842 }
843 
844 } // namespace llvm
845