[Mlir-commits] [flang] [mlir] [mlir][CSE] Add pruneDeadOps to CSE pass (PR #193778)

lonely eagle llvmlistbot at llvm.org
Tue May 5 07:05:58 PDT 2026


================
@@ -294,15 +297,38 @@ LogicalResult CSEDriver::simplifyOperation(ScopedMapTy &knownValues,
   return failure();
 }
 
+void CSEDriver::pruneDeadOps(Operation *root, ScopedMapTy &knownValues) {
+  // We use `SetVector` to prevent already inserted ops from being added to the
+  // `worklist` repeatedly, avoiding secondary access to erased operations.
+  llvm::SetVector<Operation *> worklist;
+  worklist.insert(root);
+  while (!worklist.empty()) {
+    Operation *op = worklist.front();
+    worklist.erase(worklist.begin());
+    if (!isOpTriviallyDead(op))
+      continue;
+
+    for (Value arg : op->getOperands())
+      if (Operation *argOp = arg.getDefiningOp())
+        worklist.insert(argOp);
+
+    // Since the root op is not inserted into the ScopedHashMap, do not undo
+    // its previous insertion.
----------------
linuxlonelyeagle wrote:

Here is the conclusion: Any operation that becomes dead only after its root op is deleted must already reside in the ScopedHashTableScope.

First, let’s consider the insertion logic for ScopedHashTableScope:

If an op is already dead, it is deleted immediately and never inserted into the scope.

If an op becomes dead after successful CSE (i.e., it was replaced), it is pushed into opsToErase and is not inserted into the scope.

If CSE fails, the op is inserted into the scope as an 'existing op'. It may only become dead later if its users are eventually deleted.

Now, let's consider the deletion process:
The root op itself is a direct dead op and thus cannot be in the ScopedHashTableScope. However, any subsequent dead ops found via its operands must be in the scope. This is because they previously had users, which qualifies them as 'existing ops' in the scope. In Case 2, since the 'existing op' replaced the current op, the original op would have no users

https://github.com/llvm/llvm-project/pull/193778


More information about the Mlir-commits mailing list