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

    <tr>
        <th>Summary</th>
        <td>
            [mlir][arith] Erroneous canonicalization pattern for `arith.addi`
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            mlir:arith
      </td>
    </tr>

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

    <tr>
      <th>Reporter</th>
      <td>
          math-fehr
      </td>
    </tr>
</table>

<pre>
    When running `mlir-opt --canonicalize` (https://godbolt.org/z/6q9ehf7q7), the following program:
```
func.func @foo(%x : i2) -> i2 {
  %c-1 = arith.constant -1 : i2
  %c-2 = arith.constant -2 : i2
  %temp = arith.addi %x, %c-2 overflow<nsw> : i2
  %res = arith.addi %temp, %c-1 overflow<nsw> : i2
  func.return %res : i2
}
```
gets compiled into the following program:
```
func.func @foo(%arg0: i2) -> i2 {
  %c1_i2 = arith.constant 1 : i2
  %0 = arith.addi %arg0, %c1_i2 overflow<nsw> : i2
  return %0 : i2
}
```

Note that while I use `i2` for the example, there is equivalent issues for any integer sizes (besides 1). Reminder, the allowed values are `-2, -1, 0, 1` for `i2`. 
When the input is 1, the first program will return `-2`, while the second program will return `poison`.

I played a bit with the alive-like tool I am working on, and what I'm getting is that [this canonicalization pattern](https://github.com/llvm/llvm-project/blob/f7ef8dcbad9d5ac6cf2a8917d5ce03564fdfd0d8/mlir/lib/Dialect/Arith/IR/ArithCanonicalization.td#L43) is buggy whenever the two input adds have only the `nsw` flag, or if one has the `nsw` flag and the other has the `nsw` and `nuw` flag.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJyklc9u4zYQxp9mfBnYoCjr30EHJ14DAYoe9tJjQYkjiV2aVEjKTvL0BWk72abeAEUBQ4bEmU_D33xDCe_VaIhaKB6g2K_EEibr2qMI03qgya06K1_bPyYy6BZjlBkRSnbUyq3tHHC97oWxRvVCqzeCkiHwegph9pDv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