<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/82177>82177</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [InstCombine] Fold `usub_sat((sub nuw C1, A), C2)` to `usub_sat(C1 - C2, A)` or `0`
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          XChy
      </td>
    </tr>
</table>

<pre>
    Alive2 proof: https://alive2.llvm.org/ce/z/Bre2we

### Motivating example 

```llvm
define i32 @src(i32 %a){
entry:
  %add = sub nuw i32 64, %a
  %cond = call i32 @llvm.usub.sat.i32(i32 %add, i32 14)
  ret i32 %cond
}
```

can be folded to:

```llvm
define i32 @tgt(i32 %a){
entry:
  %cond = call i32 @llvm.usub.sat.i32(i32 50, i32 %a)
  ret i32 %cond
}
```
When `C2 u< C1`, we get `usub_sat(C1 - C2, A)`, otherwise we get `0`. See also the examples in alive2 proof.

### Real-world motivation

This snippet of IR is derived from [jemalloc/src/psset.c@psset_maybe_remove_purge_list](https://github.com/jemalloc/jemalloc/blob/1aba4f41a3fef53fa913e655444dbba53a0c82df/src/psset.c#L226) (after O3 pipeline).
The example above is a reduced version. If you're interested in the original suboptimal IR and optimal IR, contact me to get it, please. Actually such pattern is found frequently in the IRs in jemalloc project.

**Let me know if you can confirm that it's an optimization opportunity, thanks.**
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVd2O4zYPfRrlhhjDpv8vcpFxYGCA_fAB2wLt3UC26Fi7suRKctLs0xeyk5nstGi3BYTEMimSRzyH5s7Jkybas_yZ5ccdX_xo7P7XZrzuOiOu-4OSZ0KYrTEDSw8wej87lh4Ytgxbvlojpc5TZOyJYdsTw_Ybw_bZEl6IxUcWH26_mG4L_me8PHMv9Qnodz7NiuA7xyLeVoi7vRI0SE0gUw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