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

    <tr>
        <th>Summary</th>
        <td>
            Missed optimization: unsigned ckd_add(&unused, a, 1) can be folded to (a == UINT_MAX)
        </td>
    </tr>

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

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

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

<pre>
    Consider the following function, using C23's checked operations feature:

```c
#include <stdbool.h>
#include <stdckdint.h>

bool foo(unsigned int num) {
    unsigned int res;
    return ckd_add(&res, num, 1);
}
```

Clang generates the following IR[^1]:

```llvm
define dso_local zeroext i1 @foo(i32 noundef %num) local_unnamed_addr {
entry:
  tail call void @llvm.dbg.value(metadata i32 %num, metadata !17, metadata !DIExpression())
  %0 = zext i32 %num to i33
  %1 = tail call { i33, i1 } @llvm.sadd.with.overflow.i33(i33 %0, i33 1)
  %2 = extractvalue { i33, i1 } %1, 1
  %3 = extractvalue { i33, i1 } %1, 0
  %4 = icmp slt i33 %3, 0
  %5 = or i1 %2, %4
  tail call void @llvm.dbg.value(metadata i33 %3, metadata !18, metadata !DIExpression(DW_OP_LLVM_convert, 33, DW_ATE_unsigned, DW_OP_LLVM_convert, 32, DW_ATE_unsigned, DW_OP_stack_value))
  ret i1 %5
}

declare { i33, i1 } @llvm.sadd.with.overflow.i33(i33, i33) #1

declare void @llvm.dbg.value(metadata, metadata, metadata) #2
```

However, this IR is equivalent[^2]:

```llvm
define dso_local zeroext i1 @foo(i32 noundef %num) local_unnamed_addr {
entry:
  tail call void @llvm.dbg.value(metadata i32 %num, metadata !17, metadata !DIExpression())
  %cmp = icmp eq i32 %num, -1
  ret i1 %cmp
}

declare void @llvm.dbg.value(metadata, metadata, metadata) #1
```

Credit for finding this also goes to @redacted-moose.

[^1]: https://godbolt.org/z/cMWY6jP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