Skip to content

Commit 696bfe2

Browse files
[InstCombine] Fold smin(-a, x - a) + a to smin(x, 0)
This adds support for folding `smin(-a, x - a) + a` and its commuted variants to `smin(x, 0)`. This does give different in cases where `-a` or `x - a` overflow. Co-authored-by: Jami Rithvik <[email protected]>
1 parent 6c12623 commit 696bfe2

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2037,6 +2037,20 @@ Instruction *InstCombinerImpl::visitFAdd(BinaryOperator &I) {
20372037
return BinaryOperator::CreateFSubFMF(Z, XY, &I);
20382038
}
20392039

2040+
// smin(-a, x - a) + a --> smin(x, 0) [2 commuted variants]
2041+
// smin(x - a, -a) + a --> smin(x, 0) [2 commuted variants]
2042+
if (match(&I,
2043+
m_c_FAdd(m_SMin(m_FNeg(m_Value(A)), m_FSub(m_Value(X), m_Value(A))),
2044+
m_Value(A))) ||
2045+
match(&I,
2046+
m_c_FAdd(m_SMin(m_FSub(m_Value(X), m_Value(A)), m_FNeg(m_Value(A))),
2047+
m_Value(A)))) {
2048+
Constant *Zero = Constant::getNullValue(I.getType());
2049+
return replaceInstUsesWith(
2050+
I,
2051+
Builder.CreateIntrinsic(Intrinsic::smin, {I.getType()}, {X, Zero}, &I));
2052+
}
2053+
20402054
// Check for (fadd double (sitofp x), y), see if we can merge this into an
20412055
// integer add followed by a promotion.
20422056
if (Instruction *R = foldFBinOpOfIntCasts(I))

llvm/test/Transforms/InstCombine/add-min-max.ll

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,18 @@ entry:
8383
%res = add nuw nsw i32 %min, %max
8484
ret i32 %res
8585
}
86+
87+
88+
define i32 @sadd_min_neg(i32 %x, i32 %a) {
89+
; CHECK-LABEL: @sadd_min_neg(
90+
; CHECK-NEXT: entry:
91+
; CHECK-NEXT: [[RES:%.*]] = call i32 @llvm.smin.i32(i32 [[A:%.*]], i64 5)
92+
; CHECK-NEXT: ret i32 [[RES]]
93+
;
94+
entry:
95+
%neg_a = sub nsw i32 0, %a
96+
%x_minus_a = sub nsw i32 %x, %a
97+
%smin = call i32 @llvm.smin.i32(i32 %neg_a, i32 %x_minus_a)
98+
%res = add nsw i32 %smin, %a
99+
ret i32 %res
100+
}

0 commit comments

Comments
 (0)