23#include "llvm/Support/CheckedArithmetic.h"
24#include "llvm/Support/MathExtras.h"
35 : ConversionPattern(typeConverter, rootOpName, benefit, context) {}
39 ConversionPattern::getTypeConverter());
68 return LLVM::ConstantOp::create(builder, loc, resultType,
80 ConversionPatternRewriter &rewriter,
Location loc, MemRefType type,
82 LLVM::GEPNoWrapFlags noWrapFlags)
const {
84 memRefDesc,
indices, noWrapFlags);
90 MemRefType type)
const {
91 if (!type.getLayout().isIdentity())
93 return static_cast<bool>(typeConverter->convertType(type));
98 if (failed(addressSpace))
100 return LLVM::LLVMPointerType::get(type.getContext(), *addressSpace);
108 "layout maps must have been normalized away");
109 assert(count(memRefType.getShape(), ShapedType::kDynamic) ==
110 static_cast<ssize_t
>(dynamicSizes.size()) &&
111 "dynamicSizes size doesn't match dynamic sizes count in memref shape");
113 sizes.reserve(memRefType.getRank());
114 unsigned dynamicIndex = 0;
116 for (
int64_t size : memRefType.getShape()) {
118 size == ShapedType::kDynamic
119 ? dynamicSizes[dynamicIndex++]
125 bool overflowed =
false;
127 strides.resize(memRefType.getRank());
128 for (
auto i = memRefType.getRank(); i-- > 0;) {
129 strides[i] = overflowed ? LLVM::PoisonOp::create(rewriter, loc, indexType)
132 int64_t staticSize = memRefType.getShape()[i];
133 bool useSizeAsStride = stride == 1;
134 if (staticSize == ShapedType::kDynamic)
135 stride = ShapedType::kDynamic;
136 if (stride != ShapedType::kDynamic) {
137 std::optional<int64_t> res = llvm::checkedMul(stride, staticSize);
142 stride = res.value();
146 runningStride = LLVM::PoisonOp::create(rewriter, loc, indexType);
147 else if (useSizeAsStride)
148 runningStride = sizes[i];
149 else if (stride == ShapedType::kDynamic)
151 LLVM::MulOp::create(rewriter, loc, runningStride, sizes[i]);
157 Type elementType = typeConverter->convertType(memRefType.getElementType());
158 auto elementPtrType = LLVM::LLVMPointerType::get(rewriter.getContext());
159 Value nullPtr = LLVM::ZeroOp::create(rewriter, loc, elementPtrType);
160 Value gepPtr = LLVM::GEPOp::create(rewriter, loc, elementPtrType,
161 elementType, nullPtr, runningStride);
162 size = LLVM::PtrToIntOp::create(rewriter, loc,
getIndexType(), gepPtr);
164 size = runningStride;
169 Location loc,
Type type, ConversionPatternRewriter &rewriter)
const {
175 Type llvmType = typeConverter->convertType(type);
176 auto convertedPtrType = LLVM::LLVMPointerType::get(rewriter.getContext());
177 auto nullPtr = LLVM::ZeroOp::create(rewriter, loc, convertedPtrType);
178 auto gep = LLVM::GEPOp::create(rewriter, loc, convertedPtrType, llvmType,
180 return LLVM::PtrToIntOp::create(rewriter, loc,
getIndexType(), gep);
185 ConversionPatternRewriter &rewriter)
const {
186 assert(count(memRefType.getShape(), ShapedType::kDynamic) ==
187 static_cast<ssize_t
>(dynamicSizes.size()) &&
188 "dynamicSizes size doesn't match dynamic sizes count in memref shape");
191 Value numElements = memRefType.getRank() == 0
194 unsigned dynamicIndex = 0;
197 for (
int64_t staticSize : memRefType.getShape()) {
200 staticSize == ShapedType::kDynamic
201 ? dynamicSizes[dynamicIndex++]
203 numElements = LLVM::MulOp::create(rewriter, loc, numElements, size);
206 staticSize == ShapedType::kDynamic
207 ? dynamicSizes[dynamicIndex++]
218 ConversionPatternRewriter &rewriter)
const {
219 auto structType = typeConverter->convertType(memRefType);
223 memRefDescriptor.setAllocatedPtr(rewriter, loc, allocatedPtr);
226 memRefDescriptor.setAlignedPtr(rewriter, loc, alignedPtr);
230 memRefDescriptor.setOffset(
234 for (
const auto &en : llvm::enumerate(sizes))
235 memRefDescriptor.setSize(rewriter, loc, en.index(), en.value());
238 for (
const auto &en : llvm::enumerate(strides))
239 memRefDescriptor.setStride(rewriter, loc, en.index(), en.value());
241 return memRefDescriptor;
246 Value operand,
bool toDynamic)
const {
248 FailureOr<unsigned> addressSpace =
250 if (failed(addressSpace))
257 auto module = builder.getInsertionPoint()->getParentOfType<ModuleOp>();
258 FailureOr<LLVM::LLVMFuncOp> freeFunc, mallocFunc;
261 if (failed(mallocFunc))
266 if (failed(freeFunc))
275 Value memory = toDynamic
276 ? LLVM::CallOp::create(builder, loc, mallocFunc.value(),
279 : LLVM::AllocaOp::create(builder, loc,
getPtrType(),
284 LLVM::MemcpyOp::create(builder, loc, memory, source, allocationSize,
false);
286 LLVM::CallOp::create(builder, loc, freeFunc.value(), source);
298 updatedDesc.setRank(builder, loc, rank);
299 updatedDesc.setMemRefDescPtr(builder, loc, memory);
306 assert(origTypes.size() == operands.size() &&
307 "expected as may original types as operands");
308 for (
unsigned i = 0, e = operands.size(); i < e; ++i) {
309 if (
auto memRefType = dyn_cast<UnrankedMemRefType>(origTypes[i])) {
311 operands[i], toDynamic);
314 operands[i] = updatedDesc;
330 ConversionPatternRewriter &rewriter) {
334 if (numResults != 0) {
335 resultTypes.push_back(
337 if (!resultTypes.back())
343 resultTypes, targetAttrs);
345 Operation *newOp = rewriter.create(state);
349 return rewriter.eraseOp(op),
success();
356 results.reserve(numResults);
357 for (
unsigned i = 0; i < numResults; ++i) {
358 results.push_back(LLVM::ExtractValueOp::create(rewriter, op->
getLoc(),
361 rewriter.replaceOp(op, results);
370 if (!llvm::all_of(operands, [](
Value value) {
380 auto callIntrOp = LLVM::CallIntrinsicOp::create(
381 rewriter, loc, resType, rewriter.
getStringAttr(intrinsic), operands);
384 auto copyAttr = [&](StringAttr name,
Attribute attr) {
385 if (callIntrOp->getInherentAttr(name).has_value())
386 callIntrOp->setInherentAttr(name, attr);
388 discardableAttrs.emplace_back(name, attr);
391 copyAttr(attr.getName(), attr.getValue());
395 callIntrOp->setDiscardableAttrs(discardableAttrs);
397 if (numResults <= 1) {
406 results.reserve(numResults);
407 Value intrRes = callIntrOp.getResults();
408 for (
unsigned i = 0; i < numResults; ++i)
409 results.push_back(LLVM::ExtractValueOp::create(rewriter, loc, intrRes, i));
419 auto vec = cast<VectorType>(type);
420 assert(!vec.isScalable() &&
"scalable vectors are not supported");
421 return vec.getNumElements() *
getBitWidth(vec.getElementType());
429 if (
auto arrayType = dyn_cast<LLVM::LLVMArrayType>(type))
431 if (
auto structType = dyn_cast<LLVM::LLVMStructType>(type))
432 return llvm::all_of(structType.getBody(), [&](
Type fieldType) {
433 return isFixedSizeAggregate(fieldType, dstType);
435 if (
auto vecTy = dyn_cast<VectorType>(type))
436 return !vecTy.isScalable();
443 return LLVM::ConstantOp::create(builder, loc, i32, value);
452 if (srcType == dstType) {
457 if (
auto arrayType = dyn_cast<LLVM::LLVMArrayType>(srcType)) {
458 for (
auto i : llvm::seq(arrayType.getNumElements())) {
459 Value elem = LLVM::ExtractValueOp::create(builder, loc, src, i);
465 if (
auto structType = dyn_cast<LLVM::LLVMStructType>(srcType)) {
466 for (
auto [i, fieldType] : llvm::enumerate(structType.getBody())) {
467 Value field = LLVM::ExtractValueOp::create(builder, loc, src,
475 if (!srcType.
isIntOrFloat() && !isa<VectorType>(srcType)) {
482 if (srcBitWidth == dstBitWidth) {
483 Value cast = LLVM::BitcastOp::create(builder, loc, dstType, src);
488 if (dstBitWidth > srcBitWidth) {
490 if (srcType != smallerInt)
491 src = LLVM::BitcastOp::create(builder, loc, smallerInt, src);
494 Value res = LLVM::ZExtOp::create(builder, loc, largerInt, src);
498 int64_t numElements = llvm::divideCeil(srcBitWidth, dstBitWidth);
499 int64_t roundedBitWidth = numElements * dstBitWidth;
502 if (roundedBitWidth != srcBitWidth) {
504 if (srcType != srcInt)
505 src = LLVM::BitcastOp::create(builder, loc, srcInt, src);
507 src = LLVM::ZExtOp::create(builder, loc, roundedInt, src);
510 auto vecType = VectorType::get(numElements, dstType);
511 src = LLVM::BitcastOp::create(builder, loc, vecType, src);
513 for (
auto i : llvm::seq(numElements)) {
515 Value elem = LLVM::ExtractElementOp::create(builder, loc, src, idx);
523 bool permitVariablySizedScalars) {
526 if (!permitVariablySizedScalars &&
537 size_t &offset,
Type dstType) {
538 if (
auto arrayType = dyn_cast<LLVM::LLVMArrayType>(dstType)) {
539 Value result = LLVM::PoisonOp::create(builder, loc, arrayType);
540 Type elemType = arrayType.getElementType();
541 for (
auto i : llvm::seq(arrayType.getNumElements())) {
543 result = LLVM::InsertValueOp::create(builder, loc,
result, elem, i);
548 if (
auto structType = dyn_cast<LLVM::LLVMStructType>(dstType)) {
549 Value result = LLVM::PoisonOp::create(builder, loc, structType);
550 for (
auto [i, fieldType] : llvm::enumerate(structType.getBody())) {
552 result = LLVM::InsertValueOp::create(builder, loc,
result, field,
559 if (!dstType.
isIntOrFloat() && !isa<VectorType>(dstType))
560 return src[offset++];
564 Value front = src[offset];
565 if (front.
getType() == dstType) {
573 if (srcBitWidth >= dstBitWidth) {
576 if (dstBitWidth < srcBitWidth) {
578 if (res.getType() != largerInt)
579 res = LLVM::BitcastOp::create(builder, loc, largerInt, res);
582 res = LLVM::TruncOp::create(builder, loc, smallerInt, res);
584 if (res.getType() != dstType)
585 res = LLVM::BitcastOp::create(builder, loc, dstType, res);
592 int64_t numElements = llvm::divideCeil(dstBitWidth, elemBitWidth);
593 int64_t roundedBitWidth = numElements * elemBitWidth;
595 auto vecType = VectorType::get(numElements, front.
getType());
596 Value res = LLVM::PoisonOp::create(builder, loc, vecType);
597 for (
auto i : llvm::seq(numElements)) {
599 res = LLVM::InsertElementOp::create(builder, loc, vecType, res,
604 if (roundedBitWidth != dstBitWidth) {
606 res = LLVM::BitcastOp::create(builder, loc, roundedInt, res);
608 res = LLVM::TruncOp::create(builder, loc, dstInt, res);
609 if (dstType != dstInt)
610 res = LLVM::BitcastOp::create(builder, loc, dstType, res);
612 if (res.getType() != dstType)
613 res = LLVM::BitcastOp::create(builder, loc, dstType, res);
621 assert(!src.empty() &&
"src range must not be empty");
624 assert(offset == src.size() &&
"not all decomposed values were consumed");
630 MemRefType type,
Value memRefDesc,
632 LLVM::GEPNoWrapFlags noWrapFlags) {
633 auto [strides, offset] = type.getStridesAndOffset();
640 Value base = memRefDescriptor.
bufferPtr(builder, loc, converter, type);
642 LLVM::IntegerOverflowFlags intOverflowFlags =
643 LLVM::IntegerOverflowFlags::none;
644 if (LLVM::bitEnumContainsAny(noWrapFlags, LLVM::GEPNoWrapFlags::nusw)) {
645 intOverflowFlags = intOverflowFlags | LLVM::IntegerOverflowFlags::nsw;
647 if (LLVM::bitEnumContainsAny(noWrapFlags, LLVM::GEPNoWrapFlags::nuw)) {
648 intOverflowFlags = intOverflowFlags | LLVM::IntegerOverflowFlags::nuw;
653 for (
int i = 0, e =
indices.size(); i < e; ++i) {
655 if (strides[i] != 1) {
656 Value stride = ShapedType::isDynamic(strides[i])
657 ? memRefDescriptor.
stride(builder, loc, i)
659 indexType, strides[i]);
660 increment = LLVM::MulOp::create(builder, loc, increment, stride,
670 ? LLVM::GEPOp::create(builder, loc, elementPtrType,
671 converter.convertType(type.getElementType()),
672 base,
index, noWrapFlags)
679 if (
auto floatType = dyn_cast<FloatType>(type))
681 if (
auto vecType = dyn_cast<VectorType>(type))
682 return dyn_cast<FloatType>(vecType.getElementType());
691 Type convertedType = typeConverter.convertType(floatType);
694 return !isa<FloatType>(convertedType);
703 return isUnsupportedFloatingPointType(typeConverter, r.getType());
static Value createI32Constant(ConversionPatternRewriter &rewriter, Location loc, int32_t value)
static unsigned getBitWidth(Type type)
static FloatType getFloatingPointType(Type type)
Return the given type if it's a floating point type.
static bool isFixedSizeAggregate(Type type, Type dstType)
Returns true if every leaf in type (recursing through LLVM arrays and structs) is either equal to dst...
static Value composeValueImpl(OpBuilder &builder, Location loc, ValueRange src, size_t &offset, Type dstType)
Recursive implementation of composeValue.
static void decomposeValueImpl(OpBuilder &builder, Location loc, Value src, Type dstType, SmallVectorImpl< Value > &result)
Recursive implementation of decomposeValue.
Attributes are known-constant values of operations.
IntegerAttr getIntegerAttr(Type type, int64_t value)
IntegerType getIntegerType(unsigned width)
StringAttr getStringAttr(const Twine &bytes)
Type getVoidType() const
Gets the MLIR type wrapping the LLVM void type.
MemRefDescriptor createMemRefDescriptor(Location loc, MemRefType memRefType, Value allocatedPtr, Value alignedPtr, ArrayRef< Value > sizes, ArrayRef< Value > strides, ConversionPatternRewriter &rewriter) const
Creates and populates a canonical memref descriptor struct.
ConvertToLLVMPattern(StringRef rootOpName, MLIRContext *context, const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
Value getStridedElementPtr(ConversionPatternRewriter &rewriter, Location loc, MemRefType type, Value memRefDesc, ValueRange indices, LLVM::GEPNoWrapFlags noWrapFlags=LLVM::GEPNoWrapFlags::none) const
Convenience wrapper for the corresponding helper utility.
void getMemRefDescriptorSizes(Location loc, MemRefType memRefType, ValueRange dynamicSizes, ConversionPatternRewriter &rewriter, SmallVectorImpl< Value > &sizes, SmallVectorImpl< Value > &strides, Value &size, bool sizeInBytes=true) const
Computes sizes, strides and buffer size of memRefType with identity layout.
Type getPtrType(unsigned addressSpace=0) const
Get the MLIR type wrapping the LLVM ptr type.
Type getIndexType() const
Gets the MLIR type wrapping the LLVM integer type whose bit width is defined by the used type convert...
const LLVMTypeConverter * getTypeConverter() const
Value getNumElements(Location loc, MemRefType memRefType, ValueRange dynamicSizes, ConversionPatternRewriter &rewriter) const
Computes total number of elements for the given MemRef and dynamicSizes.
LLVM::LLVMDialect & getDialect() const
Returns the LLVM dialect.
Value getSizeInBytes(Location loc, Type type, ConversionPatternRewriter &rewriter) const
Computes the size of type in bytes.
Type getIntPtrType(unsigned addressSpace=0) const
Gets the MLIR type wrapping the LLVM integer type whose bit width corresponds to that of a LLVM point...
Value copyUnrankedDescriptor(OpBuilder &builder, Location loc, UnrankedMemRefType memRefType, Value operand, bool toDynamic) const
Copies the given unranked memory descriptor to heap-allocated memory (if toDynamic is true) or to sta...
LogicalResult copyUnrankedDescriptors(OpBuilder &builder, Location loc, TypeRange origTypes, SmallVectorImpl< Value > &operands, bool toDynamic) const
Copies the memory descriptor for any operands that were unranked descriptors originally to heap-alloc...
Type getElementPtrType(MemRefType type) const
Returns the type of a pointer to an element of the memref.
static Value createIndexAttrConstant(OpBuilder &builder, Location loc, Type resultType, int64_t value)
Create a constant Op producing a value of resultType from an index-typed integer attribute.
bool isConvertibleAndHasIdentityMaps(MemRefType type) const
Returns if the given memref type is convertible to LLVM and has an identity layout map.
Type getVoidPtrType() const
Get the MLIR type wrapping the LLVM i8* type.
Conversion from types to the LLVM IR dialect.
Type packOperationResults(TypeRange types) const
Convert a non-empty list of types of values produced by an operation into an LLVM-compatible type.
FailureOr< unsigned > getMemRefAddressSpace(BaseMemRefType type) const
Return the LLVM address space corresponding to the memory space of the memref type type or failure if...
LLVM::LLVMDialect * getDialect() const
Returns the LLVM dialect.
Type getIndexType() const
Gets the LLVM representation of the index type.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
Value bufferPtr(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type)
Builds IR for getting the start address of the buffer represented by this memref: memref....
LLVM::LLVMPointerType getElementPtrType()
Returns the (LLVM) pointer type this descriptor contains.
Value stride(OpBuilder &builder, Location loc, unsigned pos)
Builds IR extracting the pos-th size from the descriptor.
static MemRefDescriptor poison(OpBuilder &builder, Location loc, Type descriptorType)
Builds IR creating a poison value of the descriptor type.
NamedAttribute represents a combination of a name and an Attribute value.
This class helps build Operations.
This is a value defined by a result of an operation.
void walkInherentAttrs(Operation *op, InherentAttrVisitor visitor) const
Visit the inherent attributes stored in the properties of op.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
OperationName getName()
The name of an operation is the key identifier for it.
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
result_range getResults()
unsigned getNumResults()
Return the number of results held by this operation.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
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...
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
static Value computeSize(OpBuilder &builder, Location loc, const LLVMTypeConverter &typeConverter, UnrankedMemRefDescriptor desc, unsigned addressSpace)
Builds and returns IR computing the size in bytes (suitable for opaque allocation).
Value memRefDescPtr(OpBuilder &builder, Location loc) const
Builds IR extracting ranked memref descriptor ptr.
static UnrankedMemRefDescriptor poison(OpBuilder &builder, Location loc, Type descriptorType)
Builds IR creating an undef value of the descriptor type.
Value rank(OpBuilder &builder, Location loc) const
Builds IR extracting the rank from the descriptor.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
bool isUnsupportedFloatingPointType(const TypeConverter &typeConverter, Type type)
Return "true" if the given type is an unsupported floating point type.
LogicalResult oneToOneRewrite(Operation *op, StringRef targetOp, ValueRange operands, ArrayRef< NamedAttribute > targetAttrs, Attribute propertiesAttr, const LLVMTypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Replaces the given operation "op" with a new operation of type "targetOp" and given operands.
bool opHasUnsupportedFloatingPointTypes(Operation *op, const TypeConverter &typeConverter)
Return "true" if the given op has any unsupported floating point types (either operands or results).
LogicalResult intrinsicRewrite(Operation *op, StringRef intrinsic, ValueRange operands, const LLVMTypeConverter &typeConverter, RewriterBase &rewriter)
Replaces the given operation "op" with a call to an LLVM intrinsic with the specified name "intrinsic...
FailureOr< LLVM::LLVMFuncOp > lookupOrCreateFreeFn(OpBuilder &b, Operation *moduleOp, SymbolTableCollection *symbolTables=nullptr)
Value getStridedElementPtr(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type, Value memRefDesc, ValueRange indices, LLVM::GEPNoWrapFlags noWrapFlags=LLVM::GEPNoWrapFlags::none)
Performs the index computation to get to the element at indices of the memory pointed to by memRefDes...
LogicalResult decomposeValue(OpBuilder &builder, Location loc, Value src, Type dstType, SmallVectorImpl< Value > &result, bool permitVariablySizedScalars=false)
Decomposes a src value into a set of values of type dstType through series of bitcasts and vector ops...
Value createIndexAttrConstant(OpBuilder &builder, Location loc, Type resultType, int64_t value)
Creates an llvm.mlir.constant producing value as resultType, which is expected to be the converted in...
Value composeValue(OpBuilder &builder, Location loc, ValueRange src, Type dstType)
Composes a set of src values into a single value of type dstType through series of bitcasts and vecto...
FailureOr< LLVM::LLVMFuncOp > lookupOrCreateMallocFn(OpBuilder &b, Operation *moduleOp, Type indexType, SymbolTableCollection *symbolTables=nullptr)
bool isCompatibleType(Type type)
Returns true if the given type is compatible with the LLVM dialect.
Include the generated interface declarations.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
Attribute propertiesAttr
This Attribute is used to opaquely construct the properties of the operation.