[llvm] [AArch64] Fold CSEL of a CSEL with the same flags (PR #224992)

Henry Jiang via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 20 21:29:29 PDT 2026


https://github.com/mustartt created https://github.com/llvm/llvm-project/pull/224992

None

>From 307730d76b3e765dee661a8b1a6667716f26ca0f Mon Sep 17 00:00:00 2001
From: Henry Jiang <henry_jiang2 at apple.com>
Date: Sun, 20 Sep 2026 12:25:10 -0700
Subject: [PATCH 1/2] [AArch64] Subsitute inner CSEL

---
 .../Target/AArch64/AArch64ISelLowering.cpp    | 117 +++++++++
 .../CodeGen/AArch64/csel-fold-inner-csel.ll   | 223 ++++++++++++++++++
 2 files changed, 340 insertions(+)
 create mode 100644 llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll

diff --git a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
index 2a50c0c474ab95..0fb5af5727bf75 100644
--- a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
+++ b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
@@ -29493,7 +29493,121 @@ static SDValue foldCSELofLASTB(SDNode *Op, SelectionDAG &DAG) {
                      AnyPred, Default, LastB.getOperand(1));
 }
 
+// Whether an inner CSEL may be substituted into \p Arm. Both arms of a CSEL are
+// evaluated whatever the condition, so the expression has to be safe to
+// evaluate unconditionally: no immediate UB such as division by zero. Poison is
+// fine; UB is not.
+//
+// Restricting to a single result with exactly two operands is what lets the
+// caller rebuild the expression from one value type and an operand pair.
+// isBinOp alone is not enough for that: it also admits multi-result nodes such
+// as UADDO and SMUL_LOHI, and ADDE, which takes three operands.
+static bool isFoldableCSELArm(SDValue Arm, const SelectionDAG &DAG) {
+  if (Arm->getNumValues() != 1 || Arm.getNumOperands() != 2)
+    return false;
+  unsigned Opc = Arm.getOpcode();
+  return DAG.getTargetLoweringInfo().isBinOp(Opc) &&
+         DAG.isSafeToSpeculativelyExecute(Opc);
+}
+
 // Optimize CSEL instructions
+// Inside an arm of `CSEL(TV, FV, CC, Flags)`, an inner `CSEL(A, B, CCi, Flags)`
+// reading the very same flags value is known to be A or B, depending on how CCi
+// relates to CC. Substituting it there breaks the arm's dependency on the inner
+// CSEL.
+//
+//   t37 = CSEL a, b, EQ, F        ; the read
+//   t13 = add t37, 1
+//   t36 = CSEL t13, a, EQ, F      ; t37 is a here, so t13 is a+1
+//
+// After substitution the arm is `add a, 1`, which instruction selection folds
+// into CSINC a, a -- i.e. CINC -- so the duplicated add costs nothing.
+//
+// Requiring operand identity on the flags operand is what makes this safe: the
+// dependence is explicit in the DAG, so there is no need to scan for an
+// intervening redefinition of NZCV.
+static SDValue foldInnerCSELInArms(SDNode *N, SelectionDAG &DAG) {
+  SDValue Flags = N->getOperand(3);
+  auto CC = static_cast<AArch64CC::CondCode>(N->getConstantOperandVal(2));
+
+  // getInvertedCondCode only flips the low bit, so it maps AL to NV, but both
+  // of those are always true on AArch64. Treating them as complementary would
+  // pick the wrong operand, so bail out as getCSETCondCode does.
+  if (CC == AArch64CC::AL || CC == AArch64CC::NV)
+    return SDValue();
+
+  // Which arm of an inner CSEL on the same flags is live inside outer arm
+  // \p ArmNo: in arm 0 the outer condition holds, in arm 1 it does not.
+  auto innerArmIn = [&](SDValue Inner, unsigned ArmNo) -> SDValue {
+    if (Inner.getOpcode() != AArch64ISD::CSEL || Inner.getOperand(3) != Flags)
+      return SDValue();
+    auto ICC =
+        static_cast<AArch64CC::CondCode>(Inner->getConstantOperandVal(2));
+    bool TakesTrueArm;
+    if (ICC == CC)
+      TakesTrueArm = (ArmNo == 0);
+    else if (ICC == AArch64CC::getInvertedCondCode(CC))
+      TakesTrueArm = (ArmNo != 0);
+    else
+      return SDValue();
+    return Inner.getOperand(TakesTrueArm ? 0 : 1);
+  };
+
+  // The arm may be the inner CSEL directly, with no arithmetic in between. This
+  // creates no new nodes -- it only forwards one of the inner CSEL's operands
+  // -- so it needs no cost guard, and it lets the `CSEL x, x, cc -> x` rule
+  // above finish the job. CNEG/CSNEG are CSELs over a negation, so chained
+  // absolute values reach here and collapse.
+  for (unsigned ArmNo : {0, 1}) {
+    SDValue Repl = innerArmIn(N->getOperand(ArmNo), ArmNo);
+    if (!Repl || Repl == N->getOperand(ArmNo))
+      continue;
+    SmallVector<SDValue, 4> NewOps(N->op_values());
+    NewOps[ArmNo] = Repl;
+    return DAG.getNode(AArch64ISD::CSEL, SDLoc(N), N->getVTList(), NewOps);
+  }
+
+  for (unsigned ArmNo : {0, 1}) {
+    SDValue Arm = N->getOperand(ArmNo);
+    if (!isFoldableCSELArm(Arm, DAG))
+      continue;
+    unsigned Opc = Arm.getOpcode();
+    // A copy of the arm is free when instruction selection can absorb it back
+    // into the CSEL that consumes it, which it does for exactly the three
+    // shapes the CSINC/CSINV/CSNEG patterns match: inc is (add x, 1), not is
+    // (xor x, -1) and ineg is (sub 0, x). Any other constant -- add x, 1000 --
+    // stays a real instruction in every copy, so restrict duplication to a
+    // single use there.
+    bool FoldsIntoSelect =
+        (Opc == ISD::ADD && isOneConstant(Arm.getOperand(1))) ||
+        (Opc == ISD::XOR && isAllOnesConstant(Arm.getOperand(1))) ||
+        (Opc == ISD::SUB && isNullConstant(Arm.getOperand(0)));
+    if (!Arm.hasOneUse() && !FoldsIntoSelect)
+      continue;
+
+    for (unsigned OpNo : {0, 1}) {
+      SDValue Inner = Arm.getOperand(OpNo);
+      SDValue Repl = innerArmIn(Inner, ArmNo);
+      if (!Repl || Repl == Inner)
+        continue;
+      SmallVector<SDValue, 2> Ops(Arm->op_values());
+      Ops[OpNo] = Repl;
+      // The substituted value only equals the inner CSEL under the outer
+      // condition, but the rebuilt arm is still evaluated unconditionally, so a
+      // poison-generating flag justified for the original operand need not hold
+      // for the copy.
+      SDNodeFlags ArmFlags = Arm->getFlags();
+      ArmFlags &= SDNodeFlags(~unsigned(SDNodeFlags::PoisonGeneratingFlags));
+      SDValue NewArm =
+          DAG.getNode(Opc, SDLoc(Arm), Arm.getValueType(), Ops, ArmFlags);
+      SmallVector<SDValue, 4> NewOps(N->op_values());
+      NewOps[ArmNo] = NewArm;
+      return DAG.getNode(AArch64ISD::CSEL, SDLoc(N), N->getVTList(), NewOps);
+    }
+  }
+  return SDValue();
+}
+
 static SDValue performCSELCombine(SDNode *N,
                                   TargetLowering::DAGCombinerInfo &DCI,
                                   SelectionDAG &DAG) {
@@ -29501,6 +29615,9 @@ static SDValue performCSELCombine(SDNode *N,
   if (N->getOperand(0) == N->getOperand(1))
     return N->getOperand(0);
 
+  if (SDValue R = foldInnerCSELInArms(N, DAG))
+    return R;
+
   if (SDValue R = foldCSELOfCSEL(N, DAG))
     return R;
 
diff --git a/llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll b/llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll
new file mode 100644
index 00000000000000..8e1dd818c68697
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll
@@ -0,0 +1,223 @@
+; Inside an arm of a CSEL, an inner CSEL on the same flags folds to the
+; corresponding arm, which breaks the arm's dependency on that inner CSEL.
+; RUN: llc -mtriple=aarch64-linux-gnu < %s | FileCheck %s
+
+; The counter-pair idiom: both updates increment the *selected* value, so
+; without the fold each CSINC reads the CSEL and serialises on it. After the
+; fold each increment reads its own counter and becomes a CINC.
+define { i32, i32, i32 } @counter_pair(i8 %p, i32 %a, i32 %b) {
+; CHECK-LABEL: counter_pair:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    csel w0, w1, w2, eq
+; CHECK-NEXT:    cinc w1, w1, eq
+; CHECK-NEXT:    cinc w2, w2, ne
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %inc = add i32 %sel, 1
+  %an = select i1 %c, i32 %inc, i32 %a
+  %bn = select i1 %c, i32 %b, i32 %inc
+  %r0 = insertvalue { i32, i32, i32 } poison, i32 %sel, 0
+  %r1 = insertvalue { i32, i32, i32 } %r0, i32 %an, 1
+  %r2 = insertvalue { i32, i32, i32 } %r1, i32 %bn, 2
+  ret { i32, i32, i32 } %r2
+}
+
+; The inverted condition on the inner select selects the other arm.
+define i32 @inverted_inner(i8 %p, i32 %a, i32 %b) {
+; CHECK-LABEL: inverted_inner:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    cinc w0, w1, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %n = xor i1 %c, true
+  %sel = select i1 %n, i32 %b, i32 %a
+  %inc = add i32 %sel, 1
+  %r = select i1 %c, i32 %inc, i32 %a
+  ret i32 %r
+}
+
+; A select arm is evaluated unconditionally, so the substitution must not be
+; able to introduce a division by zero: here the inner select is what keeps the
+; divisor non-zero.
+define i32 @no_fold_sdiv(i8 %p, i32 %a, i32 %x) {
+; CHECK-LABEL: no_fold_sdiv:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    csinc w8, w1, wzr, eq
+; CHECK-NEXT:    sdiv w8, w2, w8
+; CHECK-NEXT:    csel w0, w8, w1, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 1
+  %v = sdiv i32 %x, %sel
+  %r = select i1 %c, i32 %v, i32 %a
+  ret i32 %r
+}
+
+; Different flags: the two selects test unrelated conditions, so nothing is
+; known about the inner one inside the outer arm.
+define i32 @no_fold_other_flags(i8 %p, i8 %q, i32 %a, i32 %b) {
+; CHECK-LABEL: no_fold_other_flags:
+; CHECK:         tst w1, #0xff
+; CHECK-NEXT:    csel w8, w2, w3, eq
+; CHECK-NEXT:    tst w0, #0xff
+; CHECK-NEXT:    csinc w0, w2, w8, ne
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %d = icmp eq i8 %q, 0
+  %sel = select i1 %d, i32 %a, i32 %b
+  %inc = add i32 %sel, 1
+  %r = select i1 %c, i32 %inc, i32 %a
+  ret i32 %r
+}
+
+; A multi-use arm that is not an inc/dec shape would have to be duplicated
+; without folding into the select, so it is left alone.
+define { i32, i32 } @no_fold_multiuse_mul(i8 %p, i32 %a, i32 %b, i32 %x) {
+; CHECK-LABEL: no_fold_multiuse_mul:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    csel w8, w1, w2, eq
+; CHECK-NEXT:    mul w8, w8, w3
+; CHECK-NEXT:    csel w0, w8, w1, eq
+; CHECK-NEXT:    csel w1, w2, w8, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = mul i32 %sel, %x
+  %an = select i1 %c, i32 %v, i32 %a
+  %bn = select i1 %c, i32 %b, i32 %v
+  %r0 = insertvalue { i32, i32 } poison, i32 %an, 0
+  %r1 = insertvalue { i32, i32 } %r0, i32 %bn, 1
+  ret { i32, i32 } %r1
+}
+
+; A multi-use arm whose constant is not the one CSINC folds stays a real
+; instruction in every copy, so duplicating it would be a straight cost.
+define { i32, i32 } @no_fold_multiuse_add_big_const(i8 %p, i32 %a, i32 %b) {
+; CHECK-LABEL: no_fold_multiuse_add_big_const:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    csel w8, w1, w2, eq
+; CHECK-NEXT:    add w8, w8, #1000
+; CHECK-NEXT:    csel w0, w8, w1, eq
+; CHECK-NEXT:    csel w1, w2, w8, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = add i32 %sel, 1000
+  %an = select i1 %c, i32 %v, i32 %a
+  %bn = select i1 %c, i32 %b, i32 %v
+  %r0 = insertvalue { i32, i32 } poison, i32 %an, 0
+  %r1 = insertvalue { i32, i32 } %r0, i32 %bn, 1
+  ret { i32, i32 } %r1
+}
+
+; The other two shapes selection absorbs for free: `xor x, -1` becomes CSINV and
+; `sub 0, x` becomes CSNEG, so a copy per use costs nothing and the inner CSEL
+; dies.
+define { i32, i32 } @multiuse_not(i8 %p, i32 %a, i32 %b) {
+; CHECK-LABEL: multiuse_not:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    cinv w0, w1, eq
+; CHECK-NEXT:    cinv w1, w2, ne
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = xor i32 %sel, -1
+  %an = select i1 %c, i32 %v, i32 %a
+  %bn = select i1 %c, i32 %b, i32 %v
+  %r0 = insertvalue { i32, i32 } poison, i32 %an, 0
+  %r1 = insertvalue { i32, i32 } %r0, i32 %bn, 1
+  ret { i32, i32 } %r1
+}
+
+define { i32, i32 } @multiuse_neg(i8 %p, i32 %a, i32 %b) {
+; CHECK-LABEL: multiuse_neg:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    cneg w0, w1, eq
+; CHECK-NEXT:    cneg w1, w2, ne
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = sub i32 0, %sel
+  %an = select i1 %c, i32 %v, i32 %a
+  %bn = select i1 %c, i32 %b, i32 %v
+  %r0 = insertvalue { i32, i32 } poison, i32 %an, 0
+  %r1 = insertvalue { i32, i32 } %r0, i32 %bn, 1
+  ret { i32, i32 } %r1
+}
+
+; An FP condition needing two condition codes lowers to nested FCSELs on the same
+; flags, but the second tests VS rather than EQ or NE, so nothing is known about
+; the inner one and the sequence is left alone.
+define double @no_fold_fp_two_cc(double %x, double %y, double %a, double %b) {
+; CHECK-LABEL: no_fold_fp_two_cc:
+; CHECK:         fcmp d0, d1
+; CHECK:         fcsel d0, d2, d3, eq
+; CHECK-NEXT:    fcsel d0, d2, d0, vs
+; CHECK-NEXT:    fadd d0, d0, d4
+  %c = fcmp ueq double %x, %y
+  %sel = select i1 %c, double %a, double %b
+  %v = fadd double %sel, 1.0
+  %r = select i1 %c, double %v, double %a
+  ret double %r
+}
+
+; --- the arm is the inner CSEL directly, with no arithmetic in between -------
+
+; Forwarding the inner arm creates no new nodes, so this needs no cost guard;
+; the `CSEL x, x, cc -> x` rule then removes the outer select entirely.
+define i32 @direct_inner_arm(i8 %p, i32 %a, i32 %b, i32 %d) {
+; CHECK-LABEL: direct_inner_arm:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    csel w0, w1, w3, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %r = select i1 %c, i32 %sel, i32 %d
+  ret i32 %r
+}
+
+; Same, reached through the inverted condition on the inner select.
+define i32 @direct_inner_arm_inverted(i8 %p, i32 %a, i32 %b, i32 %d) {
+; CHECK-LABEL: direct_inner_arm_inverted:
+; CHECK:         tst w0, #0xff
+; CHECK-NEXT:    csel w0, w1, w3, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %n = xor i1 %c, true
+  %sel = select i1 %n, i32 %b, i32 %a
+  %r = select i1 %c, i32 %sel, i32 %d
+  ret i32 %r
+}
+
+; CNEG and CSNEG are CSELs over a negation, so a chained absolute value lands in
+; the direct-arm case: abs(abs(x)) is x, and the whole sequence disappears.
+; Without the fold this stays two CNEGs; folding only the arithmetic arm would
+; leave a redundant `csel x0, x8, x0, pl` behind.
+define i64 @chained_abs(i64 %x) {
+; CHECK-LABEL: chained_abs:
+; CHECK-NOT:     cneg
+; CHECK:         ret
+  %n = sub i64 0, %x
+  %c = icmp slt i64 %x, 0
+  %a1 = select i1 %c, i64 %n, i64 %x
+  %n2 = sub i64 0, %a1
+  %a2 = select i1 %c, i64 %n2, i64 %a1
+  ret i64 %a2
+}
+
+; The inner abs has another use, so only the outer CNEG folds away.
+define i64 @chained_abs_live(i64 %x, ptr %p) {
+; CHECK-LABEL: chained_abs_live:
+; CHECK:         cmp x0, #0
+; CHECK-NEXT:    cneg x8, x0, mi
+; CHECK-NEXT:    str x8, [x1]
+; CHECK-NEXT:    ret
+  %n = sub i64 0, %x
+  %c = icmp slt i64 %x, 0
+  %a1 = select i1 %c, i64 %n, i64 %x
+  store i64 %a1, ptr %p
+  %n2 = sub i64 0, %a1
+  %a2 = select i1 %c, i64 %n2, i64 %a1
+  ret i64 %a2
+}

>From fc0f2ae9d428515f9a512474c11aef3e4cc6aec0 Mon Sep 17 00:00:00 2001
From: Henry Jiang <henry_jiang2 at apple.com>
Date: Sun, 20 Sep 2026 21:27:20 -0700
Subject: [PATCH 2/2] [AArch64] Fold CSEL of a CSEL with the same flags

---
 .../Target/AArch64/AArch64ISelLowering.cpp    | 151 +++++++-----------
 ...ner-csel.ll => csel-of-csel-same-flags.ll} | 137 ++++++++++------
 2 files changed, 148 insertions(+), 140 deletions(-)
 rename llvm/test/CodeGen/AArch64/{csel-fold-inner-csel.ll => csel-of-csel-same-flags.ll} (64%)

diff --git a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
index 0fb5af5727bf75..920c12f0a51c9d 100644
--- a/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
+++ b/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
@@ -29493,121 +29493,92 @@ static SDValue foldCSELofLASTB(SDNode *Op, SelectionDAG &DAG) {
                      AnyPred, Default, LastB.getOperand(1));
 }
 
-// Whether an inner CSEL may be substituted into \p Arm. Both arms of a CSEL are
-// evaluated whatever the condition, so the expression has to be safe to
-// evaluate unconditionally: no immediate UB such as division by zero. Poison is
-// fine; UB is not.
-//
-// Restricting to a single result with exactly two operands is what lets the
-// caller rebuild the expression from one value type and an operand pair.
-// isBinOp alone is not enough for that: it also admits multi-result nodes such
-// as UADDO and SMUL_LOHI, and ADDE, which takes three operands.
-static bool isFoldableCSELArm(SDValue Arm, const SelectionDAG &DAG) {
-  if (Arm->getNumValues() != 1 || Arm.getNumOperands() != 2)
-    return false;
-  unsigned Opc = Arm.getOpcode();
-  return DAG.getTargetLoweringInfo().isBinOp(Opc) &&
-         DAG.isSafeToSpeculativelyExecute(Opc);
-}
-
-// Optimize CSEL instructions
-// Inside an arm of `CSEL(TV, FV, CC, Flags)`, an inner `CSEL(A, B, CCi, Flags)`
-// reading the very same flags value is known to be A or B, depending on how CCi
-// relates to CC. Substituting it there breaks the arm's dependency on the inner
-// CSEL.
-//
-//   t37 = CSEL a, b, EQ, F        ; the read
-//   t13 = add t37, 1
-//   t36 = CSEL t13, a, EQ, F      ; t37 is a here, so t13 is a+1
-//
-// After substitution the arm is `add a, 1`, which instruction selection folds
-// into CSINC a, a -- i.e. CINC -- so the duplicated add costs nothing.
-//
-// Requiring operand identity on the flags operand is what makes this safe: the
-// dependence is explicit in the DAG, so there is no need to scan for an
-// intervening redefinition of NZCV.
-static SDValue foldInnerCSELInArms(SDNode *N, SelectionDAG &DAG) {
+// Optimize CSEL of a CSEL with the same flags:
+// (CSEL (CSEL a b  cc F) d cc F) => (CSEL a d cc F)
+// (CSEL (CSEL a b !cc F) d cc F) => (CSEL b d cc F)
+// (CSEL d (CSEL a b  cc F) cc F) => (CSEL d b cc F)
+// (CSEL d (CSEL a b !cc F) cc F) => (CSEL d a cc F)
+// (CSEL (OP x.. (CSEL a b cc F) y..) d cc F) => (CSEL (OP x.. a y..) d cc F)
+// CSINC/CSINV/CSNEG absorb (ADD x 1), (XOR x -1), (SUB 0 x), repsectively.
+static SDValue foldCSELOfCSELSameFlags(SDNode *N, SelectionDAG &DAG) {
   SDValue Flags = N->getOperand(3);
   auto CC = static_cast<AArch64CC::CondCode>(N->getConstantOperandVal(2));
-
-  // getInvertedCondCode only flips the low bit, so it maps AL to NV, but both
-  // of those are always true on AArch64. Treating them as complementary would
-  // pick the wrong operand, so bail out as getCSETCondCode does.
   if (CC == AArch64CC::AL || CC == AArch64CC::NV)
     return SDValue();
 
-  // Which arm of an inner CSEL on the same flags is live inside outer arm
-  // \p ArmNo: in arm 0 the outer condition holds, in arm 1 it does not.
-  auto innerArmIn = [&](SDValue Inner, unsigned ArmNo) -> SDValue {
+  auto GetSelectedInnerCSELValue = [](SDValue Inner, unsigned ValNo,
+                                      AArch64CC::CondCode CC,
+                                      SDValue Flags) -> SDValue {
     if (Inner.getOpcode() != AArch64ISD::CSEL || Inner.getOperand(3) != Flags)
       return SDValue();
     auto ICC =
         static_cast<AArch64CC::CondCode>(Inner->getConstantOperandVal(2));
-    bool TakesTrueArm;
+    bool TakesTVal;
     if (ICC == CC)
-      TakesTrueArm = (ArmNo == 0);
+      TakesTVal = (ValNo == 0);
     else if (ICC == AArch64CC::getInvertedCondCode(CC))
-      TakesTrueArm = (ArmNo != 0);
+      TakesTVal = (ValNo != 0);
     else
       return SDValue();
-    return Inner.getOperand(TakesTrueArm ? 0 : 1);
+    return Inner.getOperand(TakesTVal ? 0 : 1);
   };
 
-  // The arm may be the inner CSEL directly, with no arithmetic in between. This
-  // creates no new nodes -- it only forwards one of the inner CSEL's operands
-  // -- so it needs no cost guard, and it lets the `CSEL x, x, cc -> x` rule
-  // above finish the job. CNEG/CSNEG are CSELs over a negation, so chained
-  // absolute values reach here and collapse.
-  for (unsigned ArmNo : {0, 1}) {
-    SDValue Repl = innerArmIn(N->getOperand(ArmNo), ArmNo);
-    if (!Repl || Repl == N->getOperand(ArmNo))
-      continue;
-    SmallVector<SDValue, 4> NewOps(N->op_values());
-    NewOps[ArmNo] = Repl;
-    return DAG.getNode(AArch64ISD::CSEL, SDLoc(N), N->getVTList(), NewOps);
-  }
+  for (unsigned OperandNo : {0, 1}) {
+    SDValue Val = N->getOperand(OperandNo);
 
-  for (unsigned ArmNo : {0, 1}) {
-    SDValue Arm = N->getOperand(ArmNo);
-    if (!isFoldableCSELArm(Arm, DAG))
-      continue;
-    unsigned Opc = Arm.getOpcode();
-    // A copy of the arm is free when instruction selection can absorb it back
-    // into the CSEL that consumes it, which it does for exactly the three
-    // shapes the CSINC/CSINV/CSNEG patterns match: inc is (add x, 1), not is
-    // (xor x, -1) and ineg is (sub 0, x). Any other constant -- add x, 1000 --
-    // stays a real instruction in every copy, so restrict duplication to a
-    // single use there.
-    bool FoldsIntoSelect =
-        (Opc == ISD::ADD && isOneConstant(Arm.getOperand(1))) ||
-        (Opc == ISD::XOR && isAllOnesConstant(Arm.getOperand(1))) ||
-        (Opc == ISD::SUB && isNullConstant(Arm.getOperand(0)));
-    if (!Arm.hasOneUse() && !FoldsIntoSelect)
+    // The expression is the inner CSEL itself, so directly substitute.
+    if (SDValue SelectedVal =
+            GetSelectedInnerCSELValue(Val, OperandNo, CC, Flags)) {
+      SmallVector<SDValue, 4> NewOps(N->op_values());
+      NewOps[OperandNo] = SelectedVal;
+      return DAG.getNode(AArch64ISD::CSEL, SDLoc(N), N->getVTList(), NewOps);
+    }
+
+    unsigned Opc = Val.getOpcode();
+    if (Val->getNumValues() != 1 || Val.getNumOperands() == 0 ||
+        !DAG.isSafeToSpeculativelyExecuteNode(Val.getNode()) ||
+        any_of(Val->op_values(), [](SDValue Operand) {
+          EVT VT = Operand.getValueType();
+          return VT == MVT::Other || VT == MVT::Glue;
+        }))
       continue;
 
-    for (unsigned OpNo : {0, 1}) {
-      SDValue Inner = Arm.getOperand(OpNo);
-      SDValue Repl = innerArmIn(Inner, ArmNo);
-      if (!Repl || Repl == Inner)
+    // Only profitable to duplicate forms that can be folded back into the CSEL
+    // as CSINC/CSINV/CSNEG: (ADD x 1), (XOR x -1), and (SUB 0 x).
+    if (!Val.hasOneUse()) {
+      bool IsProfitableFormToFold =
+          Val.getNumOperands() == 2 &&
+          ((Opc == ISD::ADD && isOneConstant(Val.getOperand(1))) ||
+           (Opc == ISD::XOR && isAllOnesConstant(Val.getOperand(1))) ||
+           (Opc == ISD::SUB && isNullConstant(Val.getOperand(0))));
+      if (!IsProfitableFormToFold)
         continue;
-      SmallVector<SDValue, 2> Ops(Arm->op_values());
-      Ops[OpNo] = Repl;
-      // The substituted value only equals the inner CSEL under the outer
-      // condition, but the rebuilt arm is still evaluated unconditionally, so a
-      // poison-generating flag justified for the original operand need not hold
-      // for the copy.
-      SDNodeFlags ArmFlags = Arm->getFlags();
-      ArmFlags &= SDNodeFlags(~unsigned(SDNodeFlags::PoisonGeneratingFlags));
-      SDValue NewArm =
-          DAG.getNode(Opc, SDLoc(Arm), Arm.getValueType(), Ops, ArmFlags);
+    }
+
+    // The inner CSEL is an operand of the OP expression, so the expression has
+    // to be rebuilt around the substituted value.
+    for (unsigned InnerOperandNo = 0; InnerOperandNo != Val.getNumOperands();
+         ++InnerOperandNo) {
+      SDValue Inner = Val.getOperand(InnerOperandNo);
+      SDValue SelectedInner =
+          GetSelectedInnerCSELValue(Inner, OperandNo, CC, Flags);
+      if (!SelectedInner)
+        continue;
+      SmallVector<SDValue, 4> Ops(Val->op_values());
+      Ops[InnerOperandNo] = SelectedInner;
+      SDNodeFlags ValFlags =
+          Val->getFlags() & ~SDNodeFlags::PoisonGeneratingFlags;
+      SDValue NewVal =
+          DAG.getNode(Opc, SDLoc(Val), Val.getValueType(), Ops, ValFlags);
       SmallVector<SDValue, 4> NewOps(N->op_values());
-      NewOps[ArmNo] = NewArm;
+      NewOps[OperandNo] = NewVal;
       return DAG.getNode(AArch64ISD::CSEL, SDLoc(N), N->getVTList(), NewOps);
     }
   }
   return SDValue();
 }
 
+// Optimize CSEL instructions
 static SDValue performCSELCombine(SDNode *N,
                                   TargetLowering::DAGCombinerInfo &DCI,
                                   SelectionDAG &DAG) {
@@ -29615,7 +29586,7 @@ static SDValue performCSELCombine(SDNode *N,
   if (N->getOperand(0) == N->getOperand(1))
     return N->getOperand(0);
 
-  if (SDValue R = foldInnerCSELInArms(N, DAG))
+  if (SDValue R = foldCSELOfCSELSameFlags(N, DAG))
     return R;
 
   if (SDValue R = foldCSELOfCSEL(N, DAG))
diff --git a/llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll b/llvm/test/CodeGen/AArch64/csel-of-csel-same-flags.ll
similarity index 64%
rename from llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll
rename to llvm/test/CodeGen/AArch64/csel-of-csel-same-flags.ll
index 8e1dd818c68697..82f6cb3d63cd31 100644
--- a/llvm/test/CodeGen/AArch64/csel-fold-inner-csel.ll
+++ b/llvm/test/CodeGen/AArch64/csel-of-csel-same-flags.ll
@@ -1,13 +1,10 @@
-; Inside an arm of a CSEL, an inner CSEL on the same flags folds to the
-; corresponding arm, which breaks the arm's dependency on that inner CSEL.
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 6
 ; RUN: llc -mtriple=aarch64-linux-gnu < %s | FileCheck %s
 
-; The counter-pair idiom: both updates increment the *selected* value, so
-; without the fold each CSINC reads the CSEL and serialises on it. After the
-; fold each increment reads its own counter and becomes a CINC.
 define { i32, i32, i32 } @counter_pair(i8 %p, i32 %a, i32 %b) {
 ; CHECK-LABEL: counter_pair:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csel w0, w1, w2, eq
 ; CHECK-NEXT:    cinc w1, w1, eq
 ; CHECK-NEXT:    cinc w2, w2, ne
@@ -23,10 +20,10 @@ define { i32, i32, i32 } @counter_pair(i8 %p, i32 %a, i32 %b) {
   ret { i32, i32, i32 } %r2
 }
 
-; The inverted condition on the inner select selects the other arm.
 define i32 @inverted_inner(i8 %p, i32 %a, i32 %b) {
 ; CHECK-LABEL: inverted_inner:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    cinc w0, w1, eq
 ; CHECK-NEXT:    ret
   %c = icmp eq i8 %p, 0
@@ -37,12 +34,10 @@ define i32 @inverted_inner(i8 %p, i32 %a, i32 %b) {
   ret i32 %r
 }
 
-; A select arm is evaluated unconditionally, so the substitution must not be
-; able to introduce a division by zero: here the inner select is what keeps the
-; divisor non-zero.
 define i32 @no_fold_sdiv(i8 %p, i32 %a, i32 %x) {
 ; CHECK-LABEL: no_fold_sdiv:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csinc w8, w1, wzr, eq
 ; CHECK-NEXT:    sdiv w8, w2, w8
 ; CHECK-NEXT:    csel w0, w8, w1, eq
@@ -54,11 +49,10 @@ define i32 @no_fold_sdiv(i8 %p, i32 %a, i32 %x) {
   ret i32 %r
 }
 
-; Different flags: the two selects test unrelated conditions, so nothing is
-; known about the inner one inside the outer arm.
 define i32 @no_fold_other_flags(i8 %p, i8 %q, i32 %a, i32 %b) {
 ; CHECK-LABEL: no_fold_other_flags:
-; CHECK:         tst w1, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w1, #0xff
 ; CHECK-NEXT:    csel w8, w2, w3, eq
 ; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csinc w0, w2, w8, ne
@@ -71,11 +65,10 @@ define i32 @no_fold_other_flags(i8 %p, i8 %q, i32 %a, i32 %b) {
   ret i32 %r
 }
 
-; A multi-use arm that is not an inc/dec shape would have to be duplicated
-; without folding into the select, so it is left alone.
 define { i32, i32 } @no_fold_multiuse_mul(i8 %p, i32 %a, i32 %b, i32 %x) {
 ; CHECK-LABEL: no_fold_multiuse_mul:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csel w8, w1, w2, eq
 ; CHECK-NEXT:    mul w8, w8, w3
 ; CHECK-NEXT:    csel w0, w8, w1, eq
@@ -91,11 +84,30 @@ define { i32, i32 } @no_fold_multiuse_mul(i8 %p, i32 %a, i32 %b, i32 %x) {
   ret { i32, i32 } %r1
 }
 
-; A multi-use arm whose constant is not the one CSINC folds stays a real
-; instruction in every copy, so duplicating it would be a straight cost.
+define { i32, i32, i32 } @live_inner_mul(i8 %p, i32 %a, i32 %b, i32 %x) {
+; CHECK-LABEL: live_inner_mul:
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
+; CHECK-NEXT:    csel w0, w1, w2, eq
+; CHECK-NEXT:    mul w8, w0, w3
+; CHECK-NEXT:    csel w1, w8, w1, eq
+; CHECK-NEXT:    csel w2, w2, w8, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = mul i32 %sel, %x
+  %an = select i1 %c, i32 %v, i32 %a
+  %bn = select i1 %c, i32 %b, i32 %v
+  %r0 = insertvalue { i32, i32, i32 } poison, i32 %sel, 0
+  %r1 = insertvalue { i32, i32, i32 } %r0, i32 %an, 1
+  %r2 = insertvalue { i32, i32, i32 } %r1, i32 %bn, 2
+  ret { i32, i32, i32 } %r2
+}
+
 define { i32, i32 } @no_fold_multiuse_add_big_const(i8 %p, i32 %a, i32 %b) {
 ; CHECK-LABEL: no_fold_multiuse_add_big_const:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csel w8, w1, w2, eq
 ; CHECK-NEXT:    add w8, w8, #1000
 ; CHECK-NEXT:    csel w0, w8, w1, eq
@@ -111,12 +123,10 @@ define { i32, i32 } @no_fold_multiuse_add_big_const(i8 %p, i32 %a, i32 %b) {
   ret { i32, i32 } %r1
 }
 
-; The other two shapes selection absorbs for free: `xor x, -1` becomes CSINV and
-; `sub 0, x` becomes CSNEG, so a copy per use costs nothing and the inner CSEL
-; dies.
 define { i32, i32 } @multiuse_not(i8 %p, i32 %a, i32 %b) {
 ; CHECK-LABEL: multiuse_not:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    cinv w0, w1, eq
 ; CHECK-NEXT:    cinv w1, w2, ne
 ; CHECK-NEXT:    ret
@@ -132,7 +142,8 @@ define { i32, i32 } @multiuse_not(i8 %p, i32 %a, i32 %b) {
 
 define { i32, i32 } @multiuse_neg(i8 %p, i32 %a, i32 %b) {
 ; CHECK-LABEL: multiuse_neg:
-; CHECK:         tst w0, #0xff
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    cneg w0, w1, eq
 ; CHECK-NEXT:    cneg w1, w2, ne
 ; CHECK-NEXT:    ret
@@ -146,15 +157,17 @@ define { i32, i32 } @multiuse_neg(i8 %p, i32 %a, i32 %b) {
   ret { i32, i32 } %r1
 }
 
-; An FP condition needing two condition codes lowers to nested FCSELs on the same
-; flags, but the second tests VS rather than EQ or NE, so nothing is known about
-; the inner one and the sequence is left alone.
 define double @no_fold_fp_two_cc(double %x, double %y, double %a, double %b) {
 ; CHECK-LABEL: no_fold_fp_two_cc:
-; CHECK:         fcmp d0, d1
-; CHECK:         fcsel d0, d2, d3, eq
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    fcmp d0, d1
+; CHECK-NEXT:    fmov d4, #1.00000000
+; CHECK-NEXT:    fcsel d0, d2, d3, eq
 ; CHECK-NEXT:    fcsel d0, d2, d0, vs
 ; CHECK-NEXT:    fadd d0, d0, d4
+; CHECK-NEXT:    fcsel d1, d0, d2, eq
+; CHECK-NEXT:    fcsel d0, d0, d1, vs
+; CHECK-NEXT:    ret
   %c = fcmp ueq double %x, %y
   %sel = select i1 %c, double %a, double %b
   %v = fadd double %sel, 1.0
@@ -162,13 +175,10 @@ define double @no_fold_fp_two_cc(double %x, double %y, double %a, double %b) {
   ret double %r
 }
 
-; --- the arm is the inner CSEL directly, with no arithmetic in between -------
-
-; Forwarding the inner arm creates no new nodes, so this needs no cost guard;
-; the `CSEL x, x, cc -> x` rule then removes the outer select entirely.
-define i32 @direct_inner_arm(i8 %p, i32 %a, i32 %b, i32 %d) {
-; CHECK-LABEL: direct_inner_arm:
-; CHECK:         tst w0, #0xff
+define i32 @direct_inner_csel(i8 %p, i32 %a, i32 %b, i32 %d) {
+; CHECK-LABEL: direct_inner_csel:
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csel w0, w1, w3, eq
 ; CHECK-NEXT:    ret
   %c = icmp eq i8 %p, 0
@@ -177,10 +187,10 @@ define i32 @direct_inner_arm(i8 %p, i32 %a, i32 %b, i32 %d) {
   ret i32 %r
 }
 
-; Same, reached through the inverted condition on the inner select.
-define i32 @direct_inner_arm_inverted(i8 %p, i32 %a, i32 %b, i32 %d) {
-; CHECK-LABEL: direct_inner_arm_inverted:
-; CHECK:         tst w0, #0xff
+define i32 @direct_inner_csel_inverted(i8 %p, i32 %a, i32 %b, i32 %d) {
+; CHECK-LABEL: direct_inner_csel_inverted:
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    tst w0, #0xff
 ; CHECK-NEXT:    csel w0, w1, w3, eq
 ; CHECK-NEXT:    ret
   %c = icmp eq i8 %p, 0
@@ -190,14 +200,10 @@ define i32 @direct_inner_arm_inverted(i8 %p, i32 %a, i32 %b, i32 %d) {
   ret i32 %r
 }
 
-; CNEG and CSNEG are CSELs over a negation, so a chained absolute value lands in
-; the direct-arm case: abs(abs(x)) is x, and the whole sequence disappears.
-; Without the fold this stays two CNEGs; folding only the arithmetic arm would
-; leave a redundant `csel x0, x8, x0, pl` behind.
 define i64 @chained_abs(i64 %x) {
 ; CHECK-LABEL: chained_abs:
-; CHECK-NOT:     cneg
-; CHECK:         ret
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    ret
   %n = sub i64 0, %x
   %c = icmp slt i64 %x, 0
   %a1 = select i1 %c, i64 %n, i64 %x
@@ -206,10 +212,10 @@ define i64 @chained_abs(i64 %x) {
   ret i64 %a2
 }
 
-; The inner abs has another use, so only the outer CNEG folds away.
 define i64 @chained_abs_live(i64 %x, ptr %p) {
 ; CHECK-LABEL: chained_abs_live:
-; CHECK:         cmp x0, #0
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    cmp x0, #0
 ; CHECK-NEXT:    cneg x8, x0, mi
 ; CHECK-NEXT:    str x8, [x1]
 ; CHECK-NEXT:    ret
@@ -221,3 +227,34 @@ define i64 @chained_abs_live(i64 %x, ptr %p) {
   %a2 = select i1 %c, i64 %n2, i64 %a1
   ret i64 %a2
 }
+
+define i32 @unary_clz(i8 %p, i32 %a, i32 %b) {
+; CHECK-LABEL: unary_clz:
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    clz w8, w1
+; CHECK-NEXT:    tst w0, #0xff
+; CHECK-NEXT:    csel w0, w8, w1, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = call i32 @llvm.ctlz.i32(i32 %sel, i1 false)
+  %r = select i1 %c, i32 %v, i32 %a
+  ret i32 %r
+}
+
+define i32 @ternary_fshl(i8 %p, i32 %a, i32 %b, i32 %y) {
+; CHECK-LABEL: ternary_fshl:
+; CHECK:       // %bb.0:
+; CHECK-NEXT:    extr w8, w1, w3, #25
+; CHECK-NEXT:    tst w0, #0xff
+; CHECK-NEXT:    csel w0, w8, w1, eq
+; CHECK-NEXT:    ret
+  %c = icmp eq i8 %p, 0
+  %sel = select i1 %c, i32 %a, i32 %b
+  %v = call i32 @llvm.fshl.i32(i32 %sel, i32 %y, i32 7)
+  %r = select i1 %c, i32 %v, i32 %a
+  ret i32 %r
+}
+
+declare i32 @llvm.ctlz.i32(i32, i1)
+declare i32 @llvm.fshl.i32(i32, i32, i32)



More information about the llvm-commits mailing list