15c0c51a9SNicolas Vasilache //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===// 25c0c51a9SNicolas Vasilache // 330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information. 556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65c0c51a9SNicolas Vasilache // 756222a06SMehdi Amini //===----------------------------------------------------------------------===// 85c0c51a9SNicolas Vasilache 965678d93SNicolas Vasilache #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" 10870c1fd4SAlex Zinenko 11*75e5f0aaSAlex Zinenko #include "mlir/Conversion/LLVMCommon/VectorPattern.h" 12e332c22cSNicolas Vasilache #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h" 135c0c51a9SNicolas Vasilache #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 14e2310704SJulian Gross #include "mlir/Dialect/MemRef/IR/MemRef.h" 1569d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h" 164d60f47bSRob Suderman #include "mlir/Dialect/Vector/VectorOps.h" 1709f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h" 1829a50c58SStephen Neuendorffer #include "mlir/Support/MathExtras.h" 19929189a4SWilliam S. Moses #include "mlir/Target/LLVMIR/TypeToLLVM.h" 205c0c51a9SNicolas Vasilache #include "mlir/Transforms/DialectConversion.h" 215c0c51a9SNicolas Vasilache 225c0c51a9SNicolas Vasilache using namespace mlir; 2365678d93SNicolas Vasilache using namespace mlir::vector; 245c0c51a9SNicolas Vasilache 259826fe5cSAart Bik // Helper to reduce vector type by one rank at front. 269826fe5cSAart Bik static VectorType reducedVectorTypeFront(VectorType tp) { 279826fe5cSAart Bik assert((tp.getRank() > 1) && "unlowerable vector type"); 289826fe5cSAart Bik return VectorType::get(tp.getShape().drop_front(), tp.getElementType()); 299826fe5cSAart Bik } 309826fe5cSAart Bik 319826fe5cSAart Bik // Helper to reduce vector type by *all* but one rank at back. 329826fe5cSAart Bik static VectorType reducedVectorTypeBack(VectorType tp) { 339826fe5cSAart Bik assert((tp.getRank() > 1) && "unlowerable vector type"); 349826fe5cSAart Bik return VectorType::get(tp.getShape().take_back(), tp.getElementType()); 359826fe5cSAart Bik } 369826fe5cSAart Bik 371c81adf3SAart Bik // Helper that picks the proper sequence for inserting. 38e62a6956SRiver Riddle static Value insertOne(ConversionPatternRewriter &rewriter, 390f04384dSAlex Zinenko LLVMTypeConverter &typeConverter, Location loc, 400f04384dSAlex Zinenko Value val1, Value val2, Type llvmType, int64_t rank, 410f04384dSAlex Zinenko int64_t pos) { 421c81adf3SAart Bik if (rank == 1) { 431c81adf3SAart Bik auto idxType = rewriter.getIndexType(); 441c81adf3SAart Bik auto constant = rewriter.create<LLVM::ConstantOp>( 450f04384dSAlex Zinenko loc, typeConverter.convertType(idxType), 461c81adf3SAart Bik rewriter.getIntegerAttr(idxType, pos)); 471c81adf3SAart Bik return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2, 481c81adf3SAart Bik constant); 491c81adf3SAart Bik } 501c81adf3SAart Bik return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2, 511c81adf3SAart Bik rewriter.getI64ArrayAttr(pos)); 521c81adf3SAart Bik } 531c81adf3SAart Bik 542d515e49SNicolas Vasilache // Helper that picks the proper sequence for inserting. 552d515e49SNicolas Vasilache static Value insertOne(PatternRewriter &rewriter, Location loc, Value from, 562d515e49SNicolas Vasilache Value into, int64_t offset) { 572d515e49SNicolas Vasilache auto vectorType = into.getType().cast<VectorType>(); 582d515e49SNicolas Vasilache if (vectorType.getRank() > 1) 592d515e49SNicolas Vasilache return rewriter.create<InsertOp>(loc, from, into, offset); 602d515e49SNicolas Vasilache return rewriter.create<vector::InsertElementOp>( 612d515e49SNicolas Vasilache loc, vectorType, from, into, 622d515e49SNicolas Vasilache rewriter.create<ConstantIndexOp>(loc, offset)); 632d515e49SNicolas Vasilache } 642d515e49SNicolas Vasilache 651c81adf3SAart Bik // Helper that picks the proper sequence for extracting. 66e62a6956SRiver Riddle static Value extractOne(ConversionPatternRewriter &rewriter, 670f04384dSAlex Zinenko LLVMTypeConverter &typeConverter, Location loc, 680f04384dSAlex Zinenko Value val, Type llvmType, int64_t rank, int64_t pos) { 691c81adf3SAart Bik if (rank == 1) { 701c81adf3SAart Bik auto idxType = rewriter.getIndexType(); 711c81adf3SAart Bik auto constant = rewriter.create<LLVM::ConstantOp>( 720f04384dSAlex Zinenko loc, typeConverter.convertType(idxType), 731c81adf3SAart Bik rewriter.getIntegerAttr(idxType, pos)); 741c81adf3SAart Bik return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val, 751c81adf3SAart Bik constant); 761c81adf3SAart Bik } 771c81adf3SAart Bik return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val, 781c81adf3SAart Bik rewriter.getI64ArrayAttr(pos)); 791c81adf3SAart Bik } 801c81adf3SAart Bik 812d515e49SNicolas Vasilache // Helper that picks the proper sequence for extracting. 822d515e49SNicolas Vasilache static Value extractOne(PatternRewriter &rewriter, Location loc, Value vector, 832d515e49SNicolas Vasilache int64_t offset) { 842d515e49SNicolas Vasilache auto vectorType = vector.getType().cast<VectorType>(); 852d515e49SNicolas Vasilache if (vectorType.getRank() > 1) 862d515e49SNicolas Vasilache return rewriter.create<ExtractOp>(loc, vector, offset); 872d515e49SNicolas Vasilache return rewriter.create<vector::ExtractElementOp>( 882d515e49SNicolas Vasilache loc, vectorType.getElementType(), vector, 892d515e49SNicolas Vasilache rewriter.create<ConstantIndexOp>(loc, offset)); 902d515e49SNicolas Vasilache } 912d515e49SNicolas Vasilache 922d515e49SNicolas Vasilache // Helper that returns a subset of `arrayAttr` as a vector of int64_t. 939db53a18SRiver Riddle // TODO: Better support for attribute subtype forwarding + slicing. 942d515e49SNicolas Vasilache static SmallVector<int64_t, 4> getI64SubArray(ArrayAttr arrayAttr, 952d515e49SNicolas Vasilache unsigned dropFront = 0, 962d515e49SNicolas Vasilache unsigned dropBack = 0) { 972d515e49SNicolas Vasilache assert(arrayAttr.size() > dropFront + dropBack && "Out of bounds"); 982d515e49SNicolas Vasilache auto range = arrayAttr.getAsRange<IntegerAttr>(); 992d515e49SNicolas Vasilache SmallVector<int64_t, 4> res; 1002d515e49SNicolas Vasilache res.reserve(arrayAttr.size() - dropFront - dropBack); 1012d515e49SNicolas Vasilache for (auto it = range.begin() + dropFront, eit = range.end() - dropBack; 1022d515e49SNicolas Vasilache it != eit; ++it) 1032d515e49SNicolas Vasilache res.push_back((*it).getValue().getSExtValue()); 1042d515e49SNicolas Vasilache return res; 1052d515e49SNicolas Vasilache } 1062d515e49SNicolas Vasilache 10726c8f908SThomas Raoux // Helper that returns data layout alignment of a memref. 10826c8f908SThomas Raoux LogicalResult getMemRefAlignment(LLVMTypeConverter &typeConverter, 10926c8f908SThomas Raoux MemRefType memrefType, unsigned &align) { 11026c8f908SThomas Raoux Type elementTy = typeConverter.convertType(memrefType.getElementType()); 1115f9e0466SNicolas Vasilache if (!elementTy) 1125f9e0466SNicolas Vasilache return failure(); 1135f9e0466SNicolas Vasilache 114b2ab375dSAlex Zinenko // TODO: this should use the MLIR data layout when it becomes available and 115b2ab375dSAlex Zinenko // stop depending on translation. 11687a89e0fSAlex Zinenko llvm::LLVMContext llvmContext; 11787a89e0fSAlex Zinenko align = LLVM::TypeToLLVMIRTranslator(llvmContext) 118c69c9e0fSAlex Zinenko .getPreferredAlignment(elementTy, typeConverter.getDataLayout()); 1195f9e0466SNicolas Vasilache return success(); 1205f9e0466SNicolas Vasilache } 1215f9e0466SNicolas Vasilache 12229a50c58SStephen Neuendorffer // Return the minimal alignment value that satisfies all the AssumeAlignment 12329a50c58SStephen Neuendorffer // uses of `value`. If no such uses exist, return 1. 12429a50c58SStephen Neuendorffer static unsigned getAssumedAlignment(Value value) { 12529a50c58SStephen Neuendorffer unsigned align = 1; 12629a50c58SStephen Neuendorffer for (auto &u : value.getUses()) { 12729a50c58SStephen Neuendorffer Operation *owner = u.getOwner(); 12829a50c58SStephen Neuendorffer if (auto op = dyn_cast<memref::AssumeAlignmentOp>(owner)) 12929a50c58SStephen Neuendorffer align = mlir::lcm(align, op.alignment()); 13029a50c58SStephen Neuendorffer } 13129a50c58SStephen Neuendorffer return align; 13229a50c58SStephen Neuendorffer } 13329a50c58SStephen Neuendorffer // Helper that returns data layout alignment of a memref associated with a 13429a50c58SStephen Neuendorffer // transfer op, including additional information from assume_alignment calls 13529a50c58SStephen Neuendorffer // on the source of the transfer 13629a50c58SStephen Neuendorffer LogicalResult getTransferOpAlignment(LLVMTypeConverter &typeConverter, 13729a50c58SStephen Neuendorffer VectorTransferOpInterface xfer, 13829a50c58SStephen Neuendorffer unsigned &align) { 13929a50c58SStephen Neuendorffer if (failed(getMemRefAlignment( 14029a50c58SStephen Neuendorffer typeConverter, xfer.getShapedType().cast<MemRefType>(), align))) 14129a50c58SStephen Neuendorffer return failure(); 14229a50c58SStephen Neuendorffer align = std::max(align, getAssumedAlignment(xfer.source())); 14329a50c58SStephen Neuendorffer return success(); 14429a50c58SStephen Neuendorffer } 14529a50c58SStephen Neuendorffer 14629a50c58SStephen Neuendorffer // Helper that returns data layout alignment of a memref associated with a 14729a50c58SStephen Neuendorffer // load, store, scatter, or gather op, including additional information from 14829a50c58SStephen Neuendorffer // assume_alignment calls on the source of the transfer 14929a50c58SStephen Neuendorffer template <class OpAdaptor> 15029a50c58SStephen Neuendorffer LogicalResult getMemRefOpAlignment(LLVMTypeConverter &typeConverter, 15129a50c58SStephen Neuendorffer OpAdaptor op, unsigned &align) { 15229a50c58SStephen Neuendorffer if (failed(getMemRefAlignment(typeConverter, op.getMemRefType(), align))) 15329a50c58SStephen Neuendorffer return failure(); 15429a50c58SStephen Neuendorffer align = std::max(align, getAssumedAlignment(op.base())); 15529a50c58SStephen Neuendorffer return success(); 15629a50c58SStephen Neuendorffer } 15729a50c58SStephen Neuendorffer 158df5ccf5aSAart Bik // Add an index vector component to a base pointer. This almost always succeeds 159df5ccf5aSAart Bik // unless the last stride is non-unit or the memory space is not zero. 160df5ccf5aSAart Bik static LogicalResult getIndexedPtrs(ConversionPatternRewriter &rewriter, 161df5ccf5aSAart Bik Location loc, Value memref, Value base, 162df5ccf5aSAart Bik Value index, MemRefType memRefType, 163df5ccf5aSAart Bik VectorType vType, Value &ptrs) { 16419dbb230Saartbik int64_t offset; 16519dbb230Saartbik SmallVector<int64_t, 4> strides; 16619dbb230Saartbik auto successStrides = getStridesAndOffset(memRefType, strides, offset); 167df5ccf5aSAart Bik if (failed(successStrides) || strides.back() != 1 || 16837eca08eSVladislav Vinogradov memRefType.getMemorySpaceAsInt() != 0) 169e8dcf5f8Saartbik return failure(); 1703a577f54SChristian Sigg auto pType = MemRefDescriptor(memref).getElementPtrType(); 171bd30a796SAlex Zinenko auto ptrsType = LLVM::getFixedVectorType(pType, vType.getDimSize(0)); 172df5ccf5aSAart Bik ptrs = rewriter.create<LLVM::GEPOp>(loc, ptrsType, base, index); 17319dbb230Saartbik return success(); 17419dbb230Saartbik } 17519dbb230Saartbik 176a57def30SAart Bik // Casts a strided element pointer to a vector pointer. The vector pointer 17708c681f6SAndrew Pritchard // will be in the same address space as the incoming memref type. 178a57def30SAart Bik static Value castDataPtr(ConversionPatternRewriter &rewriter, Location loc, 179a57def30SAart Bik Value ptr, MemRefType memRefType, Type vt) { 18037eca08eSVladislav Vinogradov auto pType = LLVM::LLVMPointerType::get(vt, memRefType.getMemorySpaceAsInt()); 181a57def30SAart Bik return rewriter.create<LLVM::BitcastOp>(loc, pType, ptr); 182a57def30SAart Bik } 183a57def30SAart Bik 1845f9e0466SNicolas Vasilache static LogicalResult 1855f9e0466SNicolas Vasilache replaceTransferOpWithLoadOrStore(ConversionPatternRewriter &rewriter, 1865f9e0466SNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 1875f9e0466SNicolas Vasilache TransferReadOp xferOp, 1885f9e0466SNicolas Vasilache ArrayRef<Value> operands, Value dataPtr) { 189affbc0cdSNicolas Vasilache unsigned align; 19029a50c58SStephen Neuendorffer if (failed(getTransferOpAlignment(typeConverter, xferOp, align))) 191affbc0cdSNicolas Vasilache return failure(); 192affbc0cdSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::LoadOp>(xferOp, dataPtr, align); 1935f9e0466SNicolas Vasilache return success(); 1945f9e0466SNicolas Vasilache } 1955f9e0466SNicolas Vasilache 1965f9e0466SNicolas Vasilache static LogicalResult 1975f9e0466SNicolas Vasilache replaceTransferOpWithMasked(ConversionPatternRewriter &rewriter, 1985f9e0466SNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 1995f9e0466SNicolas Vasilache TransferReadOp xferOp, ArrayRef<Value> operands, 2005f9e0466SNicolas Vasilache Value dataPtr, Value mask) { 2015f9e0466SNicolas Vasilache Type vecTy = typeConverter.convertType(xferOp.getVectorType()); 2025f9e0466SNicolas Vasilache if (!vecTy) 2035f9e0466SNicolas Vasilache return failure(); 2045f9e0466SNicolas Vasilache 205b614ada0STobias Gysi auto adaptor = TransferReadOpAdaptor(operands, xferOp->getAttrDictionary()); 206b614ada0STobias Gysi Value fill = rewriter.create<SplatOp>(loc, vecTy, adaptor.padding()); 207b614ada0STobias Gysi 2085f9e0466SNicolas Vasilache unsigned align; 20929a50c58SStephen Neuendorffer if (failed(getTransferOpAlignment(typeConverter, xferOp, align))) 2105f9e0466SNicolas Vasilache return failure(); 2115f9e0466SNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>( 2125f9e0466SNicolas Vasilache xferOp, vecTy, dataPtr, mask, ValueRange{fill}, 2135f9e0466SNicolas Vasilache rewriter.getI32IntegerAttr(align)); 2145f9e0466SNicolas Vasilache return success(); 2155f9e0466SNicolas Vasilache } 2165f9e0466SNicolas Vasilache 2175f9e0466SNicolas Vasilache static LogicalResult 2185f9e0466SNicolas Vasilache replaceTransferOpWithLoadOrStore(ConversionPatternRewriter &rewriter, 2195f9e0466SNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 2205f9e0466SNicolas Vasilache TransferWriteOp xferOp, 2215f9e0466SNicolas Vasilache ArrayRef<Value> operands, Value dataPtr) { 222affbc0cdSNicolas Vasilache unsigned align; 22329a50c58SStephen Neuendorffer if (failed(getTransferOpAlignment(typeConverter, xferOp, align))) 224affbc0cdSNicolas Vasilache return failure(); 22565a3f289SMatthias Springer auto adaptor = TransferWriteOpAdaptor(operands, xferOp->getAttrDictionary()); 226affbc0cdSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::StoreOp>(xferOp, adaptor.vector(), dataPtr, 227affbc0cdSNicolas Vasilache align); 2285f9e0466SNicolas Vasilache return success(); 2295f9e0466SNicolas Vasilache } 2305f9e0466SNicolas Vasilache 2315f9e0466SNicolas Vasilache static LogicalResult 2325f9e0466SNicolas Vasilache replaceTransferOpWithMasked(ConversionPatternRewriter &rewriter, 2335f9e0466SNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 2345f9e0466SNicolas Vasilache TransferWriteOp xferOp, ArrayRef<Value> operands, 2355f9e0466SNicolas Vasilache Value dataPtr, Value mask) { 2365f9e0466SNicolas Vasilache unsigned align; 23729a50c58SStephen Neuendorffer if (failed(getTransferOpAlignment(typeConverter, xferOp, align))) 2385f9e0466SNicolas Vasilache return failure(); 2395f9e0466SNicolas Vasilache 24065a3f289SMatthias Springer auto adaptor = TransferWriteOpAdaptor(operands, xferOp->getAttrDictionary()); 2415f9e0466SNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>( 2425f9e0466SNicolas Vasilache xferOp, adaptor.vector(), dataPtr, mask, 2435f9e0466SNicolas Vasilache rewriter.getI32IntegerAttr(align)); 2445f9e0466SNicolas Vasilache return success(); 2455f9e0466SNicolas Vasilache } 2465f9e0466SNicolas Vasilache 2472d2c73c5SJacques Pienaar static TransferReadOpAdaptor getTransferOpAdapter(TransferReadOp xferOp, 2482d2c73c5SJacques Pienaar ArrayRef<Value> operands) { 24965a3f289SMatthias Springer return TransferReadOpAdaptor(operands, xferOp->getAttrDictionary()); 2505f9e0466SNicolas Vasilache } 2515f9e0466SNicolas Vasilache 2522d2c73c5SJacques Pienaar static TransferWriteOpAdaptor getTransferOpAdapter(TransferWriteOp xferOp, 2532d2c73c5SJacques Pienaar ArrayRef<Value> operands) { 25465a3f289SMatthias Springer return TransferWriteOpAdaptor(operands, xferOp->getAttrDictionary()); 2555f9e0466SNicolas Vasilache } 2565f9e0466SNicolas Vasilache 25790c01357SBenjamin Kramer namespace { 258e83b7b99Saartbik 259cf5c517cSDiego Caballero /// Conversion pattern for a vector.bitcast. 260cf5c517cSDiego Caballero class VectorBitCastOpConversion 261cf5c517cSDiego Caballero : public ConvertOpToLLVMPattern<vector::BitCastOp> { 262cf5c517cSDiego Caballero public: 263cf5c517cSDiego Caballero using ConvertOpToLLVMPattern<vector::BitCastOp>::ConvertOpToLLVMPattern; 264cf5c517cSDiego Caballero 265cf5c517cSDiego Caballero LogicalResult 266cf5c517cSDiego Caballero matchAndRewrite(vector::BitCastOp bitCastOp, ArrayRef<Value> operands, 267cf5c517cSDiego Caballero ConversionPatternRewriter &rewriter) const override { 268cf5c517cSDiego Caballero // Only 1-D vectors can be lowered to LLVM. 269cf5c517cSDiego Caballero VectorType resultTy = bitCastOp.getType(); 270cf5c517cSDiego Caballero if (resultTy.getRank() != 1) 271cf5c517cSDiego Caballero return failure(); 272cf5c517cSDiego Caballero Type newResultTy = typeConverter->convertType(resultTy); 273cf5c517cSDiego Caballero rewriter.replaceOpWithNewOp<LLVM::BitcastOp>(bitCastOp, newResultTy, 274cf5c517cSDiego Caballero operands[0]); 275cf5c517cSDiego Caballero return success(); 276cf5c517cSDiego Caballero } 277cf5c517cSDiego Caballero }; 278cf5c517cSDiego Caballero 27963b683a8SNicolas Vasilache /// Conversion pattern for a vector.matrix_multiply. 28063b683a8SNicolas Vasilache /// This is lowered directly to the proper llvm.intr.matrix.multiply. 281563879b6SRahul Joshi class VectorMatmulOpConversion 282563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::MatmulOp> { 28363b683a8SNicolas Vasilache public: 284563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::MatmulOp>::ConvertOpToLLVMPattern; 28563b683a8SNicolas Vasilache 2863145427dSRiver Riddle LogicalResult 287563879b6SRahul Joshi matchAndRewrite(vector::MatmulOp matmulOp, ArrayRef<Value> operands, 28863b683a8SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 2892d2c73c5SJacques Pienaar auto adaptor = vector::MatmulOpAdaptor(operands); 29063b683a8SNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MatrixMultiplyOp>( 291563879b6SRahul Joshi matmulOp, typeConverter->convertType(matmulOp.res().getType()), 292563879b6SRahul Joshi adaptor.lhs(), adaptor.rhs(), matmulOp.lhs_rows(), 293563879b6SRahul Joshi matmulOp.lhs_columns(), matmulOp.rhs_columns()); 2943145427dSRiver Riddle return success(); 29563b683a8SNicolas Vasilache } 29663b683a8SNicolas Vasilache }; 29763b683a8SNicolas Vasilache 298c295a65dSaartbik /// Conversion pattern for a vector.flat_transpose. 299c295a65dSaartbik /// This is lowered directly to the proper llvm.intr.matrix.transpose. 300563879b6SRahul Joshi class VectorFlatTransposeOpConversion 301563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::FlatTransposeOp> { 302c295a65dSaartbik public: 303563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::FlatTransposeOp>::ConvertOpToLLVMPattern; 304c295a65dSaartbik 305c295a65dSaartbik LogicalResult 306563879b6SRahul Joshi matchAndRewrite(vector::FlatTransposeOp transOp, ArrayRef<Value> operands, 307c295a65dSaartbik ConversionPatternRewriter &rewriter) const override { 3082d2c73c5SJacques Pienaar auto adaptor = vector::FlatTransposeOpAdaptor(operands); 309c295a65dSaartbik rewriter.replaceOpWithNewOp<LLVM::MatrixTransposeOp>( 310dcec2ca5SChristian Sigg transOp, typeConverter->convertType(transOp.res().getType()), 311c295a65dSaartbik adaptor.matrix(), transOp.rows(), transOp.columns()); 312c295a65dSaartbik return success(); 313c295a65dSaartbik } 314c295a65dSaartbik }; 315c295a65dSaartbik 316ee66e43aSDiego Caballero /// Overloaded utility that replaces a vector.load, vector.store, 317ee66e43aSDiego Caballero /// vector.maskedload and vector.maskedstore with their respective LLVM 318ee66e43aSDiego Caballero /// couterparts. 319ee66e43aSDiego Caballero static void replaceLoadOrStoreOp(vector::LoadOp loadOp, 320ee66e43aSDiego Caballero vector::LoadOpAdaptor adaptor, 321ee66e43aSDiego Caballero VectorType vectorTy, Value ptr, unsigned align, 322ee66e43aSDiego Caballero ConversionPatternRewriter &rewriter) { 323ee66e43aSDiego Caballero rewriter.replaceOpWithNewOp<LLVM::LoadOp>(loadOp, ptr, align); 32439379916Saartbik } 32539379916Saartbik 326ee66e43aSDiego Caballero static void replaceLoadOrStoreOp(vector::MaskedLoadOp loadOp, 327ee66e43aSDiego Caballero vector::MaskedLoadOpAdaptor adaptor, 328ee66e43aSDiego Caballero VectorType vectorTy, Value ptr, unsigned align, 329ee66e43aSDiego Caballero ConversionPatternRewriter &rewriter) { 330ee66e43aSDiego Caballero rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>( 331ee66e43aSDiego Caballero loadOp, vectorTy, ptr, adaptor.mask(), adaptor.pass_thru(), align); 332ee66e43aSDiego Caballero } 333ee66e43aSDiego Caballero 334ee66e43aSDiego Caballero static void replaceLoadOrStoreOp(vector::StoreOp storeOp, 335ee66e43aSDiego Caballero vector::StoreOpAdaptor adaptor, 336ee66e43aSDiego Caballero VectorType vectorTy, Value ptr, unsigned align, 337ee66e43aSDiego Caballero ConversionPatternRewriter &rewriter) { 338ee66e43aSDiego Caballero rewriter.replaceOpWithNewOp<LLVM::StoreOp>(storeOp, adaptor.valueToStore(), 339ee66e43aSDiego Caballero ptr, align); 340ee66e43aSDiego Caballero } 341ee66e43aSDiego Caballero 342ee66e43aSDiego Caballero static void replaceLoadOrStoreOp(vector::MaskedStoreOp storeOp, 343ee66e43aSDiego Caballero vector::MaskedStoreOpAdaptor adaptor, 344ee66e43aSDiego Caballero VectorType vectorTy, Value ptr, unsigned align, 345ee66e43aSDiego Caballero ConversionPatternRewriter &rewriter) { 346ee66e43aSDiego Caballero rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>( 347ee66e43aSDiego Caballero storeOp, adaptor.valueToStore(), ptr, adaptor.mask(), align); 348ee66e43aSDiego Caballero } 349ee66e43aSDiego Caballero 350ee66e43aSDiego Caballero /// Conversion pattern for a vector.load, vector.store, vector.maskedload, and 351ee66e43aSDiego Caballero /// vector.maskedstore. 352ee66e43aSDiego Caballero template <class LoadOrStoreOp, class LoadOrStoreOpAdaptor> 353ee66e43aSDiego Caballero class VectorLoadStoreConversion : public ConvertOpToLLVMPattern<LoadOrStoreOp> { 35439379916Saartbik public: 355ee66e43aSDiego Caballero using ConvertOpToLLVMPattern<LoadOrStoreOp>::ConvertOpToLLVMPattern; 35639379916Saartbik 35739379916Saartbik LogicalResult 358ee66e43aSDiego Caballero matchAndRewrite(LoadOrStoreOp loadOrStoreOp, ArrayRef<Value> operands, 35939379916Saartbik ConversionPatternRewriter &rewriter) const override { 360ee66e43aSDiego Caballero // Only 1-D vectors can be lowered to LLVM. 361ee66e43aSDiego Caballero VectorType vectorTy = loadOrStoreOp.getVectorType(); 362ee66e43aSDiego Caballero if (vectorTy.getRank() > 1) 363ee66e43aSDiego Caballero return failure(); 364ee66e43aSDiego Caballero 365ee66e43aSDiego Caballero auto loc = loadOrStoreOp->getLoc(); 366ee66e43aSDiego Caballero auto adaptor = LoadOrStoreOpAdaptor(operands); 367ee66e43aSDiego Caballero MemRefType memRefTy = loadOrStoreOp.getMemRefType(); 36839379916Saartbik 36939379916Saartbik // Resolve alignment. 37039379916Saartbik unsigned align; 37129a50c58SStephen Neuendorffer if (failed(getMemRefOpAlignment(*this->getTypeConverter(), loadOrStoreOp, 37229a50c58SStephen Neuendorffer align))) 37339379916Saartbik return failure(); 37439379916Saartbik 375a57def30SAart Bik // Resolve address. 376ee66e43aSDiego Caballero auto vtype = this->typeConverter->convertType(loadOrStoreOp.getVectorType()) 377ee66e43aSDiego Caballero .template cast<VectorType>(); 378ee66e43aSDiego Caballero Value dataPtr = this->getStridedElementPtr(loc, memRefTy, adaptor.base(), 379a57def30SAart Bik adaptor.indices(), rewriter); 380ee66e43aSDiego Caballero Value ptr = castDataPtr(rewriter, loc, dataPtr, memRefTy, vtype); 38139379916Saartbik 382ee66e43aSDiego Caballero replaceLoadOrStoreOp(loadOrStoreOp, adaptor, vtype, ptr, align, rewriter); 38339379916Saartbik return success(); 38439379916Saartbik } 38539379916Saartbik }; 38639379916Saartbik 38719dbb230Saartbik /// Conversion pattern for a vector.gather. 388563879b6SRahul Joshi class VectorGatherOpConversion 389563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::GatherOp> { 39019dbb230Saartbik public: 391563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::GatherOp>::ConvertOpToLLVMPattern; 39219dbb230Saartbik 39319dbb230Saartbik LogicalResult 394563879b6SRahul Joshi matchAndRewrite(vector::GatherOp gather, ArrayRef<Value> operands, 39519dbb230Saartbik ConversionPatternRewriter &rewriter) const override { 396563879b6SRahul Joshi auto loc = gather->getLoc(); 39719dbb230Saartbik auto adaptor = vector::GatherOpAdaptor(operands); 398df5ccf5aSAart Bik MemRefType memRefType = gather.getMemRefType(); 39919dbb230Saartbik 40019dbb230Saartbik // Resolve alignment. 40119dbb230Saartbik unsigned align; 40229a50c58SStephen Neuendorffer if (failed(getMemRefOpAlignment(*getTypeConverter(), gather, align))) 40319dbb230Saartbik return failure(); 40419dbb230Saartbik 405df5ccf5aSAart Bik // Resolve address. 40619dbb230Saartbik Value ptrs; 407df5ccf5aSAart Bik VectorType vType = gather.getVectorType(); 408df5ccf5aSAart Bik Value ptr = getStridedElementPtr(loc, memRefType, adaptor.base(), 409df5ccf5aSAart Bik adaptor.indices(), rewriter); 410df5ccf5aSAart Bik if (failed(getIndexedPtrs(rewriter, loc, adaptor.base(), ptr, 411df5ccf5aSAart Bik adaptor.index_vec(), memRefType, vType, ptrs))) 41219dbb230Saartbik return failure(); 41319dbb230Saartbik 41419dbb230Saartbik // Replace with the gather intrinsic. 41519dbb230Saartbik rewriter.replaceOpWithNewOp<LLVM::masked_gather>( 416dcec2ca5SChristian Sigg gather, typeConverter->convertType(vType), ptrs, adaptor.mask(), 4170c2a4d3cSBenjamin Kramer adaptor.pass_thru(), rewriter.getI32IntegerAttr(align)); 41819dbb230Saartbik return success(); 41919dbb230Saartbik } 42019dbb230Saartbik }; 42119dbb230Saartbik 42219dbb230Saartbik /// Conversion pattern for a vector.scatter. 423563879b6SRahul Joshi class VectorScatterOpConversion 424563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::ScatterOp> { 42519dbb230Saartbik public: 426563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::ScatterOp>::ConvertOpToLLVMPattern; 42719dbb230Saartbik 42819dbb230Saartbik LogicalResult 429563879b6SRahul Joshi matchAndRewrite(vector::ScatterOp scatter, ArrayRef<Value> operands, 43019dbb230Saartbik ConversionPatternRewriter &rewriter) const override { 431563879b6SRahul Joshi auto loc = scatter->getLoc(); 43219dbb230Saartbik auto adaptor = vector::ScatterOpAdaptor(operands); 433df5ccf5aSAart Bik MemRefType memRefType = scatter.getMemRefType(); 43419dbb230Saartbik 43519dbb230Saartbik // Resolve alignment. 43619dbb230Saartbik unsigned align; 43729a50c58SStephen Neuendorffer if (failed(getMemRefOpAlignment(*getTypeConverter(), scatter, align))) 43819dbb230Saartbik return failure(); 43919dbb230Saartbik 440df5ccf5aSAart Bik // Resolve address. 44119dbb230Saartbik Value ptrs; 442df5ccf5aSAart Bik VectorType vType = scatter.getVectorType(); 443df5ccf5aSAart Bik Value ptr = getStridedElementPtr(loc, memRefType, adaptor.base(), 444df5ccf5aSAart Bik adaptor.indices(), rewriter); 445df5ccf5aSAart Bik if (failed(getIndexedPtrs(rewriter, loc, adaptor.base(), ptr, 446df5ccf5aSAart Bik adaptor.index_vec(), memRefType, vType, ptrs))) 44719dbb230Saartbik return failure(); 44819dbb230Saartbik 44919dbb230Saartbik // Replace with the scatter intrinsic. 45019dbb230Saartbik rewriter.replaceOpWithNewOp<LLVM::masked_scatter>( 451656674a7SDiego Caballero scatter, adaptor.valueToStore(), ptrs, adaptor.mask(), 45219dbb230Saartbik rewriter.getI32IntegerAttr(align)); 45319dbb230Saartbik return success(); 45419dbb230Saartbik } 45519dbb230Saartbik }; 45619dbb230Saartbik 457e8dcf5f8Saartbik /// Conversion pattern for a vector.expandload. 458563879b6SRahul Joshi class VectorExpandLoadOpConversion 459563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::ExpandLoadOp> { 460e8dcf5f8Saartbik public: 461563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::ExpandLoadOp>::ConvertOpToLLVMPattern; 462e8dcf5f8Saartbik 463e8dcf5f8Saartbik LogicalResult 464563879b6SRahul Joshi matchAndRewrite(vector::ExpandLoadOp expand, ArrayRef<Value> operands, 465e8dcf5f8Saartbik ConversionPatternRewriter &rewriter) const override { 466563879b6SRahul Joshi auto loc = expand->getLoc(); 467e8dcf5f8Saartbik auto adaptor = vector::ExpandLoadOpAdaptor(operands); 468a57def30SAart Bik MemRefType memRefType = expand.getMemRefType(); 469e8dcf5f8Saartbik 470a57def30SAart Bik // Resolve address. 471656674a7SDiego Caballero auto vtype = typeConverter->convertType(expand.getVectorType()); 472df5ccf5aSAart Bik Value ptr = getStridedElementPtr(loc, memRefType, adaptor.base(), 473a57def30SAart Bik adaptor.indices(), rewriter); 474e8dcf5f8Saartbik 475e8dcf5f8Saartbik rewriter.replaceOpWithNewOp<LLVM::masked_expandload>( 476a57def30SAart Bik expand, vtype, ptr, adaptor.mask(), adaptor.pass_thru()); 477e8dcf5f8Saartbik return success(); 478e8dcf5f8Saartbik } 479e8dcf5f8Saartbik }; 480e8dcf5f8Saartbik 481e8dcf5f8Saartbik /// Conversion pattern for a vector.compressstore. 482563879b6SRahul Joshi class VectorCompressStoreOpConversion 483563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::CompressStoreOp> { 484e8dcf5f8Saartbik public: 485563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::CompressStoreOp>::ConvertOpToLLVMPattern; 486e8dcf5f8Saartbik 487e8dcf5f8Saartbik LogicalResult 488563879b6SRahul Joshi matchAndRewrite(vector::CompressStoreOp compress, ArrayRef<Value> operands, 489e8dcf5f8Saartbik ConversionPatternRewriter &rewriter) const override { 490563879b6SRahul Joshi auto loc = compress->getLoc(); 491e8dcf5f8Saartbik auto adaptor = vector::CompressStoreOpAdaptor(operands); 492a57def30SAart Bik MemRefType memRefType = compress.getMemRefType(); 493e8dcf5f8Saartbik 494a57def30SAart Bik // Resolve address. 495df5ccf5aSAart Bik Value ptr = getStridedElementPtr(loc, memRefType, adaptor.base(), 496a57def30SAart Bik adaptor.indices(), rewriter); 497e8dcf5f8Saartbik 498e8dcf5f8Saartbik rewriter.replaceOpWithNewOp<LLVM::masked_compressstore>( 499656674a7SDiego Caballero compress, adaptor.valueToStore(), ptr, adaptor.mask()); 500e8dcf5f8Saartbik return success(); 501e8dcf5f8Saartbik } 502e8dcf5f8Saartbik }; 503e8dcf5f8Saartbik 50419dbb230Saartbik /// Conversion pattern for all vector reductions. 505563879b6SRahul Joshi class VectorReductionOpConversion 506563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::ReductionOp> { 507e83b7b99Saartbik public: 508563879b6SRahul Joshi explicit VectorReductionOpConversion(LLVMTypeConverter &typeConv, 509060c9dd1Saartbik bool reassociateFPRed) 510563879b6SRahul Joshi : ConvertOpToLLVMPattern<vector::ReductionOp>(typeConv), 511060c9dd1Saartbik reassociateFPReductions(reassociateFPRed) {} 512e83b7b99Saartbik 5133145427dSRiver Riddle LogicalResult 514563879b6SRahul Joshi matchAndRewrite(vector::ReductionOp reductionOp, ArrayRef<Value> operands, 515e83b7b99Saartbik ConversionPatternRewriter &rewriter) const override { 516e83b7b99Saartbik auto kind = reductionOp.kind(); 517e83b7b99Saartbik Type eltType = reductionOp.dest().getType(); 518dcec2ca5SChristian Sigg Type llvmType = typeConverter->convertType(eltType); 519e9628955SAart Bik if (eltType.isIntOrIndex()) { 520e83b7b99Saartbik // Integer reductions: add/mul/min/max/and/or/xor. 521e83b7b99Saartbik if (kind == "add") 522322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_add>( 523563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 524e83b7b99Saartbik else if (kind == "mul") 525322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_mul>( 526563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 527e9628955SAart Bik else if (kind == "min" && 528e9628955SAart Bik (eltType.isIndex() || eltType.isUnsignedInteger())) 529322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_umin>( 530563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 531e83b7b99Saartbik else if (kind == "min") 532322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_smin>( 533563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 534e9628955SAart Bik else if (kind == "max" && 535e9628955SAart Bik (eltType.isIndex() || eltType.isUnsignedInteger())) 536322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_umax>( 537563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 538e83b7b99Saartbik else if (kind == "max") 539322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_smax>( 540563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 541e83b7b99Saartbik else if (kind == "and") 542322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_and>( 543563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 544e83b7b99Saartbik else if (kind == "or") 545322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_or>( 546563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 547e83b7b99Saartbik else if (kind == "xor") 548322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_xor>( 549563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 550e83b7b99Saartbik else 5513145427dSRiver Riddle return failure(); 5523145427dSRiver Riddle return success(); 553dcec2ca5SChristian Sigg } 554e83b7b99Saartbik 555dcec2ca5SChristian Sigg if (!eltType.isa<FloatType>()) 556dcec2ca5SChristian Sigg return failure(); 557dcec2ca5SChristian Sigg 558e83b7b99Saartbik // Floating-point reductions: add/mul/min/max 559e83b7b99Saartbik if (kind == "add") { 5600d924700Saartbik // Optional accumulator (or zero). 5610d924700Saartbik Value acc = operands.size() > 1 ? operands[1] 5620d924700Saartbik : rewriter.create<LLVM::ConstantOp>( 563563879b6SRahul Joshi reductionOp->getLoc(), llvmType, 5640d924700Saartbik rewriter.getZeroAttr(eltType)); 565322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_fadd>( 566563879b6SRahul Joshi reductionOp, llvmType, acc, operands[0], 567ceb1b327Saartbik rewriter.getBoolAttr(reassociateFPReductions)); 568e83b7b99Saartbik } else if (kind == "mul") { 5690d924700Saartbik // Optional accumulator (or one). 5700d924700Saartbik Value acc = operands.size() > 1 5710d924700Saartbik ? operands[1] 5720d924700Saartbik : rewriter.create<LLVM::ConstantOp>( 573563879b6SRahul Joshi reductionOp->getLoc(), llvmType, 5740d924700Saartbik rewriter.getFloatAttr(eltType, 1.0)); 575322d0afdSAmara Emerson rewriter.replaceOpWithNewOp<LLVM::vector_reduce_fmul>( 576563879b6SRahul Joshi reductionOp, llvmType, acc, operands[0], 577ceb1b327Saartbik rewriter.getBoolAttr(reassociateFPReductions)); 578e83b7b99Saartbik } else if (kind == "min") 579563879b6SRahul Joshi rewriter.replaceOpWithNewOp<LLVM::vector_reduce_fmin>( 580563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 581e83b7b99Saartbik else if (kind == "max") 582563879b6SRahul Joshi rewriter.replaceOpWithNewOp<LLVM::vector_reduce_fmax>( 583563879b6SRahul Joshi reductionOp, llvmType, operands[0]); 584e83b7b99Saartbik else 5853145427dSRiver Riddle return failure(); 5863145427dSRiver Riddle return success(); 587e83b7b99Saartbik } 588ceb1b327Saartbik 589ceb1b327Saartbik private: 590ceb1b327Saartbik const bool reassociateFPReductions; 591e83b7b99Saartbik }; 592e83b7b99Saartbik 593563879b6SRahul Joshi class VectorShuffleOpConversion 594563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::ShuffleOp> { 5951c81adf3SAart Bik public: 596563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::ShuffleOp>::ConvertOpToLLVMPattern; 5971c81adf3SAart Bik 5983145427dSRiver Riddle LogicalResult 599563879b6SRahul Joshi matchAndRewrite(vector::ShuffleOp shuffleOp, ArrayRef<Value> operands, 6001c81adf3SAart Bik ConversionPatternRewriter &rewriter) const override { 601563879b6SRahul Joshi auto loc = shuffleOp->getLoc(); 6022d2c73c5SJacques Pienaar auto adaptor = vector::ShuffleOpAdaptor(operands); 6031c81adf3SAart Bik auto v1Type = shuffleOp.getV1VectorType(); 6041c81adf3SAart Bik auto v2Type = shuffleOp.getV2VectorType(); 6051c81adf3SAart Bik auto vectorType = shuffleOp.getVectorType(); 606dcec2ca5SChristian Sigg Type llvmType = typeConverter->convertType(vectorType); 6071c81adf3SAart Bik auto maskArrayAttr = shuffleOp.mask(); 6081c81adf3SAart Bik 6091c81adf3SAart Bik // Bail if result type cannot be lowered. 6101c81adf3SAart Bik if (!llvmType) 6113145427dSRiver Riddle return failure(); 6121c81adf3SAart Bik 6131c81adf3SAart Bik // Get rank and dimension sizes. 6141c81adf3SAart Bik int64_t rank = vectorType.getRank(); 6151c81adf3SAart Bik assert(v1Type.getRank() == rank); 6161c81adf3SAart Bik assert(v2Type.getRank() == rank); 6171c81adf3SAart Bik int64_t v1Dim = v1Type.getDimSize(0); 6181c81adf3SAart Bik 6191c81adf3SAart Bik // For rank 1, where both operands have *exactly* the same vector type, 6201c81adf3SAart Bik // there is direct shuffle support in LLVM. Use it! 6211c81adf3SAart Bik if (rank == 1 && v1Type == v2Type) { 622563879b6SRahul Joshi Value llvmShuffleOp = rewriter.create<LLVM::ShuffleVectorOp>( 6231c81adf3SAart Bik loc, adaptor.v1(), adaptor.v2(), maskArrayAttr); 624563879b6SRahul Joshi rewriter.replaceOp(shuffleOp, llvmShuffleOp); 6253145427dSRiver Riddle return success(); 626b36aaeafSAart Bik } 627b36aaeafSAart Bik 6281c81adf3SAart Bik // For all other cases, insert the individual values individually. 629e62a6956SRiver Riddle Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType); 6301c81adf3SAart Bik int64_t insPos = 0; 6311c81adf3SAart Bik for (auto en : llvm::enumerate(maskArrayAttr)) { 6321c81adf3SAart Bik int64_t extPos = en.value().cast<IntegerAttr>().getInt(); 633e62a6956SRiver Riddle Value value = adaptor.v1(); 6341c81adf3SAart Bik if (extPos >= v1Dim) { 6351c81adf3SAart Bik extPos -= v1Dim; 6361c81adf3SAart Bik value = adaptor.v2(); 637b36aaeafSAart Bik } 638dcec2ca5SChristian Sigg Value extract = extractOne(rewriter, *getTypeConverter(), loc, value, 639dcec2ca5SChristian Sigg llvmType, rank, extPos); 640dcec2ca5SChristian Sigg insert = insertOne(rewriter, *getTypeConverter(), loc, insert, extract, 6410f04384dSAlex Zinenko llvmType, rank, insPos++); 6421c81adf3SAart Bik } 643563879b6SRahul Joshi rewriter.replaceOp(shuffleOp, insert); 6443145427dSRiver Riddle return success(); 645b36aaeafSAart Bik } 646b36aaeafSAart Bik }; 647b36aaeafSAart Bik 648563879b6SRahul Joshi class VectorExtractElementOpConversion 649563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::ExtractElementOp> { 650cd5dab8aSAart Bik public: 651563879b6SRahul Joshi using ConvertOpToLLVMPattern< 652563879b6SRahul Joshi vector::ExtractElementOp>::ConvertOpToLLVMPattern; 653cd5dab8aSAart Bik 6543145427dSRiver Riddle LogicalResult 655563879b6SRahul Joshi matchAndRewrite(vector::ExtractElementOp extractEltOp, 656563879b6SRahul Joshi ArrayRef<Value> operands, 657cd5dab8aSAart Bik ConversionPatternRewriter &rewriter) const override { 6582d2c73c5SJacques Pienaar auto adaptor = vector::ExtractElementOpAdaptor(operands); 659cd5dab8aSAart Bik auto vectorType = extractEltOp.getVectorType(); 660dcec2ca5SChristian Sigg auto llvmType = typeConverter->convertType(vectorType.getElementType()); 661cd5dab8aSAart Bik 662cd5dab8aSAart Bik // Bail if result type cannot be lowered. 663cd5dab8aSAart Bik if (!llvmType) 6643145427dSRiver Riddle return failure(); 665cd5dab8aSAart Bik 666cd5dab8aSAart Bik rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>( 667563879b6SRahul Joshi extractEltOp, llvmType, adaptor.vector(), adaptor.position()); 6683145427dSRiver Riddle return success(); 669cd5dab8aSAart Bik } 670cd5dab8aSAart Bik }; 671cd5dab8aSAart Bik 672563879b6SRahul Joshi class VectorExtractOpConversion 673563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::ExtractOp> { 6745c0c51a9SNicolas Vasilache public: 675563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::ExtractOp>::ConvertOpToLLVMPattern; 6765c0c51a9SNicolas Vasilache 6773145427dSRiver Riddle LogicalResult 678563879b6SRahul Joshi matchAndRewrite(vector::ExtractOp extractOp, ArrayRef<Value> operands, 6795c0c51a9SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 680563879b6SRahul Joshi auto loc = extractOp->getLoc(); 6812d2c73c5SJacques Pienaar auto adaptor = vector::ExtractOpAdaptor(operands); 6829826fe5cSAart Bik auto vectorType = extractOp.getVectorType(); 6832bdf33ccSRiver Riddle auto resultType = extractOp.getResult().getType(); 684dcec2ca5SChristian Sigg auto llvmResultType = typeConverter->convertType(resultType); 6855c0c51a9SNicolas Vasilache auto positionArrayAttr = extractOp.position(); 6869826fe5cSAart Bik 6879826fe5cSAart Bik // Bail if result type cannot be lowered. 6889826fe5cSAart Bik if (!llvmResultType) 6893145427dSRiver Riddle return failure(); 6909826fe5cSAart Bik 691864adf39SMatthias Springer // Extract entire vector. Should be handled by folder, but just to be safe. 692864adf39SMatthias Springer if (positionArrayAttr.empty()) { 693864adf39SMatthias Springer rewriter.replaceOp(extractOp, adaptor.vector()); 694864adf39SMatthias Springer return success(); 695864adf39SMatthias Springer } 696864adf39SMatthias Springer 6975c0c51a9SNicolas Vasilache // One-shot extraction of vector from array (only requires extractvalue). 6985c0c51a9SNicolas Vasilache if (resultType.isa<VectorType>()) { 699e62a6956SRiver Riddle Value extracted = rewriter.create<LLVM::ExtractValueOp>( 7005c0c51a9SNicolas Vasilache loc, llvmResultType, adaptor.vector(), positionArrayAttr); 701563879b6SRahul Joshi rewriter.replaceOp(extractOp, extracted); 7023145427dSRiver Riddle return success(); 7035c0c51a9SNicolas Vasilache } 7045c0c51a9SNicolas Vasilache 7059826fe5cSAart Bik // Potential extraction of 1-D vector from array. 706563879b6SRahul Joshi auto *context = extractOp->getContext(); 707e62a6956SRiver Riddle Value extracted = adaptor.vector(); 7085c0c51a9SNicolas Vasilache auto positionAttrs = positionArrayAttr.getValue(); 7095c0c51a9SNicolas Vasilache if (positionAttrs.size() > 1) { 7109826fe5cSAart Bik auto oneDVectorType = reducedVectorTypeBack(vectorType); 7115c0c51a9SNicolas Vasilache auto nMinusOnePositionAttrs = 712c2c83e97STres Popp ArrayAttr::get(context, positionAttrs.drop_back()); 7135c0c51a9SNicolas Vasilache extracted = rewriter.create<LLVM::ExtractValueOp>( 714dcec2ca5SChristian Sigg loc, typeConverter->convertType(oneDVectorType), extracted, 7155c0c51a9SNicolas Vasilache nMinusOnePositionAttrs); 7165c0c51a9SNicolas Vasilache } 7175c0c51a9SNicolas Vasilache 7185c0c51a9SNicolas Vasilache // Remaining extraction of element from 1-D LLVM vector 7195c0c51a9SNicolas Vasilache auto position = positionAttrs.back().cast<IntegerAttr>(); 7202230bf99SAlex Zinenko auto i64Type = IntegerType::get(rewriter.getContext(), 64); 7211d47564aSAart Bik auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 7225c0c51a9SNicolas Vasilache extracted = 7235c0c51a9SNicolas Vasilache rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant); 724563879b6SRahul Joshi rewriter.replaceOp(extractOp, extracted); 7255c0c51a9SNicolas Vasilache 7263145427dSRiver Riddle return success(); 7275c0c51a9SNicolas Vasilache } 7285c0c51a9SNicolas Vasilache }; 7295c0c51a9SNicolas Vasilache 730681f929fSNicolas Vasilache /// Conversion pattern that turns a vector.fma on a 1-D vector 731681f929fSNicolas Vasilache /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion. 732681f929fSNicolas Vasilache /// This does not match vectors of n >= 2 rank. 733681f929fSNicolas Vasilache /// 734681f929fSNicolas Vasilache /// Example: 735681f929fSNicolas Vasilache /// ``` 736681f929fSNicolas Vasilache /// vector.fma %a, %a, %a : vector<8xf32> 737681f929fSNicolas Vasilache /// ``` 738681f929fSNicolas Vasilache /// is converted to: 739681f929fSNicolas Vasilache /// ``` 7403bffe602SBenjamin Kramer /// llvm.intr.fmuladd %va, %va, %va: 741dd5165a9SAlex Zinenko /// (!llvm."<8 x f32>">, !llvm<"<8 x f32>">, !llvm<"<8 x f32>">) 742dd5165a9SAlex Zinenko /// -> !llvm."<8 x f32>"> 743681f929fSNicolas Vasilache /// ``` 744563879b6SRahul Joshi class VectorFMAOp1DConversion : public ConvertOpToLLVMPattern<vector::FMAOp> { 745681f929fSNicolas Vasilache public: 746563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::FMAOp>::ConvertOpToLLVMPattern; 747681f929fSNicolas Vasilache 7483145427dSRiver Riddle LogicalResult 749563879b6SRahul Joshi matchAndRewrite(vector::FMAOp fmaOp, ArrayRef<Value> operands, 750681f929fSNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 7512d2c73c5SJacques Pienaar auto adaptor = vector::FMAOpAdaptor(operands); 752681f929fSNicolas Vasilache VectorType vType = fmaOp.getVectorType(); 753681f929fSNicolas Vasilache if (vType.getRank() != 1) 7543145427dSRiver Riddle return failure(); 755563879b6SRahul Joshi rewriter.replaceOpWithNewOp<LLVM::FMulAddOp>(fmaOp, adaptor.lhs(), 7563bffe602SBenjamin Kramer adaptor.rhs(), adaptor.acc()); 7573145427dSRiver Riddle return success(); 758681f929fSNicolas Vasilache } 759681f929fSNicolas Vasilache }; 760681f929fSNicolas Vasilache 761563879b6SRahul Joshi class VectorInsertElementOpConversion 762563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::InsertElementOp> { 763cd5dab8aSAart Bik public: 764563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::InsertElementOp>::ConvertOpToLLVMPattern; 765cd5dab8aSAart Bik 7663145427dSRiver Riddle LogicalResult 767563879b6SRahul Joshi matchAndRewrite(vector::InsertElementOp insertEltOp, ArrayRef<Value> operands, 768cd5dab8aSAart Bik ConversionPatternRewriter &rewriter) const override { 7692d2c73c5SJacques Pienaar auto adaptor = vector::InsertElementOpAdaptor(operands); 770cd5dab8aSAart Bik auto vectorType = insertEltOp.getDestVectorType(); 771dcec2ca5SChristian Sigg auto llvmType = typeConverter->convertType(vectorType); 772cd5dab8aSAart Bik 773cd5dab8aSAart Bik // Bail if result type cannot be lowered. 774cd5dab8aSAart Bik if (!llvmType) 7753145427dSRiver Riddle return failure(); 776cd5dab8aSAart Bik 777cd5dab8aSAart Bik rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>( 778563879b6SRahul Joshi insertEltOp, llvmType, adaptor.dest(), adaptor.source(), 779563879b6SRahul Joshi adaptor.position()); 7803145427dSRiver Riddle return success(); 781cd5dab8aSAart Bik } 782cd5dab8aSAart Bik }; 783cd5dab8aSAart Bik 784563879b6SRahul Joshi class VectorInsertOpConversion 785563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::InsertOp> { 7869826fe5cSAart Bik public: 787563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::InsertOp>::ConvertOpToLLVMPattern; 7889826fe5cSAart Bik 7893145427dSRiver Riddle LogicalResult 790563879b6SRahul Joshi matchAndRewrite(vector::InsertOp insertOp, ArrayRef<Value> operands, 7919826fe5cSAart Bik ConversionPatternRewriter &rewriter) const override { 792563879b6SRahul Joshi auto loc = insertOp->getLoc(); 7932d2c73c5SJacques Pienaar auto adaptor = vector::InsertOpAdaptor(operands); 7949826fe5cSAart Bik auto sourceType = insertOp.getSourceType(); 7959826fe5cSAart Bik auto destVectorType = insertOp.getDestVectorType(); 796dcec2ca5SChristian Sigg auto llvmResultType = typeConverter->convertType(destVectorType); 7979826fe5cSAart Bik auto positionArrayAttr = insertOp.position(); 7989826fe5cSAart Bik 7999826fe5cSAart Bik // Bail if result type cannot be lowered. 8009826fe5cSAart Bik if (!llvmResultType) 8013145427dSRiver Riddle return failure(); 8029826fe5cSAart Bik 803864adf39SMatthias Springer // Overwrite entire vector with value. Should be handled by folder, but 804864adf39SMatthias Springer // just to be safe. 805864adf39SMatthias Springer if (positionArrayAttr.empty()) { 806864adf39SMatthias Springer rewriter.replaceOp(insertOp, adaptor.source()); 807864adf39SMatthias Springer return success(); 808864adf39SMatthias Springer } 809864adf39SMatthias Springer 8109826fe5cSAart Bik // One-shot insertion of a vector into an array (only requires insertvalue). 8119826fe5cSAart Bik if (sourceType.isa<VectorType>()) { 812e62a6956SRiver Riddle Value inserted = rewriter.create<LLVM::InsertValueOp>( 8139826fe5cSAart Bik loc, llvmResultType, adaptor.dest(), adaptor.source(), 8149826fe5cSAart Bik positionArrayAttr); 815563879b6SRahul Joshi rewriter.replaceOp(insertOp, inserted); 8163145427dSRiver Riddle return success(); 8179826fe5cSAart Bik } 8189826fe5cSAart Bik 8199826fe5cSAart Bik // Potential extraction of 1-D vector from array. 820563879b6SRahul Joshi auto *context = insertOp->getContext(); 821e62a6956SRiver Riddle Value extracted = adaptor.dest(); 8229826fe5cSAart Bik auto positionAttrs = positionArrayAttr.getValue(); 8239826fe5cSAart Bik auto position = positionAttrs.back().cast<IntegerAttr>(); 8249826fe5cSAart Bik auto oneDVectorType = destVectorType; 8259826fe5cSAart Bik if (positionAttrs.size() > 1) { 8269826fe5cSAart Bik oneDVectorType = reducedVectorTypeBack(destVectorType); 8279826fe5cSAart Bik auto nMinusOnePositionAttrs = 828c2c83e97STres Popp ArrayAttr::get(context, positionAttrs.drop_back()); 8299826fe5cSAart Bik extracted = rewriter.create<LLVM::ExtractValueOp>( 830dcec2ca5SChristian Sigg loc, typeConverter->convertType(oneDVectorType), extracted, 8319826fe5cSAart Bik nMinusOnePositionAttrs); 8329826fe5cSAart Bik } 8339826fe5cSAart Bik 8349826fe5cSAart Bik // Insertion of an element into a 1-D LLVM vector. 8352230bf99SAlex Zinenko auto i64Type = IntegerType::get(rewriter.getContext(), 64); 8361d47564aSAart Bik auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 837e62a6956SRiver Riddle Value inserted = rewriter.create<LLVM::InsertElementOp>( 838dcec2ca5SChristian Sigg loc, typeConverter->convertType(oneDVectorType), extracted, 8390f04384dSAlex Zinenko adaptor.source(), constant); 8409826fe5cSAart Bik 8419826fe5cSAart Bik // Potential insertion of resulting 1-D vector into array. 8429826fe5cSAart Bik if (positionAttrs.size() > 1) { 8439826fe5cSAart Bik auto nMinusOnePositionAttrs = 844c2c83e97STres Popp ArrayAttr::get(context, positionAttrs.drop_back()); 8459826fe5cSAart Bik inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType, 8469826fe5cSAart Bik adaptor.dest(), inserted, 8479826fe5cSAart Bik nMinusOnePositionAttrs); 8489826fe5cSAart Bik } 8499826fe5cSAart Bik 850563879b6SRahul Joshi rewriter.replaceOp(insertOp, inserted); 8513145427dSRiver Riddle return success(); 8529826fe5cSAart Bik } 8539826fe5cSAart Bik }; 8549826fe5cSAart Bik 855681f929fSNicolas Vasilache /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1. 856681f929fSNicolas Vasilache /// 857681f929fSNicolas Vasilache /// Example: 858681f929fSNicolas Vasilache /// ``` 859681f929fSNicolas Vasilache /// %d = vector.fma %a, %b, %c : vector<2x4xf32> 860681f929fSNicolas Vasilache /// ``` 861681f929fSNicolas Vasilache /// is rewritten into: 862681f929fSNicolas Vasilache /// ``` 863681f929fSNicolas Vasilache /// %r = splat %f0: vector<2x4xf32> 864681f929fSNicolas Vasilache /// %va = vector.extractvalue %a[0] : vector<2x4xf32> 865681f929fSNicolas Vasilache /// %vb = vector.extractvalue %b[0] : vector<2x4xf32> 866681f929fSNicolas Vasilache /// %vc = vector.extractvalue %c[0] : vector<2x4xf32> 867681f929fSNicolas Vasilache /// %vd = vector.fma %va, %vb, %vc : vector<4xf32> 868681f929fSNicolas Vasilache /// %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32> 869681f929fSNicolas Vasilache /// %va2 = vector.extractvalue %a2[1] : vector<2x4xf32> 870681f929fSNicolas Vasilache /// %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32> 871681f929fSNicolas Vasilache /// %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32> 872681f929fSNicolas Vasilache /// %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32> 873681f929fSNicolas Vasilache /// %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32> 874681f929fSNicolas Vasilache /// // %r3 holds the final value. 875681f929fSNicolas Vasilache /// ``` 876681f929fSNicolas Vasilache class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> { 877681f929fSNicolas Vasilache public: 878681f929fSNicolas Vasilache using OpRewritePattern<FMAOp>::OpRewritePattern; 879681f929fSNicolas Vasilache 8803145427dSRiver Riddle LogicalResult matchAndRewrite(FMAOp op, 881681f929fSNicolas Vasilache PatternRewriter &rewriter) const override { 882681f929fSNicolas Vasilache auto vType = op.getVectorType(); 883681f929fSNicolas Vasilache if (vType.getRank() < 2) 8843145427dSRiver Riddle return failure(); 885681f929fSNicolas Vasilache 886681f929fSNicolas Vasilache auto loc = op.getLoc(); 887681f929fSNicolas Vasilache auto elemType = vType.getElementType(); 888681f929fSNicolas Vasilache Value zero = rewriter.create<ConstantOp>(loc, elemType, 889681f929fSNicolas Vasilache rewriter.getZeroAttr(elemType)); 890681f929fSNicolas Vasilache Value desc = rewriter.create<SplatOp>(loc, vType, zero); 891681f929fSNicolas Vasilache for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) { 892681f929fSNicolas Vasilache Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i); 893681f929fSNicolas Vasilache Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i); 894681f929fSNicolas Vasilache Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i); 895681f929fSNicolas Vasilache Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC); 896681f929fSNicolas Vasilache desc = rewriter.create<InsertOp>(loc, fma, desc, i); 897681f929fSNicolas Vasilache } 898681f929fSNicolas Vasilache rewriter.replaceOp(op, desc); 8993145427dSRiver Riddle return success(); 900681f929fSNicolas Vasilache } 901681f929fSNicolas Vasilache }; 902681f929fSNicolas Vasilache 9032d515e49SNicolas Vasilache // When ranks are different, InsertStridedSlice needs to extract a properly 9042d515e49SNicolas Vasilache // ranked vector from the destination vector into which to insert. This pattern 9052d515e49SNicolas Vasilache // only takes care of this part and forwards the rest of the conversion to 9062d515e49SNicolas Vasilache // another pattern that converts InsertStridedSlice for operands of the same 9072d515e49SNicolas Vasilache // rank. 9082d515e49SNicolas Vasilache // 9092d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors 9102d515e49SNicolas Vasilache // have different ranks. In this case: 9112d515e49SNicolas Vasilache // 1. the proper subvector is extracted from the destination vector 9122d515e49SNicolas Vasilache // 2. a new InsertStridedSlice op is created to insert the source in the 9132d515e49SNicolas Vasilache // destination subvector 9142d515e49SNicolas Vasilache // 3. the destination subvector is inserted back in the proper place 9152d515e49SNicolas Vasilache // 4. the op is replaced by the result of step 3. 9162d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a 9172d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`. 9182d515e49SNicolas Vasilache class VectorInsertStridedSliceOpDifferentRankRewritePattern 9192d515e49SNicolas Vasilache : public OpRewritePattern<InsertStridedSliceOp> { 9202d515e49SNicolas Vasilache public: 9212d515e49SNicolas Vasilache using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 9222d515e49SNicolas Vasilache 9233145427dSRiver Riddle LogicalResult matchAndRewrite(InsertStridedSliceOp op, 9242d515e49SNicolas Vasilache PatternRewriter &rewriter) const override { 9252d515e49SNicolas Vasilache auto srcType = op.getSourceVectorType(); 9262d515e49SNicolas Vasilache auto dstType = op.getDestVectorType(); 9272d515e49SNicolas Vasilache 9282d515e49SNicolas Vasilache if (op.offsets().getValue().empty()) 9293145427dSRiver Riddle return failure(); 9302d515e49SNicolas Vasilache 9312d515e49SNicolas Vasilache auto loc = op.getLoc(); 9322d515e49SNicolas Vasilache int64_t rankDiff = dstType.getRank() - srcType.getRank(); 9332d515e49SNicolas Vasilache assert(rankDiff >= 0); 9342d515e49SNicolas Vasilache if (rankDiff == 0) 9353145427dSRiver Riddle return failure(); 9362d515e49SNicolas Vasilache 9372d515e49SNicolas Vasilache int64_t rankRest = dstType.getRank() - rankDiff; 9382d515e49SNicolas Vasilache // Extract / insert the subvector of matching rank and InsertStridedSlice 9392d515e49SNicolas Vasilache // on it. 9402d515e49SNicolas Vasilache Value extracted = 9412d515e49SNicolas Vasilache rewriter.create<ExtractOp>(loc, op.dest(), 9422d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/0, 943dcec2ca5SChristian Sigg /*dropBack=*/rankRest)); 9442d515e49SNicolas Vasilache // A different pattern will kick in for InsertStridedSlice with matching 9452d515e49SNicolas Vasilache // ranks. 9462d515e49SNicolas Vasilache auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>( 9472d515e49SNicolas Vasilache loc, op.source(), extracted, 9482d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/rankDiff), 949c8fc76a9Saartbik getI64SubArray(op.strides(), /*dropFront=*/0)); 9502d515e49SNicolas Vasilache rewriter.replaceOpWithNewOp<InsertOp>( 9512d515e49SNicolas Vasilache op, stridedSliceInnerOp.getResult(), op.dest(), 9522d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/0, 953dcec2ca5SChristian Sigg /*dropBack=*/rankRest)); 9543145427dSRiver Riddle return success(); 9552d515e49SNicolas Vasilache } 9562d515e49SNicolas Vasilache }; 9572d515e49SNicolas Vasilache 9582d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors 9592d515e49SNicolas Vasilache // have the same rank. In this case, we reduce 9602d515e49SNicolas Vasilache // 1. the proper subvector is extracted from the destination vector 9612d515e49SNicolas Vasilache // 2. a new InsertStridedSlice op is created to insert the source in the 9622d515e49SNicolas Vasilache // destination subvector 9632d515e49SNicolas Vasilache // 3. the destination subvector is inserted back in the proper place 9642d515e49SNicolas Vasilache // 4. the op is replaced by the result of step 3. 9652d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a 9662d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`. 9672d515e49SNicolas Vasilache class VectorInsertStridedSliceOpSameRankRewritePattern 9682d515e49SNicolas Vasilache : public OpRewritePattern<InsertStridedSliceOp> { 9692d515e49SNicolas Vasilache public: 9702257e4a7SRiver Riddle using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 9712257e4a7SRiver Riddle 9722257e4a7SRiver Riddle void initialize() { 973b99bd771SRiver Riddle // This pattern creates recursive InsertStridedSliceOp, but the recursion is 974b99bd771SRiver Riddle // bounded as the rank is strictly decreasing. 975b99bd771SRiver Riddle setHasBoundedRewriteRecursion(); 976b99bd771SRiver Riddle } 9772d515e49SNicolas Vasilache 9783145427dSRiver Riddle LogicalResult matchAndRewrite(InsertStridedSliceOp op, 9792d515e49SNicolas Vasilache PatternRewriter &rewriter) const override { 9802d515e49SNicolas Vasilache auto srcType = op.getSourceVectorType(); 9812d515e49SNicolas Vasilache auto dstType = op.getDestVectorType(); 9822d515e49SNicolas Vasilache 9832d515e49SNicolas Vasilache if (op.offsets().getValue().empty()) 9843145427dSRiver Riddle return failure(); 9852d515e49SNicolas Vasilache 9862d515e49SNicolas Vasilache int64_t rankDiff = dstType.getRank() - srcType.getRank(); 9872d515e49SNicolas Vasilache assert(rankDiff >= 0); 9882d515e49SNicolas Vasilache if (rankDiff != 0) 9893145427dSRiver Riddle return failure(); 9902d515e49SNicolas Vasilache 9912d515e49SNicolas Vasilache if (srcType == dstType) { 9922d515e49SNicolas Vasilache rewriter.replaceOp(op, op.source()); 9933145427dSRiver Riddle return success(); 9942d515e49SNicolas Vasilache } 9952d515e49SNicolas Vasilache 9962d515e49SNicolas Vasilache int64_t offset = 9972d515e49SNicolas Vasilache op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 9982d515e49SNicolas Vasilache int64_t size = srcType.getShape().front(); 9992d515e49SNicolas Vasilache int64_t stride = 10002d515e49SNicolas Vasilache op.strides().getValue().front().cast<IntegerAttr>().getInt(); 10012d515e49SNicolas Vasilache 10022d515e49SNicolas Vasilache auto loc = op.getLoc(); 10032d515e49SNicolas Vasilache Value res = op.dest(); 10042d515e49SNicolas Vasilache // For each slice of the source vector along the most major dimension. 10052d515e49SNicolas Vasilache for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 10062d515e49SNicolas Vasilache off += stride, ++idx) { 10072d515e49SNicolas Vasilache // 1. extract the proper subvector (or element) from source 10082d515e49SNicolas Vasilache Value extractedSource = extractOne(rewriter, loc, op.source(), idx); 10092d515e49SNicolas Vasilache if (extractedSource.getType().isa<VectorType>()) { 10102d515e49SNicolas Vasilache // 2. If we have a vector, extract the proper subvector from destination 10112d515e49SNicolas Vasilache // Otherwise we are at the element level and no need to recurse. 10122d515e49SNicolas Vasilache Value extractedDest = extractOne(rewriter, loc, op.dest(), off); 10132d515e49SNicolas Vasilache // 3. Reduce the problem to lowering a new InsertStridedSlice op with 10142d515e49SNicolas Vasilache // smaller rank. 1015bd1ccfe6SRiver Riddle extractedSource = rewriter.create<InsertStridedSliceOp>( 10162d515e49SNicolas Vasilache loc, extractedSource, extractedDest, 10172d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /* dropFront=*/1), 10182d515e49SNicolas Vasilache getI64SubArray(op.strides(), /* dropFront=*/1)); 10192d515e49SNicolas Vasilache } 10202d515e49SNicolas Vasilache // 4. Insert the extractedSource into the res vector. 10212d515e49SNicolas Vasilache res = insertOne(rewriter, loc, extractedSource, res, off); 10222d515e49SNicolas Vasilache } 10232d515e49SNicolas Vasilache 10242d515e49SNicolas Vasilache rewriter.replaceOp(op, res); 10253145427dSRiver Riddle return success(); 10262d515e49SNicolas Vasilache } 10272d515e49SNicolas Vasilache }; 10282d515e49SNicolas Vasilache 10295017b0f8SMatthias Springer /// Return true if the last dimension of the MemRefType has unit stride. Also 10305017b0f8SMatthias Springer /// return true for memrefs with no strides. 10315017b0f8SMatthias Springer static bool isLastMemrefDimUnitStride(MemRefType type) { 10325017b0f8SMatthias Springer int64_t offset; 10335017b0f8SMatthias Springer SmallVector<int64_t> strides; 10345017b0f8SMatthias Springer auto successStrides = getStridesAndOffset(type, strides, offset); 10355017b0f8SMatthias Springer return succeeded(successStrides) && (strides.empty() || strides.back() == 1); 10365017b0f8SMatthias Springer } 10375017b0f8SMatthias Springer 103830e6033bSNicolas Vasilache /// Returns the strides if the memory underlying `memRefType` has a contiguous 103930e6033bSNicolas Vasilache /// static layout. 104030e6033bSNicolas Vasilache static llvm::Optional<SmallVector<int64_t, 4>> 104130e6033bSNicolas Vasilache computeContiguousStrides(MemRefType memRefType) { 10422bf491c7SBenjamin Kramer int64_t offset; 104330e6033bSNicolas Vasilache SmallVector<int64_t, 4> strides; 104430e6033bSNicolas Vasilache if (failed(getStridesAndOffset(memRefType, strides, offset))) 104530e6033bSNicolas Vasilache return None; 104630e6033bSNicolas Vasilache if (!strides.empty() && strides.back() != 1) 104730e6033bSNicolas Vasilache return None; 104830e6033bSNicolas Vasilache // If no layout or identity layout, this is contiguous by definition. 104930e6033bSNicolas Vasilache if (memRefType.getAffineMaps().empty() || 105030e6033bSNicolas Vasilache memRefType.getAffineMaps().front().isIdentity()) 105130e6033bSNicolas Vasilache return strides; 105230e6033bSNicolas Vasilache 105330e6033bSNicolas Vasilache // Otherwise, we must determine contiguity form shapes. This can only ever 105430e6033bSNicolas Vasilache // work in static cases because MemRefType is underspecified to represent 105530e6033bSNicolas Vasilache // contiguous dynamic shapes in other ways than with just empty/identity 105630e6033bSNicolas Vasilache // layout. 10572bf491c7SBenjamin Kramer auto sizes = memRefType.getShape(); 10585017b0f8SMatthias Springer for (int index = 0, e = strides.size() - 1; index < e; ++index) { 105930e6033bSNicolas Vasilache if (ShapedType::isDynamic(sizes[index + 1]) || 106030e6033bSNicolas Vasilache ShapedType::isDynamicStrideOrOffset(strides[index]) || 106130e6033bSNicolas Vasilache ShapedType::isDynamicStrideOrOffset(strides[index + 1])) 106230e6033bSNicolas Vasilache return None; 106330e6033bSNicolas Vasilache if (strides[index] != strides[index + 1] * sizes[index + 1]) 106430e6033bSNicolas Vasilache return None; 10652bf491c7SBenjamin Kramer } 106630e6033bSNicolas Vasilache return strides; 10672bf491c7SBenjamin Kramer } 10682bf491c7SBenjamin Kramer 1069563879b6SRahul Joshi class VectorTypeCastOpConversion 1070563879b6SRahul Joshi : public ConvertOpToLLVMPattern<vector::TypeCastOp> { 10715c0c51a9SNicolas Vasilache public: 1072563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::TypeCastOp>::ConvertOpToLLVMPattern; 10735c0c51a9SNicolas Vasilache 10743145427dSRiver Riddle LogicalResult 1075563879b6SRahul Joshi matchAndRewrite(vector::TypeCastOp castOp, ArrayRef<Value> operands, 10765c0c51a9SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 1077563879b6SRahul Joshi auto loc = castOp->getLoc(); 10785c0c51a9SNicolas Vasilache MemRefType sourceMemRefType = 10792bdf33ccSRiver Riddle castOp.getOperand().getType().cast<MemRefType>(); 10809eb3e564SChris Lattner MemRefType targetMemRefType = castOp.getType(); 10815c0c51a9SNicolas Vasilache 10825c0c51a9SNicolas Vasilache // Only static shape casts supported atm. 10835c0c51a9SNicolas Vasilache if (!sourceMemRefType.hasStaticShape() || 10845c0c51a9SNicolas Vasilache !targetMemRefType.hasStaticShape()) 10853145427dSRiver Riddle return failure(); 10865c0c51a9SNicolas Vasilache 10875c0c51a9SNicolas Vasilache auto llvmSourceDescriptorTy = 10888de43b92SAlex Zinenko operands[0].getType().dyn_cast<LLVM::LLVMStructType>(); 10898de43b92SAlex Zinenko if (!llvmSourceDescriptorTy) 10903145427dSRiver Riddle return failure(); 10915c0c51a9SNicolas Vasilache MemRefDescriptor sourceMemRef(operands[0]); 10925c0c51a9SNicolas Vasilache 1093dcec2ca5SChristian Sigg auto llvmTargetDescriptorTy = typeConverter->convertType(targetMemRefType) 10948de43b92SAlex Zinenko .dyn_cast_or_null<LLVM::LLVMStructType>(); 10958de43b92SAlex Zinenko if (!llvmTargetDescriptorTy) 10963145427dSRiver Riddle return failure(); 10975c0c51a9SNicolas Vasilache 109830e6033bSNicolas Vasilache // Only contiguous source buffers supported atm. 109930e6033bSNicolas Vasilache auto sourceStrides = computeContiguousStrides(sourceMemRefType); 110030e6033bSNicolas Vasilache if (!sourceStrides) 110130e6033bSNicolas Vasilache return failure(); 110230e6033bSNicolas Vasilache auto targetStrides = computeContiguousStrides(targetMemRefType); 110330e6033bSNicolas Vasilache if (!targetStrides) 110430e6033bSNicolas Vasilache return failure(); 110530e6033bSNicolas Vasilache // Only support static strides for now, regardless of contiguity. 110630e6033bSNicolas Vasilache if (llvm::any_of(*targetStrides, [](int64_t stride) { 110730e6033bSNicolas Vasilache return ShapedType::isDynamicStrideOrOffset(stride); 110830e6033bSNicolas Vasilache })) 11093145427dSRiver Riddle return failure(); 11105c0c51a9SNicolas Vasilache 11112230bf99SAlex Zinenko auto int64Ty = IntegerType::get(rewriter.getContext(), 64); 11125c0c51a9SNicolas Vasilache 11135c0c51a9SNicolas Vasilache // Create descriptor. 11145c0c51a9SNicolas Vasilache auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy); 11153a577f54SChristian Sigg Type llvmTargetElementTy = desc.getElementPtrType(); 11165c0c51a9SNicolas Vasilache // Set allocated ptr. 1117e62a6956SRiver Riddle Value allocated = sourceMemRef.allocatedPtr(rewriter, loc); 11185c0c51a9SNicolas Vasilache allocated = 11195c0c51a9SNicolas Vasilache rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated); 11205c0c51a9SNicolas Vasilache desc.setAllocatedPtr(rewriter, loc, allocated); 11215c0c51a9SNicolas Vasilache // Set aligned ptr. 1122e62a6956SRiver Riddle Value ptr = sourceMemRef.alignedPtr(rewriter, loc); 11235c0c51a9SNicolas Vasilache ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr); 11245c0c51a9SNicolas Vasilache desc.setAlignedPtr(rewriter, loc, ptr); 11255c0c51a9SNicolas Vasilache // Fill offset 0. 11265c0c51a9SNicolas Vasilache auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0); 11275c0c51a9SNicolas Vasilache auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr); 11285c0c51a9SNicolas Vasilache desc.setOffset(rewriter, loc, zero); 11295c0c51a9SNicolas Vasilache 11305c0c51a9SNicolas Vasilache // Fill size and stride descriptors in memref. 11315c0c51a9SNicolas Vasilache for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) { 11325c0c51a9SNicolas Vasilache int64_t index = indexedSize.index(); 11335c0c51a9SNicolas Vasilache auto sizeAttr = 11345c0c51a9SNicolas Vasilache rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value()); 11355c0c51a9SNicolas Vasilache auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr); 11365c0c51a9SNicolas Vasilache desc.setSize(rewriter, loc, index, size); 113730e6033bSNicolas Vasilache auto strideAttr = rewriter.getIntegerAttr(rewriter.getIndexType(), 113830e6033bSNicolas Vasilache (*targetStrides)[index]); 11395c0c51a9SNicolas Vasilache auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr); 11405c0c51a9SNicolas Vasilache desc.setStride(rewriter, loc, index, stride); 11415c0c51a9SNicolas Vasilache } 11425c0c51a9SNicolas Vasilache 1143563879b6SRahul Joshi rewriter.replaceOp(castOp, {desc}); 11443145427dSRiver Riddle return success(); 11455c0c51a9SNicolas Vasilache } 11465c0c51a9SNicolas Vasilache }; 11475c0c51a9SNicolas Vasilache 114865a3f289SMatthias Springer /// Conversion pattern that converts a 1-D vector transfer read/write op into a 114965a3f289SMatthias Springer /// a masked or unmasked read/write. 11508345b86dSNicolas Vasilache template <typename ConcreteOp> 1151563879b6SRahul Joshi class VectorTransferConversion : public ConvertOpToLLVMPattern<ConcreteOp> { 11528345b86dSNicolas Vasilache public: 115365a3f289SMatthias Springer using ConvertOpToLLVMPattern<ConcreteOp>::ConvertOpToLLVMPattern; 11548345b86dSNicolas Vasilache 11558345b86dSNicolas Vasilache LogicalResult 1156563879b6SRahul Joshi matchAndRewrite(ConcreteOp xferOp, ArrayRef<Value> operands, 11578345b86dSNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 11588345b86dSNicolas Vasilache auto adaptor = getTransferOpAdapter(xferOp, operands); 1159b2c79c50SNicolas Vasilache 11605017b0f8SMatthias Springer if (xferOp.getVectorType().getRank() > 1 || xferOp.indices().empty()) 11618345b86dSNicolas Vasilache return failure(); 11625f9e0466SNicolas Vasilache if (xferOp.permutation_map() != 11635f9e0466SNicolas Vasilache AffineMap::getMinorIdentityMap(xferOp.permutation_map().getNumInputs(), 11645f9e0466SNicolas Vasilache xferOp.getVectorType().getRank(), 1165563879b6SRahul Joshi xferOp->getContext())) 11668345b86dSNicolas Vasilache return failure(); 116726c8f908SThomas Raoux auto memRefType = xferOp.getShapedType().template dyn_cast<MemRefType>(); 116826c8f908SThomas Raoux if (!memRefType) 116926c8f908SThomas Raoux return failure(); 11705017b0f8SMatthias Springer // Last dimension must be contiguous. (Otherwise: Use VectorToSCF.) 11715017b0f8SMatthias Springer if (!isLastMemrefDimUnitStride(memRefType)) 11722bf491c7SBenjamin Kramer return failure(); 117365a3f289SMatthias Springer // Out-of-bounds dims are handled by MaterializeTransferMask. 117465a3f289SMatthias Springer if (xferOp.hasOutOfBoundsDim()) 117565a3f289SMatthias Springer return failure(); 11768345b86dSNicolas Vasilache 1177563879b6SRahul Joshi auto toLLVMTy = [&](Type t) { 1178563879b6SRahul Joshi return this->getTypeConverter()->convertType(t); 1179563879b6SRahul Joshi }; 11808345b86dSNicolas Vasilache 1181563879b6SRahul Joshi Location loc = xferOp->getLoc(); 11828345b86dSNicolas Vasilache 118368330ee0SThomas Raoux if (auto memrefVectorElementType = 118426c8f908SThomas Raoux memRefType.getElementType().template dyn_cast<VectorType>()) { 118568330ee0SThomas Raoux // Memref has vector element type. 118668330ee0SThomas Raoux if (memrefVectorElementType.getElementType() != 118768330ee0SThomas Raoux xferOp.getVectorType().getElementType()) 118868330ee0SThomas Raoux return failure(); 11890de60b55SThomas Raoux #ifndef NDEBUG 119068330ee0SThomas Raoux // Check that memref vector type is a suffix of 'vectorType. 119168330ee0SThomas Raoux unsigned memrefVecEltRank = memrefVectorElementType.getRank(); 119268330ee0SThomas Raoux unsigned resultVecRank = xferOp.getVectorType().getRank(); 119368330ee0SThomas Raoux assert(memrefVecEltRank <= resultVecRank); 119468330ee0SThomas Raoux // TODO: Move this to isSuffix in Vector/Utils.h. 119568330ee0SThomas Raoux unsigned rankOffset = resultVecRank - memrefVecEltRank; 119668330ee0SThomas Raoux auto memrefVecEltShape = memrefVectorElementType.getShape(); 119768330ee0SThomas Raoux auto resultVecShape = xferOp.getVectorType().getShape(); 119868330ee0SThomas Raoux for (unsigned i = 0; i < memrefVecEltRank; ++i) 119968330ee0SThomas Raoux assert(memrefVecEltShape[i] != resultVecShape[rankOffset + i] && 120068330ee0SThomas Raoux "memref vector element shape should match suffix of vector " 120168330ee0SThomas Raoux "result shape."); 12020de60b55SThomas Raoux #endif // ifndef NDEBUG 120368330ee0SThomas Raoux } 120468330ee0SThomas Raoux 120565a3f289SMatthias Springer // Get the source/dst address as an LLVM vector pointer. 1206a57def30SAart Bik VectorType vtp = xferOp.getVectorType(); 1207563879b6SRahul Joshi Value dataPtr = this->getStridedElementPtr( 120826c8f908SThomas Raoux loc, memRefType, adaptor.source(), adaptor.indices(), rewriter); 1209a57def30SAart Bik Value vectorDataPtr = 1210a57def30SAart Bik castDataPtr(rewriter, loc, dataPtr, memRefType, toLLVMTy(vtp)); 12118345b86dSNicolas Vasilache 121265a3f289SMatthias Springer // Rewrite as an unmasked masked read / write. 121365a3f289SMatthias Springer if (!xferOp.mask()) 1214563879b6SRahul Joshi return replaceTransferOpWithLoadOrStore(rewriter, 1215563879b6SRahul Joshi *this->getTypeConverter(), loc, 1216563879b6SRahul Joshi xferOp, operands, vectorDataPtr); 12171870e787SNicolas Vasilache 121865a3f289SMatthias Springer // Rewrite as a masked read / write. 1219563879b6SRahul Joshi return replaceTransferOpWithMasked(rewriter, *this->getTypeConverter(), loc, 122065a3f289SMatthias Springer xferOp, operands, vectorDataPtr, 122165a3f289SMatthias Springer xferOp.mask()); 12228345b86dSNicolas Vasilache } 12238345b86dSNicolas Vasilache }; 12248345b86dSNicolas Vasilache 1225563879b6SRahul Joshi class VectorPrintOpConversion : public ConvertOpToLLVMPattern<vector::PrintOp> { 1226d9b500d3SAart Bik public: 1227563879b6SRahul Joshi using ConvertOpToLLVMPattern<vector::PrintOp>::ConvertOpToLLVMPattern; 1228d9b500d3SAart Bik 1229d9b500d3SAart Bik // Proof-of-concept lowering implementation that relies on a small 1230d9b500d3SAart Bik // runtime support library, which only needs to provide a few 1231d9b500d3SAart Bik // printing methods (single value for all data types, opening/closing 1232d9b500d3SAart Bik // bracket, comma, newline). The lowering fully unrolls a vector 1233d9b500d3SAart Bik // in terms of these elementary printing operations. The advantage 1234d9b500d3SAart Bik // of this approach is that the library can remain unaware of all 1235d9b500d3SAart Bik // low-level implementation details of vectors while still supporting 1236d9b500d3SAart Bik // output of any shaped and dimensioned vector. Due to full unrolling, 1237d9b500d3SAart Bik // this approach is less suited for very large vectors though. 1238d9b500d3SAart Bik // 12399db53a18SRiver Riddle // TODO: rely solely on libc in future? something else? 1240d9b500d3SAart Bik // 12413145427dSRiver Riddle LogicalResult 1242563879b6SRahul Joshi matchAndRewrite(vector::PrintOp printOp, ArrayRef<Value> operands, 1243d9b500d3SAart Bik ConversionPatternRewriter &rewriter) const override { 12442d2c73c5SJacques Pienaar auto adaptor = vector::PrintOpAdaptor(operands); 1245d9b500d3SAart Bik Type printType = printOp.getPrintType(); 1246d9b500d3SAart Bik 1247dcec2ca5SChristian Sigg if (typeConverter->convertType(printType) == nullptr) 12483145427dSRiver Riddle return failure(); 1249d9b500d3SAart Bik 1250b8880f5fSAart Bik // Make sure element type has runtime support. 1251b8880f5fSAart Bik PrintConversion conversion = PrintConversion::None; 1252d9b500d3SAart Bik VectorType vectorType = printType.dyn_cast<VectorType>(); 1253d9b500d3SAart Bik Type eltType = vectorType ? vectorType.getElementType() : printType; 1254d9b500d3SAart Bik Operation *printer; 1255b8880f5fSAart Bik if (eltType.isF32()) { 1256e332c22cSNicolas Vasilache printer = 1257e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintF32Fn(printOp->getParentOfType<ModuleOp>()); 1258b8880f5fSAart Bik } else if (eltType.isF64()) { 1259e332c22cSNicolas Vasilache printer = 1260e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintF64Fn(printOp->getParentOfType<ModuleOp>()); 126154759cefSAart Bik } else if (eltType.isIndex()) { 1262e332c22cSNicolas Vasilache printer = 1263e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintU64Fn(printOp->getParentOfType<ModuleOp>()); 1264b8880f5fSAart Bik } else if (auto intTy = eltType.dyn_cast<IntegerType>()) { 1265b8880f5fSAart Bik // Integers need a zero or sign extension on the operand 1266b8880f5fSAart Bik // (depending on the source type) as well as a signed or 1267b8880f5fSAart Bik // unsigned print method. Up to 64-bit is supported. 1268b8880f5fSAart Bik unsigned width = intTy.getWidth(); 1269b8880f5fSAart Bik if (intTy.isUnsigned()) { 127054759cefSAart Bik if (width <= 64) { 1271b8880f5fSAart Bik if (width < 64) 1272b8880f5fSAart Bik conversion = PrintConversion::ZeroExt64; 1273e332c22cSNicolas Vasilache printer = LLVM::lookupOrCreatePrintU64Fn( 1274e332c22cSNicolas Vasilache printOp->getParentOfType<ModuleOp>()); 1275b8880f5fSAart Bik } else { 12763145427dSRiver Riddle return failure(); 1277b8880f5fSAart Bik } 1278b8880f5fSAart Bik } else { 1279b8880f5fSAart Bik assert(intTy.isSignless() || intTy.isSigned()); 128054759cefSAart Bik if (width <= 64) { 1281b8880f5fSAart Bik // Note that we *always* zero extend booleans (1-bit integers), 1282b8880f5fSAart Bik // so that true/false is printed as 1/0 rather than -1/0. 1283b8880f5fSAart Bik if (width == 1) 128454759cefSAart Bik conversion = PrintConversion::ZeroExt64; 128554759cefSAart Bik else if (width < 64) 1286b8880f5fSAart Bik conversion = PrintConversion::SignExt64; 1287e332c22cSNicolas Vasilache printer = LLVM::lookupOrCreatePrintI64Fn( 1288e332c22cSNicolas Vasilache printOp->getParentOfType<ModuleOp>()); 1289b8880f5fSAart Bik } else { 1290b8880f5fSAart Bik return failure(); 1291b8880f5fSAart Bik } 1292b8880f5fSAart Bik } 1293b8880f5fSAart Bik } else { 1294b8880f5fSAart Bik return failure(); 1295b8880f5fSAart Bik } 1296d9b500d3SAart Bik 1297d9b500d3SAart Bik // Unroll vector into elementary print calls. 1298b8880f5fSAart Bik int64_t rank = vectorType ? vectorType.getRank() : 0; 1299563879b6SRahul Joshi emitRanks(rewriter, printOp, adaptor.source(), vectorType, printer, rank, 1300b8880f5fSAart Bik conversion); 1301e332c22cSNicolas Vasilache emitCall(rewriter, printOp->getLoc(), 1302e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintNewlineFn( 1303e332c22cSNicolas Vasilache printOp->getParentOfType<ModuleOp>())); 1304563879b6SRahul Joshi rewriter.eraseOp(printOp); 13053145427dSRiver Riddle return success(); 1306d9b500d3SAart Bik } 1307d9b500d3SAart Bik 1308d9b500d3SAart Bik private: 1309b8880f5fSAart Bik enum class PrintConversion { 131030e6033bSNicolas Vasilache // clang-format off 1311b8880f5fSAart Bik None, 1312b8880f5fSAart Bik ZeroExt64, 1313b8880f5fSAart Bik SignExt64 131430e6033bSNicolas Vasilache // clang-format on 1315b8880f5fSAart Bik }; 1316b8880f5fSAart Bik 1317d9b500d3SAart Bik void emitRanks(ConversionPatternRewriter &rewriter, Operation *op, 1318e62a6956SRiver Riddle Value value, VectorType vectorType, Operation *printer, 1319b8880f5fSAart Bik int64_t rank, PrintConversion conversion) const { 1320d9b500d3SAart Bik Location loc = op->getLoc(); 1321d9b500d3SAart Bik if (rank == 0) { 1322b8880f5fSAart Bik switch (conversion) { 1323b8880f5fSAart Bik case PrintConversion::ZeroExt64: 1324b8880f5fSAart Bik value = rewriter.create<ZeroExtendIOp>( 13252230bf99SAlex Zinenko loc, value, IntegerType::get(rewriter.getContext(), 64)); 1326b8880f5fSAart Bik break; 1327b8880f5fSAart Bik case PrintConversion::SignExt64: 1328b8880f5fSAart Bik value = rewriter.create<SignExtendIOp>( 13292230bf99SAlex Zinenko loc, value, IntegerType::get(rewriter.getContext(), 64)); 1330b8880f5fSAart Bik break; 1331b8880f5fSAart Bik case PrintConversion::None: 1332b8880f5fSAart Bik break; 1333c9eeeb38Saartbik } 1334d9b500d3SAart Bik emitCall(rewriter, loc, printer, value); 1335d9b500d3SAart Bik return; 1336d9b500d3SAart Bik } 1337d9b500d3SAart Bik 1338e332c22cSNicolas Vasilache emitCall(rewriter, loc, 1339e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintOpenFn(op->getParentOfType<ModuleOp>())); 1340e332c22cSNicolas Vasilache Operation *printComma = 1341e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintCommaFn(op->getParentOfType<ModuleOp>()); 1342d9b500d3SAart Bik int64_t dim = vectorType.getDimSize(0); 1343d9b500d3SAart Bik for (int64_t d = 0; d < dim; ++d) { 1344d9b500d3SAart Bik auto reducedType = 1345d9b500d3SAart Bik rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr; 1346dcec2ca5SChristian Sigg auto llvmType = typeConverter->convertType( 1347d9b500d3SAart Bik rank > 1 ? reducedType : vectorType.getElementType()); 1348dcec2ca5SChristian Sigg Value nestedVal = extractOne(rewriter, *getTypeConverter(), loc, value, 1349dcec2ca5SChristian Sigg llvmType, rank, d); 1350b8880f5fSAart Bik emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1, 1351b8880f5fSAart Bik conversion); 1352d9b500d3SAart Bik if (d != dim - 1) 1353d9b500d3SAart Bik emitCall(rewriter, loc, printComma); 1354d9b500d3SAart Bik } 1355e332c22cSNicolas Vasilache emitCall(rewriter, loc, 1356e332c22cSNicolas Vasilache LLVM::lookupOrCreatePrintCloseFn(op->getParentOfType<ModuleOp>())); 1357d9b500d3SAart Bik } 1358d9b500d3SAart Bik 1359d9b500d3SAart Bik // Helper to emit a call. 1360d9b500d3SAart Bik static void emitCall(ConversionPatternRewriter &rewriter, Location loc, 1361d9b500d3SAart Bik Operation *ref, ValueRange params = ValueRange()) { 136208e4f078SRahul Joshi rewriter.create<LLVM::CallOp>(loc, TypeRange(), 1363d9b500d3SAart Bik rewriter.getSymbolRefAttr(ref), params); 1364d9b500d3SAart Bik } 1365d9b500d3SAart Bik }; 1366d9b500d3SAart Bik 1367334a4159SReid Tatge /// Progressive lowering of ExtractStridedSliceOp to either: 1368c3c95b9cSaartbik /// 1. express single offset extract as a direct shuffle. 1369c3c95b9cSaartbik /// 2. extract + lower rank strided_slice + insert for the n-D case. 1370c3c95b9cSaartbik class VectorExtractStridedSliceOpConversion 1371334a4159SReid Tatge : public OpRewritePattern<ExtractStridedSliceOp> { 137265678d93SNicolas Vasilache public: 13732257e4a7SRiver Riddle using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 13742257e4a7SRiver Riddle 13752257e4a7SRiver Riddle void initialize() { 1376b99bd771SRiver Riddle // This pattern creates recursive ExtractStridedSliceOp, but the recursion 1377b99bd771SRiver Riddle // is bounded as the rank is strictly decreasing. 1378b99bd771SRiver Riddle setHasBoundedRewriteRecursion(); 1379b99bd771SRiver Riddle } 138065678d93SNicolas Vasilache 1381334a4159SReid Tatge LogicalResult matchAndRewrite(ExtractStridedSliceOp op, 138265678d93SNicolas Vasilache PatternRewriter &rewriter) const override { 13839eb3e564SChris Lattner auto dstType = op.getType(); 138465678d93SNicolas Vasilache 138565678d93SNicolas Vasilache assert(!op.offsets().getValue().empty() && "Unexpected empty offsets"); 138665678d93SNicolas Vasilache 138765678d93SNicolas Vasilache int64_t offset = 138865678d93SNicolas Vasilache op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 138965678d93SNicolas Vasilache int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt(); 139065678d93SNicolas Vasilache int64_t stride = 139165678d93SNicolas Vasilache op.strides().getValue().front().cast<IntegerAttr>().getInt(); 139265678d93SNicolas Vasilache 139365678d93SNicolas Vasilache auto loc = op.getLoc(); 139465678d93SNicolas Vasilache auto elemType = dstType.getElementType(); 139535b68527SLei Zhang assert(elemType.isSignlessIntOrIndexOrFloat()); 1396c3c95b9cSaartbik 1397c3c95b9cSaartbik // Single offset can be more efficiently shuffled. 1398c3c95b9cSaartbik if (op.offsets().getValue().size() == 1) { 1399c3c95b9cSaartbik SmallVector<int64_t, 4> offsets; 1400c3c95b9cSaartbik offsets.reserve(size); 1401c3c95b9cSaartbik for (int64_t off = offset, e = offset + size * stride; off < e; 1402c3c95b9cSaartbik off += stride) 1403c3c95b9cSaartbik offsets.push_back(off); 1404c3c95b9cSaartbik rewriter.replaceOpWithNewOp<ShuffleOp>(op, dstType, op.vector(), 1405c3c95b9cSaartbik op.vector(), 1406c3c95b9cSaartbik rewriter.getI64ArrayAttr(offsets)); 1407c3c95b9cSaartbik return success(); 1408c3c95b9cSaartbik } 1409c3c95b9cSaartbik 1410c3c95b9cSaartbik // Extract/insert on a lower ranked extract strided slice op. 141165678d93SNicolas Vasilache Value zero = rewriter.create<ConstantOp>(loc, elemType, 141265678d93SNicolas Vasilache rewriter.getZeroAttr(elemType)); 141365678d93SNicolas Vasilache Value res = rewriter.create<SplatOp>(loc, dstType, zero); 141465678d93SNicolas Vasilache for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 141565678d93SNicolas Vasilache off += stride, ++idx) { 1416c3c95b9cSaartbik Value one = extractOne(rewriter, loc, op.vector(), off); 1417c3c95b9cSaartbik Value extracted = rewriter.create<ExtractStridedSliceOp>( 1418c3c95b9cSaartbik loc, one, getI64SubArray(op.offsets(), /* dropFront=*/1), 141965678d93SNicolas Vasilache getI64SubArray(op.sizes(), /* dropFront=*/1), 142065678d93SNicolas Vasilache getI64SubArray(op.strides(), /* dropFront=*/1)); 142165678d93SNicolas Vasilache res = insertOne(rewriter, loc, extracted, res, idx); 142265678d93SNicolas Vasilache } 1423c3c95b9cSaartbik rewriter.replaceOp(op, res); 14243145427dSRiver Riddle return success(); 142565678d93SNicolas Vasilache } 142665678d93SNicolas Vasilache }; 142765678d93SNicolas Vasilache 1428df186507SBenjamin Kramer } // namespace 1429df186507SBenjamin Kramer 14305c0c51a9SNicolas Vasilache /// Populate the given list with patterns that convert from Vector to LLVM. 14315c0c51a9SNicolas Vasilache void mlir::populateVectorToLLVMConversionPatterns( 1432dc4e913bSChris Lattner LLVMTypeConverter &converter, RewritePatternSet &patterns, 143365a3f289SMatthias Springer bool reassociateFPReductions) { 143465678d93SNicolas Vasilache MLIRContext *ctx = converter.getDialect()->getContext(); 1435dc4e913bSChris Lattner patterns.add<VectorFMAOpNDRewritePattern, 1436681f929fSNicolas Vasilache VectorInsertStridedSliceOpDifferentRankRewritePattern, 14372d515e49SNicolas Vasilache VectorInsertStridedSliceOpSameRankRewritePattern, 1438c3c95b9cSaartbik VectorExtractStridedSliceOpConversion>(ctx); 1439dc4e913bSChris Lattner patterns.add<VectorReductionOpConversion>(converter, reassociateFPReductions); 14408345b86dSNicolas Vasilache patterns 1441dc4e913bSChris Lattner .add<VectorBitCastOpConversion, VectorShuffleOpConversion, 1442dc4e913bSChris Lattner VectorExtractElementOpConversion, VectorExtractOpConversion, 1443dc4e913bSChris Lattner VectorFMAOp1DConversion, VectorInsertElementOpConversion, 1444dc4e913bSChris Lattner VectorInsertOpConversion, VectorPrintOpConversion, 144519dbb230Saartbik VectorTypeCastOpConversion, 1446dc4e913bSChris Lattner VectorLoadStoreConversion<vector::LoadOp, vector::LoadOpAdaptor>, 1447ee66e43aSDiego Caballero VectorLoadStoreConversion<vector::MaskedLoadOp, 1448ee66e43aSDiego Caballero vector::MaskedLoadOpAdaptor>, 1449dc4e913bSChris Lattner VectorLoadStoreConversion<vector::StoreOp, vector::StoreOpAdaptor>, 1450ee66e43aSDiego Caballero VectorLoadStoreConversion<vector::MaskedStoreOp, 1451ee66e43aSDiego Caballero vector::MaskedStoreOpAdaptor>, 1452dc4e913bSChris Lattner VectorGatherOpConversion, VectorScatterOpConversion, 145365a3f289SMatthias Springer VectorExpandLoadOpConversion, VectorCompressStoreOpConversion, 145465a3f289SMatthias Springer VectorTransferConversion<TransferReadOp>, 145565a3f289SMatthias Springer VectorTransferConversion<TransferWriteOp>>(converter); 14565c0c51a9SNicolas Vasilache } 14575c0c51a9SNicolas Vasilache 145863b683a8SNicolas Vasilache void mlir::populateVectorToLLVMMatrixConversionPatterns( 1459dc4e913bSChris Lattner LLVMTypeConverter &converter, RewritePatternSet &patterns) { 1460dc4e913bSChris Lattner patterns.add<VectorMatmulOpConversion>(converter); 1461dc4e913bSChris Lattner patterns.add<VectorFlatTransposeOpConversion>(converter); 146263b683a8SNicolas Vasilache } 1463