[llvm] [InstCombine] Fold square into comparison with constant (reopened) (PR #197665)
Macsen Casaus via llvm-commits
llvm-commits at lists.llvm.org
Thu Jun 11 11:52:02 PDT 2026
================
@@ -2188,12 +2188,49 @@ Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
Type *MulTy = Mul->getType();
Value *X = Mul->getOperand(0);
- // If there's no overflow:
- // X * X == 0 --> X == 0
- // X * X != 0 --> X != 0
- if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
- (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
- return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
+ // If comparing a square with a constant, try simplifying to comparing square
+ // roots
+ if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
+ APInt R = C.sqrtFloor();
+ APInt R2 = R * R;
+ bool IsSqr = C == R2;
+
+ // X * X eq/ne C
+ if (Cmp.isEquality() &&
+ (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
----------------
macsencasaus wrote:
This optimization was already present and tested for
https://github.com/llvm/llvm-project/blob/b6501be5448273989e28210b4befd3b862568aff/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp#L2191-L2196
https://github.com/llvm/llvm-project/blob/b6501be5448273989e28210b4befd3b862568aff/llvm/test/Transforms/InstCombine/icmp-mul.ll#L9-L17
https://github.com/llvm/llvm-project/pull/197665
More information about the llvm-commits
mailing list