Skip to content

Commit

Permalink
[DAG] visitSUBSAT - fold subsat(x,y) -> sub(x,y) if it never overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
RKSimon committed May 6, 2023
1 parent 05a57fd commit 8f82d8e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
8 changes: 7 additions & 1 deletion llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4042,9 +4042,11 @@ SDValue DAGCombiner::visitSUB(SDNode *N) {
}

SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
unsigned Opcode = N->getOpcode();
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
bool IsSigned = Opcode == ISD::SSUBSAT;
SDLoc DL(N);

// fold (sub_sat x, undef) -> 0
Expand All @@ -4056,7 +4058,7 @@ SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
return DAG.getConstant(0, DL, VT);

// fold (sub_sat c1, c2) -> c3
if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
return C;

// fold vector ops
Expand All @@ -4073,6 +4075,10 @@ SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
if (isNullConstant(N1))
return N0;

// If it cannot overflow, transform into an sub.
if (DAG.computeOverflowForSub(IsSigned, N0, N1) == SelectionDAG::OFK_Never)
return DAG.getNode(ISD::SUB, DL, VT, N0, N1);

return SDValue();
}

Expand Down
14 changes: 5 additions & 9 deletions llvm/test/CodeGen/X86/combine-sub-ssat.ll
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,10 @@ define <8 x i16> @combine_self_v8i16(<8 x i16> %a0) {
define i32 @combine_no_overflow_i32(i32 %a0, i32 %a1) {
; CHECK-LABEL: combine_no_overflow_i32:
; CHECK: # %bb.0:
; CHECK-NEXT: sarl $16, %edi
; CHECK-NEXT: movl %edi, %eax
; CHECK-NEXT: sarl $16, %eax
; CHECK-NEXT: shrl $16, %esi
; CHECK-NEXT: xorl %eax, %eax
; CHECK-NEXT: cmpl %esi, %edi
; CHECK-NEXT: setns %al
; CHECK-NEXT: addl $2147483647, %eax # imm = 0x7FFFFFFF
; CHECK-NEXT: subl %esi, %edi
; CHECK-NEXT: cmovnol %edi, %eax
; CHECK-NEXT: subl %esi, %eax
; CHECK-NEXT: retq
%1 = ashr i32 %a0, 16
%2 = lshr i32 %a1, 16
Expand All @@ -139,14 +135,14 @@ define <8 x i16> @combine_no_overflow_v8i16(<8 x i16> %a0, <8 x i16> %a1) {
; SSE: # %bb.0:
; SSE-NEXT: psraw $10, %xmm0
; SSE-NEXT: psrlw $10, %xmm1
; SSE-NEXT: psubsw %xmm1, %xmm0
; SSE-NEXT: psubw %xmm1, %xmm0
; SSE-NEXT: retq
;
; AVX-LABEL: combine_no_overflow_v8i16:
; AVX: # %bb.0:
; AVX-NEXT: vpsraw $10, %xmm0, %xmm0
; AVX-NEXT: vpsrlw $10, %xmm1, %xmm1
; AVX-NEXT: vpsubsw %xmm1, %xmm0, %xmm0
; AVX-NEXT: vpsubw %xmm1, %xmm0, %xmm0
; AVX-NEXT: retq
%1 = ashr <8 x i16> %a0, <i16 10, i16 10, i16 10, i16 10, i16 10, i16 10, i16 10, i16 10>
%2 = lshr <8 x i16> %a1, <i16 10, i16 10, i16 10, i16 10, i16 10, i16 10, i16 10, i16 10>
Expand Down

0 comments on commit 8f82d8e

Please sign in to comment.