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

    <tr>
        <th>Summary</th>
        <td>
            [LoopIdiomRecognize] ShiftUntilBitTest optimization leads to incorrect behavior in case 0
        </td>
    </tr>

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

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

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

<pre>
    I am using the clang 17.0.6 compiler on Ubuntu 22.04.
I compile this code with the following attributes:  -march=rv64gc_zbb_zba_zbc --target=gcc-riscv64-linux-gnu -fuse-ld=/usr/bin/riscv64-linux-gnu-ld -O3 

```
#include "stdint.h"
#include <stdio.h>
#include <stdlib.h>

uint32_t count_leading(uint32_t n)
{
    int j = 10;
    uint32_t bitmask = 1 << j;
    uint32_t k = 0;
    while ((n & bitmask) == 0)
    {
        n <<= 1;
        printf("%d\n", k);
        k++;
    }
    return k;
}

int main(int argc, char *argv[])
{
    uint32_t a = strtoul(argv[1], NULL, 10);
    printf("%d\n", count_leading(a));
    return 0;
}
```

LoopIdiomRecognize pass optimizes the ShiftUntilBitTest idiom as follows https://godbolt.org/z/5jM1onchn , using intrinsic ctlz.
 If we compile the program without optimizations and pass 0 into it, the loop will be executed infinitely, but after O3 optimizations the loop will be executed only j+1 times.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVd2O4jgTfRpzU0pkHBLCBRfd8CG1NN-OtLtz3XIckxTt2MguwzRPv3JI9_QfOytFLkPVOTnlKldkCNhZrdesvGfldiYj9c6v987rk_aHaGeNa5_XDyAHiAFtB9RrUEbaDubLnOcVKDcc0WgPzsKPJlqKIETOFznjW8bvHl4CgHoMoFyr4YzUj0R7Z4w7J1pJ5LGJpAMr7gCyQXrVs2LrT9WiU4-Xpnm8NPLx0ijIMpK-08SKbadU5jGoU7XIDN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