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

    <tr>
        <th>Summary</th>
        <td>
            [mlir][python] Running passes can invalidate objects and lead to crashes
        </td>
    </tr>

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

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

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

<pre>
    If C++ code deletes an operation the `PyOperation::valid` flag isn't updated, which can lead to crashes:
```py
from mlir import ir
from mlir.dialects import builtin
from mlir.passmanager import PassManager

with ir.Context():
  module = builtin.ModuleOp.parse("""
    module {
      arith.constant 10
 }
  """)
  const_op = module.body.operations[0]
 print(const_op)
 PassManager.parse('builtin.module(canonicalize)').run(module)
 print(const_op)
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyEk99uqzgQxp9muBkVGRP-XXCRNIq0F1WrfYHVgA1419jINu3mPP0RTkiq3hzJAunz_L7x2DPkvRqNlC0UJyjOCa1hsq51_9GVVJiSzopr-9eAr8BPwE_YWyFRSC2D9EgG7SIdBWUNhkkilOzj-r5LkB8hP36SVgJKhoOmEZU3wKuA6yIoSAH8Fb8m1U_Yk0EtSWCw2Dvyk_Qbz87AjlCy21quN2FwdsZZK4dqXqwLqNyPjVQo0rIPfo_oVqWDMj_DFvJ-JkOjfHh9kPdvN-mePn6_VJhQufTVmiD_D8Br4M3jiIizFauWCPl5z5W-Rel9SRdyXkaC39cdemLV6akhklNhSntrfCATMGP3TajOe9jTize7FoF_7BJPcXNOtxdMH8_koTgxKHaXxSmzlbKDT69vt_Dt-NVe2s18I8lYo3rS6pfcaF4Bb1K3GuD1HtT8KdvjgRPR5qLJG0pkm5V1U2a8rMtkarOsqLtMDFVfU173dT7UB1lxQWXHOJWHRLWc8ZxVWZWVRcbLdBgoqwTjrOoOlPEGDkzOpHSq9eecWjcmyvtVtmXeZGWiqZPaxyngfOsMyI_LNUzWbDdcnBPXbtxLt44eDkwrH_zTKaig4whFsjhDcbrDxRn_Xo1RZsSt1aSPja5MnAoKEm33b2xTMuJn_yer0-0UwhIngV-AX0YVprVLezsDv2zp77-XxdnNB_glVuWBX2JhvwMAAP__lZs2WQ">