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

    <tr>
        <th>Summary</th>
        <td>
            [mips] mfhi/mflo hazard miscompilation
        </td>
    </tr>

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

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

    <tr>
      <th>Reporter</th>
      <td>
          cmccord-dev
      </td>
    </tr>
</table>

<pre>
    
```
int div(int a, int b, int c) {
 return a / b / c;
}
```
compiled with clang --target=mipsel-freestanding -mcpu=mips3 -O3 -fomit-frame-pointer
```
        div     $zero, $4, $5
        teq     $5, $zero, 7
        teq     $6, $zero, 7
        mflo    $1
        div     $zero, $1, $6
        jr      $ra
        mflo    $2
```

The earlier mips ISAs require a minimum of 2 instructions between a mflo/mfhi and the next mul/div instruction.  The output from clang V18.1.0 does not honor this.  It is also more than happy to put the mflo into the delay slot for the return, which can also cause bugs.

The reason for this hazard is the div/mul instructions start an asynchronous operation.  If an interrupt occurs the mfhi/mflo instruction might be flushed after the next div/mul has been started.  

GCC correctly handles this in both cases.

I'm more than happy to work on this if anyone is willing to give me a few pointers. Forbidding mfhi/mflo in branch delay slots seems like a reasonable start, but I'm not sure how to handle the other case. I could add a pass to insert nops similar to the mulmul fix.  I'm also not completely certain when the constraint goes away, but it's at least present in mips1-4.  
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJx8VU2P4zYM_TXKhbBhy_E4OeQwO4MUc-qhRe-yREfa1YdXoiab_fWFbM9XO7tAEMkgxcf3SEoiJXPxiCfWf2H9405k0iGepJMyRFUpfN6NQd1OrHlkzT27a7bf8mk8gTLPjB_KTjD-AGUzvmwk40dgw5fVGyJSjh4EMH6GcfmXrNusbHj8FEMGNxuLCq6GNEgr_AWqikS8ILHu0Zk5oa2miJhIeGWK2ck5b7YOqj87qKbgDFVTFA6rORhPGD9FY82xEGqOjO9_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