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 
9 #include "mlir/IR/BuiltinAttributes.h"
10 #include "AttributeDetail.h"
11 #include "mlir/IR/AffineMap.h"
12 #include "mlir/IR/BuiltinDialect.h"
13 #include "mlir/IR/Dialect.h"
14 #include "mlir/IR/IntegerSet.h"
15 #include "mlir/IR/Operation.h"
16 #include "mlir/IR/SymbolTable.h"
17 #include "mlir/IR/Types.h"
18 #include "mlir/Interfaces/DecodeAttributesInterfaces.h"
19 #include "llvm/ADT/APSInt.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/Support/Endian.h"
22 
23 using namespace mlir;
24 using namespace mlir::detail;
25 
26 //===----------------------------------------------------------------------===//
27 /// Tablegen Attribute Definitions
28 //===----------------------------------------------------------------------===//
29 
30 #define GET_ATTRDEF_CLASSES
31 #include "mlir/IR/BuiltinAttributes.cpp.inc"
32 
33 //===----------------------------------------------------------------------===//
34 // BuiltinDialect
35 //===----------------------------------------------------------------------===//
36 
37 void BuiltinDialect::registerAttributes() {
38   addAttributes<AffineMapAttr, ArrayAttr, DenseIntOrFPElementsAttr,
39                 DenseStringElementsAttr, DictionaryAttr, FloatAttr,
40                 SymbolRefAttr, IntegerAttr, IntegerSetAttr, OpaqueAttr,
41                 OpaqueElementsAttr, SparseElementsAttr, StringAttr, TypeAttr,
42                 UnitAttr>();
43 }
44 
45 //===----------------------------------------------------------------------===//
46 // ArrayAttr
47 //===----------------------------------------------------------------------===//
48 
49 void ArrayAttr::walkImmediateSubElements(
50     function_ref<void(Attribute)> walkAttrsFn,
51     function_ref<void(Type)> walkTypesFn) const {
52   for (Attribute attr : getValue())
53     walkAttrsFn(attr);
54 }
55 
56 SubElementAttrInterface ArrayAttr::replaceImmediateSubAttribute(
57     ArrayRef<std::pair<size_t, Attribute>> replacements) const {
58   std::vector<Attribute> vector = getValue().vec();
59   for (auto &it : replacements) {
60     vector[it.first] = it.second;
61   }
62   return get(getContext(), vector);
63 }
64 
65 //===----------------------------------------------------------------------===//
66 // DictionaryAttr
67 //===----------------------------------------------------------------------===//
68 
69 /// Helper function that does either an in place sort or sorts from source array
70 /// into destination. If inPlace then storage is both the source and the
71 /// destination, else value is the source and storage destination. Returns
72 /// whether source was sorted.
73 template <bool inPlace>
74 static bool dictionaryAttrSort(ArrayRef<NamedAttribute> value,
75                                SmallVectorImpl<NamedAttribute> &storage) {
76   // Specialize for the common case.
77   switch (value.size()) {
78   case 0:
79     // Zero already sorted.
80     if (!inPlace)
81       storage.clear();
82     break;
83   case 1:
84     // One already sorted but may need to be copied.
85     if (!inPlace)
86       storage.assign({value[0]});
87     break;
88   case 2: {
89     bool isSorted = value[0] < value[1];
90     if (inPlace) {
91       if (!isSorted)
92         std::swap(storage[0], storage[1]);
93     } else if (isSorted) {
94       storage.assign({value[0], value[1]});
95     } else {
96       storage.assign({value[1], value[0]});
97     }
98     return !isSorted;
99   }
100   default:
101     if (!inPlace)
102       storage.assign(value.begin(), value.end());
103     // Check to see they are sorted already.
104     bool isSorted = llvm::is_sorted(value);
105     // If not, do a general sort.
106     if (!isSorted)
107       llvm::array_pod_sort(storage.begin(), storage.end());
108     return !isSorted;
109   }
110   return false;
111 }
112 
113 /// Returns an entry with a duplicate name from the given sorted array of named
114 /// attributes. Returns llvm::None if all elements have unique names.
115 static Optional<NamedAttribute>
116 findDuplicateElement(ArrayRef<NamedAttribute> value) {
117   const Optional<NamedAttribute> none{llvm::None};
118   if (value.size() < 2)
119     return none;
120 
121   if (value.size() == 2)
122     return value[0].getName() == value[1].getName() ? value[0] : none;
123 
124   const auto *it = std::adjacent_find(value.begin(), value.end(),
125                                       [](NamedAttribute l, NamedAttribute r) {
126                                         return l.getName() == r.getName();
127                                       });
128   return it != value.end() ? *it : none;
129 }
130 
131 bool DictionaryAttr::sort(ArrayRef<NamedAttribute> value,
132                           SmallVectorImpl<NamedAttribute> &storage) {
133   bool isSorted = dictionaryAttrSort</*inPlace=*/false>(value, storage);
134   assert(!findDuplicateElement(storage) &&
135          "DictionaryAttr element names must be unique");
136   return isSorted;
137 }
138 
139 bool DictionaryAttr::sortInPlace(SmallVectorImpl<NamedAttribute> &array) {
140   bool isSorted = dictionaryAttrSort</*inPlace=*/true>(array, array);
141   assert(!findDuplicateElement(array) &&
142          "DictionaryAttr element names must be unique");
143   return isSorted;
144 }
145 
146 Optional<NamedAttribute>
147 DictionaryAttr::findDuplicate(SmallVectorImpl<NamedAttribute> &array,
148                               bool isSorted) {
149   if (!isSorted)
150     dictionaryAttrSort</*inPlace=*/true>(array, array);
151   return findDuplicateElement(array);
152 }
153 
154 DictionaryAttr DictionaryAttr::get(MLIRContext *context,
155                                    ArrayRef<NamedAttribute> value) {
156   if (value.empty())
157     return DictionaryAttr::getEmpty(context);
158 
159   // We need to sort the element list to canonicalize it.
160   SmallVector<NamedAttribute, 8> storage;
161   if (dictionaryAttrSort</*inPlace=*/false>(value, storage))
162     value = storage;
163   assert(!findDuplicateElement(value) &&
164          "DictionaryAttr element names must be unique");
165   return Base::get(context, value);
166 }
167 /// Construct a dictionary with an array of values that is known to already be
168 /// sorted by name and uniqued.
169 DictionaryAttr DictionaryAttr::getWithSorted(MLIRContext *context,
170                                              ArrayRef<NamedAttribute> value) {
171   if (value.empty())
172     return DictionaryAttr::getEmpty(context);
173   // Ensure that the attribute elements are unique and sorted.
174   assert(llvm::is_sorted(
175              value, [](NamedAttribute l, NamedAttribute r) { return l < r; }) &&
176          "expected attribute values to be sorted");
177   assert(!findDuplicateElement(value) &&
178          "DictionaryAttr element names must be unique");
179   return Base::get(context, value);
180 }
181 
182 /// Return the specified attribute if present, null otherwise.
183 Attribute DictionaryAttr::get(StringRef name) const {
184   auto it = impl::findAttrSorted(begin(), end(), name);
185   return it.second ? it.first->getValue() : Attribute();
186 }
187 Attribute DictionaryAttr::get(StringAttr name) const {
188   auto it = impl::findAttrSorted(begin(), end(), name);
189   return it.second ? it.first->getValue() : Attribute();
190 }
191 
192 /// Return the specified named attribute if present, None otherwise.
193 Optional<NamedAttribute> DictionaryAttr::getNamed(StringRef name) const {
194   auto it = impl::findAttrSorted(begin(), end(), name);
195   return it.second ? *it.first : Optional<NamedAttribute>();
196 }
197 Optional<NamedAttribute> DictionaryAttr::getNamed(StringAttr name) const {
198   auto it = impl::findAttrSorted(begin(), end(), name);
199   return it.second ? *it.first : Optional<NamedAttribute>();
200 }
201 
202 /// Return whether the specified attribute is present.
203 bool DictionaryAttr::contains(StringRef name) const {
204   return impl::findAttrSorted(begin(), end(), name).second;
205 }
206 bool DictionaryAttr::contains(StringAttr name) const {
207   return impl::findAttrSorted(begin(), end(), name).second;
208 }
209 
210 DictionaryAttr::iterator DictionaryAttr::begin() const {
211   return getValue().begin();
212 }
213 DictionaryAttr::iterator DictionaryAttr::end() const {
214   return getValue().end();
215 }
216 size_t DictionaryAttr::size() const { return getValue().size(); }
217 
218 DictionaryAttr DictionaryAttr::getEmptyUnchecked(MLIRContext *context) {
219   return Base::get(context, ArrayRef<NamedAttribute>());
220 }
221 
222 void DictionaryAttr::walkImmediateSubElements(
223     function_ref<void(Attribute)> walkAttrsFn,
224     function_ref<void(Type)> walkTypesFn) const {
225   for (const NamedAttribute &attr : getValue())
226     walkAttrsFn(attr.getValue());
227 }
228 
229 SubElementAttrInterface DictionaryAttr::replaceImmediateSubAttribute(
230     ArrayRef<std::pair<size_t, Attribute>> replacements) const {
231   std::vector<NamedAttribute> vec = getValue().vec();
232   for (auto &it : replacements)
233     vec[it.first].setValue(it.second);
234 
235   // The above only modifies the mapped value, but not the key, and therefore
236   // not the order of the elements. It remains sorted
237   return getWithSorted(getContext(), vec);
238 }
239 
240 //===----------------------------------------------------------------------===//
241 // StringAttr
242 //===----------------------------------------------------------------------===//
243 
244 StringAttr StringAttr::getEmptyStringAttrUnchecked(MLIRContext *context) {
245   return Base::get(context, "", NoneType::get(context));
246 }
247 
248 /// Twine support for StringAttr.
249 StringAttr StringAttr::get(MLIRContext *context, const Twine &twine) {
250   // Fast-path empty twine.
251   if (twine.isTriviallyEmpty())
252     return get(context);
253   SmallVector<char, 32> tempStr;
254   return Base::get(context, twine.toStringRef(tempStr), NoneType::get(context));
255 }
256 
257 /// Twine support for StringAttr.
258 StringAttr StringAttr::get(const Twine &twine, Type type) {
259   SmallVector<char, 32> tempStr;
260   return Base::get(type.getContext(), twine.toStringRef(tempStr), type);
261 }
262 
263 StringRef StringAttr::getValue() const { return getImpl()->value; }
264 
265 Dialect *StringAttr::getReferencedDialect() const {
266   return getImpl()->referencedDialect;
267 }
268 
269 //===----------------------------------------------------------------------===//
270 // FloatAttr
271 //===----------------------------------------------------------------------===//
272 
273 double FloatAttr::getValueAsDouble() const {
274   return getValueAsDouble(getValue());
275 }
276 double FloatAttr::getValueAsDouble(APFloat value) {
277   if (&value.getSemantics() != &APFloat::IEEEdouble()) {
278     bool losesInfo = false;
279     value.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
280                   &losesInfo);
281   }
282   return value.convertToDouble();
283 }
284 
285 LogicalResult FloatAttr::verify(function_ref<InFlightDiagnostic()> emitError,
286                                 Type type, APFloat value) {
287   // Verify that the type is correct.
288   if (!type.isa<FloatType>())
289     return emitError() << "expected floating point type";
290 
291   // Verify that the type semantics match that of the value.
292   if (&type.cast<FloatType>().getFloatSemantics() != &value.getSemantics()) {
293     return emitError()
294            << "FloatAttr type doesn't match the type implied by its value";
295   }
296   return success();
297 }
298 
299 //===----------------------------------------------------------------------===//
300 // SymbolRefAttr
301 //===----------------------------------------------------------------------===//
302 
303 SymbolRefAttr SymbolRefAttr::get(MLIRContext *ctx, StringRef value,
304                                  ArrayRef<FlatSymbolRefAttr> nestedRefs) {
305   return get(StringAttr::get(ctx, value), nestedRefs);
306 }
307 
308 FlatSymbolRefAttr SymbolRefAttr::get(MLIRContext *ctx, StringRef value) {
309   return get(ctx, value, {}).cast<FlatSymbolRefAttr>();
310 }
311 
312 FlatSymbolRefAttr SymbolRefAttr::get(StringAttr value) {
313   return get(value, {}).cast<FlatSymbolRefAttr>();
314 }
315 
316 FlatSymbolRefAttr SymbolRefAttr::get(Operation *symbol) {
317   auto symName =
318       symbol->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
319   assert(symName && "value does not have a valid symbol name");
320   return SymbolRefAttr::get(symName);
321 }
322 
323 StringAttr SymbolRefAttr::getLeafReference() const {
324   ArrayRef<FlatSymbolRefAttr> nestedRefs = getNestedReferences();
325   return nestedRefs.empty() ? getRootReference() : nestedRefs.back().getAttr();
326 }
327 
328 //===----------------------------------------------------------------------===//
329 // IntegerAttr
330 //===----------------------------------------------------------------------===//
331 
332 int64_t IntegerAttr::getInt() const {
333   assert((getType().isIndex() || getType().isSignlessInteger()) &&
334          "must be signless integer");
335   return getValue().getSExtValue();
336 }
337 
338 int64_t IntegerAttr::getSInt() const {
339   assert(getType().isSignedInteger() && "must be signed integer");
340   return getValue().getSExtValue();
341 }
342 
343 uint64_t IntegerAttr::getUInt() const {
344   assert(getType().isUnsignedInteger() && "must be unsigned integer");
345   return getValue().getZExtValue();
346 }
347 
348 /// Return the value as an APSInt which carries the signed from the type of
349 /// the attribute.  This traps on signless integers types!
350 APSInt IntegerAttr::getAPSInt() const {
351   assert(!getType().isSignlessInteger() &&
352          "Signless integers don't carry a sign for APSInt");
353   return APSInt(getValue(), getType().isUnsignedInteger());
354 }
355 
356 LogicalResult IntegerAttr::verify(function_ref<InFlightDiagnostic()> emitError,
357                                   Type type, APInt value) {
358   if (IntegerType integerType = type.dyn_cast<IntegerType>()) {
359     if (integerType.getWidth() != value.getBitWidth())
360       return emitError() << "integer type bit width (" << integerType.getWidth()
361                          << ") doesn't match value bit width ("
362                          << value.getBitWidth() << ")";
363     return success();
364   }
365   if (type.isa<IndexType>())
366     return success();
367   return emitError() << "expected integer or index type";
368 }
369 
370 BoolAttr IntegerAttr::getBoolAttrUnchecked(IntegerType type, bool value) {
371   auto attr = Base::get(type.getContext(), type, APInt(/*numBits=*/1, value));
372   return attr.cast<BoolAttr>();
373 }
374 
375 //===----------------------------------------------------------------------===//
376 // BoolAttr
377 //===----------------------------------------------------------------------===//
378 
379 bool BoolAttr::getValue() const {
380   auto *storage = reinterpret_cast<IntegerAttrStorage *>(impl);
381   return storage->value.getBoolValue();
382 }
383 
384 bool BoolAttr::classof(Attribute attr) {
385   IntegerAttr intAttr = attr.dyn_cast<IntegerAttr>();
386   return intAttr && intAttr.getType().isSignlessInteger(1);
387 }
388 
389 //===----------------------------------------------------------------------===//
390 // OpaqueAttr
391 //===----------------------------------------------------------------------===//
392 
393 LogicalResult OpaqueAttr::verify(function_ref<InFlightDiagnostic()> emitError,
394                                  StringAttr dialect, StringRef attrData,
395                                  Type type) {
396   if (!Dialect::isValidNamespace(dialect.strref()))
397     return emitError() << "invalid dialect namespace '" << dialect << "'";
398 
399   // Check that the dialect is actually registered.
400   MLIRContext *context = dialect.getContext();
401   if (!context->allowsUnregisteredDialects() &&
402       !context->getLoadedDialect(dialect.strref())) {
403     return emitError()
404            << "#" << dialect << "<\"" << attrData << "\"> : " << type
405            << " attribute created with unregistered dialect. If this is "
406               "intended, please call allowUnregisteredDialects() on the "
407               "MLIRContext, or use -allow-unregistered-dialect with "
408               "the MLIR opt tool used";
409   }
410 
411   return success();
412 }
413 
414 //===----------------------------------------------------------------------===//
415 // DenseElementsAttr Utilities
416 //===----------------------------------------------------------------------===//
417 
418 /// Get the bitwidth of a dense element type within the buffer.
419 /// DenseElementsAttr requires bitwidths greater than 1 to be aligned by 8.
420 static size_t getDenseElementStorageWidth(size_t origWidth) {
421   return origWidth == 1 ? origWidth : llvm::alignTo<8>(origWidth);
422 }
423 static size_t getDenseElementStorageWidth(Type elementType) {
424   return getDenseElementStorageWidth(getDenseElementBitWidth(elementType));
425 }
426 
427 /// Set a bit to a specific value.
428 static void setBit(char *rawData, size_t bitPos, bool value) {
429   if (value)
430     rawData[bitPos / CHAR_BIT] |= (1 << (bitPos % CHAR_BIT));
431   else
432     rawData[bitPos / CHAR_BIT] &= ~(1 << (bitPos % CHAR_BIT));
433 }
434 
435 /// Return the value of the specified bit.
436 static bool getBit(const char *rawData, size_t bitPos) {
437   return (rawData[bitPos / CHAR_BIT] & (1 << (bitPos % CHAR_BIT))) != 0;
438 }
439 
440 /// Copy actual `numBytes` data from `value` (APInt) to char array(`result`) for
441 /// BE format.
442 static void copyAPIntToArrayForBEmachine(APInt value, size_t numBytes,
443                                          char *result) {
444   assert(llvm::support::endian::system_endianness() == // NOLINT
445          llvm::support::endianness::big);              // NOLINT
446   assert(value.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes);
447 
448   // Copy the words filled with data.
449   // For example, when `value` has 2 words, the first word is filled with data.
450   // `value` (10 bytes, BE):|abcdefgh|------ij| ==> `result` (BE):|abcdefgh|--|
451   size_t numFilledWords = (value.getNumWords() - 1) * APInt::APINT_WORD_SIZE;
452   std::copy_n(reinterpret_cast<const char *>(value.getRawData()),
453               numFilledWords, result);
454   // Convert last word of APInt to LE format and store it in char
455   // array(`valueLE`).
456   // ex. last word of `value` (BE): |------ij|  ==> `valueLE` (LE): |ji------|
457   size_t lastWordPos = numFilledWords;
458   SmallVector<char, 8> valueLE(APInt::APINT_WORD_SIZE);
459   DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine(
460       reinterpret_cast<const char *>(value.getRawData()) + lastWordPos,
461       valueLE.begin(), APInt::APINT_BITS_PER_WORD, 1);
462   // Extract actual APInt data from `valueLE`, convert endianness to BE format,
463   // and store it in `result`.
464   // ex. `valueLE` (LE): |ji------|  ==> `result` (BE): |abcdefgh|ij|
465   DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine(
466       valueLE.begin(), result + lastWordPos,
467       (numBytes - lastWordPos) * CHAR_BIT, 1);
468 }
469 
470 /// Copy `numBytes` data from `inArray`(char array) to `result`(APINT) for BE
471 /// format.
472 static void copyArrayToAPIntForBEmachine(const char *inArray, size_t numBytes,
473                                          APInt &result) {
474   assert(llvm::support::endian::system_endianness() == // NOLINT
475          llvm::support::endianness::big);              // NOLINT
476   assert(result.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes);
477 
478   // Copy the data that fills the word of `result` from `inArray`.
479   // For example, when `result` has 2 words, the first word will be filled with
480   // data. So, the first 8 bytes are copied from `inArray` here.
481   // `inArray` (10 bytes, BE): |abcdefgh|ij|
482   //                     ==> `result` (2 words, BE): |abcdefgh|--------|
483   size_t numFilledWords = (result.getNumWords() - 1) * APInt::APINT_WORD_SIZE;
484   std::copy_n(
485       inArray, numFilledWords,
486       const_cast<char *>(reinterpret_cast<const char *>(result.getRawData())));
487 
488   // Convert array data which will be last word of `result` to LE format, and
489   // store it in char array(`inArrayLE`).
490   // ex. `inArray` (last two bytes, BE): |ij|  ==> `inArrayLE` (LE): |ji------|
491   size_t lastWordPos = numFilledWords;
492   SmallVector<char, 8> inArrayLE(APInt::APINT_WORD_SIZE);
493   DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine(
494       inArray + lastWordPos, inArrayLE.begin(),
495       (numBytes - lastWordPos) * CHAR_BIT, 1);
496 
497   // Convert `inArrayLE` to BE format, and store it in last word of `result`.
498   // ex. `inArrayLE` (LE): |ji------|  ==> `result` (BE): |abcdefgh|------ij|
499   DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine(
500       inArrayLE.begin(),
501       const_cast<char *>(reinterpret_cast<const char *>(result.getRawData())) +
502           lastWordPos,
503       APInt::APINT_BITS_PER_WORD, 1);
504 }
505 
506 /// Writes value to the bit position `bitPos` in array `rawData`.
507 static void writeBits(char *rawData, size_t bitPos, APInt value) {
508   size_t bitWidth = value.getBitWidth();
509 
510   // If the bitwidth is 1 we just toggle the specific bit.
511   if (bitWidth == 1)
512     return setBit(rawData, bitPos, value.isOneValue());
513 
514   // Otherwise, the bit position is guaranteed to be byte aligned.
515   assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned");
516   if (llvm::support::endian::system_endianness() ==
517       llvm::support::endianness::big) {
518     // Copy from `value` to `rawData + (bitPos / CHAR_BIT)`.
519     // Copying the first `llvm::divideCeil(bitWidth, CHAR_BIT)` bytes doesn't
520     // work correctly in BE format.
521     // ex. `value` (2 words including 10 bytes)
522     // ==> BE: |abcdefgh|------ij|,  LE: |hgfedcba|ji------|
523     copyAPIntToArrayForBEmachine(value, llvm::divideCeil(bitWidth, CHAR_BIT),
524                                  rawData + (bitPos / CHAR_BIT));
525   } else {
526     std::copy_n(reinterpret_cast<const char *>(value.getRawData()),
527                 llvm::divideCeil(bitWidth, CHAR_BIT),
528                 rawData + (bitPos / CHAR_BIT));
529   }
530 }
531 
532 /// Reads the next `bitWidth` bits from the bit position `bitPos` in array
533 /// `rawData`.
534 static APInt readBits(const char *rawData, size_t bitPos, size_t bitWidth) {
535   // Handle a boolean bit position.
536   if (bitWidth == 1)
537     return APInt(1, getBit(rawData, bitPos) ? 1 : 0);
538 
539   // Otherwise, the bit position must be 8-bit aligned.
540   assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned");
541   APInt result(bitWidth, 0);
542   if (llvm::support::endian::system_endianness() ==
543       llvm::support::endianness::big) {
544     // Copy from `rawData + (bitPos / CHAR_BIT)` to `result`.
545     // Copying the first `llvm::divideCeil(bitWidth, CHAR_BIT)` bytes doesn't
546     // work correctly in BE format.
547     // ex. `result` (2 words including 10 bytes)
548     // ==> BE: |abcdefgh|------ij|,  LE: |hgfedcba|ji------| This function
549     copyArrayToAPIntForBEmachine(rawData + (bitPos / CHAR_BIT),
550                                  llvm::divideCeil(bitWidth, CHAR_BIT), result);
551   } else {
552     std::copy_n(rawData + (bitPos / CHAR_BIT),
553                 llvm::divideCeil(bitWidth, CHAR_BIT),
554                 const_cast<char *>(
555                     reinterpret_cast<const char *>(result.getRawData())));
556   }
557   return result;
558 }
559 
560 /// Returns true if 'values' corresponds to a splat, i.e. one element, or has
561 /// the same element count as 'type'.
562 template <typename Values>
563 static bool hasSameElementsOrSplat(ShapedType type, const Values &values) {
564   return (values.size() == 1) ||
565          (type.getNumElements() == static_cast<int64_t>(values.size()));
566 }
567 
568 //===----------------------------------------------------------------------===//
569 // DenseElementsAttr Iterators
570 //===----------------------------------------------------------------------===//
571 
572 //===----------------------------------------------------------------------===//
573 // AttributeElementIterator
574 
575 DenseElementsAttr::AttributeElementIterator::AttributeElementIterator(
576     DenseElementsAttr attr, size_t index)
577     : llvm::indexed_accessor_iterator<AttributeElementIterator, const void *,
578                                       Attribute, Attribute, Attribute>(
579           attr.getAsOpaquePointer(), index) {}
580 
581 Attribute DenseElementsAttr::AttributeElementIterator::operator*() const {
582   auto owner = getFromOpaquePointer(base).cast<DenseElementsAttr>();
583   Type eltTy = owner.getElementType();
584   if (auto intEltTy = eltTy.dyn_cast<IntegerType>())
585     return IntegerAttr::get(eltTy, *IntElementIterator(owner, index));
586   if (eltTy.isa<IndexType>())
587     return IntegerAttr::get(eltTy, *IntElementIterator(owner, index));
588   if (auto floatEltTy = eltTy.dyn_cast<FloatType>()) {
589     IntElementIterator intIt(owner, index);
590     FloatElementIterator floatIt(floatEltTy.getFloatSemantics(), intIt);
591     return FloatAttr::get(eltTy, *floatIt);
592   }
593   if (auto complexTy = eltTy.dyn_cast<ComplexType>()) {
594     auto complexEltTy = complexTy.getElementType();
595     ComplexIntElementIterator complexIntIt(owner, index);
596     if (complexEltTy.isa<IntegerType>()) {
597       auto value = *complexIntIt;
598       auto real = IntegerAttr::get(complexEltTy, value.real());
599       auto imag = IntegerAttr::get(complexEltTy, value.imag());
600       return ArrayAttr::get(complexTy.getContext(),
601                             ArrayRef<Attribute>{real, imag});
602     }
603 
604     ComplexFloatElementIterator complexFloatIt(
605         complexEltTy.cast<FloatType>().getFloatSemantics(), complexIntIt);
606     auto value = *complexFloatIt;
607     auto real = FloatAttr::get(complexEltTy, value.real());
608     auto imag = FloatAttr::get(complexEltTy, value.imag());
609     return ArrayAttr::get(complexTy.getContext(),
610                           ArrayRef<Attribute>{real, imag});
611   }
612   if (owner.isa<DenseStringElementsAttr>()) {
613     ArrayRef<StringRef> vals = owner.getRawStringData();
614     return StringAttr::get(owner.isSplat() ? vals.front() : vals[index], eltTy);
615   }
616   llvm_unreachable("unexpected element type");
617 }
618 
619 //===----------------------------------------------------------------------===//
620 // BoolElementIterator
621 
622 DenseElementsAttr::BoolElementIterator::BoolElementIterator(
623     DenseElementsAttr attr, size_t dataIndex)
624     : DenseElementIndexedIteratorImpl<BoolElementIterator, bool, bool, bool>(
625           attr.getRawData().data(), attr.isSplat(), dataIndex) {}
626 
627 bool DenseElementsAttr::BoolElementIterator::operator*() const {
628   return getBit(getData(), getDataIndex());
629 }
630 
631 //===----------------------------------------------------------------------===//
632 // IntElementIterator
633 
634 DenseElementsAttr::IntElementIterator::IntElementIterator(
635     DenseElementsAttr attr, size_t dataIndex)
636     : DenseElementIndexedIteratorImpl<IntElementIterator, APInt, APInt, APInt>(
637           attr.getRawData().data(), attr.isSplat(), dataIndex),
638       bitWidth(getDenseElementBitWidth(attr.getElementType())) {}
639 
640 APInt DenseElementsAttr::IntElementIterator::operator*() const {
641   return readBits(getData(),
642                   getDataIndex() * getDenseElementStorageWidth(bitWidth),
643                   bitWidth);
644 }
645 
646 //===----------------------------------------------------------------------===//
647 // ComplexIntElementIterator
648 
649 DenseElementsAttr::ComplexIntElementIterator::ComplexIntElementIterator(
650     DenseElementsAttr attr, size_t dataIndex)
651     : DenseElementIndexedIteratorImpl<ComplexIntElementIterator,
652                                       std::complex<APInt>, std::complex<APInt>,
653                                       std::complex<APInt>>(
654           attr.getRawData().data(), attr.isSplat(), dataIndex) {
655   auto complexType = attr.getElementType().cast<ComplexType>();
656   bitWidth = getDenseElementBitWidth(complexType.getElementType());
657 }
658 
659 std::complex<APInt>
660 DenseElementsAttr::ComplexIntElementIterator::operator*() const {
661   size_t storageWidth = getDenseElementStorageWidth(bitWidth);
662   size_t offset = getDataIndex() * storageWidth * 2;
663   return {readBits(getData(), offset, bitWidth),
664           readBits(getData(), offset + storageWidth, bitWidth)};
665 }
666 
667 //===----------------------------------------------------------------------===//
668 // DenseElementsAttr
669 //===----------------------------------------------------------------------===//
670 
671 /// Method for support type inquiry through isa, cast and dyn_cast.
672 bool DenseElementsAttr::classof(Attribute attr) {
673   return attr.isa<DenseIntOrFPElementsAttr, DenseStringElementsAttr>();
674 }
675 
676 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
677                                          ArrayRef<Attribute> values) {
678   assert(hasSameElementsOrSplat(type, values));
679 
680   // If the element type is not based on int/float/index, assume it is a string
681   // type.
682   auto eltType = type.getElementType();
683   if (!type.getElementType().isIntOrIndexOrFloat()) {
684     SmallVector<StringRef, 8> stringValues;
685     stringValues.reserve(values.size());
686     for (Attribute attr : values) {
687       assert(attr.isa<StringAttr>() &&
688              "expected string value for non integer/index/float element");
689       stringValues.push_back(attr.cast<StringAttr>().getValue());
690     }
691     return get(type, stringValues);
692   }
693 
694   // Otherwise, get the raw storage width to use for the allocation.
695   size_t bitWidth = getDenseElementBitWidth(eltType);
696   size_t storageBitWidth = getDenseElementStorageWidth(bitWidth);
697 
698   // Compress the attribute values into a character buffer.
699   SmallVector<char, 8> data(llvm::divideCeil(storageBitWidth, CHAR_BIT) *
700                             values.size());
701   APInt intVal;
702   for (unsigned i = 0, e = values.size(); i < e; ++i) {
703     assert(eltType == values[i].getType() &&
704            "expected attribute value to have element type");
705     if (eltType.isa<FloatType>())
706       intVal = values[i].cast<FloatAttr>().getValue().bitcastToAPInt();
707     else if (eltType.isa<IntegerType, IndexType>())
708       intVal = values[i].cast<IntegerAttr>().getValue();
709     else
710       llvm_unreachable("unexpected element type");
711 
712     assert(intVal.getBitWidth() == bitWidth &&
713            "expected value to have same bitwidth as element type");
714     writeBits(data.data(), i * storageBitWidth, intVal);
715   }
716   return DenseIntOrFPElementsAttr::getRaw(type, data,
717                                           /*isSplat=*/(values.size() == 1));
718 }
719 
720 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
721                                          ArrayRef<bool> values) {
722   assert(hasSameElementsOrSplat(type, values));
723   assert(type.getElementType().isInteger(1));
724 
725   std::vector<char> buff(llvm::divideCeil(values.size(), CHAR_BIT));
726   for (int i = 0, e = values.size(); i != e; ++i)
727     setBit(buff.data(), i, values[i]);
728   return DenseIntOrFPElementsAttr::getRaw(type, buff,
729                                           /*isSplat=*/(values.size() == 1));
730 }
731 
732 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
733                                          ArrayRef<StringRef> values) {
734   assert(!type.getElementType().isIntOrFloat());
735   return DenseStringElementsAttr::get(type, values);
736 }
737 
738 /// Constructs a dense integer elements attribute from an array of APInt
739 /// values. Each APInt value is expected to have the same bitwidth as the
740 /// element type of 'type'.
741 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
742                                          ArrayRef<APInt> values) {
743   assert(type.getElementType().isIntOrIndex());
744   assert(hasSameElementsOrSplat(type, values));
745   size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType());
746   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, values,
747                                           /*isSplat=*/(values.size() == 1));
748 }
749 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
750                                          ArrayRef<std::complex<APInt>> values) {
751   ComplexType complex = type.getElementType().cast<ComplexType>();
752   assert(complex.getElementType().isa<IntegerType>());
753   assert(hasSameElementsOrSplat(type, values));
754   size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2;
755   ArrayRef<APInt> intVals(reinterpret_cast<const APInt *>(values.data()),
756                           values.size() * 2);
757   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, intVals,
758                                           /*isSplat=*/(values.size() == 1));
759 }
760 
761 // Constructs a dense float elements attribute from an array of APFloat
762 // values. Each APFloat value is expected to have the same bitwidth as the
763 // element type of 'type'.
764 DenseElementsAttr DenseElementsAttr::get(ShapedType type,
765                                          ArrayRef<APFloat> values) {
766   assert(type.getElementType().isa<FloatType>());
767   assert(hasSameElementsOrSplat(type, values));
768   size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType());
769   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, values,
770                                           /*isSplat=*/(values.size() == 1));
771 }
772 DenseElementsAttr
773 DenseElementsAttr::get(ShapedType type,
774                        ArrayRef<std::complex<APFloat>> values) {
775   ComplexType complex = type.getElementType().cast<ComplexType>();
776   assert(complex.getElementType().isa<FloatType>());
777   assert(hasSameElementsOrSplat(type, values));
778   ArrayRef<APFloat> apVals(reinterpret_cast<const APFloat *>(values.data()),
779                            values.size() * 2);
780   size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2;
781   return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, apVals,
782                                           /*isSplat=*/(values.size() == 1));
783 }
784 
785 /// Construct a dense elements attribute from a raw buffer representing the
786 /// data for this attribute. Users should generally not use this methods as
787 /// the expected buffer format may not be a form the user expects.
788 DenseElementsAttr DenseElementsAttr::getFromRawBuffer(ShapedType type,
789                                                       ArrayRef<char> rawBuffer,
790                                                       bool isSplatBuffer) {
791   return DenseIntOrFPElementsAttr::getRaw(type, rawBuffer, isSplatBuffer);
792 }
793 
794 /// Returns true if the given buffer is a valid raw buffer for the given type.
795 bool DenseElementsAttr::isValidRawBuffer(ShapedType type,
796                                          ArrayRef<char> rawBuffer,
797                                          bool &detectedSplat) {
798   size_t storageWidth = getDenseElementStorageWidth(type.getElementType());
799   size_t rawBufferWidth = rawBuffer.size() * CHAR_BIT;
800 
801   // Storage width of 1 is special as it is packed by the bit.
802   if (storageWidth == 1) {
803     // Check for a splat, or a buffer equal to the number of elements which
804     // consists of either all 0's or all 1's.
805     detectedSplat = false;
806     if (rawBuffer.size() == 1) {
807       auto rawByte = static_cast<uint8_t>(rawBuffer[0]);
808       if (rawByte == 0 || rawByte == 0xff) {
809         detectedSplat = true;
810         return true;
811       }
812     }
813     return rawBufferWidth == llvm::alignTo<8>(type.getNumElements());
814   }
815   // All other types are 8-bit aligned.
816   if ((detectedSplat = rawBufferWidth == storageWidth))
817     return true;
818   return rawBufferWidth == (storageWidth * type.getNumElements());
819 }
820 
821 /// Check the information for a C++ data type, check if this type is valid for
822 /// the current attribute. This method is used to verify specific type
823 /// invariants that the templatized 'getValues' method cannot.
824 static bool isValidIntOrFloat(Type type, int64_t dataEltSize, bool isInt,
825                               bool isSigned) {
826   // Make sure that the data element size is the same as the type element width.
827   if (getDenseElementBitWidth(type) !=
828       static_cast<size_t>(dataEltSize * CHAR_BIT))
829     return false;
830 
831   // Check that the element type is either float or integer or index.
832   if (!isInt)
833     return type.isa<FloatType>();
834   if (type.isIndex())
835     return true;
836 
837   auto intType = type.dyn_cast<IntegerType>();
838   if (!intType)
839     return false;
840 
841   // Make sure signedness semantics is consistent.
842   if (intType.isSignless())
843     return true;
844   return intType.isSigned() ? isSigned : !isSigned;
845 }
846 
847 /// Defaults down the subclass implementation.
848 DenseElementsAttr DenseElementsAttr::getRawComplex(ShapedType type,
849                                                    ArrayRef<char> data,
850                                                    int64_t dataEltSize,
851                                                    bool isInt, bool isSigned) {
852   return DenseIntOrFPElementsAttr::getRawComplex(type, data, dataEltSize, isInt,
853                                                  isSigned);
854 }
855 DenseElementsAttr DenseElementsAttr::getRawIntOrFloat(ShapedType type,
856                                                       ArrayRef<char> data,
857                                                       int64_t dataEltSize,
858                                                       bool isInt,
859                                                       bool isSigned) {
860   return DenseIntOrFPElementsAttr::getRawIntOrFloat(type, data, dataEltSize,
861                                                     isInt, isSigned);
862 }
863 
864 bool DenseElementsAttr::isValidIntOrFloat(int64_t dataEltSize, bool isInt,
865                                           bool isSigned) const {
866   return ::isValidIntOrFloat(getElementType(), dataEltSize, isInt, isSigned);
867 }
868 bool DenseElementsAttr::isValidComplex(int64_t dataEltSize, bool isInt,
869                                        bool isSigned) const {
870   return ::isValidIntOrFloat(
871       getElementType().cast<ComplexType>().getElementType(), dataEltSize / 2,
872       isInt, isSigned);
873 }
874 
875 /// Returns true if this attribute corresponds to a splat, i.e. if all element
876 /// values are the same.
877 bool DenseElementsAttr::isSplat() const {
878   return static_cast<DenseElementsAttributeStorage *>(impl)->isSplat;
879 }
880 
881 /// Return if the given complex type has an integer element type.
882 LLVM_ATTRIBUTE_UNUSED static bool isComplexOfIntType(Type type) {
883   return type.cast<ComplexType>().getElementType().isa<IntegerType>();
884 }
885 
886 auto DenseElementsAttr::getComplexIntValues() const
887     -> iterator_range_impl<ComplexIntElementIterator> {
888   assert(isComplexOfIntType(getElementType()) &&
889          "expected complex integral type");
890   return {getType(), ComplexIntElementIterator(*this, 0),
891           ComplexIntElementIterator(*this, getNumElements())};
892 }
893 auto DenseElementsAttr::complex_value_begin() const
894     -> ComplexIntElementIterator {
895   assert(isComplexOfIntType(getElementType()) &&
896          "expected complex integral type");
897   return ComplexIntElementIterator(*this, 0);
898 }
899 auto DenseElementsAttr::complex_value_end() const -> ComplexIntElementIterator {
900   assert(isComplexOfIntType(getElementType()) &&
901          "expected complex integral type");
902   return ComplexIntElementIterator(*this, getNumElements());
903 }
904 
905 /// Return the held element values as a range of APFloat. The element type of
906 /// this attribute must be of float type.
907 auto DenseElementsAttr::getFloatValues() const
908     -> iterator_range_impl<FloatElementIterator> {
909   auto elementType = getElementType().cast<FloatType>();
910   const auto &elementSemantics = elementType.getFloatSemantics();
911   return {getType(), FloatElementIterator(elementSemantics, raw_int_begin()),
912           FloatElementIterator(elementSemantics, raw_int_end())};
913 }
914 auto DenseElementsAttr::float_value_begin() const -> FloatElementIterator {
915   auto elementType = getElementType().cast<FloatType>();
916   return FloatElementIterator(elementType.getFloatSemantics(), raw_int_begin());
917 }
918 auto DenseElementsAttr::float_value_end() const -> FloatElementIterator {
919   auto elementType = getElementType().cast<FloatType>();
920   return FloatElementIterator(elementType.getFloatSemantics(), raw_int_end());
921 }
922 
923 auto DenseElementsAttr::getComplexFloatValues() const
924     -> iterator_range_impl<ComplexFloatElementIterator> {
925   Type eltTy = getElementType().cast<ComplexType>().getElementType();
926   assert(eltTy.isa<FloatType>() && "expected complex float type");
927   const auto &semantics = eltTy.cast<FloatType>().getFloatSemantics();
928   return {getType(),
929           {semantics, {*this, 0}},
930           {semantics, {*this, static_cast<size_t>(getNumElements())}}};
931 }
932 auto DenseElementsAttr::complex_float_value_begin() const
933     -> ComplexFloatElementIterator {
934   Type eltTy = getElementType().cast<ComplexType>().getElementType();
935   assert(eltTy.isa<FloatType>() && "expected complex float type");
936   return {eltTy.cast<FloatType>().getFloatSemantics(), {*this, 0}};
937 }
938 auto DenseElementsAttr::complex_float_value_end() const
939     -> ComplexFloatElementIterator {
940   Type eltTy = getElementType().cast<ComplexType>().getElementType();
941   assert(eltTy.isa<FloatType>() && "expected complex float type");
942   return {eltTy.cast<FloatType>().getFloatSemantics(),
943           {*this, static_cast<size_t>(getNumElements())}};
944 }
945 
946 /// Return the raw storage data held by this attribute.
947 ArrayRef<char> DenseElementsAttr::getRawData() const {
948   return static_cast<DenseIntOrFPElementsAttrStorage *>(impl)->data;
949 }
950 
951 ArrayRef<StringRef> DenseElementsAttr::getRawStringData() const {
952   return static_cast<DenseStringElementsAttrStorage *>(impl)->data;
953 }
954 
955 /// Return a new DenseElementsAttr that has the same data as the current
956 /// attribute, but has been reshaped to 'newType'. The new type must have the
957 /// same total number of elements as well as element type.
958 DenseElementsAttr DenseElementsAttr::reshape(ShapedType newType) {
959   ShapedType curType = getType();
960   if (curType == newType)
961     return *this;
962 
963   assert(newType.getElementType() == curType.getElementType() &&
964          "expected the same element type");
965   assert(newType.getNumElements() == curType.getNumElements() &&
966          "expected the same number of elements");
967   return DenseIntOrFPElementsAttr::getRaw(newType, getRawData(), isSplat());
968 }
969 
970 DenseElementsAttr DenseElementsAttr::resizeSplat(ShapedType newType) {
971   assert(isSplat() && "expected a splat type");
972 
973   ShapedType curType = getType();
974   if (curType == newType)
975     return *this;
976 
977   assert(newType.getElementType() == curType.getElementType() &&
978          "expected the same element type");
979   return DenseIntOrFPElementsAttr::getRaw(newType, getRawData(), true);
980 }
981 
982 /// Return a new DenseElementsAttr that has the same data as the current
983 /// attribute, but has bitcast elements such that it is now 'newType'. The new
984 /// type must have the same shape and element types of the same bitwidth as the
985 /// current type.
986 DenseElementsAttr DenseElementsAttr::bitcast(Type newElType) {
987   ShapedType curType = getType();
988   Type curElType = curType.getElementType();
989   if (curElType == newElType)
990     return *this;
991 
992   assert(getDenseElementBitWidth(newElType) ==
993              getDenseElementBitWidth(curElType) &&
994          "expected element types with the same bitwidth");
995   return DenseIntOrFPElementsAttr::getRaw(curType.clone(newElType),
996                                           getRawData(), isSplat());
997 }
998 
999 DenseElementsAttr
1000 DenseElementsAttr::mapValues(Type newElementType,
1001                              function_ref<APInt(const APInt &)> mapping) const {
1002   return cast<DenseIntElementsAttr>().mapValues(newElementType, mapping);
1003 }
1004 
1005 DenseElementsAttr DenseElementsAttr::mapValues(
1006     Type newElementType, function_ref<APInt(const APFloat &)> mapping) const {
1007   return cast<DenseFPElementsAttr>().mapValues(newElementType, mapping);
1008 }
1009 
1010 ShapedType DenseElementsAttr::getType() const {
1011   return Attribute::getType().cast<ShapedType>();
1012 }
1013 
1014 Type DenseElementsAttr::getElementType() const {
1015   return getType().getElementType();
1016 }
1017 
1018 int64_t DenseElementsAttr::getNumElements() const {
1019   return getType().getNumElements();
1020 }
1021 
1022 //===----------------------------------------------------------------------===//
1023 // DenseIntOrFPElementsAttr
1024 //===----------------------------------------------------------------------===//
1025 
1026 /// Utility method to write a range of APInt values to a buffer.
1027 template <typename APRangeT>
1028 static void writeAPIntsToBuffer(size_t storageWidth, std::vector<char> &data,
1029                                 APRangeT &&values) {
1030   data.resize(llvm::divideCeil(storageWidth, CHAR_BIT) * llvm::size(values));
1031   size_t offset = 0;
1032   for (auto it = values.begin(), e = values.end(); it != e;
1033        ++it, offset += storageWidth) {
1034     assert((*it).getBitWidth() <= storageWidth);
1035     writeBits(data.data(), offset, *it);
1036   }
1037 }
1038 
1039 /// Constructs a dense elements attribute from an array of raw APFloat values.
1040 /// Each APFloat value is expected to have the same bitwidth as the element
1041 /// type of 'type'. 'type' must be a vector or tensor with static shape.
1042 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type,
1043                                                    size_t storageWidth,
1044                                                    ArrayRef<APFloat> values,
1045                                                    bool isSplat) {
1046   std::vector<char> data;
1047   auto unwrapFloat = [](const APFloat &val) { return val.bitcastToAPInt(); };
1048   writeAPIntsToBuffer(storageWidth, data, llvm::map_range(values, unwrapFloat));
1049   return DenseIntOrFPElementsAttr::getRaw(type, data, isSplat);
1050 }
1051 
1052 /// Constructs a dense elements attribute from an array of raw APInt values.
1053 /// Each APInt value is expected to have the same bitwidth as the element type
1054 /// of 'type'.
1055 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type,
1056                                                    size_t storageWidth,
1057                                                    ArrayRef<APInt> values,
1058                                                    bool isSplat) {
1059   std::vector<char> data;
1060   writeAPIntsToBuffer(storageWidth, data, values);
1061   return DenseIntOrFPElementsAttr::getRaw(type, data, isSplat);
1062 }
1063 
1064 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type,
1065                                                    ArrayRef<char> data,
1066                                                    bool isSplat) {
1067   assert((type.isa<RankedTensorType, VectorType>()) &&
1068          "type must be ranked tensor or vector");
1069   assert(type.hasStaticShape() && "type must have static shape");
1070   return Base::get(type.getContext(), type, data, isSplat);
1071 }
1072 
1073 /// Overload of the raw 'get' method that asserts that the given type is of
1074 /// complex type. This method is used to verify type invariants that the
1075 /// templatized 'get' method cannot.
1076 DenseElementsAttr DenseIntOrFPElementsAttr::getRawComplex(ShapedType type,
1077                                                           ArrayRef<char> data,
1078                                                           int64_t dataEltSize,
1079                                                           bool isInt,
1080                                                           bool isSigned) {
1081   assert(::isValidIntOrFloat(
1082       type.getElementType().cast<ComplexType>().getElementType(),
1083       dataEltSize / 2, isInt, isSigned));
1084 
1085   int64_t numElements = data.size() / dataEltSize;
1086   assert(numElements == 1 || numElements == type.getNumElements());
1087   return getRaw(type, data, /*isSplat=*/numElements == 1);
1088 }
1089 
1090 /// Overload of the 'getRaw' method that asserts that the given type is of
1091 /// integer type. This method is used to verify type invariants that the
1092 /// templatized 'get' method cannot.
1093 DenseElementsAttr
1094 DenseIntOrFPElementsAttr::getRawIntOrFloat(ShapedType type, ArrayRef<char> data,
1095                                            int64_t dataEltSize, bool isInt,
1096                                            bool isSigned) {
1097   assert(
1098       ::isValidIntOrFloat(type.getElementType(), dataEltSize, isInt, isSigned));
1099 
1100   int64_t numElements = data.size() / dataEltSize;
1101   assert(numElements == 1 || numElements == type.getNumElements());
1102   return getRaw(type, data, /*isSplat=*/numElements == 1);
1103 }
1104 
1105 void DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine(
1106     const char *inRawData, char *outRawData, size_t elementBitWidth,
1107     size_t numElements) {
1108   using llvm::support::ulittle16_t;
1109   using llvm::support::ulittle32_t;
1110   using llvm::support::ulittle64_t;
1111 
1112   assert(llvm::support::endian::system_endianness() == // NOLINT
1113          llvm::support::endianness::big);              // NOLINT
1114   // NOLINT to avoid warning message about replacing by static_assert()
1115 
1116   // Following std::copy_n always converts endianness on BE machine.
1117   switch (elementBitWidth) {
1118   case 16: {
1119     const ulittle16_t *inRawDataPos =
1120         reinterpret_cast<const ulittle16_t *>(inRawData);
1121     uint16_t *outDataPos = reinterpret_cast<uint16_t *>(outRawData);
1122     std::copy_n(inRawDataPos, numElements, outDataPos);
1123     break;
1124   }
1125   case 32: {
1126     const ulittle32_t *inRawDataPos =
1127         reinterpret_cast<const ulittle32_t *>(inRawData);
1128     uint32_t *outDataPos = reinterpret_cast<uint32_t *>(outRawData);
1129     std::copy_n(inRawDataPos, numElements, outDataPos);
1130     break;
1131   }
1132   case 64: {
1133     const ulittle64_t *inRawDataPos =
1134         reinterpret_cast<const ulittle64_t *>(inRawData);
1135     uint64_t *outDataPos = reinterpret_cast<uint64_t *>(outRawData);
1136     std::copy_n(inRawDataPos, numElements, outDataPos);
1137     break;
1138   }
1139   default: {
1140     size_t nBytes = elementBitWidth / CHAR_BIT;
1141     for (size_t i = 0; i < nBytes; i++)
1142       std::copy_n(inRawData + (nBytes - 1 - i), 1, outRawData + i);
1143     break;
1144   }
1145   }
1146 }
1147 
1148 void DenseIntOrFPElementsAttr::convertEndianOfArrayRefForBEmachine(
1149     ArrayRef<char> inRawData, MutableArrayRef<char> outRawData,
1150     ShapedType type) {
1151   size_t numElements = type.getNumElements();
1152   Type elementType = type.getElementType();
1153   if (ComplexType complexTy = elementType.dyn_cast<ComplexType>()) {
1154     elementType = complexTy.getElementType();
1155     numElements = numElements * 2;
1156   }
1157   size_t elementBitWidth = getDenseElementStorageWidth(elementType);
1158   assert(numElements * elementBitWidth == inRawData.size() * CHAR_BIT &&
1159          inRawData.size() <= outRawData.size());
1160   convertEndianOfCharForBEmachine(inRawData.begin(), outRawData.begin(),
1161                                   elementBitWidth, numElements);
1162 }
1163 
1164 //===----------------------------------------------------------------------===//
1165 // DenseFPElementsAttr
1166 //===----------------------------------------------------------------------===//
1167 
1168 template <typename Fn, typename Attr>
1169 static ShapedType mappingHelper(Fn mapping, Attr &attr, ShapedType inType,
1170                                 Type newElementType,
1171                                 llvm::SmallVectorImpl<char> &data) {
1172   size_t bitWidth = getDenseElementBitWidth(newElementType);
1173   size_t storageBitWidth = getDenseElementStorageWidth(bitWidth);
1174 
1175   ShapedType newArrayType;
1176   if (inType.isa<RankedTensorType>())
1177     newArrayType = RankedTensorType::get(inType.getShape(), newElementType);
1178   else if (inType.isa<UnrankedTensorType>())
1179     newArrayType = RankedTensorType::get(inType.getShape(), newElementType);
1180   else if (auto vType = inType.dyn_cast<VectorType>())
1181     newArrayType = VectorType::get(vType.getShape(), newElementType,
1182                                    vType.getNumScalableDims());
1183   else
1184     assert(newArrayType && "Unhandled tensor type");
1185 
1186   size_t numRawElements = attr.isSplat() ? 1 : newArrayType.getNumElements();
1187   data.resize(llvm::divideCeil(storageBitWidth, CHAR_BIT) * numRawElements);
1188 
1189   // Functor used to process a single element value of the attribute.
1190   auto processElt = [&](decltype(*attr.begin()) value, size_t index) {
1191     auto newInt = mapping(value);
1192     assert(newInt.getBitWidth() == bitWidth);
1193     writeBits(data.data(), index * storageBitWidth, newInt);
1194   };
1195 
1196   // Check for the splat case.
1197   if (attr.isSplat()) {
1198     processElt(*attr.begin(), /*index=*/0);
1199     return newArrayType;
1200   }
1201 
1202   // Otherwise, process all of the element values.
1203   uint64_t elementIdx = 0;
1204   for (auto value : attr)
1205     processElt(value, elementIdx++);
1206   return newArrayType;
1207 }
1208 
1209 DenseElementsAttr DenseFPElementsAttr::mapValues(
1210     Type newElementType, function_ref<APInt(const APFloat &)> mapping) const {
1211   llvm::SmallVector<char, 8> elementData;
1212   auto newArrayType =
1213       mappingHelper(mapping, *this, getType(), newElementType, elementData);
1214 
1215   return getRaw(newArrayType, elementData, isSplat());
1216 }
1217 
1218 /// Method for supporting type inquiry through isa, cast and dyn_cast.
1219 bool DenseFPElementsAttr::classof(Attribute attr) {
1220   return attr.isa<DenseElementsAttr>() &&
1221          attr.getType().cast<ShapedType>().getElementType().isa<FloatType>();
1222 }
1223 
1224 //===----------------------------------------------------------------------===//
1225 // DenseIntElementsAttr
1226 //===----------------------------------------------------------------------===//
1227 
1228 DenseElementsAttr DenseIntElementsAttr::mapValues(
1229     Type newElementType, function_ref<APInt(const APInt &)> mapping) const {
1230   llvm::SmallVector<char, 8> elementData;
1231   auto newArrayType =
1232       mappingHelper(mapping, *this, getType(), newElementType, elementData);
1233 
1234   return getRaw(newArrayType, elementData, isSplat());
1235 }
1236 
1237 /// Method for supporting type inquiry through isa, cast and dyn_cast.
1238 bool DenseIntElementsAttr::classof(Attribute attr) {
1239   return attr.isa<DenseElementsAttr>() &&
1240          attr.getType().cast<ShapedType>().getElementType().isIntOrIndex();
1241 }
1242 
1243 //===----------------------------------------------------------------------===//
1244 // OpaqueElementsAttr
1245 //===----------------------------------------------------------------------===//
1246 
1247 bool OpaqueElementsAttr::decode(ElementsAttr &result) {
1248   Dialect *dialect = getContext()->getLoadedDialect(getDialect());
1249   if (!dialect)
1250     return true;
1251   auto *interface = llvm::dyn_cast<DialectDecodeAttributesInterface>(dialect);
1252   if (!interface)
1253     return true;
1254   return failed(interface->decode(*this, result));
1255 }
1256 
1257 LogicalResult
1258 OpaqueElementsAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1259                            StringAttr dialect, StringRef value,
1260                            ShapedType type) {
1261   if (!Dialect::isValidNamespace(dialect.strref()))
1262     return emitError() << "invalid dialect namespace '" << dialect << "'";
1263   return success();
1264 }
1265 
1266 //===----------------------------------------------------------------------===//
1267 // SparseElementsAttr
1268 //===----------------------------------------------------------------------===//
1269 
1270 /// Get a zero APFloat for the given sparse attribute.
1271 APFloat SparseElementsAttr::getZeroAPFloat() const {
1272   auto eltType = getElementType().cast<FloatType>();
1273   return APFloat(eltType.getFloatSemantics());
1274 }
1275 
1276 /// Get a zero APInt for the given sparse attribute.
1277 APInt SparseElementsAttr::getZeroAPInt() const {
1278   auto eltType = getElementType().cast<IntegerType>();
1279   return APInt::getZero(eltType.getWidth());
1280 }
1281 
1282 /// Get a zero attribute for the given attribute type.
1283 Attribute SparseElementsAttr::getZeroAttr() const {
1284   auto eltType = getElementType();
1285 
1286   // Handle floating point elements.
1287   if (eltType.isa<FloatType>())
1288     return FloatAttr::get(eltType, 0);
1289 
1290   // Handle string type.
1291   if (getValues().isa<DenseStringElementsAttr>())
1292     return StringAttr::get("", eltType);
1293 
1294   // Otherwise, this is an integer.
1295   return IntegerAttr::get(eltType, 0);
1296 }
1297 
1298 /// Flatten, and return, all of the sparse indices in this attribute in
1299 /// row-major order.
1300 std::vector<ptrdiff_t> SparseElementsAttr::getFlattenedSparseIndices() const {
1301   std::vector<ptrdiff_t> flatSparseIndices;
1302 
1303   // The sparse indices are 64-bit integers, so we can reinterpret the raw data
1304   // as a 1-D index array.
1305   auto sparseIndices = getIndices();
1306   auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1307   if (sparseIndices.isSplat()) {
1308     SmallVector<uint64_t, 8> indices(getType().getRank(),
1309                                      *sparseIndexValues.begin());
1310     flatSparseIndices.push_back(getFlattenedIndex(indices));
1311     return flatSparseIndices;
1312   }
1313 
1314   // Otherwise, reinterpret each index as an ArrayRef when flattening.
1315   auto numSparseIndices = sparseIndices.getType().getDimSize(0);
1316   size_t rank = getType().getRank();
1317   for (size_t i = 0, e = numSparseIndices; i != e; ++i)
1318     flatSparseIndices.push_back(getFlattenedIndex(
1319         {&*std::next(sparseIndexValues.begin(), i * rank), rank}));
1320   return flatSparseIndices;
1321 }
1322 
1323 LogicalResult
1324 SparseElementsAttr::verify(function_ref<InFlightDiagnostic()> emitError,
1325                            ShapedType type, DenseIntElementsAttr sparseIndices,
1326                            DenseElementsAttr values) {
1327   ShapedType valuesType = values.getType();
1328   if (valuesType.getRank() != 1)
1329     return emitError() << "expected 1-d tensor for sparse element values";
1330 
1331   // Verify the indices and values shape.
1332   ShapedType indicesType = sparseIndices.getType();
1333   auto emitShapeError = [&]() {
1334     return emitError() << "expected shape ([" << type.getShape()
1335                        << "]); inferred shape of indices literal (["
1336                        << indicesType.getShape()
1337                        << "]); inferred shape of values literal (["
1338                        << valuesType.getShape() << "])";
1339   };
1340   // Verify indices shape.
1341   size_t rank = type.getRank(), indicesRank = indicesType.getRank();
1342   if (indicesRank == 2) {
1343     if (indicesType.getDimSize(1) != static_cast<int64_t>(rank))
1344       return emitShapeError();
1345   } else if (indicesRank != 1 || rank != 1) {
1346     return emitShapeError();
1347   }
1348   // Verify the values shape.
1349   int64_t numSparseIndices = indicesType.getDimSize(0);
1350   if (numSparseIndices != valuesType.getDimSize(0))
1351     return emitShapeError();
1352 
1353   // Verify that the sparse indices are within the value shape.
1354   auto emitIndexError = [&](unsigned indexNum, ArrayRef<uint64_t> index) {
1355     return emitError()
1356            << "sparse index #" << indexNum
1357            << " is not contained within the value shape, with index=[" << index
1358            << "], and type=" << type;
1359   };
1360 
1361   // Handle the case where the index values are a splat.
1362   auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1363   if (sparseIndices.isSplat()) {
1364     SmallVector<uint64_t> indices(rank, *sparseIndexValues.begin());
1365     if (!ElementsAttr::isValidIndex(type, indices))
1366       return emitIndexError(0, indices);
1367     return success();
1368   }
1369 
1370   // Otherwise, reinterpret each index as an ArrayRef.
1371   for (size_t i = 0, e = numSparseIndices; i != e; ++i) {
1372     ArrayRef<uint64_t> index(&*std::next(sparseIndexValues.begin(), i * rank),
1373                              rank);
1374     if (!ElementsAttr::isValidIndex(type, index))
1375       return emitIndexError(i, index);
1376   }
1377 
1378   return success();
1379 }
1380 
1381 //===----------------------------------------------------------------------===//
1382 // TypeAttr
1383 //===----------------------------------------------------------------------===//
1384 
1385 void TypeAttr::walkImmediateSubElements(
1386     function_ref<void(Attribute)> walkAttrsFn,
1387     function_ref<void(Type)> walkTypesFn) const {
1388   walkTypesFn(getValue());
1389 }
1390