[llvm] [AArch64] Convert comparisons with 1 and -1 to 0 if it is profitable (PR #141151)

via llvm-commits llvm-commits at lists.llvm.org
Thu May 29 07:25:03 PDT 2025


================
@@ -3755,58 +3763,82 @@ static unsigned getCmpOperandFoldingProfit(SDValue Op) {
   return 0;
 }
 
+// emitComparison() converts comparison with one or negative one to comparison
+// with 0.
+static bool shouldBeAdjustedToZero(SDValue LHS, APInt C, ISD::CondCode CC) {
+  // Only works for not signed values.
+  if (isUnsignedIntSetCC(CC))
+    return false;
+  // Only works for ANDS and AND.
+  if (LHS.getOpcode() != ISD::AND && LHS.getOpcode() != AArch64ISD::ANDS)
+    return false;
+  if (C.isOne() && (CC == ISD::SETLT || CC == ISD::SETGE))
+    return true;
+  if (C.isAllOnes() && (CC == ISD::SETLE || CC == ISD::SETGT))
+    return true;
+
+  return false;
+}
+
 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
                              SDValue &AArch64cc, SelectionDAG &DAG,
                              const SDLoc &dl) {
   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
     EVT VT = RHS.getValueType();
-    uint64_t C = RHSC->getZExtValue();
-    if (!isLegalArithImmed(C)) {
+    APInt C = RHSC->getAPIntValue();
+    int64_t C = RHSC->getSExtValue();
+    // This is a special case to better fold with emitComparison().
+    if (shouldBeAdjustedToZero(LHS, C, CC)) {
+      if (C.isOne()) {
----------------
AZero13 wrote:

Yes

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


More information about the llvm-commits mailing list