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

    <tr>
        <th>Summary</th>
        <td>
            Missing optimisation for select of masked operands
        </td>
    </tr>

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

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

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

<pre>
    Consider these two IR functions:

```
define i16 @bad(i32 %src) {
  %bit15mask = and i32 %src, 32768
  %isbit15zero = icmp eq i32 %bit15mask, 0
  %src15bits = and i32 %src, 32767
  %select = select i1 %isbit15zero, i32 %src15bits, i32 %src
  %result = trunc i32 %select to i16
  ret i16 %result
}

define i16 @good(i32 %src) {
 %src16bits = and i32 %src, 65535
  %bit15mask = and i32 %src, 32768
 %isbit15zero = icmp eq i32 %bit15mask, 0
  %src15bits = and i32 %src, 32767
  %select = select i1 %isbit15zero, i32 %src15bits, i32 %src16bits
 %result = trunc i32 %select to i16
  ret i16 %result
}
```
The difference is that in `@good` we add an extra redundant `and` before the `select` masking `%src` to 16 bits.

Running `opt -O3` on the above gives:
```
define i16 @bad(i32 %src) {
  %bit15mask = and i32 %src, 32768
  %isbit15zero = icmp eq i32 %bit15mask, 0
  %src15bits = and i32 %src, 32767
  %select = select i1 %isbit15zero, i32 %src15bits, i32 %src
 %result = trunc i32 %select to i16
  ret i16 %result
}

define i16 @good(i32 %src) {
  %result = trunc i32 %src to i16
  ret i16 %result
}
```

So by adding the redundant `and`  instcombine manages to collapse the select completely. But for @bad it fails to simplify the IR.

Note that removing the select would be legal due to the trunc only demanding 16 bits. So maybe this should be handled by InstCombineSimplifyDemanded.cpp somehow? Maybe the %src15bits operand in the select should be simplified (looking through the and) given that the predicate indicate that %src15bits is equal to %src?
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzsVl2L6zYQ_TXKy7BBlr-SB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