21#include "llvm/ADT/APSInt.h"
22#include "llvm/Support/Alignment.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/DebugLog.h"
25#include "llvm/Support/Endian.h"
28#define DEBUG_TYPE "builtinattributes"
37#define GET_ATTRDEF_CLASSES
38#include "mlir/IR/BuiltinAttributes.cpp.inc"
48template <
bool inPlace>
52 switch (value.size()) {
61 storage.assign({value[0]});
64 bool isSorted = value[0] < value[1];
67 std::swap(storage[0], storage[1]);
68 }
else if (isSorted) {
69 storage.assign({value[0], value[1]});
71 storage.assign({value[1], value[0]});
77 storage.assign(value.begin(), value.end());
79 bool isSorted = llvm::is_sorted(value);
82 llvm::array_pod_sort(storage.begin(), storage.end());
90static std::optional<NamedAttribute>
92 const std::optional<NamedAttribute> none{std::nullopt};
96 if (value.size() == 2)
97 return value[0].getName() == value[1].getName() ? value[0] : none;
99 const auto *it = std::adjacent_find(value.begin(), value.end(),
101 return l.getName() == r.getName();
103 return it != value.end() ? *it : none;
110 "DictionaryAttr element names must be unique");
117 "DictionaryAttr element names must be unique");
121std::optional<NamedAttribute>
129DictionaryAttr DictionaryAttr::get(
MLIRContext *context,
132 return DictionaryAttr::getEmpty(context);
135 SmallVector<NamedAttribute, 8> storage;
139 "DictionaryAttr element names must be unique");
140 return Base::get(context, value);
144DictionaryAttr DictionaryAttr::getWithSorted(
MLIRContext *context,
147 return DictionaryAttr::getEmpty(context);
149 assert(llvm::is_sorted(
150 value, [](NamedAttribute l, NamedAttribute r) {
return l < r; }) &&
151 "expected attribute values to be sorted");
153 "DictionaryAttr element names must be unique");
154 return Base::get(context, value);
158Attribute DictionaryAttr::get(StringRef name)
const {
159 auto it = impl::findAttrSorted(begin(), end(), name);
160 return it.second ? it.first->getValue() : Attribute();
162Attribute DictionaryAttr::get(StringAttr name)
const {
163 auto it = impl::findAttrSorted(begin(), end(), name);
164 return it.second ? it.first->getValue() : Attribute();
168std::optional<NamedAttribute> DictionaryAttr::getNamed(StringRef name)
const {
169 auto it = impl::findAttrSorted(begin(), end(), name);
170 return it.second ? *it.first : std::optional<NamedAttribute>();
172std::optional<NamedAttribute> DictionaryAttr::getNamed(StringAttr name)
const {
173 auto it = impl::findAttrSorted(begin(), end(), name);
174 return it.second ? *it.first : std::optional<NamedAttribute>();
178bool DictionaryAttr::contains(StringRef name)
const {
179 return impl::findAttrSorted(begin(), end(), name).second;
181bool DictionaryAttr::contains(StringAttr name)
const {
182 return impl::findAttrSorted(begin(), end(), name).second;
185DictionaryAttr::iterator DictionaryAttr::begin()
const {
186 return getValue().begin();
188DictionaryAttr::iterator DictionaryAttr::end()
const {
189 return getValue().end();
191size_t DictionaryAttr::size()
const {
return getValue().size(); }
193DictionaryAttr DictionaryAttr::getEmptyUnchecked(
MLIRContext *context) {
194 return Base::get(context, ArrayRef<NamedAttribute>());
202void StridedLayoutAttr::print(llvm::raw_ostream &os)
const {
203 auto printIntOrQuestion = [&](
int64_t value) {
204 if (ShapedType::isDynamic(value))
211 llvm::interleaveComma(getStrides(), os, printIntOrQuestion);
214 if (getOffset() != 0) {
216 printIntOrQuestion(getOffset());
223bool StridedLayoutAttr::hasStaticLayout()
const {
224 return ShapedType::isStatic(getOffset()) &&
225 ShapedType::isStaticShape(getStrides());
229AffineMap StridedLayoutAttr::getAffineMap()
const {
241LogicalResult StridedLayoutAttr::verifyLayout(
244 if (
shape.size() != getStrides().size())
245 return emitError() <<
"expected the number of strides to match the rank";
254 llvm::append_range(strides, getStrides());
255 offset = getOffset();
263StringAttr StringAttr::getEmptyStringAttrUnchecked(
MLIRContext *context) {
264 return Base::get(context,
"", NoneType::get(context));
268StringAttr StringAttr::get(
MLIRContext *context,
const Twine &twine) {
270 if (twine.isTriviallyEmpty())
272 SmallVector<char, 32> tempStr;
273 return Base::get(context, twine.toStringRef(tempStr), NoneType::get(context));
277StringAttr StringAttr::get(
const Twine &twine,
Type type) {
278 SmallVector<char, 32> tempStr;
279 return Base::get(type.
getContext(), twine.toStringRef(tempStr), type);
282StringRef StringAttr::getValue()
const {
return getImpl()->value; }
284Type StringAttr::getType()
const {
return getImpl()->type; }
286Dialect *StringAttr::getReferencedDialect()
const {
287 return getImpl()->referencedDialect;
294double FloatAttr::getValueAsDouble()
const {
295 return getValueAsDouble(getValue());
297double FloatAttr::getValueAsDouble(APFloat value) {
298 if (&value.getSemantics() != &APFloat::IEEEdouble()) {
299 bool losesInfo =
false;
300 value.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
303 return value.convertToDouble();
307 Type type, APFloat value) {
309 if (!llvm::isa<FloatType>(type))
310 return emitError() <<
"expected floating point type";
314 &value.getSemantics()) {
316 <<
"FloatAttr type doesn't match the type implied by its value";
325SymbolRefAttr SymbolRefAttr::get(
MLIRContext *ctx, StringRef value,
327 return get(StringAttr::get(ctx, value), nestedRefs);
331 return llvm::cast<FlatSymbolRefAttr>(
get(ctx, value, {}));
335 return llvm::cast<FlatSymbolRefAttr>(
get(value, {}));
339 auto symbolOp = cast<SymbolOpInterface>(symbol);
340 return SymbolRefAttr::get(symbolOp.getNameAttr());
343StringAttr SymbolRefAttr::getLeafReference()
const {
344 ArrayRef<FlatSymbolRefAttr> nestedRefs = getNestedReferences();
345 return nestedRefs.empty() ? getRootReference() : nestedRefs.back().getAttr();
352int64_t IntegerAttr::getInt()
const {
354 "must be signless integer");
355 return getValue().getSExtValue();
358int64_t IntegerAttr::getSInt()
const {
359 assert(
getType().isSignedInteger() &&
"must be signed integer");
360 return getValue().getSExtValue();
363uint64_t IntegerAttr::getUInt()
const {
364 assert(
getType().isUnsignedInteger() &&
"must be unsigned integer");
365 return getValue().getZExtValue();
370APSInt IntegerAttr::getAPSInt()
const {
371 assert(!
getType().isSignlessInteger() &&
372 "Signless integers don't carry a sign for APSInt");
373 return APSInt(getValue(),
getType().isUnsignedInteger());
377 Type type, APInt value) {
378 if (IntegerType integerType = llvm::dyn_cast<IntegerType>(type)) {
379 if (integerType.getWidth() != value.getBitWidth())
380 return emitError() <<
"integer type bit width (" << integerType.getWidth()
381 <<
") doesn't match value bit width ("
382 << value.getBitWidth() <<
")";
385 if (llvm::isa<IndexType>(type)) {
386 if (value.getBitWidth() != IndexType::kInternalStorageBitWidth)
388 <<
"value bit width (" << value.getBitWidth()
389 <<
") doesn't match index type internal storage bit width ("
390 << IndexType::kInternalStorageBitWidth <<
")";
393 return emitError() <<
"expected integer or index type";
396BoolAttr IntegerAttr::getBoolAttrUnchecked(IntegerType type,
bool value) {
397 auto attr = Base::get(type.getContext(), type, APInt(1, value));
398 return llvm::cast<BoolAttr>(attr);
406 auto *storage =
reinterpret_cast<IntegerAttrStorage *
>(
impl);
407 return storage->value.getBoolValue();
411 IntegerAttr intAttr = llvm::dyn_cast<IntegerAttr>(attr);
412 return intAttr && intAttr.getType().isSignlessInteger(1);
420 StringAttr dialect, StringRef attrData,
423 return emitError() <<
"invalid dialect namespace '" << dialect <<
"'";
430 <<
"#" << dialect <<
"<\"" << attrData <<
"\"> : " << type
431 <<
" attribute created with unregistered dialect. If this is "
432 "intended, please call allowUnregisteredDialects() on the "
433 "MLIRContext, or use -allow-unregistered-dialect with "
434 "the MLIR opt tool used";
447 return llvm::alignTo<8>(origWidth);
457 assert(llvm::endianness::native == llvm::endianness::big);
458 assert(value.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes);
463 size_t numFilledWords = (value.getNumWords() - 1) * APInt::APINT_WORD_SIZE;
464 std::copy_n(
reinterpret_cast<const char *
>(value.getRawData()),
469 size_t lastWordPos = numFilledWords;
471 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
472 reinterpret_cast<const char *
>(value.getRawData()) + lastWordPos,
473 valueLE.begin(), APInt::APINT_BITS_PER_WORD, 1);
477 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
478 valueLE.begin(),
result + lastWordPos,
479 (numBytes - lastWordPos) * CHAR_BIT, 1);
486 assert(llvm::endianness::native == llvm::endianness::big);
487 assert(
result.getNumWords() * APInt::APINT_WORD_SIZE >= numBytes);
494 size_t numFilledWords = (
result.getNumWords() - 1) * APInt::APINT_WORD_SIZE;
496 inArray, numFilledWords,
497 const_cast<char *
>(
reinterpret_cast<const char *
>(
result.getRawData())));
502 size_t lastWordPos = numFilledWords;
504 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
505 inArray + lastWordPos, inArrayLE.begin(),
506 (numBytes - lastWordPos) * CHAR_BIT, 1);
510 DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
512 const_cast<char *
>(
reinterpret_cast<const char *
>(
result.getRawData())) +
514 APInt::APINT_BITS_PER_WORD, 1);
519 size_t bitWidth = value.getBitWidth();
522 assert((bitPos % CHAR_BIT) == 0 &&
"expected bitPos to be 8-bit aligned");
523 if (llvm::endianness::native == llvm::endianness::big) {
530 rawData + (bitPos / CHAR_BIT));
532 std::copy_n(
reinterpret_cast<const char *
>(value.getRawData()),
533 llvm::divideCeil(bitWidth, CHAR_BIT),
534 rawData + (bitPos / CHAR_BIT));
543 assert((bitPos % CHAR_BIT) == 0 &&
"expected bitPos to be 8-bit aligned");
544 APInt
result(bitWidth, 0);
545 if (llvm::endianness::native == llvm::endianness::big) {
552 llvm::divideCeil(bitWidth, CHAR_BIT),
result);
554 std::copy_n(rawData + (bitPos / CHAR_BIT),
555 llvm::divideCeil(bitWidth, CHAR_BIT),
557 reinterpret_cast<const char *
>(
result.getRawData())));
564template <
typename Values>
566 return (values.size() == 1) ||
567 (type.getNumElements() ==
static_cast<int64_t>(values.size()));
578DenseElementsAttr::AttributeElementIterator::AttributeElementIterator(
580 : llvm::indexed_accessor_iterator<AttributeElementIterator, const void *,
582 attr.getAsOpaquePointer(),
index) {}
586 Type eltTy = owner.getElementType();
589 if (llvm::isa<DenseStringElementsAttr>(owner)) {
591 return StringAttr::get(owner.isSplat() ? vals.front() : vals[
index], eltTy);
595 auto denseEltTy = llvm::cast<DenseElementType>(eltTy);
598 size_t bitSize = denseEltTy.getDenseElementBitSize();
599 size_t byteSize = llvm::divideCeil(bitSize, CHAR_BIT);
600 size_t offset = owner.isSplat() ? 0 :
index * byteSize;
601 return denseEltTy.convertToAttribute(rawData.slice(offset, byteSize));
608DenseElementsAttr::BoolElementIterator::BoolElementIterator(
621DenseElementsAttr::IntElementIterator::IntElementIterator(
637DenseElementsAttr::ComplexIntElementIterator::ComplexIntElementIterator(
643 auto complexType = llvm::cast<ComplexType>(attr.
getElementType());
663 return emitError() <<
"expected integer or floating point element type";
664 int64_t dataSize = rawData.size();
667 if (
size * elementSize != dataSize) {
668 return emitError() <<
"expected data size (" <<
size <<
" elements, "
670 <<
" bytes each) does not match: " << dataSize
679template <
size_t width,
680 IntegerType::SignednessSemantics signedness = IntegerType::Signless>
681struct DenseArrayAttrIntUtil {
682 static bool checkElementType(
Type eltType) {
683 auto type = llvm::dyn_cast<IntegerType>(eltType);
684 if (!type || type.getWidth() != width)
686 return type.getSignedness() == signedness;
690 return IntegerType::get(ctx, width, signedness);
693 template <
typename T>
694 static void printElement(raw_ostream &os, T value) {
698 template <
typename T>
699 static ParseResult parseElement(AsmParser &parser, T &value) {
704struct DenseArrayAttrUtil;
709struct DenseArrayAttrUtil<bool> :
public DenseArrayAttrIntUtil<1> {
710 static void printElement(raw_ostream &os,
bool value) {
711 os << (value ?
"true" :
"false");
718struct DenseArrayAttrUtil<int8_t> :
public DenseArrayAttrIntUtil<8> {
719 static void printElement(raw_ostream &os, int8_t value) {
720 os << static_cast<int>(value);
724struct DenseArrayAttrUtil<int16_t> :
public DenseArrayAttrIntUtil<16> {};
726struct DenseArrayAttrUtil<int32_t> :
public DenseArrayAttrIntUtil<32> {};
728struct DenseArrayAttrUtil<
int64_t> :
public DenseArrayAttrIntUtil<64> {};
732struct DenseArrayAttrUtil<float> {
733 static bool checkElementType(
Type eltType) {
return eltType.
isF32(); }
735 static void printElement(raw_ostream &os,
float value) { os << value; }
738 static ParseResult parseElement(AsmParser &parser,
float &value) {
749struct DenseArrayAttrUtil<double> {
750 static bool checkElementType(Type eltType) {
return eltType.
isF64(); }
751 static Type
getElementType(MLIRContext *ctx) {
return Float64Type::get(ctx); }
752 static void printElement(raw_ostream &os,
float value) { os << value; }
753 static ParseResult parseElement(AsmParser &parser,
double &value) {
766 llvm::interleaveComma(
asArrayRef(), os, [&](T value) {
767 DenseArrayAttrUtil<T>::printElement(os, value);
785 if (DenseArrayAttrUtil<T>::parseElement(parser, value))
787 data.push_back(value);
812 assert(llvm::isAddrAligned(llvm::Align(
alignof(T)), raw.data()));
813 assert((raw.size() %
sizeof(T)) == 0);
814 return ArrayRef<T>(
reinterpret_cast<const T *
>(raw.data()),
815 raw.size() /
sizeof(T));
822 Type elementType = DenseArrayAttrUtil<T>::getElementType(context);
823 auto rawArray =
ArrayRef<char>(
reinterpret_cast<const char *
>(content.data()),
824 content.size() *
sizeof(T));
825 return llvm::cast<DenseArrayAttrImpl<T>>(
826 Base::get(context, elementType, content.size(), rawArray));
831 if (
auto denseArray = llvm::dyn_cast<DenseArrayAttr>(attr))
832 return DenseArrayAttrUtil<T>::checkElementType(denseArray.getElementType());
855 return llvm::isa<DenseTypedElementsAttr, DenseStringElementsAttr>(attr);
861 Type eltType = type.getElementType();
864 if (!llvm::isa<DenseElementType>(eltType)) {
866 stringValues.reserve(values.size());
868 assert(llvm::isa<StringAttr>(attr) &&
869 "expected string value for non-DenseElementType element");
870 stringValues.push_back(llvm::cast<StringAttr>(attr).getValue());
872 return get(type, stringValues);
876 auto denseEltType = llvm::dyn_cast<DenseElementType>(eltType);
877 assert(denseEltType &&
878 "attempted to get DenseElementsAttr with unsupported element type");
881 LogicalResult
result = denseEltType.convertFromAttribute(attr, data);
885 return DenseTypedElementsAttr::getRaw(type, data);
891 assert(type.getElementType().isInteger(1));
892 return DenseTypedElementsAttr::getRaw(
893 type,
ArrayRef<char>(
reinterpret_cast<const char *
>(values.data()),
899 assert(!type.getElementType().isIntOrFloat());
900 return DenseStringElementsAttr::get(type, values);
908 assert(type.getElementType().isIntOrIndex());
911 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, values);
915 ComplexType
complex = llvm::cast<ComplexType>(type.getElementType());
916 assert(llvm::isa<IntegerType>(
complex.getElementType()));
919 ArrayRef<APInt> intVals(
reinterpret_cast<const APInt *
>(values.data()),
921 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, intVals);
929 assert(llvm::isa<FloatType>(type.getElementType()));
932 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, values);
937 ComplexType
complex = llvm::cast<ComplexType>(type.getElementType());
938 assert(llvm::isa<FloatType>(
complex.getElementType()));
943 return DenseTypedElementsAttr::getRaw(type, storageBitWidth, apVals);
951 return DenseTypedElementsAttr::getRaw(type, rawBuffer);
958 size_t rawBufferWidth = rawBuffer.size() * CHAR_BIT;
959 int64_t numElements = type.getNumElements();
963 return rawBufferWidth == storageWidth ||
964 rawBufferWidth == storageWidth * numElements;
974 auto dataSize =
static_cast<size_t>(dataEltSize * CHAR_BIT);
975 if (denseEltBitWidth != dataSize) {
976 LDBG() <<
"expected dense element bit width " << denseEltBitWidth
977 <<
" to match data size " << dataSize <<
" for type " << type;
983 bool valid = llvm::isa<FloatType>(type);
985 LDBG() <<
"expected float type when isInt is false, but found " << type;
991 auto intType = llvm::dyn_cast<IntegerType>(type);
993 LDBG() <<
"expected integer type when isInt is true, but found " << type;
998 if (intType.isSignless())
1001 bool valid = intType.isSigned() == isSigned;
1003 LDBG() <<
"expected signedness " << isSigned <<
" to match type " << type;
1011 bool isInt,
bool isSigned) {
1012 return DenseTypedElementsAttr::getRawComplex(type, data, dataEltSize, isInt,
1020 return DenseTypedElementsAttr::getRawIntOrFloat(type, data, dataEltSize,
1025 bool isSigned)
const {
1026 return ::isValidIntOrFloat(
getElementType(), dataEltSize, isInt, isSigned);
1029 bool isSigned)
const {
1030 return ::isValidIntOrFloat(
1032 dataEltSize / 2, isInt, isSigned);
1039 if (isa<DenseStringElementsAttr>(*
this))
1042 size_t storageSize = llvm::divideCeil(
1049 return llvm::isa<IntegerType>(llvm::cast<ComplexType>(type).
getElementType());
1066 const auto &elementSemantics = eltTy.getFloatSemantics();
1077 auto eltTy = llvm::dyn_cast<FloatType>(complexTy.getElementType());
1080 const auto &semantics = eltTy.getFloatSemantics();
1082 getType(), {semantics, {*
this, 0}},
1099 ShapedType curType =
getType();
1100 if (curType == newType)
1103 assert(newType.getElementType() == curType.getElementType() &&
1104 "expected the same element type");
1105 assert(newType.getNumElements() == curType.getNumElements() &&
1106 "expected the same number of elements");
1107 return DenseTypedElementsAttr::getRaw(newType,
getRawData());
1111 assert(
isSplat() &&
"expected a splat type");
1113 ShapedType curType =
getType();
1114 if (curType == newType)
1117 assert(newType.getElementType() == curType.getElementType() &&
1118 "expected the same element type");
1119 return DenseTypedElementsAttr::getRaw(newType,
getRawData());
1127 ShapedType curType =
getType();
1128 Type curElType = curType.getElementType();
1129 if (curElType == newElType)
1134 "expected element types with the same bitwidth");
1135 return DenseTypedElementsAttr::getRaw(curType.clone(newElType),
getRawData());
1141 return llvm::cast<DenseIntElementsAttr>(*this).
mapValues(newElementType,
1147 return llvm::cast<DenseFPElementsAttr>(*this).
mapValues(newElementType,
1156 return getType().getElementType();
1160 return getType().getNumElements();
1168template <
typename APRangeT>
1171 APRangeT &&values) {
1172 size_t numValues = llvm::size(values);
1173 data.resize(llvm::divideCeil(storageWidth * numValues, CHAR_BIT));
1175 for (
auto it = values.begin(), e = values.end(); it != e;
1176 ++it, offset += storageWidth) {
1177 assert((*it).getBitWidth() <= storageWidth);
1185DenseElementsAttr DenseTypedElementsAttr::getRaw(ShapedType type,
1186 size_t storageWidth,
1187 ArrayRef<APFloat> values) {
1188 SmallVector<char> data;
1189 auto unwrapFloat = [](
const APFloat &val) {
return val.bitcastToAPInt(); };
1191 return DenseTypedElementsAttr::getRaw(type, data);
1197DenseElementsAttr DenseTypedElementsAttr::getRaw(ShapedType type,
1198 size_t storageWidth,
1199 ArrayRef<APInt> values) {
1200 SmallVector<char> data;
1202 return DenseTypedElementsAttr::getRaw(type, data);
1205DenseElementsAttr DenseTypedElementsAttr::getRaw(ShapedType type,
1206 ArrayRef<char> data) {
1207 assert(type.hasStaticShape() &&
"type must have static shape");
1208 assert(isValidRawBuffer(type, data));
1209 return Base::get(type.getContext(), type, data);
1215DenseElementsAttr DenseTypedElementsAttr::getRawComplex(ShapedType type,
1216 ArrayRef<char> data,
1217 int64_t dataEltSize,
1221 llvm::cast<ComplexType>(type.getElementType()).getElementType(),
1222 dataEltSize / 2, isInt, isSigned) &&
1223 "Try re-running with -debug-only=builtinattributes");
1225 int64_t numElements = data.size() / dataEltSize;
1227 assert(numElements == 1 || numElements == type.getNumElements());
1228 return getRaw(type, data);
1234DenseElementsAttr DenseTypedElementsAttr::getRawIntOrFloat(ShapedType type,
1235 ArrayRef<char> data,
1236 int64_t dataEltSize,
1241 "Try re-running with -debug-only=builtinattributes");
1243 int64_t numElements = data.size() / dataEltSize;
1244 assert(numElements == 1 || numElements == type.getNumElements());
1246 return getRaw(type, data);
1249void DenseTypedElementsAttr::convertEndianOfCharForBEmachine(
1250 const char *inRawData,
char *outRawData,
size_t elementBitWidth,
1251 size_t numElements) {
1252 using llvm::support::ulittle16_t;
1253 using llvm::support::ulittle32_t;
1254 using llvm::support::ulittle64_t;
1256 assert(llvm::endianness::native == llvm::endianness::big);
1260 switch (elementBitWidth) {
1262 const ulittle16_t *inRawDataPos =
1263 reinterpret_cast<const ulittle16_t *
>(inRawData);
1264 uint16_t *outDataPos =
reinterpret_cast<uint16_t *
>(outRawData);
1265 std::copy_n(inRawDataPos, numElements, outDataPos);
1269 const ulittle32_t *inRawDataPos =
1270 reinterpret_cast<const ulittle32_t *
>(inRawData);
1271 uint32_t *outDataPos =
reinterpret_cast<uint32_t *
>(outRawData);
1272 std::copy_n(inRawDataPos, numElements, outDataPos);
1276 const ulittle64_t *inRawDataPos =
1277 reinterpret_cast<const ulittle64_t *
>(inRawData);
1278 uint64_t *outDataPos =
reinterpret_cast<uint64_t *
>(outRawData);
1279 std::copy_n(inRawDataPos, numElements, outDataPos);
1283 size_t nBytes = elementBitWidth / CHAR_BIT;
1284 for (
size_t i = 0; i < nBytes; i++)
1285 std::copy_n(inRawData + (nBytes - 1 - i), 1, outRawData + i);
1291void DenseTypedElementsAttr::convertEndianOfArrayRefForBEmachine(
1292 ArrayRef<char> inRawData, MutableArrayRef<char> outRawData,
1294 size_t numElements = type.getNumElements();
1295 Type elementType = type.getElementType();
1296 if (ComplexType complexTy = llvm::dyn_cast<ComplexType>(elementType)) {
1297 elementType = complexTy.getElementType();
1298 numElements = numElements * 2;
1301 assert(numElements * elementBitWidth == inRawData.size() * CHAR_BIT &&
1302 inRawData.size() <= outRawData.size());
1303 if (elementBitWidth <= CHAR_BIT)
1304 std::memcpy(outRawData.begin(), inRawData.begin(), inRawData.size());
1306 convertEndianOfCharForBEmachine(inRawData.begin(), outRawData.begin(),
1307 elementBitWidth, numElements);
1314template <
typename Fn,
typename Attr>
1316 Type newElementType,
1321 ShapedType newArrayType = inType.cloneWith(inType.getShape(), newElementType);
1323 size_t numRawElements = attr.isSplat() ? 1 : newArrayType.getNumElements();
1324 data.resize(llvm::divideCeil(storageBitWidth * numRawElements, CHAR_BIT));
1327 auto processElt = [&](
decltype(*attr.begin()) value,
size_t index) {
1328 auto newInt = mapping(value);
1329 assert(newInt.getBitWidth() == bitWidth);
1334 if (attr.isSplat()) {
1335 processElt(*attr.begin(), 0);
1336 return newArrayType;
1340 uint64_t elementIdx = 0;
1341 for (
auto value : attr)
1342 processElt(value, elementIdx++);
1343 return newArrayType;
1352 return getRaw(newArrayType, elementData);
1357 if (
auto denseAttr = llvm::dyn_cast<DenseElementsAttr>(attr))
1358 return llvm::isa<FloatType>(denseAttr.getType().getElementType());
1371 return getRaw(newArrayType, elementData);
1376 if (
auto denseAttr = llvm::dyn_cast<DenseElementsAttr>(attr))
1377 return denseAttr.getType().getElementType().isIntOrIndex();
1385DenseResourceElementsAttr
1386DenseResourceElementsAttr::get(ShapedType type,
1388 return Base::get(type.getContext(), type, handle);
1391DenseResourceElementsAttr DenseResourceElementsAttr::get(ShapedType type,
1398 return get(type, manager.insert(blobName, std::move(blob)));
1401ArrayRef<char> DenseResourceElementsAttr::getData() {
1402 if (AsmResourceBlob *blob = this->getRawHandle().getBlob())
1403 return blob->getDataAs<
char>();
1414template <
typename T>
1415struct DenseResourceAttrUtil;
1416template <
size_t w
idth,
bool isSigned>
1417struct DenseResourceElementsAttrIntUtil {
1418 static bool checkElementType(Type eltType) {
1419 IntegerType type = llvm::dyn_cast<IntegerType>(eltType);
1420 if (!type || type.getWidth() != width)
1422 return isSigned ? !type.isUnsigned() : !type.isSigned();
1426struct DenseResourceAttrUtil<bool> {
1427 static bool checkElementType(Type eltType) {
1432struct DenseResourceAttrUtil<int8_t>
1433 :
public DenseResourceElementsAttrIntUtil<8, true> {};
1435struct DenseResourceAttrUtil<uint8_t>
1436 :
public DenseResourceElementsAttrIntUtil<8, false> {};
1438struct DenseResourceAttrUtil<int16_t>
1439 :
public DenseResourceElementsAttrIntUtil<16, true> {};
1441struct DenseResourceAttrUtil<uint16_t>
1442 :
public DenseResourceElementsAttrIntUtil<16, false> {};
1444struct DenseResourceAttrUtil<int32_t>
1445 :
public DenseResourceElementsAttrIntUtil<32, true> {};
1447struct DenseResourceAttrUtil<uint32_t>
1448 :
public DenseResourceElementsAttrIntUtil<32, false> {};
1450struct DenseResourceAttrUtil<int64_t>
1451 :
public DenseResourceElementsAttrIntUtil<64, true> {};
1453struct DenseResourceAttrUtil<uint64_t>
1454 :
public DenseResourceElementsAttrIntUtil<64, false> {};
1456struct DenseResourceAttrUtil<float> {
1457 static bool checkElementType(Type eltType) {
return eltType.
isF32(); }
1460struct DenseResourceAttrUtil<double> {
1461 static bool checkElementType(Type eltType) {
return eltType.
isF64(); }
1465template <
typename T>
1466DenseResourceElementsAttrBase<T>
1471 "alignment mismatch between expected alignment and blob alignment");
1472 assert(((blob.
getData().size() %
sizeof(T)) == 0) &&
1473 "size mismatch between expected element width and blob size");
1474 assert(DenseResourceAttrUtil<T>::checkElementType(type.getElementType()) &&
1475 "invalid shape element type for provided type `T`");
1476 return llvm::cast<DenseResourceElementsAttrBase<T>>(
1477 DenseResourceElementsAttr::get(type, blobName, std::move(blob)));
1480template <
typename T>
1481std::optional<ArrayRef<T>>
1484 return blob->template getDataAs<T>();
1485 return std::nullopt;
1488template <
typename T>
1490 auto resourceAttr = llvm::dyn_cast<DenseResourceElementsAttr>(attr);
1491 return resourceAttr && DenseResourceAttrUtil<T>::checkElementType(
1492 resourceAttr.getElementType());
1517APFloat SparseElementsAttr::getZeroAPFloat()
const {
1519 return APFloat(eltType.getFloatSemantics());
1523APInt SparseElementsAttr::getZeroAPInt()
const {
1525 return APInt::getZero(eltType.getWidth());
1529Attribute SparseElementsAttr::getZeroAttr()
const {
1533 if (llvm::isa<FloatType>(eltType))
1534 return FloatAttr::get(eltType, 0);
1537 if (
auto complexTy = llvm::dyn_cast<ComplexType>(eltType)) {
1538 auto eltType = complexTy.getElementType();
1540 if (llvm::isa<FloatType>(eltType))
1541 zero = FloatAttr::get(eltType, 0);
1543 zero = IntegerAttr::get(eltType, 0);
1544 return ArrayAttr::get(complexTy.getContext(),
1545 ArrayRef<Attribute>{zero, zero});
1549 if (llvm::isa<DenseStringElementsAttr>(getValues()))
1550 return StringAttr::get(
"", eltType);
1553 if (llvm::isa<MXI8Type>(eltType))
1554 return IntegerAttr::get(IntegerType::get(eltType.
getContext(), 8), 0);
1557 return IntegerAttr::get(eltType, 0);
1562SmallVector<ptrdiff_t> SparseElementsAttr::getFlattenedSparseIndices()
const {
1563 SmallVector<ptrdiff_t> flatSparseIndices;
1568 auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1569 if (sparseIndices.isSplat()) {
1571 *sparseIndexValues.begin());
1572 flatSparseIndices.push_back(getFlattenedIndex(
indices));
1573 return flatSparseIndices;
1577 auto numSparseIndices = sparseIndices.getType().getDimSize(0);
1578 size_t rank =
getType().getRank();
1579 for (
size_t i = 0, e = numSparseIndices; i != e; ++i)
1580 flatSparseIndices.push_back(getFlattenedIndex(
1581 {&*std::next(sparseIndexValues.begin(), i * rank), rank}));
1582 return flatSparseIndices;
1587 ShapedType type, DenseIntElementsAttr sparseIndices,
1588 DenseElementsAttr values) {
1589 ShapedType valuesType = values.
getType();
1590 if (valuesType.getRank() != 1)
1591 return emitError() <<
"expected 1-d tensor for sparse element values";
1594 ShapedType indicesType = sparseIndices.getType();
1595 auto emitShapeError = [&]() {
1596 return emitError() <<
"expected shape ([" << type.getShape()
1597 <<
"]); inferred shape of indices literal (["
1598 << indicesType.getShape()
1599 <<
"]); inferred shape of values literal (["
1600 << valuesType.getShape() <<
"])";
1603 size_t rank = type.getRank(), indicesRank = indicesType.getRank();
1604 if (indicesRank == 2) {
1605 if (indicesType.getDimSize(1) !=
static_cast<int64_t
>(rank))
1606 return emitShapeError();
1607 }
else if (indicesRank != 1 || rank != 1) {
1608 return emitShapeError();
1611 int64_t numSparseIndices = indicesType.getDimSize(0);
1612 if (numSparseIndices != valuesType.getDimSize(0))
1613 return emitShapeError();
1616 auto emitIndexError = [&](
unsigned indexNum, ArrayRef<uint64_t> index) {
1618 <<
"sparse index #" << indexNum
1619 <<
" is not contained within the value shape, with index=[" << index
1620 <<
"], and type=" << type;
1624 auto sparseIndexValues = sparseIndices.getValues<uint64_t>();
1625 if (sparseIndices.isSplat()) {
1626 SmallVector<uint64_t>
indices(rank, *sparseIndexValues.begin());
1627 if (!ElementsAttr::isValidIndex(type,
indices))
1628 return emitIndexError(0,
indices);
1633 for (
size_t i = 0, e = numSparseIndices; i != e; ++i) {
1634 ArrayRef<uint64_t> index(&*std::next(sparseIndexValues.begin(), i * rank),
1636 if (!ElementsAttr::isValidIndex(type, index))
1637 return emitIndexError(i, index);
1652 return getImpl()->referencedAttr;
1663 unsigned nSymbols = 0;
1667 if (ShapedType::isStatic(offset)) {
1677 for (
const auto &en : llvm::enumerate(strides)) {
1678 auto dim = en.index();
1679 auto stride = en.value();
1683 if (ShapedType::isStatic(stride))
1688 expr = expr + d * mult;
static bool isValidIntOrFloat(Type type, int64_t dataEltSize, bool isInt, bool isSigned)
Check the information for a C++ data type, check if this type is valid for the current attribute.
static void copyAPIntToArrayForBEmachine(APInt value, size_t numBytes, char *result)
Copy actual numBytes data from value (APInt) to char array(result) for BE format.
static ShapedType mappingHelper(Fn mapping, Attr &attr, ShapedType inType, Type newElementType, llvm::SmallVectorImpl< char > &data)
static bool hasSameNumElementsOrSplat(ShapedType type, const Values &values)
Returns true if 'values' corresponds to a splat, i.e.
static void writeAPIntsToBuffer(size_t storageWidth, SmallVectorImpl< char > &data, APRangeT &&values)
Utility method to write a range of APInt values to a buffer.
static bool dictionaryAttrSort(ArrayRef< NamedAttribute > value, SmallVectorImpl< NamedAttribute > &storage)
Helper function that does either an in place sort or sorts from source array into destination.
static std::optional< NamedAttribute > findDuplicateElement(ArrayRef< NamedAttribute > value)
Returns an entry with a duplicate name from the given sorted array of named attributes.
static size_t getDenseElementStorageWidth(size_t origWidth)
Get the bitwidth of a dense element type within the buffer.
static void copyArrayToAPIntForBEmachine(const char *inArray, size_t numBytes, APInt &result)
Copy numBytes data from inArray(char array) to result(APINT) for BE format.
static bool isComplexOfIntType(Type type)
Return if the given complex type has an integer element type.
static int64_t getNumElements(Type t)
Compute the total number of elements in the given type, also taking into account nested types.
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static const llvm::fltSemantics * getFloatSemantics(TruncfSrcElemTypes etype)
Float semantics the element type attributes of xevm.truncf and xevm.extf stand for.
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
MLIRContext * getContext() const
virtual ParseResult parseLSquare()=0
Parse a [ token.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseOptionalRSquare()=0
Parse a ] token if present.
virtual ParseResult parseFloat(double &result)=0
Parse a floating point value from the stream.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual raw_ostream & getStream() const
Return the raw output stream used by this printer.
This class represents a processed binary blob of data.
size_t getDataAlignment() const
Return the alignment of the underlying data.
ArrayRef< char > getData() const
Return the raw underlying data of this blob.
Attributes are known-constant values of operations.
void print(raw_ostream &os, bool elideType=false) const
Print the attribute.
MLIRContext * getContext() const
Return the context this attribute belongs to.
static Attribute getFromOpaquePointer(const void *ptr)
Construct an attribute from the opaque pointer representation.
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
static bool classof(Attribute attr)
Methods for support type inquiry through isa, cast, and dyn_cast.
constexpr Attribute()=default
bool getValue() const
Return the boolean value of this attribute.
Attribute operator*() const
Accesses the Attribute value at this iterator position.
A utility iterator that allows walking over the internal bool values.
bool operator*() const
Accesses the bool value at this iterator position.
Iterator for walking over complex APFloat values.
A utility iterator that allows walking over the internal raw complex APInt values.
mlir::Complex< APInt > operator*() const
Accesses the raw mlir::Complex<APInt> value at this iterator position.
Iterator for walking over APFloat values.
A utility iterator that allows walking over the internal raw APInt values.
APInt operator*() const
Accesses the raw APInt value at this iterator position.
An attribute that represents a reference to a dense vector or tensor object.
ArrayRef< StringRef > getRawStringData() const
Return the raw StringRef data held by this attribute.
IntElementIterator raw_int_begin() const
Iterators to various elements that require out-of-line definition.
static DenseElementsAttr getRawIntOrFloat(ShapedType type, ArrayRef< char > data, int64_t dataEltSize, bool isInt, bool isSigned)
Overload of the raw 'get' method that asserts that the given type is of integer or floating-point typ...
static DenseElementsAttr getRawComplex(ShapedType type, ArrayRef< char > data, int64_t dataEltSize, bool isInt, bool isSigned)
Overload of the raw 'get' method that asserts that the given type is of complex type.
static bool classof(Attribute attr)
Method for support type inquiry through isa, cast and dyn_cast.
bool isValidComplex(int64_t dataEltSize, bool isInt, bool isSigned) const
DenseElementsAttr resizeSplat(ShapedType newType)
Return a new DenseElementsAttr that has the same data as the current attribute, but with a different ...
detail::ElementsAttrRange< IteratorT > iterator_range_impl
The iterator range over the given iterator type T.
int64_t getNumElements() const
Returns the number of elements held by this attribute.
static DenseElementsAttr getFromRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Construct a dense elements attribute from a raw buffer representing the data for this attribute.
static bool isValidRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Returns true if the given buffer is a valid raw buffer for the given type.
int64_t size() const
Returns the number of elements held by this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
ArrayRef< char > getRawData() const
Return the raw storage data held by this attribute.
constexpr Attribute()=default
DenseElementsAttr mapValues(Type newElementType, function_ref< APInt(const APInt &)> mapping) const
Generates a new DenseElementsAttr by mapping each int value to a new underlying APInt.
Type getElementType() const
Return the element type of this DenseElementsAttr.
FailureOr< iterator_range_impl< ComplexFloatElementIterator > > tryGetComplexFloatValues() const
IntElementIterator raw_int_end() const
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
FailureOr< iterator_range_impl< FloatElementIterator > > tryGetFloatValues() const
DenseElementsAttr bitcast(Type newElType)
Return a new DenseElementsAttr that has the same data as the current attribute, but has bitcast eleme...
bool isValidIntOrFloat(int64_t dataEltSize, bool isInt, bool isSigned) const
DenseElementsAttr reshape(ShapedType newType)
Return a new DenseElementsAttr that has the same data as the current attribute, but has been reshaped...
FailureOr< iterator_range_impl< ComplexIntElementIterator > > tryGetComplexIntValues() const
static bool classof(Attribute attr)
Method for supporting type inquiry through isa, cast and dyn_cast.
DenseElementsAttr mapValues(Type newElementType, function_ref< APInt(const APFloat &)> mapping) const
Generates a new DenseElementsAttr by mapping each value attribute, and constructing the DenseElements...
static bool classof(Attribute attr)
Method for supporting type inquiry through isa, cast and dyn_cast.
DenseElementsAttr mapValues(Type newElementType, function_ref< APInt(const APInt &)> mapping) const
Generates a new DenseElementsAttr by mapping each value attribute, and constructing the DenseElements...
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
An attribute that associates a referenced attribute with a unique identifier.
static DistinctAttr create(Attribute referencedAttr)
Creates a distinct attribute that associates a referenced attribute with a unique identifier.
Attribute getReferencedAttr() const
Returns the referenced attribute.
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
NamedAttribute represents a combination of a name and an Attribute value.
Operation is the basic unit of execution within MLIR.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Base class for DenseArrayAttr that is instantiated and specialized for each supported element type be...
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< T > content)
Builder from ArrayRef<T>.
static bool classof(Attribute attr)
Support for isa<>/cast<>.
ArrayRef< T > asArrayRef() const
void print(AsmPrinter &printer) const
Print the short form [42, 100, -1] without any type prefix.
static Attribute parse(AsmParser &parser, Type type)
Parse the short form [42, 100, -1] without any type prefix.
static Attribute parseWithoutBraces(AsmParser &parser, Type type)
Parse the short form 42, 100, -1 without any type prefix or braces.
void printWithoutBraces(raw_ostream &os) const
Print the short form 42, 100, -1 without any braces or type prefix.
Impl iterator for indexed DenseElementsAttr iterators that records a data pointer and data index that...
ptrdiff_t getDataIndex() const
const char * getData() const
Base class for DenseResourceElementsAttr that is instantiated and specialized for each supported elem...
static bool classof(Attribute attr)
Support for isa<>/cast<>.
static DenseResourceElementsAttrBase< T > get(ShapedType type, StringRef blobName, AsmResourceBlob blob)
A builder that inserts a new resource using the provided blob.
std::optional< ArrayRef< T > > tryGetAsArrayRef() const
Return the data of this attribute as an ArrayRef<T> if it is present, returns std::nullopt otherwise.
static ConcreteT get(MLIRContext *ctx, Args &&...args)
Get or create a new ConcreteT instance within the ctx.
ImplType * getImpl() const
llvm::APInt readBits(const char *rawData, size_t bitPos, size_t bitWidth)
Read bitWidth bits from byte-aligned position in rawData and return as an APInt.
size_t getDenseElementBitWidth(Type eltType)
Return the bit width which DenseElementsAttr should use for this type.
void writeBits(char *rawData, size_t bitPos, llvm::APInt value)
Write value to byte-aligned position bitPos in rawData.
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
DialectResourceBlobHandle< BuiltinDialect > DenseResourceElementsHandle
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
std::conditional_t< std::is_floating_point_v< T >, std::complex< T >, NonFloatComplex< T > > Complex
AffineMap makeStridedLinearLayoutMap(ArrayRef< int64_t > strides, int64_t offset, MLIRContext *context)
Given a list of strides (in which ShapedType::kDynamic represents a dynamic value),...
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
llvm::function_ref< Fn > function_ref
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)
static ManagerInterface & getManagerInterface(MLIRContext *ctx)
An attribute representing a reference to a dense vector or tensor object.
An attribute representing a reference to a dense vector or tensor object containing strings.
An attribute representing a reference to a dense vector or tensor object.