[llvm] [DAGCombiner] Fix the "subtraction if above a constant threshold" transform (PR #140042)

Björn Pettersson via llvm-commits llvm-commits at lists.llvm.org
Thu May 15 15:37:42 PDT 2025


================
@@ -1917,3 +1917,24 @@ define i32 @sub_if_uge_C_swapped_i32(i32 %x) {
   %cond = select i1 %cmp, i32 %x, i32 %sub
   ret i32 %cond
 }
+
+define noundef i8 @sub_if_uge_C_nsw_i8(i8 zeroext %x) {
+; RV32I-LABEL: sub_if_uge_C_nsw_i8:
+; RV32I:       # %bb.0:
+; RV32I-NEXT:    sltiu a1, a0, 13
+; RV32I-NEXT:    addi a1, a1, -1
+; RV32I-NEXT:    andi a1, a1, -13
+; RV32I-NEXT:    add a0, a0, a1
+; RV32I-NEXT:    ret
+;
+; RV32ZBB-LABEL: sub_if_uge_C_nsw_i8:
+; RV32ZBB:       # %bb.0:
+; RV32ZBB-NEXT:    addi a1, a0, -13
+; RV32ZBB-NEXT:    zext.b a1, a1
+; RV32ZBB-NEXT:    minu a0, a0, a1
+; RV32ZBB-NEXT:    ret
+  %cmp = icmp ugt i8 %x, 12
+  %sub = add nsw i8 %x, -13
+  %conv4 = select i1 %cmp, i8 %sub, i8 %x
+  ret i8 %conv4
+}
----------------
bjope wrote:

I think this might do the trick (at least for the ult variant):

```
define i7 @src(i7 %a) {
  %x = or i7 %a, 51
  %c = icmp ult i7 %x, -17
  %add = add nsw i7 %x, 17
  %s = select i1 %c, i7 %x, i7 %add
  ret i7 %s
}
```


https://github.com/llvm/llvm-project/pull/140042


More information about the llvm-commits mailing list