1 //===- IRAttributes.cpp - Exports builtin and standard attributes ---------===//
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 
11 #include "IRModule.h"
12 
13 #include "PybindUtils.h"
14 
15 #include "mlir-c/BuiltinAttributes.h"
16 #include "mlir-c/BuiltinTypes.h"
17 
18 namespace py = pybind11;
19 using namespace mlir;
20 using namespace mlir::python;
21 
22 using llvm::Optional;
23 using llvm::SmallVector;
24 using llvm::Twine;
25 
26 //------------------------------------------------------------------------------
27 // Docstrings (trivial, non-duplicated docstrings are included inline).
28 //------------------------------------------------------------------------------
29 
30 static const char kDenseElementsAttrGetDocstring[] =
31     R"(Gets a DenseElementsAttr from a Python buffer or array.
32 
33 When `type` is not provided, then some limited type inferencing is done based
34 on the buffer format. Support presently exists for 8/16/32/64 signed and
35 unsigned integers and float16/float32/float64. DenseElementsAttrs of these
36 types can also be converted back to a corresponding buffer.
37 
38 For conversions outside of these types, a `type=` must be explicitly provided
39 and the buffer contents must be bit-castable to the MLIR internal
40 representation:
41 
42   * Integer types (except for i1): the buffer must be byte aligned to the
43     next byte boundary.
44   * Floating point types: Must be bit-castable to the given floating point
45     size.
46   * i1 (bool): Bit packed into 8bit words where the bit pattern matches a
47     row major ordering. An arbitrary Numpy `bool_` array can be bit packed to
48     this specification with: `np.packbits(ary, axis=None, bitorder='little')`.
49 
50 If a single element buffer is passed (or for i1, a single byte with value 0
51 or 255), then a splat will be created.
52 
53 Args:
54   array: The array or buffer to convert.
55   signless: If inferring an appropriate MLIR type, use signless types for
56     integers (defaults True).
57   type: Skips inference of the MLIR element type and uses this instead. The
58     storage size must be consistent with the actual contents of the buffer.
59   shape: Overrides the shape of the buffer when constructing the MLIR
60     shaped type. This is needed when the physical and logical shape differ (as
61     for i1).
62   context: Explicit context, if not from context manager.
63 
64 Returns:
65   DenseElementsAttr on success.
66 
67 Raises:
68   ValueError: If the type of the buffer or array cannot be matched to an MLIR
69     type or if the buffer does not meet expectations.
70 )";
71 
72 namespace {
73 
74 static MlirStringRef toMlirStringRef(const std::string &s) {
75   return mlirStringRefCreate(s.data(), s.size());
76 }
77 
78 class PyAffineMapAttribute : public PyConcreteAttribute<PyAffineMapAttribute> {
79 public:
80   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAAffineMap;
81   static constexpr const char *pyClassName = "AffineMapAttr";
82   using PyConcreteAttribute::PyConcreteAttribute;
83 
84   static void bindDerived(ClassTy &c) {
85     c.def_static(
86         "get",
87         [](PyAffineMap &affineMap) {
88           MlirAttribute attr = mlirAffineMapAttrGet(affineMap.get());
89           return PyAffineMapAttribute(affineMap.getContext(), attr);
90         },
91         py::arg("affine_map"), "Gets an attribute wrapping an AffineMap.");
92   }
93 };
94 
95 template <typename T>
96 static T pyTryCast(py::handle object) {
97   try {
98     return object.cast<T>();
99   } catch (py::cast_error &err) {
100     std::string msg =
101         std::string(
102             "Invalid attribute when attempting to create an ArrayAttribute (") +
103         err.what() + ")";
104     throw py::cast_error(msg);
105   } catch (py::reference_cast_error &err) {
106     std::string msg = std::string("Invalid attribute (None?) when attempting "
107                                   "to create an ArrayAttribute (") +
108                       err.what() + ")";
109     throw py::cast_error(msg);
110   }
111 }
112 
113 class PyArrayAttribute : public PyConcreteAttribute<PyArrayAttribute> {
114 public:
115   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAArray;
116   static constexpr const char *pyClassName = "ArrayAttr";
117   using PyConcreteAttribute::PyConcreteAttribute;
118 
119   class PyArrayAttributeIterator {
120   public:
121     PyArrayAttributeIterator(PyAttribute attr) : attr(std::move(attr)) {}
122 
123     PyArrayAttributeIterator &dunderIter() { return *this; }
124 
125     PyAttribute dunderNext() {
126       if (nextIndex >= mlirArrayAttrGetNumElements(attr.get())) {
127         throw py::stop_iteration();
128       }
129       return PyAttribute(attr.getContext(),
130                          mlirArrayAttrGetElement(attr.get(), nextIndex++));
131     }
132 
133     static void bind(py::module &m) {
134       py::class_<PyArrayAttributeIterator>(m, "ArrayAttributeIterator",
135                                            py::module_local())
136           .def("__iter__", &PyArrayAttributeIterator::dunderIter)
137           .def("__next__", &PyArrayAttributeIterator::dunderNext);
138     }
139 
140   private:
141     PyAttribute attr;
142     int nextIndex = 0;
143   };
144 
145   PyAttribute getItem(intptr_t i) {
146     return PyAttribute(getContext(), mlirArrayAttrGetElement(*this, i));
147   }
148 
149   static void bindDerived(ClassTy &c) {
150     c.def_static(
151         "get",
152         [](py::list attributes, DefaultingPyMlirContext context) {
153           SmallVector<MlirAttribute> mlirAttributes;
154           mlirAttributes.reserve(py::len(attributes));
155           for (auto attribute : attributes) {
156             mlirAttributes.push_back(pyTryCast<PyAttribute>(attribute));
157           }
158           MlirAttribute attr = mlirArrayAttrGet(
159               context->get(), mlirAttributes.size(), mlirAttributes.data());
160           return PyArrayAttribute(context->getRef(), attr);
161         },
162         py::arg("attributes"), py::arg("context") = py::none(),
163         "Gets a uniqued Array attribute");
164     c.def("__getitem__",
165           [](PyArrayAttribute &arr, intptr_t i) {
166             if (i >= mlirArrayAttrGetNumElements(arr))
167               throw py::index_error("ArrayAttribute index out of range");
168             return arr.getItem(i);
169           })
170         .def("__len__",
171              [](const PyArrayAttribute &arr) {
172                return mlirArrayAttrGetNumElements(arr);
173              })
174         .def("__iter__", [](const PyArrayAttribute &arr) {
175           return PyArrayAttributeIterator(arr);
176         });
177     c.def("__add__", [](PyArrayAttribute arr, py::list extras) {
178       std::vector<MlirAttribute> attributes;
179       intptr_t numOldElements = mlirArrayAttrGetNumElements(arr);
180       attributes.reserve(numOldElements + py::len(extras));
181       for (intptr_t i = 0; i < numOldElements; ++i)
182         attributes.push_back(arr.getItem(i));
183       for (py::handle attr : extras)
184         attributes.push_back(pyTryCast<PyAttribute>(attr));
185       MlirAttribute arrayAttr = mlirArrayAttrGet(
186           arr.getContext()->get(), attributes.size(), attributes.data());
187       return PyArrayAttribute(arr.getContext(), arrayAttr);
188     });
189   }
190 };
191 
192 /// Float Point Attribute subclass - FloatAttr.
193 class PyFloatAttribute : public PyConcreteAttribute<PyFloatAttribute> {
194 public:
195   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAFloat;
196   static constexpr const char *pyClassName = "FloatAttr";
197   using PyConcreteAttribute::PyConcreteAttribute;
198 
199   static void bindDerived(ClassTy &c) {
200     c.def_static(
201         "get",
202         [](PyType &type, double value, DefaultingPyLocation loc) {
203           MlirAttribute attr = mlirFloatAttrDoubleGetChecked(loc, type, value);
204           // TODO: Rework error reporting once diagnostic engine is exposed
205           // in C API.
206           if (mlirAttributeIsNull(attr)) {
207             throw SetPyError(PyExc_ValueError,
208                              Twine("invalid '") +
209                                  py::repr(py::cast(type)).cast<std::string>() +
210                                  "' and expected floating point type.");
211           }
212           return PyFloatAttribute(type.getContext(), attr);
213         },
214         py::arg("type"), py::arg("value"), py::arg("loc") = py::none(),
215         "Gets an uniqued float point attribute associated to a type");
216     c.def_static(
217         "get_f32",
218         [](double value, DefaultingPyMlirContext context) {
219           MlirAttribute attr = mlirFloatAttrDoubleGet(
220               context->get(), mlirF32TypeGet(context->get()), value);
221           return PyFloatAttribute(context->getRef(), attr);
222         },
223         py::arg("value"), py::arg("context") = py::none(),
224         "Gets an uniqued float point attribute associated to a f32 type");
225     c.def_static(
226         "get_f64",
227         [](double value, DefaultingPyMlirContext context) {
228           MlirAttribute attr = mlirFloatAttrDoubleGet(
229               context->get(), mlirF64TypeGet(context->get()), value);
230           return PyFloatAttribute(context->getRef(), attr);
231         },
232         py::arg("value"), py::arg("context") = py::none(),
233         "Gets an uniqued float point attribute associated to a f64 type");
234     c.def_property_readonly(
235         "value",
236         [](PyFloatAttribute &self) {
237           return mlirFloatAttrGetValueDouble(self);
238         },
239         "Returns the value of the float point attribute");
240   }
241 };
242 
243 /// Integer Attribute subclass - IntegerAttr.
244 class PyIntegerAttribute : public PyConcreteAttribute<PyIntegerAttribute> {
245 public:
246   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAInteger;
247   static constexpr const char *pyClassName = "IntegerAttr";
248   using PyConcreteAttribute::PyConcreteAttribute;
249 
250   static void bindDerived(ClassTy &c) {
251     c.def_static(
252         "get",
253         [](PyType &type, int64_t value) {
254           MlirAttribute attr = mlirIntegerAttrGet(type, value);
255           return PyIntegerAttribute(type.getContext(), attr);
256         },
257         py::arg("type"), py::arg("value"),
258         "Gets an uniqued integer attribute associated to a type");
259     c.def_property_readonly(
260         "value",
261         [](PyIntegerAttribute &self) {
262           return mlirIntegerAttrGetValueInt(self);
263         },
264         "Returns the value of the integer attribute");
265   }
266 };
267 
268 /// Bool Attribute subclass - BoolAttr.
269 class PyBoolAttribute : public PyConcreteAttribute<PyBoolAttribute> {
270 public:
271   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsABool;
272   static constexpr const char *pyClassName = "BoolAttr";
273   using PyConcreteAttribute::PyConcreteAttribute;
274 
275   static void bindDerived(ClassTy &c) {
276     c.def_static(
277         "get",
278         [](bool value, DefaultingPyMlirContext context) {
279           MlirAttribute attr = mlirBoolAttrGet(context->get(), value);
280           return PyBoolAttribute(context->getRef(), attr);
281         },
282         py::arg("value"), py::arg("context") = py::none(),
283         "Gets an uniqued bool attribute");
284     c.def_property_readonly(
285         "value",
286         [](PyBoolAttribute &self) { return mlirBoolAttrGetValue(self); },
287         "Returns the value of the bool attribute");
288   }
289 };
290 
291 class PyFlatSymbolRefAttribute
292     : public PyConcreteAttribute<PyFlatSymbolRefAttribute> {
293 public:
294   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAFlatSymbolRef;
295   static constexpr const char *pyClassName = "FlatSymbolRefAttr";
296   using PyConcreteAttribute::PyConcreteAttribute;
297 
298   static void bindDerived(ClassTy &c) {
299     c.def_static(
300         "get",
301         [](std::string value, DefaultingPyMlirContext context) {
302           MlirAttribute attr =
303               mlirFlatSymbolRefAttrGet(context->get(), toMlirStringRef(value));
304           return PyFlatSymbolRefAttribute(context->getRef(), attr);
305         },
306         py::arg("value"), py::arg("context") = py::none(),
307         "Gets a uniqued FlatSymbolRef attribute");
308     c.def_property_readonly(
309         "value",
310         [](PyFlatSymbolRefAttribute &self) {
311           MlirStringRef stringRef = mlirFlatSymbolRefAttrGetValue(self);
312           return py::str(stringRef.data, stringRef.length);
313         },
314         "Returns the value of the FlatSymbolRef attribute as a string");
315   }
316 };
317 
318 class PyStringAttribute : public PyConcreteAttribute<PyStringAttribute> {
319 public:
320   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAString;
321   static constexpr const char *pyClassName = "StringAttr";
322   using PyConcreteAttribute::PyConcreteAttribute;
323 
324   static void bindDerived(ClassTy &c) {
325     c.def_static(
326         "get",
327         [](std::string value, DefaultingPyMlirContext context) {
328           MlirAttribute attr =
329               mlirStringAttrGet(context->get(), toMlirStringRef(value));
330           return PyStringAttribute(context->getRef(), attr);
331         },
332         py::arg("value"), py::arg("context") = py::none(),
333         "Gets a uniqued string attribute");
334     c.def_static(
335         "get_typed",
336         [](PyType &type, std::string value) {
337           MlirAttribute attr =
338               mlirStringAttrTypedGet(type, toMlirStringRef(value));
339           return PyStringAttribute(type.getContext(), attr);
340         },
341         py::arg("type"), py::arg("value"),
342         "Gets a uniqued string attribute associated to a type");
343     c.def_property_readonly(
344         "value",
345         [](PyStringAttribute &self) {
346           MlirStringRef stringRef = mlirStringAttrGetValue(self);
347           return py::str(stringRef.data, stringRef.length);
348         },
349         "Returns the value of the string attribute");
350   }
351 };
352 
353 // TODO: Support construction of string elements.
354 class PyDenseElementsAttribute
355     : public PyConcreteAttribute<PyDenseElementsAttribute> {
356 public:
357   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseElements;
358   static constexpr const char *pyClassName = "DenseElementsAttr";
359   using PyConcreteAttribute::PyConcreteAttribute;
360 
361   static PyDenseElementsAttribute
362   getFromBuffer(py::buffer array, bool signless, Optional<PyType> explicitType,
363                 Optional<std::vector<int64_t>> explicitShape,
364                 DefaultingPyMlirContext contextWrapper) {
365     // Request a contiguous view. In exotic cases, this will cause a copy.
366     int flags = PyBUF_C_CONTIGUOUS | PyBUF_FORMAT;
367     Py_buffer *view = new Py_buffer();
368     if (PyObject_GetBuffer(array.ptr(), view, flags) != 0) {
369       delete view;
370       throw py::error_already_set();
371     }
372     py::buffer_info arrayInfo(view);
373     SmallVector<int64_t> shape;
374     if (explicitShape) {
375       shape.append(explicitShape->begin(), explicitShape->end());
376     } else {
377       shape.append(arrayInfo.shape.begin(),
378                    arrayInfo.shape.begin() + arrayInfo.ndim);
379     }
380 
381     MlirAttribute encodingAttr = mlirAttributeGetNull();
382     MlirContext context = contextWrapper->get();
383 
384     // Detect format codes that are suitable for bulk loading. This includes
385     // all byte aligned integer and floating point types up to 8 bytes.
386     // Notably, this excludes, bool (which needs to be bit-packed) and
387     // other exotics which do not have a direct representation in the buffer
388     // protocol (i.e. complex, etc).
389     Optional<MlirType> bulkLoadElementType;
390     if (explicitType) {
391       bulkLoadElementType = *explicitType;
392     } else if (arrayInfo.format == "f") {
393       // f32
394       assert(arrayInfo.itemsize == 4 && "mismatched array itemsize");
395       bulkLoadElementType = mlirF32TypeGet(context);
396     } else if (arrayInfo.format == "d") {
397       // f64
398       assert(arrayInfo.itemsize == 8 && "mismatched array itemsize");
399       bulkLoadElementType = mlirF64TypeGet(context);
400     } else if (arrayInfo.format == "e") {
401       // f16
402       assert(arrayInfo.itemsize == 2 && "mismatched array itemsize");
403       bulkLoadElementType = mlirF16TypeGet(context);
404     } else if (isSignedIntegerFormat(arrayInfo.format)) {
405       if (arrayInfo.itemsize == 4) {
406         // i32
407         bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 32)
408                                        : mlirIntegerTypeSignedGet(context, 32);
409       } else if (arrayInfo.itemsize == 8) {
410         // i64
411         bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 64)
412                                        : mlirIntegerTypeSignedGet(context, 64);
413       } else if (arrayInfo.itemsize == 1) {
414         // i8
415         bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 8)
416                                        : mlirIntegerTypeSignedGet(context, 8);
417       } else if (arrayInfo.itemsize == 2) {
418         // i16
419         bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 16)
420                                        : mlirIntegerTypeSignedGet(context, 16);
421       }
422     } else if (isUnsignedIntegerFormat(arrayInfo.format)) {
423       if (arrayInfo.itemsize == 4) {
424         // unsigned i32
425         bulkLoadElementType = signless
426                                   ? mlirIntegerTypeGet(context, 32)
427                                   : mlirIntegerTypeUnsignedGet(context, 32);
428       } else if (arrayInfo.itemsize == 8) {
429         // unsigned i64
430         bulkLoadElementType = signless
431                                   ? mlirIntegerTypeGet(context, 64)
432                                   : mlirIntegerTypeUnsignedGet(context, 64);
433       } else if (arrayInfo.itemsize == 1) {
434         // i8
435         bulkLoadElementType = signless ? mlirIntegerTypeGet(context, 8)
436                                        : mlirIntegerTypeUnsignedGet(context, 8);
437       } else if (arrayInfo.itemsize == 2) {
438         // i16
439         bulkLoadElementType = signless
440                                   ? mlirIntegerTypeGet(context, 16)
441                                   : mlirIntegerTypeUnsignedGet(context, 16);
442       }
443     }
444     if (bulkLoadElementType) {
445       auto shapedType = mlirRankedTensorTypeGet(
446           shape.size(), shape.data(), *bulkLoadElementType, encodingAttr);
447       size_t rawBufferSize = arrayInfo.size * arrayInfo.itemsize;
448       MlirAttribute attr = mlirDenseElementsAttrRawBufferGet(
449           shapedType, rawBufferSize, arrayInfo.ptr);
450       if (mlirAttributeIsNull(attr)) {
451         throw std::invalid_argument(
452             "DenseElementsAttr could not be constructed from the given buffer. "
453             "This may mean that the Python buffer layout does not match that "
454             "MLIR expected layout and is a bug.");
455       }
456       return PyDenseElementsAttribute(contextWrapper->getRef(), attr);
457     }
458 
459     throw std::invalid_argument(
460         std::string("unimplemented array format conversion from format: ") +
461         arrayInfo.format);
462   }
463 
464   static PyDenseElementsAttribute getSplat(const PyType &shapedType,
465                                            PyAttribute &elementAttr) {
466     auto contextWrapper =
467         PyMlirContext::forContext(mlirTypeGetContext(shapedType));
468     if (!mlirAttributeIsAInteger(elementAttr) &&
469         !mlirAttributeIsAFloat(elementAttr)) {
470       std::string message = "Illegal element type for DenseElementsAttr: ";
471       message.append(py::repr(py::cast(elementAttr)));
472       throw SetPyError(PyExc_ValueError, message);
473     }
474     if (!mlirTypeIsAShaped(shapedType) ||
475         !mlirShapedTypeHasStaticShape(shapedType)) {
476       std::string message =
477           "Expected a static ShapedType for the shaped_type parameter: ";
478       message.append(py::repr(py::cast(shapedType)));
479       throw SetPyError(PyExc_ValueError, message);
480     }
481     MlirType shapedElementType = mlirShapedTypeGetElementType(shapedType);
482     MlirType attrType = mlirAttributeGetType(elementAttr);
483     if (!mlirTypeEqual(shapedElementType, attrType)) {
484       std::string message =
485           "Shaped element type and attribute type must be equal: shaped=";
486       message.append(py::repr(py::cast(shapedType)));
487       message.append(", element=");
488       message.append(py::repr(py::cast(elementAttr)));
489       throw SetPyError(PyExc_ValueError, message);
490     }
491 
492     MlirAttribute elements =
493         mlirDenseElementsAttrSplatGet(shapedType, elementAttr);
494     return PyDenseElementsAttribute(contextWrapper->getRef(), elements);
495   }
496 
497   intptr_t dunderLen() { return mlirElementsAttrGetNumElements(*this); }
498 
499   py::buffer_info accessBuffer() {
500     if (mlirDenseElementsAttrIsSplat(*this)) {
501       // TODO: Currently crashes the program.
502       // Reported as https://github.com/pybind/pybind11/issues/3336
503       throw std::invalid_argument(
504           "unsupported data type for conversion to Python buffer");
505     }
506 
507     MlirType shapedType = mlirAttributeGetType(*this);
508     MlirType elementType = mlirShapedTypeGetElementType(shapedType);
509     std::string format;
510 
511     if (mlirTypeIsAF32(elementType)) {
512       // f32
513       return bufferInfo<float>(shapedType);
514     }
515     if (mlirTypeIsAF64(elementType)) {
516       // f64
517       return bufferInfo<double>(shapedType);
518     }
519     if (mlirTypeIsAF16(elementType)) {
520       // f16
521       return bufferInfo<uint16_t>(shapedType, "e");
522     }
523     if (mlirTypeIsAInteger(elementType) &&
524         mlirIntegerTypeGetWidth(elementType) == 32) {
525       if (mlirIntegerTypeIsSignless(elementType) ||
526           mlirIntegerTypeIsSigned(elementType)) {
527         // i32
528         return bufferInfo<int32_t>(shapedType);
529       }
530       if (mlirIntegerTypeIsUnsigned(elementType)) {
531         // unsigned i32
532         return bufferInfo<uint32_t>(shapedType);
533       }
534     } else if (mlirTypeIsAInteger(elementType) &&
535                mlirIntegerTypeGetWidth(elementType) == 64) {
536       if (mlirIntegerTypeIsSignless(elementType) ||
537           mlirIntegerTypeIsSigned(elementType)) {
538         // i64
539         return bufferInfo<int64_t>(shapedType);
540       }
541       if (mlirIntegerTypeIsUnsigned(elementType)) {
542         // unsigned i64
543         return bufferInfo<uint64_t>(shapedType);
544       }
545     } else if (mlirTypeIsAInteger(elementType) &&
546                mlirIntegerTypeGetWidth(elementType) == 8) {
547       if (mlirIntegerTypeIsSignless(elementType) ||
548           mlirIntegerTypeIsSigned(elementType)) {
549         // i8
550         return bufferInfo<int8_t>(shapedType);
551       }
552       if (mlirIntegerTypeIsUnsigned(elementType)) {
553         // unsigned i8
554         return bufferInfo<uint8_t>(shapedType);
555       }
556     } else if (mlirTypeIsAInteger(elementType) &&
557                mlirIntegerTypeGetWidth(elementType) == 16) {
558       if (mlirIntegerTypeIsSignless(elementType) ||
559           mlirIntegerTypeIsSigned(elementType)) {
560         // i16
561         return bufferInfo<int16_t>(shapedType);
562       }
563       if (mlirIntegerTypeIsUnsigned(elementType)) {
564         // unsigned i16
565         return bufferInfo<uint16_t>(shapedType);
566       }
567     }
568 
569     // TODO: Currently crashes the program.
570     // Reported as https://github.com/pybind/pybind11/issues/3336
571     throw std::invalid_argument(
572         "unsupported data type for conversion to Python buffer");
573   }
574 
575   static void bindDerived(ClassTy &c) {
576     c.def("__len__", &PyDenseElementsAttribute::dunderLen)
577         .def_static("get", PyDenseElementsAttribute::getFromBuffer,
578                     py::arg("array"), py::arg("signless") = true,
579                     py::arg("type") = py::none(), py::arg("shape") = py::none(),
580                     py::arg("context") = py::none(),
581                     kDenseElementsAttrGetDocstring)
582         .def_static("get_splat", PyDenseElementsAttribute::getSplat,
583                     py::arg("shaped_type"), py::arg("element_attr"),
584                     "Gets a DenseElementsAttr where all values are the same")
585         .def_property_readonly("is_splat",
586                                [](PyDenseElementsAttribute &self) -> bool {
587                                  return mlirDenseElementsAttrIsSplat(self);
588                                })
589         .def_buffer(&PyDenseElementsAttribute::accessBuffer);
590   }
591 
592 private:
593   static bool isUnsignedIntegerFormat(const std::string &format) {
594     if (format.empty())
595       return false;
596     char code = format[0];
597     return code == 'I' || code == 'B' || code == 'H' || code == 'L' ||
598            code == 'Q';
599   }
600 
601   static bool isSignedIntegerFormat(const std::string &format) {
602     if (format.empty())
603       return false;
604     char code = format[0];
605     return code == 'i' || code == 'b' || code == 'h' || code == 'l' ||
606            code == 'q';
607   }
608 
609   template <typename Type>
610   py::buffer_info bufferInfo(MlirType shapedType,
611                              const char *explicitFormat = nullptr) {
612     intptr_t rank = mlirShapedTypeGetRank(shapedType);
613     // Prepare the data for the buffer_info.
614     // Buffer is configured for read-only access below.
615     Type *data = static_cast<Type *>(
616         const_cast<void *>(mlirDenseElementsAttrGetRawData(*this)));
617     // Prepare the shape for the buffer_info.
618     SmallVector<intptr_t, 4> shape;
619     for (intptr_t i = 0; i < rank; ++i)
620       shape.push_back(mlirShapedTypeGetDimSize(shapedType, i));
621     // Prepare the strides for the buffer_info.
622     SmallVector<intptr_t, 4> strides;
623     intptr_t strideFactor = 1;
624     for (intptr_t i = 1; i < rank; ++i) {
625       strideFactor = 1;
626       for (intptr_t j = i; j < rank; ++j) {
627         strideFactor *= mlirShapedTypeGetDimSize(shapedType, j);
628       }
629       strides.push_back(sizeof(Type) * strideFactor);
630     }
631     strides.push_back(sizeof(Type));
632     std::string format;
633     if (explicitFormat) {
634       format = explicitFormat;
635     } else {
636       format = py::format_descriptor<Type>::format();
637     }
638     return py::buffer_info(data, sizeof(Type), format, rank, shape, strides,
639                            /*readonly=*/true);
640   }
641 }; // namespace
642 
643 /// Refinement of the PyDenseElementsAttribute for attributes containing integer
644 /// (and boolean) values. Supports element access.
645 class PyDenseIntElementsAttribute
646     : public PyConcreteAttribute<PyDenseIntElementsAttribute,
647                                  PyDenseElementsAttribute> {
648 public:
649   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseIntElements;
650   static constexpr const char *pyClassName = "DenseIntElementsAttr";
651   using PyConcreteAttribute::PyConcreteAttribute;
652 
653   /// Returns the element at the given linear position. Asserts if the index is
654   /// out of range.
655   py::int_ dunderGetItem(intptr_t pos) {
656     if (pos < 0 || pos >= dunderLen()) {
657       throw SetPyError(PyExc_IndexError,
658                        "attempt to access out of bounds element");
659     }
660 
661     MlirType type = mlirAttributeGetType(*this);
662     type = mlirShapedTypeGetElementType(type);
663     assert(mlirTypeIsAInteger(type) &&
664            "expected integer element type in dense int elements attribute");
665     // Dispatch element extraction to an appropriate C function based on the
666     // elemental type of the attribute. py::int_ is implicitly constructible
667     // from any C++ integral type and handles bitwidth correctly.
668     // TODO: consider caching the type properties in the constructor to avoid
669     // querying them on each element access.
670     unsigned width = mlirIntegerTypeGetWidth(type);
671     bool isUnsigned = mlirIntegerTypeIsUnsigned(type);
672     if (isUnsigned) {
673       if (width == 1) {
674         return mlirDenseElementsAttrGetBoolValue(*this, pos);
675       }
676       if (width == 8) {
677         return mlirDenseElementsAttrGetUInt8Value(*this, pos);
678       }
679       if (width == 16) {
680         return mlirDenseElementsAttrGetUInt16Value(*this, pos);
681       }
682       if (width == 32) {
683         return mlirDenseElementsAttrGetUInt32Value(*this, pos);
684       }
685       if (width == 64) {
686         return mlirDenseElementsAttrGetUInt64Value(*this, pos);
687       }
688     } else {
689       if (width == 1) {
690         return mlirDenseElementsAttrGetBoolValue(*this, pos);
691       }
692       if (width == 8) {
693         return mlirDenseElementsAttrGetInt8Value(*this, pos);
694       }
695       if (width == 16) {
696         return mlirDenseElementsAttrGetInt16Value(*this, pos);
697       }
698       if (width == 32) {
699         return mlirDenseElementsAttrGetInt32Value(*this, pos);
700       }
701       if (width == 64) {
702         return mlirDenseElementsAttrGetInt64Value(*this, pos);
703       }
704     }
705     throw SetPyError(PyExc_TypeError, "Unsupported integer type");
706   }
707 
708   static void bindDerived(ClassTy &c) {
709     c.def("__getitem__", &PyDenseIntElementsAttribute::dunderGetItem);
710   }
711 };
712 
713 class PyDictAttribute : public PyConcreteAttribute<PyDictAttribute> {
714 public:
715   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADictionary;
716   static constexpr const char *pyClassName = "DictAttr";
717   using PyConcreteAttribute::PyConcreteAttribute;
718 
719   intptr_t dunderLen() { return mlirDictionaryAttrGetNumElements(*this); }
720 
721   bool dunderContains(const std::string &name) {
722     return !mlirAttributeIsNull(
723         mlirDictionaryAttrGetElementByName(*this, toMlirStringRef(name)));
724   }
725 
726   static void bindDerived(ClassTy &c) {
727     c.def("__contains__", &PyDictAttribute::dunderContains);
728     c.def("__len__", &PyDictAttribute::dunderLen);
729     c.def_static(
730         "get",
731         [](py::dict attributes, DefaultingPyMlirContext context) {
732           SmallVector<MlirNamedAttribute> mlirNamedAttributes;
733           mlirNamedAttributes.reserve(attributes.size());
734           for (auto &it : attributes) {
735             auto &mlirAttr = it.second.cast<PyAttribute &>();
736             auto name = it.first.cast<std::string>();
737             mlirNamedAttributes.push_back(mlirNamedAttributeGet(
738                 mlirIdentifierGet(mlirAttributeGetContext(mlirAttr),
739                                   toMlirStringRef(name)),
740                 mlirAttr));
741           }
742           MlirAttribute attr =
743               mlirDictionaryAttrGet(context->get(), mlirNamedAttributes.size(),
744                                     mlirNamedAttributes.data());
745           return PyDictAttribute(context->getRef(), attr);
746         },
747         py::arg("value") = py::dict(), py::arg("context") = py::none(),
748         "Gets an uniqued dict attribute");
749     c.def("__getitem__", [](PyDictAttribute &self, const std::string &name) {
750       MlirAttribute attr =
751           mlirDictionaryAttrGetElementByName(self, toMlirStringRef(name));
752       if (mlirAttributeIsNull(attr)) {
753         throw SetPyError(PyExc_KeyError,
754                          "attempt to access a non-existent attribute");
755       }
756       return PyAttribute(self.getContext(), attr);
757     });
758     c.def("__getitem__", [](PyDictAttribute &self, intptr_t index) {
759       if (index < 0 || index >= self.dunderLen()) {
760         throw SetPyError(PyExc_IndexError,
761                          "attempt to access out of bounds attribute");
762       }
763       MlirNamedAttribute namedAttr = mlirDictionaryAttrGetElement(self, index);
764       return PyNamedAttribute(
765           namedAttr.attribute,
766           std::string(mlirIdentifierStr(namedAttr.name).data));
767     });
768   }
769 };
770 
771 /// Refinement of PyDenseElementsAttribute for attributes containing
772 /// floating-point values. Supports element access.
773 class PyDenseFPElementsAttribute
774     : public PyConcreteAttribute<PyDenseFPElementsAttribute,
775                                  PyDenseElementsAttribute> {
776 public:
777   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsADenseFPElements;
778   static constexpr const char *pyClassName = "DenseFPElementsAttr";
779   using PyConcreteAttribute::PyConcreteAttribute;
780 
781   py::float_ dunderGetItem(intptr_t pos) {
782     if (pos < 0 || pos >= dunderLen()) {
783       throw SetPyError(PyExc_IndexError,
784                        "attempt to access out of bounds element");
785     }
786 
787     MlirType type = mlirAttributeGetType(*this);
788     type = mlirShapedTypeGetElementType(type);
789     // Dispatch element extraction to an appropriate C function based on the
790     // elemental type of the attribute. py::float_ is implicitly constructible
791     // from float and double.
792     // TODO: consider caching the type properties in the constructor to avoid
793     // querying them on each element access.
794     if (mlirTypeIsAF32(type)) {
795       return mlirDenseElementsAttrGetFloatValue(*this, pos);
796     }
797     if (mlirTypeIsAF64(type)) {
798       return mlirDenseElementsAttrGetDoubleValue(*this, pos);
799     }
800     throw SetPyError(PyExc_TypeError, "Unsupported floating-point type");
801   }
802 
803   static void bindDerived(ClassTy &c) {
804     c.def("__getitem__", &PyDenseFPElementsAttribute::dunderGetItem);
805   }
806 };
807 
808 class PyTypeAttribute : public PyConcreteAttribute<PyTypeAttribute> {
809 public:
810   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAType;
811   static constexpr const char *pyClassName = "TypeAttr";
812   using PyConcreteAttribute::PyConcreteAttribute;
813 
814   static void bindDerived(ClassTy &c) {
815     c.def_static(
816         "get",
817         [](PyType value, DefaultingPyMlirContext context) {
818           MlirAttribute attr = mlirTypeAttrGet(value.get());
819           return PyTypeAttribute(context->getRef(), attr);
820         },
821         py::arg("value"), py::arg("context") = py::none(),
822         "Gets a uniqued Type attribute");
823     c.def_property_readonly("value", [](PyTypeAttribute &self) {
824       return PyType(self.getContext()->getRef(),
825                     mlirTypeAttrGetValue(self.get()));
826     });
827   }
828 };
829 
830 /// Unit Attribute subclass. Unit attributes don't have values.
831 class PyUnitAttribute : public PyConcreteAttribute<PyUnitAttribute> {
832 public:
833   static constexpr IsAFunctionTy isaFunction = mlirAttributeIsAUnit;
834   static constexpr const char *pyClassName = "UnitAttr";
835   using PyConcreteAttribute::PyConcreteAttribute;
836 
837   static void bindDerived(ClassTy &c) {
838     c.def_static(
839         "get",
840         [](DefaultingPyMlirContext context) {
841           return PyUnitAttribute(context->getRef(),
842                                  mlirUnitAttrGet(context->get()));
843         },
844         py::arg("context") = py::none(), "Create a Unit attribute.");
845   }
846 };
847 
848 } // namespace
849 
850 void mlir::python::populateIRAttributes(py::module &m) {
851   PyAffineMapAttribute::bind(m);
852   PyArrayAttribute::bind(m);
853   PyArrayAttribute::PyArrayAttributeIterator::bind(m);
854   PyBoolAttribute::bind(m);
855   PyDenseElementsAttribute::bind(m);
856   PyDenseFPElementsAttribute::bind(m);
857   PyDenseIntElementsAttribute::bind(m);
858   PyDictAttribute::bind(m);
859   PyFlatSymbolRefAttribute::bind(m);
860   PyFloatAttribute::bind(m);
861   PyIntegerAttribute::bind(m);
862   PyStringAttribute::bind(m);
863   PyTypeAttribute::bind(m);
864   PyUnitAttribute::bind(m);
865 }
866