Skip to content

Commit b5d0caa

Browse files
PragmaTwiceclingfei
authored andcommitted
[MLIR][Python] Make the TypeID allocator globally defined in PassManager.add (llvm#162594)
Previously, each time we called `PassManager.add(python_pass_callable)`, a new `TypeID` allocator was created and never released afterward. This approach could potentially lead to some issues. In this PR, we introduce a global `TypeIDAllocator` that is shared across all `add` calls to allocate IDs.
1 parent 2b6290c commit b5d0caa

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

mlir/lib/Bindings/Python/Globals.h

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
#include "NanobindUtils.h"
1919
#include "mlir-c/IR.h"
20+
#include "mlir-c/Support.h"
2021
#include "mlir/CAPI/Support.h"
2122
#include "llvm/ADT/DenseMap.h"
2223
#include "llvm/ADT/StringExtras.h"
@@ -151,6 +152,29 @@ class PyGlobals {
151152

152153
TracebackLoc &getTracebackLoc() { return tracebackLoc; }
153154

155+
class TypeIDAllocator {
156+
public:
157+
TypeIDAllocator() : allocator(mlirTypeIDAllocatorCreate()) {}
158+
~TypeIDAllocator() {
159+
if (allocator.ptr)
160+
mlirTypeIDAllocatorDestroy(allocator);
161+
}
162+
TypeIDAllocator(const TypeIDAllocator &) = delete;
163+
TypeIDAllocator(TypeIDAllocator &&other) : allocator(other.allocator) {
164+
other.allocator.ptr = nullptr;
165+
}
166+
167+
MlirTypeIDAllocator get() { return allocator; }
168+
MlirTypeID allocate() {
169+
return mlirTypeIDAllocatorAllocateTypeID(allocator);
170+
}
171+
172+
private:
173+
MlirTypeIDAllocator allocator;
174+
};
175+
176+
MlirTypeID allocateTypeID() { return typeIDAllocator.allocate(); }
177+
154178
private:
155179
static PyGlobals *instance;
156180

@@ -173,6 +197,7 @@ class PyGlobals {
173197
llvm::StringSet<> loadedDialectModules;
174198

175199
TracebackLoc tracebackLoc;
200+
TypeIDAllocator typeIDAllocator;
176201
};
177202

178203
} // namespace python

mlir/lib/Bindings/Python/Pass.cpp

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
#include "Pass.h"
1010

11+
#include "Globals.h"
1112
#include "IRModule.h"
1213
#include "mlir-c/Pass.h"
1314
// clang-format off
@@ -181,9 +182,7 @@ void mlir::python::populatePassManagerSubmodule(nb::module_ &m) {
181182
name = nb::cast<std::string>(
182183
nb::borrow<nb::str>(run.attr("__name__")));
183184
}
184-
MlirTypeIDAllocator typeIDAllocator = mlirTypeIDAllocatorCreate();
185-
MlirTypeID passID =
186-
mlirTypeIDAllocatorAllocateTypeID(typeIDAllocator);
185+
MlirTypeID passID = PyGlobals::get().allocateTypeID();
187186
MlirExternalPassCallbacks callbacks;
188187
callbacks.construct = [](void *obj) {
189188
(void)nb::handle(static_cast<PyObject *>(obj)).inc_ref();

0 commit comments

Comments
 (0)