Skip to content

[MLIR] Add getter for the action handler of MLIR context - #197230

Merged
joker-eph merged 4 commits into
llvm:mainfrom
akigyosi:get-context-action-handler
May 13, 2026
Merged

joker-eph merged 4 commits into
llvm:mainfrom
akigyosi:get-context-action-handler

Conversation

@akigyosi

@akigyosi akigyosi commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Current implementation of MLIRContext's action handling, requires the user to hold the stored memory for any observer or breakpoint manager added to the execution context. Using a getter for the registered action handler, permits the user to store the observers and breakpoints into MLIRContext and modify their state later, by retrieving the action handler and invoking the functor's target. Mainly for attaching new observers later in the compilation pipeline, after the execution context got registered.

@akigyosi
akigyosi marked this pull request as draft May 12, 2026 16:00
@github-actions

Copy link
Copy Markdown

Hello @Nameduser(login="akigyosi") 👋

Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.

  • All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
  • The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.

Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.


Frequently asked questions

How do I add reviewers?

This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.

You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.

What if there are no comments?

If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.

Are any special GitHub settings required to contribute to LLVM?

We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.


If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.

Thank you,
The LLVM Community

@llvmorg-github-actions llvmorg-github-actions Bot added mlir:core MLIR Core Infrastructure mlir labels May 12, 2026
@llvmorg-github-actions

llvmorg-github-actions Bot commented May 12, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-mlir-core

Author: Kigyosi Alexandru (akigyosi)

Changes

Full diff: https://github.com/llvm/llvm-project/pull/197230.diff

4 Files Affected:

  • (modified) mlir/include/mlir/IR/MLIRContext.h (+4)
  • (modified) mlir/lib/IR/MLIRContext.cpp (+2)
  • (added) mlir/unittests/Debug/ActionHandlerTest.cpp (+111)
  • (modified) mlir/unittests/Debug/CMakeLists.txt (+1)
diff --git a/mlir/include/mlir/IR/MLIRContext.h b/mlir/include/mlir/IR/MLIRContext.h
index 9690029256474..3f4844f5d040d 100644
--- a/mlir/include/mlir/IR/MLIRContext.h
+++ b/mlir/include/mlir/IR/MLIRContext.h
@@ -267,6 +267,10 @@ class MLIRContext {
   /// context. A nullptr handler can be set to disable a previously set handler.
   void registerActionHandler(HandlerTy handler);
 
+  /// Return a copy of the currently registered action handler. Its target can
+  /// be used to gain access to the handler's state, if any.
+  HandlerTy getActionHandler();
+
   /// Return true if a valid ActionHandler is set.
   bool hasActionHandler();
 
diff --git a/mlir/lib/IR/MLIRContext.cpp b/mlir/lib/IR/MLIRContext.cpp
index 7b666d11a4a89..132f03b2aeaf1 100644
--- a/mlir/lib/IR/MLIRContext.cpp
+++ b/mlir/lib/IR/MLIRContext.cpp
@@ -380,6 +380,8 @@ void MLIRContext::registerActionHandler(HandlerTy handler) {
   getImpl().actionHandler = std::move(handler);
 }
 
+MLIRContext::HandlerTy MLIRContext::getActionHandler() { return getImpl().actionHandler; }
+
 /// Dispatch the provided action to the handler if any, or just execute it.
 void MLIRContext::executeActionInternal(function_ref<void()> actionFn,
                                         const tracing::Action &action) {
diff --git a/mlir/unittests/Debug/ActionHandlerTest.cpp b/mlir/unittests/Debug/ActionHandlerTest.cpp
new file mode 100644
index 0000000000000..87a828d8ee87f
--- /dev/null
+++ b/mlir/unittests/Debug/ActionHandlerTest.cpp
@@ -0,0 +1,111 @@
+//===- ActionHandlerTest.cpp - Debug Action Handler Tests -----------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/IR/Action.h"
+#include "mlir/Support/TypeID.h"
+#include "gmock/gmock.h"
+
+#include <gtest/gtest.h>
+
+#include <mlir/IR/MLIRContext.h>
+#include <mlir/IR/Action.h>
+#include <mlir/Support/LLVM.h>
+#include <mlir/Debug/ExecutionContext.h>
+#include <llvm/ADT/StringRef.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+using namespace mlir;
+using namespace mlir::tracing;
+
+namespace {
+
+struct DummyAction final : ActionImpl<DummyAction> {
+    MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(DummyAction)
+    static constexpr StringLiteral tag = "dummy-action";
+};
+
+} // namespace
+
+namespace {
+
+// State class — lives on the heap, shared across all copies of the handler
+struct HandlerState {
+    bool enabled{true};
+};
+
+/// Owner of a shared_ptr to the state
+/// Every copy of the functor points at the same HandlerState object.
+struct StatefulHandler {
+    std::shared_ptr<HandlerState> state;
+
+    void operator()(mlir::function_ref<void()> actionFn,
+                    const mlir::tracing::Action& /*action*/) const {
+        if (!state->enabled) {
+            // Skip execution entirely when disabled.
+            return;
+        }
+        actionFn();
+    }
+};
+
+TEST(ActionHandlerSharedState, SingleCopyEnabledState) {
+    mlir::MLIRContext ctx;
+
+    ctx.registerActionHandler(StatefulHandler{std::make_shared<HandlerState>()});
+
+    // Retrieve a copy of the handler.
+    auto handlerCopy = ctx.getActionHandler();
+    ASSERT_TRUE(static_cast<bool>(handlerCopy));
+
+    int executionCount = 0;
+    auto workFn = [&]() { ++executionCount; };
+
+    DummyAction action;
+
+    handlerCopy(workFn, action);
+
+    // Recover the shared_ptr from the handler copy via target<StatefulHandler>().
+    // target<T>() returns a non-null pointer only when the stored callable type
+    // matches T exactly — which is guaranteed here since we registered StatefulHandler.
+    auto* recovered = handlerCopy.target<StatefulHandler>();
+    ASSERT_NE(recovered, nullptr);
+
+    EXPECT_EQ(executionCount, 1);
+    EXPECT_TRUE(recovered->state->enabled == true);
+}
+
+TEST(ActionHandlerSharedState, MultipleCopiesDisabledState) {
+    mlir::MLIRContext ctx;
+
+    ctx.registerActionHandler(StatefulHandler{std::make_shared<HandlerState>()});
+
+    // Recover the shared_ptr and disable the state
+    auto handlerCopy = ctx.getActionHandler();
+    auto* recovered = handlerCopy.target<StatefulHandler>();
+    ASSERT_NE(recovered, nullptr);
+    recovered->state->enabled = false;
+
+    // A second independent copy also sees enabled==false
+    auto handlerCopy2 = ctx.getActionHandler();
+
+    int executionCount = 0;
+    auto workFn = [&]() { ++executionCount; };
+
+    DummyAction action;
+
+    handlerCopy2(workFn, action);
+
+    // workFn was skipped because the handler saw enabled==false
+    EXPECT_EQ(executionCount, 0);
+    EXPECT_TRUE(recovered->state->enabled == false);
+}
+
+} // namespace
diff --git a/mlir/unittests/Debug/CMakeLists.txt b/mlir/unittests/Debug/CMakeLists.txt
index d55282937956a..2ab00102f93b4 100644
--- a/mlir/unittests/Debug/CMakeLists.txt
+++ b/mlir/unittests/Debug/CMakeLists.txt
@@ -1,4 +1,5 @@
 add_mlir_unittest(MLIRDebugTests
+  ActionHandlerTest.cpp
   DebugCounterTest.cpp
   ExecutionContextTest.cpp
   FileLineColLocBreakpointManagerTest.cpp

Comment thread mlir/include/mlir/IR/MLIRContext.h Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not return by const ref?

Suggested change
const HandlerTy &getActionHandler();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. the user can copy the object if desired.

@andrey-golubev andrey-golubev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please do not forget to add description. I'd also update the title to something like "Add getter for an action handler of MLIR context".

Then we need an approval from Mehdi (at least?) to merge it.

Comment thread mlir/include/mlir/IR/MLIRContext.h Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. the user can copy the object if desired.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly I would skip adding an entire new C++ unit-test just for exposing a getter.

@andrey-golubev andrey-golubev May 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we were thinking that a test can be:

a) protection against deletion - someone decides to delete the getter, they'd need to delete the test, but they'd probably look at it first and see that downstream project uses the getter (can be stated in the test)
b) if handler's type changes (e.g. someone decides to switch from std::function to a class), these tests could be the first place to see how the new API would work (from set / get / implicit use perspectives)

but i don't have a strong preference overall personally

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand that this can be the general point of tests, but this still seems overkill: C++ unit-tests are the exception already, and a whole new TU to build for a getter is unprecedented.

For example for 1) I would not keep an API because there is a test, in general "downstream" isn't my main concern for upstream APIs and a test wouldn't guarantee anything.

@akigyosi akigyosi changed the title ActionHandler getter [MLIR] Add getter for the action handler of MLIR context May 13, 2026

@andrey-golubev andrey-golubev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add the PR description! :)

@github-actions

github-actions Bot commented May 13, 2026 •

Copy link
Copy Markdown

✅ With the latest revision this PR passed the C/C++ code formatter.

@joker-eph

Copy link
Copy Markdown
Contributor

The MR is still "Draft" by the way

@akigyosi
akigyosi marked this pull request as ready for review May 13, 2026 12:26
@akigyosi
akigyosi requested a review from joker-eph May 13, 2026 12:31
@joker-eph
joker-eph enabled auto-merge (squash) May 13, 2026 12:39
@joker-eph
joker-eph merged commit 918e93b into llvm:main May 13, 2026
8 checks passed
@github-actions

Copy link
Copy Markdown

@akigyosi Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@akigyosi
akigyosi deleted the get-context-action-handler branch May 13, 2026 13:30
lialan pushed a commit to lialan/llvm-project that referenced this pull request May 13, 2026
Current implementation of MLIRContext's action handling, requires the
user to hold the stored memory for any observer or breakpoint manager
added to the execution context. Using a getter for the registered action
handler, permits the user to store the observers and breakpoints into
MLIRContext and modify their state later, by retrieving the action
handler and invoking the functor's target. Mainly for attaching new
observers later in the compilation pipeline, after the execution context
got registered.
EuphoricThinking pushed a commit to EuphoricThinking/llvm-project that referenced this pull request May 14, 2026
Current implementation of MLIRContext's action handling, requires the
user to hold the stored memory for any observer or breakpoint manager
added to the execution context. Using a getter for the registered action
handler, permits the user to store the observers and breakpoints into
MLIRContext and modify their state later, by retrieving the action
handler and invoking the functor's target. Mainly for attaching new
observers later in the compilation pipeline, after the execution context
got registered.
andrey-golubev pushed a commit to intel-staging/npu-compiler-llvm that referenced this pull request May 18, 2026
Current implementation of MLIRContext's action handling, requires the
user to hold the stored memory for any observer or breakpoint manager
added to the execution context. Using a getter for the registered action
handler, permits the user to store the observers and breakpoints into
MLIRContext and modify their state later, by retrieving the action
handler and invoking the functor's target. Mainly for attaching new
observers later in the compilation pipeline, after the execution context
got registered.
pedroMVicente pushed a commit to pedroMVicente/llvm-project that referenced this pull request May 19, 2026
Current implementation of MLIRContext's action handling, requires the
user to hold the stored memory for any observer or breakpoint manager
added to the execution context. Using a getter for the registered action
handler, permits the user to store the observers and breakpoints into
MLIRContext and modify their state later, by retrieving the action
handler and invoking the functor's target. Mainly for attaching new
observers later in the compilation pipeline, after the execution context
got registered.
hockyy pushed a commit that referenced this pull request May 27, 2026
#197230 added a getter for the ActionHandler, but only returns a const
ref with a non-const accessor.
Instead provide both variants: a const accessor returning a const ref
and non-const one returning a mutable ref.
ggladilo pushed a commit to ggladilo/npu-compiler-llvm that referenced this pull request May 27, 2026
Current implementation of MLIRContext's action handling, requires the
user to hold the stored memory for any observer or breakpoint manager
added to the execution context. Using a getter for the registered action
handler, permits the user to store the observers and breakpoints into
MLIRContext and modify their state later, by retrieving the action
handler and invoking the functor's target. Mainly for attaching new
observers later in the compilation pipeline, after the execution context
got registered.
ggladilo added a commit to intel-staging/npu-compiler-llvm that referenced this pull request Jul 1, 2026
* [mlir][RFC] Allow to skip operands type specification in ASM form
* Add FlatSymbolRefAttr and ArrayAttr for memory space representation (llvm#44/llvm#45)
* [mlir] Relax ASM parser requirements about operands Type presence
* [mlir] Remove LIT tests affected by ASM simplification
* Add method getInlineBlockAndPoint for DialectInlinerInterface
* Initialize pass options using pipeline options
* Fix compilation issue with MSVC
* Port Ubunu-24 warning fixes to npu/release/18.x (llvm#45)
* Extend Quant dialect with Quantile Quantization type (llvm#53)
* Extending QuantileQuantizedType with quantileType mlir::Type member (llvm#60)
* Relax negative scales conditions in Quant Dialect (llvm#61)
* Adding missing check in QuantileQuantizedPerAxisType::verify (llvm#66)
* Adding new quantileType types to mlir test (llvm#85)
* Add Value back to SideEffectInterfaces
* EISW-130780: remove all wd flag to enable warnings when LLVM_ENABLE_WARNINGS is ON (llvm#99)
* EISW-176770 Fix argument parsing issue in mlir-src-sharder after command-line parser reset
* Enable quantization for FP4 type
* [MLIR] Make printing Value to a stream thread-safe (llvm#185762)
* [MLIR] Fix mlir-doc build failures by adding -dialect to add_mlir_doc calls
* [MLIR] Add getter for the action handler of MLIR context (llvm#197230)
* Silence deprecation warning for OpBuilder::create
* [MLIR] make One-Shot and SCF bufferization TensorLikeType-aware (llvm#189073)
* [NFC][mlir][bufferization] Remove getMemRefType() helper (llvm#199034)
* [mlir][bufferization] Drop TensorLikeType::getBufferType() (llvm#201350)

---------

Signed-off-by: Gladilov, Gleb <[email protected]>
Signed-off-by: Zhu, Shaojie <[email protected]>
Signed-off-by: Dmitrii Makarenko <[email protected]>
Co-authored-by: Vladislav Vinogradov <[email protected]>
Co-authored-by: Nikita Kudriavtsev <[email protected]>
Co-authored-by: Schondube, Jorn <[email protected]>
Co-authored-by: Daria Mityagina <[email protected]>
Co-authored-by: Luca Sarti <[email protected]>
Co-authored-by: Zoran Zomborat <[email protected]>
Co-authored-by: Ngun, Raymond <[email protected]>
Co-authored-by: Shaojie Zhu <[email protected]>
Co-authored-by: Surendar Rama Sitaraman <[email protected]>
Co-authored-by: Andruszkiewicz, Jacenty <[email protected]>
Co-authored-by: Mehdi Amini <[email protected]>
Co-authored-by: Kigyosi Alexandru <[email protected]>
Co-authored-by: Dmitrii Makarenko <[email protected]>
Co-authored-by: Andrei Golubev <[email protected]>
andrey-golubev pushed a commit to intel-staging/npu-compiler-llvm that referenced this pull request Jul 29, 2026
Current implementation of MLIRContext's action handling, requires the
user to hold the stored memory for any observer or breakpoint manager
added to the execution context. Using a getter for the registered action
handler, permits the user to store the observers and breakpoints into
MLIRContext and modify their state later, by retrieving the action
handler and invoking the functor's target. Mainly for attaching new
observers later in the compilation pipeline, after the execution context
got registered.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mlir:core MLIR Core Infrastructure mlir

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants