[llvm] [RISCV] Rewrite ADD to SUB to reuse a materialized negated constant (PR #221027)
Pengcheng Wang via llvm-commits
llvm-commits at lists.llvm.org
Wed Sep 9 00:58:10 PDT 2026
================
@@ -128,6 +128,75 @@ void RISCVDAGToDAGISel::PreprocessISelDAG() {
TrueMask, VLMAX);
break;
}
+ case ISD::ADD: {
+ // Turn (add X, C) into (sub X, -C) when a constant node holding -C
+ // already exists in the DAG, so both share one materialization. Do this
+ // before selection, while both are still ConstantSDNodes: by selection
+ // time -C may already have been selected into instructions.
+ //
+ // ADD is commutative, but getNode canonicalizes constants to the RHS, so
+ // the constant is always operand 1.
+ auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
+ if (!N1C)
+ break;
+ MVT VT = N->getSimpleValueType(0);
+ if (VT != Subtarget->getXLenVT())
+ break;
+ int64_t Imm = N1C->getSExtValue();
+ // Only worthwhile for wide constants: values that fit in 32 bits take at
+ // most two instructions to materialize, matching the threshold used by
+ // selectNegImm. Skip INT64_MIN too, whose negation is itself.
+ if (isInt<32>(Imm) || Imm == INT64_MIN)
+ break;
+ // A constant is anchored if it has a user other than an ADD, i.e. it is
+ // materialized regardless of this fold. N1C is the (unique) node for Imm,
+ // so the positive side needs no search.
+ auto IsAnchored = [](const SDNode *C) {
+ return any_of(C->users(), [](const SDNode *U) {
+ return U->getOpcode() != ISD::ADD;
+ });
+ };
+ // If Imm is materialized anyway, keep the ADD so it reuses Imm; an ADD is
+ // also more compressible than a SUB. This also lets us skip the search
+ // for -Imm below.
+ if (IsAnchored(N1C))
+ break;
+ // Find the (unique) constant node for -Imm, if any.
+ const SDNode *NegC = nullptr;
+ for (const SDNode &Node : CurDAG->allnodes()) {
+ auto *C = dyn_cast<ConstantSDNode>(&Node);
+ if (C && C->getSimpleValueType(0) == VT && C->getSExtValue() == -Imm) {
----------------
wangpc-pp wrote:
I just added an assertion.
https://github.com/llvm/llvm-project/pull/221027
More information about the llvm-commits
mailing list