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

    <tr>
        <th>Summary</th>
        <td>
            [InstCombine] Failure to fold bswap(and(x,bswap(y)) -> and(bswap(x),y)
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            llvm:instcombine
      </td>
    </tr>

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

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

<pre>
    https://alive2.llvm.org/ce/z/FbY8Cu

```ll
declare i16 @llvm.bswap.i16(i16)

define i16 @src(i16 %x, i16 %y) {
  %yy = tail call i16 @llvm.bswap.i16(i16 %y)
  %and = and i16 %x, %yy
  %res = tail call i16 @llvm.bswap.i16(i16 %and)
  ret i16 %res
}
define i16 @tgt(i16 %x, i16 %y) {
  %xx = tail call i16 @llvm.bswap.i16(i16 %x)
 %and = and i16 %xx, %y
  ret i16 %and
}
```

If the inner bswap has oneuse, then we can push the outer bswap through the bitlogic op and reduce the number of bswaps, this is probably true for bitreverse as well.

```ll
----------------------------------------
define i16 @src(i16 %x, i16 %y) {
%0:
  %yy = bswap i16 %y
  %and = and i16 %x, %yy
  %res = bswap i16 %and
  ret i16 %res
}
=>
define i16 @tgt(i16 %x, i16 %y) {
%0:
  %xx = bswap i16 %x
  %and = and i16 %xx, %y
  ret i16 %and
}
Transformation seems to be correct!
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJykVU1v6joQ_TXOZgRKJhDIIosWGql6u_fe5i5tZ0J85djIdlq4v_4qDlD6cftxi1CC7Jnjc2aOB-692hmiii1v2XKb8CF01lX__vOf6q1JhG2OVRfC3rP8hmHNsOZaPRDOtX7o59btGNaSGNa_GNa1-LHeDCzdsvTm9CzS6av1tNCQ1NwRqKwAtkgjivCPfD9XWcFwHZ_lNURDrTKXBO_kFAUMlweGGzj9PjIsga1upySIS0dg-RYCVxok1_q9Q88QV-ncNDF_fF8fGJGv4hz5r53DTXN1kqNwhnfkT8pX27fEh134tPjD4WukDk-U_qD9Iv4N5qOk58wvnb_u5X0LoSNQxpCDSAI67sEaGjyN8KEjA48EkhvYD76L4XYIl_DQOTvspnWhgrY7JcHuI1FHzSApbpmhF-TAtlOan7CVB-Vh76zgQh8huIGgtW4EcvRAzhNwD4-k9fxdE88--fmGgRku0_HKvXLzVIZLzt_b9RnQpX8f-JHlW5bffcObr3WdjPqMzuEDXV-z4v-OG99a1_OgrAFP1HsIFgSBtM6RDAyzF61OmipvyrzkCVVZsc7KLF0UmHRVK2QhF3wlpSCZNesyz3jbLhZtzgWuxCpRFaaYp4uszHLMUpy3eVu0ZZqKleQFLwq2SKnnSl9GaKK8H6gqEPMi0VyQ9nEcI44RLL9Rxgdpe6EMMcRxTLtq3JqJYefHO6188E9wQQUdB_q98WFzyltuoeZKD45G6a3VzVRyhus4j9ZjTc8rcRJiCTOW38G0fd6KcwI3Y0QyOP3iz2GnQjeIubQ9wzqyn16zvbM_Y6HrKNYzrKPe3wEAAP__CuXPQw">