[llvm] [InstCombine] Canonicalize Bit Testing by Shifting to Sign Bit (PR #101822)

via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 10 08:01:18 PDT 2024


================
@@ -2304,19 +2304,33 @@ Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
     if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
       return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
 
+  unsigned TypeBits = C.getBitWidth();
+  Value *X = Shl->getOperand(0);
+  Type *ShType = Shl->getType();
+
+  // (icmp slt (shl X, (sub bw-1, Y)), 0)  --> (icmp ne (and X, (shl 1, Y)), 0)
+  // (icmp sgt (shl X, (sub bw-1, Y)), -1) --> (icmp eq (and X, (shl 1, Y)), 0)
+  Value *Y;
+  if (Shl->hasOneUse() &&
+      (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT) &&
+      (Pred == ICmpInst::ICMP_SLT ? C.isZero() : C.isAllOnes()) &&
+      match(Shl->getOperand(1),
+            m_OneUse(m_Sub(m_SpecificInt(TypeBits - 1), m_Value(Y)))))
+    return new ICmpInst(
+        Pred == ICmpInst::ICMP_SLT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
+        Builder.CreateAnd(X, Builder.CreateShl(ConstantInt::get(ShType, 1), Y,
----------------
goldsteinn wrote:

Maybe just `X` -> `Shl->getOperand(0)`. You never use `X` anywhere else so not really simplifying to make it a variable.

https://github.com/llvm/llvm-project/pull/101822


More information about the llvm-commits mailing list