130815c53SDimitry Andric //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
230815c53SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
630815c53SDimitry Andric //
730815c53SDimitry Andric //===----------------------------------------------------------------------===//
830815c53SDimitry Andric //
930815c53SDimitry Andric // This file implements induction variable simplification. It does
1030815c53SDimitry Andric // not define any actual pass or policy, but provides a single function to
1130815c53SDimitry Andric // simplify a loop's induction variables based on ScalarEvolution.
1230815c53SDimitry Andric //
1330815c53SDimitry Andric //===----------------------------------------------------------------------===//
1430815c53SDimitry Andric
154a16efa3SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
164a16efa3SDimitry Andric #include "llvm/ADT/SmallVector.h"
174a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
1830815c53SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
19ac9a064cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
205ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
215ca98fd9SDimitry Andric #include "llvm/IR/IRBuilder.h"
224a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
23e6d15924SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
24ca089b24SDimitry Andric #include "llvm/IR/PatternMatch.h"
2530815c53SDimitry Andric #include "llvm/Support/Debug.h"
2630815c53SDimitry Andric #include "llvm/Support/raw_ostream.h"
27eb11fae6SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
28ac9a064cSDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
29cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
3030815c53SDimitry Andric
3130815c53SDimitry Andric using namespace llvm;
3299aabd70SDimitry Andric using namespace llvm::PatternMatch;
3330815c53SDimitry Andric
345ca98fd9SDimitry Andric #define DEBUG_TYPE "indvars"
355ca98fd9SDimitry Andric
3630815c53SDimitry Andric STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
3730815c53SDimitry Andric STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
38044eb2f6SDimitry Andric STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
3930815c53SDimitry Andric STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
4071d5a254SDimitry Andric STATISTIC(
4171d5a254SDimitry Andric NumSimplifiedSDiv,
4271d5a254SDimitry Andric "Number of IV signed division operations converted to unsigned division");
43044eb2f6SDimitry Andric STATISTIC(
44044eb2f6SDimitry Andric NumSimplifiedSRem,
45044eb2f6SDimitry Andric "Number of IV signed remainder operations converted to unsigned remainder");
4630815c53SDimitry Andric STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
4730815c53SDimitry Andric
4830815c53SDimitry Andric namespace {
4967c32a98SDimitry Andric /// This is a utility for simplifying induction variables
5030815c53SDimitry Andric /// based on ScalarEvolution. It is the primary instrument of the
5130815c53SDimitry Andric /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
5230815c53SDimitry Andric /// other loop passes that preserve SCEV.
5330815c53SDimitry Andric class SimplifyIndvar {
5430815c53SDimitry Andric Loop *L;
5530815c53SDimitry Andric LoopInfo *LI;
5630815c53SDimitry Andric ScalarEvolution *SE;
57dd58ef01SDimitry Andric DominatorTree *DT;
58cfca06d7SDimitry Andric const TargetTransformInfo *TTI;
59044eb2f6SDimitry Andric SCEVExpander &Rewriter;
60a303c417SDimitry Andric SmallVectorImpl<WeakTrackingVH> &DeadInsts;
6130815c53SDimitry Andric
62145449b1SDimitry Andric bool Changed = false;
63ac9a064cSDimitry Andric bool RunUnswitching = false;
6430815c53SDimitry Andric
6530815c53SDimitry Andric public:
SimplifyIndvar(Loop * Loop,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,const TargetTransformInfo * TTI,SCEVExpander & Rewriter,SmallVectorImpl<WeakTrackingVH> & Dead)66dd58ef01SDimitry Andric SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
67cfca06d7SDimitry Andric LoopInfo *LI, const TargetTransformInfo *TTI,
68cfca06d7SDimitry Andric SCEVExpander &Rewriter,
69044eb2f6SDimitry Andric SmallVectorImpl<WeakTrackingVH> &Dead)
70cfca06d7SDimitry Andric : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter),
71145449b1SDimitry Andric DeadInsts(Dead) {
7230815c53SDimitry Andric assert(LI && "IV simplification requires LoopInfo");
7330815c53SDimitry Andric }
7430815c53SDimitry Andric
hasChanged() const7530815c53SDimitry Andric bool hasChanged() const { return Changed; }
runUnswitching() const76ac9a064cSDimitry Andric bool runUnswitching() const { return RunUnswitching; }
7730815c53SDimitry Andric
7830815c53SDimitry Andric /// Iteratively perform simplification on a worklist of users of the
7930815c53SDimitry Andric /// specified induction variable. This is the top-level driver that applies
80dd58ef01SDimitry Andric /// all simplifications to users of an IV.
815ca98fd9SDimitry Andric void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
8230815c53SDimitry Andric
83ac9a064cSDimitry Andric void pushIVUsers(Instruction *Def,
84ac9a064cSDimitry Andric SmallPtrSet<Instruction *, 16> &Simplified,
85ac9a064cSDimitry Andric SmallVectorImpl<std::pair<Instruction *, Instruction *>>
86ac9a064cSDimitry Andric &SimpleIVUsers);
87ac9a064cSDimitry Andric
8830815c53SDimitry Andric Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
8930815c53SDimitry Andric
90dd58ef01SDimitry Andric bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
91044eb2f6SDimitry Andric bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
921f917f69SDimitry Andric bool replaceFloatIVWithIntegerIV(Instruction *UseInst);
93dd58ef01SDimitry Andric
94e6d15924SDimitry Andric bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
95e6d15924SDimitry Andric bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
96eb11fae6SDimitry Andric bool eliminateTrunc(TruncInst *TI);
9730815c53SDimitry Andric bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
981f917f69SDimitry Andric bool makeIVComparisonInvariant(ICmpInst *ICmp, Instruction *IVOperand);
991f917f69SDimitry Andric void eliminateIVComparison(ICmpInst *ICmp, Instruction *IVOperand);
1001f917f69SDimitry Andric void simplifyIVRemainder(BinaryOperator *Rem, Instruction *IVOperand,
10130815c53SDimitry Andric bool IsSigned);
102044eb2f6SDimitry Andric void replaceRemWithNumerator(BinaryOperator *Rem);
103044eb2f6SDimitry Andric void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
104044eb2f6SDimitry Andric void replaceSRemWithURem(BinaryOperator *Rem);
10571d5a254SDimitry Andric bool eliminateSDiv(BinaryOperator *SDiv);
1067fa27ce4SDimitry Andric bool strengthenBinaryOp(BinaryOperator *BO, Instruction *IVOperand);
1071f917f69SDimitry Andric bool strengthenOverflowingOperation(BinaryOperator *OBO,
1081f917f69SDimitry Andric Instruction *IVOperand);
1091f917f69SDimitry Andric bool strengthenRightShift(BinaryOperator *BO, Instruction *IVOperand);
11030815c53SDimitry Andric };
1111a82d4c0SDimitry Andric }
11230815c53SDimitry Andric
113344a3780SDimitry Andric /// Find a point in code which dominates all given instructions. We can safely
114344a3780SDimitry Andric /// assume that, whatever fact we can prove at the found point, this fact is
115344a3780SDimitry Andric /// also true for each of the given instructions.
findCommonDominator(ArrayRef<Instruction * > Instructions,DominatorTree & DT)116344a3780SDimitry Andric static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions,
117344a3780SDimitry Andric DominatorTree &DT) {
118344a3780SDimitry Andric Instruction *CommonDom = nullptr;
119344a3780SDimitry Andric for (auto *Insn : Instructions)
120344a3780SDimitry Andric CommonDom =
121e3b55780SDimitry Andric CommonDom ? DT.findNearestCommonDominator(CommonDom, Insn) : Insn;
122344a3780SDimitry Andric assert(CommonDom && "Common dominator not found?");
123344a3780SDimitry Andric return CommonDom;
124344a3780SDimitry Andric }
125344a3780SDimitry Andric
12667c32a98SDimitry Andric /// Fold an IV operand into its use. This removes increments of an
12730815c53SDimitry Andric /// aligned IV when used by a instruction that ignores the low bits.
12830815c53SDimitry Andric ///
12930815c53SDimitry Andric /// IVOperand is guaranteed SCEVable, but UseInst may not be.
13030815c53SDimitry Andric ///
13130815c53SDimitry Andric /// Return the operand of IVOperand for this induction variable if IVOperand can
13230815c53SDimitry Andric /// be folded (in case more folding opportunities have been exposed).
13330815c53SDimitry Andric /// Otherwise return null.
foldIVUser(Instruction * UseInst,Instruction * IVOperand)13430815c53SDimitry Andric Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
1355ca98fd9SDimitry Andric Value *IVSrc = nullptr;
136d8e91e46SDimitry Andric const unsigned OperIdx = 0;
1375ca98fd9SDimitry Andric const SCEV *FoldedExpr = nullptr;
138d8e91e46SDimitry Andric bool MustDropExactFlag = false;
13930815c53SDimitry Andric switch (UseInst->getOpcode()) {
14030815c53SDimitry Andric default:
1415ca98fd9SDimitry Andric return nullptr;
14230815c53SDimitry Andric case Instruction::UDiv:
14330815c53SDimitry Andric case Instruction::LShr:
14430815c53SDimitry Andric // We're only interested in the case where we know something about
14530815c53SDimitry Andric // the numerator and have a constant denominator.
14630815c53SDimitry Andric if (IVOperand != UseInst->getOperand(OperIdx) ||
14730815c53SDimitry Andric !isa<ConstantInt>(UseInst->getOperand(1)))
1485ca98fd9SDimitry Andric return nullptr;
14930815c53SDimitry Andric
15030815c53SDimitry Andric // Attempt to fold a binary operator with constant operand.
15130815c53SDimitry Andric // e.g. ((I + 1) >> 2) => I >> 2
15263faed5bSDimitry Andric if (!isa<BinaryOperator>(IVOperand)
15363faed5bSDimitry Andric || !isa<ConstantInt>(IVOperand->getOperand(1)))
1545ca98fd9SDimitry Andric return nullptr;
15530815c53SDimitry Andric
15630815c53SDimitry Andric IVSrc = IVOperand->getOperand(0);
15730815c53SDimitry Andric // IVSrc must be the (SCEVable) IV, since the other operand is const.
15830815c53SDimitry Andric assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
15930815c53SDimitry Andric
16030815c53SDimitry Andric ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
16130815c53SDimitry Andric if (UseInst->getOpcode() == Instruction::LShr) {
16230815c53SDimitry Andric // Get a constant for the divisor. See createSCEV.
16330815c53SDimitry Andric uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
16430815c53SDimitry Andric if (D->getValue().uge(BitWidth))
1655ca98fd9SDimitry Andric return nullptr;
16630815c53SDimitry Andric
16730815c53SDimitry Andric D = ConstantInt::get(UseInst->getContext(),
168f8af5cf6SDimitry Andric APInt::getOneBitSet(BitWidth, D->getZExtValue()));
16930815c53SDimitry Andric }
170145449b1SDimitry Andric const auto *LHS = SE->getSCEV(IVSrc);
171145449b1SDimitry Andric const auto *RHS = SE->getSCEV(D);
172145449b1SDimitry Andric FoldedExpr = SE->getUDivExpr(LHS, RHS);
173d8e91e46SDimitry Andric // We might have 'exact' flag set at this point which will no longer be
174d8e91e46SDimitry Andric // correct after we make the replacement.
175145449b1SDimitry Andric if (UseInst->isExact() && LHS != SE->getMulExpr(FoldedExpr, RHS))
176d8e91e46SDimitry Andric MustDropExactFlag = true;
17730815c53SDimitry Andric }
17830815c53SDimitry Andric // We have something that might fold it's operand. Compare SCEVs.
17930815c53SDimitry Andric if (!SE->isSCEVable(UseInst->getType()))
1805ca98fd9SDimitry Andric return nullptr;
18130815c53SDimitry Andric
18230815c53SDimitry Andric // Bypass the operand if SCEV can prove it has no effect.
18330815c53SDimitry Andric if (SE->getSCEV(UseInst) != FoldedExpr)
1845ca98fd9SDimitry Andric return nullptr;
18530815c53SDimitry Andric
186eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
18730815c53SDimitry Andric << " -> " << *UseInst << '\n');
18830815c53SDimitry Andric
18930815c53SDimitry Andric UseInst->setOperand(OperIdx, IVSrc);
19030815c53SDimitry Andric assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
19130815c53SDimitry Andric
192d8e91e46SDimitry Andric if (MustDropExactFlag)
193d8e91e46SDimitry Andric UseInst->dropPoisonGeneratingFlags();
194d8e91e46SDimitry Andric
19530815c53SDimitry Andric ++NumElimOperand;
19630815c53SDimitry Andric Changed = true;
19730815c53SDimitry Andric if (IVOperand->use_empty())
19885d8b2bbSDimitry Andric DeadInsts.emplace_back(IVOperand);
19930815c53SDimitry Andric return IVSrc;
20030815c53SDimitry Andric }
20130815c53SDimitry Andric
makeIVComparisonInvariant(ICmpInst * ICmp,Instruction * IVOperand)202044eb2f6SDimitry Andric bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
2031f917f69SDimitry Andric Instruction *IVOperand) {
204e3b55780SDimitry Andric auto *Preheader = L->getLoopPreheader();
205e3b55780SDimitry Andric if (!Preheader)
206e3b55780SDimitry Andric return false;
207044eb2f6SDimitry Andric unsigned IVOperIdx = 0;
208044eb2f6SDimitry Andric ICmpInst::Predicate Pred = ICmp->getPredicate();
209044eb2f6SDimitry Andric if (IVOperand != ICmp->getOperand(0)) {
210044eb2f6SDimitry Andric // Swapped
211044eb2f6SDimitry Andric assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
212044eb2f6SDimitry Andric IVOperIdx = 1;
213044eb2f6SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred);
214044eb2f6SDimitry Andric }
215044eb2f6SDimitry Andric
216044eb2f6SDimitry Andric // Get the SCEVs for the ICmp operands (in the specific context of the
217044eb2f6SDimitry Andric // current loop)
218044eb2f6SDimitry Andric const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
219044eb2f6SDimitry Andric const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
220044eb2f6SDimitry Andric const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
221e3b55780SDimitry Andric auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L, ICmp);
222b60736ecSDimitry Andric if (!LIP)
223044eb2f6SDimitry Andric return false;
224b60736ecSDimitry Andric ICmpInst::Predicate InvariantPredicate = LIP->Pred;
225b60736ecSDimitry Andric const SCEV *InvariantLHS = LIP->LHS;
226b60736ecSDimitry Andric const SCEV *InvariantRHS = LIP->RHS;
227044eb2f6SDimitry Andric
228e3b55780SDimitry Andric // Do not generate something ridiculous.
229e3b55780SDimitry Andric auto *PHTerm = Preheader->getTerminator();
230e3b55780SDimitry Andric if (Rewriter.isHighCostExpansion({InvariantLHS, InvariantRHS}, L,
2317fa27ce4SDimitry Andric 2 * SCEVCheapExpansionBudget, TTI, PHTerm) ||
2327fa27ce4SDimitry Andric !Rewriter.isSafeToExpandAt(InvariantLHS, PHTerm) ||
2337fa27ce4SDimitry Andric !Rewriter.isSafeToExpandAt(InvariantRHS, PHTerm))
234044eb2f6SDimitry Andric return false;
235e3b55780SDimitry Andric auto *NewLHS =
236e3b55780SDimitry Andric Rewriter.expandCodeFor(InvariantLHS, IVOperand->getType(), PHTerm);
237e3b55780SDimitry Andric auto *NewRHS =
238e3b55780SDimitry Andric Rewriter.expandCodeFor(InvariantRHS, IVOperand->getType(), PHTerm);
239eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
240044eb2f6SDimitry Andric ICmp->setPredicate(InvariantPredicate);
241044eb2f6SDimitry Andric ICmp->setOperand(0, NewLHS);
242044eb2f6SDimitry Andric ICmp->setOperand(1, NewRHS);
243ac9a064cSDimitry Andric RunUnswitching = true;
244044eb2f6SDimitry Andric return true;
245044eb2f6SDimitry Andric }
246044eb2f6SDimitry Andric
24767c32a98SDimitry Andric /// SimplifyIVUsers helper for eliminating useless
24830815c53SDimitry Andric /// comparisons against an induction variable.
eliminateIVComparison(ICmpInst * ICmp,Instruction * IVOperand)2491f917f69SDimitry Andric void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp,
2501f917f69SDimitry Andric Instruction *IVOperand) {
25130815c53SDimitry Andric unsigned IVOperIdx = 0;
25230815c53SDimitry Andric ICmpInst::Predicate Pred = ICmp->getPredicate();
253ca089b24SDimitry Andric ICmpInst::Predicate OriginalPred = Pred;
25430815c53SDimitry Andric if (IVOperand != ICmp->getOperand(0)) {
25530815c53SDimitry Andric // Swapped
25630815c53SDimitry Andric assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
25730815c53SDimitry Andric IVOperIdx = 1;
25830815c53SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred);
25930815c53SDimitry Andric }
26030815c53SDimitry Andric
261044eb2f6SDimitry Andric // Get the SCEVs for the ICmp operands (in the specific context of the
262044eb2f6SDimitry Andric // current loop)
26330815c53SDimitry Andric const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
264044eb2f6SDimitry Andric const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
265044eb2f6SDimitry Andric const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
266dd58ef01SDimitry Andric
267344a3780SDimitry Andric // If the condition is always true or always false in the given context,
268344a3780SDimitry Andric // replace it with a constant value.
269344a3780SDimitry Andric SmallVector<Instruction *, 4> Users;
270344a3780SDimitry Andric for (auto *U : ICmp->users())
271344a3780SDimitry Andric Users.push_back(cast<Instruction>(U));
272344a3780SDimitry Andric const Instruction *CtxI = findCommonDominator(Users, *DT);
273344a3780SDimitry Andric if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) {
274e3b55780SDimitry Andric SE->forgetValue(ICmp);
275344a3780SDimitry Andric ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev));
276dd58ef01SDimitry Andric DeadInsts.emplace_back(ICmp);
277eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
278044eb2f6SDimitry Andric } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
279044eb2f6SDimitry Andric // fallthrough to end of function
280ca089b24SDimitry Andric } else if (ICmpInst::isSigned(OriginalPred) &&
281ca089b24SDimitry Andric SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
282ca089b24SDimitry Andric // If we were unable to make anything above, all we can is to canonicalize
283ca089b24SDimitry Andric // the comparison hoping that it will open the doors for other
284ca089b24SDimitry Andric // optimizations. If we find out that we compare two non-negative values,
285ca089b24SDimitry Andric // we turn the instruction's predicate to its unsigned version. Note that
286ca089b24SDimitry Andric // we cannot rely on Pred here unless we check if we have swapped it.
287ca089b24SDimitry Andric assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
288eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
289eb11fae6SDimitry Andric << '\n');
290ca089b24SDimitry Andric ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
291dd58ef01SDimitry Andric } else
292dd58ef01SDimitry Andric return;
293dd58ef01SDimitry Andric
29430815c53SDimitry Andric ++NumElimCmp;
29530815c53SDimitry Andric Changed = true;
29630815c53SDimitry Andric }
29730815c53SDimitry Andric
eliminateSDiv(BinaryOperator * SDiv)29871d5a254SDimitry Andric bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
29971d5a254SDimitry Andric // Get the SCEVs for the ICmp operands.
30071d5a254SDimitry Andric auto *N = SE->getSCEV(SDiv->getOperand(0));
30171d5a254SDimitry Andric auto *D = SE->getSCEV(SDiv->getOperand(1));
30271d5a254SDimitry Andric
30371d5a254SDimitry Andric // Simplify unnecessary loops away.
30471d5a254SDimitry Andric const Loop *L = LI->getLoopFor(SDiv->getParent());
30571d5a254SDimitry Andric N = SE->getSCEVAtScope(N, L);
30671d5a254SDimitry Andric D = SE->getSCEVAtScope(D, L);
30771d5a254SDimitry Andric
30871d5a254SDimitry Andric // Replace sdiv by udiv if both of the operands are non-negative
30971d5a254SDimitry Andric if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
31071d5a254SDimitry Andric auto *UDiv = BinaryOperator::Create(
31171d5a254SDimitry Andric BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
312ac9a064cSDimitry Andric SDiv->getName() + ".udiv", SDiv->getIterator());
31371d5a254SDimitry Andric UDiv->setIsExact(SDiv->isExact());
31471d5a254SDimitry Andric SDiv->replaceAllUsesWith(UDiv);
315ac9a064cSDimitry Andric UDiv->setDebugLoc(SDiv->getDebugLoc());
316eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
31771d5a254SDimitry Andric ++NumSimplifiedSDiv;
31871d5a254SDimitry Andric Changed = true;
31971d5a254SDimitry Andric DeadInsts.push_back(SDiv);
32071d5a254SDimitry Andric return true;
32171d5a254SDimitry Andric }
32271d5a254SDimitry Andric
32371d5a254SDimitry Andric return false;
32471d5a254SDimitry Andric }
32571d5a254SDimitry Andric
326044eb2f6SDimitry Andric // i %s n -> i %u n if i >= 0 and n >= 0
replaceSRemWithURem(BinaryOperator * Rem)327044eb2f6SDimitry Andric void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
328044eb2f6SDimitry Andric auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
329044eb2f6SDimitry Andric auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
330ac9a064cSDimitry Andric Rem->getName() + ".urem", Rem->getIterator());
331044eb2f6SDimitry Andric Rem->replaceAllUsesWith(URem);
332ac9a064cSDimitry Andric URem->setDebugLoc(Rem->getDebugLoc());
333eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
334044eb2f6SDimitry Andric ++NumSimplifiedSRem;
335044eb2f6SDimitry Andric Changed = true;
336044eb2f6SDimitry Andric DeadInsts.emplace_back(Rem);
33730815c53SDimitry Andric }
33830815c53SDimitry Andric
339044eb2f6SDimitry Andric // i % n --> i if i is in [0,n).
replaceRemWithNumerator(BinaryOperator * Rem)340044eb2f6SDimitry Andric void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
341044eb2f6SDimitry Andric Rem->replaceAllUsesWith(Rem->getOperand(0));
342eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
34330815c53SDimitry Andric ++NumElimRem;
34430815c53SDimitry Andric Changed = true;
34585d8b2bbSDimitry Andric DeadInsts.emplace_back(Rem);
34630815c53SDimitry Andric }
34730815c53SDimitry Andric
348044eb2f6SDimitry Andric // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
replaceRemWithNumeratorOrZero(BinaryOperator * Rem)349044eb2f6SDimitry Andric void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
350044eb2f6SDimitry Andric auto *T = Rem->getType();
351044eb2f6SDimitry Andric auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
352ac9a064cSDimitry Andric ICmpInst *ICmp = new ICmpInst(Rem->getIterator(), ICmpInst::ICMP_EQ, N, D);
353044eb2f6SDimitry Andric SelectInst *Sel =
354ac9a064cSDimitry Andric SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem->getIterator());
355044eb2f6SDimitry Andric Rem->replaceAllUsesWith(Sel);
356ac9a064cSDimitry Andric Sel->setDebugLoc(Rem->getDebugLoc());
357eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
358044eb2f6SDimitry Andric ++NumElimRem;
359044eb2f6SDimitry Andric Changed = true;
360044eb2f6SDimitry Andric DeadInsts.emplace_back(Rem);
361044eb2f6SDimitry Andric }
362044eb2f6SDimitry Andric
363044eb2f6SDimitry Andric /// SimplifyIVUsers helper for eliminating useless remainder operations
364044eb2f6SDimitry Andric /// operating on an induction variable or replacing srem by urem.
simplifyIVRemainder(BinaryOperator * Rem,Instruction * IVOperand,bool IsSigned)3651f917f69SDimitry Andric void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem,
3661f917f69SDimitry Andric Instruction *IVOperand,
367044eb2f6SDimitry Andric bool IsSigned) {
368044eb2f6SDimitry Andric auto *NValue = Rem->getOperand(0);
369044eb2f6SDimitry Andric auto *DValue = Rem->getOperand(1);
370044eb2f6SDimitry Andric // We're only interested in the case where we know something about
371044eb2f6SDimitry Andric // the numerator, unless it is a srem, because we want to replace srem by urem
372044eb2f6SDimitry Andric // in general.
373044eb2f6SDimitry Andric bool UsedAsNumerator = IVOperand == NValue;
374044eb2f6SDimitry Andric if (!UsedAsNumerator && !IsSigned)
375044eb2f6SDimitry Andric return;
376044eb2f6SDimitry Andric
377044eb2f6SDimitry Andric const SCEV *N = SE->getSCEV(NValue);
378044eb2f6SDimitry Andric
379044eb2f6SDimitry Andric // Simplify unnecessary loops away.
380044eb2f6SDimitry Andric const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
381044eb2f6SDimitry Andric N = SE->getSCEVAtScope(N, ICmpLoop);
382044eb2f6SDimitry Andric
383044eb2f6SDimitry Andric bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
384044eb2f6SDimitry Andric
385044eb2f6SDimitry Andric // Do not proceed if the Numerator may be negative
386044eb2f6SDimitry Andric if (!IsNumeratorNonNegative)
387044eb2f6SDimitry Andric return;
388044eb2f6SDimitry Andric
389044eb2f6SDimitry Andric const SCEV *D = SE->getSCEV(DValue);
390044eb2f6SDimitry Andric D = SE->getSCEVAtScope(D, ICmpLoop);
391044eb2f6SDimitry Andric
392044eb2f6SDimitry Andric if (UsedAsNumerator) {
393044eb2f6SDimitry Andric auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
394044eb2f6SDimitry Andric if (SE->isKnownPredicate(LT, N, D)) {
395044eb2f6SDimitry Andric replaceRemWithNumerator(Rem);
396044eb2f6SDimitry Andric return;
397044eb2f6SDimitry Andric }
398044eb2f6SDimitry Andric
399044eb2f6SDimitry Andric auto *T = Rem->getType();
400044eb2f6SDimitry Andric const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
401044eb2f6SDimitry Andric if (SE->isKnownPredicate(LT, NLessOne, D)) {
402044eb2f6SDimitry Andric replaceRemWithNumeratorOrZero(Rem);
403044eb2f6SDimitry Andric return;
404044eb2f6SDimitry Andric }
405044eb2f6SDimitry Andric }
406044eb2f6SDimitry Andric
407044eb2f6SDimitry Andric // Try to replace SRem with URem, if both N and D are known non-negative.
408044eb2f6SDimitry Andric // Since we had already check N, we only need to check D now
409044eb2f6SDimitry Andric if (!IsSigned || !SE->isKnownNonNegative(D))
410044eb2f6SDimitry Andric return;
411044eb2f6SDimitry Andric
412044eb2f6SDimitry Andric replaceSRemWithURem(Rem);
413044eb2f6SDimitry Andric }
414044eb2f6SDimitry Andric
eliminateOverflowIntrinsic(WithOverflowInst * WO)415e6d15924SDimitry Andric bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
416e6d15924SDimitry Andric const SCEV *LHS = SE->getSCEV(WO->getLHS());
417e6d15924SDimitry Andric const SCEV *RHS = SE->getSCEV(WO->getRHS());
418344a3780SDimitry Andric if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
41901095a5dSDimitry Andric return false;
42001095a5dSDimitry Andric
42101095a5dSDimitry Andric // Proved no overflow, nuke the overflow check and, if possible, the overflow
42201095a5dSDimitry Andric // intrinsic as well.
42301095a5dSDimitry Andric
42401095a5dSDimitry Andric BinaryOperator *NewResult = BinaryOperator::Create(
425ac9a064cSDimitry Andric WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO->getIterator());
42601095a5dSDimitry Andric
427e6d15924SDimitry Andric if (WO->isSigned())
42801095a5dSDimitry Andric NewResult->setHasNoSignedWrap(true);
42901095a5dSDimitry Andric else
43001095a5dSDimitry Andric NewResult->setHasNoUnsignedWrap(true);
43101095a5dSDimitry Andric
43201095a5dSDimitry Andric SmallVector<ExtractValueInst *, 4> ToDelete;
43301095a5dSDimitry Andric
434e6d15924SDimitry Andric for (auto *U : WO->users()) {
43501095a5dSDimitry Andric if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
43601095a5dSDimitry Andric if (EVI->getIndices()[0] == 1)
437e6d15924SDimitry Andric EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
43801095a5dSDimitry Andric else {
43901095a5dSDimitry Andric assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
44001095a5dSDimitry Andric EVI->replaceAllUsesWith(NewResult);
441ac9a064cSDimitry Andric NewResult->setDebugLoc(EVI->getDebugLoc());
44201095a5dSDimitry Andric }
44301095a5dSDimitry Andric ToDelete.push_back(EVI);
44401095a5dSDimitry Andric }
44501095a5dSDimitry Andric }
44601095a5dSDimitry Andric
44701095a5dSDimitry Andric for (auto *EVI : ToDelete)
44801095a5dSDimitry Andric EVI->eraseFromParent();
44901095a5dSDimitry Andric
450e6d15924SDimitry Andric if (WO->use_empty())
451e6d15924SDimitry Andric WO->eraseFromParent();
45201095a5dSDimitry Andric
453b60736ecSDimitry Andric Changed = true;
45401095a5dSDimitry Andric return true;
45501095a5dSDimitry Andric }
45601095a5dSDimitry Andric
eliminateSaturatingIntrinsic(SaturatingInst * SI)457e6d15924SDimitry Andric bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
458e6d15924SDimitry Andric const SCEV *LHS = SE->getSCEV(SI->getLHS());
459e6d15924SDimitry Andric const SCEV *RHS = SE->getSCEV(SI->getRHS());
460344a3780SDimitry Andric if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
461e6d15924SDimitry Andric return false;
462e6d15924SDimitry Andric
463e6d15924SDimitry Andric BinaryOperator *BO = BinaryOperator::Create(
464ac9a064cSDimitry Andric SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI->getIterator());
465e6d15924SDimitry Andric if (SI->isSigned())
466e6d15924SDimitry Andric BO->setHasNoSignedWrap();
467e6d15924SDimitry Andric else
468e6d15924SDimitry Andric BO->setHasNoUnsignedWrap();
469e6d15924SDimitry Andric
470e6d15924SDimitry Andric SI->replaceAllUsesWith(BO);
471ac9a064cSDimitry Andric BO->setDebugLoc(SI->getDebugLoc());
472e6d15924SDimitry Andric DeadInsts.emplace_back(SI);
473e6d15924SDimitry Andric Changed = true;
474e6d15924SDimitry Andric return true;
475e6d15924SDimitry Andric }
476e6d15924SDimitry Andric
eliminateTrunc(TruncInst * TI)477eb11fae6SDimitry Andric bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
478eb11fae6SDimitry Andric // It is always legal to replace
479eb11fae6SDimitry Andric // icmp <pred> i32 trunc(iv), n
480eb11fae6SDimitry Andric // with
481eb11fae6SDimitry Andric // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
482eb11fae6SDimitry Andric // Or with
483eb11fae6SDimitry Andric // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
484eb11fae6SDimitry Andric // Or with either of these if pred is an equality predicate.
485eb11fae6SDimitry Andric //
486eb11fae6SDimitry Andric // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
487eb11fae6SDimitry Andric // every comparison which uses trunc, it means that we can replace each of
488eb11fae6SDimitry Andric // them with comparison of iv against sext/zext(n). We no longer need trunc
489eb11fae6SDimitry Andric // after that.
490eb11fae6SDimitry Andric //
491eb11fae6SDimitry Andric // TODO: Should we do this if we can widen *some* comparisons, but not all
492eb11fae6SDimitry Andric // of them? Sometimes it is enough to enable other optimizations, but the
493eb11fae6SDimitry Andric // trunc instruction will stay in the loop.
494eb11fae6SDimitry Andric Value *IV = TI->getOperand(0);
495eb11fae6SDimitry Andric Type *IVTy = IV->getType();
496eb11fae6SDimitry Andric const SCEV *IVSCEV = SE->getSCEV(IV);
497eb11fae6SDimitry Andric const SCEV *TISCEV = SE->getSCEV(TI);
498eb11fae6SDimitry Andric
499eb11fae6SDimitry Andric // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
500eb11fae6SDimitry Andric // get rid of trunc
501eb11fae6SDimitry Andric bool DoesSExtCollapse = false;
502eb11fae6SDimitry Andric bool DoesZExtCollapse = false;
503eb11fae6SDimitry Andric if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
504eb11fae6SDimitry Andric DoesSExtCollapse = true;
505eb11fae6SDimitry Andric if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
506eb11fae6SDimitry Andric DoesZExtCollapse = true;
507eb11fae6SDimitry Andric
508eb11fae6SDimitry Andric // If neither sext nor zext does collapse, it is not profitable to do any
509eb11fae6SDimitry Andric // transform. Bail.
510eb11fae6SDimitry Andric if (!DoesSExtCollapse && !DoesZExtCollapse)
511eb11fae6SDimitry Andric return false;
512eb11fae6SDimitry Andric
513eb11fae6SDimitry Andric // Collect users of the trunc that look like comparisons against invariants.
514eb11fae6SDimitry Andric // Bail if we find something different.
515eb11fae6SDimitry Andric SmallVector<ICmpInst *, 4> ICmpUsers;
516eb11fae6SDimitry Andric for (auto *U : TI->users()) {
517eb11fae6SDimitry Andric // We don't care about users in unreachable blocks.
518eb11fae6SDimitry Andric if (isa<Instruction>(U) &&
519eb11fae6SDimitry Andric !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
520eb11fae6SDimitry Andric continue;
521e6d15924SDimitry Andric ICmpInst *ICI = dyn_cast<ICmpInst>(U);
522e6d15924SDimitry Andric if (!ICI) return false;
523eb11fae6SDimitry Andric assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
524e6d15924SDimitry Andric if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
525e6d15924SDimitry Andric !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
526e6d15924SDimitry Andric return false;
527eb11fae6SDimitry Andric // If we cannot get rid of trunc, bail.
528eb11fae6SDimitry Andric if (ICI->isSigned() && !DoesSExtCollapse)
529eb11fae6SDimitry Andric return false;
530eb11fae6SDimitry Andric if (ICI->isUnsigned() && !DoesZExtCollapse)
531eb11fae6SDimitry Andric return false;
532eb11fae6SDimitry Andric // For equality, either signed or unsigned works.
533eb11fae6SDimitry Andric ICmpUsers.push_back(ICI);
534eb11fae6SDimitry Andric }
535eb11fae6SDimitry Andric
536eb11fae6SDimitry Andric auto CanUseZExt = [&](ICmpInst *ICI) {
537eb11fae6SDimitry Andric // Unsigned comparison can be widened as unsigned.
538eb11fae6SDimitry Andric if (ICI->isUnsigned())
539eb11fae6SDimitry Andric return true;
540eb11fae6SDimitry Andric // Is it profitable to do zext?
541eb11fae6SDimitry Andric if (!DoesZExtCollapse)
542eb11fae6SDimitry Andric return false;
543eb11fae6SDimitry Andric // For equality, we can safely zext both parts.
544eb11fae6SDimitry Andric if (ICI->isEquality())
545eb11fae6SDimitry Andric return true;
546eb11fae6SDimitry Andric // Otherwise we can only use zext when comparing two non-negative or two
547eb11fae6SDimitry Andric // negative values. But in practice, we will never pass DoesZExtCollapse
548eb11fae6SDimitry Andric // check for a negative value, because zext(trunc(x)) is non-negative. So
549eb11fae6SDimitry Andric // it only make sense to check for non-negativity here.
550eb11fae6SDimitry Andric const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
551eb11fae6SDimitry Andric const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
552eb11fae6SDimitry Andric return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
553eb11fae6SDimitry Andric };
554eb11fae6SDimitry Andric // Replace all comparisons against trunc with comparisons against IV.
555eb11fae6SDimitry Andric for (auto *ICI : ICmpUsers) {
556e6d15924SDimitry Andric bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
557e6d15924SDimitry Andric auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
558b1c73532SDimitry Andric IRBuilder<> Builder(ICI);
559b1c73532SDimitry Andric Value *Ext = nullptr;
560eb11fae6SDimitry Andric // For signed/unsigned predicate, replace the old comparison with comparison
561eb11fae6SDimitry Andric // of immediate IV against sext/zext of the invariant argument. If we can
562eb11fae6SDimitry Andric // use either sext or zext (i.e. we are dealing with equality predicate),
563eb11fae6SDimitry Andric // then prefer zext as a more canonical form.
564eb11fae6SDimitry Andric // TODO: If we see a signed comparison which can be turned into unsigned,
565eb11fae6SDimitry Andric // we can do it here for canonicalization purposes.
566eb11fae6SDimitry Andric ICmpInst::Predicate Pred = ICI->getPredicate();
567e6d15924SDimitry Andric if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
568eb11fae6SDimitry Andric if (CanUseZExt(ICI)) {
569eb11fae6SDimitry Andric assert(DoesZExtCollapse && "Unprofitable zext?");
570b1c73532SDimitry Andric Ext = Builder.CreateZExt(Op1, IVTy, "zext");
571eb11fae6SDimitry Andric Pred = ICmpInst::getUnsignedPredicate(Pred);
572eb11fae6SDimitry Andric } else {
573eb11fae6SDimitry Andric assert(DoesSExtCollapse && "Unprofitable sext?");
574b1c73532SDimitry Andric Ext = Builder.CreateSExt(Op1, IVTy, "sext");
575eb11fae6SDimitry Andric assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
576eb11fae6SDimitry Andric }
577eb11fae6SDimitry Andric bool Changed;
578eb11fae6SDimitry Andric L->makeLoopInvariant(Ext, Changed);
579eb11fae6SDimitry Andric (void)Changed;
580b1c73532SDimitry Andric auto *NewCmp = Builder.CreateICmp(Pred, IV, Ext);
581b1c73532SDimitry Andric ICI->replaceAllUsesWith(NewCmp);
582eb11fae6SDimitry Andric DeadInsts.emplace_back(ICI);
583eb11fae6SDimitry Andric }
584eb11fae6SDimitry Andric
585eb11fae6SDimitry Andric // Trunc no longer needed.
5864b4fe385SDimitry Andric TI->replaceAllUsesWith(PoisonValue::get(TI->getType()));
587eb11fae6SDimitry Andric DeadInsts.emplace_back(TI);
588eb11fae6SDimitry Andric return true;
589eb11fae6SDimitry Andric }
590eb11fae6SDimitry Andric
591dd58ef01SDimitry Andric /// Eliminate an operation that consumes a simple IV and has no observable
592dd58ef01SDimitry Andric /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
593dd58ef01SDimitry Andric /// but UseInst may not be.
eliminateIVUser(Instruction * UseInst,Instruction * IVOperand)59430815c53SDimitry Andric bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
59530815c53SDimitry Andric Instruction *IVOperand) {
59630815c53SDimitry Andric if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
59730815c53SDimitry Andric eliminateIVComparison(ICmp, IVOperand);
59830815c53SDimitry Andric return true;
59930815c53SDimitry Andric }
60071d5a254SDimitry Andric if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
60171d5a254SDimitry Andric bool IsSRem = Bin->getOpcode() == Instruction::SRem;
60271d5a254SDimitry Andric if (IsSRem || Bin->getOpcode() == Instruction::URem) {
603044eb2f6SDimitry Andric simplifyIVRemainder(Bin, IVOperand, IsSRem);
60430815c53SDimitry Andric return true;
60530815c53SDimitry Andric }
60671d5a254SDimitry Andric
60771d5a254SDimitry Andric if (Bin->getOpcode() == Instruction::SDiv)
60871d5a254SDimitry Andric return eliminateSDiv(Bin);
60930815c53SDimitry Andric }
61030815c53SDimitry Andric
611e6d15924SDimitry Andric if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
612e6d15924SDimitry Andric if (eliminateOverflowIntrinsic(WO))
613e6d15924SDimitry Andric return true;
614e6d15924SDimitry Andric
615e6d15924SDimitry Andric if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
616e6d15924SDimitry Andric if (eliminateSaturatingIntrinsic(SI))
61701095a5dSDimitry Andric return true;
61801095a5dSDimitry Andric
619eb11fae6SDimitry Andric if (auto *TI = dyn_cast<TruncInst>(UseInst))
620eb11fae6SDimitry Andric if (eliminateTrunc(TI))
621eb11fae6SDimitry Andric return true;
622eb11fae6SDimitry Andric
623dd58ef01SDimitry Andric if (eliminateIdentitySCEV(UseInst, IVOperand))
624dd58ef01SDimitry Andric return true;
625dd58ef01SDimitry Andric
626dd58ef01SDimitry Andric return false;
627dd58ef01SDimitry Andric }
628dd58ef01SDimitry Andric
GetLoopInvariantInsertPosition(Loop * L,Instruction * Hint)629044eb2f6SDimitry Andric static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
630044eb2f6SDimitry Andric if (auto *BB = L->getLoopPreheader())
631044eb2f6SDimitry Andric return BB->getTerminator();
632044eb2f6SDimitry Andric
633044eb2f6SDimitry Andric return Hint;
634044eb2f6SDimitry Andric }
635044eb2f6SDimitry Andric
636cfca06d7SDimitry Andric /// Replace the UseInst with a loop invariant expression if it is safe.
replaceIVUserWithLoopInvariant(Instruction * I)637044eb2f6SDimitry Andric bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
638044eb2f6SDimitry Andric if (!SE->isSCEVable(I->getType()))
639044eb2f6SDimitry Andric return false;
640044eb2f6SDimitry Andric
641044eb2f6SDimitry Andric // Get the symbolic expression for this instruction.
642044eb2f6SDimitry Andric const SCEV *S = SE->getSCEV(I);
643044eb2f6SDimitry Andric
644044eb2f6SDimitry Andric if (!SE->isLoopInvariant(S, L))
645044eb2f6SDimitry Andric return false;
646044eb2f6SDimitry Andric
647044eb2f6SDimitry Andric // Do not generate something ridiculous even if S is loop invariant.
648cfca06d7SDimitry Andric if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
649044eb2f6SDimitry Andric return false;
650044eb2f6SDimitry Andric
651044eb2f6SDimitry Andric auto *IP = GetLoopInvariantInsertPosition(L, I);
652cfca06d7SDimitry Andric
6534b4fe385SDimitry Andric if (!Rewriter.isSafeToExpandAt(S, IP)) {
654cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
655cfca06d7SDimitry Andric << " with non-speculable loop invariant: " << *S << '\n');
656cfca06d7SDimitry Andric return false;
657cfca06d7SDimitry Andric }
658cfca06d7SDimitry Andric
659044eb2f6SDimitry Andric auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
660ac9a064cSDimitry Andric bool NeedToEmitLCSSAPhis = false;
661ac9a064cSDimitry Andric if (!LI->replacementPreservesLCSSAForm(I, Invariant))
662ac9a064cSDimitry Andric NeedToEmitLCSSAPhis = true;
663044eb2f6SDimitry Andric
664044eb2f6SDimitry Andric I->replaceAllUsesWith(Invariant);
665eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
666044eb2f6SDimitry Andric << " with loop invariant: " << *S << '\n');
667ac9a064cSDimitry Andric
668ac9a064cSDimitry Andric if (NeedToEmitLCSSAPhis) {
669ac9a064cSDimitry Andric SmallVector<Instruction *, 1> NeedsLCSSAPhis;
670ac9a064cSDimitry Andric NeedsLCSSAPhis.push_back(cast<Instruction>(Invariant));
671ac9a064cSDimitry Andric formLCSSAForInstructions(NeedsLCSSAPhis, *DT, *LI, SE);
672ac9a064cSDimitry Andric LLVM_DEBUG(dbgs() << " INDVARS: Replacement breaks LCSSA form"
673ac9a064cSDimitry Andric << " inserting LCSSA Phis" << '\n');
674ac9a064cSDimitry Andric }
675044eb2f6SDimitry Andric ++NumFoldedUser;
676044eb2f6SDimitry Andric Changed = true;
677044eb2f6SDimitry Andric DeadInsts.emplace_back(I);
678044eb2f6SDimitry Andric return true;
679044eb2f6SDimitry Andric }
680044eb2f6SDimitry Andric
6811f917f69SDimitry Andric /// Eliminate redundant type cast between integer and float.
replaceFloatIVWithIntegerIV(Instruction * UseInst)6821f917f69SDimitry Andric bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) {
6834b4fe385SDimitry Andric if (UseInst->getOpcode() != CastInst::SIToFP &&
6844b4fe385SDimitry Andric UseInst->getOpcode() != CastInst::UIToFP)
6851f917f69SDimitry Andric return false;
6861f917f69SDimitry Andric
687e3b55780SDimitry Andric Instruction *IVOperand = cast<Instruction>(UseInst->getOperand(0));
6881f917f69SDimitry Andric // Get the symbolic expression for this instruction.
6894b4fe385SDimitry Andric const SCEV *IV = SE->getSCEV(IVOperand);
690b1c73532SDimitry Andric int MaskBits;
6914b4fe385SDimitry Andric if (UseInst->getOpcode() == CastInst::SIToFP)
692b1c73532SDimitry Andric MaskBits = (int)SE->getSignedRange(IV).getMinSignedBits();
6934b4fe385SDimitry Andric else
694b1c73532SDimitry Andric MaskBits = (int)SE->getUnsignedRange(IV).getActiveBits();
695b1c73532SDimitry Andric int DestNumSigBits = UseInst->getType()->getFPMantissaWidth();
6964b4fe385SDimitry Andric if (MaskBits <= DestNumSigBits) {
6971f917f69SDimitry Andric for (User *U : UseInst->users()) {
6984b4fe385SDimitry Andric // Match for fptosi/fptoui of sitofp and with same type.
6994b4fe385SDimitry Andric auto *CI = dyn_cast<CastInst>(U);
700e3b55780SDimitry Andric if (!CI)
7011f917f69SDimitry Andric continue;
7021f917f69SDimitry Andric
7034b4fe385SDimitry Andric CastInst::CastOps Opcode = CI->getOpcode();
7044b4fe385SDimitry Andric if (Opcode != CastInst::FPToSI && Opcode != CastInst::FPToUI)
7054b4fe385SDimitry Andric continue;
7064b4fe385SDimitry Andric
707e3b55780SDimitry Andric Value *Conv = nullptr;
708e3b55780SDimitry Andric if (IVOperand->getType() != CI->getType()) {
709e3b55780SDimitry Andric IRBuilder<> Builder(CI);
710e3b55780SDimitry Andric StringRef Name = IVOperand->getName();
711e3b55780SDimitry Andric // To match InstCombine logic, we only need sext if both fptosi and
712e3b55780SDimitry Andric // sitofp are used. If one of them is unsigned, then we can use zext.
713e3b55780SDimitry Andric if (SE->getTypeSizeInBits(IVOperand->getType()) >
714e3b55780SDimitry Andric SE->getTypeSizeInBits(CI->getType())) {
715e3b55780SDimitry Andric Conv = Builder.CreateTrunc(IVOperand, CI->getType(), Name + ".trunc");
716e3b55780SDimitry Andric } else if (Opcode == CastInst::FPToUI ||
717e3b55780SDimitry Andric UseInst->getOpcode() == CastInst::UIToFP) {
718e3b55780SDimitry Andric Conv = Builder.CreateZExt(IVOperand, CI->getType(), Name + ".zext");
719e3b55780SDimitry Andric } else {
720e3b55780SDimitry Andric Conv = Builder.CreateSExt(IVOperand, CI->getType(), Name + ".sext");
721e3b55780SDimitry Andric }
722e3b55780SDimitry Andric } else
723e3b55780SDimitry Andric Conv = IVOperand;
724e3b55780SDimitry Andric
725e3b55780SDimitry Andric CI->replaceAllUsesWith(Conv);
7261f917f69SDimitry Andric DeadInsts.push_back(CI);
7271f917f69SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI
728e3b55780SDimitry Andric << " with: " << *Conv << '\n');
7291f917f69SDimitry Andric
7301f917f69SDimitry Andric ++NumFoldedUser;
7311f917f69SDimitry Andric Changed = true;
7321f917f69SDimitry Andric }
7331f917f69SDimitry Andric }
7341f917f69SDimitry Andric
7351f917f69SDimitry Andric return Changed;
7361f917f69SDimitry Andric }
7371f917f69SDimitry Andric
738dd58ef01SDimitry Andric /// Eliminate any operation that SCEV can prove is an identity function.
eliminateIdentitySCEV(Instruction * UseInst,Instruction * IVOperand)739dd58ef01SDimitry Andric bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
740dd58ef01SDimitry Andric Instruction *IVOperand) {
74130815c53SDimitry Andric if (!SE->isSCEVable(UseInst->getType()) ||
742ac9a064cSDimitry Andric UseInst->getType() != IVOperand->getType())
743ac9a064cSDimitry Andric return false;
744ac9a064cSDimitry Andric
745ac9a064cSDimitry Andric const SCEV *UseSCEV = SE->getSCEV(UseInst);
746ac9a064cSDimitry Andric if (UseSCEV != SE->getSCEV(IVOperand))
74730815c53SDimitry Andric return false;
74830815c53SDimitry Andric
749dd58ef01SDimitry Andric // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
750dd58ef01SDimitry Andric // dominator tree, even if X is an operand to Y. For instance, in
751dd58ef01SDimitry Andric //
752dd58ef01SDimitry Andric // %iv = phi i32 {0,+,1}
753dd58ef01SDimitry Andric // br %cond, label %left, label %merge
754dd58ef01SDimitry Andric //
755dd58ef01SDimitry Andric // left:
756dd58ef01SDimitry Andric // %X = add i32 %iv, 0
757dd58ef01SDimitry Andric // br label %merge
758dd58ef01SDimitry Andric //
759dd58ef01SDimitry Andric // merge:
760dd58ef01SDimitry Andric // %M = phi (%X, %iv)
761dd58ef01SDimitry Andric //
762dd58ef01SDimitry Andric // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
763dd58ef01SDimitry Andric // %M.replaceAllUsesWith(%X) would be incorrect.
764dd58ef01SDimitry Andric
765dd58ef01SDimitry Andric if (isa<PHINode>(UseInst))
766dd58ef01SDimitry Andric // If UseInst is not a PHI node then we know that IVOperand dominates
767dd58ef01SDimitry Andric // UseInst directly from the legality of SSA.
768dd58ef01SDimitry Andric if (!DT || !DT->dominates(IVOperand, UseInst))
769dd58ef01SDimitry Andric return false;
770dd58ef01SDimitry Andric
771dd58ef01SDimitry Andric if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
772dd58ef01SDimitry Andric return false;
773dd58ef01SDimitry Andric
774ac9a064cSDimitry Andric // Make sure the operand is not more poisonous than the instruction.
775ac9a064cSDimitry Andric if (!impliesPoison(IVOperand, UseInst)) {
776ac9a064cSDimitry Andric SmallVector<Instruction *> DropPoisonGeneratingInsts;
777ac9a064cSDimitry Andric if (!SE->canReuseInstruction(UseSCEV, IVOperand, DropPoisonGeneratingInsts))
778ac9a064cSDimitry Andric return false;
779ac9a064cSDimitry Andric
780ac9a064cSDimitry Andric for (Instruction *I : DropPoisonGeneratingInsts)
781ac9a064cSDimitry Andric I->dropPoisonGeneratingAnnotations();
782ac9a064cSDimitry Andric }
783ac9a064cSDimitry Andric
784eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
78530815c53SDimitry Andric
786e3b55780SDimitry Andric SE->forgetValue(UseInst);
78730815c53SDimitry Andric UseInst->replaceAllUsesWith(IVOperand);
78830815c53SDimitry Andric ++NumElimIdentity;
78930815c53SDimitry Andric Changed = true;
79085d8b2bbSDimitry Andric DeadInsts.emplace_back(UseInst);
79130815c53SDimitry Andric return true;
79230815c53SDimitry Andric }
79330815c53SDimitry Andric
strengthenBinaryOp(BinaryOperator * BO,Instruction * IVOperand)7947fa27ce4SDimitry Andric bool SimplifyIndvar::strengthenBinaryOp(BinaryOperator *BO,
7957fa27ce4SDimitry Andric Instruction *IVOperand) {
7967fa27ce4SDimitry Andric return (isa<OverflowingBinaryOperator>(BO) &&
7977fa27ce4SDimitry Andric strengthenOverflowingOperation(BO, IVOperand)) ||
7987fa27ce4SDimitry Andric (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand));
7997fa27ce4SDimitry Andric }
8007fa27ce4SDimitry Andric
80167c32a98SDimitry Andric /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
80267c32a98SDimitry Andric /// unsigned-overflow. Returns true if anything changed, false otherwise.
strengthenOverflowingOperation(BinaryOperator * BO,Instruction * IVOperand)80367c32a98SDimitry Andric bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
8041f917f69SDimitry Andric Instruction *IVOperand) {
8051f917f69SDimitry Andric auto Flags = SE->getStrengthenedNoWrapFlagsFromBinOp(
806344a3780SDimitry Andric cast<OverflowingBinaryOperator>(BO));
80767c32a98SDimitry Andric
8081f917f69SDimitry Andric if (!Flags)
8091f917f69SDimitry Andric return false;
81067c32a98SDimitry Andric
8111f917f69SDimitry Andric BO->setHasNoUnsignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) ==
812344a3780SDimitry Andric SCEV::FlagNUW);
8131f917f69SDimitry Andric BO->setHasNoSignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) ==
814344a3780SDimitry Andric SCEV::FlagNSW);
81567c32a98SDimitry Andric
816344a3780SDimitry Andric // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap
817344a3780SDimitry Andric // flags on addrecs while performing zero/sign extensions. We could call
818344a3780SDimitry Andric // forgetValue() here to make sure those flags also propagate to any other
819344a3780SDimitry Andric // SCEV expressions based on the addrec. However, this can have pathological
820344a3780SDimitry Andric // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384.
8211f917f69SDimitry Andric return true;
82267c32a98SDimitry Andric }
82367c32a98SDimitry Andric
824ca089b24SDimitry Andric /// Annotate the Shr in (X << IVOperand) >> C as exact using the
825ca089b24SDimitry Andric /// information from the IV's range. Returns true if anything changed, false
826ca089b24SDimitry Andric /// otherwise.
strengthenRightShift(BinaryOperator * BO,Instruction * IVOperand)827ca089b24SDimitry Andric bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
8281f917f69SDimitry Andric Instruction *IVOperand) {
829ca089b24SDimitry Andric if (BO->getOpcode() == Instruction::Shl) {
830ca089b24SDimitry Andric bool Changed = false;
831ca089b24SDimitry Andric ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
832ca089b24SDimitry Andric for (auto *U : BO->users()) {
833ca089b24SDimitry Andric const APInt *C;
834ca089b24SDimitry Andric if (match(U,
835ca089b24SDimitry Andric m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
836ca089b24SDimitry Andric match(U,
837ca089b24SDimitry Andric m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
838ca089b24SDimitry Andric BinaryOperator *Shr = cast<BinaryOperator>(U);
839ca089b24SDimitry Andric if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
840ca089b24SDimitry Andric Shr->setIsExact(true);
841ca089b24SDimitry Andric Changed = true;
842ca089b24SDimitry Andric }
843ca089b24SDimitry Andric }
844ca089b24SDimitry Andric }
845ca089b24SDimitry Andric return Changed;
846ca089b24SDimitry Andric }
847ca089b24SDimitry Andric
848ca089b24SDimitry Andric return false;
849ca089b24SDimitry Andric }
850ca089b24SDimitry Andric
85167c32a98SDimitry Andric /// Add all uses of Def to the current IV's worklist.
pushIVUsers(Instruction * Def,SmallPtrSet<Instruction *,16> & Simplified,SmallVectorImpl<std::pair<Instruction *,Instruction * >> & SimpleIVUsers)852ac9a064cSDimitry Andric void SimplifyIndvar::pushIVUsers(
853ac9a064cSDimitry Andric Instruction *Def, SmallPtrSet<Instruction *, 16> &Simplified,
85430815c53SDimitry Andric SmallVectorImpl<std::pair<Instruction *, Instruction *>> &SimpleIVUsers) {
8555ca98fd9SDimitry Andric for (User *U : Def->users()) {
8565ca98fd9SDimitry Andric Instruction *UI = cast<Instruction>(U);
85730815c53SDimitry Andric
85830815c53SDimitry Andric // Avoid infinite or exponential worklist processing.
85930815c53SDimitry Andric // Also ensure unique worklist users.
86030815c53SDimitry Andric // If Def is a LoopPhi, it may not be in the Simplified set, so check for
86130815c53SDimitry Andric // self edges first.
862044eb2f6SDimitry Andric if (UI == Def)
863044eb2f6SDimitry Andric continue;
864044eb2f6SDimitry Andric
865044eb2f6SDimitry Andric // Only change the current Loop, do not change the other parts (e.g. other
866044eb2f6SDimitry Andric // Loops).
867044eb2f6SDimitry Andric if (!L->contains(UI))
868044eb2f6SDimitry Andric continue;
869044eb2f6SDimitry Andric
870044eb2f6SDimitry Andric // Do not push the same instruction more than once.
871044eb2f6SDimitry Andric if (!Simplified.insert(UI).second)
872044eb2f6SDimitry Andric continue;
873044eb2f6SDimitry Andric
8745ca98fd9SDimitry Andric SimpleIVUsers.push_back(std::make_pair(UI, Def));
87530815c53SDimitry Andric }
87630815c53SDimitry Andric }
87730815c53SDimitry Andric
87867c32a98SDimitry Andric /// Return true if this instruction generates a simple SCEV
87930815c53SDimitry Andric /// expression in terms of that IV.
88030815c53SDimitry Andric ///
88130815c53SDimitry Andric /// This is similar to IVUsers' isInteresting() but processes each instruction
88230815c53SDimitry Andric /// non-recursively when the operand is already known to be a simpleIVUser.
88330815c53SDimitry Andric ///
isSimpleIVUser(Instruction * I,const Loop * L,ScalarEvolution * SE)88430815c53SDimitry Andric static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
88530815c53SDimitry Andric if (!SE->isSCEVable(I->getType()))
88630815c53SDimitry Andric return false;
88730815c53SDimitry Andric
88830815c53SDimitry Andric // Get the symbolic expression for this instruction.
88930815c53SDimitry Andric const SCEV *S = SE->getSCEV(I);
89030815c53SDimitry Andric
89130815c53SDimitry Andric // Only consider affine recurrences.
89230815c53SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
89330815c53SDimitry Andric if (AR && AR->getLoop() == L)
89430815c53SDimitry Andric return true;
89530815c53SDimitry Andric
89630815c53SDimitry Andric return false;
89730815c53SDimitry Andric }
89830815c53SDimitry Andric
89967c32a98SDimitry Andric /// Iteratively perform simplification on a worklist of users
90030815c53SDimitry Andric /// of the specified induction variable. Each successive simplification may push
90130815c53SDimitry Andric /// more users which may themselves be candidates for simplification.
90230815c53SDimitry Andric ///
90330815c53SDimitry Andric /// This algorithm does not require IVUsers analysis. Instead, it simplifies
90430815c53SDimitry Andric /// instructions in-place during analysis. Rather than rewriting induction
90530815c53SDimitry Andric /// variables bottom-up from their users, it transforms a chain of IVUsers
906dd58ef01SDimitry Andric /// top-down, updating the IR only when it encounters a clear optimization
907dd58ef01SDimitry Andric /// opportunity.
90830815c53SDimitry Andric ///
90930815c53SDimitry Andric /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
91030815c53SDimitry Andric ///
simplifyUsers(PHINode * CurrIV,IVVisitor * V)91130815c53SDimitry Andric void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
91230815c53SDimitry Andric if (!SE->isSCEVable(CurrIV->getType()))
91330815c53SDimitry Andric return;
91430815c53SDimitry Andric
91530815c53SDimitry Andric // Instructions processed by SimplifyIndvar for CurrIV.
91630815c53SDimitry Andric SmallPtrSet<Instruction*,16> Simplified;
91730815c53SDimitry Andric
91830815c53SDimitry Andric // Use-def pairs if IV users waiting to be processed for CurrIV.
91930815c53SDimitry Andric SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
92030815c53SDimitry Andric
92130815c53SDimitry Andric // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
92230815c53SDimitry Andric // called multiple times for the same LoopPhi. This is the proper thing to
92330815c53SDimitry Andric // do for loop header phis that use each other.
924ac9a064cSDimitry Andric pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
92530815c53SDimitry Andric
92630815c53SDimitry Andric while (!SimpleIVUsers.empty()) {
92730815c53SDimitry Andric std::pair<Instruction*, Instruction*> UseOper =
92830815c53SDimitry Andric SimpleIVUsers.pop_back_val();
9295ca98fd9SDimitry Andric Instruction *UseInst = UseOper.first;
9305ca98fd9SDimitry Andric
931eb11fae6SDimitry Andric // If a user of the IndVar is trivially dead, we prefer just to mark it dead
932eb11fae6SDimitry Andric // rather than try to do some complex analysis or transformation (such as
933eb11fae6SDimitry Andric // widening) basing on it.
934eb11fae6SDimitry Andric // TODO: Propagate TLI and pass it here to handle more cases.
935eb11fae6SDimitry Andric if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
936eb11fae6SDimitry Andric DeadInsts.emplace_back(UseInst);
937eb11fae6SDimitry Andric continue;
938eb11fae6SDimitry Andric }
939eb11fae6SDimitry Andric
94030815c53SDimitry Andric // Bypass back edges to avoid extra work.
9415ca98fd9SDimitry Andric if (UseInst == CurrIV) continue;
9425ca98fd9SDimitry Andric
943044eb2f6SDimitry Andric // Try to replace UseInst with a loop invariant before any other
944044eb2f6SDimitry Andric // simplifications.
945044eb2f6SDimitry Andric if (replaceIVUserWithLoopInvariant(UseInst))
946044eb2f6SDimitry Andric continue;
947044eb2f6SDimitry Andric
948b1c73532SDimitry Andric // Go further for the bitcast 'prtoint ptr to i64' or if the cast is done
949b1c73532SDimitry Andric // by truncation
950b1c73532SDimitry Andric if ((isa<PtrToIntInst>(UseInst)) || (isa<TruncInst>(UseInst)))
9517fa27ce4SDimitry Andric for (Use &U : UseInst->uses()) {
9527fa27ce4SDimitry Andric Instruction *User = cast<Instruction>(U.getUser());
9537fa27ce4SDimitry Andric if (replaceIVUserWithLoopInvariant(User))
9547fa27ce4SDimitry Andric break; // done replacing
9557fa27ce4SDimitry Andric }
9567fa27ce4SDimitry Andric
95730815c53SDimitry Andric Instruction *IVOperand = UseOper.second;
95830815c53SDimitry Andric for (unsigned N = 0; IVOperand; ++N) {
95930815c53SDimitry Andric assert(N <= Simplified.size() && "runaway iteration");
960145449b1SDimitry Andric (void) N;
96130815c53SDimitry Andric
962eb11fae6SDimitry Andric Value *NewOper = foldIVUser(UseInst, IVOperand);
96330815c53SDimitry Andric if (!NewOper)
96430815c53SDimitry Andric break; // done folding
96530815c53SDimitry Andric IVOperand = dyn_cast<Instruction>(NewOper);
96630815c53SDimitry Andric }
96730815c53SDimitry Andric if (!IVOperand)
96830815c53SDimitry Andric continue;
96930815c53SDimitry Andric
970eb11fae6SDimitry Andric if (eliminateIVUser(UseInst, IVOperand)) {
971ac9a064cSDimitry Andric pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
97230815c53SDimitry Andric continue;
97330815c53SDimitry Andric }
97467c32a98SDimitry Andric
975eb11fae6SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
9767fa27ce4SDimitry Andric if (strengthenBinaryOp(BO, IVOperand)) {
97767c32a98SDimitry Andric // re-queue uses of the now modified binary operator and fall
97867c32a98SDimitry Andric // through to the checks that remain.
979ac9a064cSDimitry Andric pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
98067c32a98SDimitry Andric }
98167c32a98SDimitry Andric }
98267c32a98SDimitry Andric
9831f917f69SDimitry Andric // Try to use integer induction for FPToSI of float induction directly.
9841f917f69SDimitry Andric if (replaceFloatIVWithIntegerIV(UseInst)) {
9851f917f69SDimitry Andric // Re-queue the potentially new direct uses of IVOperand.
986ac9a064cSDimitry Andric pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
9871f917f69SDimitry Andric continue;
9881f917f69SDimitry Andric }
9891f917f69SDimitry Andric
990eb11fae6SDimitry Andric CastInst *Cast = dyn_cast<CastInst>(UseInst);
99130815c53SDimitry Andric if (V && Cast) {
99230815c53SDimitry Andric V->visitCast(Cast);
99330815c53SDimitry Andric continue;
99430815c53SDimitry Andric }
995eb11fae6SDimitry Andric if (isSimpleIVUser(UseInst, L, SE)) {
996ac9a064cSDimitry Andric pushIVUsers(UseInst, Simplified, SimpleIVUsers);
99730815c53SDimitry Andric }
99830815c53SDimitry Andric }
99930815c53SDimitry Andric }
100030815c53SDimitry Andric
100130815c53SDimitry Andric namespace llvm {
100230815c53SDimitry Andric
anchor()100363faed5bSDimitry Andric void IVVisitor::anchor() { }
100463faed5bSDimitry Andric
100567c32a98SDimitry Andric /// Simplify instructions that use this induction variable
100630815c53SDimitry Andric /// by using ScalarEvolution to analyze the IV's recurrence.
1007ac9a064cSDimitry Andric /// Returns a pair where the first entry indicates that the function makes
1008ac9a064cSDimitry Andric /// changes and the second entry indicates that it introduced new opportunities
1009ac9a064cSDimitry Andric /// for loop unswitching.
simplifyUsersOfIV(PHINode * CurrIV,ScalarEvolution * SE,DominatorTree * DT,LoopInfo * LI,const TargetTransformInfo * TTI,SmallVectorImpl<WeakTrackingVH> & Dead,SCEVExpander & Rewriter,IVVisitor * V)1010ac9a064cSDimitry Andric std::pair<bool, bool> simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE,
1011ac9a064cSDimitry Andric DominatorTree *DT, LoopInfo *LI,
1012ac9a064cSDimitry Andric const TargetTransformInfo *TTI,
1013cfca06d7SDimitry Andric SmallVectorImpl<WeakTrackingVH> &Dead,
1014044eb2f6SDimitry Andric SCEVExpander &Rewriter, IVVisitor *V) {
1015cfca06d7SDimitry Andric SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI,
1016cfca06d7SDimitry Andric Rewriter, Dead);
101730815c53SDimitry Andric SIV.simplifyUsers(CurrIV, V);
1018ac9a064cSDimitry Andric return {SIV.hasChanged(), SIV.runUnswitching()};
101930815c53SDimitry Andric }
102030815c53SDimitry Andric
102167c32a98SDimitry Andric /// Simplify users of induction variables within this
102230815c53SDimitry 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)1023dd58ef01SDimitry Andric bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
1024cfca06d7SDimitry Andric LoopInfo *LI, const TargetTransformInfo *TTI,
1025cfca06d7SDimitry Andric SmallVectorImpl<WeakTrackingVH> &Dead) {
1026044eb2f6SDimitry Andric SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
1027044eb2f6SDimitry Andric #ifndef NDEBUG
1028044eb2f6SDimitry Andric Rewriter.setDebugType(DEBUG_TYPE);
1029044eb2f6SDimitry Andric #endif
103030815c53SDimitry Andric bool Changed = false;
103130815c53SDimitry Andric for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1032ac9a064cSDimitry Andric const auto &[C, _] =
1033cfca06d7SDimitry Andric simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter);
1034ac9a064cSDimitry Andric Changed |= C;
103530815c53SDimitry Andric }
103630815c53SDimitry Andric return Changed;
103730815c53SDimitry Andric }
103830815c53SDimitry Andric
103930815c53SDimitry Andric } // namespace llvm
1040b60736ecSDimitry Andric
1041c0981da4SDimitry Andric namespace {
1042b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
1043b60736ecSDimitry Andric // Widen Induction Variables - Extend the width of an IV to cover its
1044b60736ecSDimitry Andric // widest uses.
1045b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
1046b60736ecSDimitry Andric
1047b60736ecSDimitry Andric class WidenIV {
1048b60736ecSDimitry Andric // Parameters
1049b60736ecSDimitry Andric PHINode *OrigPhi;
1050b60736ecSDimitry Andric Type *WideType;
1051b60736ecSDimitry Andric
1052b60736ecSDimitry Andric // Context
1053b60736ecSDimitry Andric LoopInfo *LI;
1054b60736ecSDimitry Andric Loop *L;
1055b60736ecSDimitry Andric ScalarEvolution *SE;
1056b60736ecSDimitry Andric DominatorTree *DT;
1057b60736ecSDimitry Andric
1058b60736ecSDimitry Andric // Does the module have any calls to the llvm.experimental.guard intrinsic
1059b60736ecSDimitry Andric // at all? If not we can avoid scanning instructions looking for guards.
1060b60736ecSDimitry Andric bool HasGuards;
1061b60736ecSDimitry Andric
1062b60736ecSDimitry Andric bool UsePostIncrementRanges;
1063b60736ecSDimitry Andric
1064b60736ecSDimitry Andric // Statistics
1065b60736ecSDimitry Andric unsigned NumElimExt = 0;
1066b60736ecSDimitry Andric unsigned NumWidened = 0;
1067b60736ecSDimitry Andric
1068b60736ecSDimitry Andric // Result
1069b60736ecSDimitry Andric PHINode *WidePhi = nullptr;
1070b60736ecSDimitry Andric Instruction *WideInc = nullptr;
1071b60736ecSDimitry Andric const SCEV *WideIncExpr = nullptr;
1072b60736ecSDimitry Andric SmallVectorImpl<WeakTrackingVH> &DeadInsts;
1073b60736ecSDimitry Andric
1074b60736ecSDimitry Andric SmallPtrSet<Instruction *,16> Widened;
1075b60736ecSDimitry Andric
10764b4fe385SDimitry Andric enum class ExtendKind { Zero, Sign, Unknown };
1077b60736ecSDimitry Andric
1078b60736ecSDimitry Andric // A map tracking the kind of extension used to widen each narrow IV
1079b60736ecSDimitry Andric // and narrow IV user.
1080b60736ecSDimitry Andric // Key: pointer to a narrow IV or IV user.
1081b60736ecSDimitry Andric // Value: the kind of extension used to widen this Instruction.
1082b60736ecSDimitry Andric DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
1083b60736ecSDimitry Andric
1084b60736ecSDimitry Andric using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
1085b60736ecSDimitry Andric
1086b60736ecSDimitry Andric // A map with control-dependent ranges for post increment IV uses. The key is
1087b60736ecSDimitry Andric // a pair of IV def and a use of this def denoting the context. The value is
1088b60736ecSDimitry Andric // a ConstantRange representing possible values of the def at the given
1089b60736ecSDimitry Andric // context.
1090b60736ecSDimitry Andric DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
1091b60736ecSDimitry Andric
getPostIncRangeInfo(Value * Def,Instruction * UseI)1092e3b55780SDimitry Andric std::optional<ConstantRange> getPostIncRangeInfo(Value *Def,
1093b60736ecSDimitry Andric Instruction *UseI) {
1094b60736ecSDimitry Andric DefUserPair Key(Def, UseI);
1095b60736ecSDimitry Andric auto It = PostIncRangeInfos.find(Key);
1096b60736ecSDimitry Andric return It == PostIncRangeInfos.end()
1097e3b55780SDimitry Andric ? std::optional<ConstantRange>(std::nullopt)
1098e3b55780SDimitry Andric : std::optional<ConstantRange>(It->second);
1099b60736ecSDimitry Andric }
1100b60736ecSDimitry Andric
1101b60736ecSDimitry Andric void calculatePostIncRanges(PHINode *OrigPhi);
1102b60736ecSDimitry Andric void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
1103b60736ecSDimitry Andric
updatePostIncRangeInfo(Value * Def,Instruction * UseI,ConstantRange R)1104b60736ecSDimitry Andric void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
1105b60736ecSDimitry Andric DefUserPair Key(Def, UseI);
1106b60736ecSDimitry Andric auto It = PostIncRangeInfos.find(Key);
1107b60736ecSDimitry Andric if (It == PostIncRangeInfos.end())
1108b60736ecSDimitry Andric PostIncRangeInfos.insert({Key, R});
1109b60736ecSDimitry Andric else
1110b60736ecSDimitry Andric It->second = R.intersectWith(It->second);
1111b60736ecSDimitry Andric }
1112b60736ecSDimitry Andric
1113b60736ecSDimitry Andric public:
1114b60736ecSDimitry Andric /// Record a link in the Narrow IV def-use chain along with the WideIV that
1115b60736ecSDimitry Andric /// computes the same value as the Narrow IV def. This avoids caching Use*
1116b60736ecSDimitry Andric /// pointers.
1117b60736ecSDimitry Andric struct NarrowIVDefUse {
1118b60736ecSDimitry Andric Instruction *NarrowDef = nullptr;
1119b60736ecSDimitry Andric Instruction *NarrowUse = nullptr;
1120b60736ecSDimitry Andric Instruction *WideDef = nullptr;
1121b60736ecSDimitry Andric
1122b60736ecSDimitry Andric // True if the narrow def is never negative. Tracking this information lets
1123b60736ecSDimitry Andric // us use a sign extension instead of a zero extension or vice versa, when
1124b60736ecSDimitry Andric // profitable and legal.
1125b60736ecSDimitry Andric bool NeverNegative = false;
1126b60736ecSDimitry Andric
NarrowIVDefUse__anon458945740311::WidenIV::NarrowIVDefUse1127b60736ecSDimitry Andric NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
1128b60736ecSDimitry Andric bool NeverNegative)
1129b60736ecSDimitry Andric : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
1130b60736ecSDimitry Andric NeverNegative(NeverNegative) {}
1131b60736ecSDimitry Andric };
1132b60736ecSDimitry Andric
1133b60736ecSDimitry Andric WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1134b60736ecSDimitry Andric DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1135b60736ecSDimitry Andric bool HasGuards, bool UsePostIncrementRanges = true);
1136b60736ecSDimitry Andric
1137b60736ecSDimitry Andric PHINode *createWideIV(SCEVExpander &Rewriter);
1138b60736ecSDimitry Andric
getNumElimExt()1139b60736ecSDimitry Andric unsigned getNumElimExt() { return NumElimExt; };
getNumWidened()1140b60736ecSDimitry Andric unsigned getNumWidened() { return NumWidened; };
1141b60736ecSDimitry Andric
1142b60736ecSDimitry Andric protected:
1143b60736ecSDimitry Andric Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
1144b60736ecSDimitry Andric Instruction *Use);
1145b60736ecSDimitry Andric
1146b60736ecSDimitry Andric Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1147b60736ecSDimitry Andric Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1148b60736ecSDimitry Andric const SCEVAddRecExpr *WideAR);
1149b60736ecSDimitry Andric Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1150b60736ecSDimitry Andric
1151b60736ecSDimitry Andric ExtendKind getExtendKind(Instruction *I);
1152b60736ecSDimitry Andric
1153b60736ecSDimitry Andric using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1154b60736ecSDimitry Andric
1155b60736ecSDimitry Andric WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1156b60736ecSDimitry Andric
1157b60736ecSDimitry Andric WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1158b60736ecSDimitry Andric
1159b60736ecSDimitry Andric const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1160b60736ecSDimitry Andric unsigned OpCode) const;
1161b60736ecSDimitry Andric
1162ac9a064cSDimitry Andric Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter,
1163ac9a064cSDimitry Andric PHINode *OrigPhi, PHINode *WidePhi);
1164ac9a064cSDimitry Andric void truncateIVUse(NarrowIVDefUse DU);
1165b60736ecSDimitry Andric
1166b60736ecSDimitry Andric bool widenLoopCompare(NarrowIVDefUse DU);
1167b60736ecSDimitry Andric bool widenWithVariantUse(NarrowIVDefUse DU);
1168b60736ecSDimitry Andric
1169b60736ecSDimitry Andric void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1170b60736ecSDimitry Andric
1171b60736ecSDimitry Andric private:
1172b60736ecSDimitry Andric SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
1173b60736ecSDimitry Andric };
1174c0981da4SDimitry Andric } // namespace
1175b60736ecSDimitry Andric
1176b60736ecSDimitry Andric /// Determine the insertion point for this user. By default, insert immediately
1177b60736ecSDimitry Andric /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
1178b60736ecSDimitry Andric /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
1179b60736ecSDimitry Andric /// common dominator for the incoming blocks. A nullptr can be returned if no
1180b60736ecSDimitry Andric /// viable location is found: it may happen if User is a PHI and Def only comes
1181b60736ecSDimitry Andric /// to this PHI from unreachable blocks.
getInsertPointForUses(Instruction * User,Value * Def,DominatorTree * DT,LoopInfo * LI)1182b60736ecSDimitry Andric static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
1183b60736ecSDimitry Andric DominatorTree *DT, LoopInfo *LI) {
1184b60736ecSDimitry Andric PHINode *PHI = dyn_cast<PHINode>(User);
1185b60736ecSDimitry Andric if (!PHI)
1186b60736ecSDimitry Andric return User;
1187b60736ecSDimitry Andric
1188b60736ecSDimitry Andric Instruction *InsertPt = nullptr;
1189b60736ecSDimitry Andric for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
1190b60736ecSDimitry Andric if (PHI->getIncomingValue(i) != Def)
1191b60736ecSDimitry Andric continue;
1192b60736ecSDimitry Andric
1193b60736ecSDimitry Andric BasicBlock *InsertBB = PHI->getIncomingBlock(i);
1194b60736ecSDimitry Andric
1195b60736ecSDimitry Andric if (!DT->isReachableFromEntry(InsertBB))
1196b60736ecSDimitry Andric continue;
1197b60736ecSDimitry Andric
1198b60736ecSDimitry Andric if (!InsertPt) {
1199b60736ecSDimitry Andric InsertPt = InsertBB->getTerminator();
1200b60736ecSDimitry Andric continue;
1201b60736ecSDimitry Andric }
1202b60736ecSDimitry Andric InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
1203b60736ecSDimitry Andric InsertPt = InsertBB->getTerminator();
1204b60736ecSDimitry Andric }
1205b60736ecSDimitry Andric
1206b60736ecSDimitry Andric // If we have skipped all inputs, it means that Def only comes to Phi from
1207b60736ecSDimitry Andric // unreachable blocks.
1208b60736ecSDimitry Andric if (!InsertPt)
1209b60736ecSDimitry Andric return nullptr;
1210b60736ecSDimitry Andric
1211b60736ecSDimitry Andric auto *DefI = dyn_cast<Instruction>(Def);
1212b60736ecSDimitry Andric if (!DefI)
1213b60736ecSDimitry Andric return InsertPt;
1214b60736ecSDimitry Andric
1215b60736ecSDimitry Andric assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
1216b60736ecSDimitry Andric
1217b60736ecSDimitry Andric auto *L = LI->getLoopFor(DefI->getParent());
1218b60736ecSDimitry Andric assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
1219b60736ecSDimitry Andric
1220b60736ecSDimitry Andric for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
1221b60736ecSDimitry Andric if (LI->getLoopFor(DTN->getBlock()) == L)
1222b60736ecSDimitry Andric return DTN->getBlock()->getTerminator();
1223b60736ecSDimitry Andric
1224b60736ecSDimitry Andric llvm_unreachable("DefI dominates InsertPt!");
1225b60736ecSDimitry Andric }
1226b60736ecSDimitry Andric
WidenIV(const WideIVInfo & WI,LoopInfo * LInfo,ScalarEvolution * SEv,DominatorTree * DTree,SmallVectorImpl<WeakTrackingVH> & DI,bool HasGuards,bool UsePostIncrementRanges)1227b60736ecSDimitry Andric WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1228b60736ecSDimitry Andric DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1229b60736ecSDimitry Andric bool HasGuards, bool UsePostIncrementRanges)
1230b60736ecSDimitry Andric : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1231b60736ecSDimitry Andric L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
1232b60736ecSDimitry Andric HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
1233b60736ecSDimitry Andric DeadInsts(DI) {
1234b60736ecSDimitry Andric assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
12354b4fe385SDimitry Andric ExtendKindMap[OrigPhi] = WI.IsSigned ? ExtendKind::Sign : ExtendKind::Zero;
1236b60736ecSDimitry Andric }
1237b60736ecSDimitry Andric
createExtendInst(Value * NarrowOper,Type * WideType,bool IsSigned,Instruction * Use)1238b60736ecSDimitry Andric Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1239b60736ecSDimitry Andric bool IsSigned, Instruction *Use) {
1240b60736ecSDimitry Andric // Set the debug location and conservative insertion point.
1241b60736ecSDimitry Andric IRBuilder<> Builder(Use);
1242b60736ecSDimitry Andric // Hoist the insertion point into loop preheaders as far as possible.
1243b60736ecSDimitry Andric for (const Loop *L = LI->getLoopFor(Use->getParent());
1244b60736ecSDimitry Andric L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
1245b60736ecSDimitry Andric L = L->getParentLoop())
1246b60736ecSDimitry Andric Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1247b60736ecSDimitry Andric
1248b60736ecSDimitry Andric return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1249b60736ecSDimitry Andric Builder.CreateZExt(NarrowOper, WideType);
1250b60736ecSDimitry Andric }
1251b60736ecSDimitry Andric
1252b60736ecSDimitry Andric /// Instantiate a wide operation to replace a narrow operation. This only needs
1253b60736ecSDimitry Andric /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1254b60736ecSDimitry Andric /// 0 for any operation we decide not to clone.
cloneIVUser(WidenIV::NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1255b60736ecSDimitry Andric Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
1256b60736ecSDimitry Andric const SCEVAddRecExpr *WideAR) {
1257b60736ecSDimitry Andric unsigned Opcode = DU.NarrowUse->getOpcode();
1258b60736ecSDimitry Andric switch (Opcode) {
1259b60736ecSDimitry Andric default:
1260b60736ecSDimitry Andric return nullptr;
1261b60736ecSDimitry Andric case Instruction::Add:
1262b60736ecSDimitry Andric case Instruction::Mul:
1263b60736ecSDimitry Andric case Instruction::UDiv:
1264b60736ecSDimitry Andric case Instruction::Sub:
1265b60736ecSDimitry Andric return cloneArithmeticIVUser(DU, WideAR);
1266b60736ecSDimitry Andric
1267b60736ecSDimitry Andric case Instruction::And:
1268b60736ecSDimitry Andric case Instruction::Or:
1269b60736ecSDimitry Andric case Instruction::Xor:
1270b60736ecSDimitry Andric case Instruction::Shl:
1271b60736ecSDimitry Andric case Instruction::LShr:
1272b60736ecSDimitry Andric case Instruction::AShr:
1273b60736ecSDimitry Andric return cloneBitwiseIVUser(DU);
1274b60736ecSDimitry Andric }
1275b60736ecSDimitry Andric }
1276b60736ecSDimitry Andric
cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU)1277b60736ecSDimitry Andric Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
1278b60736ecSDimitry Andric Instruction *NarrowUse = DU.NarrowUse;
1279b60736ecSDimitry Andric Instruction *NarrowDef = DU.NarrowDef;
1280b60736ecSDimitry Andric Instruction *WideDef = DU.WideDef;
1281b60736ecSDimitry Andric
1282b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1283b60736ecSDimitry Andric
1284b60736ecSDimitry Andric // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1285b60736ecSDimitry Andric // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1286b60736ecSDimitry Andric // invariant and will be folded or hoisted. If it actually comes from a
1287b60736ecSDimitry Andric // widened IV, it should be removed during a future call to widenIVUse.
12884b4fe385SDimitry Andric bool IsSigned = getExtendKind(NarrowDef) == ExtendKind::Sign;
1289b60736ecSDimitry Andric Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1290b60736ecSDimitry Andric ? WideDef
1291b60736ecSDimitry Andric : createExtendInst(NarrowUse->getOperand(0), WideType,
1292b60736ecSDimitry Andric IsSigned, NarrowUse);
1293b60736ecSDimitry Andric Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1294b60736ecSDimitry Andric ? WideDef
1295b60736ecSDimitry Andric : createExtendInst(NarrowUse->getOperand(1), WideType,
1296b60736ecSDimitry Andric IsSigned, NarrowUse);
1297b60736ecSDimitry Andric
1298b60736ecSDimitry Andric auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1299b60736ecSDimitry Andric auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1300b60736ecSDimitry Andric NarrowBO->getName());
1301b60736ecSDimitry Andric IRBuilder<> Builder(NarrowUse);
1302b60736ecSDimitry Andric Builder.Insert(WideBO);
1303b60736ecSDimitry Andric WideBO->copyIRFlags(NarrowBO);
1304b60736ecSDimitry Andric return WideBO;
1305b60736ecSDimitry Andric }
1306b60736ecSDimitry Andric
cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,const SCEVAddRecExpr * WideAR)1307b60736ecSDimitry Andric Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
1308b60736ecSDimitry Andric const SCEVAddRecExpr *WideAR) {
1309b60736ecSDimitry Andric Instruction *NarrowUse = DU.NarrowUse;
1310b60736ecSDimitry Andric Instruction *NarrowDef = DU.NarrowDef;
1311b60736ecSDimitry Andric Instruction *WideDef = DU.WideDef;
1312b60736ecSDimitry Andric
1313b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1314b60736ecSDimitry Andric
1315b60736ecSDimitry Andric unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1316b60736ecSDimitry Andric
1317b60736ecSDimitry Andric // We're trying to find X such that
1318b60736ecSDimitry Andric //
1319b60736ecSDimitry Andric // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1320b60736ecSDimitry Andric //
1321b60736ecSDimitry Andric // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1322b60736ecSDimitry Andric // and check using SCEV if any of them are correct.
1323b60736ecSDimitry Andric
1324b60736ecSDimitry Andric // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1325b60736ecSDimitry Andric // correct solution to X.
1326b60736ecSDimitry Andric auto GuessNonIVOperand = [&](bool SignExt) {
1327b60736ecSDimitry Andric const SCEV *WideLHS;
1328b60736ecSDimitry Andric const SCEV *WideRHS;
1329b60736ecSDimitry Andric
1330b60736ecSDimitry Andric auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1331b60736ecSDimitry Andric if (SignExt)
1332b60736ecSDimitry Andric return SE->getSignExtendExpr(S, Ty);
1333b60736ecSDimitry Andric return SE->getZeroExtendExpr(S, Ty);
1334b60736ecSDimitry Andric };
1335b60736ecSDimitry Andric
1336b60736ecSDimitry Andric if (IVOpIdx == 0) {
1337b60736ecSDimitry Andric WideLHS = SE->getSCEV(WideDef);
1338b60736ecSDimitry Andric const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1339b60736ecSDimitry Andric WideRHS = GetExtend(NarrowRHS, WideType);
1340b60736ecSDimitry Andric } else {
1341b60736ecSDimitry Andric const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1342b60736ecSDimitry Andric WideLHS = GetExtend(NarrowLHS, WideType);
1343b60736ecSDimitry Andric WideRHS = SE->getSCEV(WideDef);
1344b60736ecSDimitry Andric }
1345b60736ecSDimitry Andric
1346b60736ecSDimitry Andric // WideUse is "WideDef `op.wide` X" as described in the comment.
1347b60736ecSDimitry Andric const SCEV *WideUse =
1348b60736ecSDimitry Andric getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode());
1349b60736ecSDimitry Andric
1350b60736ecSDimitry Andric return WideUse == WideAR;
1351b60736ecSDimitry Andric };
1352b60736ecSDimitry Andric
13534b4fe385SDimitry Andric bool SignExtend = getExtendKind(NarrowDef) == ExtendKind::Sign;
1354b60736ecSDimitry Andric if (!GuessNonIVOperand(SignExtend)) {
1355b60736ecSDimitry Andric SignExtend = !SignExtend;
1356b60736ecSDimitry Andric if (!GuessNonIVOperand(SignExtend))
1357b60736ecSDimitry Andric return nullptr;
1358b60736ecSDimitry Andric }
1359b60736ecSDimitry Andric
1360b60736ecSDimitry Andric Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1361b60736ecSDimitry Andric ? WideDef
1362b60736ecSDimitry Andric : createExtendInst(NarrowUse->getOperand(0), WideType,
1363b60736ecSDimitry Andric SignExtend, NarrowUse);
1364b60736ecSDimitry Andric Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1365b60736ecSDimitry Andric ? WideDef
1366b60736ecSDimitry Andric : createExtendInst(NarrowUse->getOperand(1), WideType,
1367b60736ecSDimitry Andric SignExtend, NarrowUse);
1368b60736ecSDimitry Andric
1369b60736ecSDimitry Andric auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1370b60736ecSDimitry Andric auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1371b60736ecSDimitry Andric NarrowBO->getName());
1372b60736ecSDimitry Andric
1373b60736ecSDimitry Andric IRBuilder<> Builder(NarrowUse);
1374b60736ecSDimitry Andric Builder.Insert(WideBO);
1375b60736ecSDimitry Andric WideBO->copyIRFlags(NarrowBO);
1376b60736ecSDimitry Andric return WideBO;
1377b60736ecSDimitry Andric }
1378b60736ecSDimitry Andric
getExtendKind(Instruction * I)1379b60736ecSDimitry Andric WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1380b60736ecSDimitry Andric auto It = ExtendKindMap.find(I);
1381b60736ecSDimitry Andric assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1382b60736ecSDimitry Andric return It->second;
1383b60736ecSDimitry Andric }
1384b60736ecSDimitry Andric
getSCEVByOpCode(const SCEV * LHS,const SCEV * RHS,unsigned OpCode) const1385b60736ecSDimitry Andric const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1386b60736ecSDimitry Andric unsigned OpCode) const {
1387b60736ecSDimitry Andric switch (OpCode) {
1388b60736ecSDimitry Andric case Instruction::Add:
1389b60736ecSDimitry Andric return SE->getAddExpr(LHS, RHS);
1390b60736ecSDimitry Andric case Instruction::Sub:
1391b60736ecSDimitry Andric return SE->getMinusSCEV(LHS, RHS);
1392b60736ecSDimitry Andric case Instruction::Mul:
1393b60736ecSDimitry Andric return SE->getMulExpr(LHS, RHS);
1394b60736ecSDimitry Andric case Instruction::UDiv:
1395b60736ecSDimitry Andric return SE->getUDivExpr(LHS, RHS);
1396b60736ecSDimitry Andric default:
1397b60736ecSDimitry Andric llvm_unreachable("Unsupported opcode.");
1398b60736ecSDimitry Andric };
1399b60736ecSDimitry Andric }
1400b60736ecSDimitry Andric
1401ac9a064cSDimitry Andric namespace {
1402ac9a064cSDimitry Andric
1403ac9a064cSDimitry Andric // Represents a interesting integer binary operation for
1404ac9a064cSDimitry Andric // getExtendedOperandRecurrence. This may be a shl that is being treated as a
1405ac9a064cSDimitry Andric // multiply or a 'or disjoint' that is being treated as 'add nsw nuw'.
1406ac9a064cSDimitry Andric struct BinaryOp {
1407ac9a064cSDimitry Andric unsigned Opcode;
1408ac9a064cSDimitry Andric std::array<Value *, 2> Operands;
1409ac9a064cSDimitry Andric bool IsNSW = false;
1410ac9a064cSDimitry Andric bool IsNUW = false;
1411ac9a064cSDimitry Andric
BinaryOp__anon458945740611::BinaryOp1412ac9a064cSDimitry Andric explicit BinaryOp(Instruction *Op)
1413ac9a064cSDimitry Andric : Opcode(Op->getOpcode()),
1414ac9a064cSDimitry Andric Operands({Op->getOperand(0), Op->getOperand(1)}) {
1415ac9a064cSDimitry Andric if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
1416ac9a064cSDimitry Andric IsNSW = OBO->hasNoSignedWrap();
1417ac9a064cSDimitry Andric IsNUW = OBO->hasNoUnsignedWrap();
1418ac9a064cSDimitry Andric }
1419ac9a064cSDimitry Andric }
1420ac9a064cSDimitry Andric
BinaryOp__anon458945740611::BinaryOp1421ac9a064cSDimitry Andric explicit BinaryOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
1422ac9a064cSDimitry Andric bool IsNSW = false, bool IsNUW = false)
1423ac9a064cSDimitry Andric : Opcode(Opcode), Operands({LHS, RHS}), IsNSW(IsNSW), IsNUW(IsNUW) {}
1424ac9a064cSDimitry Andric };
1425ac9a064cSDimitry Andric
1426ac9a064cSDimitry Andric } // end anonymous namespace
1427ac9a064cSDimitry Andric
matchBinaryOp(Instruction * Op)1428ac9a064cSDimitry Andric static std::optional<BinaryOp> matchBinaryOp(Instruction *Op) {
1429ac9a064cSDimitry Andric switch (Op->getOpcode()) {
1430ac9a064cSDimitry Andric case Instruction::Add:
1431ac9a064cSDimitry Andric case Instruction::Sub:
1432ac9a064cSDimitry Andric case Instruction::Mul:
1433ac9a064cSDimitry Andric return BinaryOp(Op);
1434ac9a064cSDimitry Andric case Instruction::Or: {
1435ac9a064cSDimitry Andric // Convert or disjoint into add nuw nsw.
1436ac9a064cSDimitry Andric if (cast<PossiblyDisjointInst>(Op)->isDisjoint())
1437ac9a064cSDimitry Andric return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
1438ac9a064cSDimitry Andric /*IsNSW=*/true, /*IsNUW=*/true);
1439ac9a064cSDimitry Andric break;
1440ac9a064cSDimitry Andric }
1441ac9a064cSDimitry Andric case Instruction::Shl: {
1442ac9a064cSDimitry Andric if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
1443ac9a064cSDimitry Andric unsigned BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
1444ac9a064cSDimitry Andric
1445ac9a064cSDimitry Andric // If the shift count is not less than the bitwidth, the result of
1446ac9a064cSDimitry Andric // the shift is undefined. Don't try to analyze it, because the
1447ac9a064cSDimitry Andric // resolution chosen here may differ from the resolution chosen in
1448ac9a064cSDimitry Andric // other parts of the compiler.
1449ac9a064cSDimitry Andric if (SA->getValue().ult(BitWidth)) {
1450ac9a064cSDimitry Andric // We can safely preserve the nuw flag in all cases. It's also safe to
1451ac9a064cSDimitry Andric // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
1452ac9a064cSDimitry Andric // requires special handling. It can be preserved as long as we're not
1453ac9a064cSDimitry Andric // left shifting by bitwidth - 1.
1454ac9a064cSDimitry Andric bool IsNUW = Op->hasNoUnsignedWrap();
1455ac9a064cSDimitry Andric bool IsNSW = Op->hasNoSignedWrap() &&
1456ac9a064cSDimitry Andric (IsNUW || SA->getValue().ult(BitWidth - 1));
1457ac9a064cSDimitry Andric
1458ac9a064cSDimitry Andric ConstantInt *X =
1459ac9a064cSDimitry Andric ConstantInt::get(Op->getContext(),
1460ac9a064cSDimitry Andric APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
1461ac9a064cSDimitry Andric return BinaryOp(Instruction::Mul, Op->getOperand(0), X, IsNSW, IsNUW);
1462ac9a064cSDimitry Andric }
1463ac9a064cSDimitry Andric }
1464ac9a064cSDimitry Andric
1465ac9a064cSDimitry Andric break;
1466ac9a064cSDimitry Andric }
1467ac9a064cSDimitry Andric }
1468ac9a064cSDimitry Andric
1469ac9a064cSDimitry Andric return std::nullopt;
1470ac9a064cSDimitry Andric }
1471ac9a064cSDimitry Andric
1472b60736ecSDimitry Andric /// No-wrap operations can transfer sign extension of their result to their
1473b60736ecSDimitry Andric /// operands. Generate the SCEV value for the widened operation without
1474b60736ecSDimitry Andric /// actually modifying the IR yet. If the expression after extending the
1475b60736ecSDimitry Andric /// operands is an AddRec for this loop, return the AddRec and the kind of
1476b60736ecSDimitry Andric /// extension used.
1477b60736ecSDimitry Andric WidenIV::WidenedRecTy
getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU)1478b60736ecSDimitry Andric WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
1479ac9a064cSDimitry Andric auto Op = matchBinaryOp(DU.NarrowUse);
1480ac9a064cSDimitry Andric if (!Op)
14814b4fe385SDimitry Andric return {nullptr, ExtendKind::Unknown};
1482b60736ecSDimitry Andric
1483ac9a064cSDimitry Andric assert((Op->Opcode == Instruction::Add || Op->Opcode == Instruction::Sub ||
1484ac9a064cSDimitry Andric Op->Opcode == Instruction::Mul) &&
1485ac9a064cSDimitry Andric "Unexpected opcode");
1486ac9a064cSDimitry Andric
1487b60736ecSDimitry Andric // One operand (NarrowDef) has already been extended to WideDef. Now determine
1488b60736ecSDimitry Andric // if extending the other will lead to a recurrence.
1489ac9a064cSDimitry Andric const unsigned ExtendOperIdx = Op->Operands[0] == DU.NarrowDef ? 1 : 0;
1490ac9a064cSDimitry Andric assert(Op->Operands[1 - ExtendOperIdx] == DU.NarrowDef && "bad DU");
1491b60736ecSDimitry Andric
1492b60736ecSDimitry Andric ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1493ac9a064cSDimitry Andric if (!(ExtKind == ExtendKind::Sign && Op->IsNSW) &&
1494ac9a064cSDimitry Andric !(ExtKind == ExtendKind::Zero && Op->IsNUW)) {
1495b1c73532SDimitry Andric ExtKind = ExtendKind::Unknown;
1496b1c73532SDimitry Andric
1497b1c73532SDimitry Andric // For a non-negative NarrowDef, we can choose either type of
1498b1c73532SDimitry Andric // extension. We want to use the current extend kind if legal
1499b1c73532SDimitry Andric // (see above), and we only hit this code if we need to check
1500b1c73532SDimitry Andric // the opposite case.
1501b1c73532SDimitry Andric if (DU.NeverNegative) {
1502ac9a064cSDimitry Andric if (Op->IsNSW) {
1503b1c73532SDimitry Andric ExtKind = ExtendKind::Sign;
1504ac9a064cSDimitry Andric } else if (Op->IsNUW) {
1505b1c73532SDimitry Andric ExtKind = ExtendKind::Zero;
1506b1c73532SDimitry Andric }
1507b1c73532SDimitry Andric }
1508b1c73532SDimitry Andric }
1509b1c73532SDimitry Andric
1510ac9a064cSDimitry Andric const SCEV *ExtendOperExpr = SE->getSCEV(Op->Operands[ExtendOperIdx]);
1511b1c73532SDimitry Andric if (ExtKind == ExtendKind::Sign)
1512b1c73532SDimitry Andric ExtendOperExpr = SE->getSignExtendExpr(ExtendOperExpr, WideType);
1513b1c73532SDimitry Andric else if (ExtKind == ExtendKind::Zero)
1514b1c73532SDimitry Andric ExtendOperExpr = SE->getZeroExtendExpr(ExtendOperExpr, WideType);
1515b60736ecSDimitry Andric else
15164b4fe385SDimitry Andric return {nullptr, ExtendKind::Unknown};
1517b60736ecSDimitry Andric
1518b60736ecSDimitry Andric // When creating this SCEV expr, don't apply the current operations NSW or NUW
1519b60736ecSDimitry Andric // flags. This instruction may be guarded by control flow that the no-wrap
1520b60736ecSDimitry Andric // behavior depends on. Non-control-equivalent instructions can be mapped to
1521b60736ecSDimitry Andric // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1522b60736ecSDimitry Andric // semantics to those operations.
1523b60736ecSDimitry Andric const SCEV *lhs = SE->getSCEV(DU.WideDef);
1524b60736ecSDimitry Andric const SCEV *rhs = ExtendOperExpr;
1525b60736ecSDimitry Andric
1526b60736ecSDimitry Andric // Let's swap operands to the initial order for the case of non-commutative
1527b60736ecSDimitry Andric // operations, like SUB. See PR21014.
1528b60736ecSDimitry Andric if (ExtendOperIdx == 0)
1529b60736ecSDimitry Andric std::swap(lhs, rhs);
1530b60736ecSDimitry Andric const SCEVAddRecExpr *AddRec =
1531ac9a064cSDimitry Andric dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, Op->Opcode));
1532b60736ecSDimitry Andric
1533b60736ecSDimitry Andric if (!AddRec || AddRec->getLoop() != L)
15344b4fe385SDimitry Andric return {nullptr, ExtendKind::Unknown};
1535b60736ecSDimitry Andric
1536b60736ecSDimitry Andric return {AddRec, ExtKind};
1537b60736ecSDimitry Andric }
1538b60736ecSDimitry Andric
1539b60736ecSDimitry Andric /// Is this instruction potentially interesting for further simplification after
1540b60736ecSDimitry Andric /// widening it's type? In other words, can the extend be safely hoisted out of
1541b60736ecSDimitry Andric /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1542b60736ecSDimitry Andric /// so, return the extended recurrence and the kind of extension used. Otherwise
15434b4fe385SDimitry Andric /// return {nullptr, ExtendKind::Unknown}.
getWideRecurrence(WidenIV::NarrowIVDefUse DU)1544b60736ecSDimitry Andric WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
1545344a3780SDimitry Andric if (!DU.NarrowUse->getType()->isIntegerTy())
15464b4fe385SDimitry Andric return {nullptr, ExtendKind::Unknown};
1547b60736ecSDimitry Andric
1548b60736ecSDimitry Andric const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1549b60736ecSDimitry Andric if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1550b60736ecSDimitry Andric SE->getTypeSizeInBits(WideType)) {
1551b60736ecSDimitry Andric // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1552b60736ecSDimitry Andric // index. So don't follow this use.
15534b4fe385SDimitry Andric return {nullptr, ExtendKind::Unknown};
1554b60736ecSDimitry Andric }
1555b60736ecSDimitry Andric
1556b60736ecSDimitry Andric const SCEV *WideExpr;
1557b60736ecSDimitry Andric ExtendKind ExtKind;
1558b60736ecSDimitry Andric if (DU.NeverNegative) {
1559b60736ecSDimitry Andric WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1560b60736ecSDimitry Andric if (isa<SCEVAddRecExpr>(WideExpr))
15614b4fe385SDimitry Andric ExtKind = ExtendKind::Sign;
1562b60736ecSDimitry Andric else {
1563b60736ecSDimitry Andric WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
15644b4fe385SDimitry Andric ExtKind = ExtendKind::Zero;
1565b60736ecSDimitry Andric }
15664b4fe385SDimitry Andric } else if (getExtendKind(DU.NarrowDef) == ExtendKind::Sign) {
1567b60736ecSDimitry Andric WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
15684b4fe385SDimitry Andric ExtKind = ExtendKind::Sign;
1569b60736ecSDimitry Andric } else {
1570b60736ecSDimitry Andric WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
15714b4fe385SDimitry Andric ExtKind = ExtendKind::Zero;
1572b60736ecSDimitry Andric }
1573b60736ecSDimitry Andric const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1574b60736ecSDimitry Andric if (!AddRec || AddRec->getLoop() != L)
15754b4fe385SDimitry Andric return {nullptr, ExtendKind::Unknown};
1576b60736ecSDimitry Andric return {AddRec, ExtKind};
1577b60736ecSDimitry Andric }
1578b60736ecSDimitry Andric
1579b60736ecSDimitry Andric /// This IV user cannot be widened. Replace this use of the original narrow IV
1580b60736ecSDimitry Andric /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
truncateIVUse(NarrowIVDefUse DU)1581ac9a064cSDimitry Andric void WidenIV::truncateIVUse(NarrowIVDefUse DU) {
1582b60736ecSDimitry Andric auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1583b60736ecSDimitry Andric if (!InsertPt)
1584b60736ecSDimitry Andric return;
1585b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1586b60736ecSDimitry Andric << *DU.NarrowUse << "\n");
1587ac9a064cSDimitry Andric ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1588b60736ecSDimitry Andric IRBuilder<> Builder(InsertPt);
1589ac9a064cSDimitry Andric Value *Trunc =
1590ac9a064cSDimitry Andric Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType(), "",
1591ac9a064cSDimitry Andric DU.NeverNegative || ExtKind == ExtendKind::Zero,
1592ac9a064cSDimitry Andric DU.NeverNegative || ExtKind == ExtendKind::Sign);
1593b60736ecSDimitry Andric DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1594b60736ecSDimitry Andric }
1595b60736ecSDimitry Andric
1596b60736ecSDimitry Andric /// If the narrow use is a compare instruction, then widen the compare
1597b60736ecSDimitry Andric // (and possibly the other operand). The extend operation is hoisted into the
1598b60736ecSDimitry Andric // loop preheader as far as possible.
widenLoopCompare(WidenIV::NarrowIVDefUse DU)1599b60736ecSDimitry Andric bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
1600b60736ecSDimitry Andric ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1601b60736ecSDimitry Andric if (!Cmp)
1602b60736ecSDimitry Andric return false;
1603b60736ecSDimitry Andric
1604b60736ecSDimitry Andric // We can legally widen the comparison in the following two cases:
1605b60736ecSDimitry Andric //
1606b60736ecSDimitry Andric // - The signedness of the IV extension and comparison match
1607b60736ecSDimitry Andric //
1608b60736ecSDimitry Andric // - The narrow IV is always positive (and thus its sign extension is equal
1609b60736ecSDimitry Andric // to its zero extension). For instance, let's say we're zero extending
1610b60736ecSDimitry Andric // %narrow for the following use
1611b60736ecSDimitry Andric //
1612b60736ecSDimitry Andric // icmp slt i32 %narrow, %val ... (A)
1613b60736ecSDimitry Andric //
1614b60736ecSDimitry Andric // and %narrow is always positive. Then
1615b60736ecSDimitry Andric //
1616b60736ecSDimitry Andric // (A) == icmp slt i32 sext(%narrow), sext(%val)
1617b60736ecSDimitry Andric // == icmp slt i32 zext(%narrow), sext(%val)
16184b4fe385SDimitry Andric bool IsSigned = getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1619b60736ecSDimitry Andric if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1620b60736ecSDimitry Andric return false;
1621b60736ecSDimitry Andric
1622b60736ecSDimitry Andric Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1623b60736ecSDimitry Andric unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1624b60736ecSDimitry Andric unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1625b60736ecSDimitry Andric assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1626b60736ecSDimitry Andric
1627b60736ecSDimitry Andric // Widen the compare instruction.
1628b60736ecSDimitry Andric DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1629b60736ecSDimitry Andric
1630b60736ecSDimitry Andric // Widen the other operand of the compare, if necessary.
1631b60736ecSDimitry Andric if (CastWidth < IVWidth) {
1632b60736ecSDimitry Andric Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1633b60736ecSDimitry Andric DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1634b60736ecSDimitry Andric }
1635b60736ecSDimitry Andric return true;
1636b60736ecSDimitry Andric }
1637b60736ecSDimitry Andric
1638b60736ecSDimitry Andric // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this
1639b60736ecSDimitry Andric // will not work when:
1640b60736ecSDimitry Andric // 1) SCEV traces back to an instruction inside the loop that SCEV can not
1641b60736ecSDimitry Andric // expand, eg. add %indvar, (load %addr)
1642b60736ecSDimitry Andric // 2) SCEV finds a loop variant, eg. add %indvar, %loopvariant
1643b60736ecSDimitry Andric // While SCEV fails to avoid trunc, we can still try to use instruction
1644b60736ecSDimitry Andric // combining approach to prove trunc is not required. This can be further
1645b60736ecSDimitry Andric // extended with other instruction combining checks, but for now we handle the
1646b60736ecSDimitry Andric // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext")
1647b60736ecSDimitry Andric //
1648b60736ecSDimitry Andric // Src:
1649b60736ecSDimitry Andric // %c = sub nsw %b, %indvar
1650b60736ecSDimitry Andric // %d = sext %c to i64
1651b60736ecSDimitry Andric // Dst:
1652b60736ecSDimitry Andric // %indvar.ext1 = sext %indvar to i64
1653b60736ecSDimitry Andric // %m = sext %b to i64
1654b60736ecSDimitry Andric // %d = sub nsw i64 %m, %indvar.ext1
1655b60736ecSDimitry Andric // Therefore, as long as the result of add/sub/mul is extended to wide type, no
1656b60736ecSDimitry Andric // trunc is required regardless of how %b is generated. This pattern is common
1657b60736ecSDimitry Andric // when calculating address in 64 bit architecture
widenWithVariantUse(WidenIV::NarrowIVDefUse DU)1658b60736ecSDimitry Andric bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
1659b60736ecSDimitry Andric Instruction *NarrowUse = DU.NarrowUse;
1660b60736ecSDimitry Andric Instruction *NarrowDef = DU.NarrowDef;
1661b60736ecSDimitry Andric Instruction *WideDef = DU.WideDef;
1662b60736ecSDimitry Andric
1663b60736ecSDimitry Andric // Handle the common case of add<nsw/nuw>
1664b60736ecSDimitry Andric const unsigned OpCode = NarrowUse->getOpcode();
1665b60736ecSDimitry Andric // Only Add/Sub/Mul instructions are supported.
1666b60736ecSDimitry Andric if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1667b60736ecSDimitry Andric OpCode != Instruction::Mul)
1668b60736ecSDimitry Andric return false;
1669b60736ecSDimitry Andric
1670b60736ecSDimitry Andric // The operand that is not defined by NarrowDef of DU. Let's call it the
1671b60736ecSDimitry Andric // other operand.
1672b60736ecSDimitry Andric assert((NarrowUse->getOperand(0) == NarrowDef ||
1673b60736ecSDimitry Andric NarrowUse->getOperand(1) == NarrowDef) &&
1674b60736ecSDimitry Andric "bad DU");
1675b60736ecSDimitry Andric
1676b60736ecSDimitry Andric const OverflowingBinaryOperator *OBO =
1677b60736ecSDimitry Andric cast<OverflowingBinaryOperator>(NarrowUse);
1678b60736ecSDimitry Andric ExtendKind ExtKind = getExtendKind(NarrowDef);
16794b4fe385SDimitry Andric bool CanSignExtend = ExtKind == ExtendKind::Sign && OBO->hasNoSignedWrap();
16804b4fe385SDimitry Andric bool CanZeroExtend = ExtKind == ExtendKind::Zero && OBO->hasNoUnsignedWrap();
1681b60736ecSDimitry Andric auto AnotherOpExtKind = ExtKind;
1682b60736ecSDimitry Andric
1683b60736ecSDimitry Andric // Check that all uses are either:
1684b60736ecSDimitry Andric // - narrow def (in case of we are widening the IV increment);
1685b60736ecSDimitry Andric // - single-input LCSSA Phis;
1686b60736ecSDimitry Andric // - comparison of the chosen type;
1687b60736ecSDimitry Andric // - extend of the chosen type (raison d'etre).
1688b60736ecSDimitry Andric SmallVector<Instruction *, 4> ExtUsers;
1689b60736ecSDimitry Andric SmallVector<PHINode *, 4> LCSSAPhiUsers;
1690b60736ecSDimitry Andric SmallVector<ICmpInst *, 4> ICmpUsers;
1691b60736ecSDimitry Andric for (Use &U : NarrowUse->uses()) {
1692b60736ecSDimitry Andric Instruction *User = cast<Instruction>(U.getUser());
1693b60736ecSDimitry Andric if (User == NarrowDef)
1694b60736ecSDimitry Andric continue;
1695b60736ecSDimitry Andric if (!L->contains(User)) {
1696b60736ecSDimitry Andric auto *LCSSAPhi = cast<PHINode>(User);
1697b60736ecSDimitry Andric // Make sure there is only 1 input, so that we don't have to split
1698b60736ecSDimitry Andric // critical edges.
1699b60736ecSDimitry Andric if (LCSSAPhi->getNumOperands() != 1)
1700b60736ecSDimitry Andric return false;
1701b60736ecSDimitry Andric LCSSAPhiUsers.push_back(LCSSAPhi);
1702b60736ecSDimitry Andric continue;
1703b60736ecSDimitry Andric }
1704b60736ecSDimitry Andric if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
1705b60736ecSDimitry Andric auto Pred = ICmp->getPredicate();
1706b60736ecSDimitry Andric // We have 3 types of predicates: signed, unsigned and equality
1707b60736ecSDimitry Andric // predicates. For equality, it's legal to widen icmp for either sign and
1708b60736ecSDimitry Andric // zero extend. For sign extend, we can also do so for signed predicates,
1709b60736ecSDimitry Andric // likeweise for zero extend we can widen icmp for unsigned predicates.
17104b4fe385SDimitry Andric if (ExtKind == ExtendKind::Zero && ICmpInst::isSigned(Pred))
1711b60736ecSDimitry Andric return false;
17124b4fe385SDimitry Andric if (ExtKind == ExtendKind::Sign && ICmpInst::isUnsigned(Pred))
1713b60736ecSDimitry Andric return false;
1714b60736ecSDimitry Andric ICmpUsers.push_back(ICmp);
1715b60736ecSDimitry Andric continue;
1716b60736ecSDimitry Andric }
17174b4fe385SDimitry Andric if (ExtKind == ExtendKind::Sign)
1718b60736ecSDimitry Andric User = dyn_cast<SExtInst>(User);
1719b60736ecSDimitry Andric else
1720b60736ecSDimitry Andric User = dyn_cast<ZExtInst>(User);
1721b60736ecSDimitry Andric if (!User || User->getType() != WideType)
1722b60736ecSDimitry Andric return false;
1723b60736ecSDimitry Andric ExtUsers.push_back(User);
1724b60736ecSDimitry Andric }
1725b60736ecSDimitry Andric if (ExtUsers.empty()) {
1726b60736ecSDimitry Andric DeadInsts.emplace_back(NarrowUse);
1727b60736ecSDimitry Andric return true;
1728b60736ecSDimitry Andric }
1729b60736ecSDimitry Andric
1730b60736ecSDimitry Andric // We'll prove some facts that should be true in the context of ext users. If
1731b60736ecSDimitry Andric // there is no users, we are done now. If there are some, pick their common
1732b60736ecSDimitry Andric // dominator as context.
1733344a3780SDimitry Andric const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
1734b60736ecSDimitry Andric
1735b60736ecSDimitry Andric if (!CanSignExtend && !CanZeroExtend) {
1736b60736ecSDimitry Andric // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
1737b60736ecSDimitry Andric // will most likely not see it. Let's try to prove it.
1738b60736ecSDimitry Andric if (OpCode != Instruction::Add)
1739b60736ecSDimitry Andric return false;
17404b4fe385SDimitry Andric if (ExtKind != ExtendKind::Zero)
1741b60736ecSDimitry Andric return false;
1742b60736ecSDimitry Andric const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
1743b60736ecSDimitry Andric const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
1744b60736ecSDimitry Andric // TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
1745b60736ecSDimitry Andric if (NarrowUse->getOperand(0) != NarrowDef)
1746b60736ecSDimitry Andric return false;
1747b60736ecSDimitry Andric if (!SE->isKnownNegative(RHS))
1748b60736ecSDimitry Andric return false;
1749344a3780SDimitry Andric bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
1750344a3780SDimitry Andric SE->getNegativeSCEV(RHS), CtxI);
1751b60736ecSDimitry Andric if (!ProvedSubNUW)
1752b60736ecSDimitry Andric return false;
1753b60736ecSDimitry Andric // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
1754b60736ecSDimitry Andric // neg(zext(neg(op))), which is basically sext(op).
17554b4fe385SDimitry Andric AnotherOpExtKind = ExtendKind::Sign;
1756b60736ecSDimitry Andric }
1757b60736ecSDimitry Andric
1758b60736ecSDimitry Andric // Verifying that Defining operand is an AddRec
1759b60736ecSDimitry Andric const SCEV *Op1 = SE->getSCEV(WideDef);
1760b60736ecSDimitry Andric const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1761b60736ecSDimitry Andric if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1762b60736ecSDimitry Andric return false;
1763b60736ecSDimitry Andric
1764b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1765b60736ecSDimitry Andric
1766b60736ecSDimitry Andric // Generating a widening use instruction.
17674b4fe385SDimitry Andric Value *LHS =
17684b4fe385SDimitry Andric (NarrowUse->getOperand(0) == NarrowDef)
1769b60736ecSDimitry Andric ? WideDef
1770b60736ecSDimitry Andric : createExtendInst(NarrowUse->getOperand(0), WideType,
17714b4fe385SDimitry Andric AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
17724b4fe385SDimitry Andric Value *RHS =
17734b4fe385SDimitry Andric (NarrowUse->getOperand(1) == NarrowDef)
1774b60736ecSDimitry Andric ? WideDef
1775b60736ecSDimitry Andric : createExtendInst(NarrowUse->getOperand(1), WideType,
17764b4fe385SDimitry Andric AnotherOpExtKind == ExtendKind::Sign, NarrowUse);
1777b60736ecSDimitry Andric
1778b60736ecSDimitry Andric auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1779b60736ecSDimitry Andric auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1780b60736ecSDimitry Andric NarrowBO->getName());
1781b60736ecSDimitry Andric IRBuilder<> Builder(NarrowUse);
1782b60736ecSDimitry Andric Builder.Insert(WideBO);
1783b60736ecSDimitry Andric WideBO->copyIRFlags(NarrowBO);
1784b60736ecSDimitry Andric ExtendKindMap[NarrowUse] = ExtKind;
1785b60736ecSDimitry Andric
1786b60736ecSDimitry Andric for (Instruction *User : ExtUsers) {
1787b60736ecSDimitry Andric assert(User->getType() == WideType && "Checked before!");
1788b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1789b60736ecSDimitry Andric << *WideBO << "\n");
1790b60736ecSDimitry Andric ++NumElimExt;
1791b60736ecSDimitry Andric User->replaceAllUsesWith(WideBO);
1792b60736ecSDimitry Andric DeadInsts.emplace_back(User);
1793b60736ecSDimitry Andric }
1794b60736ecSDimitry Andric
1795b60736ecSDimitry Andric for (PHINode *User : LCSSAPhiUsers) {
1796b60736ecSDimitry Andric assert(User->getNumOperands() == 1 && "Checked before!");
1797b60736ecSDimitry Andric Builder.SetInsertPoint(User);
1798b60736ecSDimitry Andric auto *WidePN =
1799b60736ecSDimitry Andric Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
1800b60736ecSDimitry Andric BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
1801b60736ecSDimitry Andric assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
1802b60736ecSDimitry Andric "Not a LCSSA Phi?");
1803b60736ecSDimitry Andric WidePN->addIncoming(WideBO, LoopExitingBlock);
1804b1c73532SDimitry Andric Builder.SetInsertPoint(User->getParent(),
1805b1c73532SDimitry Andric User->getParent()->getFirstInsertionPt());
1806b60736ecSDimitry Andric auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
1807b60736ecSDimitry Andric User->replaceAllUsesWith(TruncPN);
1808b60736ecSDimitry Andric DeadInsts.emplace_back(User);
1809b60736ecSDimitry Andric }
1810b60736ecSDimitry Andric
1811b60736ecSDimitry Andric for (ICmpInst *User : ICmpUsers) {
1812b60736ecSDimitry Andric Builder.SetInsertPoint(User);
1813b60736ecSDimitry Andric auto ExtendedOp = [&](Value * V)->Value * {
1814b60736ecSDimitry Andric if (V == NarrowUse)
1815b60736ecSDimitry Andric return WideBO;
18164b4fe385SDimitry Andric if (ExtKind == ExtendKind::Zero)
1817b60736ecSDimitry Andric return Builder.CreateZExt(V, WideBO->getType());
1818b60736ecSDimitry Andric else
1819b60736ecSDimitry Andric return Builder.CreateSExt(V, WideBO->getType());
1820b60736ecSDimitry Andric };
1821b60736ecSDimitry Andric auto Pred = User->getPredicate();
1822b60736ecSDimitry Andric auto *LHS = ExtendedOp(User->getOperand(0));
1823b60736ecSDimitry Andric auto *RHS = ExtendedOp(User->getOperand(1));
1824b60736ecSDimitry Andric auto *WideCmp =
1825b60736ecSDimitry Andric Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
1826b60736ecSDimitry Andric User->replaceAllUsesWith(WideCmp);
1827b60736ecSDimitry Andric DeadInsts.emplace_back(User);
1828b60736ecSDimitry Andric }
1829b60736ecSDimitry Andric
1830b60736ecSDimitry Andric return true;
1831b60736ecSDimitry Andric }
1832b60736ecSDimitry Andric
1833b60736ecSDimitry Andric /// Determine whether an individual user of the narrow IV can be widened. If so,
1834b60736ecSDimitry Andric /// return the wide clone of the user.
widenIVUse(WidenIV::NarrowIVDefUse DU,SCEVExpander & Rewriter,PHINode * OrigPhi,PHINode * WidePhi)1835ac9a064cSDimitry Andric Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU,
1836ac9a064cSDimitry Andric SCEVExpander &Rewriter, PHINode *OrigPhi,
1837ac9a064cSDimitry Andric PHINode *WidePhi) {
1838b60736ecSDimitry Andric assert(ExtendKindMap.count(DU.NarrowDef) &&
1839b60736ecSDimitry Andric "Should already know the kind of extension used to widen NarrowDef");
1840b60736ecSDimitry Andric
1841ac9a064cSDimitry Andric // This narrow use can be widened by a sext if it's non-negative or its narrow
1842ac9a064cSDimitry Andric // def was widened by a sext. Same for zext.
1843ac9a064cSDimitry Andric bool CanWidenBySExt =
1844ac9a064cSDimitry Andric DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Sign;
1845ac9a064cSDimitry Andric bool CanWidenByZExt =
1846ac9a064cSDimitry Andric DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Zero;
1847ac9a064cSDimitry Andric
1848b60736ecSDimitry Andric // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1849b60736ecSDimitry Andric if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1850b60736ecSDimitry Andric if (LI->getLoopFor(UsePhi->getParent()) != L) {
1851b60736ecSDimitry Andric // For LCSSA phis, sink the truncate outside the loop.
1852b60736ecSDimitry Andric // After SimplifyCFG most loop exit targets have a single predecessor.
1853b60736ecSDimitry Andric // Otherwise fall back to a truncate within the loop.
1854b60736ecSDimitry Andric if (UsePhi->getNumOperands() != 1)
1855ac9a064cSDimitry Andric truncateIVUse(DU);
1856b60736ecSDimitry Andric else {
1857b60736ecSDimitry Andric // Widening the PHI requires us to insert a trunc. The logical place
1858b60736ecSDimitry Andric // for this trunc is in the same BB as the PHI. This is not possible if
1859b60736ecSDimitry Andric // the BB is terminated by a catchswitch.
1860b60736ecSDimitry Andric if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1861b60736ecSDimitry Andric return nullptr;
1862b60736ecSDimitry Andric
1863b60736ecSDimitry Andric PHINode *WidePhi =
1864b60736ecSDimitry Andric PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1865ac9a064cSDimitry Andric UsePhi->getIterator());
1866b60736ecSDimitry Andric WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1867b1c73532SDimitry Andric BasicBlock *WidePhiBB = WidePhi->getParent();
1868b1c73532SDimitry Andric IRBuilder<> Builder(WidePhiBB, WidePhiBB->getFirstInsertionPt());
1869ac9a064cSDimitry Andric Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType(), "",
1870ac9a064cSDimitry Andric CanWidenByZExt, CanWidenBySExt);
1871b60736ecSDimitry Andric UsePhi->replaceAllUsesWith(Trunc);
1872b60736ecSDimitry Andric DeadInsts.emplace_back(UsePhi);
1873b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1874b60736ecSDimitry Andric << *WidePhi << "\n");
1875b60736ecSDimitry Andric }
1876b60736ecSDimitry Andric return nullptr;
1877b60736ecSDimitry Andric }
1878b60736ecSDimitry Andric }
1879b60736ecSDimitry Andric
1880b60736ecSDimitry Andric // Our raison d'etre! Eliminate sign and zero extension.
1881ac9a064cSDimitry Andric if ((match(DU.NarrowUse, m_SExtLike(m_Value())) && CanWidenBySExt) ||
1882ac9a064cSDimitry Andric (isa<ZExtInst>(DU.NarrowUse) && CanWidenByZExt)) {
1883b60736ecSDimitry Andric Value *NewDef = DU.WideDef;
1884b60736ecSDimitry Andric if (DU.NarrowUse->getType() != WideType) {
1885b60736ecSDimitry Andric unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1886b60736ecSDimitry Andric unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1887b60736ecSDimitry Andric if (CastWidth < IVWidth) {
1888b60736ecSDimitry Andric // The cast isn't as wide as the IV, so insert a Trunc.
1889b60736ecSDimitry Andric IRBuilder<> Builder(DU.NarrowUse);
1890ac9a064cSDimitry Andric NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType(), "",
1891ac9a064cSDimitry Andric CanWidenByZExt, CanWidenBySExt);
1892b60736ecSDimitry Andric }
1893b60736ecSDimitry Andric else {
1894b60736ecSDimitry Andric // A wider extend was hidden behind a narrower one. This may induce
1895b60736ecSDimitry Andric // another round of IV widening in which the intermediate IV becomes
1896b60736ecSDimitry Andric // dead. It should be very rare.
1897b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1898b60736ecSDimitry Andric << " not wide enough to subsume " << *DU.NarrowUse
1899b60736ecSDimitry Andric << "\n");
1900b60736ecSDimitry Andric DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1901b60736ecSDimitry Andric NewDef = DU.NarrowUse;
1902b60736ecSDimitry Andric }
1903b60736ecSDimitry Andric }
1904b60736ecSDimitry Andric if (NewDef != DU.NarrowUse) {
1905b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1906b60736ecSDimitry Andric << " replaced by " << *DU.WideDef << "\n");
1907b60736ecSDimitry Andric ++NumElimExt;
1908b60736ecSDimitry Andric DU.NarrowUse->replaceAllUsesWith(NewDef);
1909b60736ecSDimitry Andric DeadInsts.emplace_back(DU.NarrowUse);
1910b60736ecSDimitry Andric }
1911b60736ecSDimitry Andric // Now that the extend is gone, we want to expose it's uses for potential
1912b60736ecSDimitry Andric // further simplification. We don't need to directly inform SimplifyIVUsers
1913b60736ecSDimitry Andric // of the new users, because their parent IV will be processed later as a
1914b60736ecSDimitry Andric // new loop phi. If we preserved IVUsers analysis, we would also want to
1915b60736ecSDimitry Andric // push the uses of WideDef here.
1916b60736ecSDimitry Andric
1917b60736ecSDimitry Andric // No further widening is needed. The deceased [sz]ext had done it for us.
1918b60736ecSDimitry Andric return nullptr;
1919b60736ecSDimitry Andric }
1920b60736ecSDimitry Andric
1921b1c73532SDimitry Andric auto tryAddRecExpansion = [&]() -> Instruction* {
1922b60736ecSDimitry Andric // Does this user itself evaluate to a recurrence after widening?
1923b60736ecSDimitry Andric WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1924b60736ecSDimitry Andric if (!WideAddRec.first)
1925b60736ecSDimitry Andric WideAddRec = getWideRecurrence(DU);
19264b4fe385SDimitry Andric assert((WideAddRec.first == nullptr) ==
19274b4fe385SDimitry Andric (WideAddRec.second == ExtendKind::Unknown));
1928b1c73532SDimitry Andric if (!WideAddRec.first)
1929b60736ecSDimitry Andric return nullptr;
1930b60736ecSDimitry Andric
19317432c960SDimitry Andric auto CanUseWideInc = [&]() {
19327432c960SDimitry Andric if (!WideInc)
19337432c960SDimitry Andric return false;
19347432c960SDimitry Andric // Reuse the IV increment that SCEVExpander created. Recompute flags,
19357432c960SDimitry Andric // unless the flags for both increments agree and it is safe to use the
19367432c960SDimitry Andric // ones from the original inc. In that case, the new use of the wide
19377432c960SDimitry Andric // increment won't be more poisonous.
1938ac9a064cSDimitry Andric bool NeedToRecomputeFlags =
19397432c960SDimitry Andric !SCEVExpander::canReuseFlagsFromOriginalIVInc(
19407432c960SDimitry Andric OrigPhi, WidePhi, DU.NarrowUse, WideInc) ||
1941ac9a064cSDimitry Andric DU.NarrowUse->hasNoUnsignedWrap() != WideInc->hasNoUnsignedWrap() ||
1942ac9a064cSDimitry Andric DU.NarrowUse->hasNoSignedWrap() != WideInc->hasNoSignedWrap();
19437432c960SDimitry Andric return WideAddRec.first == WideIncExpr &&
19447432c960SDimitry Andric Rewriter.hoistIVInc(WideInc, DU.NarrowUse, NeedToRecomputeFlags);
19457432c960SDimitry Andric };
19467432c960SDimitry Andric
1947b60736ecSDimitry Andric Instruction *WideUse = nullptr;
19487432c960SDimitry Andric if (CanUseWideInc())
1949b60736ecSDimitry Andric WideUse = WideInc;
1950b60736ecSDimitry Andric else {
1951b60736ecSDimitry Andric WideUse = cloneIVUser(DU, WideAddRec.first);
1952b60736ecSDimitry Andric if (!WideUse)
1953b60736ecSDimitry Andric return nullptr;
1954b60736ecSDimitry Andric }
1955b60736ecSDimitry Andric // Evaluation of WideAddRec ensured that the narrow expression could be
1956b60736ecSDimitry Andric // extended outside the loop without overflow. This suggests that the wide use
1957b60736ecSDimitry Andric // evaluates to the same expression as the extended narrow use, but doesn't
1958b60736ecSDimitry Andric // absolutely guarantee it. Hence the following failsafe check. In rare cases
1959b60736ecSDimitry Andric // where it fails, we simply throw away the newly created wide use.
1960b60736ecSDimitry Andric if (WideAddRec.first != SE->getSCEV(WideUse)) {
1961b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1962b60736ecSDimitry Andric << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1963b60736ecSDimitry Andric << "\n");
1964b60736ecSDimitry Andric DeadInsts.emplace_back(WideUse);
1965b60736ecSDimitry Andric return nullptr;
1966b1c73532SDimitry Andric };
1967b60736ecSDimitry Andric
1968b60736ecSDimitry Andric // if we reached this point then we are going to replace
1969b60736ecSDimitry Andric // DU.NarrowUse with WideUse. Reattach DbgValue then.
1970b60736ecSDimitry Andric replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
1971b60736ecSDimitry Andric
1972b60736ecSDimitry Andric ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1973b60736ecSDimitry Andric // Returning WideUse pushes it on the worklist.
1974b60736ecSDimitry Andric return WideUse;
1975b1c73532SDimitry Andric };
1976b1c73532SDimitry Andric
1977b1c73532SDimitry Andric if (auto *I = tryAddRecExpansion())
1978b1c73532SDimitry Andric return I;
1979b1c73532SDimitry Andric
1980b1c73532SDimitry Andric // If use is a loop condition, try to promote the condition instead of
1981b1c73532SDimitry Andric // truncating the IV first.
1982b1c73532SDimitry Andric if (widenLoopCompare(DU))
1983b1c73532SDimitry Andric return nullptr;
1984b1c73532SDimitry Andric
1985b1c73532SDimitry Andric // We are here about to generate a truncate instruction that may hurt
1986b1c73532SDimitry Andric // performance because the scalar evolution expression computed earlier
1987b1c73532SDimitry Andric // in WideAddRec.first does not indicate a polynomial induction expression.
1988b1c73532SDimitry Andric // In that case, look at the operands of the use instruction to determine
1989b1c73532SDimitry Andric // if we can still widen the use instead of truncating its operand.
1990b1c73532SDimitry Andric if (widenWithVariantUse(DU))
1991b1c73532SDimitry Andric return nullptr;
1992b1c73532SDimitry Andric
1993b1c73532SDimitry Andric // This user does not evaluate to a recurrence after widening, so don't
1994b1c73532SDimitry Andric // follow it. Instead insert a Trunc to kill off the original use,
1995b1c73532SDimitry Andric // eventually isolating the original narrow IV so it can be removed.
1996ac9a064cSDimitry Andric truncateIVUse(DU);
1997b1c73532SDimitry Andric return nullptr;
1998b60736ecSDimitry Andric }
1999b60736ecSDimitry Andric
2000b60736ecSDimitry Andric /// Add eligible users of NarrowDef to NarrowIVUsers.
pushNarrowIVUsers(Instruction * NarrowDef,Instruction * WideDef)2001b60736ecSDimitry Andric void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
2002b60736ecSDimitry Andric const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
2003b60736ecSDimitry Andric bool NonNegativeDef =
2004b60736ecSDimitry Andric SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
2005b60736ecSDimitry Andric SE->getZero(NarrowSCEV->getType()));
2006b60736ecSDimitry Andric for (User *U : NarrowDef->users()) {
2007b60736ecSDimitry Andric Instruction *NarrowUser = cast<Instruction>(U);
2008b60736ecSDimitry Andric
2009b60736ecSDimitry Andric // Handle data flow merges and bizarre phi cycles.
2010b60736ecSDimitry Andric if (!Widened.insert(NarrowUser).second)
2011b60736ecSDimitry Andric continue;
2012b60736ecSDimitry Andric
2013b60736ecSDimitry Andric bool NonNegativeUse = false;
2014b60736ecSDimitry Andric if (!NonNegativeDef) {
2015b60736ecSDimitry Andric // We might have a control-dependent range information for this context.
2016b60736ecSDimitry Andric if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
2017b60736ecSDimitry Andric NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
2018b60736ecSDimitry Andric }
2019b60736ecSDimitry Andric
2020b60736ecSDimitry Andric NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
2021b60736ecSDimitry Andric NonNegativeDef || NonNegativeUse);
2022b60736ecSDimitry Andric }
2023b60736ecSDimitry Andric }
2024b60736ecSDimitry Andric
2025b60736ecSDimitry Andric /// Process a single induction variable. First use the SCEVExpander to create a
2026b60736ecSDimitry Andric /// wide induction variable that evaluates to the same recurrence as the
2027b60736ecSDimitry Andric /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
2028b60736ecSDimitry Andric /// def-use chain. After widenIVUse has processed all interesting IV users, the
2029b60736ecSDimitry Andric /// narrow IV will be isolated for removal by DeleteDeadPHIs.
2030b60736ecSDimitry Andric ///
2031b60736ecSDimitry Andric /// It would be simpler to delete uses as they are processed, but we must avoid
2032b60736ecSDimitry Andric /// invalidating SCEV expressions.
createWideIV(SCEVExpander & Rewriter)2033b60736ecSDimitry Andric PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
2034b60736ecSDimitry Andric // Is this phi an induction variable?
2035b60736ecSDimitry Andric const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
2036b60736ecSDimitry Andric if (!AddRec)
2037b60736ecSDimitry Andric return nullptr;
2038b60736ecSDimitry Andric
2039b60736ecSDimitry Andric // Widen the induction variable expression.
20404b4fe385SDimitry Andric const SCEV *WideIVExpr = getExtendKind(OrigPhi) == ExtendKind::Sign
2041b60736ecSDimitry Andric ? SE->getSignExtendExpr(AddRec, WideType)
2042b60736ecSDimitry Andric : SE->getZeroExtendExpr(AddRec, WideType);
2043b60736ecSDimitry Andric
2044b60736ecSDimitry Andric assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
2045b60736ecSDimitry Andric "Expect the new IV expression to preserve its type");
2046b60736ecSDimitry Andric
2047b60736ecSDimitry Andric // Can the IV be extended outside the loop without overflow?
2048b60736ecSDimitry Andric AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
2049b60736ecSDimitry Andric if (!AddRec || AddRec->getLoop() != L)
2050b60736ecSDimitry Andric return nullptr;
2051b60736ecSDimitry Andric
2052b60736ecSDimitry Andric // An AddRec must have loop-invariant operands. Since this AddRec is
2053b60736ecSDimitry Andric // materialized by a loop header phi, the expression cannot have any post-loop
2054b60736ecSDimitry Andric // operands, so they must dominate the loop header.
2055b60736ecSDimitry Andric assert(
2056b60736ecSDimitry Andric SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
2057b60736ecSDimitry Andric SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
2058b60736ecSDimitry Andric "Loop header phi recurrence inputs do not dominate the loop");
2059b60736ecSDimitry Andric
2060b60736ecSDimitry Andric // Iterate over IV uses (including transitive ones) looking for IV increments
2061b60736ecSDimitry Andric // of the form 'add nsw %iv, <const>'. For each increment and each use of
2062b60736ecSDimitry Andric // the increment calculate control-dependent range information basing on
2063b60736ecSDimitry Andric // dominating conditions inside of the loop (e.g. a range check inside of the
2064b60736ecSDimitry Andric // loop). Calculated ranges are stored in PostIncRangeInfos map.
2065b60736ecSDimitry Andric //
2066b60736ecSDimitry Andric // Control-dependent range information is later used to prove that a narrow
2067b60736ecSDimitry Andric // definition is not negative (see pushNarrowIVUsers). It's difficult to do
2068b60736ecSDimitry Andric // this on demand because when pushNarrowIVUsers needs this information some
2069b60736ecSDimitry Andric // of the dominating conditions might be already widened.
2070b60736ecSDimitry Andric if (UsePostIncrementRanges)
2071b60736ecSDimitry Andric calculatePostIncRanges(OrigPhi);
2072b60736ecSDimitry Andric
2073b60736ecSDimitry Andric // The rewriter provides a value for the desired IV expression. This may
2074b60736ecSDimitry Andric // either find an existing phi or materialize a new one. Either way, we
2075b60736ecSDimitry Andric // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
2076b60736ecSDimitry Andric // of the phi-SCC dominates the loop entry.
2077b60736ecSDimitry Andric Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
2078b60736ecSDimitry Andric Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
2079b60736ecSDimitry Andric // If the wide phi is not a phi node, for example a cast node, like bitcast,
2080b60736ecSDimitry Andric // inttoptr, ptrtoint, just skip for now.
2081b60736ecSDimitry Andric if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
2082b60736ecSDimitry Andric // if the cast node is an inserted instruction without any user, we should
2083b60736ecSDimitry Andric // remove it to make sure the pass don't touch the function as we can not
2084b60736ecSDimitry Andric // wide the phi.
2085b60736ecSDimitry Andric if (ExpandInst->hasNUses(0) &&
2086b60736ecSDimitry Andric Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
2087b60736ecSDimitry Andric DeadInsts.emplace_back(ExpandInst);
2088b60736ecSDimitry Andric return nullptr;
2089b60736ecSDimitry Andric }
2090b60736ecSDimitry Andric
2091b60736ecSDimitry Andric // Remembering the WideIV increment generated by SCEVExpander allows
2092b60736ecSDimitry Andric // widenIVUse to reuse it when widening the narrow IV's increment. We don't
2093b60736ecSDimitry Andric // employ a general reuse mechanism because the call above is the only call to
2094b60736ecSDimitry Andric // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
2095b60736ecSDimitry Andric if (BasicBlock *LatchBlock = L->getLoopLatch()) {
2096b60736ecSDimitry Andric WideInc =
2097b1c73532SDimitry Andric dyn_cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
2098b1c73532SDimitry Andric if (WideInc) {
2099b60736ecSDimitry Andric WideIncExpr = SE->getSCEV(WideInc);
2100b1c73532SDimitry Andric // Propagate the debug location associated with the original loop
2101b1c73532SDimitry Andric // increment to the new (widened) increment.
2102b60736ecSDimitry Andric auto *OrigInc =
2103b60736ecSDimitry Andric cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
2104ac9a064cSDimitry Andric
2105b60736ecSDimitry Andric WideInc->setDebugLoc(OrigInc->getDebugLoc());
2106ac9a064cSDimitry Andric // We are replacing a narrow IV increment with a wider IV increment. If
2107ac9a064cSDimitry Andric // the original (narrow) increment did not wrap, the wider increment one
2108ac9a064cSDimitry Andric // should not wrap either. Set the flags to be the union of both wide
2109ac9a064cSDimitry Andric // increment and original increment; this ensures we preserve flags SCEV
2110ac9a064cSDimitry Andric // could infer for the wider increment. Limit this only to cases where
2111ac9a064cSDimitry Andric // both increments directly increment the corresponding PHI nodes and have
2112ac9a064cSDimitry Andric // the same opcode. It is not safe to re-use the flags from the original
2113ac9a064cSDimitry Andric // increment, if it is more complex and SCEV expansion may have yielded a
2114ac9a064cSDimitry Andric // more simplified wider increment.
2115ac9a064cSDimitry Andric if (SCEVExpander::canReuseFlagsFromOriginalIVInc(OrigPhi, WidePhi,
2116ac9a064cSDimitry Andric OrigInc, WideInc) &&
2117ac9a064cSDimitry Andric isa<OverflowingBinaryOperator>(OrigInc) &&
2118ac9a064cSDimitry Andric isa<OverflowingBinaryOperator>(WideInc)) {
2119ac9a064cSDimitry Andric WideInc->setHasNoUnsignedWrap(WideInc->hasNoUnsignedWrap() ||
2120ac9a064cSDimitry Andric OrigInc->hasNoUnsignedWrap());
2121ac9a064cSDimitry Andric WideInc->setHasNoSignedWrap(WideInc->hasNoSignedWrap() ||
2122ac9a064cSDimitry Andric OrigInc->hasNoSignedWrap());
2123ac9a064cSDimitry Andric }
2124b60736ecSDimitry Andric }
2125b1c73532SDimitry Andric }
2126b60736ecSDimitry Andric
2127b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
2128b60736ecSDimitry Andric ++NumWidened;
2129b60736ecSDimitry Andric
2130b60736ecSDimitry Andric // Traverse the def-use chain using a worklist starting at the original IV.
2131b60736ecSDimitry Andric assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
2132b60736ecSDimitry Andric
2133b60736ecSDimitry Andric Widened.insert(OrigPhi);
2134b60736ecSDimitry Andric pushNarrowIVUsers(OrigPhi, WidePhi);
2135b60736ecSDimitry Andric
2136b60736ecSDimitry Andric while (!NarrowIVUsers.empty()) {
2137b60736ecSDimitry Andric WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
2138b60736ecSDimitry Andric
2139b60736ecSDimitry Andric // Process a def-use edge. This may replace the use, so don't hold a
2140b60736ecSDimitry Andric // use_iterator across it.
2141ac9a064cSDimitry Andric Instruction *WideUse = widenIVUse(DU, Rewriter, OrigPhi, WidePhi);
2142b60736ecSDimitry Andric
2143b60736ecSDimitry Andric // Follow all def-use edges from the previous narrow use.
2144b60736ecSDimitry Andric if (WideUse)
2145b60736ecSDimitry Andric pushNarrowIVUsers(DU.NarrowUse, WideUse);
2146b60736ecSDimitry Andric
2147b60736ecSDimitry Andric // widenIVUse may have removed the def-use edge.
2148b60736ecSDimitry Andric if (DU.NarrowDef->use_empty())
2149b60736ecSDimitry Andric DeadInsts.emplace_back(DU.NarrowDef);
2150b60736ecSDimitry Andric }
2151b60736ecSDimitry Andric
2152b60736ecSDimitry Andric // Attach any debug information to the new PHI.
2153b60736ecSDimitry Andric replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
2154b60736ecSDimitry Andric
2155b60736ecSDimitry Andric return WidePhi;
2156b60736ecSDimitry Andric }
2157b60736ecSDimitry Andric
2158b60736ecSDimitry Andric /// Calculates control-dependent range for the given def at the given context
2159b60736ecSDimitry Andric /// by looking at dominating conditions inside of the loop
calculatePostIncRange(Instruction * NarrowDef,Instruction * NarrowUser)2160b60736ecSDimitry Andric void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
2161b60736ecSDimitry Andric Instruction *NarrowUser) {
2162b60736ecSDimitry Andric Value *NarrowDefLHS;
2163b60736ecSDimitry Andric const APInt *NarrowDefRHS;
2164b60736ecSDimitry Andric if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
2165b60736ecSDimitry Andric m_APInt(NarrowDefRHS))) ||
2166b60736ecSDimitry Andric !NarrowDefRHS->isNonNegative())
2167b60736ecSDimitry Andric return;
2168b60736ecSDimitry Andric
2169b60736ecSDimitry Andric auto UpdateRangeFromCondition = [&] (Value *Condition,
2170b60736ecSDimitry Andric bool TrueDest) {
2171b60736ecSDimitry Andric CmpInst::Predicate Pred;
2172b60736ecSDimitry Andric Value *CmpRHS;
2173b60736ecSDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
2174b60736ecSDimitry Andric m_Value(CmpRHS))))
2175b60736ecSDimitry Andric return;
2176b60736ecSDimitry Andric
2177b60736ecSDimitry Andric CmpInst::Predicate P =
2178b60736ecSDimitry Andric TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
2179b60736ecSDimitry Andric
2180b60736ecSDimitry Andric auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
2181b60736ecSDimitry Andric auto CmpConstrainedLHSRange =
2182b60736ecSDimitry Andric ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
2183b60736ecSDimitry Andric auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2184b60736ecSDimitry Andric *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap);
2185b60736ecSDimitry Andric
2186b60736ecSDimitry Andric updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2187b60736ecSDimitry Andric };
2188b60736ecSDimitry Andric
2189b60736ecSDimitry Andric auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
2190b60736ecSDimitry Andric if (!HasGuards)
2191b60736ecSDimitry Andric return;
2192b60736ecSDimitry Andric
2193b60736ecSDimitry Andric for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
2194b60736ecSDimitry Andric Ctx->getParent()->rend())) {
2195b60736ecSDimitry Andric Value *C = nullptr;
2196b60736ecSDimitry Andric if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
2197b60736ecSDimitry Andric UpdateRangeFromCondition(C, /*TrueDest=*/true);
2198b60736ecSDimitry Andric }
2199b60736ecSDimitry Andric };
2200b60736ecSDimitry Andric
2201b60736ecSDimitry Andric UpdateRangeFromGuards(NarrowUser);
2202b60736ecSDimitry Andric
2203b60736ecSDimitry Andric BasicBlock *NarrowUserBB = NarrowUser->getParent();
2204b60736ecSDimitry Andric // If NarrowUserBB is statically unreachable asking dominator queries may
2205b60736ecSDimitry Andric // yield surprising results. (e.g. the block may not have a dom tree node)
2206b60736ecSDimitry Andric if (!DT->isReachableFromEntry(NarrowUserBB))
2207b60736ecSDimitry Andric return;
2208b60736ecSDimitry Andric
2209b60736ecSDimitry Andric for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2210b60736ecSDimitry Andric L->contains(DTB->getBlock());
2211b60736ecSDimitry Andric DTB = DTB->getIDom()) {
2212b60736ecSDimitry Andric auto *BB = DTB->getBlock();
2213b60736ecSDimitry Andric auto *TI = BB->getTerminator();
2214b60736ecSDimitry Andric UpdateRangeFromGuards(TI);
2215b60736ecSDimitry Andric
2216b60736ecSDimitry Andric auto *BI = dyn_cast<BranchInst>(TI);
2217b60736ecSDimitry Andric if (!BI || !BI->isConditional())
2218b60736ecSDimitry Andric continue;
2219b60736ecSDimitry Andric
2220b60736ecSDimitry Andric auto *TrueSuccessor = BI->getSuccessor(0);
2221b60736ecSDimitry Andric auto *FalseSuccessor = BI->getSuccessor(1);
2222b60736ecSDimitry Andric
2223b60736ecSDimitry Andric auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
2224b60736ecSDimitry Andric return BBE.isSingleEdge() &&
2225b60736ecSDimitry Andric DT->dominates(BBE, NarrowUser->getParent());
2226b60736ecSDimitry Andric };
2227b60736ecSDimitry Andric
2228b60736ecSDimitry Andric if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
2229b60736ecSDimitry Andric UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
2230b60736ecSDimitry Andric
2231b60736ecSDimitry Andric if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
2232b60736ecSDimitry Andric UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
2233b60736ecSDimitry Andric }
2234b60736ecSDimitry Andric }
2235b60736ecSDimitry Andric
2236b60736ecSDimitry Andric /// Calculates PostIncRangeInfos map for the given IV
calculatePostIncRanges(PHINode * OrigPhi)2237b60736ecSDimitry Andric void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2238b60736ecSDimitry Andric SmallPtrSet<Instruction *, 16> Visited;
2239b60736ecSDimitry Andric SmallVector<Instruction *, 6> Worklist;
2240b60736ecSDimitry Andric Worklist.push_back(OrigPhi);
2241b60736ecSDimitry Andric Visited.insert(OrigPhi);
2242b60736ecSDimitry Andric
2243b60736ecSDimitry Andric while (!Worklist.empty()) {
2244b60736ecSDimitry Andric Instruction *NarrowDef = Worklist.pop_back_val();
2245b60736ecSDimitry Andric
2246b60736ecSDimitry Andric for (Use &U : NarrowDef->uses()) {
2247b60736ecSDimitry Andric auto *NarrowUser = cast<Instruction>(U.getUser());
2248b60736ecSDimitry Andric
2249b60736ecSDimitry Andric // Don't go looking outside the current loop.
2250b60736ecSDimitry Andric auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
2251b60736ecSDimitry Andric if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
2252b60736ecSDimitry Andric continue;
2253b60736ecSDimitry Andric
2254b60736ecSDimitry Andric if (!Visited.insert(NarrowUser).second)
2255b60736ecSDimitry Andric continue;
2256b60736ecSDimitry Andric
2257b60736ecSDimitry Andric Worklist.push_back(NarrowUser);
2258b60736ecSDimitry Andric
2259b60736ecSDimitry Andric calculatePostIncRange(NarrowDef, NarrowUser);
2260b60736ecSDimitry Andric }
2261b60736ecSDimitry Andric }
2262b60736ecSDimitry Andric }
2263b60736ecSDimitry Andric
createWideIV(const WideIVInfo & WI,LoopInfo * LI,ScalarEvolution * SE,SCEVExpander & Rewriter,DominatorTree * DT,SmallVectorImpl<WeakTrackingVH> & DeadInsts,unsigned & NumElimExt,unsigned & NumWidened,bool HasGuards,bool UsePostIncrementRanges)2264b60736ecSDimitry Andric PHINode *llvm::createWideIV(const WideIVInfo &WI,
2265b60736ecSDimitry Andric LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
2266b60736ecSDimitry Andric DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
2267b60736ecSDimitry Andric unsigned &NumElimExt, unsigned &NumWidened,
2268b60736ecSDimitry Andric bool HasGuards, bool UsePostIncrementRanges) {
2269b60736ecSDimitry Andric WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2270b60736ecSDimitry Andric PHINode *WidePHI = Widener.createWideIV(Rewriter);
2271b60736ecSDimitry Andric NumElimExt = Widener.getNumElimExt();
2272b60736ecSDimitry Andric NumWidened = Widener.getNumWidened();
2273b60736ecSDimitry Andric return WidePHI;
2274b60736ecSDimitry Andric }
2275