[llvm] [InstCombine] optimize unnecessary sext instruction with add + cmp (PR #152291)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Fri Aug 22 08:35:58 PDT 2025
================
@@ -6381,6 +6381,82 @@ Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
}
+Instruction *InstCombinerImpl::foldICmpWithSextAndAdd(ICmpInst &ICmp) {
+ Value *X;
+ Value *Y, *Z;
+ // Match the pattern: icmp ult (add (sext X), Y), Z
+ // where X is a value, Y and Z are integer constants
+ // icmp ult (add(sext(X), Y)), Z -> icmp ult (add(X, Y)), Z
+ if (match(&ICmp, m_SpecificICmp(CmpInst::ICMP_ULT,
+ m_Add(m_SExt(m_Value(X)), m_Value(Y)),
+ m_Value(Z)))) {
+ Type *XType = X->getType();
+ if (!XType->isIntegerTy())
+ return nullptr;
+
+ unsigned XBitWidth = XType->getIntegerBitWidth();
+ auto ExtractValue = [&](Value *V, Type *TargetType,
+ int64_t &OutValue) -> Value * {
+ if (auto *C = dyn_cast<ConstantInt>(V)) {
+ OutValue = C->getSExtValue();
----------------
dtcxzyw wrote:
You can use the `m_APInt` matcher.
```
APInt &OutValue)
const APInt *C;
if (match(V, m_APInt(C))) {
OutValue = C->getValue().sextOrTrunc(TargetType->getScalarSizeInBits());
}
```
BTW, you can use `m_APInt` in the matching code above (i.e., `match(&ICmp, ...)`), as we don't want to handle non-constant cases in the original issue. Y and Z must be constants.
Then you can simply check if `Y` and `Z` have less than `X->getType()->getScalarSizeInBits()` significant bits.
```
const APInt *Y;
const APInt *Z;
if (match(&ICmp, m_SpecificICmp(CmpInst::ICMP_ULT,
m_Add(m_SExt(m_Value(X)), m_APInt(Y)),
m_APInt(Z))) && Y->isSignedIntN(X->getType()->getScalarSizeInBits()) && Z->isSignedIntN(X->getType()->getScalarSizeInBits())) {
...
}
```
https://github.com/llvm/llvm-project/pull/152291
More information about the llvm-commits
mailing list