MLIR 23.0.0git
IRInterfaces.cpp
Go to the documentation of this file.
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 <cstdint>
10#include <optional>
11#include <string>
12#include <utility>
13#include <vector>
14
16#include "mlir-c/IR.h"
17#include "mlir-c/Interfaces.h"
18#include "mlir-c/Support.h"
21
22namespace nb = nanobind;
23
24namespace mlir {
25namespace python {
27constexpr static const char *inferReturnTypesDoc =
28 R"(Given the arguments required to build an operation, attempts to infer
29its return types. Raises ValueError on failure.)";
30
31constexpr static const char *inferReturnTypeComponentsDoc =
32 R"(Given the arguments required to build an operation, attempts to infer
33its return shaped type components. Raises ValueError on failure.)";
34
35namespace {
36
37/// Takes in an optional ist of operands and converts them into a std::vector
38/// of MlirVlaues. Returns an empty std::vector if the list is empty.
39std::vector<MlirValue> wrapOperands(std::optional<nb::list> operandList) {
40 std::vector<MlirValue> mlirOperands;
41
42 if (!operandList || operandList->size() == 0) {
43 return mlirOperands;
44 }
45
46 // Note: as the list may contain other lists this may not be final size.
47 mlirOperands.reserve(operandList->size());
48 for (size_t i = 0, e = operandList->size(); i < e; ++i) {
49 nb::handle operand = (*operandList)[i];
50 intptr_t index = static_cast<intptr_t>(i);
51 if (operand.is_none())
52 continue;
53
54 PyValue *val;
55 try {
56 val = nb::cast<PyValue *>(operand);
57 if (!val)
58 throw nb::cast_error();
59 mlirOperands.push_back(val->get());
60 continue;
61 } catch (nb::cast_error &err) {
62 // Intentionally unhandled to try sequence below first.
63 (void)err;
64 }
65
66 try {
67 auto vals = nb::cast<nb::sequence>(operand);
68 for (nb::handle v : vals) {
69 try {
70 val = nb::cast<PyValue *>(v);
71 if (!val)
72 throw nb::cast_error();
73 mlirOperands.push_back(val->get());
74 } catch (nb::cast_error &err) {
75 throw nb::value_error(
76 nanobind::detail::join("Operand ", index,
77 " must be a Value or Sequence of Values (",
78 err.what(), ")")
79 .c_str());
80 }
81 }
82 continue;
83 } catch (nb::cast_error &err) {
84 throw nb::value_error(
85 nanobind::detail::join("Operand ", index,
86 " must be a Value or Sequence of Values (",
87 err.what(), ")")
88 .c_str());
89 }
90
91 throw nb::cast_error();
92 }
93
94 return mlirOperands;
95}
96
97/// Takes in an optional vector of PyRegions and returns a std::vector of
98/// MlirRegion. Returns an empty std::vector if the list is empty.
99std::vector<MlirRegion>
100wrapRegions(std::optional<std::vector<PyRegion>> regions) {
101 std::vector<MlirRegion> mlirRegions;
102
103 if (regions) {
104 mlirRegions.reserve(regions->size());
105 for (PyRegion &region : *regions) {
106 mlirRegions.push_back(region);
107 }
108 }
109
110 return mlirRegions;
111}
112
113} // namespace
114
115/// Python wrapper for InferTypeOpInterface. This interface has only static
116/// methods.
118 : public PyConcreteOpInterface<PyInferTypeOpInterface> {
119public:
121
122 constexpr static const char *pyClassName = "InferTypeOpInterface";
125
126 /// C-style user-data structure for type appending callback.
131
132 /// Appends the types provided as the two first arguments to the user-data
133 /// structure (expects AppendResultsCallbackData).
134 static void appendResultsCallback(intptr_t nTypes, MlirType *types,
135 void *userData) {
136 auto *data = static_cast<AppendResultsCallbackData *>(userData);
137 data->inferredTypes.reserve(data->inferredTypes.size() + nTypes);
138 for (intptr_t i = 0; i < nTypes; ++i) {
139 data->inferredTypes.emplace_back(data->pyMlirContext.getRef(), types[i]);
140 }
141 }
142
143 /// Given the arguments required to build an operation, attempts to infer its
144 /// return types. Throws value_error on failure.
145 std::vector<PyType>
146 inferReturnTypes(std::optional<nb::list> operandList,
147 std::optional<PyAttribute> attributes, void *properties,
148 std::optional<std::vector<PyRegion>> regions,
150 DefaultingPyLocation location) {
151 std::vector<MlirValue> mlirOperands = wrapOperands(std::move(operandList));
152 std::vector<MlirRegion> mlirRegions = wrapRegions(std::move(regions));
153
154 std::vector<PyType> inferredTypes;
155 PyMlirContext &pyContext = context.resolve();
156 AppendResultsCallbackData data{inferredTypes, pyContext};
157 MlirStringRef opNameRef =
158 mlirStringRefCreate(getOpName().data(), getOpName().length());
159 MlirAttribute attributeDict =
160 attributes ? attributes->get() : mlirAttributeGetNull();
161
163 opNameRef, pyContext.get(), location.resolve(), mlirOperands.size(),
164 mlirOperands.data(), attributeDict, properties, mlirRegions.size(),
165 mlirRegions.data(), &appendResultsCallback, &data);
166
168 throw nb::value_error("Failed to infer result types");
169 }
170
171 return inferredTypes;
172 }
173
174 static void bindDerived(ClassTy &cls) {
175 cls.def("inferReturnTypes", &PyInferTypeOpInterface::inferReturnTypes,
176 nb::arg("operands") = nb::none(),
177 nb::arg("attributes") = nb::none(),
178 nb::arg("properties") = nb::none(), nb::arg("regions") = nb::none(),
179 nb::arg("context") = nb::none(), nb::arg("loc") = nb::none(),
181 }
182};
183
184/// Wrapper around an shaped type components.
186public:
187 PyShapedTypeComponents(MlirType elementType) : elementType(elementType) {}
188 PyShapedTypeComponents(nb::list shape, MlirType elementType)
189 : shape(std::move(shape)), elementType(elementType), ranked(true) {}
190 PyShapedTypeComponents(nb::list shape, MlirType elementType,
191 MlirAttribute attribute)
192 : shape(std::move(shape)), elementType(elementType), attribute(attribute),
193 ranked(true) {}
196 : shape(other.shape), elementType(other.elementType),
197 attribute(other.attribute), ranked(other.ranked) {}
198
199 static void bind(nb::module_ &m) {
200 nb::class_<PyShapedTypeComponents>(m, "ShapedTypeComponents")
201 .def_prop_ro(
202 "element_type",
203 [](PyShapedTypeComponents &self) { return self.elementType; },
204 nb::sig("def element_type(self) -> Type"),
205 "Returns the element type of the shaped type components.")
206 .def_static(
207 "get",
208 [](PyType &elementType) {
209 return PyShapedTypeComponents(elementType);
210 },
211 nb::arg("element_type"),
212 "Create an shaped type components object with only the element "
213 "type.")
214 .def_static(
215 "get",
216 [](nb::list shape, PyType &elementType) {
217 return PyShapedTypeComponents(std::move(shape), elementType);
218 },
219 nb::arg("shape"), nb::arg("element_type"),
220 "Create a ranked shaped type components object.")
221 .def_static(
222 "get",
223 [](nb::list shape, PyType &elementType, PyAttribute &attribute) {
224 return PyShapedTypeComponents(std::move(shape), elementType,
225 attribute);
226 },
227 nb::arg("shape"), nb::arg("element_type"), nb::arg("attribute"),
228 "Create a ranked shaped type components object with attribute.")
229 .def_prop_ro(
230 "has_rank",
231 [](PyShapedTypeComponents &self) -> bool { return self.ranked; },
232 "Returns whether the given shaped type component is ranked.")
233 .def_prop_ro(
234 "rank",
235 [](PyShapedTypeComponents &self) -> std::optional<nb::int_> {
236 if (!self.ranked)
237 return {};
238 return nb::int_(self.shape.size());
239 },
240 "Returns the rank of the given ranked shaped type components. If "
241 "the shaped type components does not have a rank, None is "
242 "returned.")
243 .def_prop_ro(
244 "shape",
245 [](PyShapedTypeComponents &self) -> std::optional<nb::list> {
246 if (!self.ranked)
247 return {};
248 return nb::list(self.shape);
249 },
250 "Returns the shape of the ranked shaped type components as a list "
251 "of integers. Returns none if the shaped type component does not "
252 "have a rank.");
253 }
254
255 nb::object getCapsule();
256 static PyShapedTypeComponents createFromCapsule(nb::object capsule);
257
258private:
259 nb::list shape;
260 MlirType elementType;
261 MlirAttribute attribute;
262 bool ranked{false};
263};
264
265/// Python wrapper for InferShapedTypeOpInterface. This interface has only
266/// static methods.
268 : public PyConcreteOpInterface<PyInferShapedTypeOpInterface> {
269public:
272
273 constexpr static const char *pyClassName = "InferShapedTypeOpInterface";
276
277 /// C-style user-data structure for type appending callback.
279 std::vector<PyShapedTypeComponents> &inferredShapedTypeComponents;
280 };
281
282 /// Appends the shaped type components provided as unpacked shape, element
283 /// type, attribute to the user-data.
284 static void appendResultsCallback(bool hasRank, intptr_t rank,
285 const int64_t *shape, MlirType elementType,
286 MlirAttribute attribute, void *userData) {
287 auto *data = static_cast<AppendResultsCallbackData *>(userData);
288 if (!hasRank) {
289 data->inferredShapedTypeComponents.emplace_back(elementType);
290 } else {
291 nb::list shapeList;
292 for (intptr_t i = 0; i < rank; ++i) {
293 shapeList.append(shape[i]);
294 }
295 data->inferredShapedTypeComponents.emplace_back(shapeList, elementType,
296 attribute);
297 }
298 }
299
300 /// Given the arguments required to build an operation, attempts to infer the
301 /// shaped type components. Throws value_error on failure.
302 std::vector<PyShapedTypeComponents> inferReturnTypeComponents(
303 std::optional<nb::list> operandList,
304 std::optional<PyAttribute> attributes, void *properties,
305 std::optional<std::vector<PyRegion>> regions,
307 std::vector<MlirValue> mlirOperands = wrapOperands(std::move(operandList));
308 std::vector<MlirRegion> mlirRegions = wrapRegions(std::move(regions));
309
310 std::vector<PyShapedTypeComponents> inferredShapedTypeComponents;
311 PyMlirContext &pyContext = context.resolve();
312 AppendResultsCallbackData data{inferredShapedTypeComponents};
313 MlirStringRef opNameRef =
314 mlirStringRefCreate(getOpName().data(), getOpName().length());
315 MlirAttribute attributeDict =
316 attributes ? attributes->get() : mlirAttributeGetNull();
317
319 opNameRef, pyContext.get(), location.resolve(), mlirOperands.size(),
320 mlirOperands.data(), attributeDict, properties, mlirRegions.size(),
321 mlirRegions.data(), &appendResultsCallback, &data);
322
324 throw nb::value_error("Failed to infer result shape type components");
325 }
326
327 return inferredShapedTypeComponents;
328 }
329
330 static void bindDerived(ClassTy &cls) {
331 cls.def("inferReturnTypeComponents",
333 nb::arg("operands") = nb::none(),
334 nb::arg("attributes") = nb::none(), nb::arg("regions") = nb::none(),
335 nb::arg("properties") = nb::none(), nb::arg("context") = nb::none(),
336 nb::arg("loc") = nb::none(), inferReturnTypeComponentsDoc);
337 }
338};
339
340/// Wrapper around the MemoryEffectsOpInterface.
342 : public PyConcreteOpInterface<PyMemoryEffectsOpInterface> {
343public:
346
347 constexpr static const char *pyClassName = "MemoryEffectsOpInterface";
350
351 /// Attach a new MemoryEffectsOpInterface FallbackModel to the named
352 /// operation. The FallbackModel acts as a trampoline for callbacks on the
353 /// Python class.
354 static void attach(nb::object &target, const std::string &opName,
357 callbacks.userData = target.ptr();
358 nb::handle(static_cast<PyObject *>(callbacks.userData)).inc_ref();
359 callbacks.construct = nullptr;
360 callbacks.destruct = [](void *userData) {
361 nb::handle(static_cast<PyObject *>(userData)).dec_ref();
362 };
363 callbacks.getEffects = [](MlirOperation op,
364 MlirMemoryEffectInstancesList effects,
365 void *userData) {
366 nb::handle pyClass(static_cast<PyObject *>(userData));
367
368 // Get the 'get_effects' method from the Python class.
369 auto pyGetEffects =
370 nb::cast<nb::callable>(nb::getattr(pyClass, "get_effects"));
371
372 PyMemoryEffectsInstanceList effectsWrapper{effects};
373
374 PyMlirContextRef context =
376 auto opview = PyOperation::forOperation(context, op)->createOpView();
377
378 // Invoke `pyClass.get_effects(op, effects)`.
379 pyGetEffects(opview, effectsWrapper);
380 };
381
383 ctx->get(), mlirStringRefCreate(opName.c_str(), opName.size()),
384 callbacks);
385 }
386
387 static void bindDerived(ClassTy &cls) {
388 cls.attr("attach") = classmethod(
389 [](const nb::object &cls, const nb::object &opName, nb::object target,
390 DefaultingPyMlirContext context) {
391 if (target.is_none())
392 target = cls;
393 return attach(target, nb::cast<std::string>(opName), context);
394 },
395 nb::arg("cls"), nb::arg("op_name"), nb::kw_only(),
396 nb::arg("target").none() = nb::none(),
397 nb::arg("context").none() = nb::none(),
398 "Attach the interface subclass to the given operation name.");
399 }
400};
401
402void populateIRInterfaces(nb::module_ &m) {
403 nb::class_<PyMemoryEffectsInstanceList>(m, "MemoryEffectInstancesList");
404
409}
410} // namespace MLIR_BINDINGS_PYTHON_DOMAIN
411} // namespace python
412} // namespace mlir
true
Given two iterators into the same block, return "true" if a is before `b.
MlirContext mlirOperationGetContext(MlirOperation op)
Definition IR.cpp:650
ReferrentTy * get() const
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:525
Used in function arguments when None should resolve to the current context manager set instance.
Definition IRCore.h:279
Wrapper around the generic MlirAttribute.
Definition IRCore.h:1006
PyConcreteOpInterface(nanobind::object object, DefaultingPyMlirContext context)
std::vector< PyShapedTypeComponents > inferReturnTypeComponents(std::optional< nb::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.
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< PyType > inferReturnTypes(std::optional< nb::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.
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...
static void attach(nb::object &target, const std::string &opName, DefaultingPyMlirContext ctx)
Attach a new MemoryEffectsOpInterface FallbackModel to the named operation.
static PyMlirContextRef forContext(MlirContext context)
Returns a context reference for the singleton PyMlirContext wrapper for the given context.
Definition IRCore.cpp:486
MlirContext get()
Accesses the underlying MlirContext.
Definition IRCore.h:212
nanobind::object createOpView()
Creates an OpView suitable for this operation.
Definition IRCore.cpp:1377
static PyOperationRef forOperation(PyMlirContextRef contextRef, MlirOperation operation, nanobind::object parentKeepAlive=nanobind::object())
Returns a PyOperation for the given MlirOperation, optionally associating it with a parentKeepAlive.
Definition IRCore.cpp:983
PyShapedTypeComponents(nb::list shape, MlirType elementType, MlirAttribute attribute)
static PyShapedTypeComponents createFromCapsule(nb::object capsule)
PyShapedTypeComponents(PyShapedTypeComponents &&other) noexcept
Wrapper around the generic MlirType.
Definition IRCore.h:875
MLIR_CAPI_EXPORTED MlirAttribute mlirAttributeGetNull(void)
Returns an empty attribute.
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 MlirTypeID mlirInferTypeOpInterfaceTypeID(void)
Returns the interface TypeID of the InferTypeOpInterface.
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 mlirMemoryEffectsOpInterfaceTypeID(void)
Returns the interface TypeID of the MemoryEffectsOpInterface.
MLIR_CAPI_EXPORTED MlirTypeID mlirInferShapedTypeOpInterfaceTypeID(void)
Returns the interface TypeID of the InferShapedTypeOpInterface.
MLIR_CAPI_EXPORTED void mlirMemoryEffectsOpInterfaceAttachFallbackModel(MlirContext ctx, MlirStringRef opName, MlirMemoryEffectsOpInterfaceCallbacks callbacks)
Attach a new FallbackModel for the MemoryEffectsOpInterface to the named operation.
static MlirStringRef mlirStringRefCreate(const char *str, size_t length)
Constructs a string reference from the pointer and length.
Definition Support.h:87
static bool mlirLogicalResultIsFailure(MlirLogicalResult res)
Checks if the given logical result represents a failure.
Definition Support.h:132
PyObjectRef< PyMlirContext > PyMlirContextRef
Wrapper around MlirContext.
Definition IRCore.h:198
static constexpr const char * inferReturnTypesDoc
static constexpr const char * inferReturnTypeComponentsDoc
nanobind::object classmethod(Func f, Args... args)
Helper for creating an @classmethod.
Definition IRCore.h:1878
Include the generated interface declarations.
std::string join(const Ts &...args)
Helper function to concatenate arguments into a std::string.
A logical result value, essentially a boolean with named states.
Definition Support.h:121
Callbacks for implementing MemoryEffectsOpInterface from external code.
Definition Interfaces.h:108
void(* construct)(void *userData)
Optional constructor for user data. Set to nullptr to disable it.
Definition Interfaces.h:110
void(* getEffects)(MlirOperation op, MlirMemoryEffectInstancesList effects, void *userData)
Get memory effects callback.
Definition Interfaces.h:114
void(* destruct)(void *userData)
Optional destructor for user data. Set to nullptr to disable it.
Definition Interfaces.h:112
A pointer to a sized fragment of a string, not necessarily null-terminated.
Definition Support.h:78