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

    <tr>
        <th>Summary</th>
        <td>
            Loop Interchange bug due to loop guards not being interchanged
        </td>
    </tr>

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

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

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

<pre>
    Right now loop guards are not interchanged which leads to incorrect control flow after the interchange.
For example, consider the following code before the interchange.
```
if(n > 0)
  for(int i=0; i != n; i++)
    if(m > 0)
      for(int j=0; j != m; j++)
         A[j][i] += B[j][i] + 1;
```
IR: [before.ll](https://github.com/llvm/llvm-project/files/9717558/before.ll.txt)

After interchange:
```
if(n > 0)
  for(int j=0; j != m; j++)
    for(int i=0; i != n; i++) {
      if(m > 0)
         A[j][i] += B[j][i] + 1;
      else break;
    }
```
IR: [after.ll.txt](https://github.com/llvm/llvm-project/files/9717613/after.ll.txt)

If m is -1 at run-time then the original code only executes the outer for-i loop whereas the resulting code is an infinite loop (since `j != m` always evaluates to false).

Possible solutions under consideration:
- See if running simple loop unswitch or LICM prior to loop interchange fixes the issue. I tried this and it doesn't seem to help; loop unswitch does nothing and LICM hoists the computation of the condition m > 0 out of the for-i loop but the branch remains in place (inside the for-i loop). Still, this might be able to be tweaked to work, I'm not sure.
- View non-user generated loop guards (checked via `isGuarded()` for example) as part of anatomy of a loop.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJylVV9v2zgM_zTKCxHDdhInfvBDs94OAXbAYQPuXbZpW50sBZLctN_-SDnJ3FsxoLvAiCRS_Psjqdq2r9VX1Q8BjL2AtvYM_SRd60E6JFoAZQK6ZpCmxxYug2oG0CjpQrDEa6xz2ARorAnOaug0qZEdiUAYcCmciPRRpA-frQN8keNZo8g_sZxX7fV2ZzWJK9MTuUWosbPkxPt6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