[llvm] [ARM] Select ssat for saturating clamps with a non-zero offset (PR #203854)
David Green via llvm-commits
llvm-commits at lists.llvm.org
Sat Jun 20 23:27:14 PDT 2026
================
@@ -18099,19 +18099,50 @@ static SDValue PerformMinMaxToSatCombine(SDValue Op, SelectionDAG &DAG,
APInt MinC = Min.getConstantOperandAPInt(1);
APInt MaxC = Max.getConstantOperandAPInt(1);
- if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX ||
- !(MinC + 1).isPowerOf2())
+ if (Min.getOpcode() != ISD::SMIN || Max.getOpcode() != ISD::SMAX)
return SDValue();
SDLoc DL(Op);
- if (MinC == ~MaxC)
- return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
- DAG.getConstant(MinC.countr_one(), DL, VT));
- if (MaxC == 0)
- return DAG.getNode(ARMISD::USAT, DL, VT, Input,
- DAG.getConstant(MinC.countr_one(), DL, VT));
- return SDValue();
+ // A clamp whose bounds are already a saturation range maps to a single
+ // SSAT / USAT.
+ if ((MinC + 1).isPowerOf2()) {
+ if (MinC == ~MaxC)
+ return DAG.getNode(ARMISD::SSAT, DL, VT, Input,
+ DAG.getConstant(MinC.countr_one(), DL, VT));
+ if (MaxC == 0)
+ return DAG.getNode(ARMISD::USAT, DL, VT, Input,
+ DAG.getConstant(MinC.countr_one(), DL, VT));
+ }
+
+ // For power-of-two clamp widths, convert the range to be zero-centered,
+ // apply SSAT, and convert the result back.
+ //
+ // Width = Hi - Lo + 1
+ // Center = Lo + Width / 2
+ // Result = ssat(X - Center) + Center
+ //
+ // The idea is to shift the input so that the clamp range is centered
+ // around zero, apply ssat, and then shift the result back.
+ //
+ // For example clamp(X, -118, 137) -> Width = 256,Center = 10, so it becomes
+ // ssat(X - 10, 8) + 10
+
+ APInt Width = MinC - MaxC + 1;
----------------
davemgreen wrote:
Because this happens as a combine it might need to handle degenerate inputs like when MaxC > MinC.
https://github.com/llvm/llvm-project/pull/203854
More information about the llvm-commits
mailing list