10#include "TypeDetail.h"
21#include "llvm/ADT/APFixedPoint.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/Sequence.h"
25#include "llvm/ADT/TypeSwitch.h"
26#include "llvm/Support/CheckedArithmetic.h"
36#define GET_TYPEDEF_CLASSES
37#include "mlir/IR/BuiltinTypes.cpp.inc"
40#include "mlir/IR/BuiltinTypeConstraints.cpp.inc"
51 return emitError() <<
"invalid element type for complex";
55size_t ComplexType::getDenseElementBitSize()
const {
57 return llvm::alignTo<8>(elemTy.getDenseElementBitSize()) * 2;
62 size_t singleElementBytes =
63 llvm::alignTo<8>(elemTy.getDenseElementBitSize()) / 8;
65 elemTy.convertToAttribute(rawData.take_front(singleElementBytes));
67 elemTy.convertToAttribute(rawData.take_back(singleElementBytes));
72ComplexType::convertFromAttribute(
Attribute attr,
74 auto arrayAttr = dyn_cast<ArrayAttr>(attr);
75 if (!arrayAttr || arrayAttr.size() != 2)
79 if (
failed(elemTy.convertFromAttribute(arrayAttr[0], realData)))
81 if (
failed(elemTy.convertFromAttribute(arrayAttr[1], imagData)))
95 SignednessSemantics signedness) {
96 if (width > IntegerType::kMaxWidth) {
97 return emitError() <<
"integer bitwidth is limited to "
98 << IntegerType::kMaxWidth <<
" bits";
103unsigned IntegerType::getWidth()
const {
return getImpl()->width; }
105IntegerType::SignednessSemantics IntegerType::getSignedness()
const {
106 return getImpl()->signedness;
109IntegerType IntegerType::scaleElementBitwidth(
unsigned scale) {
111 return IntegerType();
112 return IntegerType::get(
getContext(), scale * getWidth(), getSignedness());
115size_t IntegerType::getDenseElementBitSize()
const {
121 APInt value = detail::readBits(rawData.data(), 0, getWidth());
122 return IntegerAttr::get(*
this, value);
126 size_t byteSize = llvm::divideCeil(apInt.getBitWidth(), CHAR_BIT);
127 size_t bitPos =
result.size() * CHAR_BIT;
133IntegerType::convertFromAttribute(
Attribute attr,
135 auto intAttr = dyn_cast<IntegerAttr>(attr);
136 if (!intAttr || intAttr.getType() != *
this)
146llvm::FixedPointSemantics MXI8Type::getFixedPointSemantics() {
152size_t MXI8Type::getDenseElementBitSize()
const {
return 8; }
155 return IntegerType::get(
getContext(), 8).convertToAttribute(rawData);
159MXI8Type::convertFromAttribute(
Attribute attr,
161 auto intAttr = dyn_cast<IntegerAttr>(attr);
162 if (!intAttr || !intAttr.getType().isSignlessInteger(8))
164 return cast<IntegerType>(intAttr.getType())
165 .convertFromAttribute(attr,
result);
172size_t IndexType::getDenseElementBitSize()
const {
173 return kInternalStorageBitWidth;
178 detail::readBits(rawData.data(), 0, kInternalStorageBitWidth);
179 return IntegerAttr::get(*
this, value);
183IndexType::convertFromAttribute(
Attribute attr,
185 auto intAttr = dyn_cast<IntegerAttr>(attr);
186 if (!intAttr || intAttr.getType() != *
this)
197#define FLOAT_TYPE_SEMANTICS(TYPE, SEM) \
198 const llvm::fltSemantics &TYPE::getFloatSemantics() const { \
199 return APFloat::SEM(); \
220#undef FLOAT_TYPE_SEMANTICS
222FloatType Float16Type::scaleElementBitwidth(
unsigned scale)
const {
230FloatType BFloat16Type::scaleElementBitwidth(
unsigned scale)
const {
238FloatType Float32Type::scaleElementBitwidth(
unsigned scale)
const {
248unsigned FunctionType::getNumInputs()
const {
return getImpl()->numInputs; }
251 return getImpl()->getInputs();
254unsigned FunctionType::getNumResults()
const {
return getImpl()->numResults; }
257 return getImpl()->getResults();
266FunctionType FunctionType::getWithArgsAndResults(
273 insertTypesInto(getResults(), resultIndices, resultTypes, resultStorage);
274 return clone(newArgTypes, newResultTypes);
279FunctionType::getWithoutArgsAndResults(
const BitVector &argIndices,
280 const BitVector &resultIndices) {
285 return clone(newArgTypes, newResultTypes);
292unsigned GraphType::getNumInputs()
const {
return getImpl()->numInputs; }
294ArrayRef<Type> GraphType::getInputs()
const {
return getImpl()->getInputs(); }
296unsigned GraphType::getNumResults()
const {
return getImpl()->numResults; }
298ArrayRef<Type> GraphType::getResults()
const {
return getImpl()->getResults(); }
314 insertTypesInto(getResults(), resultIndices, resultTypes, resultStorage);
315 return clone(newArgTypes, newResultTypes);
319GraphType GraphType::getWithoutArgsAndResults(
const BitVector &argIndices,
320 const BitVector &resultIndices) {
325 return clone(newArgTypes, newResultTypes);
333 StringAttr dialect, StringRef typeData) {
335 return emitError() <<
"invalid dialect namespace '" << dialect <<
"'";
342 <<
"`!" << dialect <<
"<\"" << typeData <<
"\">"
343 <<
"` type created with unregistered dialect. If this is "
344 "intended, please call allowUnregisteredDialects() on the "
345 "MLIRContext, or use -allow-unregistered-dialect with "
346 "the MLIR opt tool used";
356bool VectorType::isValidElementType(
Type t) {
357 return isValidVectorTypeElementType(t);
363 if (!isValidElementType(elementType))
365 <<
"vector elements must be int/index/float type but got "
368 if (any_of(shape, [](int64_t i) {
return i <= 0; }))
370 <<
"vector types must have positive constant sizes but got "
373 if (scalableDims.size() != shape.size())
374 return emitError() <<
"number of dims must match, got "
375 << scalableDims.size() <<
" and " << shape.size();
380VectorType VectorType::scaleElementBitwidth(
unsigned scale) {
384 if (
auto scaledEt = et.scaleElementBitwidth(scale))
385 return VectorType::get(
getShape(), scaledEt, getScalableDims());
387 if (
auto scaledEt = et.scaleElementBitwidth(scale))
388 return VectorType::get(
getShape(), scaledEt, getScalableDims());
393 Type elementType)
const {
394 return VectorType::get(shape.value_or(
getShape()), elementType,
404 .Case<RankedTensorType, UnrankedTensorType>(
405 [](
auto type) {
return type.getElementType(); });
409 return !llvm::isa<UnrankedTensorType>(*
this);
413 return llvm::cast<RankedTensorType>(*this).getShape();
417 Type elementType)
const {
418 if (llvm::dyn_cast<UnrankedTensorType>(*
this)) {
420 return RankedTensorType::get(*
shape, elementType);
421 return UnrankedTensorType::get(elementType);
424 auto rankedTy = llvm::cast<RankedTensorType>(*
this);
426 return RankedTensorType::get(rankedTy.getShape(), elementType,
427 rankedTy.getEncoding());
428 return RankedTensorType::get(
shape.value_or(rankedTy.getShape()), elementType,
429 rankedTy.getEncoding());
433 Type elementType)
const {
434 return ::llvm::cast<RankedTensorType>(
cloneWith(
shape, elementType));
446 return emitError() <<
"invalid tensor element type: " << elementType;
455 return llvm::isa<ComplexType, FloatType, IntegerType, OpaqueType, VectorType,
456 IndexType, MXI8Type>(type) ||
457 !llvm::isa<BuiltinDialect>(type.
getDialect());
469 if (s < 0 && ShapedType::isStatic(s))
470 return emitError() <<
"invalid tensor dimension size";
471 if (
auto v = llvm::dyn_cast_or_null<VerifiableTensorEncoding>(encoding))
494 [](
auto type) {
return type.getElementType(); });
498 return !llvm::isa<UnrankedMemRefType>(*
this);
502 return llvm::cast<MemRefType>(*this).getShape();
506 Type elementType)
const {
507 if (llvm::dyn_cast<UnrankedMemRefType>(*
this)) {
522FailureOr<PtrLikeTypeInterface>
524 std::optional<Type> elementType)
const {
526 if (llvm::dyn_cast<UnrankedMemRefType>(*
this))
527 return cast<PtrLikeTypeInterface>(
528 UnrankedMemRefType::get(eTy, memorySpace));
533 return cast<PtrLikeTypeInterface>(
static_cast<MemRefType
>(builder));
537 Type elementType)
const {
546 if (
auto rankedMemRefTy = llvm::dyn_cast<MemRefType>(*
this))
547 return rankedMemRefTy.getMemorySpace();
548 return llvm::cast<UnrankedMemRefType>(*this).getMemorySpace();
552 if (
auto rankedMemRefTy = llvm::dyn_cast<MemRefType>(*
this))
553 return rankedMemRefTy.getMemorySpaceAsInt();
554 return llvm::cast<UnrankedMemRefType>(*this).getMemorySpaceAsInt();
561std::optional<llvm::SmallDenseSet<unsigned>>
565 size_t originalRank = originalShape.size(), reducedRank = reducedShape.size();
566 llvm::SmallDenseSet<unsigned> unusedDims;
567 unsigned reducedIdx = 0;
568 for (
unsigned originalIdx = 0; originalIdx < originalRank; ++originalIdx) {
570 int64_t origSize = originalShape[originalIdx];
572 if (matchDynamic && reducedIdx < reducedRank && origSize != 1 &&
573 (ShapedType::isDynamic(reducedShape[reducedIdx]) ||
574 ShapedType::isDynamic(origSize))) {
578 if (reducedIdx < reducedRank && origSize == reducedShape[reducedIdx]) {
583 unusedDims.insert(originalIdx);
590 if (reducedIdx != reducedRank)
597 ShapedType candidateReducedType) {
598 if (originalType == candidateReducedType)
601 ShapedType originalShapedType = llvm::cast<ShapedType>(originalType);
602 ShapedType candidateReducedShapedType =
603 llvm::cast<ShapedType>(candidateReducedType);
608 candidateReducedShapedType.getShape();
609 unsigned originalRank = originalShape.size(),
610 candidateReducedRank = candidateReducedShape.size();
611 if (candidateReducedRank > originalRank)
614 auto optionalUnusedDimsMask =
618 if (!optionalUnusedDimsMask)
621 if (originalShapedType.getElementType() !=
622 candidateReducedShapedType.getElementType())
630 if (memorySpace == 0)
633 return IntegerAttr::get(IntegerType::get(ctx, 64), memorySpace);
637 IntegerAttr intMemorySpace = llvm::dyn_cast_or_null<IntegerAttr>(memorySpace);
638 if (intMemorySpace && intMemorySpace.getValue() == 0)
648 assert(llvm::isa<IntegerAttr>(memorySpace) &&
649 "Using `getMemorySpaceInteger` with non-Integer attribute");
651 return static_cast<unsigned>(llvm::cast<IntegerAttr>(memorySpace).getInt());
654unsigned MemRefType::getMemorySpaceAsInt()
const {
659 MemRefLayoutAttrInterface layout,
673MemRefType MemRefType::getChecked(
675 Type elementType, MemRefLayoutAttrInterface layout,
Attribute memorySpace) {
686 elementType, layout, memorySpace);
698 auto layout = AffineMapAttr::get(map);
718 auto layout = AffineMapAttr::get(map);
724 elementType, layout, memorySpace);
728 AffineMap map,
unsigned memorySpaceInd) {
736 auto layout = AffineMapAttr::get(map);
749 unsigned memorySpaceInd) {
757 auto layout = AffineMapAttr::get(map);
764 elementType, layout, memorySpace);
769 MemRefLayoutAttrInterface layout,
772 return emitError() <<
"invalid memref element type";
775 for (int64_t s :
shape)
776 if (s < 0 && ShapedType::isStatic(s))
777 return emitError() <<
"invalid memref size";
779 assert(layout &&
"missing layout specification");
786bool MemRefType::areTrailingDimsContiguous(int64_t n) {
787 assert(n <= getRank() &&
788 "number of dimensions to check must not exceed rank");
789 return n <= getNumContiguousTrailingDims();
792int64_t MemRefType::getNumContiguousTrailingDims() {
793 const int64_t n = getRank();
796 if (getLayout().isIdentity())
814 int64_t dimProduct = 1;
815 for (int64_t i = n - 1; i >= 0; --i) {
818 if (strides[i] != dimProduct)
820 if (
shape[i] == ShapedType::kDynamic)
822 dimProduct *=
shape[i];
828MemRefType MemRefType::canonicalizeStridedLayout() {
829 AffineMap m = getLayout().getAffineMap();
841 if (
auto cst = llvm::dyn_cast<AffineConstantExpr>(m.
getResult(0)))
842 if (cst.getValue() == 0)
857 auto simplifiedLayoutExpr =
859 if (expr != simplifiedLayoutExpr)
862 simplifiedLayoutExpr)));
867 int64_t &offset)
const {
868 return getLayout().getStridesAndOffset(
getShape(), strides, offset);
871std::pair<SmallVector<int64_t>, int64_t>
872MemRefType::getStridesAndOffset()
const {
877 assert(succeeded(status) &&
"Invalid use of check-free getStridesAndOffset");
878 return {strides, offset};
881bool MemRefType::isStrided() {
885 return succeeded(res);
888bool MemRefType::isLastDimUnitStride() {
892 return succeeded(successStrides) && (strides.empty() || strides.back() == 1);
899unsigned UnrankedMemRefType::getMemorySpaceAsInt()
const {
907 return emitError() <<
"invalid memref element type";
917ArrayRef<Type> TupleType::getTypes()
const {
return getImpl()->getTypes(); }
924 for (
Type type : getTypes()) {
925 if (
auto nestedTuple = llvm::dyn_cast<TupleType>(type))
926 nestedTuple.getFlattenedTypes(types);
928 types.push_back(type);
933size_t TupleType::size()
const {
return getImpl()->size(); }
946 assert(!exprs.empty() &&
"expected exprs");
948 assert(!maps.empty() &&
"Expected one non-empty map");
949 unsigned numDims = maps[0].getNumDims(), nSymbols = maps[0].getNumSymbols();
952 bool dynamicPoisonBit =
false;
954 for (
auto en : llvm::zip(llvm::reverse(exprs), llvm::reverse(sizes))) {
955 int64_t size = std::get<1>(en);
960 expr = expr ? expr + dimExpr * stride : dimExpr * stride;
962 auto result = llvm::checkedMul(runningSize, size);
965 dynamicPoisonBit =
true;
970 dynamicPoisonBit =
true;
979 exprs.reserve(sizes.size());
980 for (
auto dim : llvm::seq<unsigned>(0, sizes.size()))
static LogicalResult getStridesAndOffset(AffineMap m, ArrayRef< int64_t > shape, SmallVectorImpl< AffineExpr > &strides, AffineExpr &offset)
A stride specification is a list of integer values that are either static or dynamic (encoded with Sh...
static void writeAPIntToVector(APInt apInt, SmallVectorImpl< char > &result)
static LogicalResult checkTensorElementType(function_ref< InFlightDiagnostic()> emitError, Type elementType)
#define FLOAT_TYPE_SEMANTICS(TYPE, SEM)
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 ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
static AffineMap getMultiDimIdentityMap(unsigned numDims, MLIRContext *context)
Returns an AffineMap with 'numDims' identity result dim exprs.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
unsigned getNumSymbols() const
unsigned getNumDims() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
bool isIdentity() const
Returns true if this affine map is an identity affine map.
Attributes are known-constant values of operations.
This class provides a shared interface for ranked and unranked memref types.
ArrayRef< int64_t > getShape() const
Returns the shape of this memref type.
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a memref.
FailureOr< PtrLikeTypeInterface > clonePtrWith(Attribute memorySpace, std::optional< Type > elementType) const
Clone this type with the given memory space and element type.
Attribute getMemorySpace() const
Returns the memory space in which data referred to by this memref resides.
unsigned getMemorySpaceAsInt() const
[deprecated] Returns the memory space in old raw integer representation.
BaseMemRefType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
Clone this type with the given shape and element type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
Type getElementType() const
Returns the element type of this memref type.
MemRefType clone(ArrayRef< int64_t > shape, Type elementType) const
Return a clone of this type with the given new shape and element type.
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
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.
This is a builder type that keeps local references to arguments.
Builder & setShape(ArrayRef< int64_t > newShape)
Builder & setMemorySpace(Attribute newMemorySpace)
Builder & setElementType(Type newElementType)
Builder & setLayout(MemRefLayoutAttrInterface newLayout)
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
TensorType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
Clone this type with the given shape and element type.
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a tensor.
ArrayRef< int64_t > getShape() const
Returns the shape of this tensor type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
RankedTensorType clone(ArrayRef< int64_t > shape, Type elementType) const
Return a clone of this type with the given new shape and element type.
Type getElementType() const
Returns the element type of this tensor type.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Dialect & getDialect() const
Get the dialect this type is registered to.
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Attribute wrapIntegerMemorySpace(unsigned memorySpace, MLIRContext *ctx)
Wraps deprecated integer memory space to the new Attribute form.
unsigned getMemorySpaceAsInt(Attribute memorySpace)
[deprecated] Returns the memory space in old raw integer representation.
Attribute skipDefaultMemorySpace(Attribute memorySpace)
Replaces default memorySpace (integer == 0) with empty Attribute.
void writeBits(char *rawData, size_t bitPos, llvm::APInt value)
Write value to byte-aligned position bitPos in rawData.
Include the generated interface declarations.
SliceVerificationResult
Enum that captures information related to verifier error conditions on slice insert/extract type of o...
constexpr T real(const NonFloatComplex< T > &x)
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
TypeRange filterTypesOut(TypeRange types, const BitVector &indices, SmallVectorImpl< Type > &storage)
Filters out any elements referenced by indices.
constexpr T imag(const NonFloatComplex< T > &x)
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
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 makeCanonicalStridedLayoutExpr(ArrayRef< int64_t > sizes, ArrayRef< AffineExpr > exprs, MLIRContext *context)
Given MemRef sizes that are either static or dynamic, returns the canonical "contiguous" strides Affi...
std::optional< llvm::SmallDenseSet< unsigned > > computeRankReductionMask(ArrayRef< int64_t > originalShape, ArrayRef< int64_t > reducedShape, bool matchDynamic=false)
Given an originalShape and a reducedShape assumed to be a subset of originalShape with some 1 entries...
AffineExpr simplifyAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols)
Simplify an affine expression by flattening and some amount of simple analysis.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
SliceVerificationResult isRankReducedType(ShapedType originalType, ShapedType candidateReducedType)
Check if originalType can be rank reduced to candidateReducedType type by dropping some dimensions wi...
TypeRange insertTypesInto(TypeRange oldTypes, ArrayRef< unsigned > indices, TypeRange newTypes, SmallVectorImpl< Type > &storage)
Insert a set of newTypes into oldTypes at the given indices.
llvm::function_ref< Fn > function_ref
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)