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 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 bool BoolAttr::getValue() const { 379 auto *storage = reinterpret_cast<IntegerAttrStorage *>(impl); 380 return storage->value.getBoolValue(); 381 } 382 383 bool BoolAttr::classof(Attribute attr) { 384 IntegerAttr intAttr = attr.dyn_cast<IntegerAttr>(); 385 return intAttr && intAttr.getType().isSignlessInteger(1); 386 } 387 388 //===----------------------------------------------------------------------===// 389 // OpaqueAttr 390 //===----------------------------------------------------------------------===// 391 392 LogicalResult OpaqueAttr::verify(function_ref<InFlightDiagnostic()> emitError, 393 StringAttr dialect, StringRef attrData, 394 Type type) { 395 if (!Dialect::isValidNamespace(dialect.strref())) 396 return emitError() << "invalid dialect namespace '" << dialect << "'"; 397 398 // Check that the dialect is actually registered. 399 MLIRContext *context = dialect.getContext(); 400 if (!context->allowsUnregisteredDialects() && 401 !context->getLoadedDialect(dialect.strref())) { 402 return emitError() 403 << "#" << dialect << "<\"" << attrData << "\"> : " << type 404 << " attribute created with unregistered dialect. If this is " 405 "intended, please call allowUnregisteredDialects() on the " 406 "MLIRContext, or use -allow-unregistered-dialect with " 407 "the MLIR opt tool used"; 408 } 409 410 return success(); 411 } 412 413 //===----------------------------------------------------------------------===// 414 // DenseElementsAttr Utilities 415 //===----------------------------------------------------------------------===// 416 417 /// Get the bitwidth of a dense element type within the buffer. 418 /// DenseElementsAttr requires bitwidths greater than 1 to be aligned by 8. 419 static size_t getDenseElementStorageWidth(size_t origWidth) { 420 return origWidth == 1 ? origWidth : llvm::alignTo<8>(origWidth); 421 } 422 static size_t getDenseElementStorageWidth(Type elementType) { 423 return getDenseElementStorageWidth(getDenseElementBitWidth(elementType)); 424 } 425 426 /// Set a bit to a specific value. 427 static void setBit(char *rawData, size_t bitPos, bool value) { 428 if (value) 429 rawData[bitPos / CHAR_BIT] |= (1 << (bitPos % CHAR_BIT)); 430 else 431 rawData[bitPos / CHAR_BIT] &= ~(1 << (bitPos % CHAR_BIT)); 432 } 433 434 /// Return the value of the specified bit. 435 static bool getBit(const char *rawData, size_t bitPos) { 436 return (rawData[bitPos / CHAR_BIT] & (1 << (bitPos % CHAR_BIT))) != 0; 437 } 438 439 /// Copy actual `numBytes` data from `value` (APInt) to char array(`result`) for 440 /// BE format. 441 static void copyAPIntToArrayForBEmachine(APInt value, size_t numBytes, 442 char *result) { 443 assert(llvm::support::endian::system_endianness() == // NOLINT 444 llvm::support::endianness::big); // NOLINT 445 assert(value.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes); 446 447 // Copy the words filled with data. 448 // For example, when `value` has 2 words, the first word is filled with data. 449 // `value` (10 bytes, BE):|abcdefgh|------ij| ==> `result` (BE):|abcdefgh|--| 450 size_t numFilledWords = (value.getNumWords() - 1) * APInt::APINT_WORD_SIZE; 451 std::copy_n(reinterpret_cast<const char *>(value.getRawData()), 452 numFilledWords, result); 453 // Convert last word of APInt to LE format and store it in char 454 // array(`valueLE`). 455 // ex. last word of `value` (BE): |------ij| ==> `valueLE` (LE): |ji------| 456 size_t lastWordPos = numFilledWords; 457 SmallVector<char, 8> valueLE(APInt::APINT_WORD_SIZE); 458 DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine( 459 reinterpret_cast<const char *>(value.getRawData()) + lastWordPos, 460 valueLE.begin(), APInt::APINT_BITS_PER_WORD, 1); 461 // Extract actual APInt data from `valueLE`, convert endianness to BE format, 462 // and store it in `result`. 463 // ex. `valueLE` (LE): |ji------| ==> `result` (BE): |abcdefgh|ij| 464 DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine( 465 valueLE.begin(), result + lastWordPos, 466 (numBytes - lastWordPos) * CHAR_BIT, 1); 467 } 468 469 /// Copy `numBytes` data from `inArray`(char array) to `result`(APINT) for BE 470 /// format. 471 static void copyArrayToAPIntForBEmachine(const char *inArray, size_t numBytes, 472 APInt &result) { 473 assert(llvm::support::endian::system_endianness() == // NOLINT 474 llvm::support::endianness::big); // NOLINT 475 assert(result.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes); 476 477 // Copy the data that fills the word of `result` from `inArray`. 478 // For example, when `result` has 2 words, the first word will be filled with 479 // data. So, the first 8 bytes are copied from `inArray` here. 480 // `inArray` (10 bytes, BE): |abcdefgh|ij| 481 // ==> `result` (2 words, BE): |abcdefgh|--------| 482 size_t numFilledWords = (result.getNumWords() - 1) * APInt::APINT_WORD_SIZE; 483 std::copy_n( 484 inArray, numFilledWords, 485 const_cast<char *>(reinterpret_cast<const char *>(result.getRawData()))); 486 487 // Convert array data which will be last word of `result` to LE format, and 488 // store it in char array(`inArrayLE`). 489 // ex. `inArray` (last two bytes, BE): |ij| ==> `inArrayLE` (LE): |ji------| 490 size_t lastWordPos = numFilledWords; 491 SmallVector<char, 8> inArrayLE(APInt::APINT_WORD_SIZE); 492 DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine( 493 inArray + lastWordPos, inArrayLE.begin(), 494 (numBytes - lastWordPos) * CHAR_BIT, 1); 495 496 // Convert `inArrayLE` to BE format, and store it in last word of `result`. 497 // ex. `inArrayLE` (LE): |ji------| ==> `result` (BE): |abcdefgh|------ij| 498 DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine( 499 inArrayLE.begin(), 500 const_cast<char *>(reinterpret_cast<const char *>(result.getRawData())) + 501 lastWordPos, 502 APInt::APINT_BITS_PER_WORD, 1); 503 } 504 505 /// Writes value to the bit position `bitPos` in array `rawData`. 506 static void writeBits(char *rawData, size_t bitPos, APInt value) { 507 size_t bitWidth = value.getBitWidth(); 508 509 // If the bitwidth is 1 we just toggle the specific bit. 510 if (bitWidth == 1) 511 return setBit(rawData, bitPos, value.isOneValue()); 512 513 // Otherwise, the bit position is guaranteed to be byte aligned. 514 assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned"); 515 if (llvm::support::endian::system_endianness() == 516 llvm::support::endianness::big) { 517 // Copy from `value` to `rawData + (bitPos / CHAR_BIT)`. 518 // Copying the first `llvm::divideCeil(bitWidth, CHAR_BIT)` bytes doesn't 519 // work correctly in BE format. 520 // ex. `value` (2 words including 10 bytes) 521 // ==> BE: |abcdefgh|------ij|, LE: |hgfedcba|ji------| 522 copyAPIntToArrayForBEmachine(value, llvm::divideCeil(bitWidth, CHAR_BIT), 523 rawData + (bitPos / CHAR_BIT)); 524 } else { 525 std::copy_n(reinterpret_cast<const char *>(value.getRawData()), 526 llvm::divideCeil(bitWidth, CHAR_BIT), 527 rawData + (bitPos / CHAR_BIT)); 528 } 529 } 530 531 /// Reads the next `bitWidth` bits from the bit position `bitPos` in array 532 /// `rawData`. 533 static APInt readBits(const char *rawData, size_t bitPos, size_t bitWidth) { 534 // Handle a boolean bit position. 535 if (bitWidth == 1) 536 return APInt(1, getBit(rawData, bitPos) ? 1 : 0); 537 538 // Otherwise, the bit position must be 8-bit aligned. 539 assert((bitPos % CHAR_BIT) == 0 && "expected bitPos to be 8-bit aligned"); 540 APInt result(bitWidth, 0); 541 if (llvm::support::endian::system_endianness() == 542 llvm::support::endianness::big) { 543 // Copy from `rawData + (bitPos / CHAR_BIT)` to `result`. 544 // Copying the first `llvm::divideCeil(bitWidth, CHAR_BIT)` bytes doesn't 545 // work correctly in BE format. 546 // ex. `result` (2 words including 10 bytes) 547 // ==> BE: |abcdefgh|------ij|, LE: |hgfedcba|ji------| This function 548 copyArrayToAPIntForBEmachine(rawData + (bitPos / CHAR_BIT), 549 llvm::divideCeil(bitWidth, CHAR_BIT), result); 550 } else { 551 std::copy_n(rawData + (bitPos / CHAR_BIT), 552 llvm::divideCeil(bitWidth, CHAR_BIT), 553 const_cast<char *>( 554 reinterpret_cast<const char *>(result.getRawData()))); 555 } 556 return result; 557 } 558 559 /// Returns true if 'values' corresponds to a splat, i.e. one element, or has 560 /// the same element count as 'type'. 561 template <typename Values> 562 static bool hasSameElementsOrSplat(ShapedType type, const Values &values) { 563 return (values.size() == 1) || 564 (type.getNumElements() == static_cast<int64_t>(values.size())); 565 } 566 567 //===----------------------------------------------------------------------===// 568 // DenseElementsAttr Iterators 569 //===----------------------------------------------------------------------===// 570 571 //===----------------------------------------------------------------------===// 572 // AttributeElementIterator 573 574 DenseElementsAttr::AttributeElementIterator::AttributeElementIterator( 575 DenseElementsAttr attr, size_t index) 576 : llvm::indexed_accessor_iterator<AttributeElementIterator, const void *, 577 Attribute, Attribute, Attribute>( 578 attr.getAsOpaquePointer(), index) {} 579 580 Attribute DenseElementsAttr::AttributeElementIterator::operator*() const { 581 auto owner = getFromOpaquePointer(base).cast<DenseElementsAttr>(); 582 Type eltTy = owner.getElementType(); 583 if (auto intEltTy = eltTy.dyn_cast<IntegerType>()) 584 return IntegerAttr::get(eltTy, *IntElementIterator(owner, index)); 585 if (eltTy.isa<IndexType>()) 586 return IntegerAttr::get(eltTy, *IntElementIterator(owner, index)); 587 if (auto floatEltTy = eltTy.dyn_cast<FloatType>()) { 588 IntElementIterator intIt(owner, index); 589 FloatElementIterator floatIt(floatEltTy.getFloatSemantics(), intIt); 590 return FloatAttr::get(eltTy, *floatIt); 591 } 592 if (auto complexTy = eltTy.dyn_cast<ComplexType>()) { 593 auto complexEltTy = complexTy.getElementType(); 594 ComplexIntElementIterator complexIntIt(owner, index); 595 if (complexEltTy.isa<IntegerType>()) { 596 auto value = *complexIntIt; 597 auto real = IntegerAttr::get(complexEltTy, value.real()); 598 auto imag = IntegerAttr::get(complexEltTy, value.imag()); 599 return ArrayAttr::get(complexTy.getContext(), 600 ArrayRef<Attribute>{real, imag}); 601 } 602 603 ComplexFloatElementIterator complexFloatIt( 604 complexEltTy.cast<FloatType>().getFloatSemantics(), complexIntIt); 605 auto value = *complexFloatIt; 606 auto real = FloatAttr::get(complexEltTy, value.real()); 607 auto imag = FloatAttr::get(complexEltTy, value.imag()); 608 return ArrayAttr::get(complexTy.getContext(), 609 ArrayRef<Attribute>{real, imag}); 610 } 611 if (owner.isa<DenseStringElementsAttr>()) { 612 ArrayRef<StringRef> vals = owner.getRawStringData(); 613 return StringAttr::get(owner.isSplat() ? vals.front() : vals[index], eltTy); 614 } 615 llvm_unreachable("unexpected element type"); 616 } 617 618 //===----------------------------------------------------------------------===// 619 // BoolElementIterator 620 621 DenseElementsAttr::BoolElementIterator::BoolElementIterator( 622 DenseElementsAttr attr, size_t dataIndex) 623 : DenseElementIndexedIteratorImpl<BoolElementIterator, bool, bool, bool>( 624 attr.getRawData().data(), attr.isSplat(), dataIndex) {} 625 626 bool DenseElementsAttr::BoolElementIterator::operator*() const { 627 return getBit(getData(), getDataIndex()); 628 } 629 630 //===----------------------------------------------------------------------===// 631 // IntElementIterator 632 633 DenseElementsAttr::IntElementIterator::IntElementIterator( 634 DenseElementsAttr attr, size_t dataIndex) 635 : DenseElementIndexedIteratorImpl<IntElementIterator, APInt, APInt, APInt>( 636 attr.getRawData().data(), attr.isSplat(), dataIndex), 637 bitWidth(getDenseElementBitWidth(attr.getElementType())) {} 638 639 APInt DenseElementsAttr::IntElementIterator::operator*() const { 640 return readBits(getData(), 641 getDataIndex() * getDenseElementStorageWidth(bitWidth), 642 bitWidth); 643 } 644 645 //===----------------------------------------------------------------------===// 646 // ComplexIntElementIterator 647 648 DenseElementsAttr::ComplexIntElementIterator::ComplexIntElementIterator( 649 DenseElementsAttr attr, size_t dataIndex) 650 : DenseElementIndexedIteratorImpl<ComplexIntElementIterator, 651 std::complex<APInt>, std::complex<APInt>, 652 std::complex<APInt>>( 653 attr.getRawData().data(), attr.isSplat(), dataIndex) { 654 auto complexType = attr.getElementType().cast<ComplexType>(); 655 bitWidth = getDenseElementBitWidth(complexType.getElementType()); 656 } 657 658 std::complex<APInt> 659 DenseElementsAttr::ComplexIntElementIterator::operator*() const { 660 size_t storageWidth = getDenseElementStorageWidth(bitWidth); 661 size_t offset = getDataIndex() * storageWidth * 2; 662 return {readBits(getData(), offset, bitWidth), 663 readBits(getData(), offset + storageWidth, bitWidth)}; 664 } 665 666 //===----------------------------------------------------------------------===// 667 // DenseElementsAttr 668 //===----------------------------------------------------------------------===// 669 670 /// Method for support type inquiry through isa, cast and dyn_cast. 671 bool DenseElementsAttr::classof(Attribute attr) { 672 return attr.isa<DenseIntOrFPElementsAttr, DenseStringElementsAttr>(); 673 } 674 675 DenseElementsAttr DenseElementsAttr::get(ShapedType type, 676 ArrayRef<Attribute> values) { 677 assert(hasSameElementsOrSplat(type, values)); 678 679 // If the element type is not based on int/float/index, assume it is a string 680 // type. 681 auto eltType = type.getElementType(); 682 if (!type.getElementType().isIntOrIndexOrFloat()) { 683 SmallVector<StringRef, 8> stringValues; 684 stringValues.reserve(values.size()); 685 for (Attribute attr : values) { 686 assert(attr.isa<StringAttr>() && 687 "expected string value for non integer/index/float element"); 688 stringValues.push_back(attr.cast<StringAttr>().getValue()); 689 } 690 return get(type, stringValues); 691 } 692 693 // Otherwise, get the raw storage width to use for the allocation. 694 size_t bitWidth = getDenseElementBitWidth(eltType); 695 size_t storageBitWidth = getDenseElementStorageWidth(bitWidth); 696 697 // Compress the attribute values into a character buffer. 698 SmallVector<char, 8> data(llvm::divideCeil(storageBitWidth, CHAR_BIT) * 699 values.size()); 700 APInt intVal; 701 for (unsigned i = 0, e = values.size(); i < e; ++i) { 702 assert(eltType == values[i].getType() && 703 "expected attribute value to have element type"); 704 if (eltType.isa<FloatType>()) 705 intVal = values[i].cast<FloatAttr>().getValue().bitcastToAPInt(); 706 else if (eltType.isa<IntegerType, IndexType>()) 707 intVal = values[i].cast<IntegerAttr>().getValue(); 708 else 709 llvm_unreachable("unexpected element type"); 710 711 assert(intVal.getBitWidth() == bitWidth && 712 "expected value to have same bitwidth as element type"); 713 writeBits(data.data(), i * storageBitWidth, intVal); 714 } 715 return DenseIntOrFPElementsAttr::getRaw(type, data, 716 /*isSplat=*/(values.size() == 1)); 717 } 718 719 DenseElementsAttr DenseElementsAttr::get(ShapedType type, 720 ArrayRef<bool> values) { 721 assert(hasSameElementsOrSplat(type, values)); 722 assert(type.getElementType().isInteger(1)); 723 724 std::vector<char> buff(llvm::divideCeil(values.size(), CHAR_BIT)); 725 for (int i = 0, e = values.size(); i != e; ++i) 726 setBit(buff.data(), i, values[i]); 727 return DenseIntOrFPElementsAttr::getRaw(type, buff, 728 /*isSplat=*/(values.size() == 1)); 729 } 730 731 DenseElementsAttr DenseElementsAttr::get(ShapedType type, 732 ArrayRef<StringRef> values) { 733 assert(!type.getElementType().isIntOrFloat()); 734 return DenseStringElementsAttr::get(type, values); 735 } 736 737 /// Constructs a dense integer elements attribute from an array of APInt 738 /// values. Each APInt value is expected to have the same bitwidth as the 739 /// element type of 'type'. 740 DenseElementsAttr DenseElementsAttr::get(ShapedType type, 741 ArrayRef<APInt> values) { 742 assert(type.getElementType().isIntOrIndex()); 743 assert(hasSameElementsOrSplat(type, values)); 744 size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType()); 745 return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, values, 746 /*isSplat=*/(values.size() == 1)); 747 } 748 DenseElementsAttr DenseElementsAttr::get(ShapedType type, 749 ArrayRef<std::complex<APInt>> values) { 750 ComplexType complex = type.getElementType().cast<ComplexType>(); 751 assert(complex.getElementType().isa<IntegerType>()); 752 assert(hasSameElementsOrSplat(type, values)); 753 size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2; 754 ArrayRef<APInt> intVals(reinterpret_cast<const APInt *>(values.data()), 755 values.size() * 2); 756 return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, intVals, 757 /*isSplat=*/(values.size() == 1)); 758 } 759 760 // Constructs a dense float elements attribute from an array of APFloat 761 // values. Each APFloat value is expected to have the same bitwidth as the 762 // element type of 'type'. 763 DenseElementsAttr DenseElementsAttr::get(ShapedType type, 764 ArrayRef<APFloat> values) { 765 assert(type.getElementType().isa<FloatType>()); 766 assert(hasSameElementsOrSplat(type, values)); 767 size_t storageBitWidth = getDenseElementStorageWidth(type.getElementType()); 768 return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, values, 769 /*isSplat=*/(values.size() == 1)); 770 } 771 DenseElementsAttr 772 DenseElementsAttr::get(ShapedType type, 773 ArrayRef<std::complex<APFloat>> values) { 774 ComplexType complex = type.getElementType().cast<ComplexType>(); 775 assert(complex.getElementType().isa<FloatType>()); 776 assert(hasSameElementsOrSplat(type, values)); 777 ArrayRef<APFloat> apVals(reinterpret_cast<const APFloat *>(values.data()), 778 values.size() * 2); 779 size_t storageBitWidth = getDenseElementStorageWidth(complex) / 2; 780 return DenseIntOrFPElementsAttr::getRaw(type, storageBitWidth, apVals, 781 /*isSplat=*/(values.size() == 1)); 782 } 783 784 /// Construct a dense elements attribute from a raw buffer representing the 785 /// data for this attribute. Users should generally not use this methods as 786 /// the expected buffer format may not be a form the user expects. 787 DenseElementsAttr DenseElementsAttr::getFromRawBuffer(ShapedType type, 788 ArrayRef<char> rawBuffer, 789 bool isSplatBuffer) { 790 return DenseIntOrFPElementsAttr::getRaw(type, rawBuffer, isSplatBuffer); 791 } 792 793 /// Returns true if the given buffer is a valid raw buffer for the given type. 794 bool DenseElementsAttr::isValidRawBuffer(ShapedType type, 795 ArrayRef<char> rawBuffer, 796 bool &detectedSplat) { 797 size_t storageWidth = getDenseElementStorageWidth(type.getElementType()); 798 size_t rawBufferWidth = rawBuffer.size() * CHAR_BIT; 799 800 // Storage width of 1 is special as it is packed by the bit. 801 if (storageWidth == 1) { 802 // Check for a splat, or a buffer equal to the number of elements which 803 // consists of either all 0's or all 1's. 804 detectedSplat = false; 805 if (rawBuffer.size() == 1) { 806 auto rawByte = static_cast<uint8_t>(rawBuffer[0]); 807 if (rawByte == 0 || rawByte == 0xff) { 808 detectedSplat = true; 809 return true; 810 } 811 } 812 return rawBufferWidth == llvm::alignTo<8>(type.getNumElements()); 813 } 814 // All other types are 8-bit aligned. 815 if ((detectedSplat = rawBufferWidth == storageWidth)) 816 return true; 817 return rawBufferWidth == (storageWidth * type.getNumElements()); 818 } 819 820 /// Check the information for a C++ data type, check if this type is valid for 821 /// the current attribute. This method is used to verify specific type 822 /// invariants that the templatized 'getValues' method cannot. 823 static bool isValidIntOrFloat(Type type, int64_t dataEltSize, bool isInt, 824 bool isSigned) { 825 // Make sure that the data element size is the same as the type element width. 826 if (getDenseElementBitWidth(type) != 827 static_cast<size_t>(dataEltSize * CHAR_BIT)) 828 return false; 829 830 // Check that the element type is either float or integer or index. 831 if (!isInt) 832 return type.isa<FloatType>(); 833 if (type.isIndex()) 834 return true; 835 836 auto intType = type.dyn_cast<IntegerType>(); 837 if (!intType) 838 return false; 839 840 // Make sure signedness semantics is consistent. 841 if (intType.isSignless()) 842 return true; 843 return intType.isSigned() ? isSigned : !isSigned; 844 } 845 846 /// Defaults down the subclass implementation. 847 DenseElementsAttr DenseElementsAttr::getRawComplex(ShapedType type, 848 ArrayRef<char> data, 849 int64_t dataEltSize, 850 bool isInt, bool isSigned) { 851 return DenseIntOrFPElementsAttr::getRawComplex(type, data, dataEltSize, isInt, 852 isSigned); 853 } 854 DenseElementsAttr DenseElementsAttr::getRawIntOrFloat(ShapedType type, 855 ArrayRef<char> data, 856 int64_t dataEltSize, 857 bool isInt, 858 bool isSigned) { 859 return DenseIntOrFPElementsAttr::getRawIntOrFloat(type, data, dataEltSize, 860 isInt, isSigned); 861 } 862 863 bool DenseElementsAttr::isValidIntOrFloat(int64_t dataEltSize, bool isInt, 864 bool isSigned) const { 865 return ::isValidIntOrFloat(getElementType(), dataEltSize, isInt, isSigned); 866 } 867 bool DenseElementsAttr::isValidComplex(int64_t dataEltSize, bool isInt, 868 bool isSigned) const { 869 return ::isValidIntOrFloat( 870 getElementType().cast<ComplexType>().getElementType(), dataEltSize / 2, 871 isInt, isSigned); 872 } 873 874 /// Returns true if this attribute corresponds to a splat, i.e. if all element 875 /// values are the same. 876 bool DenseElementsAttr::isSplat() const { 877 return static_cast<DenseElementsAttributeStorage *>(impl)->isSplat; 878 } 879 880 /// Return if the given complex type has an integer element type. 881 LLVM_ATTRIBUTE_UNUSED static bool isComplexOfIntType(Type type) { 882 return type.cast<ComplexType>().getElementType().isa<IntegerType>(); 883 } 884 885 auto DenseElementsAttr::getComplexIntValues() const 886 -> iterator_range_impl<ComplexIntElementIterator> { 887 assert(isComplexOfIntType(getElementType()) && 888 "expected complex integral type"); 889 return {getType(), ComplexIntElementIterator(*this, 0), 890 ComplexIntElementIterator(*this, getNumElements())}; 891 } 892 auto DenseElementsAttr::complex_value_begin() const 893 -> ComplexIntElementIterator { 894 assert(isComplexOfIntType(getElementType()) && 895 "expected complex integral type"); 896 return ComplexIntElementIterator(*this, 0); 897 } 898 auto DenseElementsAttr::complex_value_end() const -> ComplexIntElementIterator { 899 assert(isComplexOfIntType(getElementType()) && 900 "expected complex integral type"); 901 return ComplexIntElementIterator(*this, getNumElements()); 902 } 903 904 /// Return the held element values as a range of APFloat. The element type of 905 /// this attribute must be of float type. 906 auto DenseElementsAttr::getFloatValues() const 907 -> iterator_range_impl<FloatElementIterator> { 908 auto elementType = getElementType().cast<FloatType>(); 909 const auto &elementSemantics = elementType.getFloatSemantics(); 910 return {getType(), FloatElementIterator(elementSemantics, raw_int_begin()), 911 FloatElementIterator(elementSemantics, raw_int_end())}; 912 } 913 auto DenseElementsAttr::float_value_begin() const -> FloatElementIterator { 914 auto elementType = getElementType().cast<FloatType>(); 915 return FloatElementIterator(elementType.getFloatSemantics(), raw_int_begin()); 916 } 917 auto DenseElementsAttr::float_value_end() const -> FloatElementIterator { 918 auto elementType = getElementType().cast<FloatType>(); 919 return FloatElementIterator(elementType.getFloatSemantics(), raw_int_end()); 920 } 921 922 auto DenseElementsAttr::getComplexFloatValues() const 923 -> iterator_range_impl<ComplexFloatElementIterator> { 924 Type eltTy = getElementType().cast<ComplexType>().getElementType(); 925 assert(eltTy.isa<FloatType>() && "expected complex float type"); 926 const auto &semantics = eltTy.cast<FloatType>().getFloatSemantics(); 927 return {getType(), 928 {semantics, {*this, 0}}, 929 {semantics, {*this, static_cast<size_t>(getNumElements())}}}; 930 } 931 auto DenseElementsAttr::complex_float_value_begin() const 932 -> ComplexFloatElementIterator { 933 Type eltTy = getElementType().cast<ComplexType>().getElementType(); 934 assert(eltTy.isa<FloatType>() && "expected complex float type"); 935 return {eltTy.cast<FloatType>().getFloatSemantics(), {*this, 0}}; 936 } 937 auto DenseElementsAttr::complex_float_value_end() const 938 -> ComplexFloatElementIterator { 939 Type eltTy = getElementType().cast<ComplexType>().getElementType(); 940 assert(eltTy.isa<FloatType>() && "expected complex float type"); 941 return {eltTy.cast<FloatType>().getFloatSemantics(), 942 {*this, static_cast<size_t>(getNumElements())}}; 943 } 944 945 /// Return the raw storage data held by this attribute. 946 ArrayRef<char> DenseElementsAttr::getRawData() const { 947 return static_cast<DenseIntOrFPElementsAttrStorage *>(impl)->data; 948 } 949 950 ArrayRef<StringRef> DenseElementsAttr::getRawStringData() const { 951 return static_cast<DenseStringElementsAttrStorage *>(impl)->data; 952 } 953 954 /// Return a new DenseElementsAttr that has the same data as the current 955 /// attribute, but has been reshaped to 'newType'. The new type must have the 956 /// same total number of elements as well as element type. 957 DenseElementsAttr DenseElementsAttr::reshape(ShapedType newType) { 958 ShapedType curType = getType(); 959 if (curType == newType) 960 return *this; 961 962 assert(newType.getElementType() == curType.getElementType() && 963 "expected the same element type"); 964 assert(newType.getNumElements() == curType.getNumElements() && 965 "expected the same number of elements"); 966 return DenseIntOrFPElementsAttr::getRaw(newType, getRawData(), isSplat()); 967 } 968 969 /// Return a new DenseElementsAttr that has the same data as the current 970 /// attribute, but has bitcast elements such that it is now 'newType'. The new 971 /// type must have the same shape and element types of the same bitwidth as the 972 /// current type. 973 DenseElementsAttr DenseElementsAttr::bitcast(Type newElType) { 974 ShapedType curType = getType(); 975 Type curElType = curType.getElementType(); 976 if (curElType == newElType) 977 return *this; 978 979 assert(getDenseElementBitWidth(newElType) == 980 getDenseElementBitWidth(curElType) && 981 "expected element types with the same bitwidth"); 982 return DenseIntOrFPElementsAttr::getRaw(curType.clone(newElType), 983 getRawData(), isSplat()); 984 } 985 986 DenseElementsAttr 987 DenseElementsAttr::mapValues(Type newElementType, 988 function_ref<APInt(const APInt &)> mapping) const { 989 return cast<DenseIntElementsAttr>().mapValues(newElementType, mapping); 990 } 991 992 DenseElementsAttr DenseElementsAttr::mapValues( 993 Type newElementType, function_ref<APInt(const APFloat &)> mapping) const { 994 return cast<DenseFPElementsAttr>().mapValues(newElementType, mapping); 995 } 996 997 ShapedType DenseElementsAttr::getType() const { 998 return Attribute::getType().cast<ShapedType>(); 999 } 1000 1001 Type DenseElementsAttr::getElementType() const { 1002 return getType().getElementType(); 1003 } 1004 1005 int64_t DenseElementsAttr::getNumElements() const { 1006 return getType().getNumElements(); 1007 } 1008 1009 //===----------------------------------------------------------------------===// 1010 // DenseIntOrFPElementsAttr 1011 //===----------------------------------------------------------------------===// 1012 1013 /// Utility method to write a range of APInt values to a buffer. 1014 template <typename APRangeT> 1015 static void writeAPIntsToBuffer(size_t storageWidth, std::vector<char> &data, 1016 APRangeT &&values) { 1017 data.resize(llvm::divideCeil(storageWidth, CHAR_BIT) * llvm::size(values)); 1018 size_t offset = 0; 1019 for (auto it = values.begin(), e = values.end(); it != e; 1020 ++it, offset += storageWidth) { 1021 assert((*it).getBitWidth() <= storageWidth); 1022 writeBits(data.data(), offset, *it); 1023 } 1024 } 1025 1026 /// Constructs a dense elements attribute from an array of raw APFloat values. 1027 /// Each APFloat value is expected to have the same bitwidth as the element 1028 /// type of 'type'. 'type' must be a vector or tensor with static shape. 1029 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type, 1030 size_t storageWidth, 1031 ArrayRef<APFloat> values, 1032 bool isSplat) { 1033 std::vector<char> data; 1034 auto unwrapFloat = [](const APFloat &val) { return val.bitcastToAPInt(); }; 1035 writeAPIntsToBuffer(storageWidth, data, llvm::map_range(values, unwrapFloat)); 1036 return DenseIntOrFPElementsAttr::getRaw(type, data, isSplat); 1037 } 1038 1039 /// Constructs a dense elements attribute from an array of raw APInt values. 1040 /// Each APInt value is expected to have the same bitwidth as the element type 1041 /// of 'type'. 1042 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type, 1043 size_t storageWidth, 1044 ArrayRef<APInt> values, 1045 bool isSplat) { 1046 std::vector<char> data; 1047 writeAPIntsToBuffer(storageWidth, data, values); 1048 return DenseIntOrFPElementsAttr::getRaw(type, data, isSplat); 1049 } 1050 1051 DenseElementsAttr DenseIntOrFPElementsAttr::getRaw(ShapedType type, 1052 ArrayRef<char> data, 1053 bool isSplat) { 1054 assert((type.isa<RankedTensorType, VectorType>()) && 1055 "type must be ranked tensor or vector"); 1056 assert(type.hasStaticShape() && "type must have static shape"); 1057 return Base::get(type.getContext(), type, data, isSplat); 1058 } 1059 1060 /// Overload of the raw 'get' method that asserts that the given type is of 1061 /// complex type. This method is used to verify type invariants that the 1062 /// templatized 'get' method cannot. 1063 DenseElementsAttr DenseIntOrFPElementsAttr::getRawComplex(ShapedType type, 1064 ArrayRef<char> data, 1065 int64_t dataEltSize, 1066 bool isInt, 1067 bool isSigned) { 1068 assert(::isValidIntOrFloat( 1069 type.getElementType().cast<ComplexType>().getElementType(), 1070 dataEltSize / 2, isInt, isSigned)); 1071 1072 int64_t numElements = data.size() / dataEltSize; 1073 assert(numElements == 1 || numElements == type.getNumElements()); 1074 return getRaw(type, data, /*isSplat=*/numElements == 1); 1075 } 1076 1077 /// Overload of the 'getRaw' method that asserts that the given type is of 1078 /// integer type. This method is used to verify type invariants that the 1079 /// templatized 'get' method cannot. 1080 DenseElementsAttr 1081 DenseIntOrFPElementsAttr::getRawIntOrFloat(ShapedType type, ArrayRef<char> data, 1082 int64_t dataEltSize, bool isInt, 1083 bool isSigned) { 1084 assert( 1085 ::isValidIntOrFloat(type.getElementType(), dataEltSize, isInt, isSigned)); 1086 1087 int64_t numElements = data.size() / dataEltSize; 1088 assert(numElements == 1 || numElements == type.getNumElements()); 1089 return getRaw(type, data, /*isSplat=*/numElements == 1); 1090 } 1091 1092 void DenseIntOrFPElementsAttr::convertEndianOfCharForBEmachine( 1093 const char *inRawData, char *outRawData, size_t elementBitWidth, 1094 size_t numElements) { 1095 using llvm::support::ulittle16_t; 1096 using llvm::support::ulittle32_t; 1097 using llvm::support::ulittle64_t; 1098 1099 assert(llvm::support::endian::system_endianness() == // NOLINT 1100 llvm::support::endianness::big); // NOLINT 1101 // NOLINT to avoid warning message about replacing by static_assert() 1102 1103 // Following std::copy_n always converts endianness on BE machine. 1104 switch (elementBitWidth) { 1105 case 16: { 1106 const ulittle16_t *inRawDataPos = 1107 reinterpret_cast<const ulittle16_t *>(inRawData); 1108 uint16_t *outDataPos = reinterpret_cast<uint16_t *>(outRawData); 1109 std::copy_n(inRawDataPos, numElements, outDataPos); 1110 break; 1111 } 1112 case 32: { 1113 const ulittle32_t *inRawDataPos = 1114 reinterpret_cast<const ulittle32_t *>(inRawData); 1115 uint32_t *outDataPos = reinterpret_cast<uint32_t *>(outRawData); 1116 std::copy_n(inRawDataPos, numElements, outDataPos); 1117 break; 1118 } 1119 case 64: { 1120 const ulittle64_t *inRawDataPos = 1121 reinterpret_cast<const ulittle64_t *>(inRawData); 1122 uint64_t *outDataPos = reinterpret_cast<uint64_t *>(outRawData); 1123 std::copy_n(inRawDataPos, numElements, outDataPos); 1124 break; 1125 } 1126 default: { 1127 size_t nBytes = elementBitWidth / CHAR_BIT; 1128 for (size_t i = 0; i < nBytes; i++) 1129 std::copy_n(inRawData + (nBytes - 1 - i), 1, outRawData + i); 1130 break; 1131 } 1132 } 1133 } 1134 1135 void DenseIntOrFPElementsAttr::convertEndianOfArrayRefForBEmachine( 1136 ArrayRef<char> inRawData, MutableArrayRef<char> outRawData, 1137 ShapedType type) { 1138 size_t numElements = type.getNumElements(); 1139 Type elementType = type.getElementType(); 1140 if (ComplexType complexTy = elementType.dyn_cast<ComplexType>()) { 1141 elementType = complexTy.getElementType(); 1142 numElements = numElements * 2; 1143 } 1144 size_t elementBitWidth = getDenseElementStorageWidth(elementType); 1145 assert(numElements * elementBitWidth == inRawData.size() * CHAR_BIT && 1146 inRawData.size() <= outRawData.size()); 1147 convertEndianOfCharForBEmachine(inRawData.begin(), outRawData.begin(), 1148 elementBitWidth, numElements); 1149 } 1150 1151 //===----------------------------------------------------------------------===// 1152 // DenseFPElementsAttr 1153 //===----------------------------------------------------------------------===// 1154 1155 template <typename Fn, typename Attr> 1156 static ShapedType mappingHelper(Fn mapping, Attr &attr, ShapedType inType, 1157 Type newElementType, 1158 llvm::SmallVectorImpl<char> &data) { 1159 size_t bitWidth = getDenseElementBitWidth(newElementType); 1160 size_t storageBitWidth = getDenseElementStorageWidth(bitWidth); 1161 1162 ShapedType newArrayType; 1163 if (inType.isa<RankedTensorType>()) 1164 newArrayType = RankedTensorType::get(inType.getShape(), newElementType); 1165 else if (inType.isa<UnrankedTensorType>()) 1166 newArrayType = RankedTensorType::get(inType.getShape(), newElementType); 1167 else if (inType.isa<VectorType>()) 1168 newArrayType = VectorType::get(inType.getShape(), newElementType); 1169 else 1170 assert(newArrayType && "Unhandled tensor type"); 1171 1172 size_t numRawElements = attr.isSplat() ? 1 : newArrayType.getNumElements(); 1173 data.resize(llvm::divideCeil(storageBitWidth, CHAR_BIT) * numRawElements); 1174 1175 // Functor used to process a single element value of the attribute. 1176 auto processElt = [&](decltype(*attr.begin()) value, size_t index) { 1177 auto newInt = mapping(value); 1178 assert(newInt.getBitWidth() == bitWidth); 1179 writeBits(data.data(), index * storageBitWidth, newInt); 1180 }; 1181 1182 // Check for the splat case. 1183 if (attr.isSplat()) { 1184 processElt(*attr.begin(), /*index=*/0); 1185 return newArrayType; 1186 } 1187 1188 // Otherwise, process all of the element values. 1189 uint64_t elementIdx = 0; 1190 for (auto value : attr) 1191 processElt(value, elementIdx++); 1192 return newArrayType; 1193 } 1194 1195 DenseElementsAttr DenseFPElementsAttr::mapValues( 1196 Type newElementType, function_ref<APInt(const APFloat &)> mapping) const { 1197 llvm::SmallVector<char, 8> elementData; 1198 auto newArrayType = 1199 mappingHelper(mapping, *this, getType(), newElementType, elementData); 1200 1201 return getRaw(newArrayType, elementData, isSplat()); 1202 } 1203 1204 /// Method for supporting type inquiry through isa, cast and dyn_cast. 1205 bool DenseFPElementsAttr::classof(Attribute attr) { 1206 return attr.isa<DenseElementsAttr>() && 1207 attr.getType().cast<ShapedType>().getElementType().isa<FloatType>(); 1208 } 1209 1210 //===----------------------------------------------------------------------===// 1211 // DenseIntElementsAttr 1212 //===----------------------------------------------------------------------===// 1213 1214 DenseElementsAttr DenseIntElementsAttr::mapValues( 1215 Type newElementType, function_ref<APInt(const APInt &)> mapping) const { 1216 llvm::SmallVector<char, 8> elementData; 1217 auto newArrayType = 1218 mappingHelper(mapping, *this, getType(), newElementType, elementData); 1219 1220 return getRaw(newArrayType, elementData, isSplat()); 1221 } 1222 1223 /// Method for supporting type inquiry through isa, cast and dyn_cast. 1224 bool DenseIntElementsAttr::classof(Attribute attr) { 1225 return attr.isa<DenseElementsAttr>() && 1226 attr.getType().cast<ShapedType>().getElementType().isIntOrIndex(); 1227 } 1228 1229 //===----------------------------------------------------------------------===// 1230 // OpaqueElementsAttr 1231 //===----------------------------------------------------------------------===// 1232 1233 bool OpaqueElementsAttr::decode(ElementsAttr &result) { 1234 Dialect *dialect = getContext()->getLoadedDialect(getDialect()); 1235 if (!dialect) 1236 return true; 1237 auto *interface = 1238 dialect->getRegisteredInterface<DialectDecodeAttributesInterface>(); 1239 if (!interface) 1240 return true; 1241 return failed(interface->decode(*this, result)); 1242 } 1243 1244 LogicalResult 1245 OpaqueElementsAttr::verify(function_ref<InFlightDiagnostic()> emitError, 1246 StringAttr dialect, StringRef value, 1247 ShapedType type) { 1248 if (!Dialect::isValidNamespace(dialect.strref())) 1249 return emitError() << "invalid dialect namespace '" << dialect << "'"; 1250 return success(); 1251 } 1252 1253 //===----------------------------------------------------------------------===// 1254 // SparseElementsAttr 1255 //===----------------------------------------------------------------------===// 1256 1257 /// Get a zero APFloat for the given sparse attribute. 1258 APFloat SparseElementsAttr::getZeroAPFloat() const { 1259 auto eltType = getElementType().cast<FloatType>(); 1260 return APFloat(eltType.getFloatSemantics()); 1261 } 1262 1263 /// Get a zero APInt for the given sparse attribute. 1264 APInt SparseElementsAttr::getZeroAPInt() const { 1265 auto eltType = getElementType().cast<IntegerType>(); 1266 return APInt::getZero(eltType.getWidth()); 1267 } 1268 1269 /// Get a zero attribute for the given attribute type. 1270 Attribute SparseElementsAttr::getZeroAttr() const { 1271 auto eltType = getElementType(); 1272 1273 // Handle floating point elements. 1274 if (eltType.isa<FloatType>()) 1275 return FloatAttr::get(eltType, 0); 1276 1277 // Handle string type. 1278 if (getValues().isa<DenseStringElementsAttr>()) 1279 return StringAttr::get("", eltType); 1280 1281 // Otherwise, this is an integer. 1282 return IntegerAttr::get(eltType, 0); 1283 } 1284 1285 /// Flatten, and return, all of the sparse indices in this attribute in 1286 /// row-major order. 1287 std::vector<ptrdiff_t> SparseElementsAttr::getFlattenedSparseIndices() const { 1288 std::vector<ptrdiff_t> flatSparseIndices; 1289 1290 // The sparse indices are 64-bit integers, so we can reinterpret the raw data 1291 // as a 1-D index array. 1292 auto sparseIndices = getIndices(); 1293 auto sparseIndexValues = sparseIndices.getValues<uint64_t>(); 1294 if (sparseIndices.isSplat()) { 1295 SmallVector<uint64_t, 8> indices(getType().getRank(), 1296 *sparseIndexValues.begin()); 1297 flatSparseIndices.push_back(getFlattenedIndex(indices)); 1298 return flatSparseIndices; 1299 } 1300 1301 // Otherwise, reinterpret each index as an ArrayRef when flattening. 1302 auto numSparseIndices = sparseIndices.getType().getDimSize(0); 1303 size_t rank = getType().getRank(); 1304 for (size_t i = 0, e = numSparseIndices; i != e; ++i) 1305 flatSparseIndices.push_back(getFlattenedIndex( 1306 {&*std::next(sparseIndexValues.begin(), i * rank), rank})); 1307 return flatSparseIndices; 1308 } 1309 1310 LogicalResult 1311 SparseElementsAttr::verify(function_ref<InFlightDiagnostic()> emitError, 1312 ShapedType type, DenseIntElementsAttr sparseIndices, 1313 DenseElementsAttr values) { 1314 ShapedType valuesType = values.getType(); 1315 if (valuesType.getRank() != 1) 1316 return emitError() << "expected 1-d tensor for sparse element values"; 1317 1318 // Verify the indices and values shape. 1319 ShapedType indicesType = sparseIndices.getType(); 1320 auto emitShapeError = [&]() { 1321 return emitError() << "expected shape ([" << type.getShape() 1322 << "]); inferred shape of indices literal ([" 1323 << indicesType.getShape() 1324 << "]); inferred shape of values literal ([" 1325 << valuesType.getShape() << "])"; 1326 }; 1327 // Verify indices shape. 1328 size_t rank = type.getRank(), indicesRank = indicesType.getRank(); 1329 if (indicesRank == 2) { 1330 if (indicesType.getDimSize(1) != static_cast<int64_t>(rank)) 1331 return emitShapeError(); 1332 } else if (indicesRank != 1 || rank != 1) { 1333 return emitShapeError(); 1334 } 1335 // Verify the values shape. 1336 int64_t numSparseIndices = indicesType.getDimSize(0); 1337 if (numSparseIndices != valuesType.getDimSize(0)) 1338 return emitShapeError(); 1339 1340 // Verify that the sparse indices are within the value shape. 1341 auto emitIndexError = [&](unsigned indexNum, ArrayRef<uint64_t> index) { 1342 return emitError() 1343 << "sparse index #" << indexNum 1344 << " is not contained within the value shape, with index=[" << index 1345 << "], and type=" << type; 1346 }; 1347 1348 // Handle the case where the index values are a splat. 1349 auto sparseIndexValues = sparseIndices.getValues<uint64_t>(); 1350 if (sparseIndices.isSplat()) { 1351 SmallVector<uint64_t> indices(rank, *sparseIndexValues.begin()); 1352 if (!ElementsAttr::isValidIndex(type, indices)) 1353 return emitIndexError(0, indices); 1354 return success(); 1355 } 1356 1357 // Otherwise, reinterpret each index as an ArrayRef. 1358 for (size_t i = 0, e = numSparseIndices; i != e; ++i) { 1359 ArrayRef<uint64_t> index(&*std::next(sparseIndexValues.begin(), i * rank), 1360 rank); 1361 if (!ElementsAttr::isValidIndex(type, index)) 1362 return emitIndexError(i, index); 1363 } 1364 1365 return success(); 1366 } 1367 1368 //===----------------------------------------------------------------------===// 1369 // TypeAttr 1370 //===----------------------------------------------------------------------===// 1371 1372 void TypeAttr::walkImmediateSubElements( 1373 function_ref<void(Attribute)> walkAttrsFn, 1374 function_ref<void(Type)> walkTypesFn) const { 1375 walkTypesFn(getValue()); 1376 } 1377