diff --git a/mlir/lib/Bindings/Python/IRCore.cpp b/mlir/lib/Bindings/Python/IRCore.cpp --- a/mlir/lib/Bindings/Python/IRCore.cpp +++ b/mlir/lib/Bindings/Python/IRCore.cpp @@ -2102,6 +2102,8 @@ }) .def("__eq__", [](PyOperationBase &self, py::object other) { return false; }) + .def("__hash__", + [](PyOperationBase &self) { return (size_t)&self.getOperation(); }) .def_property_readonly("attributes", [](PyOperationBase &self) { return PyOpAttributeMap( @@ -2603,6 +2605,7 @@ return self.get().ptr == other.get().ptr; }) .def("__eq__", [](PyValue &self, py::object other) { return false; }) + .def("__hash__", [](PyValue &self) { return (size_t)self.get().ptr; }) .def( "__str__", [](PyValue &self) { diff --git a/mlir/test/python/ir/operation.py b/mlir/test/python/ir/operation.py --- a/mlir/test/python/ir/operation.py +++ b/mlir/test/python/ir/operation.py @@ -740,3 +740,15 @@ op = Operation.create("custom.op", loc=loc) assert op.location == loc assert op.operation.location == loc + + +# CHECK-LABEL: TEST: testOperationHash +@run +def testOperationHash(): + ctx = Context() + ctx.allow_unregistered_dialects = True + with ctx, Location.unknown(): + op1 = Operation.create("custom.op1") + op2 = Operation.create("custom.op2") + assert hash(op1) == hash(op1.operation) + assert hash(op1) != hash(op2) diff --git a/mlir/test/python/ir/value.py b/mlir/test/python/ir/value.py --- a/mlir/test/python/ir/value.py +++ b/mlir/test/python/ir/value.py @@ -55,3 +55,23 @@ op = func.regions[0].blocks[0].operations[0] assert not BlockArgument.isinstance(op.results[0]) assert OpResult.isinstance(op.results[0]) + + +# CHECK-LABEL: TEST: testValueHash +@run +def testValueHash(): + ctx = Context() + ctx.allow_unregistered_dialects = True + module = Module.parse( + r""" + func @foo(%arg0: f32) -> f32 { + %0 = "some_dialect.some_op"(%arg0) : (f32) -> f32 + return %0 : f32 + }""", ctx) + + [func] = module.body.operations + block = func.entry_block + op, ret = block.operations + assert hash(block.arguments[0]) == hash(op.operands[0]) + assert hash(op.result) == hash(ret.operands[0]) + assert hash(block.arguments[0]) != ret.operands[0]