Skip to content

Commit a148b9e

Browse files
committed
[InstCombine] Fix infinite min/max canonicalization loop (PR44541)
While D72944 also fixes https://bugs.llvm.org/show_bug.cgi?id=44541, it does so in a more roundabout manner and there might be other loopholes to trigger the same issue. This is a more direct fix, that prevents the transform if the min/max is based on a non-canonical sub X, 0 instruction. Differential Revision: https://reviews.llvm.org/D73849
1 parent 5c159b9 commit a148b9e

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,12 @@ canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
10131013
Cmp.getPredicate() == CanonicalPred)
10141014
return nullptr;
10151015

1016+
// Bail out on unsimplified X-0 operand (due to some worklist management bug),
1017+
// as this may cause an infinite combine loop. Let the sub be folded first.
1018+
if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1019+
match(RHS, m_Sub(m_Value(), m_Zero())))
1020+
return nullptr;
1021+
10161022
// Create the canonical compare and plug it into the select.
10171023
Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
10181024

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
2+
; RUN: opt -S -instcombine -expensive-combines=0 -instcombine-infinite-loop-threshold=3 < %s | FileCheck %s
3+
4+
; This test used to cause an infinite combine loop.
5+
6+
define i16 @passthru(i16 returned %x) {
7+
; CHECK-LABEL: @passthru(
8+
; CHECK-NEXT: ret i16 [[X:%.*]]
9+
;
10+
ret i16 %x
11+
}
12+
13+
define i16 @test(i16 %arg) {
14+
; CHECK-LABEL: @test(
15+
; CHECK-NEXT: [[ZERO:%.*]] = call i16 @passthru(i16 0)
16+
; CHECK-NEXT: [[TMP1:%.*]] = icmp sgt i16 [[ARG:%.*]], 0
17+
; CHECK-NEXT: [[RET:%.*]] = select i1 [[TMP1]], i16 [[ARG]], i16 0
18+
; CHECK-NEXT: ret i16 [[RET]]
19+
;
20+
%zero = call i16 @passthru(i16 0)
21+
%sub = sub nuw nsw i16 %arg, %zero
22+
%cmp = icmp slt i16 %sub, 0
23+
%ret = select i1 %cmp, i16 0, i16 %sub
24+
ret i16 %ret
25+
}

0 commit comments

Comments
 (0)