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