11 #include <pybind11/cast.h>
12 #include <pybind11/detail/common.h>
13 #include <pybind11/pybind11.h>
14 #include <pybind11/pytypes.h>
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
33 R
"(Creates an interface from a given operation/opview object or from a
34 subclass of OpView. Raises ValueError if the operation does not implement the
38 R
"(Returns an Operation for which the interface was constructed.)";
41 R
"(Returns an OpView subclass _instance_ for which the interface was
45 R
"(Given the arguments required to build an operation, attempts to infer
46 its return types. Raises ValueError on failure.)";
49 R
"(Given the arguments required to build an operation, attempts to infer
50 its return shaped type components. Raises ValueError on failure.)";
59 if (!operandList || operandList->empty()) {
64 mlirOperands.reserve(operandList->size());
66 if (it.value().is_none())
71 val = py::cast<PyValue *>(it.value());
73 throw py::cast_error();
74 mlirOperands.push_back(val->
get());
76 }
catch (py::cast_error &err) {
82 auto vals = py::cast<py::sequence>(it.value());
83 for (py::object v : vals) {
85 val = py::cast<PyValue *>(v);
87 throw py::cast_error();
88 mlirOperands.push_back(val->
get());
89 }
catch (py::cast_error &err) {
90 throw py::value_error(
91 (llvm::Twine(
"Operand ") + llvm::Twine(it.index()) +
92 " must be a Value or Sequence of Values (" + err.what() +
")")
97 }
catch (py::cast_error &err) {
98 throw py::value_error((llvm::Twine(
"Operand ") + llvm::Twine(it.index()) +
99 " must be a Value or Sequence of Values (" +
104 throw py::cast_error();
113 wrapRegions(std::optional<std::vector<PyRegion>> regions) {
117 mlirRegions.reserve(regions->size());
119 mlirRegions.push_back(region);
144 template <
typename ConcreteIface>
155 : obj(std::move(object)) {
157 operation = &py::cast<PyOperation &>(obj);
158 }
catch (py::cast_error &) {
164 }
catch (py::cast_error &) {
168 if (operation !=
nullptr) {
170 ConcreteIface::getInterfaceID())) {
171 std::string msg =
"the operation does not implement ";
172 throw py::value_error(msg + ConcreteIface::pyClassName);
177 opName = std::string(stringRef.
data, stringRef.
length);
180 opName = obj.attr(
"OPERATION_NAME").template cast<std::string>();
181 }
catch (py::cast_error &) {
182 throw py::type_error(
183 "Op interface does not refer to an operation or OpView class");
188 context.
resolve().
get(), ConcreteIface::getInterfaceID())) {
189 std::string msg =
"the operation does not implement ";
190 throw py::value_error(msg + ConcreteIface::pyClassName);
196 static void bind(py::module &m) {
197 py::class_<ConcreteIface> cls(m, ConcreteIface::pyClassName,
199 cls.def(py::init<py::object, DefaultingPyMlirContext>(), py::arg(
"object"),
201 .def_property_readonly(
"operation",
206 ConcreteIface::bindDerived(cls);
220 if (operation ==
nullptr) {
221 throw py::type_error(
"Cannot get an operation from a static interface");
231 if (operation ==
nullptr) {
232 throw py::type_error(
"Cannot get an opview from a static interface");
255 constexpr
static const char *
pyClassName =
"InferTypeOpInterface";
270 data->
inferredTypes.reserve(data->inferredTypes.size() + nTypes);
271 for (intptr_t i = 0; i < nTypes; ++i) {
272 data->inferredTypes.emplace_back(data->pyMlirContext.getRef(), types[i]);
280 std::optional<PyAttribute> attributes,
void *properties,
281 std::optional<std::vector<PyRegion>> regions,
285 wrapOperands(std::move(operandList));
288 std::vector<PyType> inferredTypes;
293 MlirAttribute attributeDict =
297 opNameRef, pyContext.
get(), location.
resolve(), mlirOperands.size(),
298 mlirOperands.data(), attributeDict, properties, mlirRegions.size(),
302 throw py::value_error(
"Failed to infer result types");
305 return inferredTypes;
310 py::arg(
"operands") = py::none(),
311 py::arg(
"attributes") = py::none(),
312 py::arg(
"properties") = py::none(), py::arg(
"regions") = py::none(),
313 py::arg(
"context") = py::none(), py::arg(
"loc") = py::none(),
323 : shape(std::move(shape)), elementType(elementType), ranked(true) {}
325 MlirAttribute attribute)
326 : shape(std::move(shape)), elementType(elementType), attribute(attribute),
330 : shape(other.shape), elementType(other.elementType),
331 attribute(other.attribute), ranked(other.ranked) {}
333 static void bind(py::module &m) {
334 py::class_<PyShapedTypeComponents>(m,
"ShapedTypeComponents",
336 .def_property_readonly(
339 "Returns the element type of the shaped type components.")
345 py::arg(
"element_type"),
346 "Create an shaped type components object with only the element "
350 [](py::list shape,
PyType &elementType) {
353 py::arg(
"shape"), py::arg(
"element_type"),
354 "Create a ranked shaped type components object.")
361 py::arg(
"shape"), py::arg(
"element_type"), py::arg(
"attribute"),
362 "Create a ranked shaped type components object with attribute.")
363 .def_property_readonly(
366 "Returns whether the given shaped type component is ranked.")
367 .def_property_readonly(
373 return py::int_(
self.shape.size());
375 "Returns the rank of the given ranked shaped type components. If "
376 "the shaped type components does not have a rank, None is "
378 .def_property_readonly(
384 return py::list(
self.shape);
386 "Returns the shape of the ranked shaped type components as a list "
387 "of integers. Returns none if the shaped type component does not "
396 MlirType elementType;
397 MlirAttribute attribute;
409 constexpr
static const char *
pyClassName =
"InferShapedTypeOpInterface";
421 const int64_t *shape, MlirType elementType,
422 MlirAttribute attribute,
void *userData) {
428 for (intptr_t i = 0; i < rank; ++i) {
429 shapeList.append(shape[i]);
431 data->inferredShapedTypeComponents.emplace_back(shapeList, elementType,
439 std::optional<py::list> operandList,
440 std::optional<PyAttribute> attributes,
void *properties,
441 std::optional<std::vector<PyRegion>> regions,
444 wrapOperands(std::move(operandList));
447 std::vector<PyShapedTypeComponents> inferredShapedTypeComponents;
452 MlirAttribute attributeDict =
456 opNameRef, pyContext.
get(), location.
resolve(), mlirOperands.size(),
457 mlirOperands.data(), attributeDict, properties, mlirRegions.size(),
461 throw py::value_error(
"Failed to infer result shape type components");
464 return inferredShapedTypeComponents;
468 cls.def(
"inferReturnTypeComponents",
470 py::arg(
"operands") = py::none(),
471 py::arg(
"attributes") = py::none(), py::arg(
"regions") = py::none(),
472 py::arg(
"properties") = py::none(), py::arg(
"context") = py::none(),
Used in function arguments when None should resolve to the current context manager set instance.
static PyLocation & resolve()
Used in function arguments when None should resolve to the current context manager set instance.
static PyMlirContext & resolve()
Wrapper around the generic MlirAttribute.
CRTP base class for Python classes representing MLIR Op interfaces.
static void bind(py::module &m)
Creates the Python bindings for this class in the given module.
py::object getOpView()
Returns the opview of the operation instance from which this object was constructed.
MlirTypeID(*)() GetTypeIDFunctionTy
py::class_< ConcreteIface > ClassTy
PyConcreteOpInterface(py::object object, DefaultingPyMlirContext context)
Constructs an interface instance from an object that is either an operation or a subclass of OpView.
bool isStatic()
Returns true if this object was constructed from a subclass of OpView rather than from an operation i...
static void bindDerived(ClassTy &cls)
Hook for derived classes to add class-specific bindings.
py::object getOperationObject()
Returns the operation instance from which this object was constructed.
const std::string & getOpName()
Returns the canonical name of the operation this interface is constructed from.
Python wrapper for InferShapedTypeOpInterface.
constexpr static const char * pyClassName
static void appendResultsCallback(bool hasRank, intptr_t rank, const int64_t *shape, MlirType elementType, MlirAttribute attribute, void *userData)
Appends the shaped type components provided as unpacked shape, element type, attribute to the user-da...
std::vector< PyShapedTypeComponents > inferReturnTypeComponents(std::optional< py::list > operandList, std::optional< PyAttribute > attributes, void *properties, std::optional< std::vector< PyRegion >> regions, DefaultingPyMlirContext context, DefaultingPyLocation location)
Given the arguments required to build an operation, attempts to infer the shaped type components.
constexpr static GetTypeIDFunctionTy getInterfaceID
static void bindDerived(ClassTy &cls)
Python wrapper for InferTypeOpInterface.
constexpr static GetTypeIDFunctionTy getInterfaceID
std::vector< PyType > inferReturnTypes(std::optional< py::list > operandList, std::optional< PyAttribute > attributes, void *properties, std::optional< std::vector< PyRegion >> regions, DefaultingPyMlirContext context, DefaultingPyLocation location)
Given the arguments required to build an operation, attempts to infer its return types.
constexpr static const char * pyClassName
static void bindDerived(ClassTy &cls)
static void appendResultsCallback(intptr_t nTypes, MlirType *types, void *userData)
Appends the types provided as the two first arguments to the user-data structure (expects AppendResul...
MlirContext get()
Accesses the underlying MlirContext.
pybind11::object releaseObject()
Releases the object held by this instance, returning it.
PyOperation & getOperation() override
Each must provide access to the raw Operation.
pybind11::object createOpView()
Creates an OpView suitable for this operation.
Wrapper around an MlirRegion.
Wrapper around an shaped type components.
PyShapedTypeComponents(PyShapedTypeComponents &)=delete
static void bind(py::module &m)
pybind11::object getCapsule()
PyShapedTypeComponents(PyShapedTypeComponents &&other) noexcept
PyShapedTypeComponents(py::list shape, MlirType elementType)
PyShapedTypeComponents(MlirType elementType)
PyShapedTypeComponents(py::list shape, MlirType elementType, MlirAttribute attribute)
static PyShapedTypeComponents createFromCapsule(pybind11::object capsule)
Wrapper around the generic MlirType.
Wrapper around the generic MlirValue.
MLIR_CAPI_EXPORTED MlirAttribute mlirAttributeGetNull(void)
Returns an empty attribute.
MLIR_CAPI_EXPORTED MlirIdentifier mlirOperationGetName(MlirOperation op)
Gets the name of the operation as an identifier.
MLIR_CAPI_EXPORTED MlirStringRef mlirIdentifierStr(MlirIdentifier ident)
Gets the string value of the identifier.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirInferShapedTypeOpInterfaceInferReturnTypes(MlirStringRef opName, MlirContext context, MlirLocation location, intptr_t nOperands, MlirValue *operands, MlirAttribute attributes, void *properties, intptr_t nRegions, MlirRegion *regions, MlirShapedTypeComponentsCallback callback, void *userData)
Infers the return shaped type components of the operation.
MLIR_CAPI_EXPORTED bool mlirOperationImplementsInterfaceStatic(MlirStringRef operationName, MlirContext context, MlirTypeID interfaceTypeID)
Returns true if the operation identified by its canonical string name implements the interface identi...
MLIR_CAPI_EXPORTED MlirTypeID mlirInferTypeOpInterfaceTypeID()
Returns the interface TypeID of the InferTypeOpInterface.
MLIR_CAPI_EXPORTED bool mlirOperationImplementsInterface(MlirOperation operation, MlirTypeID interfaceTypeID)
Returns true if the given operation implements an interface identified by its TypeID.
MLIR_CAPI_EXPORTED MlirLogicalResult mlirInferTypeOpInterfaceInferReturnTypes(MlirStringRef opName, MlirContext context, MlirLocation location, intptr_t nOperands, MlirValue *operands, MlirAttribute attributes, void *properties, intptr_t nRegions, MlirRegion *regions, MlirTypesCallback callback, void *userData)
Infers the return types of the operation identified by its canonical given the arguments that will be...
MLIR_CAPI_EXPORTED MlirTypeID mlirInferShapedTypeOpInterfaceTypeID()
Returns the interface TypeID of the InferShapedTypeOpInterface.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
static bool mlirLogicalResultIsFailure(MlirLogicalResult res)
Checks if the given logical result represents a failure.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
constexpr static const char * inferReturnTypesDoc
constexpr static const char * operationDoc
constexpr static const char * opviewDoc
constexpr static const char * constructorDoc
constexpr static const char * inferReturnTypeComponentsDoc
void populateIRInterfaces(py::module &m)
Include the generated interface declarations.
A logical result value, essentially a boolean with named states.
A pointer to a sized fragment of a string, not necessarily null-terminated.
const char * data
Pointer to the first symbol.
size_t length
Length of the fragment.
C-style user-data structure for type appending callback.
std::vector< PyShapedTypeComponents > & inferredShapedTypeComponents
C-style user-data structure for type appending callback.
std::vector< PyType > & inferredTypes
PyMlirContext & pyMlirContext