34 #define DEBUG_TYPE "indvars"
36 STATISTIC(NumElimIdentity,
"Number of IV identities eliminated");
37 STATISTIC(NumElimOperand,
"Number of IV operands folded into a use");
38 STATISTIC(NumElimRem ,
"Number of IV remainder operations eliminated");
41 "Number of IV signed division operations converted to unsigned division");
42 STATISTIC(NumElimCmp ,
"Number of IV comparisons eliminated");
49 class SimplifyIndvar {
62 :
L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(
false) {
63 assert(LI &&
"IV simplification requires LoopInfo");
66 bool hasChanged()
const {
return Changed; }
77 bool eliminateOverflowIntrinsic(
CallInst *CI);
97 Value *IVSrc =
nullptr;
99 const SCEV *FoldedExpr =
nullptr;
103 case Instruction::UDiv:
104 case Instruction::LShr:
107 if (IVOperand != UseInst->
getOperand(OperIdx) ||
113 if (!isa<BinaryOperator>(IVOperand)
114 || !isa<ConstantInt>(IVOperand->
getOperand(1)))
119 assert(SE->isSCEVable(IVSrc->
getType()) &&
"Expect SCEVable IV operand");
122 if (UseInst->
getOpcode() == Instruction::LShr) {
131 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
134 if (!SE->isSCEVable(UseInst->
getType()))
138 if (SE->getSCEV(UseInst) != FoldedExpr)
141 DEBUG(
dbgs() <<
"INDVARS: Eliminated IV operand: " << *IVOperand
142 <<
" -> " << *UseInst <<
'\n');
145 assert(SE->getSCEV(UseInst) == FoldedExpr &&
"bad SCEV with folded oper");
150 DeadInsts.emplace_back(IVOperand);
156 void SimplifyIndvar::eliminateIVComparison(
ICmpInst *ICmp,
Value *IVOperand) {
157 unsigned IVOperIdx = 0;
173 S = SE->getSCEVAtScope(S, ICmpLoop);
174 X = SE->getSCEVAtScope(X, ICmpLoop);
177 const SCEV *InvariantLHS, *InvariantRHS;
181 if (SE->isKnownPredicate(Pred, S, X)) {
183 DeadInsts.emplace_back(ICmp);
184 DEBUG(
dbgs() <<
"INDVARS: Eliminated comparison: " << *ICmp <<
'\n');
187 DeadInsts.emplace_back(ICmp);
188 DEBUG(
dbgs() <<
"INDVARS: Eliminated comparison: " << *ICmp <<
'\n');
189 }
else if (isa<PHINode>(IVOperand) &&
190 SE->isLoopInvariantPredicate(Pred, S, X,
L, InvariantPredicate,
191 InvariantLHS, InvariantRHS)) {
197 Value *NewLHS =
nullptr, *NewRHS =
nullptr;
199 if (S == InvariantLHS || X == InvariantLHS)
201 ICmp->
getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
203 if (S == InvariantRHS || X == InvariantRHS)
205 ICmp->
getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
207 auto *PN = cast<PHINode>(IVOperand);
208 for (
unsigned i = 0, e = PN->getNumIncomingValues();
209 i != e && (!NewLHS || !NewRHS);
214 if (
L->
contains(PN->getIncomingBlock(i)))
243 Value *Incoming = PN->getIncomingValue(i);
246 if (
auto *
I = dyn_cast<Instruction>(Incoming))
247 assert(DT->dominates(
I, ICmp) &&
"Should be a unique loop dominating value!");
250 const SCEV *IncomingS = SE->getSCEV(Incoming);
252 if (!NewLHS && IncomingS == InvariantLHS)
254 if (!NewRHS && IncomingS == InvariantRHS)
258 if (!NewLHS || !NewRHS)
264 DEBUG(
dbgs() <<
"INDVARS: Simplified comparison: " << *ICmp <<
'\n');
269 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
276 DEBUG(
dbgs() <<
"INDVARS: Turn to unsigned comparison: " << *ICmp <<
'\n');
292 N = SE->getSCEVAtScope(
N, L);
293 D = SE->getSCEVAtScope(D, L);
296 if (SE->isKnownNonNegative(
N) && SE->isKnownNonNegative(D)) {
299 SDiv->
getName() +
".udiv", SDiv);
302 DEBUG(
dbgs() <<
"INDVARS: Simplified sdiv: " << *SDiv <<
'\n');
305 DeadInsts.push_back(SDiv);
328 S = SE->getSCEVAtScope(S, ICmpLoop);
329 X = SE->getSCEVAtScope(X, ICmpLoop);
332 if ((!IsSigned || SE->isKnownNonNegative(S)) &&
338 const SCEV *LessOne = SE->getMinusSCEV(S, SE->getOne(S->
getType()));
339 if (IsSigned && !SE->isKnownNonNegative(LessOne))
342 if (!SE->isKnownPredicate(IsSigned ?
356 DEBUG(
dbgs() <<
"INDVARS: Simplified rem: " << *Rem <<
'\n');
359 DeadInsts.emplace_back(Rem);
362 bool SimplifyIndvar::eliminateOverflowIntrinsic(
CallInst *CI) {
372 OperationFunctionTy Operation;
373 ExtensionFunctionTy Extension;
379 bool NoSignedOverflow;
381 switch (
F->getIntrinsicID()) {
385 case Intrinsic::sadd_with_overflow:
389 NoSignedOverflow =
true;
392 case Intrinsic::uadd_with_overflow:
396 NoSignedOverflow =
false;
399 case Intrinsic::ssub_with_overflow:
402 RawOp = Instruction::Sub;
403 NoSignedOverflow =
true;
406 case Intrinsic::usub_with_overflow:
409 RawOp = Instruction::Sub;
410 NoSignedOverflow =
false;
417 auto *NarrowTy = cast<IntegerType>(LHS->
getType());
425 (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
426 (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
437 if (NoSignedOverflow)
444 for (
auto *U : CI->
users()) {
445 if (
auto *EVI = dyn_cast<ExtractValueInst>(U)) {
446 if (EVI->getIndices()[0] == 1)
449 assert(EVI->getIndices()[0] == 0 &&
"Only two possibilities!");
450 EVI->replaceAllUsesWith(NewResult);
456 for (
auto *EVI : ToDelete)
457 EVI->eraseFromParent();
468 bool SimplifyIndvar::eliminateIVUser(
Instruction *UseInst,
470 if (
ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
471 eliminateIVComparison(ICmp, IVOperand);
475 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
476 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
477 eliminateIVRemainder(Bin, IVOperand, IsSRem);
481 if (Bin->getOpcode() == Instruction::SDiv)
482 return eliminateSDiv(Bin);
485 if (
auto *CI = dyn_cast<CallInst>(UseInst))
486 if (eliminateOverflowIntrinsic(CI))
489 if (eliminateIdentitySCEV(UseInst, IVOperand))
496 bool SimplifyIndvar::eliminateIdentitySCEV(
Instruction *UseInst,
498 if (!SE->isSCEVable(UseInst->
getType()) ||
500 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
519 if (isa<PHINode>(UseInst))
522 if (!DT || !DT->dominates(IVOperand, UseInst))
525 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
528 DEBUG(
dbgs() <<
"INDVARS: Eliminated identity: " << *UseInst <<
'\n');
533 DeadInsts.emplace_back(UseInst);
539 bool SimplifyIndvar::strengthenOverflowingOperation(
BinaryOperator *BO,
556 case Instruction::Sub:
560 case Instruction::Mul:
570 bool Changed =
false;
573 const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
574 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
575 SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
577 if (ExtendAfterOp == OpAfterExtend) {
585 const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
586 const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
587 SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
589 if (ExtendAfterOp == OpAfterExtend) {
604 using namespace llvm::PatternMatch;
606 if (BO->
getOpcode() == Instruction::Shl) {
607 bool Changed =
false;
608 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
609 for (
auto *U : BO->
users()) {
632 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
641 if (UI != Def && Simplified.
insert(UI).second)
642 SimpleIVUsers.push_back(std::make_pair(UI, Def));
680 if (!SE->isSCEVable(CurrIV->
getType()))
694 while (!SimpleIVUsers.
empty()) {
695 std::pair<Instruction*, Instruction*> UseOper =
700 if (UseInst == CurrIV)
continue;
703 for (
unsigned N = 0; IVOperand; ++
N) {
704 assert(
N <= Simplified.
size() &&
"runaway iteration");
706 Value *NewOper = foldIVUser(UseOper.first, IVOperand);
714 if (eliminateIVUser(UseOper.first, IVOperand)) {
719 if (
BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
720 if ((isa<OverflowingBinaryOperator>(BO) &&
721 strengthenOverflowingOperation(BO, IVOperand)) ||
722 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
735 pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
750 SIV.simplifyUsers(CurrIV, V);
751 return SIV.hasChanged();
758 bool Changed =
false;
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
STATISTIC(NumFunctions,"Total number of functions")
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
bool isSigned() const
Determine if this instruction is using a signed comparison.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
BlockT * getHeader() const
StringRef getName() const
Return a constant reference to the value's name.
bool match(Val *V, const Pattern &P)
Interface for visiting interesting IV users that are recognized but not simplified by this utility...
This class represents the LLVM 'select' instruction.
This is the base class for all instructions that perform data casts.
const APInt & getValue() const
Return the constant as an APInt value reference.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
This node represents a polynomial recurrence on the trip count of the specified loop.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function Alias Analysis false
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
bool isExact() const
Determine whether the exact flag is set.
The instances of the Type class are immutable: once they are created, they are never changed...
Type * getType() const
Return the LLVM type of this SCEV expression.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Value * getOperand(unsigned i) const
Predicate getPredicate() const
Return the predicate for this instruction.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
LLVMContext & getContext() const
All values hold a context through their type.
BinaryOps getOpcode() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
This class represents a range of values.
LLVM_NODISCARD T pop_back_val()
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
static ConstantInt * getTrue(LLVMContext &Context)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE)
Return true if this instruction generates a simple SCEV expression in terms of that IV...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Class for arbitrary precision integers.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
This class represents an analyzed expression in the program.
virtual void visitCast(CastInst *Cast)=0
Represents a single loop in the control flow graph.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const Loop * getLoop() const
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void pushIVUsers(Instruction *Def, SmallPtrSet< Instruction *, 16 > &Simplified, SmallVectorImpl< std::pair< Instruction *, Instruction * > > &SimpleIVUsers)
Add all uses of Def to the current IV's worklist.
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const BasicBlock * getParent() const
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.