MLIR 24.0.0git
BuiltinAttributes.cpp
Go to the documentation of this file.
1//===- BuiltinAttributes.cpp - MLIR Builtin Attribute Classes -------------===//
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
10#include "AttributeDetail.h"
11#include "mlir/IR/AffineMap.h"
14#include "mlir/IR/Dialect.h"
16#include "mlir/IR/IntegerSet.h"
18#include "mlir/IR/Operation.h"
19#include "mlir/IR/SymbolTable.h"
20#include "mlir/IR/Types.h"
21#include "llvm/ADT/APSInt.h"
22#include "llvm/Support/Alignment.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/DebugLog.h"
25#include "llvm/Support/Endian.h"
26#include <optional>
27
28#define DEBUG_TYPE "builtinattributes"
29
30using namespace mlir;
31using namespace mlir::detail;
32
33//===----------------------------------------------------------------------===//
34/// Tablegen Attribute Definitions
35//===----------------------------------------------------------------------===//
36
37#define GET_ATTRDEF_CLASSES
38#include "mlir/IR/BuiltinAttributes.cpp.inc"
39
40//===----------------------------------------------------------------------===//
41// DictionaryAttr
42//===----------------------------------------------------------------------===//
43
44/// Helper function that does either an in place sort or sorts from source array
45/// into destination. If inPlace then storage is both the source and the
46/// destination, else value is the source and storage destination. Returns
47/// whether source was sorted.
48template <bool inPlace>
51 // Specialize for the common case.
52 switch (value.size()) {
53 case 0:
54 // Zero already sorted.
55 if (!inPlace)
56 storage.clear();
57 break;
58 case 1:
59 // One already sorted but may need to be copied.
60 if (!inPlace)
61 storage.assign({value[0]});
62 break;
63 case 2: {
64 bool isSorted = value[0] < value[1];
65 if (inPlace) {
66 if (!isSorted)
67 std::swap(storage[0], storage[1]);
68 } else if (isSorted) {
69 storage.assign({value[0], value[1]});
70 } else {
71 storage.assign({value[1], value[0]});
72 }
73 return !isSorted;
74 }
75 default:
76 if (!inPlace)
77 storage.assign(value.begin(), value.end());
78 // Check to see they are sorted already.
79 bool isSorted = llvm::is_sorted(value);
80 // If not, do a general sort.
81 if (!isSorted)
82 llvm::array_pod_sort(storage.begin(), storage.end());
83 return !isSorted;
84 }
85 return false;
86}
87
88/// Returns an entry with a duplicate name from the given sorted array of named
89/// attributes. Returns std::nullopt if all elements have unique names.
90static std::optional<NamedAttribute>
92 const std::optional<NamedAttribute> none{std::nullopt};
93 if (value.size() < 2)
94 return none;
95
96 if (value.size() == 2)
97 return value[0].getName() == value[1].getName() ? value[0] : none;
98
99 const auto *it = std::adjacent_find(value.begin(), value.end(),
101 return l.getName() == r.getName();
102 });
103 return it != value.end() ? *it : none;
104}
105
106bool DictionaryAttr::sort(ArrayRef<NamedAttribute> value,
108 bool isSorted = dictionaryAttrSort</*inPlace=*/false>(value, storage);
109 assert(!findDuplicateElement(storage) &&
110 "DictionaryAttr element names must be unique");
111 return isSorted;
112}
113
114bool DictionaryAttr::sortInPlace(SmallVectorImpl<NamedAttribute> &array) {
115 bool isSorted = dictionaryAttrSort</*inPlace=*/true>(array, array);
116 assert(!findDuplicateElement(array) &&
117 "DictionaryAttr element names must be unique");
118 return isSorted;
119}
120
121std::optional<NamedAttribute>
122DictionaryAttr::findDuplicate(SmallVectorImpl<NamedAttribute> &array,
123 bool isSorted) {
124 if (!isSorted)
125 dictionaryAttrSort</*inPlace=*/true>(array, array);
126 return findDuplicateElement(array);
127}
128
129DictionaryAttr DictionaryAttr::get(MLIRContext *context,
131 if (value.empty())
132 return DictionaryAttr::getEmpty(context);
133
134 // We need to sort the element list to canonicalize it.
135 SmallVector<NamedAttribute, 8> storage;
136 if (dictionaryAttrSort</*inPlace=*/false>(value, storage))
137 value = storage;
138 assert(!findDuplicateElement(value) &&
139 "DictionaryAttr element names must be unique");
140 return Base::get(context, value);
141}
142/// Construct a dictionary with an array of values that is known to already be
143/// sorted by name and uniqued.
144DictionaryAttr DictionaryAttr::getWithSorted(MLIRContext *context,
146 if (value.empty())
147 return DictionaryAttr::getEmpty(context);
148 // Ensure that the attribute elements are unique and sorted.
149 assert(llvm::is_sorted(
150 value, [](NamedAttribute l, NamedAttribute r) { return l < r; }) &&
151 "expected attribute values to be sorted");
152 assert(!findDuplicateElement(value) &&
153 "DictionaryAttr element names must be unique");
154 return Base::get(context, value);
155}
156
157/// Return the specified attribute if present, null otherwise.
158Attribute DictionaryAttr::get(StringRef name) const {
159 auto it = impl::findAttrSorted(begin(), end(), name);
160 return it.second ? it.first->getValue() : Attribute();
161}
162Attribute DictionaryAttr::get(StringAttr name) const {
163 auto it = impl::findAttrSorted(begin(), end(), name);
164 return it.second ? it.first->getValue() : Attribute();
165}
166
167/// Return the specified named attribute if present, std::nullopt otherwise.
168std::optional<NamedAttribute> DictionaryAttr::getNamed(StringRef name) const {
169 auto it = impl::findAttrSorted(begin(), end(), name);
170 return it.second ? *it.first : std::optional<NamedAttribute>();
171}
172std::optional<NamedAttribute> DictionaryAttr::getNamed(StringAttr name) const {
173 auto it = impl::findAttrSorted(begin(), end(), name);
174 return it.second ? *it.first : std::optional<NamedAttribute>();
175}
176
177/// Return whether the specified attribute is present.
178bool DictionaryAttr::contains(StringRef name) const {
179 return impl::findAttrSorted(begin(), end(), name).second;
180}
181bool DictionaryAttr::contains(StringAttr name) const {
182 return impl::findAttrSorted(begin(), end(), name).second;
183}
184
185DictionaryAttr::iterator DictionaryAttr::begin() const {
186 return getValue().begin();
187}
188DictionaryAttr::iterator DictionaryAttr::end() const {
189 return getValue().end();
190}
191size_t DictionaryAttr::size() const { return getValue().size(); }
192
193DictionaryAttr DictionaryAttr::getEmptyUnchecked(MLIRContext *context) {
194 return Base::get(context, ArrayRef<NamedAttribute>());
195}
196
197//===----------------------------------------------------------------------===//
198// StridedLayoutAttr
199//===----------------------------------------------------------------------===//
200
201/// Prints a strided layout attribute.
202void StridedLayoutAttr::print(llvm::raw_ostream &os) const {
203 auto printIntOrQuestion = [&](int64_t value) {
204 if (ShapedType::isDynamic(value))
205 os << "?";
206 else
207 os << value;
208 };
209
210 os << "strided<[";
211 llvm::interleaveComma(getStrides(), os, printIntOrQuestion);
212 os << "]";
213
214 if (getOffset() != 0) {
215 os << ", offset: ";
216 printIntOrQuestion(getOffset());
217 }
218 os << ">";
219}
220
221/// Returns true if this layout is static, i.e. the strides and offset all have
222/// a known value > 0.
223bool StridedLayoutAttr::hasStaticLayout() const {
224 return ShapedType::isStatic(getOffset()) &&
225 ShapedType::isStaticShape(getStrides());
226}
227
228/// Returns the strided layout as an affine map.
229AffineMap StridedLayoutAttr::getAffineMap() const {
230 return makeStridedLinearLayoutMap(getStrides(), getOffset(), getContext());
231}
232
233/// Checks that the type-agnostic strided layout invariants are satisfied.
234LogicalResult
235StridedLayoutAttr::verify(function_ref<InFlightDiagnostic()> emitError,
236 int64_t offset, ArrayRef<int64_t> strides) {
237 return success();
238}
239
240/// Checks that the type-specific strided layout invariants are satisfied.
241LogicalResult StridedLayoutAttr::verifyLayout(
244 if (shape.size() != getStrides().size())
245 return emitError() << "expected the number of strides to match the rank";
246
247 return success();
248}
249
250LogicalResult
251StridedLayoutAttr::getStridesAndOffset(ArrayRef<int64_t>,
253 int64_t &offset) const {
254 llvm::append_range(strides, getStrides());
255 offset = getOffset();
256 return success();
257}
258
259//===----------------------------------------------------------------------===//
260// StringAttr
261//===----------------------------------------------------------------------===//
262
263StringAttr StringAttr::getEmptyStringAttrUnchecked(MLIRContext *context) {
264 return Base::get(context, "", NoneType::get(context));
265}
266
267/// Twine support for StringAttr.
268StringAttr StringAttr::get(MLIRContext *context, const Twine &twine) {
269 // Fast-path empty twine.
270 if (twine.isTriviallyEmpty())
271 return get(context);
272 SmallVector<char, 32> tempStr;
273 return Base::get(context, twine.toStringRef(tempStr), NoneType::get(context));
274}
275
276/// Twine support for StringAttr.
277StringAttr StringAttr::get(const Twine &twine, Type type) {
278 SmallVector<char, 32> tempStr;
279 return Base::get(type.getContext(), twine.toStringRef(tempStr), type);
280}
281
282StringRef StringAttr::getValue() const { return getImpl()->value; }
283
284Type StringAttr::getType() const { return getImpl()->type; }
285
286Dialect *StringAttr::getReferencedDialect() const {
287 return getImpl()->referencedDialect;
288}
289
290//===----------------------------------------------------------------------===//
291// FloatAttr
292//===----------------------------------------------------------------------===//
293
294double FloatAttr::getValueAsDouble() const {
295 return getValueAsDouble(getValue());
296}
297double FloatAttr::getValueAsDouble(APFloat value) {
298 if (&value.getSemantics() != &APFloat::IEEEdouble()) {
299 bool losesInfo = false;
300 value.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
301 &losesInfo);
302 }
303 return value.convertToDouble();
304}
305
306LogicalResult FloatAttr::verify(function_ref<InFlightDiagnostic()> emitError,
307 Type type, APFloat value) {
308 // Verify that the type is correct.
309 if (!llvm::isa<FloatType>(type))
310 return emitError() << "expected floating point type";
311
312 // Verify that the type semantics match that of the value.
313 if (&llvm::cast<FloatType>(type).getFloatSemantics() !=
314 &value.getSemantics()) {
315 return emitError()
316 << "FloatAttr type doesn't match the type implied by its value";
317 }
318 return success();
319}
320
321//===----------------------------------------------------------------------===//
322// SymbolRefAttr
323//===----------------------------------------------------------------------===//
324
325SymbolRefAttr SymbolRefAttr::get(MLIRContext *ctx, StringRef value,
326 ArrayRef<FlatSymbolRefAttr> nestedRefs) {
327 return get(StringAttr::get(ctx, value), nestedRefs);
328}
329
330FlatSymbolRefAttr SymbolRefAttr::get(MLIRContext *ctx, StringRef value) {
331 return llvm::cast<FlatSymbolRefAttr>(get(ctx, value, {}));
332}
333
334FlatSymbolRefAttr SymbolRefAttr::get(StringAttr value) {
335 return llvm::cast<FlatSymbolRefAttr>(get(value, {}));
336}
337
338FlatSymbolRefAttr SymbolRefAttr::get(Operation *symbol) {
339 auto symbolOp = cast<SymbolOpInterface>(symbol);
340 return SymbolRefAttr::get(symbolOp.getNameAttr());
341}
342
343StringAttr SymbolRefAttr::getLeafReference() const {
344 ArrayRef<FlatSymbolRefAttr> nestedRefs = getNestedReferences();
345 return nestedRefs.empty() ? getRootReference() : nestedRefs.back().getAttr();
346}
347
348//===----------------------------------------------------------------------===//
349// IntegerAttr
350//===----------------------------------------------------------------------===//
351
352int64_t IntegerAttr::getInt() const {
353 assert((getType().isIndex() || getType().isSignlessInteger()) &&
354 "must be signless integer");
355 return getValue().getSExtValue();
356}
357
358int64_t IntegerAttr::getSInt() const {
359 assert(getType().isSignedInteger() && "must be signed integer");
360 return getValue().getSExtValue();
361}
362
363uint64_t IntegerAttr::getUInt() const {
364 assert(getType().isUnsignedInteger() && "must be unsigned integer");
365 return getValue().getZExtValue();
366}
367
368/// Return the value as an APSInt which carries the signed from the type of
369/// the attribute. This traps on signless integers types!
370APSInt IntegerAttr::getAPSInt() const {
371 assert(!getType().isSignlessInteger() &&
372 "Signless integers don't carry a sign for APSInt");
373 return APSInt(getValue(), getType().isUnsignedInteger());
374}
375
376LogicalResult IntegerAttr::verify(function_ref<InFlightDiagnostic()> emitError,
377 Type type, APInt value) {
378 if (IntegerType integerType = llvm::dyn_cast<IntegerType>(type)) {
379 if (integerType.getWidth() != value.getBitWidth())
380 return emitError() << "integer type bit width (" << integerType.getWidth()
381 << ") doesn't match value bit width ("
382 << value.getBitWidth() << ")";
383 return success();
384 }
385 if (llvm::isa<IndexType>(type)) {
386 if (value.getBitWidth() != IndexType::kInternalStorageBitWidth)
387 return emitError()
388 << "value bit width (" << value.getBitWidth()
389 << ") doesn't match index type internal storage bit width ("
390 << IndexType::kInternalStorageBitWidth << ")";
391 return success();
392 }
393 return emitError() << "expected integer or index type";
394}
395
396BoolAttr IntegerAttr::getBoolAttrUnchecked(IntegerType type, bool value) {
397 auto attr = Base::get(type.getContext(), type, APInt(/*numBits=*/1, value));
398 return llvm::cast<BoolAttr>(attr);
399}
400
401//===----------------------------------------------------------------------===//
402// BoolAttr
403//===----------------------------------------------------------------------===//
404
405bool BoolAttr::getValue() const {
406 auto *storage = reinterpret_cast<IntegerAttrStorage *>(impl);
407 return storage->value.getBoolValue();
408}
409
411 IntegerAttr intAttr = llvm::dyn_cast<IntegerAttr>(attr);
412 return intAttr && intAttr.getType().isSignlessInteger(1);
413}
414
415//===----------------------------------------------------------------------===//
416// OpaqueAttr
417//===----------------------------------------------------------------------===//
418
419LogicalResult OpaqueAttr::verify(function_ref<InFlightDiagnostic()> emitError,
420 StringAttr dialect, StringRef attrData,
421 Type type) {
422 if (!Dialect::isValidNamespace(dialect.strref()))
423 return emitError() << "invalid dialect namespace '" << dialect << "'";
424
425 // Check that the dialect is actually registered.
426 MLIRContext *context = dialect.getContext();
427 if (!context->allowsUnregisteredDialects() &&
428 !context->getLoadedDialect(dialect.strref())) {
429 return emitError()
430 << "#" << dialect << "<\"" << attrData << "\"> : " << type
431 << " attribute created with unregistered dialect. If this is "
432 "intended, please call allowUnregisteredDialects() on the "
433 "MLIRContext, or use -allow-unregistered-dialect with "
434 "the MLIR opt tool used";
435 }
436
437 return success();
438}
439
440//===----------------------------------------------------------------------===//
441// DenseElementsAttr Utilities
442//===----------------------------------------------------------------------===//
443
444/// Get the bitwidth of a dense element type within the buffer.
445/// DenseElementsAttr requires bitwidths to be aligned by 8.
446static size_t getDenseElementStorageWidth(size_t origWidth) {
447 return llvm::alignTo<8>(origWidth);
448}
449static size_t getDenseElementStorageWidth(Type elementType) {
451}
452
453/// Copy actual `numBytes` data from `value` (APInt) to char array(`result`) for
454/// BE format.
455static void copyAPIntToArrayForBEmachine(APInt value, size_t numBytes,
456 char *result) {
457 assert(llvm::endianness::native == llvm::endianness::big);
458 assert(value.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes);
459
460 // Copy the words filled with data.
461 // For example, when `value` has 2 words, the first word is filled with data.
462 // `value` (10 bytes, BE):|abcdefgh|------ij| ==> `result` (BE):|abcdefgh|--|
463 size_t numFilledWords = (value.getNumWords() - 1) * APInt::APINT_WORD_SIZE;
464 std::copy_n(reinterpret_cast<const char *>(value.getRawData()),
465 numFilledWords, result);
466 // Convert last word of APInt to LE format and store it in char
467 // array(`valueLE`).
468 // ex. last word of `value` (BE): |------ij| ==> `valueLE` (LE): |ji------|
469 size_t lastWordPos = numFilledWords;
470 SmallVector<char, 8> valueLE(APInt::APINT_WORD_SIZE);
471 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
472 reinterpret_cast<const char *>(value.getRawData()) + lastWordPos,
473 valueLE.begin(), APInt::APINT_BITS_PER_WORD, 1);
474 // Extract actual APInt data from `valueLE`, convert endianness to BE format,
475 // and store it in `result`.
476 // ex. `valueLE` (LE): |ji------| ==> `result` (BE): |abcdefgh|ij|
477 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
478 valueLE.begin(), result + lastWordPos,
479 (numBytes - lastWordPos) * CHAR_BIT, 1);
480}
481
482/// Copy `numBytes` data from `inArray`(char array) to `result`(APINT) for BE
483/// format.
484static void copyArrayToAPIntForBEmachine(const char *inArray, size_t numBytes,
485 APInt &result) {
486 assert(llvm::endianness::native == llvm::endianness::big);
487 assert(result.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes);
488
489 // Copy the data that fills the word of `result` from `inArray`.
490 // For example, when `result` has 2 words, the first word will be filled with
491 // data. So, the first 8 bytes are copied from `inArray` here.
492 // `inArray` (10 bytes, BE): |abcdefgh|ij|
493 // ==> `result` (2 words, BE): |abcdefgh|--------|
494 size_t numFilledWords = (result.getNumWords() - 1) * APInt::APINT_WORD_SIZE;
495 std::copy_n(
496 inArray, numFilledWords,
497 const_cast<char *>(reinterpret_cast<const char *>(result.getRawData())));
498
499 // Convert array data which will be last word of `result` to LE format, and
500 // store it in char array(`inArrayLE`).
501 // ex. `inArray` (last two bytes, BE): |ij| ==> `inArrayLE` (LE): |ji------|
502 size_t lastWordPos = numFilledWords;
503 SmallVector<char, 8> inArrayLE(APInt::APINT_WORD_SIZE);
504 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
505 inArray + lastWordPos, inArrayLE.begin(),
506 (numBytes - lastWordPos) * CHAR_BIT, 1);
507
508 // Convert `inArrayLE` to BE format, and store it in last word of `result`.
509 // ex. `inArrayLE` (LE): |ji------| ==> `result` (BE): |abcdefgh|------ij|
510 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
511 inArrayLE.begin(),
512 const_cast<char *>(reinterpret_cast<const char *>(result.getRawData())) +
513 lastWordPos,
514 APInt::APINT_BITS_PER_WORD, 1);
515}
516
517/// Writes value to the bit position `bitPos` in array `rawData`.
518void mlir::detail::writeBits(char *rawData, size_t bitPos, APInt value) {
519 size_t bitWidth = value.getBitWidth();
520
521 // The bit position is guaranteed to be byte aligned.
522 assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned");
523 if (llvm::endianness::native == llvm::endianness::big) {
524 // Copy from `value` to `rawData + (bitPos / CHAR_BIT)`.
525 // Copying the first `llvm::divideCeil(bitWidth, CHAR_BIT)` bytes doesn't
526 // work correctly in BE format.
527 // ex. `value` (2 words including 10 bytes)
528 // ==> BE: |abcdefgh|------ij|, LE: |hgfedcba|ji------|
529 copyAPIntToArrayForBEmachine(value, llvm::divideCeil(bitWidth, CHAR_BIT),
530 rawData + (bitPos / CHAR_BIT));
531 } else {
532 std::copy_n(reinterpret_cast<const char *>(value.getRawData()),
533 llvm::divideCeil(bitWidth, CHAR_BIT),
534 rawData + (bitPos / CHAR_BIT));
535 }
536}
537
538/// Reads the next `bitWidth` bits from the bit position `bitPos` in array
539/// `rawData`.
540APInt mlir::detail::readBits(const char *rawData, size_t bitPos,
541 size_t bitWidth) {
542 // The bit position is guaranteed to be byte aligned.
543 assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned");
544 APInt result(bitWidth, 0);
545 if (llvm::endianness::native == llvm::endianness::big) {
546 // Copy from `rawData + (bitPos / CHAR_BIT)` to `result`.
547 // Copying the first `llvm::divideCeil(bitWidth, CHAR_BIT)` bytes doesn't
548 // work correctly in BE format.
549 // ex. `result` (2 words including 10 bytes)
550 // ==> BE: |abcdefgh|------ij|, LE: |hgfedcba|ji------| This function
551 copyArrayToAPIntForBEmachine(rawData + (bitPos / CHAR_BIT),
552 llvm::divideCeil(bitWidth, CHAR_BIT), result);
553 } else {
554 std::copy_n(rawData + (bitPos / CHAR_BIT),
555 llvm::divideCeil(bitWidth, CHAR_BIT),
556 const_cast<char *>(
557 reinterpret_cast<const char *>(result.getRawData())));
558 }
559 return result;
560}
561
562/// Returns true if 'values' corresponds to a splat, i.e. one element, or has
563/// the same element count as 'type'.
564template <typename Values>
565static bool hasSameNumElementsOrSplat(ShapedType type, const Values &values) {
566 return (values.size() == 1) ||
567 (type.getNumElements() == static_cast<int64_t>(values.size()));
568}
569
570//===----------------------------------------------------------------------===//
571// DenseElementsAttr Iterators
572//===----------------------------------------------------------------------===//
573
574//===----------------------------------------------------------------------===//
575// AttributeElementIterator
576//===----------------------------------------------------------------------===//
577
578DenseElementsAttr::AttributeElementIterator::AttributeElementIterator(
579 DenseElementsAttr attr, size_t index)
580 : llvm::indexed_accessor_iterator<AttributeElementIterator, const void *,
582 attr.getAsOpaquePointer(), index) {}
583
585 auto owner = llvm::cast<DenseElementsAttr>(getFromOpaquePointer(base));
586 Type eltTy = owner.getElementType();
587
588 // Handle strings specially.
589 if (llvm::isa<DenseStringElementsAttr>(owner)) {
590 ArrayRef<StringRef> vals = owner.getRawStringData();
591 return StringAttr::get(owner.isSplat() ? vals.front() : vals[index], eltTy);
592 }
593
594 // All other types should implement DenseElementTypeInterface.
595 auto denseEltTy = llvm::cast<DenseElementType>(eltTy);
596 ArrayRef<char> rawData = owner.getRawData();
597 // Storage is byte-aligned: align bit size up to next byte boundary.
598 size_t bitSize = denseEltTy.getDenseElementBitSize();
599 size_t byteSize = llvm::divideCeil(bitSize, CHAR_BIT);
600 size_t offset = owner.isSplat() ? 0 : index * byteSize;
601 return denseEltTy.convertToAttribute(rawData.slice(offset, byteSize));
602}
603
604//===----------------------------------------------------------------------===//
605// BoolElementIterator
606//===----------------------------------------------------------------------===//
607
608DenseElementsAttr::BoolElementIterator::BoolElementIterator(
609 DenseElementsAttr attr, size_t dataIndex)
611 attr.getRawData().data(), attr.isSplat(), dataIndex) {}
612
614 return static_cast<bool>(getData()[getDataIndex()]);
615}
616
617//===----------------------------------------------------------------------===//
618// IntElementIterator
619//===----------------------------------------------------------------------===//
620
621DenseElementsAttr::IntElementIterator::IntElementIterator(
622 DenseElementsAttr attr, size_t dataIndex)
624 attr.getRawData().data(), attr.isSplat(), dataIndex),
625 bitWidth(getDenseElementBitWidth(attr.getElementType())) {}
626
628 return readBits(getData(),
630 bitWidth);
631}
632
633//===----------------------------------------------------------------------===//
634// ComplexIntElementIterator
635//===----------------------------------------------------------------------===//
636
637DenseElementsAttr::ComplexIntElementIterator::ComplexIntElementIterator(
638 DenseElementsAttr attr, size_t dataIndex)
641 mlir::Complex<APInt>>(attr.getRawData().data(), attr.isSplat(),
642 dataIndex) {
643 auto complexType = llvm::cast<ComplexType>(attr.getElementType());
644 bitWidth = getDenseElementBitWidth(complexType.getElementType());
645}
646
649 size_t storageWidth = getDenseElementStorageWidth(bitWidth);
650 size_t offset = getDataIndex() * storageWidth * 2;
651 return {readBits(getData(), offset, bitWidth),
652 readBits(getData(), offset + storageWidth, bitWidth)};
653}
654
655//===----------------------------------------------------------------------===//
656// DenseArrayAttr
657//===----------------------------------------------------------------------===//
658
659LogicalResult
660DenseArrayAttr::verify(function_ref<InFlightDiagnostic()> emitError,
661 Type elementType, int64_t size, ArrayRef<char> rawData) {
662 if (!elementType.isIntOrIndexOrFloat())
663 return emitError() << "expected integer or floating point element type";
664 int64_t dataSize = rawData.size();
665 int64_t elementSize =
666 llvm::divideCeil(elementType.getIntOrFloatBitWidth(), CHAR_BIT);
667 if (size * elementSize != dataSize) {
668 return emitError() << "expected data size (" << size << " elements, "
669 << elementSize
670 << " bytes each) does not match: " << dataSize
671 << " bytes";
672 }
673 return success();
674}
675
676namespace {
677/// Instantiations of this class provide utilities for interacting with native
678/// data types in the context of DenseArrayAttr.
679template <size_t width,
680 IntegerType::SignednessSemantics signedness = IntegerType::Signless>
681struct DenseArrayAttrIntUtil {
682 static bool checkElementType(Type eltType) {
683 auto type = llvm::dyn_cast<IntegerType>(eltType);
684 if (!type || type.getWidth() != width)
685 return false;
686 return type.getSignedness() == signedness;
687 }
688
689 static Type getElementType(MLIRContext *ctx) {
690 return IntegerType::get(ctx, width, signedness);
691 }
692
693 template <typename T>
694 static void printElement(raw_ostream &os, T value) {
695 os << value;
696 }
697
698 template <typename T>
699 static ParseResult parseElement(AsmParser &parser, T &value) {
700 return parser.parseInteger(value);
701 }
702};
703template <typename T>
704struct DenseArrayAttrUtil;
705
706/// Specialization for boolean elements to print 'true' and 'false' literals for
707/// elements.
708template <>
709struct DenseArrayAttrUtil<bool> : public DenseArrayAttrIntUtil<1> {
710 static void printElement(raw_ostream &os, bool value) {
711 os << (value ? "true" : "false");
712 }
713};
714
715/// Specialization for 8-bit integers to ensure values are printed as integers
716/// and not characters.
717template <>
718struct DenseArrayAttrUtil<int8_t> : public DenseArrayAttrIntUtil<8> {
719 static void printElement(raw_ostream &os, int8_t value) {
720 os << static_cast<int>(value);
721 }
722};
723template <>
724struct DenseArrayAttrUtil<int16_t> : public DenseArrayAttrIntUtil<16> {};
725template <>
726struct DenseArrayAttrUtil<int32_t> : public DenseArrayAttrIntUtil<32> {};
727template <>
728struct DenseArrayAttrUtil<int64_t> : public DenseArrayAttrIntUtil<64> {};
729
730/// Specialization for 32-bit floats.
731template <>
732struct DenseArrayAttrUtil<float> {
733 static bool checkElementType(Type eltType) { return eltType.isF32(); }
734 static Type getElementType(MLIRContext *ctx) { return Float32Type::get(ctx); }
735 static void printElement(raw_ostream &os, float value) { os << value; }
736
737 /// Parse a double and cast it to a float.
738 static ParseResult parseElement(AsmParser &parser, float &value) {
739 double doubleVal;
740 if (parser.parseFloat(doubleVal))
741 return failure();
742 value = doubleVal;
743 return success();
744 }
745};
746
747/// Specialization for 64-bit floats.
748template <>
749struct DenseArrayAttrUtil<double> {
750 static bool checkElementType(Type eltType) { return eltType.isF64(); }
751 static Type getElementType(MLIRContext *ctx) { return Float64Type::get(ctx); }
752 static void printElement(raw_ostream &os, float value) { os << value; }
753 static ParseResult parseElement(AsmParser &parser, double &value) {
754 return parser.parseFloat(value);
755 }
756};
757} // namespace
758
759template <typename T>
761 print(printer.getStream());
762}
763
764template <typename T>
766 llvm::interleaveComma(asArrayRef(), os, [&](T value) {
767 DenseArrayAttrUtil<T>::printElement(os, value);
768 });
769}
770
771template <typename T>
773 os << "[";
775 os << "]";
776}
777
778/// Parse a DenseArrayAttr without the braces: `1, 2, 3`
779template <typename T>
781 Type odsType) {
782 SmallVector<T> data;
783 if (failed(parser.parseCommaSeparatedList([&]() {
784 T value;
785 if (DenseArrayAttrUtil<T>::parseElement(parser, value))
786 return failure();
787 data.push_back(value);
788 return success();
789 })))
790 return {};
791 return get(parser.getContext(), data);
792}
793
794/// Parse a DenseArrayAttr: `[ 1, 2, 3 ]`
795template <typename T>
797 if (parser.parseLSquare())
798 return {};
799 // Handle empty list case.
800 if (succeeded(parser.parseOptionalRSquare()))
801 return get(parser.getContext(), {});
802 Attribute result = parseWithoutBraces(parser, odsType);
803 if (parser.parseRSquare())
804 return {};
805 return result;
806}
807
808/// Conversion from DenseArrayAttr<T> to ArrayRef<T>.
809template <typename T>
812 assert(llvm::isAddrAligned(llvm::Align(alignof(T)), raw.data()));
813 assert((raw.size() % sizeof(T)) == 0);
814 return ArrayRef<T>(reinterpret_cast<const T *>(raw.data()),
815 raw.size() / sizeof(T));
816}
817
818/// Builds a DenseArrayAttr<T> from an ArrayRef<T>.
819template <typename T>
821 ArrayRef<T> content) {
822 Type elementType = DenseArrayAttrUtil<T>::getElementType(context);
823 auto rawArray = ArrayRef<char>(reinterpret_cast<const char *>(content.data()),
824 content.size() * sizeof(T));
825 return llvm::cast<DenseArrayAttrImpl<T>>(
826 Base::get(context, elementType, content.size(), rawArray));
827}
828
829template <typename T>
831 if (auto denseArray = llvm::dyn_cast<DenseArrayAttr>(attr))
832 return DenseArrayAttrUtil<T>::checkElementType(denseArray.getElementType());
833 return false;
834}
835
836namespace mlir {
837namespace detail {
838// Explicit instantiation for all the supported DenseArrayAttr.
839template class DenseArrayAttrImpl<bool>;
840template class DenseArrayAttrImpl<int8_t>;
841template class DenseArrayAttrImpl<int16_t>;
842template class DenseArrayAttrImpl<int32_t>;
843template class DenseArrayAttrImpl<int64_t>;
844template class DenseArrayAttrImpl<float>;
845template class DenseArrayAttrImpl<double>;
846} // namespace detail
847} // namespace mlir
848
849//===----------------------------------------------------------------------===//
850// DenseElementsAttr
851//===----------------------------------------------------------------------===//
852
853/// Method for support type inquiry through isa, cast and dyn_cast.
855 return llvm::isa<DenseTypedElementsAttr, DenseStringElementsAttr>(attr);
856}
857
859 ArrayRef<Attribute> values) {
860 assert(hasSameNumElementsOrSplat(type, values));
861 Type eltType = type.getElementType();
862
863 // Handle strings specially.
864 if (!llvm::isa<DenseElementType>(eltType)) {
865 SmallVector<StringRef, 8> stringValues;
866 stringValues.reserve(values.size());
867 for (Attribute attr : values) {
868 assert(llvm::isa<StringAttr>(attr) &&
869 "expected string value for non-DenseElementType element");
870 stringValues.push_back(llvm::cast<StringAttr>(attr).getValue());
871 }
872 return get(type, stringValues);
873 }
874
875 // All other types go through DenseElementTypeInterface.
876 auto denseEltType = llvm::dyn_cast<DenseElementType>(eltType);
877 assert(denseEltType &&
878 "attempted to get DenseElementsAttr with unsupported element type");
880 for (Attribute attr : values) {
881 LogicalResult result = denseEltType.convertFromAttribute(attr, data);
882 if (failed(result))
883 return {};
884 }
885 return DenseTypedElementsAttr::getRaw(type, data);
886}
887
889 ArrayRef<bool> values) {
890 assert(hasSameNumElementsOrSplat(type, values));
891 assert(type.getElementType().isInteger(1));
892 return DenseTypedElementsAttr::getRaw(
893 type, ArrayRef<char>(reinterpret_cast<const char *>(values.data()),
894 values.size()));
895}
896
898 ArrayRef<StringRef> values) {
899 assert(!type.getElementType().isIntOrFloat());
900 return DenseStringElementsAttr::get(type, values);
901}
902
903/// Constructs a dense integer elements attribute from an array of APInt
904/// values. Each APInt value is expected to have the same bitwidth as the
905/// element type of 'type'.
907 ArrayRef<APInt> values) {
908 assert(type.getElementType().isIntOrIndex());
909 assert(hasSameNumElementsOrSplat(type, values));
910 size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType());
911 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, values);
912}
915 ComplexType complex = llvm::cast<ComplexType>(type.getElementType());
916 assert(llvm::isa<IntegerType>(complex.getElementType()));
917 assert(hasSameNumElementsOrSplat(type, values));
918 size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2;
919 ArrayRef<APInt> intVals(reinterpret_cast<const APInt *>(values.data()),
920 values.size() * 2);
921 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, intVals);
922}
923
924// Constructs a dense float elements attribute from an array of APFloat
925// values. Each APFloat value is expected to have the same bitwidth as the
926// element type of 'type'.
928 ArrayRef<APFloat> values) {
929 assert(llvm::isa<FloatType>(type.getElementType()));
930 assert(hasSameNumElementsOrSplat(type, values));
931 size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType());
932 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, values);
933}
937 ComplexType complex = llvm::cast<ComplexType>(type.getElementType());
938 assert(llvm::isa<FloatType>(complex.getElementType()));
939 assert(hasSameNumElementsOrSplat(type, values));
940 ArrayRef<APFloat> apVals(reinterpret_cast<const APFloat *>(values.data()),
941 values.size() * 2);
942 size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2;
943 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, apVals);
944}
945
946/// Construct a dense elements attribute from a raw buffer representing the
947/// data for this attribute. Users should generally not use this methods as
948/// the expected buffer format may not be a form the user expects.
951 return DenseTypedElementsAttr::getRaw(type, rawBuffer);
952}
953
954/// Returns true if the given buffer is a valid raw buffer for the given type.
956 ArrayRef<char> rawBuffer) {
957 size_t storageWidth = getDenseElementStorageWidth(type.getElementType());
958 size_t rawBufferWidth = rawBuffer.size() * CHAR_BIT;
959 int64_t numElements = type.getNumElements();
960
961 // The raw buffer is valid if it has a single element (splat) or the right
962 // number of elements.
963 return rawBufferWidth == storageWidth ||
964 rawBufferWidth == storageWidth * numElements;
965}
966
967/// Check the information for a C++ data type, check if this type is valid for
968/// the current attribute. This method is used to verify specific type
969/// invariants that the templatized 'getValues' method cannot.
970static bool isValidIntOrFloat(Type type, int64_t dataEltSize, bool isInt,
971 bool isSigned) {
972 // Make sure that the data element size is the same as the type element width.
973 auto denseEltBitWidth = getDenseElementBitWidth(type);
974 auto dataSize = static_cast<size_t>(dataEltSize * CHAR_BIT);
975 if (denseEltBitWidth != dataSize) {
976 LDBG() << "expected dense element bit width " << denseEltBitWidth
977 << " to match data size " << dataSize << " for type " << type;
978 return false;
979 }
980
981 // Check that the element type is either float or integer or index.
982 if (!isInt) {
983 bool valid = llvm::isa<FloatType>(type);
984 if (!valid)
985 LDBG() << "expected float type when isInt is false, but found " << type;
986 return valid;
987 }
988 if (type.isIndex())
989 return true;
990
991 auto intType = llvm::dyn_cast<IntegerType>(type);
992 if (!intType) {
993 LDBG() << "expected integer type when isInt is true, but found " << type;
994 return false;
995 }
996
997 // Make sure signedness semantics is consistent.
998 if (intType.isSignless())
999 return true;
1000
1001 bool valid = intType.isSigned() == isSigned;
1002 if (!valid)
1003 LDBG() << "expected signedness " << isSigned << " to match type " << type;
1004 return valid;
1005}
1006
1007/// Defaults down the subclass implementation.
1009 ArrayRef<char> data,
1010 int64_t dataEltSize,
1011 bool isInt, bool isSigned) {
1012 return DenseTypedElementsAttr::getRawComplex(type, data, dataEltSize, isInt,
1013 isSigned);
1014}
1016 ArrayRef<char> data,
1017 int64_t dataEltSize,
1018 bool isInt,
1019 bool isSigned) {
1020 return DenseTypedElementsAttr::getRawIntOrFloat(type, data, dataEltSize,
1021 isInt, isSigned);
1022}
1023
1025 bool isSigned) const {
1026 return ::isValidIntOrFloat(getElementType(), dataEltSize, isInt, isSigned);
1027}
1028bool DenseElementsAttr::isValidComplex(int64_t dataEltSize, bool isInt,
1029 bool isSigned) const {
1030 return ::isValidIntOrFloat(
1031 llvm::cast<ComplexType>(getElementType()).getElementType(),
1032 dataEltSize / 2, isInt, isSigned);
1033}
1034
1035/// Returns true if this attribute corresponds to a splat, i.e. if all element
1036/// values are the same.
1038 // Splat iff the data array has exactly one element.
1039 if (isa<DenseStringElementsAttr>(*this))
1040 return getRawStringData().size() == 1;
1041 // FP/Int case.
1042 size_t storageSize = llvm::divideCeil(
1044 return getRawData().size() == storageSize;
1045}
1046
1047/// Return if the given complex type has an integer element type.
1048static bool isComplexOfIntType(Type type) {
1049 return llvm::isa<IntegerType>(llvm::cast<ComplexType>(type).getElementType());
1050}
1051
1060
1063 auto eltTy = llvm::dyn_cast<FloatType>(getElementType());
1064 if (!eltTy)
1065 return failure();
1066 const auto &elementSemantics = eltTy.getFloatSemantics();
1068 getType(), FloatElementIterator(elementSemantics, raw_int_begin()),
1069 FloatElementIterator(elementSemantics, raw_int_end()));
1070}
1071
1074 auto complexTy = llvm::dyn_cast<ComplexType>(getElementType());
1075 if (!complexTy)
1076 return failure();
1077 auto eltTy = llvm::dyn_cast<FloatType>(complexTy.getElementType());
1078 if (!eltTy)
1079 return failure();
1080 const auto &semantics = eltTy.getFloatSemantics();
1082 getType(), {semantics, {*this, 0}},
1083 {semantics, {*this, static_cast<size_t>(getNumElements())}});
1084}
1085
1086/// Return the raw storage data held by this attribute.
1088 return static_cast<DenseTypedElementsAttrStorage *>(impl)->data;
1089}
1090
1094
1095/// Return a new DenseElementsAttr that has the same data as the current
1096/// attribute, but has been reshaped to 'newType'. The new type must have the
1097/// same total number of elements as well as element type.
1099 ShapedType curType = getType();
1100 if (curType == newType)
1101 return *this;
1102
1103 assert(newType.getElementType() == curType.getElementType() &&
1104 "expected the same element type");
1105 assert(newType.getNumElements() == curType.getNumElements() &&
1106 "expected the same number of elements");
1107 return DenseTypedElementsAttr::getRaw(newType, getRawData());
1108}
1109
1111 assert(isSplat() && "expected a splat type");
1112
1113 ShapedType curType = getType();
1114 if (curType == newType)
1115 return *this;
1116
1117 assert(newType.getElementType() == curType.getElementType() &&
1118 "expected the same element type");
1119 return DenseTypedElementsAttr::getRaw(newType, getRawData());
1120}
1121
1122/// Return a new DenseElementsAttr that has the same data as the current
1123/// attribute, but has bitcast elements such that it is now 'newType'. The new
1124/// type must have the same shape and element types of the same bitwidth as the
1125/// current type.
1127 ShapedType curType = getType();
1128 Type curElType = curType.getElementType();
1129 if (curElType == newElType)
1130 return *this;
1131
1132 assert(getDenseElementBitWidth(newElType) ==
1133 getDenseElementBitWidth(curElType) &&
1134 "expected element types with the same bitwidth");
1135 return DenseTypedElementsAttr::getRaw(curType.clone(newElType), getRawData());
1136}
1137
1140 function_ref<APInt(const APInt &)> mapping) const {
1141 return llvm::cast<DenseIntElementsAttr>(*this).mapValues(newElementType,
1142 mapping);
1143}
1144
1146 Type newElementType, function_ref<APInt(const APFloat &)> mapping) const {
1147 return llvm::cast<DenseFPElementsAttr>(*this).mapValues(newElementType,
1148 mapping);
1149}
1150
1151ShapedType DenseElementsAttr::getType() const {
1152 return static_cast<const DenseElementsAttributeStorage *>(impl)->type;
1153}
1154
1156 return getType().getElementType();
1157}
1158
1160 return getType().getNumElements();
1161}
1162
1163//===----------------------------------------------------------------------===//
1164// DenseTypedElementsAttr
1165//===----------------------------------------------------------------------===//
1166
1167/// Utility method to write a range of APInt values to a buffer.
1168template <typename APRangeT>
1169static void writeAPIntsToBuffer(size_t storageWidth,
1171 APRangeT &&values) {
1172 size_t numValues = llvm::size(values);
1173 data.resize(llvm::divideCeil(storageWidth * numValues, CHAR_BIT));
1174 size_t offset = 0;
1175 for (auto it = values.begin(), e = values.end(); it != e;
1176 ++it, offset += storageWidth) {
1177 assert((*it).getBitWidth() <= storageWidth);
1178 writeBits(data.data(), offset, *it);
1179 }
1180}
1181
1182/// Constructs a dense elements attribute from an array of raw APFloat values.
1183/// Each APFloat value is expected to have the same bitwidth as the element
1184/// type of 'type'. 'type' must be a vector or tensor with static shape.
1185DenseElementsAttr DenseTypedElementsAttr::getRaw(ShapedType type,
1186 size_t storageWidth,
1187 ArrayRef<APFloat> values) {
1188 SmallVector<char> data;
1189 auto unwrapFloat = [](const APFloat &val) { return val.bitcastToAPInt(); };
1190 writeAPIntsToBuffer(storageWidth, data, llvm::map_range(values, unwrapFloat));
1191 return DenseTypedElementsAttr::getRaw(type, data);
1192}
1193
1194/// Constructs a dense elements attribute from an array of raw APInt values.
1195/// Each APInt value is expected to have the same bitwidth as the element type
1196/// of 'type'.
1197DenseElementsAttr DenseTypedElementsAttr::getRaw(ShapedType type,
1198 size_t storageWidth,
1199 ArrayRef<APInt> values) {
1200 SmallVector<char> data;
1201 writeAPIntsToBuffer(storageWidth, data, values);
1202 return DenseTypedElementsAttr::getRaw(type, data);
1203}
1204
1205DenseElementsAttr DenseTypedElementsAttr::getRaw(ShapedType type,
1206 ArrayRef<char> data) {
1207 assert(type.hasStaticShape() && "type must have static shape");
1208 assert(isValidRawBuffer(type, data));
1209 return Base::get(type.getContext(), type, data);
1210}
1211
1212/// Overload of the raw 'get' method that asserts that the given type is of
1213/// complex type. This method is used to verify type invariants that the
1214/// templatized 'get' method cannot.
1215DenseElementsAttr DenseTypedElementsAttr::getRawComplex(ShapedType type,
1216 ArrayRef<char> data,
1217 int64_t dataEltSize,
1218 bool isInt,
1219 bool isSigned) {
1220 assert(::isValidIntOrFloat(
1221 llvm::cast<ComplexType>(type.getElementType()).getElementType(),
1222 dataEltSize / 2, isInt, isSigned) &&
1223 "Try re-running with -debug-only=builtinattributes");
1224
1225 int64_t numElements = data.size() / dataEltSize;
1226 (void)numElements;
1227 assert(numElements == 1 || numElements == type.getNumElements());
1228 return getRaw(type, data);
1229}
1230
1231/// Overload of the 'getRaw' method that asserts that the given type is of
1232/// integer type. This method is used to verify type invariants that the
1233/// templatized 'get' method cannot.
1234DenseElementsAttr DenseTypedElementsAttr::getRawIntOrFloat(ShapedType type,
1235 ArrayRef<char> data,
1236 int64_t dataEltSize,
1237 bool isInt,
1238 bool isSigned) {
1239 assert(::isValidIntOrFloat(type.getElementType(), dataEltSize, isInt,
1240 isSigned) &&
1241 "Try re-running with -debug-only=builtinattributes");
1242
1243 int64_t numElements = data.size() / dataEltSize;
1244 assert(numElements == 1 || numElements == type.getNumElements());
1245 (void)numElements;
1246 return getRaw(type, data);
1247}
1248
1249void DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
1250 const char *inRawData, char *outRawData, size_t elementBitWidth,
1251 size_t numElements) {
1252 using llvm::support::ulittle16_t;
1253 using llvm::support::ulittle32_t;
1254 using llvm::support::ulittle64_t;
1255
1256 assert(llvm::endianness::native == llvm::endianness::big);
1257 // NOLINT to avoid warning message about replacing by static_assert()
1258
1259 // Following std::copy_n always converts endianness on BE machine.
1260 switch (elementBitWidth) {
1261 case 16: {
1262 const ulittle16_t *inRawDataPos =
1263 reinterpret_cast<const ulittle16_t *>(inRawData);
1264 uint16_t *outDataPos = reinterpret_cast<uint16_t *>(outRawData);
1265 std::copy_n(inRawDataPos, numElements, outDataPos);
1266 break;
1267 }
1268 case 32: {
1269 const ulittle32_t *inRawDataPos =
1270 reinterpret_cast<const ulittle32_t *>(inRawData);
1271 uint32_t *outDataPos = reinterpret_cast<uint32_t *>(outRawData);
1272 std::copy_n(inRawDataPos, numElements, outDataPos);
1273 break;
1274 }
1275 case 64: {
1276 const ulittle64_t *inRawDataPos =
1277 reinterpret_cast<const ulittle64_t *>(inRawData);
1278 uint64_t *outDataPos = reinterpret_cast<uint64_t *>(outRawData);
1279 std::copy_n(inRawDataPos, numElements, outDataPos);
1280 break;
1281 }
1282 default: {
1283 size_t nBytes = elementBitWidth / CHAR_BIT;
1284 for (size_t i = 0; i < nBytes; i++)
1285 std::copy_n(inRawData + (nBytes - 1 - i), 1, outRawData + i);
1286 break;
1287 }
1288 }
1289}
1290
1291void DenseTypedElementsAttr::convertEndianOfArrayRefForBEmachine(
1292 ArrayRef<char> inRawData, MutableArrayRef<char> outRawData,
1293 ShapedType type) {
1294 size_t numElements = type.getNumElements();
1295 Type elementType = type.getElementType();
1296 if (ComplexType complexTy = llvm::dyn_cast<ComplexType>(elementType)) {
1297 elementType = complexTy.getElementType();
1298 numElements = numElements * 2;
1299 }
1300 size_t elementBitWidth = getDenseElementStorageWidth(elementType);
1301 assert(numElements * elementBitWidth == inRawData.size() * CHAR_BIT &&
1302 inRawData.size() <= outRawData.size());
1303 if (elementBitWidth <= CHAR_BIT)
1304 std::memcpy(outRawData.begin(), inRawData.begin(), inRawData.size());
1305 else
1306 convertEndianOfCharForBEmachine(inRawData.begin(), outRawData.begin(),
1307 elementBitWidth, numElements);
1308}
1309
1310//===----------------------------------------------------------------------===//
1311// DenseFPElementsAttr
1312//===----------------------------------------------------------------------===//
1313
1314template <typename Fn, typename Attr>
1315static ShapedType mappingHelper(Fn mapping, Attr &attr, ShapedType inType,
1316 Type newElementType,
1318 size_t bitWidth = getDenseElementBitWidth(newElementType);
1319 size_t storageBitWidth = getDenseElementStorageWidth(bitWidth);
1320
1321 ShapedType newArrayType = inType.cloneWith(inType.getShape(), newElementType);
1322
1323 size_t numRawElements = attr.isSplat() ? 1 : newArrayType.getNumElements();
1324 data.resize(llvm::divideCeil(storageBitWidth * numRawElements, CHAR_BIT));
1325
1326 // Functor used to process a single element value of the attribute.
1327 auto processElt = [&](decltype(*attr.begin()) value, size_t index) {
1328 auto newInt = mapping(value);
1329 assert(newInt.getBitWidth() == bitWidth);
1330 writeBits(data.data(), index * storageBitWidth, newInt);
1331 };
1332
1333 // Check for the splat case.
1334 if (attr.isSplat()) {
1335 processElt(*attr.begin(), /*index=*/0);
1336 return newArrayType;
1337 }
1338
1339 // Otherwise, process all of the element values.
1340 uint64_t elementIdx = 0;
1341 for (auto value : attr)
1342 processElt(value, elementIdx++);
1343 return newArrayType;
1344}
1345
1347 Type newElementType, function_ref<APInt(const APFloat &)> mapping) const {
1348 llvm::SmallVector<char, 8> elementData;
1349 auto newArrayType =
1350 mappingHelper(mapping, *this, getType(), newElementType, elementData);
1351
1352 return getRaw(newArrayType, elementData);
1353}
1354
1355/// Method for supporting type inquiry through isa, cast and dyn_cast.
1357 if (auto denseAttr = llvm::dyn_cast<DenseElementsAttr>(attr))
1358 return llvm::isa<FloatType>(denseAttr.getType().getElementType());
1359 return false;
1360}
1361
1362//===----------------------------------------------------------------------===//
1363// DenseIntElementsAttr
1364//===----------------------------------------------------------------------===//
1365
1367 Type newElementType, function_ref<APInt(const APInt &)> mapping) const {
1368 llvm::SmallVector<char, 8> elementData;
1369 auto newArrayType =
1370 mappingHelper(mapping, *this, getType(), newElementType, elementData);
1371 return getRaw(newArrayType, elementData);
1372}
1373
1374/// Method for supporting type inquiry through isa, cast and dyn_cast.
1376 if (auto denseAttr = llvm::dyn_cast<DenseElementsAttr>(attr))
1377 return denseAttr.getType().getElementType().isIntOrIndex();
1378 return false;
1379}
1380
1381//===----------------------------------------------------------------------===//
1382// DenseResourceElementsAttr
1383//===----------------------------------------------------------------------===//
1384
1385DenseResourceElementsAttr
1386DenseResourceElementsAttr::get(ShapedType type,
1388 return Base::get(type.getContext(), type, handle);
1389}
1390
1391DenseResourceElementsAttr DenseResourceElementsAttr::get(ShapedType type,
1392 StringRef blobName,
1393 AsmResourceBlob blob) {
1394 // Extract the builtin dialect resource manager from context and construct a
1395 // handle by inserting a new resource using the provided blob.
1396 auto &manager =
1398 return get(type, manager.insert(blobName, std::move(blob)));
1399}
1400
1401ArrayRef<char> DenseResourceElementsAttr::getData() {
1402 if (AsmResourceBlob *blob = this->getRawHandle().getBlob())
1403 return blob->getDataAs<char>();
1404 return {};
1405}
1406
1407//===----------------------------------------------------------------------===//
1408// DenseResourceElementsAttrBase
1409//===----------------------------------------------------------------------===//
1410
1411namespace {
1412/// Instantiations of this class provide utilities for interacting with native
1413/// data types in the context of DenseResourceElementsAttr.
1414template <typename T>
1415struct DenseResourceAttrUtil;
1416template <size_t width, bool isSigned>
1417struct DenseResourceElementsAttrIntUtil {
1418 static bool checkElementType(Type eltType) {
1419 IntegerType type = llvm::dyn_cast<IntegerType>(eltType);
1420 if (!type || type.getWidth() != width)
1421 return false;
1422 return isSigned ? !type.isUnsigned() : !type.isSigned();
1423 }
1424};
1425template <>
1426struct DenseResourceAttrUtil<bool> {
1427 static bool checkElementType(Type eltType) {
1428 return eltType.isSignlessInteger(1);
1429 }
1430};
1431template <>
1432struct DenseResourceAttrUtil<int8_t>
1433 : public DenseResourceElementsAttrIntUtil<8, true> {};
1434template <>
1435struct DenseResourceAttrUtil<uint8_t>
1436 : public DenseResourceElementsAttrIntUtil<8, false> {};
1437template <>
1438struct DenseResourceAttrUtil<int16_t>
1439 : public DenseResourceElementsAttrIntUtil<16, true> {};
1440template <>
1441struct DenseResourceAttrUtil<uint16_t>
1442 : public DenseResourceElementsAttrIntUtil<16, false> {};
1443template <>
1444struct DenseResourceAttrUtil<int32_t>
1445 : public DenseResourceElementsAttrIntUtil<32, true> {};
1446template <>
1447struct DenseResourceAttrUtil<uint32_t>
1448 : public DenseResourceElementsAttrIntUtil<32, false> {};
1449template <>
1450struct DenseResourceAttrUtil<int64_t>
1451 : public DenseResourceElementsAttrIntUtil<64, true> {};
1452template <>
1453struct DenseResourceAttrUtil<uint64_t>
1454 : public DenseResourceElementsAttrIntUtil<64, false> {};
1455template <>
1456struct DenseResourceAttrUtil<float> {
1457 static bool checkElementType(Type eltType) { return eltType.isF32(); }
1458};
1459template <>
1460struct DenseResourceAttrUtil<double> {
1461 static bool checkElementType(Type eltType) { return eltType.isF64(); }
1462};
1463} // namespace
1464
1465template <typename T>
1466DenseResourceElementsAttrBase<T>
1467DenseResourceElementsAttrBase<T>::get(ShapedType type, StringRef blobName,
1468 AsmResourceBlob blob) {
1469 // Check that the blob is in the form we were expecting.
1470 assert(blob.getDataAlignment() == alignof(T) &&
1471 "alignment mismatch between expected alignment and blob alignment");
1472 assert(((blob.getData().size() % sizeof(T)) == 0) &&
1473 "size mismatch between expected element width and blob size");
1474 assert(DenseResourceAttrUtil<T>::checkElementType(type.getElementType()) &&
1475 "invalid shape element type for provided type `T`");
1476 return llvm::cast<DenseResourceElementsAttrBase<T>>(
1477 DenseResourceElementsAttr::get(type, blobName, std::move(blob)));
1478}
1479
1480template <typename T>
1481std::optional<ArrayRef<T>>
1483 if (AsmResourceBlob *blob = this->getRawHandle().getBlob())
1484 return blob->template getDataAs<T>();
1485 return std::nullopt;
1486}
1487
1488template <typename T>
1490 auto resourceAttr = llvm::dyn_cast<DenseResourceElementsAttr>(attr);
1491 return resourceAttr && DenseResourceAttrUtil<T>::checkElementType(
1492 resourceAttr.getElementType());
1493}
1494
1495namespace mlir {
1496namespace detail {
1497// Explicit instantiation for all the supported DenseResourceElementsAttr.
1509} // namespace detail
1510} // namespace mlir
1511
1512//===----------------------------------------------------------------------===//
1513// SparseElementsAttr
1514//===----------------------------------------------------------------------===//
1515
1516/// Get a zero APFloat for the given sparse attribute.
1517APFloat SparseElementsAttr::getZeroAPFloat() const {
1518 auto eltType = llvm::cast<FloatType>(getElementType());
1519 return APFloat(eltType.getFloatSemantics());
1520}
1521
1522/// Get a zero APInt for the given sparse attribute.
1523APInt SparseElementsAttr::getZeroAPInt() const {
1524 auto eltType = llvm::cast<IntegerType>(getElementType());
1525 return APInt::getZero(eltType.getWidth());
1526}
1527
1528/// Get a zero attribute for the given attribute type.
1529Attribute SparseElementsAttr::getZeroAttr() const {
1530 auto eltType = getElementType();
1531
1532 // Handle floating point elements.
1533 if (llvm::isa<FloatType>(eltType))
1534 return FloatAttr::get(eltType, 0);
1535
1536 // Handle complex elements.
1537 if (auto complexTy = llvm::dyn_cast<ComplexType>(eltType)) {
1538 auto eltType = complexTy.getElementType();
1539 Attribute zero;
1540 if (llvm::isa<FloatType>(eltType))
1541 zero = FloatAttr::get(eltType, 0);
1542 else // must be integer
1543 zero = IntegerAttr::get(eltType, 0);
1544 return ArrayAttr::get(complexTy.getContext(),
1545 ArrayRef<Attribute>{zero, zero});
1546 }
1547
1548 // Handle string type.
1549 if (llvm::isa<DenseStringElementsAttr>(getValues()))
1550 return StringAttr::get("", eltType);
1551
1552 // MXI8 elements use signless i8 attributes for their encoded bits.
1553 if (llvm::isa<MXI8Type>(eltType))
1554 return IntegerAttr::get(IntegerType::get(eltType.getContext(), 8), 0);
1555
1556 // Otherwise, this is an integer.
1557 return IntegerAttr::get(eltType, 0);
1558}
1559
1560/// Flatten, and return, all of the sparse indices in this attribute in
1561/// row-major order.
1562SmallVector<ptrdiff_t> SparseElementsAttr::getFlattenedSparseIndices() const {
1563 SmallVector<ptrdiff_t> flatSparseIndices;
1564
1565 // The sparse indices are 64-bit integers, so we can reinterpret the raw data
1566 // as a 1-D index array.
1567 auto sparseIndices = getIndices();
1568 auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1569 if (sparseIndices.isSplat()) {
1570 SmallVector<uint64_t, 8> indices(getType().getRank(),
1571 *sparseIndexValues.begin());
1572 flatSparseIndices.push_back(getFlattenedIndex(indices));
1573 return flatSparseIndices;
1574 }
1575
1576 // Otherwise, reinterpret each index as an ArrayRef when flattening.
1577 auto numSparseIndices = sparseIndices.getType().getDimSize(0);
1578 size_t rank = getType().getRank();
1579 for (size_t i = 0, e = numSparseIndices; i != e; ++i)
1580 flatSparseIndices.push_back(getFlattenedIndex(
1581 {&*std::next(sparseIndexValues.begin(), i * rank), rank}));
1582 return flatSparseIndices;
1583}
1584
1585LogicalResult
1586SparseElementsAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1587 ShapedType type, DenseIntElementsAttr sparseIndices,
1588 DenseElementsAttr values) {
1589 ShapedType valuesType = values.getType();
1590 if (valuesType.getRank() != 1)
1591 return emitError() << "expected 1-d tensor for sparse element values";
1592
1593 // Verify the indices and values shape.
1594 ShapedType indicesType = sparseIndices.getType();
1595 auto emitShapeError = [&]() {
1596 return emitError() << "expected shape ([" << type.getShape()
1597 << "]); inferred shape of indices literal (["
1598 << indicesType.getShape()
1599 << "]); inferred shape of values literal (["
1600 << valuesType.getShape() << "])";
1601 };
1602 // Verify indices shape.
1603 size_t rank = type.getRank(), indicesRank = indicesType.getRank();
1604 if (indicesRank == 2) {
1605 if (indicesType.getDimSize(1) != static_cast<int64_t>(rank))
1606 return emitShapeError();
1607 } else if (indicesRank != 1 || rank != 1) {
1608 return emitShapeError();
1609 }
1610 // Verify the values shape.
1611 int64_t numSparseIndices = indicesType.getDimSize(0);
1612 if (numSparseIndices != valuesType.getDimSize(0))
1613 return emitShapeError();
1614
1615 // Verify that the sparse indices are within the value shape.
1616 auto emitIndexError = [&](unsigned indexNum, ArrayRef<uint64_t> index) {
1617 return emitError()
1618 << "sparse index #" << indexNum
1619 << " is not contained within the value shape, with index=[" << index
1620 << "], and type=" << type;
1621 };
1622
1623 // Handle the case where the index values are a splat.
1624 auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1625 if (sparseIndices.isSplat()) {
1626 SmallVector<uint64_t> indices(rank, *sparseIndexValues.begin());
1627 if (!ElementsAttr::isValidIndex(type, indices))
1628 return emitIndexError(0, indices);
1629 return success();
1630 }
1631
1632 // Otherwise, reinterpret each index as an ArrayRef.
1633 for (size_t i = 0, e = numSparseIndices; i != e; ++i) {
1634 ArrayRef<uint64_t> index(&*std::next(sparseIndexValues.begin(), i * rank),
1635 rank);
1636 if (!ElementsAttr::isValidIndex(type, index))
1637 return emitIndexError(i, index);
1638 }
1639
1640 return success();
1641}
1642
1643//===----------------------------------------------------------------------===//
1644// DistinctAttr
1645//===----------------------------------------------------------------------===//
1646
1648 return Base::get(referencedAttr.getContext(), referencedAttr);
1649}
1650
1652 return getImpl()->referencedAttr;
1653}
1654
1655//===----------------------------------------------------------------------===//
1656// Attribute Utilities
1657//===----------------------------------------------------------------------===//
1658
1660 int64_t offset,
1661 MLIRContext *context) {
1662 AffineExpr expr;
1663 unsigned nSymbols = 0;
1664
1665 // AffineExpr for offset.
1666 // Static case.
1667 if (ShapedType::isStatic(offset)) {
1668 auto cst = getAffineConstantExpr(offset, context);
1669 expr = cst;
1670 } else {
1671 // Dynamic case, new symbol for the offset.
1672 auto sym = getAffineSymbolExpr(nSymbols++, context);
1673 expr = sym;
1674 }
1675
1676 // AffineExpr for strides.
1677 for (const auto &en : llvm::enumerate(strides)) {
1678 auto dim = en.index();
1679 auto stride = en.value();
1680 auto d = getAffineDimExpr(dim, context);
1681 AffineExpr mult;
1682 // Static case.
1683 if (ShapedType::isStatic(stride))
1684 mult = getAffineConstantExpr(stride, context);
1685 else
1686 // Dynamic case, new symbol for each new stride.
1687 mult = getAffineSymbolExpr(nSymbols++, context);
1688 expr = expr + d * mult;
1689 }
1690
1691 return AffineMap::get(strides.size(), nSymbols, expr);
1692}
return success()
static bool isValidIntOrFloat(Type type, int64_t dataEltSize, bool isInt, bool isSigned)
Check the information for a C++ data type, check if this type is valid for the current attribute.
static void copyAPIntToArrayForBEmachine(APInt value, size_t numBytes, char *result)
Copy actual numBytes data from value (APInt) to char array(result) for BE format.
static ShapedType mappingHelper(Fn mapping, Attr &attr, ShapedType inType, Type newElementType, llvm::SmallVectorImpl< char > &data)
static bool hasSameNumElementsOrSplat(ShapedType type, const Values &values)
Returns true if 'values' corresponds to a splat, i.e.
static void writeAPIntsToBuffer(size_t storageWidth, SmallVectorImpl< char > &data, APRangeT &&values)
Utility method to write a range of APInt values to a buffer.
static bool dictionaryAttrSort(ArrayRef< NamedAttribute > value, SmallVectorImpl< NamedAttribute > &storage)
Helper function that does either an in place sort or sorts from source array into destination.
static std::optional< NamedAttribute > findDuplicateElement(ArrayRef< NamedAttribute > value)
Returns an entry with a duplicate name from the given sorted array of named attributes.
static size_t getDenseElementStorageWidth(size_t origWidth)
Get the bitwidth of a dense element type within the buffer.
static void copyArrayToAPIntForBEmachine(const char *inArray, size_t numBytes, APInt &result)
Copy numBytes data from inArray(char array) to result(APINT) for BE format.
static bool isComplexOfIntType(Type type)
Return if the given complex type has an integer element type.
static int64_t getNumElements(Type t)
Compute the total number of elements in the given type, also taking into account nested types.
b getContext())
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static const llvm::fltSemantics * getFloatSemantics(TruncfSrcElemTypes etype)
Float semantics the element type attributes of xevm.truncf and xevm.extf stand for.
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
MLIRContext * getContext() const
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalRSquare()=0
Parse a ] token if present.
virtual ParseResult parseFloat(double &result)=0
Parse a floating point value from the stream.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual raw_ostream & getStream() const
Return the raw output stream used by this printer.
This class represents a processed binary blob of data.
Definition AsmState.h:91
size_t getDataAlignment() const
Return the alignment of the underlying data.
Definition AsmState.h:142
ArrayRef< char > getData() const
Return the raw underlying data of this blob.
Definition AsmState.h:145
Attributes are known-constant values of operations.
Definition Attributes.h:25
void print(raw_ostream &os, bool elideType=false) const
Print the attribute.
MLIRContext * getContext() const
Return the context this attribute belongs to.
static Attribute getFromOpaquePointer(const void *ptr)
Construct an attribute from the opaque pointer representation.
Definition Attributes.h:77
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
static bool classof(Attribute attr)
Methods for support type inquiry through isa, cast, and dyn_cast.
constexpr Attribute()=default
bool getValue() const
Return the boolean value of this attribute.
Attribute operator*() const
Accesses the Attribute value at this iterator position.
A utility iterator that allows walking over the internal bool values.
bool operator*() const
Accesses the bool value at this iterator position.
Iterator for walking over complex APFloat values.
A utility iterator that allows walking over the internal raw complex APInt values.
mlir::Complex< APInt > operator*() const
Accesses the raw mlir::Complex<APInt> value at this iterator position.
Iterator for walking over APFloat values.
A utility iterator that allows walking over the internal raw APInt values.
APInt operator*() const
Accesses the raw APInt value at this iterator position.
An attribute that represents a reference to a dense vector or tensor object.
ArrayRef< StringRef > getRawStringData() const
Return the raw StringRef data held by this attribute.
IntElementIterator raw_int_begin() const
Iterators to various elements that require out-of-line definition.
static DenseElementsAttr getRawIntOrFloat(ShapedType type, ArrayRef< char > data, int64_t dataEltSize, bool isInt, bool isSigned)
Overload of the raw 'get' method that asserts that the given type is of integer or floating-point typ...
static DenseElementsAttr getRawComplex(ShapedType type, ArrayRef< char > data, int64_t dataEltSize, bool isInt, bool isSigned)
Overload of the raw 'get' method that asserts that the given type is of complex type.
static bool classof(Attribute attr)
Method for support type inquiry through isa, cast and dyn_cast.
bool isValidComplex(int64_t dataEltSize, bool isInt, bool isSigned) const
DenseElementsAttr resizeSplat(ShapedType newType)
Return a new DenseElementsAttr that has the same data as the current attribute, but with a different ...
detail::ElementsAttrRange< IteratorT > iterator_range_impl
The iterator range over the given iterator type T.
int64_t getNumElements() const
Returns the number of elements held by this attribute.
static DenseElementsAttr getFromRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Construct a dense elements attribute from a raw buffer representing the data for this attribute.
static bool isValidRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Returns true if the given buffer is a valid raw buffer for the given type.
int64_t size() const
Returns the number of elements held by this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
ArrayRef< char > getRawData() const
Return the raw storage data held by this attribute.
constexpr Attribute()=default
DenseElementsAttr mapValues(Type newElementType, function_ref< APInt(const APInt &)> mapping) const
Generates a new DenseElementsAttr by mapping each int value to a new underlying APInt.
Type getElementType() const
Return the element type of this DenseElementsAttr.
FailureOr< iterator_range_impl< ComplexFloatElementIterator > > tryGetComplexFloatValues() const
IntElementIterator raw_int_end() const
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
FailureOr< iterator_range_impl< FloatElementIterator > > tryGetFloatValues() const
DenseElementsAttr bitcast(Type newElType)
Return a new DenseElementsAttr that has the same data as the current attribute, but has bitcast eleme...
bool isValidIntOrFloat(int64_t dataEltSize, bool isInt, bool isSigned) const
DenseElementsAttr reshape(ShapedType newType)
Return a new DenseElementsAttr that has the same data as the current attribute, but has been reshaped...
FailureOr< iterator_range_impl< ComplexIntElementIterator > > tryGetComplexIntValues() const
static bool classof(Attribute attr)
Method for supporting type inquiry through isa, cast and dyn_cast.
DenseElementsAttr mapValues(Type newElementType, function_ref< APInt(const APFloat &)> mapping) const
Generates a new DenseElementsAttr by mapping each value attribute, and constructing the DenseElements...
static bool classof(Attribute attr)
Method for supporting type inquiry through isa, cast and dyn_cast.
DenseElementsAttr mapValues(Type newElementType, function_ref< APInt(const APInt &)> mapping) const
Generates a new DenseElementsAttr by mapping each value attribute, and constructing the DenseElements...
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
Definition Dialect.cpp:95
An attribute that associates a referenced attribute with a unique identifier.
static DistinctAttr create(Attribute referencedAttr)
Creates a distinct attribute that associates a referenced attribute with a unique identifier.
Attribute getReferencedAttr() const
Returns the referenced attribute.
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isF64() const
Definition Types.cpp:41
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isIndex() const
Definition Types.cpp:56
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
bool isF32() const
Definition Types.cpp:40
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
Base class for DenseArrayAttr that is instantiated and specialized for each supported element type be...
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< T > content)
Builder from ArrayRef<T>.
static bool classof(Attribute attr)
Support for isa<>/cast<>.
void print(AsmPrinter &printer) const
Print the short form [42, 100, -1] without any type prefix.
static Attribute parse(AsmParser &parser, Type type)
Parse the short form [42, 100, -1] without any type prefix.
static Attribute parseWithoutBraces(AsmParser &parser, Type type)
Parse the short form 42, 100, -1 without any type prefix or braces.
void printWithoutBraces(raw_ostream &os) const
Print the short form 42, 100, -1 without any braces or type prefix.
Impl iterator for indexed DenseElementsAttr iterators that records a data pointer and data index that...
Base class for DenseResourceElementsAttr that is instantiated and specialized for each supported elem...
static bool classof(Attribute attr)
Support for isa<>/cast<>.
static DenseResourceElementsAttrBase< T > get(ShapedType type, StringRef blobName, AsmResourceBlob blob)
A builder that inserts a new resource using the provided blob.
std::optional< ArrayRef< T > > tryGetAsArrayRef() const
Return the data of this attribute as an ArrayRef<T> if it is present, returns std::nullopt otherwise.
static ConcreteT get(MLIRContext *ctx, Args &&...args)
Get or create a new ConcreteT instance within the ctx.
AttrTypeReplacer.
llvm::APInt readBits(const char *rawData, size_t bitPos, size_t bitWidth)
Read bitWidth bits from byte-aligned position in rawData and return as an APInt.
size_t getDenseElementBitWidth(Type eltType)
Return the bit width which DenseElementsAttr should use for this type.
void writeBits(char *rawData, size_t bitPos, llvm::APInt value)
Write value to byte-aligned position bitPos in rawData.
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
DialectResourceBlobHandle< BuiltinDialect > DenseResourceElementsHandle
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
std::conditional_t< std::is_floating_point_v< T >, std::complex< T >, NonFloatComplex< T > > Complex
Definition Complex.h:265
AffineMap makeStridedLinearLayoutMap(ArrayRef< int64_t > strides, int64_t offset, MLIRContext *context)
Given a list of strides (in which ShapedType::kDynamic represents a dynamic value),...
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)
static ManagerInterface & getManagerInterface(MLIRContext *ctx)
An attribute representing a reference to a dense vector or tensor object.
An attribute representing a reference to a dense vector or tensor object containing strings.
An attribute representing a reference to a dense vector or tensor object.