Skip to content

[RISCV] Prefer (select (x < 0), y, z) -> x >> (XLEN - 1) & (y - z) + z even with Zicond. #125772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions llvm/lib/Target/RISCV/RISCVISelLowering.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8430,6 +8430,33 @@ SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV)) {
const APInt &TrueVal = TrueV->getAsAPIntVal();
const APInt &FalseVal = FalseV->getAsAPIntVal();

// Prefer these over Zicond to avoid materializing an immediate:
// (select (x < 0), y, z) -> x >> (XLEN - 1) & (y - z) + z
// (select (x > -1), z, y) -> x >> (XLEN - 1) & (y - z) + z
if (CondV.getOpcode() == ISD::SETCC &&
CondV.getOperand(0).getValueType() == VT && CondV.hasOneUse()) {
ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
if ((CCVal == ISD::SETLT && isNullConstant(CondV.getOperand(1))) ||
(CCVal == ISD::SETGT && isAllOnesConstant(CondV.getOperand(1)))) {
int64_t TrueImm = TrueVal.getSExtValue();
int64_t FalseImm = FalseVal.getSExtValue();
if (CCVal == ISD::SETGT)
std::swap(TrueImm, FalseImm);
if (isInt<12>(TrueImm) && isInt<12>(FalseImm) &&
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need isInt<12>(FalseImm)?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's needed to make guarantee the ISD::ADD becomes an ADDI. The one we probably don't need is isInt<12>(TrueImm). It currently protects the TrueImm - FalseImm from signed overflow, but we could change it to an unsigned subtract.

I copied the checks from how it was written in the RISCVISD::SELECT_CC combine.

isInt<12>(TrueImm - FalseImm)) {
SDValue SRA =
DAG.getNode(ISD::SRA, DL, VT, CondV.getOperand(0),
DAG.getConstant(Subtarget.getXLen() - 1, DL, VT));
SDValue AND =
DAG.getNode(ISD::AND, DL, VT, SRA,
DAG.getSignedConstant(TrueImm - FalseImm, DL, VT));
return DAG.getNode(ISD::ADD, DL, VT, AND,
DAG.getSignedConstant(FalseImm, DL, VT));
}
}
}

const int TrueValCost = RISCVMatInt::getIntMatCost(
TrueVal, Subtarget.getXLen(), Subtarget, /*CompressionCost=*/true);
const int FalseValCost = RISCVMatInt::getIntMatCost(
Expand Down