Skip to content

Commit 6f8bcdd

Browse files
author
Maksim Manainen
committed
init
1 parent d871702 commit 6f8bcdd

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

mlir/lib/Bindings/Python/IRAttributes.cpp

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "mlir-c/BuiltinTypes.h"
1919
#include "mlir/Bindings/Python/NanobindAdaptors.h"
2020
#include "mlir/Bindings/Python/Nanobind.h"
21+
#include "pylifecycle.h"
2122
#include "llvm/ADT/ScopeExit.h"
2223
#include "llvm/Support/raw_ostream.h"
2324

@@ -1428,6 +1429,16 @@ class PyDenseIntElementsAttribute
14281429
}
14291430
};
14301431

1432+
static bool pythonIsFinalizing() {
1433+
#if PY_VERSION_HEX >= 0x030d0000
1434+
return Py_IsFinalizing();
1435+
#elif PY_VERSION_HEX >= 0x03070000
1436+
return _Py_IsFinalizing();
1437+
#else
1438+
return _Py_Finalizing != nullptr;
1439+
#endif
1440+
}
1441+
14311442
class PyDenseResourceElementsAttribute
14321443
: public PyConcreteAttribute<PyDenseResourceElementsAttribute> {
14331444
public:
@@ -1474,7 +1485,7 @@ class PyDenseResourceElementsAttribute
14741485
// The userData is a Py_buffer* that the deleter owns.
14751486
auto deleter = [](void *userData, const void *data, size_t size,
14761487
size_t align) {
1477-
if (!Py_IsInitialized())
1488+
if (!(Py_IsInitialized() || pythonIsFinalizing()))
14781489
Py_Initialize();
14791490
Py_buffer *ownedView = static_cast<Py_buffer *>(userData);
14801491
nb::gil_scoped_acquire gil;

mlir/test/python/ir/array_attributes.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,3 +617,16 @@ def test_attribute(context, mview):
617617
# CHECK: BACKING MEMORY DELETED
618618
# CHECK: EXIT FUNCTION
619619
print("EXIT FUNCTION")
620+
621+
622+
print("TEST: danglingResource")
623+
# This error occurs only when there is an alive context with a DenseResourceElementsAttr
624+
# in the end of the program, so we put it here without an encapsulating function.
625+
ctx = Context()
626+
627+
with ctx, Location.unknown():
628+
DenseResourceElementsAttr.get_from_buffer(
629+
memoryview(np.array([1,2,3])),
630+
"some_resource",
631+
RankedTensorType.get((3,), IntegerType.get_signed(32))
632+
)

0 commit comments

Comments
 (0)