[llvm] [AArch64] Correctness fix: Turn cmn 0 into cmp 0 (PR #143965)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 12 13:36:52 PDT 2025


https://github.com/AZero13 created https://github.com/llvm/llvm-project/pull/143965

When we change the condition, in the edge case of -1, we need to change this from cmn 1 to cmp 0. We were returning cmn 0, which is not the same as cmp 0.

>From 680958538424a2b13dc7687fe3eeafc1699c97b6 Mon Sep 17 00:00:00 2001
From: Rose <gfunni234 at gmail.com>
Date: Thu, 12 Jun 2025 16:36:34 -0400
Subject: [PATCH] [AArch64] Correctness fix: Turn cmn 0 into cmp 0

When we change the condition, in the edge case of -1, we need to change this from cmn 1 to cmp 0. We were returning cmn 0, which is not the same as cmp 0.
---
 llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp b/llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp
index 4c9f8c2723493..f14a8e883447f 100644
--- a/llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp
+++ b/llvm/lib/Target/AArch64/AArch64ConditionOptimizer.cpp
@@ -255,7 +255,13 @@ AArch64ConditionOptimizer::CmpInfo AArch64ConditionOptimizer::adjustCmp(
   const int OldImm = (int)CmpMI->getOperand(2).getImm();
   const int NewImm = std::abs(OldImm + Correction);
 
-  // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate) transitions by
+  // Handle cmn 1 -> cmp 0, because we prefer CMP 0 over cmn 0.
+  if (OldImm == 1 && (Negative && Correction == 1)) {
+    // If we are adjusting from -1 to 0, we need to change the opcode.
+    Opc = getComplementOpc(Opc);
+  }
+
+  // Handle +0 -> -1 and -0 -> +1 (CMN with 0 immediate.) transitions by
   // adjusting compare instruction opcode.
   if (OldImm == 0 && ((Negative && Correction == 1) ||
                       (!Negative && Correction == -1))) {



More information about the llvm-commits mailing list