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

    <tr>
        <th>Summary</th>
        <td>
            [RISCV] Backend hangs during `RISCV DAG->DAG Pattern Instruction Selection `when having binary ops after `select`
        </td>
    </tr>

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

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

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

<pre>
    ## Description

The backend hangs during `RISCV DAG->DAG Pattern Instruction Selection` pass for the following input IR when targeting `riscv32` / `riscv64`. 

The constant operands for `select` must be -1 and 0 (order doesn't matter) to reproduce the problem.
The problem also occurs when `mul` is replaced by `add` / `sub`, but not `udiv` / `sdiv` / `urem` / `srem`.
The problem also occurs when `or` is replaced by `and`, but not `xor`.
The constant used in the 2 binary ops must be greater than or equal to 2048 and the constant operand for `mul` must be equal or slightly greater than the constant operand used for `or` (difference needs to be below 2048) to reproduce the problem.

## Cause

Through debugging, it is observed that [`DAGCombiner::visitSELECT`](https://github.com/llvm/llvm-project/blob/4309bb28ae77061d528b09dfe1c41335e92bc7a3/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp#L10542) and [`DAGCombiner::foldSelectOfBinops`](https://github.com/llvm/llvm-project/blob/4309bb28ae77061d528b09dfe1c41335e92bc7a3/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp#L24342) are called for infinite number of times.

## Minimal Reproduction

https://godbolt.org/z/5xE3c6xjb

### Code

```ll
define i32 @f(i1 %0, i32 %1, ptr %2) {
BB:
  %I = select i1 %0, i32 -1, i32 0
  %I1 = mul i32 %1, 2048
  %I2 = or i32 2048, %I
  store i32 %I1, ptr %2
  ret i32 %I2
}
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzVVU1v2zgQ_TXyZRBDoj5sH3yI7aQboItdpEXvp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