| 1 |
//===- IRInterfaces.cpp - MLIR IR interfaces pybind -----------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include <utility> |
| 10 |
#include <optional> |
| 11 |
|
| 12 |
#include "IRModule.h" |
| 13 |
#include "mlir-c/BuiltinAttributes.h" |
| 14 |
#include "mlir-c/Interfaces.h" |
| 15 |
|
| 16 |
namespace py = pybind11; |
| 17 |
|
| 18 |
namespace mlir { |
| 19 |
namespace python { |
| 20 |
|
| 21 |
constexpr static const char *constructorDoc = |
| 22 |
R"(Creates an interface from a given operation/opview object or from a |
| 23 |
subclass of OpView. Raises ValueError if the operation does not implement the |
| 24 |
interface.)"; |
| 25 |
|
| 26 |
constexpr static const char *operationDoc = |
| 27 |
R"(Returns an Operation for which the interface was constructed.)"; |
| 28 |
|
| 29 |
constexpr static const char *opviewDoc = |
| 30 |
R"(Returns an OpView subclass _instance_ for which the interface was |
| 31 |
constructed)"; |
| 32 |
|
| 33 |
constexpr static const char *inferReturnTypesDoc = |
| 34 |
R"(Given the arguments required to build an operation, attempts to infer |
| 35 |
its return types. Raises ValueError on failure.)"; |
| 36 |
|
| 37 |
/// CRTP base class for Python classes representing MLIR Op interfaces. |
| 38 |
/// Interface hierarchies are flat so no base class is expected here. The |
| 39 |
/// derived class is expected to define the following static fields: |
| 40 |
/// - `const char *pyClassName` - the name of the Python class to create; |
| 41 |
/// - `GetTypeIDFunctionTy getInterfaceID` - the function producing the TypeID |
| 42 |
/// of the interface. |
| 43 |
/// Derived classes may redefine the `bindDerived(ClassTy &)` method to bind |
| 44 |
/// interface-specific methods. |
| 45 |
/// |
| 46 |
/// An interface class may be constructed from either an Operation/OpView object |
| 47 |
/// or from a subclass of OpView. In the latter case, only the static interface |
| 48 |
/// methods are available, similarly to calling ConcereteOp::staticMethod on the |
| 49 |
/// C++ side. Implementations of concrete interfaces can use the `isStatic` |
| 50 |
/// method to check whether the interface object was constructed from a class or |
| 51 |
/// an operation/opview instance. The `getOpName` always succeeds and returns a |
| 52 |
/// canonical name of the operation suitable for lookups. |
| 53 |
template <typename ConcreteIface> |
| 54 |
class PyConcreteOpInterface { |
| 55 |
protected: |
| 56 |
using ClassTy = py::class_<ConcreteIface>; |
| 57 |
using GetTypeIDFunctionTy = MlirTypeID (*)(); |
| 58 |
|
| 59 |
public: |
| 60 |
/// Constructs an interface instance from an object that is either an |
| 61 |
/// operation or a subclass of OpView. In the latter case, only the static |
| 62 |
/// methods of the interface are accessible to the caller. |
| 63 |
PyConcreteOpInterface(py::object object, DefaultingPyMlirContext context) |
| 64 |
: obj(std::move(object)) { |
| 65 |
try { |
| 66 |
operation = &py::cast<PyOperation &>(obj); |
| 67 |
} catch (py::cast_error &) { |
| 68 |
// Do nothing. |
| 69 |
} |
| 70 |
|
| 71 |
try { |
| 72 |
operation = &py::cast<PyOpView &>(obj).getOperation(); |
| 73 |
} catch (py::cast_error &) { |
| 74 |
// Do nothing. |
| 75 |
} |
| 76 |
|
| 77 |
if (operation != nullptr) { |
| 78 |
if (!mlirOperationImplementsInterface(*operation, |
| 79 |
ConcreteIface::getInterfaceID())) { |
| 80 |
std::string msg = "the operation does not implement "; |
| 81 |
throw py::value_error(msg + ConcreteIface::pyClassName); |
| 82 |
} |
| 83 |
|
| 84 |
MlirIdentifier identifier = mlirOperationGetName(*operation); |
| 85 |
MlirStringRef stringRef = mlirIdentifierStr(identifier); |
| 86 |
opName = std::string(stringRef.data, stringRef.length); |
| 87 |
} else { |
| 88 |
try { |
| 89 |
opName = obj.attr("OPERATION_NAME").template cast<std::string>(); |
| 90 |
} catch (py::cast_error &) { |
| 91 |
throw py::type_error( |
| 92 |
"Op interface does not refer to an operation or OpView class"); |
| 93 |
} |
| 94 |
|
| 95 |
if (!mlirOperationImplementsInterfaceStatic( |
| 96 |
mlirStringRefCreate(opName.data(), opName.length()), |
| 97 |
context.resolve().get(), ConcreteIface::getInterfaceID())) { |
| 98 |
std::string msg = "the operation does not implement "; |
| 99 |
throw py::value_error(msg + ConcreteIface::pyClassName); |
| 100 |
} |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
/// Creates the Python bindings for this class in the given module. |
| 105 |
static void bind(py::module &m) { |
| 106 |
py::class_<ConcreteIface> cls(m, "InferTypeOpInterface", |
| 107 |
py::module_local()); |
| 108 |
cls.def(py::init<py::object, DefaultingPyMlirContext>(), py::arg("object"), |
| 109 |
py::arg("context") = py::none(), constructorDoc) |
| 110 |
.def_property_readonly("operation", |
| 111 |
&PyConcreteOpInterface::getOperationObject, |
| 112 |
operationDoc) |
| 113 |
.def_property_readonly("opview", &PyConcreteOpInterface::getOpView, |
| 114 |
opviewDoc); |
| 115 |
ConcreteIface::bindDerived(cls); |
| 116 |
} |
| 117 |
|
| 118 |
/// Hook for derived classes to add class-specific bindings. |
| 119 |
static void bindDerived(ClassTy &cls) {} |
| 120 |
|
| 121 |
/// Returns `true` if this object was constructed from a subclass of OpView |
| 122 |
/// rather than from an operation instance. |
| 123 |
bool isStatic() { return operation == nullptr; } |
| 124 |
|
| 125 |
/// Returns the operation instance from which this object was constructed. |
| 126 |
/// Throws a type error if this object was constructed from a subclass of |
| 127 |
/// OpView. |
| 128 |
py::object getOperationObject() { |
| 129 |
if (operation == nullptr) { |
| 130 |
throw py::type_error("Cannot get an operation from a static interface"); |
| 131 |
} |
| 132 |
|
| 133 |
return operation->getRef().releaseObject(); |
| 134 |
} |
| 135 |
|
| 136 |
/// Returns the opview of the operation instance from which this object was |
| 137 |
/// constructed. Throws a type error if this object was constructed form a |
| 138 |
/// subclass of OpView. |
| 139 |
py::object getOpView() { |
| 140 |
if (operation == nullptr) { |
| 141 |
throw py::type_error("Cannot get an opview from a static interface"); |
| 142 |
} |
| 143 |
|
| 144 |
return operation->createOpView(); |
| 145 |
} |
| 146 |
|
| 147 |
/// Returns the canonical name of the operation this interface is constructed |
| 148 |
/// from. |
| 149 |
const std::string &getOpName() { return opName; } |
| 150 |
|
| 151 |
private: |
| 152 |
PyOperation *operation = nullptr; |
| 153 |
std::string opName; |
| 154 |
py::object obj; |
| 155 |
}; |
| 156 |
|
| 157 |
/// Python wrapper for InterTypeOpInterface. This interface has only static |
| 158 |
/// methods. |
| 159 |
class PyInferTypeOpInterface |
| 160 |
: public PyConcreteOpInterface<PyInferTypeOpInterface> { |
| 161 |
public: |
| 162 |
using PyConcreteOpInterface<PyInferTypeOpInterface>::PyConcreteOpInterface; |
| 163 |
|
| 164 |
constexpr static const char *pyClassName = "InferTypeOpInterface"; |
| 165 |
constexpr static GetTypeIDFunctionTy getInterfaceID = |
| 166 |
&mlirInferTypeOpInterfaceTypeID; |
| 167 |
|
| 168 |
/// C-style user-data structure for type appending callback. |
| 169 |
struct AppendResultsCallbackData { |
| 170 |
std::vector<PyType> &inferredTypes; |
| 171 |
PyMlirContext &pyMlirContext; |
| 172 |
}; |
| 173 |
|
| 174 |
/// Appends the types provided as the two first arguments to the user-data |
| 175 |
/// structure (expects AppendResultsCallbackData). |
| 176 |
static void appendResultsCallback(intptr_t nTypes, MlirType *types, |
| 177 |
void *userData) { |
| 178 |
auto *data = static_cast<AppendResultsCallbackData *>(userData); |
| 179 |
data->inferredTypes.reserve(data->inferredTypes.size() + nTypes); |
| 180 |
for (intptr_t i = 0; i < nTypes; ++i) { |
| 181 |
data->inferredTypes.emplace_back(data->pyMlirContext.getRef(), types[i]); |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
/// Given the arguments required to build an operation, attempts to infer its |
| 186 |
/// return types. Throws value_error on faliure. |
| 187 |
std::vector<PyType> |
| 188 |
inferReturnTypes(std::optional<std::vector<PyValue>> operands, |
| 189 |
std::optional<PyAttribute> attributes, |
| 190 |
std::optional<std::vector<PyRegion>> regions, |
| 191 |
DefaultingPyMlirContext context, |
| 192 |
DefaultingPyLocation location) { |
| 193 |
llvm::SmallVector<MlirValue> mlirOperands; |
| 194 |
llvm::SmallVector<MlirRegion> mlirRegions; |
| 195 |
|
| 196 |
if (operands) { |
| 197 |
mlirOperands.reserve(operands->size()); |
| 198 |
for (PyValue &value : *operands) { |
| 199 |
mlirOperands.push_back(value); |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
if (regions) { |
| 204 |
mlirRegions.reserve(regions->size()); |
| 205 |
for (PyRegion ®ion : *regions) { |
| 206 |
mlirRegions.push_back(region); |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
std::vector<PyType> inferredTypes; |
| 211 |
PyMlirContext &pyContext = context.resolve(); |
| 212 |
AppendResultsCallbackData data{inferredTypes, pyContext}; |
| 213 |
MlirStringRef opNameRef = |
| 214 |
mlirStringRefCreate(getOpName().data(), getOpName().length()); |
| 215 |
MlirAttribute attributeDict = |
| 216 |
attributes ? attributes->get() : mlirAttributeGetNull(); |
| 217 |
|
| 218 |
MlirLogicalResult result = mlirInferTypeOpInterfaceInferReturnTypes( |
| 219 |
opNameRef, pyContext.get(), location.resolve(), mlirOperands.size(), |
| 220 |
mlirOperands.data(), attributeDict, mlirRegions.size(), |
| 221 |
mlirRegions.data(), &appendResultsCallback, &data); |
| 222 |
|
| 223 |
if (mlirLogicalResultIsFailure(result)) { |
| 224 |
throw py::value_error("Failed to infer result types"); |
| 225 |
} |
| 226 |
|
| 227 |
return inferredTypes; |
| 228 |
} |
| 229 |
|
| 230 |
static void bindDerived(ClassTy &cls) { |
| 231 |
cls.def("inferReturnTypes", &PyInferTypeOpInterface::inferReturnTypes, |
| 232 |
py::arg("operands") = py::none(), |
| 233 |
py::arg("attributes") = py::none(), py::arg("regions") = py::none(), |
| 234 |
py::arg("context") = py::none(), py::arg("loc") = py::none(), |
| 235 |
inferReturnTypesDoc); |
| 236 |
} |
| 237 |
}; |
| 238 |
|
| 239 |
void populateIRInterfaces(py::module &m) { PyInferTypeOpInterface::bind(m); } |
| 240 |
|
| 241 |
} // namespace python |
| 242 |
} // namespace mlir |