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

    <tr>
        <th>Summary</th>
        <td>
            [GVN] Redundant loads in stencil loops
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            missed-optimization,
            llvm:GVN
      </td>
    </tr>

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

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

<pre>
    The small reproducers below are insipired by `CPU2000/172.mgrid` code from `resid` routine.  LLVM is not able to fully optimize redundant loads in loops accessing adjacent elements, e.g. `a(i-1)+a(i)+a(i+1)`.

Here is the most simple example for 1D array: https://godbolt.org/z/cacGdbhnr

Here, GVN is able to optimize only one load, but fails to optimize the second one.

A more complex example with a 2D array: https://godbolt.org/z/EboxdG5ae

Here, GVN is not able to optimize any of the loads.

The actual `172.mgrid` code uses 3D arrays.

I tried to allow `Add` operations with non-constant operands in `canPHITrans`, `PHITransAddr::translateSubExpr` and `PHITransAddr::insertTranslatedSubExpr`, but GVN bails out early during the memory dependencies computations in the 2D case.

I will appreciate any suggestions how to tackle this problem, and any hints!
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJyUVMFy2zgM_Rr6grGHoizZPujgJHXamW6ns5vNHSJhiS1FaggqifP1O5TtZLvNZU-SIIB4D3h8yGw7T9SI6kYo9fSKP3uMViglqrsFTqkPsblGF20wp-ahJ-ABnYNIYwxm0hQZWnLhGTASWM92tJEMtCcQtbz9_reSUgp1KDZqNXTRGlFL0MEQHGMYck4kPkdjmJL1tAL4-vXxD7AMPiTA1hGkAMfJuROEMdnBvhJEMpM36BO4gIbBenAhjAyoNTFb3wGaH6jJJyBHA_nEQt0CrbpV7opCbe2yEGon1M388cvrzfynlish90LuP1Mmx5B6giFwArbD6AjoBefnMUQo7gBjxJMo99CnNLIo90IdhDp0wbTBpVWInVCHV6EOGvW9aXsf34_P4O4fv-UuV8pvZIPP1D3NXHNiOyU4onX8S1pGx6SDNzn5An0PQ4gEOmSgL2-In23qAUH9D9Cf2vBi7iukD0H_e1dviNCfIBxnYPOaLpiyjFCnCV1exe_SmJgYygu0a9EXSNGSyeejy4ITtdybuSiMFDHZ4PnMywe_1MFzyvqYf_qzREQtNfrvn788RPQsapkJiFpeI3tjYp5AuU_502Giv6b208sYcxv05uNk65lieriWmPea67LykNp5YWFKQBjdCcwUs0xnTdEQ4gkMjeQNeW2J541N6ULL-jlP3YFGpreJPFvnAMcxkraYzvPmqeuIz2V9eM7zSqh_5s30lmGMoXU0ZGCZT67o7Xw5ioVpSrMrd7igpthUVaE2cr1Z9M2uNIU5brebomh3VO_KtVRlrUgXqOu22C1so6Sq5LYoVVls1GZVH9VWa70tC1pX5aYWa0kDWrdy7mnImlpY5omaoioruVk4bMnxxYgGy0xmeRHRPIDsSepWKJXLRbm_f_x2sanY5NCynToWa-ksJ37vkWxys73l_OoO_vzdNDjlcbuzeSym6Jr_XAOb-qld6TAIdZi7nx_LMYYfpJNQh5kJZ487k3lq1D8BAAD__52QwUs">