[llvm] [InstCombine] simplify `x (comp) ~x` (PR #73990)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Fri Dec 1 17:12:50 PST 2023


================
@@ -7035,6 +7035,54 @@ Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
       return new ICmpInst(I.getSwappedPredicate(Pred), Builder.CreateXor(X, Y),
                           Z);
 
+    // Transform X s<  ~X  -->   X s<  0
+    //           X s>  ~X  -->   X s>  -1
+    //           X s>= ~X  -->   X s>  -1
+    //           X s<= ~X  -->   X s<  0
+    //           X u<  ~X  -->   X u<  (SIGNBIT(X))
+    //           X u>  ~X  -->   X u>  (SIGNBIT(X))
+    //           X u<= ~X  -->   X u<  (SIGNBIT(X))
+    //           X u>= ~X  -->   X u>  (SIGNBIT(X))
+    //           X ==  ~X  -->   false
+    //           X !=  ~X  -->   true
+    if (match(&I, m_c_ICmp(Pred, m_Value(X), m_Not(m_Deferred(X))))) {
+      // if `~X (comp) X`, replace it with `X (Swapped-comp) ~X`.
+      // ex) ~X s< X  -->  X s> ~X
+      if (match(I.getOperand(0), m_Not(m_Specific(X))))
+        Pred = I.getSwappedPredicate();
+
+      CmpInst::Predicate PredEqRemoved;
+      Constant *Const;
+      APInt C;
+      switch (Pred) {
+      case ICmpInst::ICMP_EQ:
+        return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
+        break;
+      case ICmpInst::ICMP_NE:
+        return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
+        break;
+      case ICmpInst::ICMP_UGT:
+      case ICmpInst::ICMP_UGE:
+      case ICmpInst::ICMP_ULT:
+      case ICmpInst::ICMP_ULE:
+        PredEqRemoved = CmpInst::getStrictPredicate(Pred);
+        C = APInt::getSignMask(X->getType()->getScalarSizeInBits());
+        Const = ConstantInt::get(X->getType(), C);
+        break;
+      case ICmpInst::ICMP_SGT:
+      case ICmpInst::ICMP_SGE:
+      case ICmpInst::ICMP_SLT:
+      case ICmpInst::ICMP_SLE:
+        PredEqRemoved = CmpInst::getStrictPredicate(Pred);
+        Const = ConstantInt::get(X->getType(),
+                                 PredEqRemoved == ICmpInst::ICMP_SGT ? -1 : 0);
----------------
dtcxzyw wrote:

```suggestion
        Const = ConstantInt::get(X->getType(),
                                 PredEqRemoved == ICmpInst::ICMP_SGT ? -1 : 0, /*IsSigned*/ true);
```
It doesn't work for `i128`. Please add some tests for `i128`.


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


More information about the llvm-commits mailing list