1//===- BuiltinAttributes.h - MLIR Builtin Attribute Classes -----*- C++ -*-===//
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#ifndef MLIR_IR_BUILTINATTRIBUTES_H
10#define MLIR_IR_BUILTINATTRIBUTES_H
11
12#include "mlir/IR/BuiltinAttributeInterfaces.h"
13#include "mlir/Support/Complex.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/Sequence.h"
16#include <optional>
17
18namespace mlir {
19class AffineMap;
20class AsmResourceBlob;
21class BoolAttr;
22class BuiltinDialect;
23class DenseIntElementsAttr;
24template <typename T>
25struct DialectResourceBlobHandle;
26class FlatSymbolRefAttr;
27class FunctionType;
28class IntegerSet;
29class IntegerType;
30class Location;
31class Operation;
32class RankedTensorType;
33
34namespace detail {
35struct DenseTypedElementsAttrStorage;
36struct DenseStringElementsAttrStorage;
37struct StringAttrStorage;
38} // namespace detail
39
40//===----------------------------------------------------------------------===//
41// Elements Attributes
42//===----------------------------------------------------------------------===//
43
44namespace detail {
45/// Pair of raw pointer and a boolean flag of whether the pointer holds a splat,
46using DenseIterPtrAndSplat = std::pair<const char *, bool>;
47
48/// Impl iterator for indexed DenseElementsAttr iterators that records a data
49/// pointer and data index that is adjusted for the case of a splat attribute.
50template <typename ConcreteT, typename T, typename PointerT = T *,
51 typename ReferenceT = T &>
52class DenseElementIndexedIteratorImpl
53 : public llvm::indexed_accessor_iterator<ConcreteT, DenseIterPtrAndSplat, T,
54 PointerT, ReferenceT> {
55protected:
56 DenseElementIndexedIteratorImpl(const char *data, bool isSplat,
57 size_t dataIndex)
58 : llvm::indexed_accessor_iterator<ConcreteT, DenseIterPtrAndSplat, T,
59 PointerT, ReferenceT>({data, isSplat},
60 dataIndex) {}
61
62 /// Return the current index for this iterator, adjusted for the case of a
63 /// splat.
64 ptrdiff_t getDataIndex() const {
65 bool isSplat = this->base.second;
66 return isSplat ? 0 : this->index;
67 }
68
69 /// Return the data base pointer.
70 const char *getData() const { return this->base.first; }
71};
72
73/// Type trait detector that checks if a given type T is a complex type.
74template <typename T>
75struct is_complex_t : public std::false_type {};
76template <typename T>
77struct is_complex_t<std::complex<T>> : public std::true_type {};
78template <typename T>
79struct is_complex_t<mlir::NonFloatComplex<T>> : public std::true_type {};
80} // namespace detail
81
82/// An attribute that represents a reference to a dense vector or tensor
83/// object.
84class DenseElementsAttr : public Attribute {
85public:
86 using Attribute::Attribute;
87
88 /// Allow implicit conversion to ElementsAttr.
89 operator ElementsAttr() const { return cast_if_present<ElementsAttr>(Val: *this); }
90 /// Allow implicit conversion to TypedAttr.
91 operator TypedAttr() const { return ElementsAttr(*this); }
92
93 /// Type trait used to check if the given type T is a potentially valid C++
94 /// floating point type that can be used to access the underlying element
95 /// types of a DenseElementsAttr.
96 template <typename T>
97 struct is_valid_cpp_fp_type {
98 /// The type is a valid floating point type if it is a builtin floating
99 /// point type, or is a potentially user defined floating point type. The
100 /// latter allows for supporting users that have custom types defined for
101 /// bfloat16/half/etc.
102 static constexpr bool value = llvm::is_one_of<T, float, double>::value ||
103 (std::numeric_limits<T>::is_specialized &&
104 !std::numeric_limits<T>::is_integer);
105 };
106
107 /// Method for support type inquiry through isa, cast and dyn_cast.
108 static bool classof(Attribute attr);
109
110 /// Constructs a dense elements attribute from an array of element values.
111 /// Each element attribute value is expected to be an element of 'type'.
112 /// 'type' must be a vector or tensor with static shape. If the element of
113 /// `type` is non-integer/index/float it is assumed to be a string type.
114 static DenseElementsAttr get(ShapedType type, ArrayRef<Attribute> values);
115
116 /// Constructs a dense integer elements attribute from an array of integer
117 /// or floating-point values. Each value is expected to be the same bitwidth
118 /// of the element type of 'type'. 'type' must be a vector or tensor with
119 /// static shape.
120 template <typename T,
121 typename = std::enable_if_t<std::numeric_limits<T>::is_integer ||
122 is_valid_cpp_fp_type<T>::value>>
123 static DenseElementsAttr get(const ShapedType &type, ArrayRef<T> values) {
124 const char *data = reinterpret_cast<const char *>(values.data());
125 return getRawIntOrFloat(
126 type, data: ArrayRef<char>(data, values.size() * sizeof(T)), dataEltSize: sizeof(T),
127 isInt: std::numeric_limits<T>::is_integer, isSigned: std::numeric_limits<T>::is_signed);
128 }
129
130 /// Constructs a dense integer elements attribute from a single element.
131 template <typename T,
132 typename = std::enable_if_t<std::numeric_limits<T>::is_integer ||
133 is_valid_cpp_fp_type<T>::value ||
134 detail::is_complex_t<T>::value>>
135 static DenseElementsAttr get(const ShapedType &type, T value) {
136 return get(type, llvm::ArrayRef(value));
137 }
138
139 /// Constructs a dense complex elements attribute from an array of complex
140 /// values. Each value is expected to be the same bitwidth of the element type
141 /// of 'type'. 'type' must be a vector or tensor with static shape.
142 template <
143 typename T, typename ElementT = typename T::value_type,
144 typename = std::enable_if_t<detail::is_complex_t<T>::value &&
145 (std::numeric_limits<ElementT>::is_integer ||
146 is_valid_cpp_fp_type<ElementT>::value)>>
147 static DenseElementsAttr get(const ShapedType &type, ArrayRef<T> values) {
148 const char *data = reinterpret_cast<const char *>(values.data());
149 return getRawComplex(type, data: ArrayRef<char>(data, values.size() * sizeof(T)),
150 dataEltSize: sizeof(T), isInt: std::numeric_limits<ElementT>::is_integer,
151 isSigned: std::numeric_limits<ElementT>::is_signed);
152 }
153
154 /// Overload of the above 'get' method that is specialized for boolean values.
155 static DenseElementsAttr get(ShapedType type, ArrayRef<bool> values);
156
157 /// Overload of the above 'get' method that is specialized for StringRef
158 /// values.
159 static DenseElementsAttr get(ShapedType type, ArrayRef<StringRef> values);
160
161 /// Constructs a dense integer elements attribute from an array of APInt
162 /// values. Each APInt value is expected to have the same bitwidth as the
163 /// element type of 'type'. 'type' must be a vector or tensor with static
164 /// shape.
165 static DenseElementsAttr get(ShapedType type, ArrayRef<APInt> values);
166
167 /// Constructs a dense complex elements attribute from an array of APInt
168 /// values. Each APInt value is expected to have the same bitwidth as the
169 /// element type of 'type'. 'type' must be a vector or tensor with static
170 /// shape.
171 static DenseElementsAttr get(ShapedType type,
172 ArrayRef<mlir::Complex<APInt>> values);
173
174 /// Constructs a dense float elements attribute from an array of APFloat
175 /// values. Each APFloat value is expected to have the same bitwidth as the
176 /// element type of 'type'. 'type' must be a vector or tensor with static
177 /// shape.
178 static DenseElementsAttr get(ShapedType type, ArrayRef<APFloat> values);
179
180 /// Constructs a dense complex elements attribute from an array of APFloat
181 /// values. Each APFloat value is expected to have the same bitwidth as the
182 /// element type of 'type'. 'type' must be a vector or tensor with static
183 /// shape.
184 static DenseElementsAttr get(ShapedType type,
185 ArrayRef<mlir::Complex<APFloat>> values);
186
187 /// Construct a dense elements attribute for an initializer_list of values.
188 /// Each value is expected to be the same bitwidth of the element type of
189 /// 'type'. 'type' must be a vector or tensor with static shape.
190 template <typename T>
191 static DenseElementsAttr get(const ShapedType &type,
192 const std::initializer_list<T> &list) {
193 return get(type, ArrayRef<T>(list));
194 }
195
196 /// Construct a dense elements attribute from a raw buffer representing the
197 /// data for this attribute. Users are encouraged to use one of the
198 /// constructors above, which provide more safeties. However, this
199 /// constructor is useful for tools which may want to interop and can
200 /// follow the precise definition.
201 ///
202 /// The format of the raw buffer is a densely packed array of values that
203 /// can be bitcast to the storage format of the element type specified.
204 /// Types that are not byte aligned will be rounded up to the next byte.
205 static DenseElementsAttr getFromRawBuffer(ShapedType type,
206 ArrayRef<char> rawBuffer);
207
208 /// Returns true if the given buffer is a valid raw buffer for the given type.
209 static bool isValidRawBuffer(ShapedType type, ArrayRef<char> rawBuffer);
210
211 //===--------------------------------------------------------------------===//
212 // Iterators
213 //===--------------------------------------------------------------------===//
214
215 /// The iterator range over the given iterator type T.
216 template <typename IteratorT>
217 using iterator_range_impl = detail::ElementsAttrRange<IteratorT>;
218
219 /// The iterator for the given element type T.
220 template <typename T, typename AttrT = DenseElementsAttr>
221 using iterator = decltype(std::declval<AttrT>().template value_begin<T>());
222 /// The iterator range over the given element T.
223 template <typename T, typename AttrT = DenseElementsAttr>
224 using iterator_range =
225 decltype(std::declval<AttrT>().template getValues<T>());
226
227 /// A utility iterator that allows walking over the internal Attribute values
228 /// of a DenseElementsAttr.
229 class AttributeElementIterator
230 : public llvm::indexed_accessor_iterator<AttributeElementIterator,
231 const void *, Attribute,
232 Attribute, Attribute> {
233 public:
234 /// Accesses the Attribute value at this iterator position.
235 Attribute operator*() const;
236
237 private:
238 friend DenseElementsAttr;
239
240 /// Constructs a new iterator.
241 AttributeElementIterator(DenseElementsAttr attr, size_t index);
242 };
243
244 /// Iterator for walking raw element values of the specified type 'T', which
245 /// may be any c++ data type matching the stored representation: int32_t,
246 /// float, etc.
247 template <typename T>
248 class ElementIterator
249 : public detail::DenseElementIndexedIteratorImpl<ElementIterator<T>,
250 const T> {
251 public:
252 /// Accesses the raw value at this iterator position.
253 const T &operator*() const {
254 return reinterpret_cast<const T *>(this->getData())[this->getDataIndex()];
255 }
256
257 private:
258 friend DenseElementsAttr;
259
260 /// Constructs a new iterator.
261 ElementIterator(const char *data, bool isSplat, size_t dataIndex)
262 : detail::DenseElementIndexedIteratorImpl<ElementIterator<T>, const T>(
263 data, isSplat, dataIndex) {}
264 };
265
266 /// A utility iterator that allows walking over the internal bool values.
267 class BoolElementIterator
268 : public detail::DenseElementIndexedIteratorImpl<BoolElementIterator,
269 bool, bool, bool> {
270 public:
271 /// Accesses the bool value at this iterator position.
272 bool operator*() const;
273
274 private:
275 friend DenseElementsAttr;
276
277 /// Constructs a new iterator.
278 BoolElementIterator(DenseElementsAttr attr, size_t dataIndex);
279 };
280
281 /// A utility iterator that allows walking over the internal raw APInt values.
282 class IntElementIterator
283 : public detail::DenseElementIndexedIteratorImpl<IntElementIterator,
284 APInt, APInt, APInt> {
285 public:
286 /// Accesses the raw APInt value at this iterator position.
287 APInt operator*() const;
288
289 private:
290 friend DenseElementsAttr;
291
292 /// Constructs a new iterator.
293 IntElementIterator(DenseElementsAttr attr, size_t dataIndex);
294
295 /// The bitwidth of the element type.
296 size_t bitWidth;
297 };
298
299 /// A utility iterator that allows walking over the internal raw complex APInt
300 /// values.
301 class ComplexIntElementIterator
302 : public detail::DenseElementIndexedIteratorImpl<
303 ComplexIntElementIterator, mlir::Complex<APInt>,
304 mlir::Complex<APInt>, mlir::Complex<APInt>> {
305 public:
306 /// Accesses the raw mlir::Complex<APInt> value at this iterator position.
307 mlir::Complex<APInt> operator*() const;
308
309 private:
310 friend DenseElementsAttr;
311
312 /// Constructs a new iterator.
313 ComplexIntElementIterator(DenseElementsAttr attr, size_t dataIndex);
314
315 /// The bitwidth of the element type.
316 size_t bitWidth;
317 };
318
319 /// Iterator for walking over APFloat values.
320 class FloatElementIterator final
321 : public llvm::mapped_iterator_base<FloatElementIterator,
322 IntElementIterator, APFloat> {
323 public:
324 /// Map the element to the iterator result type.
325 APFloat mapElement(const APInt &value) const {
326 return APFloat(*smt, value);
327 }
328
329 private:
330 friend DenseElementsAttr;
331
332 /// Initializes the float element iterator to the specified iterator.
333 FloatElementIterator(const llvm::fltSemantics &smt, IntElementIterator it)
334 : BaseT(it), smt(&smt) {}
335
336 /// The float semantics to use when constructing the APFloat.
337 const llvm::fltSemantics *smt;
338 };
339
340 /// Iterator for walking over complex APFloat values.
341 class ComplexFloatElementIterator final
342 : public llvm::mapped_iterator_base<ComplexFloatElementIterator,
343 ComplexIntElementIterator,
344 mlir::Complex<APFloat>> {
345 public:
346 /// Map the element to the iterator result type.
347 mlir::Complex<APFloat> mapElement(const mlir::Complex<APInt> &value) const {
348 return {APFloat(*smt, value.real()), APFloat(*smt, value.imag())};
349 }
350
351 private:
352 friend DenseElementsAttr;
353
354 /// Initializes the float element iterator to the specified iterator.
355 ComplexFloatElementIterator(const llvm::fltSemantics &smt,
356 ComplexIntElementIterator it)
357 : BaseT(it), smt(&smt) {}
358
359 /// The float semantics to use when constructing the APFloat.
360 const llvm::fltSemantics *smt;
361 };
362
363 //===--------------------------------------------------------------------===//
364 // Value Querying
365 //===--------------------------------------------------------------------===//
366
367 /// Returns true if this attribute corresponds to a splat, i.e. if all element
368 /// values are the same.
369 bool isSplat() const;
370
371 /// Return the splat value for this attribute. This asserts that the attribute
372 /// corresponds to a splat.
373 template <typename T>
374 std::enable_if_t<!std::is_base_of<Attribute, T>::value ||
375 std::is_same<Attribute, T>::value,
376 T>
377 getSplatValue() const {
378 assert(isSplat() && "expected the attribute to be a splat");
379 return *value_begin<T>();
380 }
381 /// Return the splat value for derived attribute element types.
382 template <typename T>
383 std::enable_if_t<std::is_base_of<Attribute, T>::value &&
384 !std::is_same<Attribute, T>::value,
385 T>
386 getSplatValue() const {
387 return llvm::cast<T>(getSplatValue<Attribute>());
388 }
389
390 /// Try to get an iterator of the given type to the start of the held element
391 /// values. Return failure if the type cannot be iterated.
392 template <typename T>
393 auto try_value_begin() const {
394 auto range = tryGetValues<T>();
395 using iterator = decltype(range->begin());
396 return failed(range) ? FailureOr<iterator>(failure()) : range->begin();
397 }
398
399 /// Try to get an iterator of the given type to the end of the held element
400 /// values. Return failure if the type cannot be iterated.
401 template <typename T>
402 auto try_value_end() const {
403 auto range = tryGetValues<T>();
404 using iterator = decltype(range->begin());
405 return failed(range) ? FailureOr<iterator>(failure()) : range->end();
406 }
407
408 /// Return the held element values as a range of the given type.
409 template <typename T>
410 auto getValues() const {
411 auto range = tryGetValues<T>();
412 assert(succeeded(range) && "element type cannot be iterated");
413 return std::move(*range);
414 }
415
416 /// Get an iterator of the given type to the start of the held element values.
417 template <typename T>
418 auto value_begin() const {
419 return getValues<T>().begin();
420 }
421
422 /// Get an iterator of the given type to the end of the held element values.
423 template <typename T>
424 auto value_end() const {
425 return getValues<T>().end();
426 }
427
428 /// Try to get the held element values as a range of integer or floating-point
429 /// values.
430 template <typename T>
431 using IntFloatValueTemplateCheckT =
432 std::enable_if_t<(!std::is_same<T, bool>::value &&
433 std::numeric_limits<T>::is_integer) ||
434 is_valid_cpp_fp_type<T>::value>;
435 template <typename T, typename = IntFloatValueTemplateCheckT<T>>
436 FailureOr<iterator_range_impl<ElementIterator<T>>> tryGetValues() const {
437 if (!isValidIntOrFloat(dataEltSize: sizeof(T), isInt: std::numeric_limits<T>::is_integer,
438 isSigned: std::numeric_limits<T>::is_signed))
439 return failure();
440 const char *rawData = getRawData().data();
441 bool splat = isSplat();
442 return iterator_range_impl<ElementIterator<T>>(
443 getType(), ElementIterator<T>(rawData, splat, 0),
444 ElementIterator<T>(rawData, splat, getNumElements()));
445 }
446
447 /// Try to get the held element values as a range of mlir::Complex.
448 template <typename T, typename ElementT>
449 using ComplexValueTemplateCheckT =
450 std::enable_if_t<detail::is_complex_t<T>::value &&
451 (std::numeric_limits<ElementT>::is_integer ||
452 is_valid_cpp_fp_type<ElementT>::value)>;
453 template <typename T, typename ElementT = typename T::value_type,
454 typename = ComplexValueTemplateCheckT<T, ElementT>>
455 FailureOr<iterator_range_impl<ElementIterator<T>>> tryGetValues() const {
456 if (!isValidComplex(dataEltSize: sizeof(T), isInt: std::numeric_limits<ElementT>::is_integer,
457 isSigned: std::numeric_limits<ElementT>::is_signed))
458 return failure();
459 const char *rawData = getRawData().data();
460 bool splat = isSplat();
461 return iterator_range_impl<ElementIterator<T>>(
462 getType(), ElementIterator<T>(rawData, splat, 0),
463 ElementIterator<T>(rawData, splat, getNumElements()));
464 }
465
466 /// Try to get the held element values as a range of StringRef.
467 template <typename T>
468 using StringRefValueTemplateCheckT =
469 std::enable_if_t<std::is_same<T, StringRef>::value>;
470 template <typename T, typename = StringRefValueTemplateCheckT<T>>
471 FailureOr<iterator_range_impl<ElementIterator<StringRef>>>
472 tryGetValues() const {
473 auto stringRefs = getRawStringData();
474 const char *ptr = reinterpret_cast<const char *>(stringRefs.data());
475 bool splat = isSplat();
476 return iterator_range_impl<ElementIterator<StringRef>>(
477 getType(), ElementIterator<StringRef>(ptr, splat, 0),
478 ElementIterator<StringRef>(ptr, splat, getNumElements()));
479 }
480
481 /// Try to get the held element values as a range of Attributes.
482 template <typename T>
483 using AttributeValueTemplateCheckT =
484 std::enable_if_t<std::is_same<T, Attribute>::value>;
485 template <typename T, typename = AttributeValueTemplateCheckT<T>>
486 FailureOr<iterator_range_impl<AttributeElementIterator>>
487 tryGetValues() const {
488 return iterator_range_impl<AttributeElementIterator>(
489 getType(), AttributeElementIterator(*this, 0),
490 AttributeElementIterator(*this, getNumElements()));
491 }
492
493 /// Try to get the held element values a range of T, where T is a derived
494 /// attribute type.
495 template <typename T>
496 using DerivedAttrValueTemplateCheckT =
497 std::enable_if_t<std::is_base_of<Attribute, T>::value &&
498 !std::is_same<Attribute, T>::value>;
499 template <typename T>
500 struct DerivedAttributeElementIterator
501 : public llvm::mapped_iterator_base<DerivedAttributeElementIterator<T>,
502 AttributeElementIterator, T> {
503 using llvm::mapped_iterator_base<DerivedAttributeElementIterator<T>,
504 AttributeElementIterator,
505 T>::mapped_iterator_base;
506
507 /// Map the element to the iterator result type.
508 T mapElement(Attribute attr) const { return llvm::cast<T>(attr); }
509 };
510 template <typename T, typename = DerivedAttrValueTemplateCheckT<T>>
511 FailureOr<iterator_range_impl<DerivedAttributeElementIterator<T>>>
512 tryGetValues() const {
513 using DerivedIterT = DerivedAttributeElementIterator<T>;
514 return iterator_range_impl<DerivedIterT>(
515 getType(), DerivedIterT(value_begin<Attribute>()),
516 DerivedIterT(value_end<Attribute>()));
517 }
518
519 /// Try to get the held element values as a range of bool. The element type of
520 /// this attribute must be of integer type of bitwidth 1.
521 template <typename T>
522 using BoolValueTemplateCheckT =
523 std::enable_if_t<std::is_same<T, bool>::value>;
524 template <typename T, typename = BoolValueTemplateCheckT<T>>
525 FailureOr<iterator_range_impl<BoolElementIterator>> tryGetValues() const {
526 if (!isValidBool())
527 return failure();
528 return iterator_range_impl<BoolElementIterator>(
529 getType(), BoolElementIterator(*this, 0),
530 BoolElementIterator(*this, getNumElements()));
531 }
532
533 /// Try to get the held element values as a range of APInts. The element type
534 /// of this attribute must be of integer type.
535 template <typename T>
536 using APIntValueTemplateCheckT =
537 std::enable_if_t<std::is_same<T, APInt>::value>;
538 template <typename T, typename = APIntValueTemplateCheckT<T>>
539 FailureOr<iterator_range_impl<IntElementIterator>> tryGetValues() const {
540 if (!getElementType().isIntOrIndex())
541 return failure();
542 return iterator_range_impl<IntElementIterator>(getType(), raw_int_begin(),
543 raw_int_end());
544 }
545
546 /// Try to get the held element values as a range of complex APInts. The
547 /// element type of this attribute must be a complex of integer type.
548 template <typename T>
549 using ComplexAPIntValueTemplateCheckT =
550 std::enable_if_t<std::is_same<T, mlir::Complex<APInt>>::value>;
551 template <typename T, typename = ComplexAPIntValueTemplateCheckT<T>>
552 FailureOr<iterator_range_impl<ComplexIntElementIterator>>
553 tryGetValues() const {
554 return tryGetComplexIntValues();
555 }
556
557 /// Try to get the held element values as a range of APFloat. The element type
558 /// of this attribute must be of float type.
559 template <typename T>
560 using APFloatValueTemplateCheckT =
561 std::enable_if_t<std::is_same<T, APFloat>::value>;
562 template <typename T, typename = APFloatValueTemplateCheckT<T>>
563 FailureOr<iterator_range_impl<FloatElementIterator>> tryGetValues() const {
564 return tryGetFloatValues();
565 }
566
567 /// Try to get the held element values as a range of complex APFloat. The
568 /// element type of this attribute must be a complex of float type.
569 template <typename T>
570 using ComplexAPFloatValueTemplateCheckT =
571 std::enable_if_t<std::is_same<T, mlir::Complex<APFloat>>::value>;
572 template <typename T, typename = ComplexAPFloatValueTemplateCheckT<T>>
573 FailureOr<iterator_range_impl<ComplexFloatElementIterator>>
574 tryGetValues() const {
575 return tryGetComplexFloatValues();
576 }
577
578 /// Return the raw storage data held by this attribute. Users should generally
579 /// not use this directly, as the internal storage format is not always in the
580 /// form the user might expect.
581 ArrayRef<char> getRawData() const;
582
583 /// Return the raw StringRef data held by this attribute.
584 ArrayRef<StringRef> getRawStringData() const;
585
586 /// Return the type of this ElementsAttr, guaranteed to be a vector or tensor
587 /// with static shape.
588 ShapedType getType() const;
589
590 /// Return the element type of this DenseElementsAttr.
591 Type getElementType() const;
592
593 /// Returns the number of elements held by this attribute.
594 int64_t getNumElements() const;
595
596 /// Returns the number of elements held by this attribute.
597 int64_t size() const { return getNumElements(); }
598
599 /// Returns if the number of elements held by this attribute is 0.
600 bool empty() const { return size() == 0; }
601
602 //===--------------------------------------------------------------------===//
603 // Mutation Utilities
604 //===--------------------------------------------------------------------===//
605
606 /// Return a new DenseElementsAttr that has the same data as the current
607 /// attribute, but has been reshaped to 'newType'. The new type must have the
608 /// same total number of elements as well as element type.
609 DenseElementsAttr reshape(ShapedType newType);
610
611 /// Return a new DenseElementsAttr that has the same data as the current
612 /// attribute, but with a different shape for a splat type. The new type must
613 /// have the same element type.
614 DenseElementsAttr resizeSplat(ShapedType newType);
615
616 /// Return a new DenseElementsAttr that has the same data as the current
617 /// attribute, but has bitcast elements to 'newElType'. The new type must have
618 /// the same bitwidth as the current element type.
619 DenseElementsAttr bitcast(Type newElType);
620
621 /// Generates a new DenseElementsAttr by mapping each int value to a new
622 /// underlying APInt. The new values can represent either an integer or float.
623 /// This underlying type must be an DenseIntElementsAttr.
624 DenseElementsAttr mapValues(Type newElementType,
625 function_ref<APInt(const APInt &)> mapping) const;
626
627 /// Generates a new DenseElementsAttr by mapping each float value to a new
628 /// underlying APInt. the new values can represent either an integer or float.
629 /// This underlying type must be an DenseFPElementsAttr.
630 DenseElementsAttr
631 mapValues(Type newElementType,
632 function_ref<APInt(const APFloat &)> mapping) const;
633
634protected:
635 /// Iterators to various elements that require out-of-line definition. These
636 /// are hidden from the user to encourage consistent use of the
637 /// getValues/value_begin/value_end API.
638 IntElementIterator raw_int_begin() const {
639 return IntElementIterator(*this, 0);
640 }
641 IntElementIterator raw_int_end() const {
642 return IntElementIterator(*this, getNumElements());
643 }
644 FailureOr<iterator_range_impl<ComplexIntElementIterator>>
645 tryGetComplexIntValues() const;
646 FailureOr<iterator_range_impl<FloatElementIterator>>
647 tryGetFloatValues() const;
648 FailureOr<iterator_range_impl<ComplexFloatElementIterator>>
649 tryGetComplexFloatValues() const;
650
651 /// Overload of the raw 'get' method that asserts that the given type is of
652 /// complex type. This method is used to verify type invariants that the
653 /// templatized 'get' method cannot.
654 static DenseElementsAttr getRawComplex(ShapedType type, ArrayRef<char> data,
655 int64_t dataEltSize, bool isInt,
656 bool isSigned);
657
658 /// Overload of the raw 'get' method that asserts that the given type is of
659 /// integer or floating-point type. This method is used to verify type
660 /// invariants that the templatized 'get' method cannot.
661 static DenseElementsAttr getRawIntOrFloat(ShapedType type,
662 ArrayRef<char> data,
663 int64_t dataEltSize, bool isInt,
664 bool isSigned);
665
666 /// Check the information for a C++ data type, check if this type is valid for
667 /// the current attribute. This method is used to verify specific type
668 /// invariants that the templatized 'getValues' method cannot.
669 bool isValidBool() const { return getElementType().isInteger(width: 1); }
670 bool isValidIntOrFloat(int64_t dataEltSize, bool isInt, bool isSigned) const;
671 bool isValidComplex(int64_t dataEltSize, bool isInt, bool isSigned) const;
672};
673
674/// An attribute that represents a reference to a splat vector or tensor
675/// constant, meaning all of the elements have the same value.
676class SplatElementsAttr : public DenseElementsAttr {
677public:
678 using DenseElementsAttr::DenseElementsAttr;
679
680 /// Method for support type inquiry through isa, cast and dyn_cast.
681 static bool classof(Attribute attr) {
682 auto denseAttr = llvm::dyn_cast<DenseElementsAttr>(Val&: attr);
683 return denseAttr && denseAttr.isSplat();
684 }
685};
686
687//===----------------------------------------------------------------------===//
688// DenseResourceElementsAttr
689//===----------------------------------------------------------------------===//
690
691using DenseResourceElementsHandle = DialectResourceBlobHandle<BuiltinDialect>;
692
693} // namespace mlir
694
695//===----------------------------------------------------------------------===//
696// Tablegen Attribute Declarations
697//===----------------------------------------------------------------------===//
698
699#define GET_ATTRDEF_CLASSES
700#include "mlir/IR/BuiltinAttributes.h.inc"
701
702//===----------------------------------------------------------------------===//
703// C++ Attribute Declarations
704//===----------------------------------------------------------------------===//
705
706namespace mlir {
707/// DenseIntOrFPElementsAttr was renamed to DenseTypedElementsAttr. This alias
708/// is provided for backwards compatibility. It will be removed in the future.
709using DenseIntOrFPElementsAttr [[deprecated(
710 "DenseIntOrFPElementsAttr has been renamed to DenseTypedElementsAttr")]] =
711 DenseTypedElementsAttr;
712
713//===----------------------------------------------------------------------===//
714// DenseArrayAttr
715//===----------------------------------------------------------------------===//
716
717namespace detail {
718/// Base class for DenseArrayAttr that is instantiated and specialized for each
719/// supported element type below.
720template <typename T>
721class DenseArrayAttrImpl : public DenseArrayAttr {
722public:
723 using DenseArrayAttr::DenseArrayAttr;
724
725 /// Implicit conversion to ArrayRef<T>.
726 operator ArrayRef<T>() const;
727 ArrayRef<T> asArrayRef() const { return ArrayRef<T>{*this}; }
728
729 /// Random access to elements.
730 T operator[](std::size_t index) const { return asArrayRef()[index]; }
731
732 /// Builder from ArrayRef<T>.
733 static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef<T> content);
734
735 /// Print the short form `[42, 100, -1]` without any type prefix.
736 void print(AsmPrinter &printer) const;
737 void print(raw_ostream &os) const;
738 /// Print the short form `42, 100, -1` without any braces or type prefix.
739 void printWithoutBraces(raw_ostream &os) const;
740
741 /// Parse the short form `[42, 100, -1]` without any type prefix.
742 static Attribute parse(AsmParser &parser, Type type);
743
744 /// Parse the short form `42, 100, -1` without any type prefix or braces.
745 static Attribute parseWithoutBraces(AsmParser &parser, Type type);
746
747 /// Support for isa<>/cast<>.
748 static bool classof(Attribute attr);
749};
750
751extern template class DenseArrayAttrImpl<bool>;
752extern template class DenseArrayAttrImpl<int8_t>;
753extern template class DenseArrayAttrImpl<int16_t>;
754extern template class DenseArrayAttrImpl<int32_t>;
755extern template class DenseArrayAttrImpl<int64_t>;
756extern template class DenseArrayAttrImpl<float>;
757extern template class DenseArrayAttrImpl<double>;
758} // namespace detail
759
760// Public name for all the supported DenseArrayAttr
761using DenseBoolArrayAttr = detail::DenseArrayAttrImpl<bool>;
762using DenseI8ArrayAttr = detail::DenseArrayAttrImpl<int8_t>;
763using DenseI16ArrayAttr = detail::DenseArrayAttrImpl<int16_t>;
764using DenseI32ArrayAttr = detail::DenseArrayAttrImpl<int32_t>;
765using DenseI64ArrayAttr = detail::DenseArrayAttrImpl<int64_t>;
766using DenseF32ArrayAttr = detail::DenseArrayAttrImpl<float>;
767using DenseF64ArrayAttr = detail::DenseArrayAttrImpl<double>;
768
769//===----------------------------------------------------------------------===//
770// DenseResourceElementsAttr
771//===----------------------------------------------------------------------===//
772
773namespace detail {
774/// Base class for DenseResourceElementsAttr that is instantiated and
775/// specialized for each supported element type below.
776template <typename T>
777class DenseResourceElementsAttrBase : public DenseResourceElementsAttr {
778public:
779 using DenseResourceElementsAttr::DenseResourceElementsAttr;
780
781 /// A builder that inserts a new resource using the provided blob. The handle
782 /// of the inserted blob is used when building the attribute. The provided
783 /// `blobName` is used as a hint for the key of the new handle for the `blob`
784 /// resource, but may be changed if necessary to ensure uniqueness during
785 /// insertion.
786 static DenseResourceElementsAttrBase<T>
787 get(ShapedType type, StringRef blobName, AsmResourceBlob blob);
788
789 /// Return the data of this attribute as an ArrayRef<T> if it is present,
790 /// returns std::nullopt otherwise.
791 std::optional<ArrayRef<T>> tryGetAsArrayRef() const;
792
793 /// Support for isa<>/cast<>.
794 static bool classof(Attribute attr);
795};
796
797extern template class DenseResourceElementsAttrBase<bool>;
798extern template class DenseResourceElementsAttrBase<int8_t>;
799extern template class DenseResourceElementsAttrBase<int16_t>;
800extern template class DenseResourceElementsAttrBase<int32_t>;
801extern template class DenseResourceElementsAttrBase<int64_t>;
802extern template class DenseResourceElementsAttrBase<uint8_t>;
803extern template class DenseResourceElementsAttrBase<uint16_t>;
804extern template class DenseResourceElementsAttrBase<uint32_t>;
805extern template class DenseResourceElementsAttrBase<uint64_t>;
806extern template class DenseResourceElementsAttrBase<float>;
807extern template class DenseResourceElementsAttrBase<double>;
808} // namespace detail
809
810// Public names for all the supported DenseResourceElementsAttr.
811
812using DenseBoolResourceElementsAttr =
813 detail::DenseResourceElementsAttrBase<bool>;
814using DenseI8ResourceElementsAttr =
815 detail::DenseResourceElementsAttrBase<int8_t>;
816using DenseI16ResourceElementsAttr =
817 detail::DenseResourceElementsAttrBase<int16_t>;
818using DenseI32ResourceElementsAttr =
819 detail::DenseResourceElementsAttrBase<int32_t>;
820using DenseI64ResourceElementsAttr =
821 detail::DenseResourceElementsAttrBase<int64_t>;
822using DenseUI8ResourceElementsAttr =
823 detail::DenseResourceElementsAttrBase<uint8_t>;
824using DenseUI16ResourceElementsAttr =
825 detail::DenseResourceElementsAttrBase<uint16_t>;
826using DenseUI32ResourceElementsAttr =
827 detail::DenseResourceElementsAttrBase<uint32_t>;
828using DenseUI64ResourceElementsAttr =
829 detail::DenseResourceElementsAttrBase<uint64_t>;
830using DenseF32ResourceElementsAttr =
831 detail::DenseResourceElementsAttrBase<float>;
832using DenseF64ResourceElementsAttr =
833 detail::DenseResourceElementsAttrBase<double>;
834
835//===----------------------------------------------------------------------===//
836// BoolAttr
837//===----------------------------------------------------------------------===//
838
839/// Special case of IntegerAttr to represent boolean integers, i.e., signless i1
840/// integers.
841class BoolAttr : public Attribute {
842public:
843 using Attribute::Attribute;
844 using ValueType = bool;
845
846 static BoolAttr get(MLIRContext *context, bool value);
847
848 /// Enable conversion to IntegerAttr and its interfaces. This uses conversion
849 /// vs. inheritance to avoid bringing in all of IntegerAttrs methods.
850 operator IntegerAttr() const { return IntegerAttr(impl); }
851 operator TypedAttr() const { return IntegerAttr(impl); }
852
853 /// Return the boolean value of this attribute.
854 bool getValue() const;
855
856 /// Methods for support type inquiry through isa, cast, and dyn_cast.
857 static bool classof(Attribute attr);
858};
859
860//===----------------------------------------------------------------------===//
861// FlatSymbolRefAttr
862//===----------------------------------------------------------------------===//
863
864/// A symbol reference with a reference path containing a single element. This
865/// is used to refer to an operation within the current symbol table.
866class FlatSymbolRefAttr : public SymbolRefAttr {
867public:
868 using SymbolRefAttr::SymbolRefAttr;
869 using ValueType = StringRef;
870
871 /// Construct a symbol reference for the given value name.
872 static FlatSymbolRefAttr get(StringAttr value) {
873 return SymbolRefAttr::get(value);
874 }
875 static FlatSymbolRefAttr get(MLIRContext *ctx, StringRef value) {
876 return SymbolRefAttr::get(ctx, value);
877 }
878
879 /// Convenience getter for building a SymbolRefAttr based on an operation
880 /// that implements the SymbolTrait.
881 static FlatSymbolRefAttr get(Operation *symbol) {
882 return SymbolRefAttr::get(symbol);
883 }
884
885 /// Returns the name of the held symbol reference as a StringAttr.
886 StringAttr getAttr() const { return getRootReference(); }
887
888 /// Returns the name of the held symbol reference.
889 StringRef getValue() const { return getAttr().getValue(); }
890
891 /// Methods for support type inquiry through isa, cast, and dyn_cast.
892 static bool classof(Attribute attr) {
893 SymbolRefAttr refAttr = llvm::dyn_cast<SymbolRefAttr>(Val&: attr);
894 return refAttr && refAttr.getNestedReferences().empty();
895 }
896
897private:
898 using SymbolRefAttr::get;
899 using SymbolRefAttr::getNestedReferences;
900};
901
902//===----------------------------------------------------------------------===//
903// DenseFPElementsAttr
904//===----------------------------------------------------------------------===//
905
906/// An attribute that represents a reference to a dense float vector or tensor
907/// object. Each element is stored as a double.
908class DenseFPElementsAttr : public DenseTypedElementsAttr {
909public:
910 using iterator = DenseElementsAttr::FloatElementIterator;
911
912 using DenseTypedElementsAttr::DenseTypedElementsAttr;
913
914 /// Get an instance of a DenseFPElementsAttr with the given arguments. This
915 /// simply wraps the DenseElementsAttr::get calls.
916 template <typename Arg>
917 static DenseFPElementsAttr get(const ShapedType &type, Arg &&arg) {
918 return llvm::cast<DenseFPElementsAttr>(
919 DenseElementsAttr::get(type, llvm::ArrayRef(arg)));
920 }
921 template <typename T>
922 static DenseFPElementsAttr get(const ShapedType &type,
923 const std::initializer_list<T> &list) {
924 return llvm::cast<DenseFPElementsAttr>(DenseElementsAttr::get(type, list));
925 }
926
927 /// Generates a new DenseElementsAttr by mapping each value attribute, and
928 /// constructing the DenseElementsAttr given the new element type.
929 DenseElementsAttr
930 mapValues(Type newElementType,
931 function_ref<APInt(const APFloat &)> mapping) const;
932
933 /// Iterator access to the float element values.
934 iterator begin() const { return tryGetFloatValues()->begin(); }
935 iterator end() const { return tryGetFloatValues()->end(); }
936
937 /// Method for supporting type inquiry through isa, cast and dyn_cast.
938 static bool classof(Attribute attr);
939};
940
941//===----------------------------------------------------------------------===//
942// DenseIntElementsAttr
943//===----------------------------------------------------------------------===//
944
945/// An attribute that represents a reference to a dense integer vector or tensor
946/// object.
947class DenseIntElementsAttr : public DenseTypedElementsAttr {
948public:
949 /// DenseIntElementsAttr iterates on APInt, so we can use the raw element
950 /// iterator directly.
951 using iterator = DenseElementsAttr::IntElementIterator;
952
953 using DenseTypedElementsAttr::DenseTypedElementsAttr;
954
955 /// Get an instance of a DenseIntElementsAttr with the given arguments. This
956 /// simply wraps the DenseElementsAttr::get calls.
957 template <typename Arg>
958 static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg) {
959 return llvm::cast<DenseIntElementsAttr>(
960 DenseElementsAttr::get(type, llvm::ArrayRef(arg)));
961 }
962 template <typename T>
963 static DenseIntElementsAttr get(const ShapedType &type,
964 const std::initializer_list<T> &list) {
965 return llvm::cast<DenseIntElementsAttr>(DenseElementsAttr::get(type, list));
966 }
967
968 /// Generates a new DenseElementsAttr by mapping each value attribute, and
969 /// constructing the DenseElementsAttr given the new element type.
970 DenseElementsAttr mapValues(Type newElementType,
971 function_ref<APInt(const APInt &)> mapping) const;
972
973 /// Iterator access to the integer element values.
974 iterator begin() const { return raw_int_begin(); }
975 iterator end() const { return raw_int_end(); }
976
977 /// Method for supporting type inquiry through isa, cast and dyn_cast.
978 static bool classof(Attribute attr);
979};
980
981//===----------------------------------------------------------------------===//
982// SparseElementsAttr
983//===----------------------------------------------------------------------===//
984
985template <typename T>
986auto SparseElementsAttr::try_value_begin_impl(OverloadToken<T>) const
987 -> FailureOr<iterator<T>> {
988 auto zeroValue = getZeroValue<T>();
989 auto valueIt = getValues().try_value_begin<T>();
990 if (failed(valueIt))
991 return failure();
992 const SmallVector<ptrdiff_t> flatSparseIndices(getFlattenedSparseIndices());
993 std::function<T(ptrdiff_t)> mapFn =
994 [flatSparseIndices{flatSparseIndices}, valueIt{std::move(*valueIt)},
995 zeroValue{std::move(zeroValue)}](ptrdiff_t index) {
996 // Try to map the current index to one of the sparse indices.
997 for (unsigned i = 0, e = flatSparseIndices.size(); i != e; ++i)
998 if (flatSparseIndices[i] == index)
999 return *std::next(valueIt, i);
1000 // Otherwise, return the zero value.
1001 return zeroValue;
1002 };
1003 return iterator<T>(llvm::seq<ptrdiff_t>(Begin: 0, End: getNumElements()).begin(), mapFn);
1004}
1005
1006//===----------------------------------------------------------------------===//
1007// DistinctAttr
1008//===----------------------------------------------------------------------===//
1009
1010namespace detail {
1011struct DistinctAttrStorage;
1012class DistinctAttributeUniquer;
1013} // namespace detail
1014
1015/// An attribute that associates a referenced attribute with a unique
1016/// identifier. Every call to the create function allocates a new distinct
1017/// attribute instance. The address of the attribute instance serves as a
1018/// temporary identifier. Similar to the names of SSA values, the final
1019/// identifiers are generated during pretty printing. This delayed numbering
1020/// ensures the printed identifiers are deterministic even if multiple distinct
1021/// attribute instances are created in-parallel.
1022///
1023/// Examples:
1024///
1025/// #distinct = distinct[0]<42.0 : f32>
1026/// #distinct1 = distinct[1]<42.0 : f32>
1027/// #distinct2 = distinct[2]<array<i32: 10, 42>>
1028///
1029/// NOTE: The distinct attribute cannot be defined using ODS since it uses a
1030/// custom distinct attribute uniquer that cannot be set from ODS.
1031class DistinctAttr
1032 : public detail::StorageUserBase<DistinctAttr, Attribute,
1033 detail::DistinctAttrStorage,
1034 detail::DistinctAttributeUniquer> {
1035public:
1036 using Base::Base;
1037
1038 /// Returns the referenced attribute.
1039 Attribute getReferencedAttr() const;
1040
1041 /// Creates a distinct attribute that associates a referenced attribute with a
1042 /// unique identifier.
1043 static DistinctAttr create(Attribute referencedAttr);
1044
1045 static constexpr StringLiteral name = "builtin.distinct";
1046};
1047
1048//===----------------------------------------------------------------------===//
1049// StringAttr
1050//===----------------------------------------------------------------------===//
1051
1052/// Define comparisons for StringAttr against nullptr and itself to avoid the
1053/// StringRef overloads from being chosen when not desirable.
1054inline bool operator==(StringAttr lhs, std::nullptr_t) { return !lhs; }
1055inline bool operator!=(StringAttr lhs, std::nullptr_t) {
1056 return static_cast<bool>(lhs);
1057}
1058inline bool operator==(StringAttr lhs, StringAttr rhs) {
1059 return (Attribute)lhs == (Attribute)rhs;
1060}
1061inline bool operator!=(StringAttr lhs, StringAttr rhs) { return !(lhs == rhs); }
1062
1063/// Allow direct comparison with StringRef.
1064inline bool operator==(StringAttr lhs, StringRef rhs) {
1065 return lhs.getValue() == rhs;
1066}
1067inline bool operator!=(StringAttr lhs, StringRef rhs) { return !(lhs == rhs); }
1068inline bool operator==(StringRef lhs, StringAttr rhs) {
1069 return rhs.getValue() == lhs;
1070}
1071inline bool operator!=(StringRef lhs, StringAttr rhs) { return !(lhs == rhs); }
1072
1073} // namespace mlir
1074
1075//===----------------------------------------------------------------------===//
1076// Attribute Utilities
1077//===----------------------------------------------------------------------===//
1078
1079namespace mlir {
1080
1081/// Given a list of strides (in which ShapedType::kDynamic
1082/// represents a dynamic value), return the single result AffineMap which
1083/// represents the linearized strided layout map. Dimensions correspond to the
1084/// offset followed by the strides in order. Symbols are inserted for each
1085/// dynamic dimension in order. A stride is always positive.
1086///
1087/// Examples:
1088/// =========
1089///
1090/// 1. For offset: 0 strides: ?, ?, 1 return
1091/// (i, j, k)[M, N]->(M * i + N * j + k)
1092///
1093/// 2. For offset: 3 strides: 32, ?, 16 return
1094/// (i, j, k)[M]->(3 + 32 * i + M * j + 16 * k)
1095///
1096/// 3. For offset: ? strides: ?, ?, ? return
1097/// (i, j, k)[off, M, N, P]->(off + M * i + N * j + P * k)
1098AffineMap makeStridedLinearLayoutMap(ArrayRef<int64_t> strides, int64_t offset,
1099 MLIRContext *context);
1100
1101} // namespace mlir
1102
1103namespace llvm {
1104
1105template <>
1106struct DenseMapInfo<mlir::StringAttr> : public DenseMapInfo<mlir::Attribute> {
1107};
1108template <>
1109struct PointerLikeTypeTraits<mlir::StringAttr>
1110 : public PointerLikeTypeTraits<mlir::Attribute> {
1111 static inline mlir::StringAttr getFromVoidPointer(void *p) {
1112 return mlir::StringAttr::getFromOpaquePointer(ptr: p);
1113 }
1114};
1115
1116template <>
1117struct PointerLikeTypeTraits<mlir::IntegerAttr>
1118 : public PointerLikeTypeTraits<mlir::Attribute> {
1119 static inline mlir::IntegerAttr getFromVoidPointer(void *p) {
1120 return mlir::IntegerAttr::getFromOpaquePointer(ptr: p);
1121 }
1122};
1123
1124template <>
1125struct PointerLikeTypeTraits<mlir::SymbolRefAttr>
1126 : public PointerLikeTypeTraits<mlir::Attribute> {
1127 static inline mlir::SymbolRefAttr getFromVoidPointer(void *ptr) {
1128 return mlir::SymbolRefAttr::getFromOpaquePointer(ptr);
1129 }
1130};
1131
1132} // namespace llvm
1133
1134#endif // MLIR_IR_BUILTINATTRIBUTES_H
1135