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

    <tr>
        <th>Summary</th>
        <td>
            Missed optimization when `b - a` is known nonnegative
        </td>
    </tr>

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

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

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

<pre>
    This issue is consider a follow-up of #142283.

I just found out additional scenarios where `b - a` (both signed integer types) can be known nonnegative.

```c
#include <stdint.h>
uint64_t func1(int32_t a, int32_t b) {
    if (b < a)
        a = b;
    return (int32_t)(b - a);
}
uint64_t func2(int32_t a, int32_t b) {
    if (b < a)
        a = b;
    return (uint32_t)(b - a);
}
uint64_t func3(int32_t a, int32_t b) {
    return (b < a ? 0 : (int32_t)(b - a));
}
uint64_t func4(int32_t a, int32_t b) {
    return (b < a ? 0 : (uint32_t)(b - a));
}
```

All four functions are equivalent. `b - a` should be known nonnegative in all four cases. In x86-64, for example, it would make shorter code by zero-extending instead of sign-extending `b - a`.

The optimizer should also be able to recognize `b - b` and optimize to constant `0`, but that's not part of the issue I'm filing now.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJy0lMFu4zYQhp9mdBlYoChZsg46eJM1kENve19Q4tjiLk265DBO8vQFFTnZtN2iBbqGAYHSzPzfEP-MitGcHNEA20-wvS9U4tmH4fPTxfpAQfTF6PXz8GU2EU2MidBEnLyLRlNAhUdvrb9u0gX9EUHWVSPlri5B7EHsH_BbioxHn5xGnxiV1oaNd8pinMipYHzE60yBEFox4gYVtAJB7kbPMy5oGo1jOlFAfr5QBNnjpByOhN-dvzp03jk6KTaPtMpCK17_Uz7I2rjJJk0I9V1kbRyXM9SfQeyTcdw2XxmPyU0VyJ1xXMuvjArkHd4OY5aE7hOIPSKiOS58uVqO69fX-acQ6nscob7FBuIUHL5XzvE5efOaugRCd_9nFvlLWdJ_g6n_Jcy7wAqEUB9QINT7n9_AP-g2_4_uT7r9KPxmmVcH7a3Nrg0LRzZsRBUI6fdkHpUlx-UHv8bZJ6v_1pJoHKpbtUlFiiU-OHzatZu2yU0dfUB6UueLpaVHxutS7Ky-Uy4cmAJOXhOOz_hCwW_oiclp405oXGRSOo9eHpUfvvxAtw7Fl5nQX9iczQuFG7Gy0WdsNVpC9hho8idnXt7GccztqTy9a2qOyuPPynEOWu5M3uGYGHlWDLKL6DzjRQXOYDzTujgeQHZnPBqbAZ2_loUeat3XvSpoqLptJZpdU4liHjopx6rtVCP6aezFtu_btlJdVzXtdtI7VZhBCrkVreyqnRSVKI9imjRp6rfU044kNILOytjS2sdz6cOpWBiGqmmruiqsGsnGZedJ6ej6SghS5hUYhpy0GdMpQiOsiRzfy7BhS8NvJkZ6uxSVHZLXmPvgChP_aociBTvMzJcI9R7kAeThZHhOYzn5M8hD1lkfm0vw32hikIeFLoI8rPiPg_wjAAD__6IeuCk">