[llvm] [RISCV][P-ext] Recognize (select (X >u ((1 << C) - 1), sext(X >s -1), trunc(X)) as usati (PR #190810)
Sam Elliott via llvm-commits
llvm-commits at lists.llvm.org
Tue Apr 7 11:47:34 PDT 2026
================
@@ -20280,11 +20280,77 @@ static SDValue performVSELECTCombine(SDNode *N, SelectionDAG &DAG) {
return DAG.getNode(ISD::ADD, DL, VT, A, NewB);
}
+// Fold (iC (select (src >u ((1 << C) - 1)), sext(src >s -1), trunc(src))) to
+// USATI. This pattern saturates a signed value to an unsigned N-bit range
+// [0, 2^N-1]:
+// - If src < 0: result = 0
+// (via the inner comparison src > -1 = false, sext to 0)
+// - If src > ((1 << C) - 1): result = all 1s
+// (via sext(true) = -1 = 0xFF...)
+// - Otherwise: result = src (via trunc(src))
+// The outer comparison is unsigned, so negative values appear as large
+// unsigned values and trigger the saturation to MaxVal path, where the
+// inner signed comparison then produces 0.
+// TODO: Support (select (src <=u ((1 << C) - 1)), trunc(src), sext(src >s -1)).
+static SDValue foldSelectToUSATI(SDNode *N, SelectionDAG &DAG,
+ const RISCVSubtarget &Subtarget) {
+ if (!Subtarget.hasStdExtP())
+ return SDValue();
+
+ EVT VT = N->getValueType(0);
+ MVT XLenVT = Subtarget.getXLenVT();
+
+ // Only support scalar integer types smaller than XLenVT
+ if (!VT.isScalarInteger() || VT.bitsGE(XLenVT))
+ return SDValue();
+
+ unsigned SatWidth = VT.getSizeInBits();
+ uint64_t MaxVal = (1ULL << SatWidth) - 1;
+
+ using namespace SDPatternMatch;
+
+ SDValue Src, InnerSetCC, FalseSrc;
+ if (!sd_match(N, m_Select(m_SetCC(m_Value(Src), m_SpecificInt(MaxVal),
+ m_SpecificCondCode(ISD::SETUGT)),
+ m_SExt(m_Value(InnerSetCC)),
+ m_Trunc(m_Value(FalseSrc)))))
+ return SDValue();
+
+ // Src can't be larger than XLenVT.
+ if (Src.getValueType().bitsGT(XLenVT))
+ return SDValue();
+
+ // Check inner setcc: src > -1 (signed comparison)
+ if (InnerSetCC.getValueType() != MVT::i1 ||
----------------
lenary wrote:
You can use `m_SpecificVT(MVT::i1, m_SetCC(...))` here I think.
There's also `m_VT` for pulling out value types as you destructure, e.g. for `Src`.
https://github.com/llvm/llvm-project/pull/190810
More information about the llvm-commits
mailing list