[Mlir-commits] [mlir] [MLIR] Introduce a OpWithState class to act as a stream modifier for Operations (NFC) (PR #151547)

Mehdi Amini llvmlistbot at llvm.org
Thu Jul 31 08:58:07 PDT 2025


https://github.com/joker-eph created https://github.com/llvm/llvm-project/pull/151547

On the model of OpWithFlags, this modifier allows to stream an operation using a custom AsmPrinter.

>From d7e5e814a3382167857e3233bfff6946da71b3a7 Mon Sep 17 00:00:00 2001
From: Mehdi Amini <joker.eph at gmail.com>
Date: Thu, 31 Jul 2025 08:55:47 -0700
Subject: [PATCH] [MLIR] Introduce a OpWithState class to act as a stream
 modifier for Operations (NFC)

On the model of OpWithFlags, this modifier allows to stream an operation
using a custom AsmPrinter.
---
 mlir/include/mlir/IR/Operation.h        | 21 +++++++++++++++++++++
 mlir/lib/Tools/mlir-opt/MlirOptMain.cpp |  3 +--
 2 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/mlir/include/mlir/IR/Operation.h b/mlir/include/mlir/IR/Operation.h
index edc8ab489e12d..f4bbc8e6c984a 100644
--- a/mlir/include/mlir/IR/Operation.h
+++ b/mlir/include/mlir/IR/Operation.h
@@ -1125,6 +1125,27 @@ inline raw_ostream &operator<<(raw_ostream &os,
   return os;
 }
 
+/// A wrapper class that allows for printing an operation with a custom
+/// AsmState, useful to act as a "stream modifier" to customize printing an
+/// operation with a stream using the operator<< overload, e.g.:
+///   llvm::dbgs() << OpWithState(op, OpPrintingFlags().skipRegions());
+class OpWithState {
+public:
+  OpWithState(Operation *op, AsmState &state) : op(op), theState(state) {}
+  AsmState &state() { return theState; }
+  const AsmState &state() const { return theState; }
+
+private:
+  Operation *op;
+  AsmState &theState;
+  friend raw_ostream &operator<<(raw_ostream &os, OpWithState &op);
+};
+
+inline raw_ostream &operator<<(raw_ostream &os, OpWithState &opWithState) {
+  opWithState.op->print(os, opWithState.state());
+  return os;
+}
+
 } // namespace mlir
 
 namespace llvm {
diff --git a/mlir/lib/Tools/mlir-opt/MlirOptMain.cpp b/mlir/lib/Tools/mlir-opt/MlirOptMain.cpp
index bdcdaa407e616..de714d8b740af 100644
--- a/mlir/lib/Tools/mlir-opt/MlirOptMain.cpp
+++ b/mlir/lib/Tools/mlir-opt/MlirOptMain.cpp
@@ -501,8 +501,7 @@ performActions(raw_ostream &os,
            << "bytecode version while not emitting bytecode";
   AsmState asmState(op.get(), OpPrintingFlags(), /*locationMap=*/nullptr,
                     &fallbackResourceMap);
-  op.get()->print(os, asmState);
-  os << '\n';
+  os << OpWithState(op.get(), asmState) << '\n';
   return success();
 }
 



More information about the Mlir-commits mailing list