[mlir] fix crash in PybindAdaptors.h
authorAlex Zinenko <zinenko@google.com>
Mon, 17 Jan 2022 13:48:28 +0000 (14:48 +0100)
committerAlex Zinenko <zinenko@google.com>
Tue, 18 Jan 2022 09:24:11 +0000 (10:24 +0100)
commit289021a45decdef8ed61d054b9c90ce775ca9c96
treee5cd0bcf39f5d00ff9ea08a0d43f57a5907d9d91
parentfd598e185972f76a50c45e1402ab3b0fd70664b9
[mlir] fix crash in PybindAdaptors.h

The constructor function was being defined without indicating its "__init__"
name, which made it interpret it as a regular fuction rather than a
constructor. When overload resolution failed, Pybind would attempt to print the
arguments actually passed to the function, including "self", which is not
initialized since the constructor couldn't be called. This would result in
"__repr__" being called with "self" referencing an uninitialized MLIR C API
object, which in turn would cause undefined behavior when attempting to print
in C++.

Fix this by specifying the correct name.

This in turn uncovers the fact the the mechanism used by PybindAdaptors.h to
bind constructors directly as "__init__" functions taking "self" is deprecated
by Pybind. Instead, leverage the fact that the adaptors are intended for
attrbutes/types that cannot have additional data members and are all ultimately
instances of "PyAttribute"/"PyType" C++ class. In constructors of derived
classes, construct an instance of the base class first, then steal its internal
pointer to the C++ object to construct the instance of the derived class.

On top of that, the definition of the function was incorrectly indicated as the
method on the "None" object instead of being the method of its parent class.
This would result in a second problem when Pybind would attempt to print
warnings pointing to the parent class since the "None" does not have a
"__name__" field or its C API equivalent.

Fix this by specifying the correct parent class by looking it up by name in the
parent module.

Reviewed By: stellaraccident

Differential Revision: https://reviews.llvm.org/D117325
mlir/include/mlir/Bindings/Python/PybindAdaptors.h