10b57cec5SDimitry Andric //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements induction variable simplification. It does
100b57cec5SDimitry Andric // not define any actual pass or policy, but provides a single function to
110b57cec5SDimitry Andric // simplify a loop's induction variables based on ScalarEvolution.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
19*8e3e0a47SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
200b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
210b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
220b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
230b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
240b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
250b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
260b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
270b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
285ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric using namespace llvm;
31e710425bSDimitry Andric using namespace llvm::PatternMatch;
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric #define DEBUG_TYPE "indvars"
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
360b57cec5SDimitry Andric STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
370b57cec5SDimitry Andric STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
380b57cec5SDimitry Andric STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
390b57cec5SDimitry Andric STATISTIC(
400b57cec5SDimitry Andric     NumSimplifiedSDiv,
410b57cec5SDimitry Andric     "Number of IV signed division operations converted to unsigned division");
420b57cec5SDimitry Andric STATISTIC(
430b57cec5SDimitry Andric     NumSimplifiedSRem,
440b57cec5SDimitry Andric     "Number of IV signed remainder operations converted to unsigned remainder");
450b57cec5SDimitry Andric STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric namespace {
480b57cec5SDimitry Andric   /// This is a utility for simplifying induction variables
490b57cec5SDimitry Andric   /// based on ScalarEvolution. It is the primary instrument of the
500b57cec5SDimitry Andric   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
510b57cec5SDimitry Andric   /// other loop passes that preserve SCEV.
520b57cec5SDimitry Andric   class SimplifyIndvar {
530b57cec5SDimitry Andric     Loop             *L;
540b57cec5SDimitry Andric     LoopInfo         *LI;
550b57cec5SDimitry Andric     ScalarEvolution  *SE;
560b57cec5SDimitry Andric     DominatorTree    *DT;
575ffd83dbSDimitry Andric     const TargetTransformInfo *TTI;
580b57cec5SDimitry Andric     SCEVExpander     &Rewriter;
590b57cec5SDimitry Andric     SmallVectorImpl<WeakTrackingVH> &DeadInsts;
600b57cec5SDimitry Andric 
6181ad6265SDimitry Andric     bool Changed = false;
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric   public:
SimplifyIndvar(Loop * Loop,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,const TargetTransformInfo * TTI,SCEVExpander & Rewriter,SmallVectorImpl<WeakTrackingVH> & Dead)640b57cec5SDimitry Andric     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
655ffd83dbSDimitry Andric                    LoopInfo *LI, const TargetTransformInfo *TTI,
665ffd83dbSDimitry Andric                    SCEVExpander &Rewriter,
670b57cec5SDimitry Andric                    SmallVectorImpl<WeakTrackingVH> &Dead)
685ffd83dbSDimitry Andric         : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter),
6981ad6265SDimitry Andric           DeadInsts(Dead) {
700b57cec5SDimitry Andric       assert(LI && "IV simplification requires LoopInfo");
710b57cec5SDimitry Andric     }
720b57cec5SDimitry Andric 
hasChanged() const730b57cec5SDimitry Andric     bool hasChanged() const { return Changed; }
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric     /// Iteratively perform simplification on a worklist of users of the
760b57cec5SDimitry Andric     /// specified induction variable. This is the top-level driver that applies
770b57cec5SDimitry Andric     /// all simplifications to users of an IV.
780b57cec5SDimitry Andric     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric     bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
830b57cec5SDimitry Andric     bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
84753f127fSDimitry Andric     bool replaceFloatIVWithIntegerIV(Instruction *UseInst);
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric     bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
870b57cec5SDimitry Andric     bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
880b57cec5SDimitry Andric     bool eliminateTrunc(TruncInst *TI);
890b57cec5SDimitry Andric     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
90753f127fSDimitry Andric     bool makeIVComparisonInvariant(ICmpInst *ICmp, Instruction *IVOperand);
91753f127fSDimitry Andric     void eliminateIVComparison(ICmpInst *ICmp, Instruction *IVOperand);
92753f127fSDimitry Andric     void simplifyIVRemainder(BinaryOperator *Rem, Instruction *IVOperand,
930b57cec5SDimitry Andric                              bool IsSigned);
940b57cec5SDimitry Andric     void replaceRemWithNumerator(BinaryOperator *Rem);
950b57cec5SDimitry Andric     void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
960b57cec5SDimitry Andric     void replaceSRemWithURem(BinaryOperator *Rem);
970b57cec5SDimitry Andric     bool eliminateSDiv(BinaryOperator *SDiv);
98fe013be4SDimitry Andric     bool strengthenBinaryOp(BinaryOperator *BO, Instruction *IVOperand);
99753f127fSDimitry Andric     bool strengthenOverflowingOperation(BinaryOperator *OBO,
100753f127fSDimitry Andric                                         Instruction *IVOperand);
101753f127fSDimitry Andric     bool strengthenRightShift(BinaryOperator *BO, Instruction *IVOperand);
1020b57cec5SDimitry Andric   };
1030b57cec5SDimitry Andric }
1040b57cec5SDimitry Andric 
105fe6060f1SDimitry Andric /// Find a point in code which dominates all given instructions. We can safely
106fe6060f1SDimitry Andric /// assume that, whatever fact we can prove at the found point, this fact is
107fe6060f1SDimitry Andric /// also true for each of the given instructions.
findCommonDominator(ArrayRef<Instruction * > Instructions,DominatorTree & DT)108fe6060f1SDimitry Andric static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions,
109fe6060f1SDimitry Andric                                         DominatorTree &DT) {
110fe6060f1SDimitry Andric   Instruction *CommonDom = nullptr;
111fe6060f1SDimitry Andric   for (auto *Insn : Instructions)
112fe6060f1SDimitry Andric     CommonDom =
113bdd1243dSDimitry Andric         CommonDom ? DT.findNearestCommonDominator(CommonDom, Insn) : Insn;
114fe6060f1SDimitry Andric   assert(CommonDom && "Common dominator not found?");
115fe6060f1SDimitry Andric   return CommonDom;
116fe6060f1SDimitry Andric }
117fe6060f1SDimitry Andric 
1180b57cec5SDimitry Andric /// Fold an IV operand into its use.  This removes increments of an
1190b57cec5SDimitry Andric /// aligned IV when used by a instruction that ignores the low bits.
1200b57cec5SDimitry Andric ///
1210b57cec5SDimitry Andric /// IVOperand is guaranteed SCEVable, but UseInst may not be.
1220b57cec5SDimitry Andric ///
1230b57cec5SDimitry Andric /// Return the operand of IVOperand for this induction variable if IVOperand can
1240b57cec5SDimitry Andric /// be folded (in case more folding opportunities have been exposed).
1250b57cec5SDimitry Andric /// Otherwise return null.
foldIVUser(Instruction * UseInst,Instruction * IVOperand)1260b57cec5SDimitry Andric Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
1270b57cec5SDimitry Andric   Value *IVSrc = nullptr;
1280b57cec5SDimitry Andric   const unsigned OperIdx = 0;
1290b57cec5SDimitry Andric   const SCEV *FoldedExpr = nullptr;
1300b57cec5SDimitry Andric   bool MustDropExactFlag = false;
1310b57cec5SDimitry Andric   switch (UseInst->getOpcode()) {
1320b57cec5SDimitry Andric   default:
1330b57cec5SDimitry Andric     return nullptr;
1340b57cec5SDimitry Andric   case Instruction::UDiv:
1350b57cec5SDimitry Andric   case Instruction::LShr:
1360b57cec5SDimitry Andric     // We're only interested in the case where we know something about
1370b57cec5SDimitry Andric     // the numerator and have a constant denominator.
1380b57cec5SDimitry Andric     if (IVOperand != UseInst->getOperand(OperIdx) ||
1390b57cec5SDimitry Andric         !isa<ConstantInt>(UseInst->getOperand(1)))
1400b57cec5SDimitry Andric       return nullptr;
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric     // Attempt to fold a binary operator with constant operand.
1430b57cec5SDimitry Andric     // e.g. ((I + 1) >> 2) => I >> 2
1440b57cec5SDimitry Andric     if (!isa<BinaryOperator>(IVOperand)
1450b57cec5SDimitry Andric         || !isa<ConstantInt>(IVOperand->getOperand(1)))
1460b57cec5SDimitry Andric       return nullptr;
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric     IVSrc = IVOperand->getOperand(0);
1490b57cec5SDimitry Andric     // IVSrc must be the (SCEVable) IV, since the other operand is const.
1500b57cec5SDimitry Andric     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
1530b57cec5SDimitry Andric     if (UseInst->getOpcode() == Instruction::LShr) {
1540b57cec5SDimitry Andric       // Get a constant for the divisor. See createSCEV.
1550b57cec5SDimitry Andric       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
1560b57cec5SDimitry Andric       if (D->getValue().uge(BitWidth))
1570b57cec5SDimitry Andric         return nullptr;
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric       D = ConstantInt::get(UseInst->getContext(),
1600b57cec5SDimitry Andric                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
1610b57cec5SDimitry Andric     }
16281ad6265SDimitry Andric     const auto *LHS = SE->getSCEV(IVSrc);
16381ad6265SDimitry Andric     const auto *RHS = SE->getSCEV(D);
16481ad6265SDimitry Andric     FoldedExpr = SE->getUDivExpr(LHS, RHS);
1650b57cec5SDimitry Andric     // We might have 'exact' flag set at this point which will no longer be
1660b57cec5SDimitry Andric     // correct after we make the replacement.
16781ad6265SDimitry Andric     if (UseInst->isExact() && LHS != SE->getMulExpr(FoldedExpr, RHS))
1680b57cec5SDimitry Andric       MustDropExactFlag = true;
1690b57cec5SDimitry Andric   }
1700b57cec5SDimitry Andric   // We have something that might fold it's operand. Compare SCEVs.
1710b57cec5SDimitry Andric   if (!SE->isSCEVable(UseInst->getType()))
1720b57cec5SDimitry Andric     return nullptr;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   // Bypass the operand if SCEV can prove it has no effect.
1750b57cec5SDimitry Andric   if (SE->getSCEV(UseInst) != FoldedExpr)
1760b57cec5SDimitry Andric     return nullptr;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
1790b57cec5SDimitry Andric                     << " -> " << *UseInst << '\n');
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   UseInst->setOperand(OperIdx, IVSrc);
1820b57cec5SDimitry Andric   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   if (MustDropExactFlag)
1850b57cec5SDimitry Andric     UseInst->dropPoisonGeneratingFlags();
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   ++NumElimOperand;
1880b57cec5SDimitry Andric   Changed = true;
1890b57cec5SDimitry Andric   if (IVOperand->use_empty())
1900b57cec5SDimitry Andric     DeadInsts.emplace_back(IVOperand);
1910b57cec5SDimitry Andric   return IVSrc;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
makeIVComparisonInvariant(ICmpInst * ICmp,Instruction * IVOperand)1940b57cec5SDimitry Andric bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
195753f127fSDimitry Andric                                                Instruction *IVOperand) {
196bdd1243dSDimitry Andric   auto *Preheader = L->getLoopPreheader();
197bdd1243dSDimitry Andric   if (!Preheader)
198bdd1243dSDimitry Andric     return false;
1990b57cec5SDimitry Andric   unsigned IVOperIdx = 0;
2000b57cec5SDimitry Andric   ICmpInst::Predicate Pred = ICmp->getPredicate();
2010b57cec5SDimitry Andric   if (IVOperand != ICmp->getOperand(0)) {
2020b57cec5SDimitry Andric     // Swapped
2030b57cec5SDimitry Andric     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
2040b57cec5SDimitry Andric     IVOperIdx = 1;
2050b57cec5SDimitry Andric     Pred = ICmpInst::getSwappedPredicate(Pred);
2060b57cec5SDimitry Andric   }
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   // Get the SCEVs for the ICmp operands (in the specific context of the
2090b57cec5SDimitry Andric   // current loop)
2100b57cec5SDimitry Andric   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
2110b57cec5SDimitry Andric   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
2120b57cec5SDimitry Andric   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
213bdd1243dSDimitry Andric   auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L, ICmp);
214e8d8bef9SDimitry Andric   if (!LIP)
2150b57cec5SDimitry Andric     return false;
216e8d8bef9SDimitry Andric   ICmpInst::Predicate InvariantPredicate = LIP->Pred;
217e8d8bef9SDimitry Andric   const SCEV *InvariantLHS = LIP->LHS;
218e8d8bef9SDimitry Andric   const SCEV *InvariantRHS = LIP->RHS;
2190b57cec5SDimitry Andric 
220bdd1243dSDimitry Andric   // Do not generate something ridiculous.
221bdd1243dSDimitry Andric   auto *PHTerm = Preheader->getTerminator();
222bdd1243dSDimitry Andric   if (Rewriter.isHighCostExpansion({InvariantLHS, InvariantRHS}, L,
223fe013be4SDimitry Andric                                    2 * SCEVCheapExpansionBudget, TTI, PHTerm) ||
224fe013be4SDimitry Andric       !Rewriter.isSafeToExpandAt(InvariantLHS, PHTerm) ||
225fe013be4SDimitry Andric       !Rewriter.isSafeToExpandAt(InvariantRHS, PHTerm))
2260b57cec5SDimitry Andric     return false;
227bdd1243dSDimitry Andric   auto *NewLHS =
228bdd1243dSDimitry Andric       Rewriter.expandCodeFor(InvariantLHS, IVOperand->getType(), PHTerm);
229bdd1243dSDimitry Andric   auto *NewRHS =
230bdd1243dSDimitry Andric       Rewriter.expandCodeFor(InvariantRHS, IVOperand->getType(), PHTerm);
2310b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
2320b57cec5SDimitry Andric   ICmp->setPredicate(InvariantPredicate);
2330b57cec5SDimitry Andric   ICmp->setOperand(0, NewLHS);
2340b57cec5SDimitry Andric   ICmp->setOperand(1, NewRHS);
2350b57cec5SDimitry Andric   return true;
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric /// SimplifyIVUsers helper for eliminating useless
2390b57cec5SDimitry Andric /// comparisons against an induction variable.
eliminateIVComparison(ICmpInst * ICmp,Instruction * IVOperand)240753f127fSDimitry Andric void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp,
241753f127fSDimitry Andric                                            Instruction *IVOperand) {
2420b57cec5SDimitry Andric   unsigned IVOperIdx = 0;
2430b57cec5SDimitry Andric   ICmpInst::Predicate Pred = ICmp->getPredicate();
2440b57cec5SDimitry Andric   ICmpInst::Predicate OriginalPred = Pred;
2450b57cec5SDimitry Andric   if (IVOperand != ICmp->getOperand(0)) {
2460b57cec5SDimitry Andric     // Swapped
2470b57cec5SDimitry Andric     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
2480b57cec5SDimitry Andric     IVOperIdx = 1;
2490b57cec5SDimitry Andric     Pred = ICmpInst::getSwappedPredicate(Pred);
2500b57cec5SDimitry Andric   }
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   // Get the SCEVs for the ICmp operands (in the specific context of the
2530b57cec5SDimitry Andric   // current loop)
2540b57cec5SDimitry Andric   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
2550b57cec5SDimitry Andric   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
2560b57cec5SDimitry Andric   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
2570b57cec5SDimitry Andric 
258fe6060f1SDimitry Andric   // If the condition is always true or always false in the given context,
259fe6060f1SDimitry Andric   // replace it with a constant value.
260fe6060f1SDimitry Andric   SmallVector<Instruction *, 4> Users;
261fe6060f1SDimitry Andric   for (auto *U : ICmp->users())
262fe6060f1SDimitry Andric     Users.push_back(cast<Instruction>(U));
263fe6060f1SDimitry Andric   const Instruction *CtxI = findCommonDominator(Users, *DT);
264fe6060f1SDimitry Andric   if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) {
265bdd1243dSDimitry Andric     SE->forgetValue(ICmp);
266fe6060f1SDimitry Andric     ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev));
2670b57cec5SDimitry Andric     DeadInsts.emplace_back(ICmp);
2680b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
2690b57cec5SDimitry Andric   } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
2700b57cec5SDimitry Andric     // fallthrough to end of function
2710b57cec5SDimitry Andric   } else if (ICmpInst::isSigned(OriginalPred) &&
2720b57cec5SDimitry Andric              SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
2730b57cec5SDimitry Andric     // If we were unable to make anything above, all we can is to canonicalize
2740b57cec5SDimitry Andric     // the comparison hoping that it will open the doors for other
2750b57cec5SDimitry Andric     // optimizations. If we find out that we compare two non-negative values,
2760b57cec5SDimitry Andric     // we turn the instruction's predicate to its unsigned version. Note that
2770b57cec5SDimitry Andric     // we cannot rely on Pred here unless we check if we have swapped it.
2780b57cec5SDimitry Andric     assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
2790b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
2800b57cec5SDimitry Andric                       << '\n');
2810b57cec5SDimitry Andric     ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
2820b57cec5SDimitry Andric   } else
2830b57cec5SDimitry Andric     return;
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   ++NumElimCmp;
2860b57cec5SDimitry Andric   Changed = true;
2870b57cec5SDimitry Andric }
2880b57cec5SDimitry Andric 
eliminateSDiv(BinaryOperator * SDiv)2890b57cec5SDimitry Andric bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
2900b57cec5SDimitry Andric   // Get the SCEVs for the ICmp operands.
2910b57cec5SDimitry Andric   auto *N = SE->getSCEV(SDiv->getOperand(0));
2920b57cec5SDimitry Andric   auto *D = SE->getSCEV(SDiv->getOperand(1));
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   // Simplify unnecessary loops away.
2950b57cec5SDimitry Andric   const Loop *L = LI->getLoopFor(SDiv->getParent());
2960b57cec5SDimitry Andric   N = SE->getSCEVAtScope(N, L);
2970b57cec5SDimitry Andric   D = SE->getSCEVAtScope(D, L);
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // Replace sdiv by udiv if both of the operands are non-negative
3000b57cec5SDimitry Andric   if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
3010b57cec5SDimitry Andric     auto *UDiv = BinaryOperator::Create(
3020b57cec5SDimitry Andric         BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
3030b57cec5SDimitry Andric         SDiv->getName() + ".udiv", SDiv);
3040b57cec5SDimitry Andric     UDiv->setIsExact(SDiv->isExact());
3050b57cec5SDimitry Andric     SDiv->replaceAllUsesWith(UDiv);
3060b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
3070b57cec5SDimitry Andric     ++NumSimplifiedSDiv;
3080b57cec5SDimitry Andric     Changed = true;
3090b57cec5SDimitry Andric     DeadInsts.push_back(SDiv);
3100b57cec5SDimitry Andric     return true;
3110b57cec5SDimitry Andric   }
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   return false;
3140b57cec5SDimitry Andric }
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric // i %s n -> i %u n if i >= 0 and n >= 0
replaceSRemWithURem(BinaryOperator * Rem)3170b57cec5SDimitry Andric void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
3180b57cec5SDimitry Andric   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
3190b57cec5SDimitry Andric   auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
3200b57cec5SDimitry Andric                                       Rem->getName() + ".urem", Rem);
3210b57cec5SDimitry Andric   Rem->replaceAllUsesWith(URem);
3220b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
3230b57cec5SDimitry Andric   ++NumSimplifiedSRem;
3240b57cec5SDimitry Andric   Changed = true;
3250b57cec5SDimitry Andric   DeadInsts.emplace_back(Rem);
3260b57cec5SDimitry Andric }
3270b57cec5SDimitry Andric 
3280b57cec5SDimitry Andric // i % n  -->  i  if i is in [0,n).
replaceRemWithNumerator(BinaryOperator * Rem)3290b57cec5SDimitry Andric void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
3300b57cec5SDimitry Andric   Rem->replaceAllUsesWith(Rem->getOperand(0));
3310b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
3320b57cec5SDimitry Andric   ++NumElimRem;
3330b57cec5SDimitry Andric   Changed = true;
3340b57cec5SDimitry Andric   DeadInsts.emplace_back(Rem);
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
replaceRemWithNumeratorOrZero(BinaryOperator * Rem)3380b57cec5SDimitry Andric void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
3390b57cec5SDimitry Andric   auto *T = Rem->getType();
3400b57cec5SDimitry Andric   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
3410b57cec5SDimitry Andric   ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
3420b57cec5SDimitry Andric   SelectInst *Sel =
3430b57cec5SDimitry Andric       SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
3440b57cec5SDimitry Andric   Rem->replaceAllUsesWith(Sel);
3450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
3460b57cec5SDimitry Andric   ++NumElimRem;
3470b57cec5SDimitry Andric   Changed = true;
3480b57cec5SDimitry Andric   DeadInsts.emplace_back(Rem);
3490b57cec5SDimitry Andric }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric /// SimplifyIVUsers helper for eliminating useless remainder operations
3520b57cec5SDimitry Andric /// operating on an induction variable or replacing srem by urem.
simplifyIVRemainder(BinaryOperator * Rem,Instruction * IVOperand,bool IsSigned)353753f127fSDimitry Andric void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem,
354753f127fSDimitry Andric                                          Instruction *IVOperand,
3550b57cec5SDimitry Andric                                          bool IsSigned) {
3560b57cec5SDimitry Andric   auto *NValue = Rem->getOperand(0);
3570b57cec5SDimitry Andric   auto *DValue = Rem->getOperand(1);
3580b57cec5SDimitry Andric   // We're only interested in the case where we know something about
3590b57cec5SDimitry Andric   // the numerator, unless it is a srem, because we want to replace srem by urem
3600b57cec5SDimitry Andric   // in general.
3610b57cec5SDimitry Andric   bool UsedAsNumerator = IVOperand == NValue;
3620b57cec5SDimitry Andric   if (!UsedAsNumerator && !IsSigned)
3630b57cec5SDimitry Andric     return;
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   const SCEV *N = SE->getSCEV(NValue);
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   // Simplify unnecessary loops away.
3680b57cec5SDimitry Andric   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
3690b57cec5SDimitry Andric   N = SE->getSCEVAtScope(N, ICmpLoop);
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
3720b57cec5SDimitry Andric 
3730b57cec5SDimitry Andric   // Do not proceed if the Numerator may be negative
3740b57cec5SDimitry Andric   if (!IsNumeratorNonNegative)
3750b57cec5SDimitry Andric     return;
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   const SCEV *D = SE->getSCEV(DValue);
3780b57cec5SDimitry Andric   D = SE->getSCEVAtScope(D, ICmpLoop);
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   if (UsedAsNumerator) {
3810b57cec5SDimitry Andric     auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
3820b57cec5SDimitry Andric     if (SE->isKnownPredicate(LT, N, D)) {
3830b57cec5SDimitry Andric       replaceRemWithNumerator(Rem);
3840b57cec5SDimitry Andric       return;
3850b57cec5SDimitry Andric     }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric     auto *T = Rem->getType();
3880b57cec5SDimitry Andric     const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
3890b57cec5SDimitry Andric     if (SE->isKnownPredicate(LT, NLessOne, D)) {
3900b57cec5SDimitry Andric       replaceRemWithNumeratorOrZero(Rem);
3910b57cec5SDimitry Andric       return;
3920b57cec5SDimitry Andric     }
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // Try to replace SRem with URem, if both N and D are known non-negative.
3960b57cec5SDimitry Andric   // Since we had already check N, we only need to check D now
3970b57cec5SDimitry Andric   if (!IsSigned || !SE->isKnownNonNegative(D))
3980b57cec5SDimitry Andric     return;
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   replaceSRemWithURem(Rem);
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
eliminateOverflowIntrinsic(WithOverflowInst * WO)4030b57cec5SDimitry Andric bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
4040b57cec5SDimitry Andric   const SCEV *LHS = SE->getSCEV(WO->getLHS());
4050b57cec5SDimitry Andric   const SCEV *RHS = SE->getSCEV(WO->getRHS());
406fe6060f1SDimitry Andric   if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
4070b57cec5SDimitry Andric     return false;
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   // Proved no overflow, nuke the overflow check and, if possible, the overflow
4100b57cec5SDimitry Andric   // intrinsic as well.
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   BinaryOperator *NewResult = BinaryOperator::Create(
4130b57cec5SDimitry Andric       WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO);
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric   if (WO->isSigned())
4160b57cec5SDimitry Andric     NewResult->setHasNoSignedWrap(true);
4170b57cec5SDimitry Andric   else
4180b57cec5SDimitry Andric     NewResult->setHasNoUnsignedWrap(true);
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   SmallVector<ExtractValueInst *, 4> ToDelete;
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric   for (auto *U : WO->users()) {
4230b57cec5SDimitry Andric     if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
4240b57cec5SDimitry Andric       if (EVI->getIndices()[0] == 1)
4250b57cec5SDimitry Andric         EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
4260b57cec5SDimitry Andric       else {
4270b57cec5SDimitry Andric         assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
4280b57cec5SDimitry Andric         EVI->replaceAllUsesWith(NewResult);
4290b57cec5SDimitry Andric       }
4300b57cec5SDimitry Andric       ToDelete.push_back(EVI);
4310b57cec5SDimitry Andric     }
4320b57cec5SDimitry Andric   }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   for (auto *EVI : ToDelete)
4350b57cec5SDimitry Andric     EVI->eraseFromParent();
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   if (WO->use_empty())
4380b57cec5SDimitry Andric     WO->eraseFromParent();
4390b57cec5SDimitry Andric 
440e8d8bef9SDimitry Andric   Changed = true;
4410b57cec5SDimitry Andric   return true;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
eliminateSaturatingIntrinsic(SaturatingInst * SI)4440b57cec5SDimitry Andric bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
4450b57cec5SDimitry Andric   const SCEV *LHS = SE->getSCEV(SI->getLHS());
4460b57cec5SDimitry Andric   const SCEV *RHS = SE->getSCEV(SI->getRHS());
447fe6060f1SDimitry Andric   if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
4480b57cec5SDimitry Andric     return false;
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   BinaryOperator *BO = BinaryOperator::Create(
4510b57cec5SDimitry Andric       SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI);
4520b57cec5SDimitry Andric   if (SI->isSigned())
4530b57cec5SDimitry Andric     BO->setHasNoSignedWrap();
4540b57cec5SDimitry Andric   else
4550b57cec5SDimitry Andric     BO->setHasNoUnsignedWrap();
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   SI->replaceAllUsesWith(BO);
4580b57cec5SDimitry Andric   DeadInsts.emplace_back(SI);
4590b57cec5SDimitry Andric   Changed = true;
4600b57cec5SDimitry Andric   return true;
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
eliminateTrunc(TruncInst * TI)4630b57cec5SDimitry Andric bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
4640b57cec5SDimitry Andric   // It is always legal to replace
4650b57cec5SDimitry Andric   //   icmp <pred> i32 trunc(iv), n
4660b57cec5SDimitry Andric   // with
4670b57cec5SDimitry Andric   //   icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
4680b57cec5SDimitry Andric   // Or with
4690b57cec5SDimitry Andric   //   icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
4700b57cec5SDimitry Andric   // Or with either of these if pred is an equality predicate.
4710b57cec5SDimitry Andric   //
4720b57cec5SDimitry Andric   // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
4730b57cec5SDimitry Andric   // every comparison which uses trunc, it means that we can replace each of
4740b57cec5SDimitry Andric   // them with comparison of iv against sext/zext(n). We no longer need trunc
4750b57cec5SDimitry Andric   // after that.
4760b57cec5SDimitry Andric   //
4770b57cec5SDimitry Andric   // TODO: Should we do this if we can widen *some* comparisons, but not all
4780b57cec5SDimitry Andric   // of them? Sometimes it is enough to enable other optimizations, but the
4790b57cec5SDimitry Andric   // trunc instruction will stay in the loop.
4800b57cec5SDimitry Andric   Value *IV = TI->getOperand(0);
4810b57cec5SDimitry Andric   Type *IVTy = IV->getType();
4820b57cec5SDimitry Andric   const SCEV *IVSCEV = SE->getSCEV(IV);
4830b57cec5SDimitry Andric   const SCEV *TISCEV = SE->getSCEV(TI);
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
4860b57cec5SDimitry Andric   // get rid of trunc
4870b57cec5SDimitry Andric   bool DoesSExtCollapse = false;
4880b57cec5SDimitry Andric   bool DoesZExtCollapse = false;
4890b57cec5SDimitry Andric   if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
4900b57cec5SDimitry Andric     DoesSExtCollapse = true;
4910b57cec5SDimitry Andric   if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
4920b57cec5SDimitry Andric     DoesZExtCollapse = true;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   // If neither sext nor zext does collapse, it is not profitable to do any
4950b57cec5SDimitry Andric   // transform. Bail.
4960b57cec5SDimitry Andric   if (!DoesSExtCollapse && !DoesZExtCollapse)
4970b57cec5SDimitry Andric     return false;
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric   // Collect users of the trunc that look like comparisons against invariants.
5000b57cec5SDimitry Andric   // Bail if we find something different.
5010b57cec5SDimitry Andric   SmallVector<ICmpInst *, 4> ICmpUsers;
5020b57cec5SDimitry Andric   for (auto *U : TI->users()) {
5030b57cec5SDimitry Andric     // We don't care about users in unreachable blocks.
5040b57cec5SDimitry Andric     if (isa<Instruction>(U) &&
5050b57cec5SDimitry Andric         !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
5060b57cec5SDimitry Andric       continue;
5070b57cec5SDimitry Andric     ICmpInst *ICI = dyn_cast<ICmpInst>(U);
5080b57cec5SDimitry Andric     if (!ICI) return false;
5090b57cec5SDimitry Andric     assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
5100b57cec5SDimitry Andric     if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
5110b57cec5SDimitry Andric         !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
5120b57cec5SDimitry Andric       return false;
5130b57cec5SDimitry Andric     // If we cannot get rid of trunc, bail.
5140b57cec5SDimitry Andric     if (ICI->isSigned() && !DoesSExtCollapse)
5150b57cec5SDimitry Andric       return false;
5160b57cec5SDimitry Andric     if (ICI->isUnsigned() && !DoesZExtCollapse)
5170b57cec5SDimitry Andric       return false;
5180b57cec5SDimitry Andric     // For equality, either signed or unsigned works.
5190b57cec5SDimitry Andric     ICmpUsers.push_back(ICI);
5200b57cec5SDimitry Andric   }
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   auto CanUseZExt = [&](ICmpInst *ICI) {
5230b57cec5SDimitry Andric     // Unsigned comparison can be widened as unsigned.
5240b57cec5SDimitry Andric     if (ICI->isUnsigned())
5250b57cec5SDimitry Andric       return true;
5260b57cec5SDimitry Andric     // Is it profitable to do zext?
5270b57cec5SDimitry Andric     if (!DoesZExtCollapse)
5280b57cec5SDimitry Andric       return false;
5290b57cec5SDimitry Andric     // For equality, we can safely zext both parts.
5300b57cec5SDimitry Andric     if (ICI->isEquality())
5310b57cec5SDimitry Andric       return true;
5320b57cec5SDimitry Andric     // Otherwise we can only use zext when comparing two non-negative or two
5330b57cec5SDimitry Andric     // negative values. But in practice, we will never pass DoesZExtCollapse
5340b57cec5SDimitry Andric     // check for a negative value, because zext(trunc(x)) is non-negative. So
5350b57cec5SDimitry Andric     // it only make sense to check for non-negativity here.
5360b57cec5SDimitry Andric     const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
5370b57cec5SDimitry Andric     const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
5380b57cec5SDimitry Andric     return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
5390b57cec5SDimitry Andric   };
5400b57cec5SDimitry Andric   // Replace all comparisons against trunc with comparisons against IV.
5410b57cec5SDimitry Andric   for (auto *ICI : ICmpUsers) {
5420b57cec5SDimitry Andric     bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
5430b57cec5SDimitry Andric     auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
544c9157d92SDimitry Andric     IRBuilder<> Builder(ICI);
545c9157d92SDimitry Andric     Value *Ext = nullptr;
5460b57cec5SDimitry Andric     // For signed/unsigned predicate, replace the old comparison with comparison
5470b57cec5SDimitry Andric     // of immediate IV against sext/zext of the invariant argument. If we can
5480b57cec5SDimitry Andric     // use either sext or zext (i.e. we are dealing with equality predicate),
5490b57cec5SDimitry Andric     // then prefer zext as a more canonical form.
5500b57cec5SDimitry Andric     // TODO: If we see a signed comparison which can be turned into unsigned,
5510b57cec5SDimitry Andric     // we can do it here for canonicalization purposes.
5520b57cec5SDimitry Andric     ICmpInst::Predicate Pred = ICI->getPredicate();
5530b57cec5SDimitry Andric     if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
5540b57cec5SDimitry Andric     if (CanUseZExt(ICI)) {
5550b57cec5SDimitry Andric       assert(DoesZExtCollapse && "Unprofitable zext?");
556c9157d92SDimitry Andric       Ext = Builder.CreateZExt(Op1, IVTy, "zext");
5570b57cec5SDimitry Andric       Pred = ICmpInst::getUnsignedPredicate(Pred);
5580b57cec5SDimitry Andric     } else {
5590b57cec5SDimitry Andric       assert(DoesSExtCollapse && "Unprofitable sext?");
560c9157d92SDimitry Andric       Ext = Builder.CreateSExt(Op1, IVTy, "sext");
5610b57cec5SDimitry Andric       assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
5620b57cec5SDimitry Andric     }
5630b57cec5SDimitry Andric     bool Changed;
5640b57cec5SDimitry Andric     L->makeLoopInvariant(Ext, Changed);
5650b57cec5SDimitry Andric     (void)Changed;
566c9157d92SDimitry Andric     auto *NewCmp = Builder.CreateICmp(Pred, IV, Ext);
567c9157d92SDimitry Andric     ICI->replaceAllUsesWith(NewCmp);
5680b57cec5SDimitry Andric     DeadInsts.emplace_back(ICI);
5690b57cec5SDimitry Andric   }
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   // Trunc no longer needed.
572fcaf7f86SDimitry Andric   TI->replaceAllUsesWith(PoisonValue::get(TI->getType()));
5730b57cec5SDimitry Andric   DeadInsts.emplace_back(TI);
5740b57cec5SDimitry Andric   return true;
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric /// Eliminate an operation that consumes a simple IV and has no observable
5780b57cec5SDimitry Andric /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
5790b57cec5SDimitry Andric /// but UseInst may not be.
eliminateIVUser(Instruction * UseInst,Instruction * IVOperand)5800b57cec5SDimitry Andric bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
5810b57cec5SDimitry Andric                                      Instruction *IVOperand) {
5820b57cec5SDimitry Andric   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
5830b57cec5SDimitry Andric     eliminateIVComparison(ICmp, IVOperand);
5840b57cec5SDimitry Andric     return true;
5850b57cec5SDimitry Andric   }
5860b57cec5SDimitry Andric   if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
5870b57cec5SDimitry Andric     bool IsSRem = Bin->getOpcode() == Instruction::SRem;
5880b57cec5SDimitry Andric     if (IsSRem || Bin->getOpcode() == Instruction::URem) {
5890b57cec5SDimitry Andric       simplifyIVRemainder(Bin, IVOperand, IsSRem);
5900b57cec5SDimitry Andric       return true;
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric     if (Bin->getOpcode() == Instruction::SDiv)
5940b57cec5SDimitry Andric       return eliminateSDiv(Bin);
5950b57cec5SDimitry Andric   }
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
5980b57cec5SDimitry Andric     if (eliminateOverflowIntrinsic(WO))
5990b57cec5SDimitry Andric       return true;
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
6020b57cec5SDimitry Andric     if (eliminateSaturatingIntrinsic(SI))
6030b57cec5SDimitry Andric       return true;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   if (auto *TI = dyn_cast<TruncInst>(UseInst))
6060b57cec5SDimitry Andric     if (eliminateTrunc(TI))
6070b57cec5SDimitry Andric       return true;
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric   if (eliminateIdentitySCEV(UseInst, IVOperand))
6100b57cec5SDimitry Andric     return true;
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   return false;
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric 
GetLoopInvariantInsertPosition(Loop * L,Instruction * Hint)6150b57cec5SDimitry Andric static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
6160b57cec5SDimitry Andric   if (auto *BB = L->getLoopPreheader())
6170b57cec5SDimitry Andric     return BB->getTerminator();
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   return Hint;
6200b57cec5SDimitry Andric }
6210b57cec5SDimitry Andric 
6225ffd83dbSDimitry Andric /// Replace the UseInst with a loop invariant expression if it is safe.
replaceIVUserWithLoopInvariant(Instruction * I)6230b57cec5SDimitry Andric bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
6240b57cec5SDimitry Andric   if (!SE->isSCEVable(I->getType()))
6250b57cec5SDimitry Andric     return false;
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   // Get the symbolic expression for this instruction.
6280b57cec5SDimitry Andric   const SCEV *S = SE->getSCEV(I);
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric   if (!SE->isLoopInvariant(S, L))
6310b57cec5SDimitry Andric     return false;
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   // Do not generate something ridiculous even if S is loop invariant.
6345ffd83dbSDimitry Andric   if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
6350b57cec5SDimitry Andric     return false;
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   auto *IP = GetLoopInvariantInsertPosition(L, I);
6385ffd83dbSDimitry Andric 
639fcaf7f86SDimitry Andric   if (!Rewriter.isSafeToExpandAt(S, IP)) {
6405ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
6415ffd83dbSDimitry Andric                       << " with non-speculable loop invariant: " << *S << '\n');
6425ffd83dbSDimitry Andric     return false;
6435ffd83dbSDimitry Andric   }
6445ffd83dbSDimitry Andric 
6450b57cec5SDimitry Andric   auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   I->replaceAllUsesWith(Invariant);
6480b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
6490b57cec5SDimitry Andric                     << " with loop invariant: " << *S << '\n');
6500b57cec5SDimitry Andric   ++NumFoldedUser;
6510b57cec5SDimitry Andric   Changed = true;
6520b57cec5SDimitry Andric   DeadInsts.emplace_back(I);
6530b57cec5SDimitry Andric   return true;
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric 
656753f127fSDimitry Andric /// Eliminate redundant type cast between integer and float.
replaceFloatIVWithIntegerIV(Instruction * UseInst)657753f127fSDimitry Andric bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
658fcaf7f86SDimitry Andric   if (UseInst->getOpcode() != CastInst::SIToFP &&
659fcaf7f86SDimitry Andric       UseInst->getOpcode() != CastInst::UIToFP)
660753f127fSDimitry Andric     return false;
661753f127fSDimitry Andric 
662bdd1243dSDimitry Andric   Instruction *IVOperand = cast<Instruction>(UseInst->getOperand(0));
663753f127fSDimitry Andric   // Get the symbolic expression for this instruction.
664fcaf7f86SDimitry Andric   const SCEV *IV = SE->getSCEV(IVOperand);
665c9157d92SDimitry Andric   int MaskBits;
666fcaf7f86SDimitry Andric   if (UseInst->getOpcode() == CastInst::SIToFP)
667c9157d92SDimitry Andric     MaskBits = (int)SE->getSignedRange(IV).getMinSignedBits();
668fcaf7f86SDimitry Andric   else
669c9157d92SDimitry Andric     MaskBits = (int)SE->getUnsignedRange(IV).getActiveBits();
670c9157d92SDimitry Andric   int DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
671fcaf7f86SDimitry Andric   if (MaskBits <= DestNumSigBits) {
672753f127fSDimitry Andric     for (User *U : UseInst->users()) {
673fcaf7f86SDimitry Andric       // Match for fptosi/fptoui of sitofp and with same type.
674fcaf7f86SDimitry Andric       auto *CI = dyn_cast<CastInst>(U);
675bdd1243dSDimitry Andric       if (!CI)
676753f127fSDimitry Andric         continue;
677753f127fSDimitry Andric 
678fcaf7f86SDimitry Andric       CastInst::CastOps Opcode = CI->getOpcode();
679fcaf7f86SDimitry Andric       if (Opcode != CastInst::FPToSI && Opcode != CastInst::FPToUI)
680fcaf7f86SDimitry Andric         continue;
681fcaf7f86SDimitry Andric 
682bdd1243dSDimitry Andric       Value *Conv = nullptr;
683bdd1243dSDimitry Andric       if (IVOperand->getType() != CI->getType()) {
684bdd1243dSDimitry Andric         IRBuilder<> Builder(CI);
685bdd1243dSDimitry Andric         StringRef Name = IVOperand->getName();
686bdd1243dSDimitry Andric         // To match InstCombine logic, we only need sext if both fptosi and
687bdd1243dSDimitry Andric         // sitofp are used. If one of them is unsigned, then we can use zext.
688bdd1243dSDimitry Andric         if (SE->getTypeSizeInBits(IVOperand->getType()) >
689bdd1243dSDimitry Andric             SE->getTypeSizeInBits(CI->getType())) {
690bdd1243dSDimitry Andric           Conv = Builder.CreateTrunc(IVOperand, CI->getType(), Name + ".trunc");
691bdd1243dSDimitry Andric         } else if (Opcode == CastInst::FPToUI ||
692bdd1243dSDimitry Andric                    UseInst->getOpcode() == CastInst::UIToFP) {
693bdd1243dSDimitry Andric           Conv = Builder.CreateZExt(IVOperand, CI->getType(), Name + ".zext");
694bdd1243dSDimitry Andric         } else {
695bdd1243dSDimitry Andric           Conv = Builder.CreateSExt(IVOperand, CI->getType(), Name + ".sext");
696bdd1243dSDimitry Andric         }
697bdd1243dSDimitry Andric       } else
698bdd1243dSDimitry Andric         Conv = IVOperand;
699bdd1243dSDimitry Andric 
700bdd1243dSDimitry Andric       CI->replaceAllUsesWith(Conv);
701753f127fSDimitry Andric       DeadInsts.push_back(CI);
702753f127fSDimitry Andric       LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI
703bdd1243dSDimitry Andric                         << " with: " << *Conv << '\n');
704753f127fSDimitry Andric 
705753f127fSDimitry Andric       ++NumFoldedUser;
706753f127fSDimitry Andric       Changed = true;
707753f127fSDimitry Andric     }
708753f127fSDimitry Andric   }
709753f127fSDimitry Andric 
710753f127fSDimitry Andric   return Changed;
711753f127fSDimitry Andric }
712753f127fSDimitry Andric 
7130b57cec5SDimitry Andric /// Eliminate any operation that SCEV can prove is an identity function.
eliminateIdentitySCEV(Instruction * UseInst,Instruction * IVOperand)7140b57cec5SDimitry Andric bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
7150b57cec5SDimitry Andric                                            Instruction *IVOperand) {
7160b57cec5SDimitry Andric   if (!SE->isSCEVable(UseInst->getType()) ||
717*8e3e0a47SDimitry Andric       UseInst->getType() != IVOperand->getType())
718*8e3e0a47SDimitry Andric     return false;
719*8e3e0a47SDimitry Andric 
720*8e3e0a47SDimitry Andric   const SCEV *UseSCEV = SE->getSCEV(UseInst);
721*8e3e0a47SDimitry Andric   if (UseSCEV != SE->getSCEV(IVOperand))
7220b57cec5SDimitry Andric     return false;
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
7250b57cec5SDimitry Andric   // dominator tree, even if X is an operand to Y.  For instance, in
7260b57cec5SDimitry Andric   //
7270b57cec5SDimitry Andric   //     %iv = phi i32 {0,+,1}
7280b57cec5SDimitry Andric   //     br %cond, label %left, label %merge
7290b57cec5SDimitry Andric   //
7300b57cec5SDimitry Andric   //   left:
7310b57cec5SDimitry Andric   //     %X = add i32 %iv, 0
7320b57cec5SDimitry Andric   //     br label %merge
7330b57cec5SDimitry Andric   //
7340b57cec5SDimitry Andric   //   merge:
7350b57cec5SDimitry Andric   //     %M = phi (%X, %iv)
7360b57cec5SDimitry Andric   //
7370b57cec5SDimitry Andric   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
7380b57cec5SDimitry Andric   // %M.replaceAllUsesWith(%X) would be incorrect.
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric   if (isa<PHINode>(UseInst))
7410b57cec5SDimitry Andric     // If UseInst is not a PHI node then we know that IVOperand dominates
7420b57cec5SDimitry Andric     // UseInst directly from the legality of SSA.
7430b57cec5SDimitry Andric     if (!DT || !DT->dominates(IVOperand, UseInst))
7440b57cec5SDimitry Andric       return false;
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
7470b57cec5SDimitry Andric     return false;
7480b57cec5SDimitry Andric 
749*8e3e0a47SDimitry Andric   // Make sure the operand is not more poisonous than the instruction.
750*8e3e0a47SDimitry Andric   if (!impliesPoison(IVOperand, UseInst)) {
751*8e3e0a47SDimitry Andric     SmallVector<Instruction *> DropPoisonGeneratingInsts;
752*8e3e0a47SDimitry Andric     if (!SE->canReuseInstruction(UseSCEV, IVOperand, DropPoisonGeneratingInsts))
753*8e3e0a47SDimitry Andric       return false;
754*8e3e0a47SDimitry Andric 
755*8e3e0a47SDimitry Andric     for (Instruction *I : DropPoisonGeneratingInsts)
756*8e3e0a47SDimitry Andric       I->dropPoisonGeneratingFlagsAndMetadata();
757*8e3e0a47SDimitry Andric   }
758*8e3e0a47SDimitry Andric 
7590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
7600b57cec5SDimitry Andric 
761bdd1243dSDimitry Andric   SE->forgetValue(UseInst);
7620b57cec5SDimitry Andric   UseInst->replaceAllUsesWith(IVOperand);
7630b57cec5SDimitry Andric   ++NumElimIdentity;
7640b57cec5SDimitry Andric   Changed = true;
7650b57cec5SDimitry Andric   DeadInsts.emplace_back(UseInst);
7660b57cec5SDimitry Andric   return true;
7670b57cec5SDimitry Andric }
7680b57cec5SDimitry Andric 
strengthenBinaryOp(BinaryOperator * BO,Instruction * IVOperand)769fe013be4SDimitry Andric bool SimplifyIndvar::strengthenBinaryOp(BinaryOperator *BO,
770fe013be4SDimitry Andric                                         Instruction *IVOperand) {
771fe013be4SDimitry Andric   return (isa<OverflowingBinaryOperator>(BO) &&
772fe013be4SDimitry Andric           strengthenOverflowingOperation(BO, IVOperand)) ||
773fe013be4SDimitry Andric          (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand));
774fe013be4SDimitry Andric }
775fe013be4SDimitry Andric 
7760b57cec5SDimitry Andric /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
7770b57cec5SDimitry Andric /// unsigned-overflow.  Returns true if anything changed, false otherwise.
strengthenOverflowingOperation(BinaryOperator * BO,Instruction * IVOperand)7780b57cec5SDimitry Andric bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
779753f127fSDimitry Andric                                                     Instruction *IVOperand) {
780753f127fSDimitry Andric   auto Flags = SE->getStrengthenedNoWrapFlagsFromBinOp(
781fe6060f1SDimitry Andric       cast<OverflowingBinaryOperator>(BO));
7820b57cec5SDimitry Andric 
783753f127fSDimitry Andric   if (!Flags)
784753f127fSDimitry Andric     return false;
7850b57cec5SDimitry Andric 
786753f127fSDimitry Andric   BO->setHasNoUnsignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) ==
787fe6060f1SDimitry Andric                            SCEV::FlagNUW);
788753f127fSDimitry Andric   BO->setHasNoSignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) ==
789fe6060f1SDimitry Andric                          SCEV::FlagNSW);
7900b57cec5SDimitry Andric 
791fe6060f1SDimitry Andric   // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap
792fe6060f1SDimitry Andric   // flags on addrecs while performing zero/sign extensions. We could call
793fe6060f1SDimitry Andric   // forgetValue() here to make sure those flags also propagate to any other
794fe6060f1SDimitry Andric   // SCEV expressions based on the addrec. However, this can have pathological
795fe6060f1SDimitry Andric   // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384.
796753f127fSDimitry Andric   return true;
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric /// Annotate the Shr in (X << IVOperand) >> C as exact using the
8000b57cec5SDimitry Andric /// information from the IV's range. Returns true if anything changed, false
8010b57cec5SDimitry Andric /// otherwise.
strengthenRightShift(BinaryOperator * BO,Instruction * IVOperand)8020b57cec5SDimitry Andric bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
803753f127fSDimitry Andric                                           Instruction *IVOperand) {
8040b57cec5SDimitry Andric   if (BO->getOpcode() == Instruction::Shl) {
8050b57cec5SDimitry Andric     bool Changed = false;
8060b57cec5SDimitry Andric     ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
8070b57cec5SDimitry Andric     for (auto *U : BO->users()) {
8080b57cec5SDimitry Andric       const APInt *C;
8090b57cec5SDimitry Andric       if (match(U,
8100b57cec5SDimitry Andric                 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
8110b57cec5SDimitry Andric           match(U,
8120b57cec5SDimitry Andric                 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
8130b57cec5SDimitry Andric         BinaryOperator *Shr = cast<BinaryOperator>(U);
8140b57cec5SDimitry Andric         if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
8150b57cec5SDimitry Andric           Shr->setIsExact(true);
8160b57cec5SDimitry Andric           Changed = true;
8170b57cec5SDimitry Andric         }
8180b57cec5SDimitry Andric       }
8190b57cec5SDimitry Andric     }
8200b57cec5SDimitry Andric     return Changed;
8210b57cec5SDimitry Andric   }
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   return false;
8240b57cec5SDimitry Andric }
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric /// Add all uses of Def to the current IV's worklist.
pushIVUsers(Instruction * Def,Loop * L,SmallPtrSet<Instruction *,16> & Simplified,SmallVectorImpl<std::pair<Instruction *,Instruction * >> & SimpleIVUsers)8270b57cec5SDimitry Andric static void pushIVUsers(
8280b57cec5SDimitry Andric   Instruction *Def, Loop *L,
8290b57cec5SDimitry Andric   SmallPtrSet<Instruction*,16> &Simplified,
8300b57cec5SDimitry Andric   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   for (User *U : Def->users()) {
8330b57cec5SDimitry Andric     Instruction *UI = cast<Instruction>(U);
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric     // Avoid infinite or exponential worklist processing.
8360b57cec5SDimitry Andric     // Also ensure unique worklist users.
8370b57cec5SDimitry Andric     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
8380b57cec5SDimitry Andric     // self edges first.
8390b57cec5SDimitry Andric     if (UI == Def)
8400b57cec5SDimitry Andric       continue;
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric     // Only change the current Loop, do not change the other parts (e.g. other
8430b57cec5SDimitry Andric     // Loops).
8440b57cec5SDimitry Andric     if (!L->contains(UI))
8450b57cec5SDimitry Andric       continue;
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric     // Do not push the same instruction more than once.
8480b57cec5SDimitry Andric     if (!Simplified.insert(UI).second)
8490b57cec5SDimitry Andric       continue;
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric     SimpleIVUsers.push_back(std::make_pair(UI, Def));
8520b57cec5SDimitry Andric   }
8530b57cec5SDimitry Andric }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric /// Return true if this instruction generates a simple SCEV
8560b57cec5SDimitry Andric /// expression in terms of that IV.
8570b57cec5SDimitry Andric ///
8580b57cec5SDimitry Andric /// This is similar to IVUsers' isInteresting() but processes each instruction
8590b57cec5SDimitry Andric /// non-recursively when the operand is already known to be a simpleIVUser.
8600b57cec5SDimitry Andric ///
isSimpleIVUser(Instruction * I,const Loop * L,ScalarEvolution * SE)8610b57cec5SDimitry Andric static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
8620b57cec5SDimitry Andric   if (!SE->isSCEVable(I->getType()))
8630b57cec5SDimitry Andric     return false;
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   // Get the symbolic expression for this instruction.
8660b57cec5SDimitry Andric   const SCEV *S = SE->getSCEV(I);
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric   // Only consider affine recurrences.
8690b57cec5SDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
8700b57cec5SDimitry Andric   if (AR && AR->getLoop() == L)
8710b57cec5SDimitry Andric     return true;
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   return false;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric /// Iteratively perform simplification on a worklist of users
8770b57cec5SDimitry Andric /// of the specified induction variable. Each successive simplification may push
8780b57cec5SDimitry Andric /// more users which may themselves be candidates for simplification.
8790b57cec5SDimitry Andric ///
8800b57cec5SDimitry Andric /// This algorithm does not require IVUsers analysis. Instead, it simplifies
8810b57cec5SDimitry Andric /// instructions in-place during analysis. Rather than rewriting induction
8820b57cec5SDimitry Andric /// variables bottom-up from their users, it transforms a chain of IVUsers
8830b57cec5SDimitry Andric /// top-down, updating the IR only when it encounters a clear optimization
8840b57cec5SDimitry Andric /// opportunity.
8850b57cec5SDimitry Andric ///
8860b57cec5SDimitry Andric /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
8870b57cec5SDimitry Andric ///
simplifyUsers(PHINode * CurrIV,IVVisitor * V)8880b57cec5SDimitry Andric void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
8890b57cec5SDimitry Andric   if (!SE->isSCEVable(CurrIV->getType()))
8900b57cec5SDimitry Andric     return;
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   // Instructions processed by SimplifyIndvar for CurrIV.
8930b57cec5SDimitry Andric   SmallPtrSet<Instruction*,16> Simplified;
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric   // Use-def pairs if IV users waiting to be processed for CurrIV.
8960b57cec5SDimitry Andric   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
8990b57cec5SDimitry Andric   // called multiple times for the same LoopPhi. This is the proper thing to
9000b57cec5SDimitry Andric   // do for loop header phis that use each other.
9010b57cec5SDimitry Andric   pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric   while (!SimpleIVUsers.empty()) {
9040b57cec5SDimitry Andric     std::pair<Instruction*, Instruction*> UseOper =
9050b57cec5SDimitry Andric       SimpleIVUsers.pop_back_val();
9060b57cec5SDimitry Andric     Instruction *UseInst = UseOper.first;
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric     // If a user of the IndVar is trivially dead, we prefer just to mark it dead
9090b57cec5SDimitry Andric     // rather than try to do some complex analysis or transformation (such as
9100b57cec5SDimitry Andric     // widening) basing on it.
9110b57cec5SDimitry Andric     // TODO: Propagate TLI and pass it here to handle more cases.
9120b57cec5SDimitry Andric     if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
9130b57cec5SDimitry Andric       DeadInsts.emplace_back(UseInst);
9140b57cec5SDimitry Andric       continue;
9150b57cec5SDimitry Andric     }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric     // Bypass back edges to avoid extra work.
9180b57cec5SDimitry Andric     if (UseInst == CurrIV) continue;
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric     // Try to replace UseInst with a loop invariant before any other
9210b57cec5SDimitry Andric     // simplifications.
9220b57cec5SDimitry Andric     if (replaceIVUserWithLoopInvariant(UseInst))
9230b57cec5SDimitry Andric       continue;
9240b57cec5SDimitry Andric 
925c9157d92SDimitry Andric     // Go further for the bitcast 'prtoint ptr to i64' or if the cast is done
926c9157d92SDimitry Andric     // by truncation
927c9157d92SDimitry Andric     if ((isa<PtrToIntInst>(UseInst)) || (isa<TruncInst>(UseInst)))
928fe013be4SDimitry Andric       for (Use &U : UseInst->uses()) {
929fe013be4SDimitry Andric         Instruction *User = cast<Instruction>(U.getUser());
930fe013be4SDimitry Andric         if (replaceIVUserWithLoopInvariant(User))
931fe013be4SDimitry Andric           break; // done replacing
932fe013be4SDimitry Andric       }
933fe013be4SDimitry Andric 
9340b57cec5SDimitry Andric     Instruction *IVOperand = UseOper.second;
9350b57cec5SDimitry Andric     for (unsigned N = 0; IVOperand; ++N) {
9360b57cec5SDimitry Andric       assert(N <= Simplified.size() && "runaway iteration");
93781ad6265SDimitry Andric       (void) N;
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric       Value *NewOper = foldIVUser(UseInst, IVOperand);
9400b57cec5SDimitry Andric       if (!NewOper)
9410b57cec5SDimitry Andric         break; // done folding
9420b57cec5SDimitry Andric       IVOperand = dyn_cast<Instruction>(NewOper);
9430b57cec5SDimitry Andric     }
9440b57cec5SDimitry Andric     if (!IVOperand)
9450b57cec5SDimitry Andric       continue;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric     if (eliminateIVUser(UseInst, IVOperand)) {
9480b57cec5SDimitry Andric       pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
9490b57cec5SDimitry Andric       continue;
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
953fe013be4SDimitry Andric       if (strengthenBinaryOp(BO, IVOperand)) {
9540b57cec5SDimitry Andric         // re-queue uses of the now modified binary operator and fall
9550b57cec5SDimitry Andric         // through to the checks that remain.
9560b57cec5SDimitry Andric         pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
9570b57cec5SDimitry Andric       }
9580b57cec5SDimitry Andric     }
9590b57cec5SDimitry Andric 
960753f127fSDimitry Andric     // Try to use integer induction for FPToSI of float induction directly.
961753f127fSDimitry Andric     if (replaceFloatIVWithIntegerIV(UseInst)) {
962753f127fSDimitry Andric       // Re-queue the potentially new direct uses of IVOperand.
963753f127fSDimitry Andric       pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
964753f127fSDimitry Andric       continue;
965753f127fSDimitry Andric     }
966753f127fSDimitry Andric 
9670b57cec5SDimitry Andric     CastInst *Cast = dyn_cast<CastInst>(UseInst);
9680b57cec5SDimitry Andric     if (V && Cast) {
9690b57cec5SDimitry Andric       V->visitCast(Cast);
9700b57cec5SDimitry Andric       continue;
9710b57cec5SDimitry Andric     }
9720b57cec5SDimitry Andric     if (isSimpleIVUser(UseInst, L, SE)) {
9730b57cec5SDimitry Andric       pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
9740b57cec5SDimitry Andric     }
9750b57cec5SDimitry Andric   }
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric namespace llvm {
9790b57cec5SDimitry Andric 
anchor()9800b57cec5SDimitry Andric void IVVisitor::anchor() { }
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric /// Simplify instructions that use this induction variable
9830b57cec5SDimitry Andric /// by using ScalarEvolution to analyze the IV's recurrence.
simplifyUsersOfIV(PHINode * CurrIV,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,const TargetTransformInfo * TTI,SmallVectorImpl<WeakTrackingVH> & Dead,SCEVExpander & Rewriter,IVVisitor * V)9840b57cec5SDimitry Andric bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
9855ffd83dbSDimitry Andric                        LoopInfo *LI, const TargetTransformInfo *TTI,
9865ffd83dbSDimitry Andric                        SmallVectorImpl<WeakTrackingVH> &Dead,
9870b57cec5SDimitry Andric                        SCEVExpander &Rewriter, IVVisitor *V) {
9885ffd83dbSDimitry Andric   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI,
9895ffd83dbSDimitry Andric                      Rewriter, Dead);
9900b57cec5SDimitry Andric   SIV.simplifyUsers(CurrIV, V);
9910b57cec5SDimitry Andric   return SIV.hasChanged();
9920b57cec5SDimitry Andric }
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric /// Simplify users of induction variables within this
9950b57cec5SDimitry Andric /// loop. This does not actually change or add IVs.
simplifyLoopIVs(Loop * L,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,const TargetTransformInfo * TTI,SmallVectorImpl<WeakTrackingVH> & Dead)9960b57cec5SDimitry Andric bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
9975ffd83dbSDimitry Andric                      LoopInfo *LI, const TargetTransformInfo *TTI,
9985ffd83dbSDimitry Andric                      SmallVectorImpl<WeakTrackingVH> &Dead) {
9990b57cec5SDimitry Andric   SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
10000b57cec5SDimitry Andric #ifndef NDEBUG
10010b57cec5SDimitry Andric   Rewriter.setDebugType(DEBUG_TYPE);
10020b57cec5SDimitry Andric #endif
10030b57cec5SDimitry Andric   bool Changed = false;
10040b57cec5SDimitry Andric   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
10055ffd83dbSDimitry Andric     Changed |=
10065ffd83dbSDimitry Andric         simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter);
10070b57cec5SDimitry Andric   }
10080b57cec5SDimitry Andric   return Changed;
10090b57cec5SDimitry Andric }
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric } // namespace llvm
1012e8d8bef9SDimitry Andric 
1013349cc55cSDimitry Andric namespace {
1014e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1015e8d8bef9SDimitry Andric // Widen Induction Variables - Extend the width of an IV to cover its
1016e8d8bef9SDimitry Andric // widest uses.
1017e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
1018e8d8bef9SDimitry Andric 
1019e8d8bef9SDimitry Andric class WidenIV {
1020e8d8bef9SDimitry Andric   // Parameters
1021e8d8bef9SDimitry Andric   PHINode *OrigPhi;
1022e8d8bef9SDimitry Andric   Type *WideType;
1023e8d8bef9SDimitry Andric 
1024e8d8bef9SDimitry Andric   // Context
1025e8d8bef9SDimitry Andric   LoopInfo        *LI;
1026e8d8bef9SDimitry Andric   Loop            *L;
1027e8d8bef9SDimitry Andric   ScalarEvolution *SE;
1028e8d8bef9SDimitry Andric   DominatorTree   *DT;
1029e8d8bef9SDimitry Andric 
1030e8d8bef9SDimitry Andric   // Does the module have any calls to the llvm.experimental.guard intrinsic
1031e8d8bef9SDimitry Andric   // at all? If not we can avoid scanning instructions looking for guards.
1032e8d8bef9SDimitry Andric   bool HasGuards;
1033e8d8bef9SDimitry Andric 
1034e8d8bef9SDimitry Andric   bool UsePostIncrementRanges;
1035e8d8bef9SDimitry Andric 
1036e8d8bef9SDimitry Andric   // Statistics
1037e8d8bef9SDimitry Andric   unsigned NumElimExt = 0;
1038e8d8bef9SDimitry Andric   unsigned NumWidened = 0;
1039e8d8bef9SDimitry Andric 
1040e8d8bef9SDimitry Andric   // Result
1041e8d8bef9SDimitry Andric   PHINode *WidePhi = nullptr;
1042e8d8bef9SDimitry Andric   Instruction *WideInc = nullptr;
1043e8d8bef9SDimitry Andric   const SCEV *WideIncExpr = nullptr;
1044e8d8bef9SDimitry Andric   SmallVectorImpl<WeakTrackingVH> &DeadInsts;
1045e8d8bef9SDimitry Andric 
1046e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *,16> Widened;
1047e8d8bef9SDimitry Andric 
1048fcaf7f86SDimitry Andric   enum class ExtendKind { Zero, Sign, Unknown };
1049e8d8bef9SDimitry Andric 
1050e8d8bef9SDimitry Andric   // A map tracking the kind of extension used to widen each narrow IV
1051e8d8bef9SDimitry Andric   // and narrow IV user.
1052e8d8bef9SDimitry Andric   // Key: pointer to a narrow IV or IV user.
1053e8d8bef9SDimitry Andric   // Value: the kind of extension used to widen this Instruction.
1054e8d8bef9SDimitry Andric   DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
1055e8d8bef9SDimitry Andric 
1056e8d8bef9SDimitry Andric   using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
1057e8d8bef9SDimitry Andric 
1058e8d8bef9SDimitry Andric   // A map with control-dependent ranges for post increment IV uses. The key is
1059e8d8bef9SDimitry Andric   // a pair of IV def and a use of this def denoting the context. The value is
1060e8d8bef9SDimitry Andric   // a ConstantRange representing possible values of the def at the given
1061e8d8bef9SDimitry Andric   // context.
1062e8d8bef9SDimitry Andric   DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
1063e8d8bef9SDimitry Andric 
getPostIncRangeInfo(Value * Def,Instruction * UseI)1064bdd1243dSDimitry Andric   std::optional<ConstantRange> getPostIncRangeInfo(Value *Def,
1065e8d8bef9SDimitry Andric                                                    Instruction *UseI) {
1066e8d8bef9SDimitry Andric     DefUserPair Key(Def, UseI);
1067e8d8bef9SDimitry Andric     auto It = PostIncRangeInfos.find(Key);
1068e8d8bef9SDimitry Andric     return It == PostIncRangeInfos.end()
1069bdd1243dSDimitry Andric                ? std::optional<ConstantRange>(std::nullopt)
1070bdd1243dSDimitry Andric                : std::optional<ConstantRange>(It->second);
1071e8d8bef9SDimitry Andric   }
1072e8d8bef9SDimitry Andric 
1073e8d8bef9SDimitry Andric   void calculatePostIncRanges(PHINode *OrigPhi);
1074e8d8bef9SDimitry Andric   void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
1075e8d8bef9SDimitry Andric 
updatePostIncRangeInfo(Value * Def,Instruction * UseI,ConstantRange R)1076e8d8bef9SDimitry Andric   void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
1077e8d8bef9SDimitry Andric     DefUserPair Key(Def, UseI);
1078e8d8bef9SDimitry Andric     auto It = PostIncRangeInfos.find(Key);
1079e8d8bef9SDimitry Andric     if (It == PostIncRangeInfos.end())
1080e8d8bef9SDimitry Andric       PostIncRangeInfos.insert({Key, R});
1081e8d8bef9SDimitry Andric     else
1082e8d8bef9SDimitry Andric       It->second = R.intersectWith(It->second);
1083e8d8bef9SDimitry Andric   }
1084e8d8bef9SDimitry Andric 
1085e8d8bef9SDimitry Andric public:
1086e8d8bef9SDimitry Andric   /// Record a link in the Narrow IV def-use chain along with the WideIV that
1087e8d8bef9SDimitry Andric   /// computes the same value as the Narrow IV def.  This avoids caching Use*
1088e8d8bef9SDimitry Andric   /// pointers.
1089e8d8bef9SDimitry Andric   struct NarrowIVDefUse {
1090e8d8bef9SDimitry Andric     Instruction *NarrowDef = nullptr;
1091e8d8bef9SDimitry Andric     Instruction *NarrowUse = nullptr;
1092e8d8bef9SDimitry Andric     Instruction *WideDef = nullptr;
1093e8d8bef9SDimitry Andric 
1094e8d8bef9SDimitry Andric     // True if the narrow def is never negative.  Tracking this information lets
1095e8d8bef9SDimitry Andric     // us use a sign extension instead of a zero extension or vice versa, when
1096e8d8bef9SDimitry Andric     // profitable and legal.
1097e8d8bef9SDimitry Andric     bool NeverNegative = false;
1098e8d8bef9SDimitry Andric 
NarrowIVDefUse__anoncf1033750311::WidenIV::NarrowIVDefUse1099e8d8bef9SDimitry Andric     NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
1100e8d8bef9SDimitry Andric                    bool NeverNegative)
1101e8d8bef9SDimitry Andric         : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
1102e8d8bef9SDimitry Andric           NeverNegative(NeverNegative) {}
1103e8d8bef9SDimitry Andric   };
1104e8d8bef9SDimitry Andric 
1105e8d8bef9SDimitry Andric   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1106e8d8bef9SDimitry Andric           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1107e8d8bef9SDimitry Andric           bool HasGuards, bool UsePostIncrementRanges = true);
1108e8d8bef9SDimitry Andric 
1109e8d8bef9SDimitry Andric   PHINode *createWideIV(SCEVExpander &Rewriter);
1110e8d8bef9SDimitry Andric 
getNumElimExt()1111e8d8bef9SDimitry Andric   unsigned getNumElimExt() { return NumElimExt; };
getNumWidened()1112e8d8bef9SDimitry Andric   unsigned getNumWidened() { return NumWidened; };
1113e8d8bef9SDimitry Andric 
1114e8d8bef9SDimitry Andric protected:
1115e8d8bef9SDimitry Andric   Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
1116e8d8bef9SDimitry Andric                           Instruction *Use);
1117e8d8bef9SDimitry Andric 
1118e8d8bef9SDimitry Andric   Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1119e8d8bef9SDimitry Andric   Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1120e8d8bef9SDimitry Andric                                      const SCEVAddRecExpr *WideAR);
1121e8d8bef9SDimitry Andric   Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1122e8d8bef9SDimitry Andric 
1123e8d8bef9SDimitry Andric   ExtendKind getExtendKind(Instruction *I);
1124e8d8bef9SDimitry Andric 
1125e8d8bef9SDimitry Andric   using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1126e8d8bef9SDimitry Andric 
1127e8d8bef9SDimitry Andric   WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1128e8d8bef9SDimitry Andric 
1129e8d8bef9SDimitry Andric   WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1130e8d8bef9SDimitry Andric 
1131e8d8bef9SDimitry Andric   const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1132e8d8bef9SDimitry Andric                               unsigned OpCode) const;
1133e8d8bef9SDimitry Andric 
1134e8d8bef9SDimitry Andric   Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
1135e8d8bef9SDimitry Andric 
1136e8d8bef9SDimitry Andric   bool widenLoopCompare(NarrowIVDefUse DU);
1137e8d8bef9SDimitry Andric   bool widenWithVariantUse(NarrowIVDefUse DU);
1138e8d8bef9SDimitry Andric 
1139e8d8bef9SDimitry Andric   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1140e8d8bef9SDimitry Andric 
1141e8d8bef9SDimitry Andric private:
1142e8d8bef9SDimitry Andric   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
1143e8d8bef9SDimitry Andric };
1144349cc55cSDimitry Andric } // namespace
1145e8d8bef9SDimitry Andric 
1146e8d8bef9SDimitry Andric /// Determine the insertion point for this user. By default, insert immediately
1147e8d8bef9SDimitry Andric /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
1148e8d8bef9SDimitry Andric /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
1149e8d8bef9SDimitry Andric /// common dominator for the incoming blocks. A nullptr can be returned if no
1150e8d8bef9SDimitry Andric /// viable location is found: it may happen if User is a PHI and Def only comes
1151e8d8bef9SDimitry Andric /// to this PHI from unreachable blocks.
getInsertPointForUses(Instruction * User,Value * Def,DominatorTree * DT,LoopInfo * LI)1152e8d8bef9SDimitry Andric static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
1153e8d8bef9SDimitry Andric                                           DominatorTree *DT, LoopInfo *LI) {
1154e8d8bef9SDimitry Andric   PHINode *PHI = dyn_cast<PHINode>(User);
1155e8d8bef9SDimitry Andric   if (!PHI)
1156e8d8bef9SDimitry Andric     return User;
1157e8d8bef9SDimitry Andric 
1158e8d8bef9SDimitry Andric   Instruction *InsertPt = nullptr;
1159e8d8bef9SDimitry Andric   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
1160e8d8bef9SDimitry Andric     if (PHI->getIncomingValue(i) != Def)
1161e8d8bef9SDimitry Andric       continue;
1162e8d8bef9SDimitry Andric 
1163e8d8bef9SDimitry Andric     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
1164e8d8bef9SDimitry Andric 
1165e8d8bef9SDimitry Andric     if (!DT->isReachableFromEntry(InsertBB))
1166e8d8bef9SDimitry Andric       continue;
1167e8d8bef9SDimitry Andric 
1168e8d8bef9SDimitry Andric     if (!InsertPt) {
1169e8d8bef9SDimitry Andric       InsertPt = InsertBB->getTerminator();
1170e8d8bef9SDimitry Andric       continue;
1171e8d8bef9SDimitry Andric     }
1172e8d8bef9SDimitry Andric     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
1173e8d8bef9SDimitry Andric     InsertPt = InsertBB->getTerminator();
1174e8d8bef9SDimitry Andric   }
1175e8d8bef9SDimitry Andric 
1176e8d8bef9SDimitry Andric   // If we have skipped all inputs, it means that Def only comes to Phi from
1177e8d8bef9SDimitry Andric   // unreachable blocks.
1178e8d8bef9SDimitry Andric   if (!InsertPt)
1179e8d8bef9SDimitry Andric     return nullptr;
1180e8d8bef9SDimitry Andric 
1181e8d8bef9SDimitry Andric   auto *DefI = dyn_cast<Instruction>(Def);
1182e8d8bef9SDimitry Andric   if (!DefI)
1183e8d8bef9SDimitry Andric     return InsertPt;
1184e8d8bef9SDimitry Andric 
1185e8d8bef9SDimitry Andric   assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
1186e8d8bef9SDimitry Andric 
1187e8d8bef9SDimitry Andric   auto *L = LI->getLoopFor(DefI->getParent());
1188e8d8bef9SDimitry Andric   assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
1189e8d8bef9SDimitry Andric 
1190e8d8bef9SDimitry Andric   for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
1191e8d8bef9SDimitry Andric     if (LI->getLoopFor(DTN->getBlock()) == L)
1192e8d8bef9SDimitry Andric       return DTN->getBlock()->getTerminator();
1193e8d8bef9SDimitry Andric 
1194e8d8bef9SDimitry Andric   llvm_unreachable("DefI dominates InsertPt!");
1195e8d8bef9SDimitry Andric }
1196e8d8bef9SDimitry Andric 
WidenIV(const WideIVInfo & WI,LoopInfo * LInfo,ScalarEvolution * SEv,DominatorTree * DTree,SmallVectorImpl<WeakTrackingVH> & DI,bool HasGuards,bool UsePostIncrementRanges)1197e8d8bef9SDimitry Andric WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1198e8d8bef9SDimitry Andric           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1199e8d8bef9SDimitry Andric           bool HasGuards, bool UsePostIncrementRanges)
1200e8d8bef9SDimitry Andric       : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1201e8d8bef9SDimitry Andric         L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
1202e8d8bef9SDimitry Andric         HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
1203e8d8bef9SDimitry Andric         DeadInsts(DI) {
1204e8d8bef9SDimitry Andric     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
1205fcaf7f86SDimitry Andric     ExtendKindMap[OrigPhi] = WI.IsSigned ? ExtendKind::Sign : ExtendKind::Zero;
1206e8d8bef9SDimitry Andric }
1207e8d8bef9SDimitry Andric 
createExtendInst(Value * NarrowOper,Type * WideType,bool IsSigned,Instruction * Use)1208e8d8bef9SDimitry Andric Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1209e8d8bef9SDimitry Andric                                  bool IsSigned, Instruction *Use) {
1210e8d8bef9SDimitry Andric   // Set the debug location and conservative insertion point.
1211e8d8bef9SDimitry Andric   IRBuilder<> Builder(Use);
1212e8d8bef9SDimitry Andric   // Hoist the insertion point into loop preheaders as far as possible.
1213e8d8bef9SDimitry Andric   for (const Loop *L = LI->getLoopFor(Use->getParent());
1214e8d8bef9SDimitry Andric        L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
1215e8d8bef9SDimitry Andric        L = L->getParentLoop())
1216e8d8bef9SDimitry Andric     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1217e8d8bef9SDimitry Andric 
1218e8d8bef9SDimitry Andric   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1219e8d8bef9SDimitry Andric                     Builder.CreateZExt(NarrowOper, WideType);
1220e8d8bef9SDimitry Andric }
1221e8d8bef9SDimitry Andric 
1222e8d8bef9SDimitry Andric /// Instantiate a wide operation to replace a narrow operation. This only needs
1223e8d8bef9SDimitry Andric /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1224e8d8bef9SDimitry Andric /// 0 for any operation we decide not to clone.
cloneIVUser(WidenIV::NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1225e8d8bef9SDimitry Andric Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
1226e8d8bef9SDimitry Andric                                   const SCEVAddRecExpr *WideAR) {
1227e8d8bef9SDimitry Andric   unsigned Opcode = DU.NarrowUse->getOpcode();
1228e8d8bef9SDimitry Andric   switch (Opcode) {
1229e8d8bef9SDimitry Andric   default:
1230e8d8bef9SDimitry Andric     return nullptr;
1231e8d8bef9SDimitry Andric   case Instruction::Add:
1232e8d8bef9SDimitry Andric   case Instruction::Mul:
1233e8d8bef9SDimitry Andric   case Instruction::UDiv:
1234e8d8bef9SDimitry Andric   case Instruction::Sub:
1235e8d8bef9SDimitry Andric     return cloneArithmeticIVUser(DU, WideAR);
1236e8d8bef9SDimitry Andric 
1237e8d8bef9SDimitry Andric   case Instruction::And:
1238e8d8bef9SDimitry Andric   case Instruction::Or:
1239e8d8bef9SDimitry Andric   case Instruction::Xor:
1240e8d8bef9SDimitry Andric   case Instruction::Shl:
1241e8d8bef9SDimitry Andric   case Instruction::LShr:
1242e8d8bef9SDimitry Andric   case Instruction::AShr:
1243e8d8bef9SDimitry Andric     return cloneBitwiseIVUser(DU);
1244e8d8bef9SDimitry Andric   }
1245e8d8bef9SDimitry Andric }
1246e8d8bef9SDimitry Andric 
cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU)1247e8d8bef9SDimitry Andric Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
1248e8d8bef9SDimitry Andric   Instruction *NarrowUse = DU.NarrowUse;
1249e8d8bef9SDimitry Andric   Instruction *NarrowDef = DU.NarrowDef;
1250e8d8bef9SDimitry Andric   Instruction *WideDef = DU.WideDef;
1251e8d8bef9SDimitry Andric 
1252e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1253e8d8bef9SDimitry Andric 
1254e8d8bef9SDimitry Andric   // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1255e8d8bef9SDimitry Andric   // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1256e8d8bef9SDimitry Andric   // invariant and will be folded or hoisted. If it actually comes from a
1257e8d8bef9SDimitry Andric   // widened IV, it should be removed during a future call to widenIVUse.
1258fcaf7f86SDimitry Andric   bool IsSigned = getExtendKind(NarrowDef) == ExtendKind::Sign;
1259e8d8bef9SDimitry Andric   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1260e8d8bef9SDimitry Andric                    ? WideDef
1261e8d8bef9SDimitry Andric                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1262e8d8bef9SDimitry Andric                                       IsSigned, NarrowUse);
1263e8d8bef9SDimitry Andric   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1264e8d8bef9SDimitry Andric                    ? WideDef
1265e8d8bef9SDimitry Andric                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1266e8d8bef9SDimitry Andric                                       IsSigned, NarrowUse);
1267e8d8bef9SDimitry Andric 
1268e8d8bef9SDimitry Andric   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1269e8d8bef9SDimitry Andric   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1270e8d8bef9SDimitry Andric                                         NarrowBO->getName());
1271e8d8bef9SDimitry Andric   IRBuilder<> Builder(NarrowUse);
1272e8d8bef9SDimitry Andric   Builder.Insert(WideBO);
1273e8d8bef9SDimitry Andric   WideBO->copyIRFlags(NarrowBO);
1274e8d8bef9SDimitry Andric   return WideBO;
1275e8d8bef9SDimitry Andric }
1276e8d8bef9SDimitry Andric 
cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1277e8d8bef9SDimitry Andric Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
1278e8d8bef9SDimitry Andric                                             const SCEVAddRecExpr *WideAR) {
1279e8d8bef9SDimitry Andric   Instruction *NarrowUse = DU.NarrowUse;
1280e8d8bef9SDimitry Andric   Instruction *NarrowDef = DU.NarrowDef;
1281e8d8bef9SDimitry Andric   Instruction *WideDef = DU.WideDef;
1282e8d8bef9SDimitry Andric 
1283e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1284e8d8bef9SDimitry Andric 
1285e8d8bef9SDimitry Andric   unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1286e8d8bef9SDimitry Andric 
1287e8d8bef9SDimitry Andric   // We're trying to find X such that
1288e8d8bef9SDimitry Andric   //
1289e8d8bef9SDimitry Andric   //  Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1290e8d8bef9SDimitry Andric   //
1291e8d8bef9SDimitry Andric   // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1292e8d8bef9SDimitry Andric   // and check using SCEV if any of them are correct.
1293e8d8bef9SDimitry Andric 
1294e8d8bef9SDimitry Andric   // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1295e8d8bef9SDimitry Andric   // correct solution to X.
1296e8d8bef9SDimitry Andric   auto GuessNonIVOperand = [&](bool SignExt) {
1297e8d8bef9SDimitry Andric     const SCEV *WideLHS;
1298e8d8bef9SDimitry Andric     const SCEV *WideRHS;
1299e8d8bef9SDimitry Andric 
1300e8d8bef9SDimitry Andric     auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1301e8d8bef9SDimitry Andric       if (SignExt)
1302e8d8bef9SDimitry Andric         return SE->getSignExtendExpr(S, Ty);
1303e8d8bef9SDimitry Andric       return SE->getZeroExtendExpr(S, Ty);
1304e8d8bef9SDimitry Andric     };
1305e8d8bef9SDimitry Andric 
1306e8d8bef9SDimitry Andric     if (IVOpIdx == 0) {
1307e8d8bef9SDimitry Andric       WideLHS = SE->getSCEV(WideDef);
1308e8d8bef9SDimitry Andric       const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1309e8d8bef9SDimitry Andric       WideRHS = GetExtend(NarrowRHS, WideType);
1310e8d8bef9SDimitry Andric     } else {
1311e8d8bef9SDimitry Andric       const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1312e8d8bef9SDimitry Andric       WideLHS = GetExtend(NarrowLHS, WideType);
1313e8d8bef9SDimitry Andric       WideRHS = SE->getSCEV(WideDef);
1314e8d8bef9SDimitry Andric     }
1315e8d8bef9SDimitry Andric 
1316e8d8bef9SDimitry Andric     // WideUse is "WideDef `op.wide` X" as described in the comment.
1317e8d8bef9SDimitry Andric     const SCEV *WideUse =
1318e8d8bef9SDimitry Andric       getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode());
1319e8d8bef9SDimitry Andric 
1320e8d8bef9SDimitry Andric     return WideUse == WideAR;
1321e8d8bef9SDimitry Andric   };
1322e8d8bef9SDimitry Andric 
1323fcaf7f86SDimitry Andric   bool SignExtend = getExtendKind(NarrowDef) == ExtendKind::Sign;
1324e8d8bef9SDimitry Andric   if (!GuessNonIVOperand(SignExtend)) {
1325e8d8bef9SDimitry Andric     SignExtend = !SignExtend;
1326e8d8bef9SDimitry Andric     if (!GuessNonIVOperand(SignExtend))
1327e8d8bef9SDimitry Andric       return nullptr;
1328e8d8bef9SDimitry Andric   }
1329e8d8bef9SDimitry Andric 
1330e8d8bef9SDimitry Andric   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1331e8d8bef9SDimitry Andric                    ? WideDef
1332e8d8bef9SDimitry Andric                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1333e8d8bef9SDimitry Andric                                       SignExtend, NarrowUse);
1334e8d8bef9SDimitry Andric   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1335e8d8bef9SDimitry Andric                    ? WideDef
1336e8d8bef9SDimitry Andric                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1337e8d8bef9SDimitry Andric                                       SignExtend, NarrowUse);
1338e8d8bef9SDimitry Andric 
1339e8d8bef9SDimitry Andric   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1340e8d8bef9SDimitry Andric   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1341e8d8bef9SDimitry Andric                                         NarrowBO->getName());
1342e8d8bef9SDimitry Andric 
1343e8d8bef9SDimitry Andric   IRBuilder<> Builder(NarrowUse);
1344e8d8bef9SDimitry Andric   Builder.Insert(WideBO);
1345e8d8bef9SDimitry Andric   WideBO->copyIRFlags(NarrowBO);
1346e8d8bef9SDimitry Andric   return WideBO;
1347e8d8bef9SDimitry Andric }
1348e8d8bef9SDimitry Andric 
getExtendKind(Instruction * I)1349e8d8bef9SDimitry Andric WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1350e8d8bef9SDimitry Andric   auto It = ExtendKindMap.find(I);
1351e8d8bef9SDimitry Andric   assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1352e8d8bef9SDimitry Andric   return It->second;
1353e8d8bef9SDimitry Andric }
1354e8d8bef9SDimitry Andric 
getSCEVByOpCode(const SCEV * LHS,const SCEV * RHS,unsigned OpCode) const1355e8d8bef9SDimitry Andric const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1356e8d8bef9SDimitry Andric                                      unsigned OpCode) const {
1357e8d8bef9SDimitry Andric   switch (OpCode) {
1358e8d8bef9SDimitry Andric   case Instruction::Add:
1359e8d8bef9SDimitry Andric     return SE->getAddExpr(LHS, RHS);
1360e8d8bef9SDimitry Andric   case Instruction::Sub:
1361e8d8bef9SDimitry Andric     return SE->getMinusSCEV(LHS, RHS);
1362e8d8bef9SDimitry Andric   case Instruction::Mul:
1363e8d8bef9SDimitry Andric     return SE->getMulExpr(LHS, RHS);
1364e8d8bef9SDimitry Andric   case Instruction::UDiv:
1365e8d8bef9SDimitry Andric     return SE->getUDivExpr(LHS, RHS);
1366e8d8bef9SDimitry Andric   default:
1367e8d8bef9SDimitry Andric     llvm_unreachable("Unsupported opcode.");
1368e8d8bef9SDimitry Andric   };
1369e8d8bef9SDimitry Andric }
1370e8d8bef9SDimitry Andric 
1371e8d8bef9SDimitry Andric /// No-wrap operations can transfer sign extension of their result to their
1372e8d8bef9SDimitry Andric /// operands. Generate the SCEV value for the widened operation without
1373e8d8bef9SDimitry Andric /// actually modifying the IR yet. If the expression after extending the
1374e8d8bef9SDimitry Andric /// operands is an AddRec for this loop, return the AddRec and the kind of
1375e8d8bef9SDimitry Andric /// extension used.
1376e8d8bef9SDimitry Andric WidenIV::WidenedRecTy
getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU)1377e8d8bef9SDimitry Andric WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
1378e8d8bef9SDimitry Andric   // Handle the common case of add<nsw/nuw>
1379e8d8bef9SDimitry Andric   const unsigned OpCode = DU.NarrowUse->getOpcode();
1380e8d8bef9SDimitry Andric   // Only Add/Sub/Mul instructions supported yet.
1381e8d8bef9SDimitry Andric   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1382e8d8bef9SDimitry Andric       OpCode != Instruction::Mul)
1383fcaf7f86SDimitry Andric     return {nullptr, ExtendKind::Unknown};
1384e8d8bef9SDimitry Andric 
1385e8d8bef9SDimitry Andric   // One operand (NarrowDef) has already been extended to WideDef. Now determine
1386e8d8bef9SDimitry Andric   // if extending the other will lead to a recurrence.
1387e8d8bef9SDimitry Andric   const unsigned ExtendOperIdx =
1388e8d8bef9SDimitry Andric       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1389e8d8bef9SDimitry Andric   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1390e8d8bef9SDimitry Andric 
1391e8d8bef9SDimitry Andric   const OverflowingBinaryOperator *OBO =
1392e8d8bef9SDimitry Andric     cast<OverflowingBinaryOperator>(DU.NarrowUse);
1393e8d8bef9SDimitry Andric   ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1394c9157d92SDimitry Andric   if (!(ExtKind == ExtendKind::Sign && OBO->hasNoSignedWrap()) &&
1395c9157d92SDimitry Andric       !(ExtKind == ExtendKind::Zero && OBO->hasNoUnsignedWrap())) {
1396c9157d92SDimitry Andric     ExtKind = ExtendKind::Unknown;
1397c9157d92SDimitry Andric 
1398c9157d92SDimitry Andric     // For a non-negative NarrowDef, we can choose either type of
1399c9157d92SDimitry Andric     // extension.  We want to use the current extend kind if legal
1400c9157d92SDimitry Andric     // (see above), and we only hit this code if we need to check
1401c9157d92SDimitry Andric     // the opposite case.
1402c9157d92SDimitry Andric     if (DU.NeverNegative) {
1403c9157d92SDimitry Andric       if (OBO->hasNoSignedWrap()) {
1404c9157d92SDimitry Andric         ExtKind = ExtendKind::Sign;
1405c9157d92SDimitry Andric       } else if (OBO->hasNoUnsignedWrap()) {
1406c9157d92SDimitry Andric         ExtKind = ExtendKind::Zero;
1407c9157d92SDimitry Andric       }
1408c9157d92SDimitry Andric     }
1409c9157d92SDimitry Andric   }
1410c9157d92SDimitry Andric 
1411c9157d92SDimitry Andric   const SCEV *ExtendOperExpr =
1412c9157d92SDimitry Andric       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx));
1413c9157d92SDimitry Andric   if (ExtKind == ExtendKind::Sign)
1414c9157d92SDimitry Andric     ExtendOperExpr = SE->getSignExtendExpr(ExtendOperExpr, WideType);
1415c9157d92SDimitry Andric   else if (ExtKind == ExtendKind::Zero)
1416c9157d92SDimitry Andric     ExtendOperExpr = SE->getZeroExtendExpr(ExtendOperExpr, WideType);
1417e8d8bef9SDimitry Andric   else
1418fcaf7f86SDimitry Andric     return {nullptr, ExtendKind::Unknown};
1419e8d8bef9SDimitry Andric 
1420e8d8bef9SDimitry Andric   // When creating this SCEV expr, don't apply the current operations NSW or NUW
1421e8d8bef9SDimitry Andric   // flags. This instruction may be guarded by control flow that the no-wrap
1422e8d8bef9SDimitry Andric   // behavior depends on. Non-control-equivalent instructions can be mapped to
1423e8d8bef9SDimitry Andric   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1424e8d8bef9SDimitry Andric   // semantics to those operations.
1425e8d8bef9SDimitry Andric   const SCEV *lhs = SE->getSCEV(DU.WideDef);
1426e8d8bef9SDimitry Andric   const SCEV *rhs = ExtendOperExpr;
1427e8d8bef9SDimitry Andric 
1428e8d8bef9SDimitry Andric   // Let's swap operands to the initial order for the case of non-commutative
1429e8d8bef9SDimitry Andric   // operations, like SUB. See PR21014.
1430e8d8bef9SDimitry Andric   if (ExtendOperIdx == 0)
1431e8d8bef9SDimitry Andric     std::swap(lhs, rhs);
1432e8d8bef9SDimitry Andric   const SCEVAddRecExpr *AddRec =
1433e8d8bef9SDimitry Andric       dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1434e8d8bef9SDimitry Andric 
1435e8d8bef9SDimitry Andric   if (!AddRec || AddRec->getLoop() != L)
1436fcaf7f86SDimitry Andric     return {nullptr, ExtendKind::Unknown};
1437e8d8bef9SDimitry Andric 
1438e8d8bef9SDimitry Andric   return {AddRec, ExtKind};
1439e8d8bef9SDimitry Andric }
1440e8d8bef9SDimitry Andric 
1441e8d8bef9SDimitry Andric /// Is this instruction potentially interesting for further simplification after
1442e8d8bef9SDimitry Andric /// widening it's type? In other words, can the extend be safely hoisted out of
1443e8d8bef9SDimitry Andric /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1444e8d8bef9SDimitry Andric /// so, return the extended recurrence and the kind of extension used. Otherwise
1445fcaf7f86SDimitry Andric /// return {nullptr, ExtendKind::Unknown}.
getWideRecurrence(WidenIV::NarrowIVDefUse DU)1446e8d8bef9SDimitry Andric WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
1447fe6060f1SDimitry Andric   if (!DU.NarrowUse->getType()->isIntegerTy())
1448fcaf7f86SDimitry Andric     return {nullptr, ExtendKind::Unknown};
1449e8d8bef9SDimitry Andric 
1450e8d8bef9SDimitry Andric   const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1451e8d8bef9SDimitry Andric   if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1452e8d8bef9SDimitry Andric       SE->getTypeSizeInBits(WideType)) {
1453e8d8bef9SDimitry Andric     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1454e8d8bef9SDimitry Andric     // index. So don't follow this use.
1455fcaf7f86SDimitry Andric     return {nullptr, ExtendKind::Unknown};
1456e8d8bef9SDimitry Andric   }
1457e8d8bef9SDimitry Andric 
1458e8d8bef9SDimitry Andric   const SCEV *WideExpr;
1459e8d8bef9SDimitry Andric   ExtendKind ExtKind;
1460e8d8bef9SDimitry Andric   if (DU.NeverNegative) {
1461e8d8bef9SDimitry Andric     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1462e8d8bef9SDimitry Andric     if (isa<SCEVAddRecExpr>(WideExpr))
1463fcaf7f86SDimitry Andric       ExtKind = ExtendKind::Sign;
1464e8d8bef9SDimitry Andric     else {
1465e8d8bef9SDimitry Andric       WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1466fcaf7f86SDimitry Andric       ExtKind = ExtendKind::Zero;
1467e8d8bef9SDimitry Andric     }
1468fcaf7f86SDimitry Andric   } else if (getExtendKind(DU.NarrowDef) == ExtendKind::Sign) {
1469e8d8bef9SDimitry Andric     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1470fcaf7f86SDimitry Andric     ExtKind = ExtendKind::Sign;
1471e8d8bef9SDimitry Andric   } else {
1472e8d8bef9SDimitry Andric     WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1473fcaf7f86SDimitry Andric     ExtKind = ExtendKind::Zero;
1474e8d8bef9SDimitry Andric   }
1475e8d8bef9SDimitry Andric   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1476e8d8bef9SDimitry Andric   if (!AddRec || AddRec->getLoop() != L)
1477fcaf7f86SDimitry Andric     return {nullptr, ExtendKind::Unknown};
1478e8d8bef9SDimitry Andric   return {AddRec, ExtKind};
1479e8d8bef9SDimitry Andric }
1480e8d8bef9SDimitry Andric 
1481e8d8bef9SDimitry Andric /// This IV user cannot be widened. Replace this use of the original narrow IV
1482e8d8bef9SDimitry Andric /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
truncateIVUse(WidenIV::NarrowIVDefUse DU,DominatorTree * DT,LoopInfo * LI)1483e8d8bef9SDimitry Andric static void truncateIVUse(WidenIV::NarrowIVDefUse DU, DominatorTree *DT,
1484e8d8bef9SDimitry Andric                           LoopInfo *LI) {
1485e8d8bef9SDimitry Andric   auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1486e8d8bef9SDimitry Andric   if (!InsertPt)
1487e8d8bef9SDimitry Andric     return;
1488e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1489e8d8bef9SDimitry Andric                     << *DU.NarrowUse << "\n");
1490e8d8bef9SDimitry Andric   IRBuilder<> Builder(InsertPt);
1491e8d8bef9SDimitry Andric   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1492e8d8bef9SDimitry Andric   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1493e8d8bef9SDimitry Andric }
1494e8d8bef9SDimitry Andric 
1495e8d8bef9SDimitry Andric /// If the narrow use is a compare instruction, then widen the compare
1496e8d8bef9SDimitry Andric //  (and possibly the other operand).  The extend operation is hoisted into the
1497e8d8bef9SDimitry Andric // loop preheader as far as possible.
widenLoopCompare(WidenIV::NarrowIVDefUse DU)1498e8d8bef9SDimitry Andric bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
1499e8d8bef9SDimitry Andric   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1500e8d8bef9SDimitry Andric   if (!Cmp)
1501e8d8bef9SDimitry Andric     return false;
1502e8d8bef9SDimitry Andric 
1503e8d8bef9SDimitry Andric   // We can legally widen the comparison in the following two cases:
1504e8d8bef9SDimitry Andric   //
1505e8d8bef9SDimitry Andric   //  - The signedness of the IV extension and comparison match
1506e8d8bef9SDimitry Andric   //
1507e8d8bef9SDimitry Andric   //  - The narrow IV is always positive (and thus its sign extension is equal
1508e8d8bef9SDimitry Andric   //    to its zero extension).  For instance, let's say we're zero extending
1509e8d8bef9SDimitry Andric   //    %narrow for the following use
1510e8d8bef9SDimitry Andric   //
1511e8d8bef9SDimitry Andric   //      icmp slt i32 %narrow, %val   ... (A)
1512e8d8bef9SDimitry Andric   //
1513e8d8bef9SDimitry Andric   //    and %narrow is always positive.  Then
1514e8d8bef9SDimitry Andric   //
1515e8d8bef9SDimitry Andric   //      (A) == icmp slt i32 sext(%narrow), sext(%val)
1516e8d8bef9SDimitry Andric   //          == icmp slt i32 zext(%narrow), sext(%val)
1517fcaf7f86SDimitry Andric   bool IsSigned = getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1518e8d8bef9SDimitry Andric   if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1519e8d8bef9SDimitry Andric     return false;
1520e8d8bef9SDimitry Andric 
1521e8d8bef9SDimitry Andric   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1522e8d8bef9SDimitry Andric   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1523e8d8bef9SDimitry Andric   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1524e8d8bef9SDimitry Andric   assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1525e8d8bef9SDimitry Andric 
1526e8d8bef9SDimitry Andric   // Widen the compare instruction.
1527e8d8bef9SDimitry Andric   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1528e8d8bef9SDimitry Andric 
1529e8d8bef9SDimitry Andric   // Widen the other operand of the compare, if necessary.
1530e8d8bef9SDimitry Andric   if (CastWidth < IVWidth) {
1531e8d8bef9SDimitry Andric     Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1532e8d8bef9SDimitry Andric     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1533e8d8bef9SDimitry Andric   }
1534e8d8bef9SDimitry Andric   return true;
1535e8d8bef9SDimitry Andric }
1536e8d8bef9SDimitry Andric 
1537e8d8bef9SDimitry Andric // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this
1538e8d8bef9SDimitry Andric // will not work when:
1539e8d8bef9SDimitry Andric //    1) SCEV traces back to an instruction inside the loop that SCEV can not
1540e8d8bef9SDimitry Andric // expand, eg. add %indvar, (load %addr)
1541e8d8bef9SDimitry Andric //    2) SCEV finds a loop variant, eg. add %indvar, %loopvariant
1542e8d8bef9SDimitry Andric // While SCEV fails to avoid trunc, we can still try to use instruction
1543e8d8bef9SDimitry Andric // combining approach to prove trunc is not required. This can be further
1544e8d8bef9SDimitry Andric // extended with other instruction combining checks, but for now we handle the
1545e8d8bef9SDimitry Andric // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext")
1546e8d8bef9SDimitry Andric //
1547e8d8bef9SDimitry Andric // Src:
1548e8d8bef9SDimitry Andric //   %c = sub nsw %b, %indvar
1549e8d8bef9SDimitry Andric //   %d = sext %c to i64
1550e8d8bef9SDimitry Andric // Dst:
1551e8d8bef9SDimitry Andric //   %indvar.ext1 = sext %indvar to i64
1552e8d8bef9SDimitry Andric //   %m = sext %b to i64
1553e8d8bef9SDimitry Andric //   %d = sub nsw i64 %m, %indvar.ext1
1554e8d8bef9SDimitry Andric // Therefore, as long as the result of add/sub/mul is extended to wide type, no
1555e8d8bef9SDimitry Andric // trunc is required regardless of how %b is generated. This pattern is common
1556e8d8bef9SDimitry Andric // when calculating address in 64 bit architecture
widenWithVariantUse(WidenIV::NarrowIVDefUse DU)1557e8d8bef9SDimitry Andric bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
1558e8d8bef9SDimitry Andric   Instruction *NarrowUse = DU.NarrowUse;
1559e8d8bef9SDimitry Andric   Instruction *NarrowDef = DU.NarrowDef;
1560e8d8bef9SDimitry Andric   Instruction *WideDef = DU.WideDef;
1561e8d8bef9SDimitry Andric 
1562e8d8bef9SDimitry Andric   // Handle the common case of add<nsw/nuw>
1563e8d8bef9SDimitry Andric   const unsigned OpCode = NarrowUse->getOpcode();
1564e8d8bef9SDimitry Andric   // Only Add/Sub/Mul instructions are supported.
1565e8d8bef9SDimitry Andric   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1566e8d8bef9SDimitry Andric       OpCode != Instruction::Mul)
1567e8d8bef9SDimitry Andric     return false;
1568e8d8bef9SDimitry Andric 
1569e8d8bef9SDimitry Andric   // The operand that is not defined by NarrowDef of DU. Let's call it the
1570e8d8bef9SDimitry Andric   // other operand.
1571e8d8bef9SDimitry Andric   assert((NarrowUse->getOperand(0) == NarrowDef ||
1572e8d8bef9SDimitry Andric           NarrowUse->getOperand(1) == NarrowDef) &&
1573e8d8bef9SDimitry Andric          "bad DU");
1574e8d8bef9SDimitry Andric 
1575e8d8bef9SDimitry Andric   const OverflowingBinaryOperator *OBO =
1576e8d8bef9SDimitry Andric     cast<OverflowingBinaryOperator>(NarrowUse);
1577e8d8bef9SDimitry Andric   ExtendKind ExtKind = getExtendKind(NarrowDef);
1578fcaf7f86SDimitry Andric   bool CanSignExtend = ExtKind == ExtendKind::Sign && OBO->hasNoSignedWrap();
1579fcaf7f86SDimitry Andric   bool CanZeroExtend = ExtKind == ExtendKind::Zero && OBO->hasNoUnsignedWrap();
1580e8d8bef9SDimitry Andric   auto AnotherOpExtKind = ExtKind;
1581e8d8bef9SDimitry Andric 
1582e8d8bef9SDimitry Andric   // Check that all uses are either:
1583e8d8bef9SDimitry Andric   // - narrow def (in case of we are widening the IV increment);
1584e8d8bef9SDimitry Andric   // - single-input LCSSA Phis;
1585e8d8bef9SDimitry Andric   // - comparison of the chosen type;
1586e8d8bef9SDimitry Andric   // - extend of the chosen type (raison d'etre).
1587e8d8bef9SDimitry Andric   SmallVector<Instruction *, 4> ExtUsers;
1588e8d8bef9SDimitry Andric   SmallVector<PHINode *, 4> LCSSAPhiUsers;
1589e8d8bef9SDimitry Andric   SmallVector<ICmpInst *, 4> ICmpUsers;
1590e8d8bef9SDimitry Andric   for (Use &U : NarrowUse->uses()) {
1591e8d8bef9SDimitry Andric     Instruction *User = cast<Instruction>(U.getUser());
1592e8d8bef9SDimitry Andric     if (User == NarrowDef)
1593e8d8bef9SDimitry Andric       continue;
1594e8d8bef9SDimitry Andric     if (!L->contains(User)) {
1595e8d8bef9SDimitry Andric       auto *LCSSAPhi = cast<PHINode>(User);
1596e8d8bef9SDimitry Andric       // Make sure there is only 1 input, so that we don't have to split
1597e8d8bef9SDimitry Andric       // critical edges.
1598e8d8bef9SDimitry Andric       if (LCSSAPhi->getNumOperands() != 1)
1599e8d8bef9SDimitry Andric         return false;
1600e8d8bef9SDimitry Andric       LCSSAPhiUsers.push_back(LCSSAPhi);
1601e8d8bef9SDimitry Andric       continue;
1602e8d8bef9SDimitry Andric     }
1603e8d8bef9SDimitry Andric     if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
1604e8d8bef9SDimitry Andric       auto Pred = ICmp->getPredicate();
1605e8d8bef9SDimitry Andric       // We have 3 types of predicates: signed, unsigned and equality
1606e8d8bef9SDimitry Andric       // predicates. For equality, it's legal to widen icmp for either sign and
1607e8d8bef9SDimitry Andric       // zero extend. For sign extend, we can also do so for signed predicates,
1608e8d8bef9SDimitry Andric       // likeweise for zero extend we can widen icmp for unsigned predicates.
1609fcaf7f86SDimitry Andric       if (ExtKind == ExtendKind::Zero && ICmpInst::isSigned(Pred))
1610e8d8bef9SDimitry Andric         return false;
1611fcaf7f86SDimitry Andric       if (ExtKind == ExtendKind::Sign && ICmpInst::isUnsigned(Pred))
1612e8d8bef9SDimitry Andric         return false;
1613e8d8bef9SDimitry Andric       ICmpUsers.push_back(ICmp);
1614e8d8bef9SDimitry Andric       continue;
1615e8d8bef9SDimitry Andric     }
1616fcaf7f86SDimitry Andric     if (ExtKind == ExtendKind::Sign)
1617e8d8bef9SDimitry Andric       User = dyn_cast<SExtInst>(User);
1618e8d8bef9SDimitry Andric     else
1619e8d8bef9SDimitry Andric       User = dyn_cast<ZExtInst>(User);
1620e8d8bef9SDimitry Andric     if (!User || User->getType() != WideType)
1621e8d8bef9SDimitry Andric       return false;
1622e8d8bef9SDimitry Andric     ExtUsers.push_back(User);
1623e8d8bef9SDimitry Andric   }
1624e8d8bef9SDimitry Andric   if (ExtUsers.empty()) {
1625e8d8bef9SDimitry Andric     DeadInsts.emplace_back(NarrowUse);
1626e8d8bef9SDimitry Andric     return true;
1627e8d8bef9SDimitry Andric   }
1628e8d8bef9SDimitry Andric 
1629e8d8bef9SDimitry Andric   // We'll prove some facts that should be true in the context of ext users. If
1630e8d8bef9SDimitry Andric   // there is no users, we are done now. If there are some, pick their common
1631e8d8bef9SDimitry Andric   // dominator as context.
1632fe6060f1SDimitry Andric   const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
1633e8d8bef9SDimitry Andric 
1634e8d8bef9SDimitry Andric   if (!CanSignExtend && !CanZeroExtend) {
1635e8d8bef9SDimitry Andric     // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
1636e8d8bef9SDimitry Andric     // will most likely not see it. Let's try to prove it.
1637e8d8bef9SDimitry Andric     if (OpCode != Instruction::Add)
1638e8d8bef9SDimitry Andric       return false;
1639fcaf7f86SDimitry Andric     if (ExtKind != ExtendKind::Zero)
1640e8d8bef9SDimitry Andric       return false;
1641e8d8bef9SDimitry Andric     const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
1642e8d8bef9SDimitry Andric     const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
1643e8d8bef9SDimitry Andric     // TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
1644e8d8bef9SDimitry Andric     if (NarrowUse->getOperand(0) != NarrowDef)
1645e8d8bef9SDimitry Andric       return false;
1646e8d8bef9SDimitry Andric     if (!SE->isKnownNegative(RHS))
1647e8d8bef9SDimitry Andric       return false;
1648fe6060f1SDimitry Andric     bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
1649fe6060f1SDimitry Andric                                                SE->getNegativeSCEV(RHS), CtxI);
1650e8d8bef9SDimitry Andric     if (!ProvedSubNUW)
1651e8d8bef9SDimitry Andric       return false;
1652e8d8bef9SDimitry Andric     // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
1653e8d8bef9SDimitry Andric     // neg(zext(neg(op))), which is basically sext(op).
1654fcaf7f86SDimitry Andric     AnotherOpExtKind = ExtendKind::Sign;
1655e8d8bef9SDimitry Andric   }
1656e8d8bef9SDimitry Andric 
1657e8d8bef9SDimitry Andric   // Verifying that Defining operand is an AddRec
1658e8d8bef9SDimitry Andric   const SCEV *Op1 = SE->getSCEV(WideDef);
1659e8d8bef9SDimitry Andric   const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1660e8d8bef9SDimitry Andric   if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1661e8d8bef9SDimitry Andric     return false;
1662e8d8bef9SDimitry Andric 
1663e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1664e8d8bef9SDimitry Andric 
1665e8d8bef9SDimitry Andric   // Generating a widening use instruction.
1666fcaf7f86SDimitry Andric   Value *LHS =
1667fcaf7f86SDimitry Andric       (NarrowUse->getOperand(0) == NarrowDef)
1668e8d8bef9SDimitry Andric           ? WideDef
1669e8d8bef9SDimitry Andric           : createExtendInst(NarrowUse->getOperand(0), WideType,
1670fcaf7f86SDimitry Andric                              AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1671fcaf7f86SDimitry Andric   Value *RHS =
1672fcaf7f86SDimitry Andric       (NarrowUse->getOperand(1) == NarrowDef)
1673e8d8bef9SDimitry Andric           ? WideDef
1674e8d8bef9SDimitry Andric           : createExtendInst(NarrowUse->getOperand(1), WideType,
1675fcaf7f86SDimitry Andric                              AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1676e8d8bef9SDimitry Andric 
1677e8d8bef9SDimitry Andric   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1678e8d8bef9SDimitry Andric   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1679e8d8bef9SDimitry Andric                                         NarrowBO->getName());
1680e8d8bef9SDimitry Andric   IRBuilder<> Builder(NarrowUse);
1681e8d8bef9SDimitry Andric   Builder.Insert(WideBO);
1682e8d8bef9SDimitry Andric   WideBO->copyIRFlags(NarrowBO);
1683e8d8bef9SDimitry Andric   ExtendKindMap[NarrowUse] = ExtKind;
1684e8d8bef9SDimitry Andric 
1685e8d8bef9SDimitry Andric   for (Instruction *User : ExtUsers) {
1686e8d8bef9SDimitry Andric     assert(User->getType() == WideType && "Checked before!");
1687e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1688e8d8bef9SDimitry Andric                       << *WideBO << "\n");
1689e8d8bef9SDimitry Andric     ++NumElimExt;
1690e8d8bef9SDimitry Andric     User->replaceAllUsesWith(WideBO);
1691e8d8bef9SDimitry Andric     DeadInsts.emplace_back(User);
1692e8d8bef9SDimitry Andric   }
1693e8d8bef9SDimitry Andric 
1694e8d8bef9SDimitry Andric   for (PHINode *User : LCSSAPhiUsers) {
1695e8d8bef9SDimitry Andric     assert(User->getNumOperands() == 1 && "Checked before!");
1696e8d8bef9SDimitry Andric     Builder.SetInsertPoint(User);
1697e8d8bef9SDimitry Andric     auto *WidePN =
1698e8d8bef9SDimitry Andric         Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
1699e8d8bef9SDimitry Andric     BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
1700e8d8bef9SDimitry Andric     assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
1701e8d8bef9SDimitry Andric            "Not a LCSSA Phi?");
1702e8d8bef9SDimitry Andric     WidePN->addIncoming(WideBO, LoopExitingBlock);
1703c9157d92SDimitry Andric     Builder.SetInsertPoint(User->getParent(),
1704c9157d92SDimitry Andric                            User->getParent()->getFirstInsertionPt());
1705e8d8bef9SDimitry Andric     auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
1706e8d8bef9SDimitry Andric     User->replaceAllUsesWith(TruncPN);
1707e8d8bef9SDimitry Andric     DeadInsts.emplace_back(User);
1708e8d8bef9SDimitry Andric   }
1709e8d8bef9SDimitry Andric 
1710e8d8bef9SDimitry Andric   for (ICmpInst *User : ICmpUsers) {
1711e8d8bef9SDimitry Andric     Builder.SetInsertPoint(User);
1712e8d8bef9SDimitry Andric     auto ExtendedOp = [&](Value * V)->Value * {
1713e8d8bef9SDimitry Andric       if (V == NarrowUse)
1714e8d8bef9SDimitry Andric         return WideBO;
1715fcaf7f86SDimitry Andric       if (ExtKind == ExtendKind::Zero)
1716e8d8bef9SDimitry Andric         return Builder.CreateZExt(V, WideBO->getType());
1717e8d8bef9SDimitry Andric       else
1718e8d8bef9SDimitry Andric         return Builder.CreateSExt(V, WideBO->getType());
1719e8d8bef9SDimitry Andric     };
1720e8d8bef9SDimitry Andric     auto Pred = User->getPredicate();
1721e8d8bef9SDimitry Andric     auto *LHS = ExtendedOp(User->getOperand(0));
1722e8d8bef9SDimitry Andric     auto *RHS = ExtendedOp(User->getOperand(1));
1723e8d8bef9SDimitry Andric     auto *WideCmp =
1724e8d8bef9SDimitry Andric         Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
1725e8d8bef9SDimitry Andric     User->replaceAllUsesWith(WideCmp);
1726e8d8bef9SDimitry Andric     DeadInsts.emplace_back(User);
1727e8d8bef9SDimitry Andric   }
1728e8d8bef9SDimitry Andric 
1729e8d8bef9SDimitry Andric   return true;
1730e8d8bef9SDimitry Andric }
1731e8d8bef9SDimitry Andric 
1732e8d8bef9SDimitry Andric /// Determine whether an individual user of the narrow IV can be widened. If so,
1733e8d8bef9SDimitry Andric /// return the wide clone of the user.
widenIVUse(WidenIV::NarrowIVDefUse DU,SCEVExpander & Rewriter)1734e8d8bef9SDimitry Andric Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1735e8d8bef9SDimitry Andric   assert(ExtendKindMap.count(DU.NarrowDef) &&
1736e8d8bef9SDimitry Andric          "Should already know the kind of extension used to widen NarrowDef");
1737e8d8bef9SDimitry Andric 
1738e8d8bef9SDimitry Andric   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1739e8d8bef9SDimitry Andric   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1740e8d8bef9SDimitry Andric     if (LI->getLoopFor(UsePhi->getParent()) != L) {
1741e8d8bef9SDimitry Andric       // For LCSSA phis, sink the truncate outside the loop.
1742e8d8bef9SDimitry Andric       // After SimplifyCFG most loop exit targets have a single predecessor.
1743e8d8bef9SDimitry Andric       // Otherwise fall back to a truncate within the loop.
1744e8d8bef9SDimitry Andric       if (UsePhi->getNumOperands() != 1)
1745e8d8bef9SDimitry Andric         truncateIVUse(DU, DT, LI);
1746e8d8bef9SDimitry Andric       else {
1747e8d8bef9SDimitry Andric         // Widening the PHI requires us to insert a trunc.  The logical place
1748e8d8bef9SDimitry Andric         // for this trunc is in the same BB as the PHI.  This is not possible if
1749e8d8bef9SDimitry Andric         // the BB is terminated by a catchswitch.
1750e8d8bef9SDimitry Andric         if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1751e8d8bef9SDimitry Andric           return nullptr;
1752e8d8bef9SDimitry Andric 
1753e8d8bef9SDimitry Andric         PHINode *WidePhi =
1754e8d8bef9SDimitry Andric           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1755e8d8bef9SDimitry Andric                           UsePhi);
1756e8d8bef9SDimitry Andric         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1757c9157d92SDimitry Andric         BasicBlock *WidePhiBB = WidePhi->getParent();
1758c9157d92SDimitry Andric         IRBuilder<> Builder(WidePhiBB, WidePhiBB->getFirstInsertionPt());
1759e8d8bef9SDimitry Andric         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1760e8d8bef9SDimitry Andric         UsePhi->replaceAllUsesWith(Trunc);
1761e8d8bef9SDimitry Andric         DeadInsts.emplace_back(UsePhi);
1762e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1763e8d8bef9SDimitry Andric                           << *WidePhi << "\n");
1764e8d8bef9SDimitry Andric       }
1765e8d8bef9SDimitry Andric       return nullptr;
1766e8d8bef9SDimitry Andric     }
1767e8d8bef9SDimitry Andric   }
1768e8d8bef9SDimitry Andric 
1769e8d8bef9SDimitry Andric   // This narrow use can be widened by a sext if it's non-negative or its narrow
1770a58f00eaSDimitry Andric   // def was widened by a sext. Same for zext.
1771e8d8bef9SDimitry Andric   auto canWidenBySExt = [&]() {
1772fcaf7f86SDimitry Andric     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1773e8d8bef9SDimitry Andric   };
1774e8d8bef9SDimitry Andric   auto canWidenByZExt = [&]() {
1775fcaf7f86SDimitry Andric     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Zero;
1776e8d8bef9SDimitry Andric   };
1777e8d8bef9SDimitry Andric 
1778e8d8bef9SDimitry Andric   // Our raison d'etre! Eliminate sign and zero extension.
1779e710425bSDimitry Andric   if ((match(DU.NarrowUse, m_SExtLike(m_Value())) && canWidenBySExt()) ||
1780e8d8bef9SDimitry Andric       (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1781e8d8bef9SDimitry Andric     Value *NewDef = DU.WideDef;
1782e8d8bef9SDimitry Andric     if (DU.NarrowUse->getType() != WideType) {
1783e8d8bef9SDimitry Andric       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1784e8d8bef9SDimitry Andric       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1785e8d8bef9SDimitry Andric       if (CastWidth < IVWidth) {
1786e8d8bef9SDimitry Andric         // The cast isn't as wide as the IV, so insert a Trunc.
1787e8d8bef9SDimitry Andric         IRBuilder<> Builder(DU.NarrowUse);
1788e8d8bef9SDimitry Andric         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1789e8d8bef9SDimitry Andric       }
1790e8d8bef9SDimitry Andric       else {
1791e8d8bef9SDimitry Andric         // A wider extend was hidden behind a narrower one. This may induce
1792e8d8bef9SDimitry Andric         // another round of IV widening in which the intermediate IV becomes
1793e8d8bef9SDimitry Andric         // dead. It should be very rare.
1794e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1795e8d8bef9SDimitry Andric                           << " not wide enough to subsume " << *DU.NarrowUse
1796e8d8bef9SDimitry Andric                           << "\n");
1797e8d8bef9SDimitry Andric         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1798e8d8bef9SDimitry Andric         NewDef = DU.NarrowUse;
1799e8d8bef9SDimitry Andric       }
1800e8d8bef9SDimitry Andric     }
1801e8d8bef9SDimitry Andric     if (NewDef != DU.NarrowUse) {
1802e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1803e8d8bef9SDimitry Andric                         << " replaced by " << *DU.WideDef << "\n");
1804e8d8bef9SDimitry Andric       ++NumElimExt;
1805e8d8bef9SDimitry Andric       DU.NarrowUse->replaceAllUsesWith(NewDef);
1806e8d8bef9SDimitry Andric       DeadInsts.emplace_back(DU.NarrowUse);
1807e8d8bef9SDimitry Andric     }
1808e8d8bef9SDimitry Andric     // Now that the extend is gone, we want to expose it's uses for potential
1809e8d8bef9SDimitry Andric     // further simplification. We don't need to directly inform SimplifyIVUsers
1810e8d8bef9SDimitry Andric     // of the new users, because their parent IV will be processed later as a
1811e8d8bef9SDimitry Andric     // new loop phi. If we preserved IVUsers analysis, we would also want to
1812e8d8bef9SDimitry Andric     // push the uses of WideDef here.
1813e8d8bef9SDimitry Andric 
1814e8d8bef9SDimitry Andric     // No further widening is needed. The deceased [sz]ext had done it for us.
1815e8d8bef9SDimitry Andric     return nullptr;
1816e8d8bef9SDimitry Andric   }
1817e8d8bef9SDimitry Andric 
1818c9157d92SDimitry Andric   auto tryAddRecExpansion = [&]() -> Instruction* {
1819e8d8bef9SDimitry Andric     // Does this user itself evaluate to a recurrence after widening?
1820e8d8bef9SDimitry Andric     WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1821e8d8bef9SDimitry Andric     if (!WideAddRec.first)
1822e8d8bef9SDimitry Andric       WideAddRec = getWideRecurrence(DU);
1823fcaf7f86SDimitry Andric     assert((WideAddRec.first == nullptr) ==
1824fcaf7f86SDimitry Andric            (WideAddRec.second == ExtendKind::Unknown));
1825c9157d92SDimitry Andric     if (!WideAddRec.first)
1826e8d8bef9SDimitry Andric       return nullptr;
1827e8d8bef9SDimitry Andric 
1828e8d8bef9SDimitry Andric     // Reuse the IV increment that SCEVExpander created as long as it dominates
1829e8d8bef9SDimitry Andric     // NarrowUse.
1830e8d8bef9SDimitry Andric     Instruction *WideUse = nullptr;
1831e8d8bef9SDimitry Andric     if (WideAddRec.first == WideIncExpr &&
1832e8d8bef9SDimitry Andric         Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1833e8d8bef9SDimitry Andric       WideUse = WideInc;
1834e8d8bef9SDimitry Andric     else {
1835e8d8bef9SDimitry Andric       WideUse = cloneIVUser(DU, WideAddRec.first);
1836e8d8bef9SDimitry Andric       if (!WideUse)
1837e8d8bef9SDimitry Andric         return nullptr;
1838e8d8bef9SDimitry Andric     }
1839e8d8bef9SDimitry Andric     // Evaluation of WideAddRec ensured that the narrow expression could be
1840e8d8bef9SDimitry Andric     // extended outside the loop without overflow. This suggests that the wide use
1841e8d8bef9SDimitry Andric     // evaluates to the same expression as the extended narrow use, but doesn't
1842e8d8bef9SDimitry Andric     // absolutely guarantee it. Hence the following failsafe check. In rare cases
1843e8d8bef9SDimitry Andric     // where it fails, we simply throw away the newly created wide use.
1844e8d8bef9SDimitry Andric     if (WideAddRec.first != SE->getSCEV(WideUse)) {
1845e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1846e8d8bef9SDimitry Andric                  << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1847e8d8bef9SDimitry Andric                  << "\n");
1848e8d8bef9SDimitry Andric       DeadInsts.emplace_back(WideUse);
1849e8d8bef9SDimitry Andric       return nullptr;
1850c9157d92SDimitry Andric     };
1851e8d8bef9SDimitry Andric 
1852e8d8bef9SDimitry Andric     // if we reached this point then we are going to replace
1853e8d8bef9SDimitry Andric     // DU.NarrowUse with WideUse. Reattach DbgValue then.
1854e8d8bef9SDimitry Andric     replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
1855e8d8bef9SDimitry Andric 
1856e8d8bef9SDimitry Andric     ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1857e8d8bef9SDimitry Andric     // Returning WideUse pushes it on the worklist.
1858e8d8bef9SDimitry Andric     return WideUse;
1859c9157d92SDimitry Andric   };
1860c9157d92SDimitry Andric 
1861c9157d92SDimitry Andric   if (auto *I = tryAddRecExpansion())
1862c9157d92SDimitry Andric     return I;
1863c9157d92SDimitry Andric 
1864c9157d92SDimitry Andric   // If use is a loop condition, try to promote the condition instead of
1865c9157d92SDimitry Andric   // truncating the IV first.
1866c9157d92SDimitry Andric   if (widenLoopCompare(DU))
1867c9157d92SDimitry Andric     return nullptr;
1868c9157d92SDimitry Andric 
1869c9157d92SDimitry Andric   // We are here about to generate a truncate instruction that may hurt
1870c9157d92SDimitry Andric   // performance because the scalar evolution expression computed earlier
1871c9157d92SDimitry Andric   // in WideAddRec.first does not indicate a polynomial induction expression.
1872c9157d92SDimitry Andric   // In that case, look at the operands of the use instruction to determine
1873c9157d92SDimitry Andric   // if we can still widen the use instead of truncating its operand.
1874c9157d92SDimitry Andric   if (widenWithVariantUse(DU))
1875c9157d92SDimitry Andric     return nullptr;
1876c9157d92SDimitry Andric 
1877c9157d92SDimitry Andric   // This user does not evaluate to a recurrence after widening, so don't
1878c9157d92SDimitry Andric   // follow it. Instead insert a Trunc to kill off the original use,
1879c9157d92SDimitry Andric   // eventually isolating the original narrow IV so it can be removed.
1880c9157d92SDimitry Andric   truncateIVUse(DU, DT, LI);
1881c9157d92SDimitry Andric   return nullptr;
1882e8d8bef9SDimitry Andric }
1883e8d8bef9SDimitry Andric 
1884e8d8bef9SDimitry Andric /// Add eligible users of NarrowDef to NarrowIVUsers.
pushNarrowIVUsers(Instruction * NarrowDef,Instruction * WideDef)1885e8d8bef9SDimitry Andric void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1886e8d8bef9SDimitry Andric   const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1887e8d8bef9SDimitry Andric   bool NonNegativeDef =
1888e8d8bef9SDimitry Andric       SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1889e8d8bef9SDimitry Andric                            SE->getZero(NarrowSCEV->getType()));
1890e8d8bef9SDimitry Andric   for (User *U : NarrowDef->users()) {
1891e8d8bef9SDimitry Andric     Instruction *NarrowUser = cast<Instruction>(U);
1892e8d8bef9SDimitry Andric 
1893e8d8bef9SDimitry Andric     // Handle data flow merges and bizarre phi cycles.
1894e8d8bef9SDimitry Andric     if (!Widened.insert(NarrowUser).second)
1895e8d8bef9SDimitry Andric       continue;
1896e8d8bef9SDimitry Andric 
1897e8d8bef9SDimitry Andric     bool NonNegativeUse = false;
1898e8d8bef9SDimitry Andric     if (!NonNegativeDef) {
1899e8d8bef9SDimitry Andric       // We might have a control-dependent range information for this context.
1900e8d8bef9SDimitry Andric       if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1901e8d8bef9SDimitry Andric         NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1902e8d8bef9SDimitry Andric     }
1903e8d8bef9SDimitry Andric 
1904e8d8bef9SDimitry Andric     NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1905e8d8bef9SDimitry Andric                                NonNegativeDef || NonNegativeUse);
1906e8d8bef9SDimitry Andric   }
1907e8d8bef9SDimitry Andric }
1908e8d8bef9SDimitry Andric 
1909e8d8bef9SDimitry Andric /// Process a single induction variable. First use the SCEVExpander to create a
1910e8d8bef9SDimitry Andric /// wide induction variable that evaluates to the same recurrence as the
1911e8d8bef9SDimitry Andric /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1912e8d8bef9SDimitry Andric /// def-use chain. After widenIVUse has processed all interesting IV users, the
1913e8d8bef9SDimitry Andric /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1914e8d8bef9SDimitry Andric ///
1915e8d8bef9SDimitry Andric /// It would be simpler to delete uses as they are processed, but we must avoid
1916e8d8bef9SDimitry Andric /// invalidating SCEV expressions.
createWideIV(SCEVExpander & Rewriter)1917e8d8bef9SDimitry Andric PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1918e8d8bef9SDimitry Andric   // Is this phi an induction variable?
1919e8d8bef9SDimitry Andric   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1920e8d8bef9SDimitry Andric   if (!AddRec)
1921e8d8bef9SDimitry Andric     return nullptr;
1922e8d8bef9SDimitry Andric 
1923e8d8bef9SDimitry Andric   // Widen the induction variable expression.
1924fcaf7f86SDimitry Andric   const SCEV *WideIVExpr = getExtendKind(OrigPhi) == ExtendKind::Sign
1925e8d8bef9SDimitry Andric                                ? SE->getSignExtendExpr(AddRec, WideType)
1926e8d8bef9SDimitry Andric                                : SE->getZeroExtendExpr(AddRec, WideType);
1927e8d8bef9SDimitry Andric 
1928e8d8bef9SDimitry Andric   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1929e8d8bef9SDimitry Andric          "Expect the new IV expression to preserve its type");
1930e8d8bef9SDimitry Andric 
1931e8d8bef9SDimitry Andric   // Can the IV be extended outside the loop without overflow?
1932e8d8bef9SDimitry Andric   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1933e8d8bef9SDimitry Andric   if (!AddRec || AddRec->getLoop() != L)
1934e8d8bef9SDimitry Andric     return nullptr;
1935e8d8bef9SDimitry Andric 
1936e8d8bef9SDimitry Andric   // An AddRec must have loop-invariant operands. Since this AddRec is
1937e8d8bef9SDimitry Andric   // materialized by a loop header phi, the expression cannot have any post-loop
1938e8d8bef9SDimitry Andric   // operands, so they must dominate the loop header.
1939e8d8bef9SDimitry Andric   assert(
1940e8d8bef9SDimitry Andric       SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1941e8d8bef9SDimitry Andric       SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1942e8d8bef9SDimitry Andric       "Loop header phi recurrence inputs do not dominate the loop");
1943e8d8bef9SDimitry Andric 
1944e8d8bef9SDimitry Andric   // Iterate over IV uses (including transitive ones) looking for IV increments
1945e8d8bef9SDimitry Andric   // of the form 'add nsw %iv, <const>'. For each increment and each use of
1946e8d8bef9SDimitry Andric   // the increment calculate control-dependent range information basing on
1947e8d8bef9SDimitry Andric   // dominating conditions inside of the loop (e.g. a range check inside of the
1948e8d8bef9SDimitry Andric   // loop). Calculated ranges are stored in PostIncRangeInfos map.
1949e8d8bef9SDimitry Andric   //
1950e8d8bef9SDimitry Andric   // Control-dependent range information is later used to prove that a narrow
1951e8d8bef9SDimitry Andric   // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1952e8d8bef9SDimitry Andric   // this on demand because when pushNarrowIVUsers needs this information some
1953e8d8bef9SDimitry Andric   // of the dominating conditions might be already widened.
1954e8d8bef9SDimitry Andric   if (UsePostIncrementRanges)
1955e8d8bef9SDimitry Andric     calculatePostIncRanges(OrigPhi);
1956e8d8bef9SDimitry Andric 
1957e8d8bef9SDimitry Andric   // The rewriter provides a value for the desired IV expression. This may
1958e8d8bef9SDimitry Andric   // either find an existing phi or materialize a new one. Either way, we
1959e8d8bef9SDimitry Andric   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1960e8d8bef9SDimitry Andric   // of the phi-SCC dominates the loop entry.
1961e8d8bef9SDimitry Andric   Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
1962e8d8bef9SDimitry Andric   Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
1963e8d8bef9SDimitry Andric   // If the wide phi is not a phi node, for example a cast node, like bitcast,
1964e8d8bef9SDimitry Andric   // inttoptr, ptrtoint, just skip for now.
1965e8d8bef9SDimitry Andric   if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
1966e8d8bef9SDimitry Andric     // if the cast node is an inserted instruction without any user, we should
1967e8d8bef9SDimitry Andric     // remove it to make sure the pass don't touch the function as we can not
1968e8d8bef9SDimitry Andric     // wide the phi.
1969e8d8bef9SDimitry Andric     if (ExpandInst->hasNUses(0) &&
1970e8d8bef9SDimitry Andric         Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
1971e8d8bef9SDimitry Andric       DeadInsts.emplace_back(ExpandInst);
1972e8d8bef9SDimitry Andric     return nullptr;
1973e8d8bef9SDimitry Andric   }
1974e8d8bef9SDimitry Andric 
1975e8d8bef9SDimitry Andric   // Remembering the WideIV increment generated by SCEVExpander allows
1976e8d8bef9SDimitry Andric   // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1977e8d8bef9SDimitry Andric   // employ a general reuse mechanism because the call above is the only call to
1978e8d8bef9SDimitry Andric   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1979e8d8bef9SDimitry Andric   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1980e8d8bef9SDimitry Andric     WideInc =
1981c9157d92SDimitry Andric         dyn_cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1982c9157d92SDimitry Andric     if (WideInc) {
1983e8d8bef9SDimitry Andric       WideIncExpr = SE->getSCEV(WideInc);
1984c9157d92SDimitry Andric       // Propagate the debug location associated with the original loop
1985c9157d92SDimitry Andric       // increment to the new (widened) increment.
1986e8d8bef9SDimitry Andric       auto *OrigInc =
1987e8d8bef9SDimitry Andric           cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1988e8d8bef9SDimitry Andric       WideInc->setDebugLoc(OrigInc->getDebugLoc());
1989e8d8bef9SDimitry Andric     }
1990c9157d92SDimitry Andric   }
1991e8d8bef9SDimitry Andric 
1992e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1993e8d8bef9SDimitry Andric   ++NumWidened;
1994e8d8bef9SDimitry Andric 
1995e8d8bef9SDimitry Andric   // Traverse the def-use chain using a worklist starting at the original IV.
1996e8d8bef9SDimitry Andric   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1997e8d8bef9SDimitry Andric 
1998e8d8bef9SDimitry Andric   Widened.insert(OrigPhi);
1999e8d8bef9SDimitry Andric   pushNarrowIVUsers(OrigPhi, WidePhi);
2000e8d8bef9SDimitry Andric 
2001e8d8bef9SDimitry Andric   while (!NarrowIVUsers.empty()) {
2002e8d8bef9SDimitry Andric     WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
2003e8d8bef9SDimitry Andric 
2004e8d8bef9SDimitry Andric     // Process a def-use edge. This may replace the use, so don't hold a
2005e8d8bef9SDimitry Andric     // use_iterator across it.
2006e8d8bef9SDimitry Andric     Instruction *WideUse = widenIVUse(DU, Rewriter);
2007e8d8bef9SDimitry Andric 
2008e8d8bef9SDimitry Andric     // Follow all def-use edges from the previous narrow use.
2009e8d8bef9SDimitry Andric     if (WideUse)
2010e8d8bef9SDimitry Andric       pushNarrowIVUsers(DU.NarrowUse, WideUse);
2011e8d8bef9SDimitry Andric 
2012e8d8bef9SDimitry Andric     // widenIVUse may have removed the def-use edge.
2013e8d8bef9SDimitry Andric     if (DU.NarrowDef->use_empty())
2014e8d8bef9SDimitry Andric       DeadInsts.emplace_back(DU.NarrowDef);
2015e8d8bef9SDimitry Andric   }
2016e8d8bef9SDimitry Andric 
2017e8d8bef9SDimitry Andric   // Attach any debug information to the new PHI.
2018e8d8bef9SDimitry Andric   replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
2019e8d8bef9SDimitry Andric 
2020e8d8bef9SDimitry Andric   return WidePhi;
2021e8d8bef9SDimitry Andric }
2022e8d8bef9SDimitry Andric 
2023e8d8bef9SDimitry Andric /// Calculates control-dependent range for the given def at the given context
2024e8d8bef9SDimitry Andric /// by looking at dominating conditions inside of the loop
calculatePostIncRange(Instruction * NarrowDef,Instruction * NarrowUser)2025e8d8bef9SDimitry Andric void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
2026e8d8bef9SDimitry Andric                                     Instruction *NarrowUser) {
2027e8d8bef9SDimitry Andric   Value *NarrowDefLHS;
2028e8d8bef9SDimitry Andric   const APInt *NarrowDefRHS;
2029e8d8bef9SDimitry Andric   if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
2030e8d8bef9SDimitry Andric                                  m_APInt(NarrowDefRHS))) ||
2031e8d8bef9SDimitry Andric       !NarrowDefRHS->isNonNegative())
2032e8d8bef9SDimitry Andric     return;
2033e8d8bef9SDimitry Andric 
2034e8d8bef9SDimitry Andric   auto UpdateRangeFromCondition = [&] (Value *Condition,
2035e8d8bef9SDimitry Andric                                        bool TrueDest) {
2036e8d8bef9SDimitry Andric     CmpInst::Predicate Pred;
2037e8d8bef9SDimitry Andric     Value *CmpRHS;
2038e8d8bef9SDimitry Andric     if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
2039e8d8bef9SDimitry Andric                                  m_Value(CmpRHS))))
2040e8d8bef9SDimitry Andric       return;
2041e8d8bef9SDimitry Andric 
2042e8d8bef9SDimitry Andric     CmpInst::Predicate P =
2043e8d8bef9SDimitry Andric             TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
2044e8d8bef9SDimitry Andric 
2045e8d8bef9SDimitry Andric     auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
2046e8d8bef9SDimitry Andric     auto CmpConstrainedLHSRange =
2047e8d8bef9SDimitry Andric             ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
2048e8d8bef9SDimitry Andric     auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2049e8d8bef9SDimitry Andric         *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap);
2050e8d8bef9SDimitry Andric 
2051e8d8bef9SDimitry Andric     updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2052e8d8bef9SDimitry Andric   };
2053e8d8bef9SDimitry Andric 
2054e8d8bef9SDimitry Andric   auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
2055e8d8bef9SDimitry Andric     if (!HasGuards)
2056e8d8bef9SDimitry Andric       return;
2057e8d8bef9SDimitry Andric 
2058e8d8bef9SDimitry Andric     for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
2059e8d8bef9SDimitry Andric                                      Ctx->getParent()->rend())) {
2060e8d8bef9SDimitry Andric       Value *C = nullptr;
2061e8d8bef9SDimitry Andric       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
2062e8d8bef9SDimitry Andric         UpdateRangeFromCondition(C, /*TrueDest=*/true);
2063e8d8bef9SDimitry Andric     }
2064e8d8bef9SDimitry Andric   };
2065e8d8bef9SDimitry Andric 
2066e8d8bef9SDimitry Andric   UpdateRangeFromGuards(NarrowUser);
2067e8d8bef9SDimitry Andric 
2068e8d8bef9SDimitry Andric   BasicBlock *NarrowUserBB = NarrowUser->getParent();
2069e8d8bef9SDimitry Andric   // If NarrowUserBB is statically unreachable asking dominator queries may
2070e8d8bef9SDimitry Andric   // yield surprising results. (e.g. the block may not have a dom tree node)
2071e8d8bef9SDimitry Andric   if (!DT->isReachableFromEntry(NarrowUserBB))
2072e8d8bef9SDimitry Andric     return;
2073e8d8bef9SDimitry Andric 
2074e8d8bef9SDimitry Andric   for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2075e8d8bef9SDimitry Andric        L->contains(DTB->getBlock());
2076e8d8bef9SDimitry Andric        DTB = DTB->getIDom()) {
2077e8d8bef9SDimitry Andric     auto *BB = DTB->getBlock();
2078e8d8bef9SDimitry Andric     auto *TI = BB->getTerminator();
2079e8d8bef9SDimitry Andric     UpdateRangeFromGuards(TI);
2080e8d8bef9SDimitry Andric 
2081e8d8bef9SDimitry Andric     auto *BI = dyn_cast<BranchInst>(TI);
2082e8d8bef9SDimitry Andric     if (!BI || !BI->isConditional())
2083e8d8bef9SDimitry Andric       continue;
2084e8d8bef9SDimitry Andric 
2085e8d8bef9SDimitry Andric     auto *TrueSuccessor = BI->getSuccessor(0);
2086e8d8bef9SDimitry Andric     auto *FalseSuccessor = BI->getSuccessor(1);
2087e8d8bef9SDimitry Andric 
2088e8d8bef9SDimitry Andric     auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
2089e8d8bef9SDimitry Andric       return BBE.isSingleEdge() &&
2090e8d8bef9SDimitry Andric              DT->dominates(BBE, NarrowUser->getParent());
2091e8d8bef9SDimitry Andric     };
2092e8d8bef9SDimitry Andric 
2093e8d8bef9SDimitry Andric     if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
2094e8d8bef9SDimitry Andric       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
2095e8d8bef9SDimitry Andric 
2096e8d8bef9SDimitry Andric     if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
2097e8d8bef9SDimitry Andric       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
2098e8d8bef9SDimitry Andric   }
2099e8d8bef9SDimitry Andric }
2100e8d8bef9SDimitry Andric 
2101e8d8bef9SDimitry Andric /// Calculates PostIncRangeInfos map for the given IV
calculatePostIncRanges(PHINode * OrigPhi)2102e8d8bef9SDimitry Andric void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2103e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 16> Visited;
2104e8d8bef9SDimitry Andric   SmallVector<Instruction *, 6> Worklist;
2105e8d8bef9SDimitry Andric   Worklist.push_back(OrigPhi);
2106e8d8bef9SDimitry Andric   Visited.insert(OrigPhi);
2107e8d8bef9SDimitry Andric 
2108e8d8bef9SDimitry Andric   while (!Worklist.empty()) {
2109e8d8bef9SDimitry Andric     Instruction *NarrowDef = Worklist.pop_back_val();
2110e8d8bef9SDimitry Andric 
2111e8d8bef9SDimitry Andric     for (Use &U : NarrowDef->uses()) {
2112e8d8bef9SDimitry Andric       auto *NarrowUser = cast<Instruction>(U.getUser());
2113e8d8bef9SDimitry Andric 
2114e8d8bef9SDimitry Andric       // Don't go looking outside the current loop.
2115e8d8bef9SDimitry Andric       auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
2116e8d8bef9SDimitry Andric       if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
2117e8d8bef9SDimitry Andric         continue;
2118e8d8bef9SDimitry Andric 
2119e8d8bef9SDimitry Andric       if (!Visited.insert(NarrowUser).second)
2120e8d8bef9SDimitry Andric         continue;
2121e8d8bef9SDimitry Andric 
2122e8d8bef9SDimitry Andric       Worklist.push_back(NarrowUser);
2123e8d8bef9SDimitry Andric 
2124e8d8bef9SDimitry Andric       calculatePostIncRange(NarrowDef, NarrowUser);
2125e8d8bef9SDimitry Andric     }
2126e8d8bef9SDimitry Andric   }
2127e8d8bef9SDimitry Andric }
2128e8d8bef9SDimitry Andric 
createWideIV(const WideIVInfo & WI,LoopInfo * LI,ScalarEvolution * SE,SCEVExpander & Rewriter,DominatorTree * DT,SmallVectorImpl<WeakTrackingVH> & DeadInsts,unsigned & NumElimExt,unsigned & NumWidened,bool HasGuards,bool UsePostIncrementRanges)2129e8d8bef9SDimitry Andric PHINode *llvm::createWideIV(const WideIVInfo &WI,
2130e8d8bef9SDimitry Andric     LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
2131e8d8bef9SDimitry Andric     DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
2132e8d8bef9SDimitry Andric     unsigned &NumElimExt, unsigned &NumWidened,
2133e8d8bef9SDimitry Andric     bool HasGuards, bool UsePostIncrementRanges) {
2134e8d8bef9SDimitry Andric   WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2135e8d8bef9SDimitry Andric   PHINode *WidePHI = Widener.createWideIV(Rewriter);
2136e8d8bef9SDimitry Andric   NumElimExt = Widener.getNumElimExt();
2137e8d8bef9SDimitry Andric   NumWidened = Widener.getNumWidened();
2138e8d8bef9SDimitry Andric   return WidePHI;
2139e8d8bef9SDimitry Andric }
2140