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

    <tr>
        <th>Summary</th>
        <td>
            Extend `bswap+shl+bswap` → `lshr` optimization to non-constant shift amounts
        </td>
    </tr>

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

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

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

<pre>
    For constant-distance shifts, it's great the the optimizer [knows](https://alive2.llvm.org/ce/z/LboYSb) that the bswaps just change the shift direction.

Could that be extended to runtime-distance shifts too, in situations where it's known that the three low-bits of the shift are `0`?

Alive2 proof that this is correct, at least for `<< (i * 8)`: https://alive2.llvm.org/ce/z/DksN6N

```llvm
define i64 @src(i64 noundef %0, i64 noundef %1) {
%start:
  %2 = bswap i64 noundef %0
  %3 = mul i64 noundef %1, 8
  %4 = shl i64 %2, %3
  %5 = bswap i64 %4
  ret i64 %5
}
=>
define i64 @tgt(i64 noundef %0, i64 noundef %1) {
%start:
  %2 = shl i64 noundef %1, 3
  %3 = lshr i64 noundef %0, %2
  ret i64 %3
}
Transformation seems to be correct!
```

But `opt` seems not to do that today:

```llvm
define i64 @src(i64 noundef %0, i64 noundef %1) unnamed_addr #0 {
  %2 = tail call i64 @llvm.bswap.i64(i64 %0)
  %3 = shl i64 %1, 3
  %4 = shl i64 %2, %3
  %5 = tail call i64 @llvm.bswap.i64(i64 %4)
  ret i64 %5
}

define i64 @tgt(i64 noundef %0, i64 noundef %1) unnamed_addr #1 {
  %2 = shl i64 %1, 3
  %3 = lshr i64 %0, %2
  ret i64 %3
}
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy1VU2ToyAQ_TV4oZJS0JgcPORjctqay-5lT1uoGJlRSAFOdubXb4MmcUxqaqZ2twpRm6a73-MBuSpfs73SuFDSWCbtrBTuXXBsalFZg8gWC4tIavBBc2axrbl_1NGKVrxxjVGyeZbqZFCyQ2RZW3s0iK4R2UNjjXjhZN40L-1c6QNYCg7dGzzfcvXze47ICsINcXNzYkeDnzpjcVEzeehT-UpwKTQvrFByjsIdCtd9v1VdU_YRco75b8tlycGgsO4kVMingGBIeVASG2E75iIafKq55megDo28VmVrzTlu1GmWC5ivqlFRDGahRRjCg-h-XNjaI8dHrfwEH0sYDK1Q2iFxRYC14QzQVrAEPsYWGgYaBXRrvAR6vHmNP83r7tk8Lh7HpbgIvjn33lTySkgAvIgxikOjC5cSfqTqgL8KkiehZ-m9LXLLhdLNEJckQK22ripvwM6HYER3_VJOp4cjN-rd2q65k2MLwK-esfc0de_pMjgPF2LklEyyunnnYc3t2ZYMlae74YPuEH24x4k92H_NyRnCFCy9oaUxtb4lr0dN7sCiE1g_NJMGNNV6eWPDeeuE77bIRX3RRBxjxWw66-QIexz6YbpU1oUo1aBmVbLXC8r_IrROStby8hcrS9gdhIZXmkesWiYaXLCmOSfxm8IrYQ6WIV-fZ3XD9EhWN2vxBeF9uoh4VMRHuvxrRU7Ji-6S9xH8iRS_KMGLFoIyo-WKrlhghW149uDPaCcvTw8iGygC-v4P5IYeCFou0Io4H5feGYfrptczyFAqOTvfWeezuAUKrAk63WTvT8uDsHWXzwvVwo_XZv-awen85DfDXhjTcbjt9klCSRrUUHPE4kVFFmVMExqlabRiC1rRNCnLKk6qoGE5b0wGtx8iRPIT9iHgG-7BQGQkJCRMwmWYRPCexzlbxWHMkmpZ0DSPYD15C6K5HOGBznxJeXcwTj9wa5nrIDNGHCTnPh3EZ52tlc5MoaxtizbwuTNf-x975TkA">