[llvm] [X86] Fix CCMP miscompile for flag-source-folded SETCC leaves (PR #217682)
Phoebe Wang via llvm-commits
llvm-commits at lists.llvm.org
Sat Aug 22 06:51:32 PDT 2026
================
@@ -25518,16 +25518,36 @@ static bool canEmitConjunctionForCCMP(SelectionDAG &DAG, SDValue Val,
return false;
unsigned Opcode = Val.getOpcode();
if (Opcode == ISD::SETCC) {
- EVT VT = Val.getOperand(0).getValueType();
+ SDValue LHS = Val.getOperand(0), RHS = Val.getOperand(1);
+ EVT VT = LHS.getValueType();
if (!VT.isInteger())
return false;
CanNegate = true;
MustBeFirst = false;
+ // A SETCC leaf whose flag source will be folded by EmitTest onto an
+ // OR/ADD/XOR node cannot appear in a non-root slot of a CCMP chain:
+ // CCMP is a subtract and CTEST is an AND, so neither can reproduce this
+ // leaf's SF/ZF. Force such a leaf to the chain root, where its flag
+ // source becomes a plain flag-setting instruction and its EFLAGS feed
+ // the next CCMP. This happens for icmp-vs-0 (and the icmp-vs-{-1,1}
+ // forms TranslateX86CC rewrites into icmp-vs-0) whose LHS is an
+ // OR/ADD/XOR the DAG will re-use for flags.
+ if (auto *C = dyn_cast<ConstantSDNode>(RHS)) {
+ ISD::CondCode CC = cast<CondCodeSDNode>(Val.getOperand(2))->get();
+ bool VsZero = C->isZero() || (CC == ISD::SETGT && C->isAllOnes()) ||
+ (CC == ISD::SETLT && C->isOne());
+ if (VsZero && LHS.hasOneUse()) {
+ unsigned LOpc = LHS.getOpcode();
+ MustBeFirst =
+ (LOpc == ISD::OR || LOpc == ISD::ADD || LOpc == ISD::XOR) &&
+ isProfitableToUseFlagOp(LHS);
+ }
+ }
// Designate this operation as a preferred first operation if the flags of a
// corresponding SUB node can be reused. The root comparison is emitted as a
// plain CMP, which can share EFLAGS with an existing SUB; a CCMP cannot.
- PreferFirst = DAG.doesNodeExist(ISD::SUB, DAG.getVTList(VT),
- {Val.getOperand(0), Val.getOperand(1)});
+ PreferFirst = MustBeFirst ||
+ DAG.doesNodeExist(ISD::SUB, DAG.getVTList(VT), {LHS, RHS});
----------------
phoebewang wrote:
I'm a bit worry about it. PreferFirst is week than MustBeFirst. Will the assertion triggered in some complex case?
https://github.com/llvm/llvm-project/pull/217682
More information about the llvm-commits
mailing list