Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[InstSimplify] Fold X < Y ? (X + zext(X < Y)) <= Y : false to X < Y #118579

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions llvm/lib/Analysis/InstructionSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4639,6 +4639,45 @@ static Value *simplifySelectWithEquivalence(Value *CmpLHS, Value *CmpRHS,
return nullptr;
}

/// Simplifies:
/// `X > Y ? (X + zext(X > Y)) >= Y : false` to `X > Y`
/// `X < Y ? (X + zext(X < Y)) <= Y : false` to `X < Y`
static Value *simplifySelectWithStrictICmp(Value *CondVal, Value *TVal,
Value *FVal,
const SimplifyQuery &Q) {
if (!match(FVal, m_Zero()))
return nullptr;

ICmpInst::Predicate Pred;
Value *CmpLHS, *CmpRHS;

if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
return nullptr;

if (!CmpInst::isStrictPredicate(Pred))
return nullptr;

ICmpInst::Predicate NonStrictPred = ICmpInst::getNonStrictPredicate(Pred);
BinaryOperator *BinOp;

if (!match(TVal,
m_SpecificICmp(NonStrictPred, m_BinOp(BinOp), m_Specific(CmpRHS))))
return nullptr;

// This fold works for GT only when it does not wrap.
if (Pred == ICmpInst::ICMP_UGT && !Q.IIQ.hasNoUnsignedWrap(BinOp))
return nullptr;

if (Pred == ICmpInst::ICMP_SGT && !Q.IIQ.hasNoSignedWrap(BinOp))
return nullptr;

if (!match(BinOp, m_c_BinOp(Instruction::Add, m_Specific(CmpLHS),
m_ZExt(m_Specific(CondVal)))))
return nullptr;

return CondVal;
}

/// Try to simplify a select instruction when its condition operand is an
/// integer comparison.
static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
Expand Down Expand Up @@ -4761,6 +4800,9 @@ static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
}
}

if (Value *V = simplifySelectWithStrictICmp(CondVal, TrueVal, FalseVal, Q))
return V;

return nullptr;
}

Expand Down
Loading
Loading