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 111834ad4aSRiver Riddle #include "../PassDetail.h" 125c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h" 135c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" 145c0c51a9SNicolas Vasilache #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 1569d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h" 164d60f47bSRob Suderman #include "mlir/Dialect/Vector/VectorOps.h" 178345b86dSNicolas Vasilache #include "mlir/IR/AffineMap.h" 185c0c51a9SNicolas Vasilache #include "mlir/IR/Attributes.h" 195c0c51a9SNicolas Vasilache #include "mlir/IR/Builders.h" 205c0c51a9SNicolas Vasilache #include "mlir/IR/MLIRContext.h" 215c0c51a9SNicolas Vasilache #include "mlir/IR/Module.h" 225c0c51a9SNicolas Vasilache #include "mlir/IR/Operation.h" 235c0c51a9SNicolas Vasilache #include "mlir/IR/PatternMatch.h" 245c0c51a9SNicolas Vasilache #include "mlir/IR/StandardTypes.h" 255c0c51a9SNicolas Vasilache #include "mlir/IR/Types.h" 265c0c51a9SNicolas Vasilache #include "mlir/Transforms/DialectConversion.h" 275c0c51a9SNicolas Vasilache #include "mlir/Transforms/Passes.h" 285c0c51a9SNicolas Vasilache #include "llvm/IR/DerivedTypes.h" 295c0c51a9SNicolas Vasilache #include "llvm/IR/Module.h" 305c0c51a9SNicolas Vasilache #include "llvm/IR/Type.h" 315c0c51a9SNicolas Vasilache #include "llvm/Support/Allocator.h" 325c0c51a9SNicolas Vasilache #include "llvm/Support/ErrorHandling.h" 335c0c51a9SNicolas Vasilache 345c0c51a9SNicolas Vasilache using namespace mlir; 3565678d93SNicolas Vasilache using namespace mlir::vector; 365c0c51a9SNicolas Vasilache 375c0c51a9SNicolas Vasilache template <typename T> 385c0c51a9SNicolas Vasilache static LLVM::LLVMType getPtrToElementType(T containerType, 390f04384dSAlex Zinenko LLVMTypeConverter &typeConverter) { 400f04384dSAlex Zinenko return typeConverter.convertType(containerType.getElementType()) 415c0c51a9SNicolas Vasilache .template cast<LLVM::LLVMType>() 425c0c51a9SNicolas Vasilache .getPointerTo(); 435c0c51a9SNicolas Vasilache } 445c0c51a9SNicolas Vasilache 459826fe5cSAart Bik // Helper to reduce vector type by one rank at front. 469826fe5cSAart Bik static VectorType reducedVectorTypeFront(VectorType tp) { 479826fe5cSAart Bik assert((tp.getRank() > 1) && "unlowerable vector type"); 489826fe5cSAart Bik return VectorType::get(tp.getShape().drop_front(), tp.getElementType()); 499826fe5cSAart Bik } 509826fe5cSAart Bik 519826fe5cSAart Bik // Helper to reduce vector type by *all* but one rank at back. 529826fe5cSAart Bik static VectorType reducedVectorTypeBack(VectorType tp) { 539826fe5cSAart Bik assert((tp.getRank() > 1) && "unlowerable vector type"); 549826fe5cSAart Bik return VectorType::get(tp.getShape().take_back(), tp.getElementType()); 559826fe5cSAart Bik } 569826fe5cSAart Bik 571c81adf3SAart Bik // Helper that picks the proper sequence for inserting. 58e62a6956SRiver Riddle static Value insertOne(ConversionPatternRewriter &rewriter, 590f04384dSAlex Zinenko LLVMTypeConverter &typeConverter, Location loc, 600f04384dSAlex Zinenko Value val1, Value val2, Type llvmType, int64_t rank, 610f04384dSAlex Zinenko int64_t pos) { 621c81adf3SAart Bik if (rank == 1) { 631c81adf3SAart Bik auto idxType = rewriter.getIndexType(); 641c81adf3SAart Bik auto constant = rewriter.create<LLVM::ConstantOp>( 650f04384dSAlex Zinenko loc, typeConverter.convertType(idxType), 661c81adf3SAart Bik rewriter.getIntegerAttr(idxType, pos)); 671c81adf3SAart Bik return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2, 681c81adf3SAart Bik constant); 691c81adf3SAart Bik } 701c81adf3SAart Bik return rewriter.create<LLVM::InsertValueOp>(loc, llvmType, val1, val2, 711c81adf3SAart Bik rewriter.getI64ArrayAttr(pos)); 721c81adf3SAart Bik } 731c81adf3SAart Bik 742d515e49SNicolas Vasilache // Helper that picks the proper sequence for inserting. 752d515e49SNicolas Vasilache static Value insertOne(PatternRewriter &rewriter, Location loc, Value from, 762d515e49SNicolas Vasilache Value into, int64_t offset) { 772d515e49SNicolas Vasilache auto vectorType = into.getType().cast<VectorType>(); 782d515e49SNicolas Vasilache if (vectorType.getRank() > 1) 792d515e49SNicolas Vasilache return rewriter.create<InsertOp>(loc, from, into, offset); 802d515e49SNicolas Vasilache return rewriter.create<vector::InsertElementOp>( 812d515e49SNicolas Vasilache loc, vectorType, from, into, 822d515e49SNicolas Vasilache rewriter.create<ConstantIndexOp>(loc, offset)); 832d515e49SNicolas Vasilache } 842d515e49SNicolas Vasilache 851c81adf3SAart Bik // Helper that picks the proper sequence for extracting. 86e62a6956SRiver Riddle static Value extractOne(ConversionPatternRewriter &rewriter, 870f04384dSAlex Zinenko LLVMTypeConverter &typeConverter, Location loc, 880f04384dSAlex Zinenko Value val, Type llvmType, int64_t rank, int64_t pos) { 891c81adf3SAart Bik if (rank == 1) { 901c81adf3SAart Bik auto idxType = rewriter.getIndexType(); 911c81adf3SAart Bik auto constant = rewriter.create<LLVM::ConstantOp>( 920f04384dSAlex Zinenko loc, typeConverter.convertType(idxType), 931c81adf3SAart Bik rewriter.getIntegerAttr(idxType, pos)); 941c81adf3SAart Bik return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val, 951c81adf3SAart Bik constant); 961c81adf3SAart Bik } 971c81adf3SAart Bik return rewriter.create<LLVM::ExtractValueOp>(loc, llvmType, val, 981c81adf3SAart Bik rewriter.getI64ArrayAttr(pos)); 991c81adf3SAart Bik } 1001c81adf3SAart Bik 1012d515e49SNicolas Vasilache // Helper that picks the proper sequence for extracting. 1022d515e49SNicolas Vasilache static Value extractOne(PatternRewriter &rewriter, Location loc, Value vector, 1032d515e49SNicolas Vasilache int64_t offset) { 1042d515e49SNicolas Vasilache auto vectorType = vector.getType().cast<VectorType>(); 1052d515e49SNicolas Vasilache if (vectorType.getRank() > 1) 1062d515e49SNicolas Vasilache return rewriter.create<ExtractOp>(loc, vector, offset); 1072d515e49SNicolas Vasilache return rewriter.create<vector::ExtractElementOp>( 1082d515e49SNicolas Vasilache loc, vectorType.getElementType(), vector, 1092d515e49SNicolas Vasilache rewriter.create<ConstantIndexOp>(loc, offset)); 1102d515e49SNicolas Vasilache } 1112d515e49SNicolas Vasilache 1122d515e49SNicolas Vasilache // Helper that returns a subset of `arrayAttr` as a vector of int64_t. 1132d515e49SNicolas Vasilache // TODO(rriddle): Better support for attribute subtype forwarding + slicing. 1142d515e49SNicolas Vasilache static SmallVector<int64_t, 4> getI64SubArray(ArrayAttr arrayAttr, 1152d515e49SNicolas Vasilache unsigned dropFront = 0, 1162d515e49SNicolas Vasilache unsigned dropBack = 0) { 1172d515e49SNicolas Vasilache assert(arrayAttr.size() > dropFront + dropBack && "Out of bounds"); 1182d515e49SNicolas Vasilache auto range = arrayAttr.getAsRange<IntegerAttr>(); 1192d515e49SNicolas Vasilache SmallVector<int64_t, 4> res; 1202d515e49SNicolas Vasilache res.reserve(arrayAttr.size() - dropFront - dropBack); 1212d515e49SNicolas Vasilache for (auto it = range.begin() + dropFront, eit = range.end() - dropBack; 1222d515e49SNicolas Vasilache it != eit; ++it) 1232d515e49SNicolas Vasilache res.push_back((*it).getValue().getSExtValue()); 1242d515e49SNicolas Vasilache return res; 1252d515e49SNicolas Vasilache } 1262d515e49SNicolas Vasilache 12790c01357SBenjamin Kramer namespace { 128e83b7b99Saartbik 12963b683a8SNicolas Vasilache /// Conversion pattern for a vector.matrix_multiply. 13063b683a8SNicolas Vasilache /// This is lowered directly to the proper llvm.intr.matrix.multiply. 13163b683a8SNicolas Vasilache class VectorMatmulOpConversion : public ConvertToLLVMPattern { 13263b683a8SNicolas Vasilache public: 13363b683a8SNicolas Vasilache explicit VectorMatmulOpConversion(MLIRContext *context, 13463b683a8SNicolas Vasilache LLVMTypeConverter &typeConverter) 13563b683a8SNicolas Vasilache : ConvertToLLVMPattern(vector::MatmulOp::getOperationName(), context, 13663b683a8SNicolas Vasilache typeConverter) {} 13763b683a8SNicolas Vasilache 1383145427dSRiver Riddle LogicalResult 13963b683a8SNicolas Vasilache matchAndRewrite(Operation *op, ArrayRef<Value> operands, 14063b683a8SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 14163b683a8SNicolas Vasilache auto matmulOp = cast<vector::MatmulOp>(op); 14263b683a8SNicolas Vasilache auto adaptor = vector::MatmulOpOperandAdaptor(operands); 14363b683a8SNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MatrixMultiplyOp>( 14463b683a8SNicolas Vasilache op, typeConverter.convertType(matmulOp.res().getType()), adaptor.lhs(), 14563b683a8SNicolas Vasilache adaptor.rhs(), matmulOp.lhs_rows(), matmulOp.lhs_columns(), 14663b683a8SNicolas Vasilache matmulOp.rhs_columns()); 1473145427dSRiver Riddle return success(); 14863b683a8SNicolas Vasilache } 14963b683a8SNicolas Vasilache }; 15063b683a8SNicolas Vasilache 151*c295a65dSaartbik /// Conversion pattern for a vector.flat_transpose. 152*c295a65dSaartbik /// This is lowered directly to the proper llvm.intr.matrix.transpose. 153*c295a65dSaartbik class VectorFlatTransposeOpConversion : public ConvertToLLVMPattern { 154*c295a65dSaartbik public: 155*c295a65dSaartbik explicit VectorFlatTransposeOpConversion(MLIRContext *context, 156*c295a65dSaartbik LLVMTypeConverter &typeConverter) 157*c295a65dSaartbik : ConvertToLLVMPattern(vector::FlatTransposeOp::getOperationName(), 158*c295a65dSaartbik context, typeConverter) {} 159*c295a65dSaartbik 160*c295a65dSaartbik LogicalResult 161*c295a65dSaartbik matchAndRewrite(Operation *op, ArrayRef<Value> operands, 162*c295a65dSaartbik ConversionPatternRewriter &rewriter) const override { 163*c295a65dSaartbik auto transOp = cast<vector::FlatTransposeOp>(op); 164*c295a65dSaartbik auto adaptor = vector::FlatTransposeOpOperandAdaptor(operands); 165*c295a65dSaartbik rewriter.replaceOpWithNewOp<LLVM::MatrixTransposeOp>( 166*c295a65dSaartbik transOp, typeConverter.convertType(transOp.res().getType()), 167*c295a65dSaartbik adaptor.matrix(), transOp.rows(), transOp.columns()); 168*c295a65dSaartbik return success(); 169*c295a65dSaartbik } 170*c295a65dSaartbik }; 171*c295a65dSaartbik 172870c1fd4SAlex Zinenko class VectorReductionOpConversion : public ConvertToLLVMPattern { 173e83b7b99Saartbik public: 174e83b7b99Saartbik explicit VectorReductionOpConversion(MLIRContext *context, 175e83b7b99Saartbik LLVMTypeConverter &typeConverter) 176870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ReductionOp::getOperationName(), context, 177e83b7b99Saartbik typeConverter) {} 178e83b7b99Saartbik 1793145427dSRiver Riddle LogicalResult 180e83b7b99Saartbik matchAndRewrite(Operation *op, ArrayRef<Value> operands, 181e83b7b99Saartbik ConversionPatternRewriter &rewriter) const override { 182e83b7b99Saartbik auto reductionOp = cast<vector::ReductionOp>(op); 183e83b7b99Saartbik auto kind = reductionOp.kind(); 184e83b7b99Saartbik Type eltType = reductionOp.dest().getType(); 1850f04384dSAlex Zinenko Type llvmType = typeConverter.convertType(eltType); 18635b68527SLei Zhang if (eltType.isSignlessInteger(32) || eltType.isSignlessInteger(64)) { 187e83b7b99Saartbik // Integer reductions: add/mul/min/max/and/or/xor. 188e83b7b99Saartbik if (kind == "add") 189e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_add>( 190e83b7b99Saartbik op, llvmType, operands[0]); 191e83b7b99Saartbik else if (kind == "mul") 192e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_mul>( 193e83b7b99Saartbik op, llvmType, operands[0]); 194e83b7b99Saartbik else if (kind == "min") 195e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smin>( 196e83b7b99Saartbik op, llvmType, operands[0]); 197e83b7b99Saartbik else if (kind == "max") 198e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smax>( 199e83b7b99Saartbik op, llvmType, operands[0]); 200e83b7b99Saartbik else if (kind == "and") 201e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_and>( 202e83b7b99Saartbik op, llvmType, operands[0]); 203e83b7b99Saartbik else if (kind == "or") 204e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_or>( 205e83b7b99Saartbik op, llvmType, operands[0]); 206e83b7b99Saartbik else if (kind == "xor") 207e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_xor>( 208e83b7b99Saartbik op, llvmType, operands[0]); 209e83b7b99Saartbik else 2103145427dSRiver Riddle return failure(); 2113145427dSRiver Riddle return success(); 212e83b7b99Saartbik 213e83b7b99Saartbik } else if (eltType.isF32() || eltType.isF64()) { 214e83b7b99Saartbik // Floating-point reductions: add/mul/min/max 215e83b7b99Saartbik if (kind == "add") { 2160d924700Saartbik // Optional accumulator (or zero). 2170d924700Saartbik Value acc = operands.size() > 1 ? operands[1] 2180d924700Saartbik : rewriter.create<LLVM::ConstantOp>( 2190d924700Saartbik op->getLoc(), llvmType, 2200d924700Saartbik rewriter.getZeroAttr(eltType)); 221e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fadd>( 2220d924700Saartbik op, llvmType, acc, operands[0]); 223e83b7b99Saartbik } else if (kind == "mul") { 2240d924700Saartbik // Optional accumulator (or one). 2250d924700Saartbik Value acc = operands.size() > 1 2260d924700Saartbik ? operands[1] 2270d924700Saartbik : rewriter.create<LLVM::ConstantOp>( 2280d924700Saartbik op->getLoc(), llvmType, 2290d924700Saartbik rewriter.getFloatAttr(eltType, 1.0)); 230e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fmul>( 2310d924700Saartbik op, llvmType, acc, operands[0]); 232e83b7b99Saartbik } else if (kind == "min") 233e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmin>( 234e83b7b99Saartbik op, llvmType, operands[0]); 235e83b7b99Saartbik else if (kind == "max") 236e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmax>( 237e83b7b99Saartbik op, llvmType, operands[0]); 238e83b7b99Saartbik else 2393145427dSRiver Riddle return failure(); 2403145427dSRiver Riddle return success(); 241e83b7b99Saartbik } 2423145427dSRiver Riddle return failure(); 243e83b7b99Saartbik } 244e83b7b99Saartbik }; 245e83b7b99Saartbik 246870c1fd4SAlex Zinenko class VectorShuffleOpConversion : public ConvertToLLVMPattern { 2471c81adf3SAart Bik public: 2481c81adf3SAart Bik explicit VectorShuffleOpConversion(MLIRContext *context, 2491c81adf3SAart Bik LLVMTypeConverter &typeConverter) 250870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ShuffleOp::getOperationName(), context, 2511c81adf3SAart Bik typeConverter) {} 2521c81adf3SAart Bik 2533145427dSRiver Riddle LogicalResult 254e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 2551c81adf3SAart Bik ConversionPatternRewriter &rewriter) const override { 2561c81adf3SAart Bik auto loc = op->getLoc(); 2571c81adf3SAart Bik auto adaptor = vector::ShuffleOpOperandAdaptor(operands); 2581c81adf3SAart Bik auto shuffleOp = cast<vector::ShuffleOp>(op); 2591c81adf3SAart Bik auto v1Type = shuffleOp.getV1VectorType(); 2601c81adf3SAart Bik auto v2Type = shuffleOp.getV2VectorType(); 2611c81adf3SAart Bik auto vectorType = shuffleOp.getVectorType(); 2620f04384dSAlex Zinenko Type llvmType = typeConverter.convertType(vectorType); 2631c81adf3SAart Bik auto maskArrayAttr = shuffleOp.mask(); 2641c81adf3SAart Bik 2651c81adf3SAart Bik // Bail if result type cannot be lowered. 2661c81adf3SAart Bik if (!llvmType) 2673145427dSRiver Riddle return failure(); 2681c81adf3SAart Bik 2691c81adf3SAart Bik // Get rank and dimension sizes. 2701c81adf3SAart Bik int64_t rank = vectorType.getRank(); 2711c81adf3SAart Bik assert(v1Type.getRank() == rank); 2721c81adf3SAart Bik assert(v2Type.getRank() == rank); 2731c81adf3SAart Bik int64_t v1Dim = v1Type.getDimSize(0); 2741c81adf3SAart Bik 2751c81adf3SAart Bik // For rank 1, where both operands have *exactly* the same vector type, 2761c81adf3SAart Bik // there is direct shuffle support in LLVM. Use it! 2771c81adf3SAart Bik if (rank == 1 && v1Type == v2Type) { 278e62a6956SRiver Riddle Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>( 2791c81adf3SAart Bik loc, adaptor.v1(), adaptor.v2(), maskArrayAttr); 2801c81adf3SAart Bik rewriter.replaceOp(op, shuffle); 2813145427dSRiver Riddle return success(); 282b36aaeafSAart Bik } 283b36aaeafSAart Bik 2841c81adf3SAart Bik // For all other cases, insert the individual values individually. 285e62a6956SRiver Riddle Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType); 2861c81adf3SAart Bik int64_t insPos = 0; 2871c81adf3SAart Bik for (auto en : llvm::enumerate(maskArrayAttr)) { 2881c81adf3SAart Bik int64_t extPos = en.value().cast<IntegerAttr>().getInt(); 289e62a6956SRiver Riddle Value value = adaptor.v1(); 2901c81adf3SAart Bik if (extPos >= v1Dim) { 2911c81adf3SAart Bik extPos -= v1Dim; 2921c81adf3SAart Bik value = adaptor.v2(); 293b36aaeafSAart Bik } 2940f04384dSAlex Zinenko Value extract = extractOne(rewriter, typeConverter, loc, value, llvmType, 2950f04384dSAlex Zinenko rank, extPos); 2960f04384dSAlex Zinenko insert = insertOne(rewriter, typeConverter, loc, insert, extract, 2970f04384dSAlex Zinenko llvmType, rank, insPos++); 2981c81adf3SAart Bik } 2991c81adf3SAart Bik rewriter.replaceOp(op, insert); 3003145427dSRiver Riddle return success(); 301b36aaeafSAart Bik } 302b36aaeafSAart Bik }; 303b36aaeafSAart Bik 304870c1fd4SAlex Zinenko class VectorExtractElementOpConversion : public ConvertToLLVMPattern { 305cd5dab8aSAart Bik public: 306cd5dab8aSAart Bik explicit VectorExtractElementOpConversion(MLIRContext *context, 307cd5dab8aSAart Bik LLVMTypeConverter &typeConverter) 308870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ExtractElementOp::getOperationName(), 309870c1fd4SAlex Zinenko context, typeConverter) {} 310cd5dab8aSAart Bik 3113145427dSRiver Riddle LogicalResult 312e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 313cd5dab8aSAart Bik ConversionPatternRewriter &rewriter) const override { 314cd5dab8aSAart Bik auto adaptor = vector::ExtractElementOpOperandAdaptor(operands); 315cd5dab8aSAart Bik auto extractEltOp = cast<vector::ExtractElementOp>(op); 316cd5dab8aSAart Bik auto vectorType = extractEltOp.getVectorType(); 3170f04384dSAlex Zinenko auto llvmType = typeConverter.convertType(vectorType.getElementType()); 318cd5dab8aSAart Bik 319cd5dab8aSAart Bik // Bail if result type cannot be lowered. 320cd5dab8aSAart Bik if (!llvmType) 3213145427dSRiver Riddle return failure(); 322cd5dab8aSAart Bik 323cd5dab8aSAart Bik rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>( 324cd5dab8aSAart Bik op, llvmType, adaptor.vector(), adaptor.position()); 3253145427dSRiver Riddle return success(); 326cd5dab8aSAart Bik } 327cd5dab8aSAart Bik }; 328cd5dab8aSAart Bik 329870c1fd4SAlex Zinenko class VectorExtractOpConversion : public ConvertToLLVMPattern { 3305c0c51a9SNicolas Vasilache public: 3319826fe5cSAart Bik explicit VectorExtractOpConversion(MLIRContext *context, 3325c0c51a9SNicolas Vasilache LLVMTypeConverter &typeConverter) 333870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ExtractOp::getOperationName(), context, 3345c0c51a9SNicolas Vasilache typeConverter) {} 3355c0c51a9SNicolas Vasilache 3363145427dSRiver Riddle LogicalResult 337e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 3385c0c51a9SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 3395c0c51a9SNicolas Vasilache auto loc = op->getLoc(); 340d37f2725SAart Bik auto adaptor = vector::ExtractOpOperandAdaptor(operands); 341d37f2725SAart Bik auto extractOp = cast<vector::ExtractOp>(op); 3429826fe5cSAart Bik auto vectorType = extractOp.getVectorType(); 3432bdf33ccSRiver Riddle auto resultType = extractOp.getResult().getType(); 3440f04384dSAlex Zinenko auto llvmResultType = typeConverter.convertType(resultType); 3455c0c51a9SNicolas Vasilache auto positionArrayAttr = extractOp.position(); 3469826fe5cSAart Bik 3479826fe5cSAart Bik // Bail if result type cannot be lowered. 3489826fe5cSAart Bik if (!llvmResultType) 3493145427dSRiver Riddle return failure(); 3509826fe5cSAart Bik 3515c0c51a9SNicolas Vasilache // One-shot extraction of vector from array (only requires extractvalue). 3525c0c51a9SNicolas Vasilache if (resultType.isa<VectorType>()) { 353e62a6956SRiver Riddle Value extracted = rewriter.create<LLVM::ExtractValueOp>( 3545c0c51a9SNicolas Vasilache loc, llvmResultType, adaptor.vector(), positionArrayAttr); 3555c0c51a9SNicolas Vasilache rewriter.replaceOp(op, extracted); 3563145427dSRiver Riddle return success(); 3575c0c51a9SNicolas Vasilache } 3585c0c51a9SNicolas Vasilache 3599826fe5cSAart Bik // Potential extraction of 1-D vector from array. 3605c0c51a9SNicolas Vasilache auto *context = op->getContext(); 361e62a6956SRiver Riddle Value extracted = adaptor.vector(); 3625c0c51a9SNicolas Vasilache auto positionAttrs = positionArrayAttr.getValue(); 3635c0c51a9SNicolas Vasilache if (positionAttrs.size() > 1) { 3649826fe5cSAart Bik auto oneDVectorType = reducedVectorTypeBack(vectorType); 3655c0c51a9SNicolas Vasilache auto nMinusOnePositionAttrs = 3665c0c51a9SNicolas Vasilache ArrayAttr::get(positionAttrs.drop_back(), context); 3675c0c51a9SNicolas Vasilache extracted = rewriter.create<LLVM::ExtractValueOp>( 3680f04384dSAlex Zinenko loc, typeConverter.convertType(oneDVectorType), extracted, 3695c0c51a9SNicolas Vasilache nMinusOnePositionAttrs); 3705c0c51a9SNicolas Vasilache } 3715c0c51a9SNicolas Vasilache 3725c0c51a9SNicolas Vasilache // Remaining extraction of element from 1-D LLVM vector 3735c0c51a9SNicolas Vasilache auto position = positionAttrs.back().cast<IntegerAttr>(); 3740f04384dSAlex Zinenko auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect()); 3751d47564aSAart Bik auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 3765c0c51a9SNicolas Vasilache extracted = 3775c0c51a9SNicolas Vasilache rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant); 3785c0c51a9SNicolas Vasilache rewriter.replaceOp(op, extracted); 3795c0c51a9SNicolas Vasilache 3803145427dSRiver Riddle return success(); 3815c0c51a9SNicolas Vasilache } 3825c0c51a9SNicolas Vasilache }; 3835c0c51a9SNicolas Vasilache 384681f929fSNicolas Vasilache /// Conversion pattern that turns a vector.fma on a 1-D vector 385681f929fSNicolas Vasilache /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion. 386681f929fSNicolas Vasilache /// This does not match vectors of n >= 2 rank. 387681f929fSNicolas Vasilache /// 388681f929fSNicolas Vasilache /// Example: 389681f929fSNicolas Vasilache /// ``` 390681f929fSNicolas Vasilache /// vector.fma %a, %a, %a : vector<8xf32> 391681f929fSNicolas Vasilache /// ``` 392681f929fSNicolas Vasilache /// is converted to: 393681f929fSNicolas Vasilache /// ``` 394681f929fSNicolas Vasilache /// llvm.intr.fma %va, %va, %va: 395681f929fSNicolas Vasilache /// (!llvm<"<8 x float>">, !llvm<"<8 x float>">, !llvm<"<8 x float>">) 396681f929fSNicolas Vasilache /// -> !llvm<"<8 x float>"> 397681f929fSNicolas Vasilache /// ``` 398870c1fd4SAlex Zinenko class VectorFMAOp1DConversion : public ConvertToLLVMPattern { 399681f929fSNicolas Vasilache public: 400681f929fSNicolas Vasilache explicit VectorFMAOp1DConversion(MLIRContext *context, 401681f929fSNicolas Vasilache LLVMTypeConverter &typeConverter) 402870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::FMAOp::getOperationName(), context, 403681f929fSNicolas Vasilache typeConverter) {} 404681f929fSNicolas Vasilache 4053145427dSRiver Riddle LogicalResult 406681f929fSNicolas Vasilache matchAndRewrite(Operation *op, ArrayRef<Value> operands, 407681f929fSNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 408681f929fSNicolas Vasilache auto adaptor = vector::FMAOpOperandAdaptor(operands); 409681f929fSNicolas Vasilache vector::FMAOp fmaOp = cast<vector::FMAOp>(op); 410681f929fSNicolas Vasilache VectorType vType = fmaOp.getVectorType(); 411681f929fSNicolas Vasilache if (vType.getRank() != 1) 4123145427dSRiver Riddle return failure(); 413681f929fSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::FMAOp>(op, adaptor.lhs(), adaptor.rhs(), 414681f929fSNicolas Vasilache adaptor.acc()); 4153145427dSRiver Riddle return success(); 416681f929fSNicolas Vasilache } 417681f929fSNicolas Vasilache }; 418681f929fSNicolas Vasilache 419870c1fd4SAlex Zinenko class VectorInsertElementOpConversion : public ConvertToLLVMPattern { 420cd5dab8aSAart Bik public: 421cd5dab8aSAart Bik explicit VectorInsertElementOpConversion(MLIRContext *context, 422cd5dab8aSAart Bik LLVMTypeConverter &typeConverter) 423870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::InsertElementOp::getOperationName(), 424870c1fd4SAlex Zinenko context, typeConverter) {} 425cd5dab8aSAart Bik 4263145427dSRiver Riddle LogicalResult 427e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 428cd5dab8aSAart Bik ConversionPatternRewriter &rewriter) const override { 429cd5dab8aSAart Bik auto adaptor = vector::InsertElementOpOperandAdaptor(operands); 430cd5dab8aSAart Bik auto insertEltOp = cast<vector::InsertElementOp>(op); 431cd5dab8aSAart Bik auto vectorType = insertEltOp.getDestVectorType(); 4320f04384dSAlex Zinenko auto llvmType = typeConverter.convertType(vectorType); 433cd5dab8aSAart Bik 434cd5dab8aSAart Bik // Bail if result type cannot be lowered. 435cd5dab8aSAart Bik if (!llvmType) 4363145427dSRiver Riddle return failure(); 437cd5dab8aSAart Bik 438cd5dab8aSAart Bik rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>( 439cd5dab8aSAart Bik op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position()); 4403145427dSRiver Riddle return success(); 441cd5dab8aSAart Bik } 442cd5dab8aSAart Bik }; 443cd5dab8aSAart Bik 444870c1fd4SAlex Zinenko class VectorInsertOpConversion : public ConvertToLLVMPattern { 4459826fe5cSAart Bik public: 4469826fe5cSAart Bik explicit VectorInsertOpConversion(MLIRContext *context, 4479826fe5cSAart Bik LLVMTypeConverter &typeConverter) 448870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::InsertOp::getOperationName(), context, 4499826fe5cSAart Bik typeConverter) {} 4509826fe5cSAart Bik 4513145427dSRiver Riddle LogicalResult 452e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 4539826fe5cSAart Bik ConversionPatternRewriter &rewriter) const override { 4549826fe5cSAart Bik auto loc = op->getLoc(); 4559826fe5cSAart Bik auto adaptor = vector::InsertOpOperandAdaptor(operands); 4569826fe5cSAart Bik auto insertOp = cast<vector::InsertOp>(op); 4579826fe5cSAart Bik auto sourceType = insertOp.getSourceType(); 4589826fe5cSAart Bik auto destVectorType = insertOp.getDestVectorType(); 4590f04384dSAlex Zinenko auto llvmResultType = typeConverter.convertType(destVectorType); 4609826fe5cSAart Bik auto positionArrayAttr = insertOp.position(); 4619826fe5cSAart Bik 4629826fe5cSAart Bik // Bail if result type cannot be lowered. 4639826fe5cSAart Bik if (!llvmResultType) 4643145427dSRiver Riddle return failure(); 4659826fe5cSAart Bik 4669826fe5cSAart Bik // One-shot insertion of a vector into an array (only requires insertvalue). 4679826fe5cSAart Bik if (sourceType.isa<VectorType>()) { 468e62a6956SRiver Riddle Value inserted = rewriter.create<LLVM::InsertValueOp>( 4699826fe5cSAart Bik loc, llvmResultType, adaptor.dest(), adaptor.source(), 4709826fe5cSAart Bik positionArrayAttr); 4719826fe5cSAart Bik rewriter.replaceOp(op, inserted); 4723145427dSRiver Riddle return success(); 4739826fe5cSAart Bik } 4749826fe5cSAart Bik 4759826fe5cSAart Bik // Potential extraction of 1-D vector from array. 4769826fe5cSAart Bik auto *context = op->getContext(); 477e62a6956SRiver Riddle Value extracted = adaptor.dest(); 4789826fe5cSAart Bik auto positionAttrs = positionArrayAttr.getValue(); 4799826fe5cSAart Bik auto position = positionAttrs.back().cast<IntegerAttr>(); 4809826fe5cSAart Bik auto oneDVectorType = destVectorType; 4819826fe5cSAart Bik if (positionAttrs.size() > 1) { 4829826fe5cSAart Bik oneDVectorType = reducedVectorTypeBack(destVectorType); 4839826fe5cSAart Bik auto nMinusOnePositionAttrs = 4849826fe5cSAart Bik ArrayAttr::get(positionAttrs.drop_back(), context); 4859826fe5cSAart Bik extracted = rewriter.create<LLVM::ExtractValueOp>( 4860f04384dSAlex Zinenko loc, typeConverter.convertType(oneDVectorType), extracted, 4879826fe5cSAart Bik nMinusOnePositionAttrs); 4889826fe5cSAart Bik } 4899826fe5cSAart Bik 4909826fe5cSAart Bik // Insertion of an element into a 1-D LLVM vector. 4910f04384dSAlex Zinenko auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect()); 4921d47564aSAart Bik auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 493e62a6956SRiver Riddle Value inserted = rewriter.create<LLVM::InsertElementOp>( 4940f04384dSAlex Zinenko loc, typeConverter.convertType(oneDVectorType), extracted, 4950f04384dSAlex Zinenko adaptor.source(), constant); 4969826fe5cSAart Bik 4979826fe5cSAart Bik // Potential insertion of resulting 1-D vector into array. 4989826fe5cSAart Bik if (positionAttrs.size() > 1) { 4999826fe5cSAart Bik auto nMinusOnePositionAttrs = 5009826fe5cSAart Bik ArrayAttr::get(positionAttrs.drop_back(), context); 5019826fe5cSAart Bik inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType, 5029826fe5cSAart Bik adaptor.dest(), inserted, 5039826fe5cSAart Bik nMinusOnePositionAttrs); 5049826fe5cSAart Bik } 5059826fe5cSAart Bik 5069826fe5cSAart Bik rewriter.replaceOp(op, inserted); 5073145427dSRiver Riddle return success(); 5089826fe5cSAart Bik } 5099826fe5cSAart Bik }; 5109826fe5cSAart Bik 511681f929fSNicolas Vasilache /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1. 512681f929fSNicolas Vasilache /// 513681f929fSNicolas Vasilache /// Example: 514681f929fSNicolas Vasilache /// ``` 515681f929fSNicolas Vasilache /// %d = vector.fma %a, %b, %c : vector<2x4xf32> 516681f929fSNicolas Vasilache /// ``` 517681f929fSNicolas Vasilache /// is rewritten into: 518681f929fSNicolas Vasilache /// ``` 519681f929fSNicolas Vasilache /// %r = splat %f0: vector<2x4xf32> 520681f929fSNicolas Vasilache /// %va = vector.extractvalue %a[0] : vector<2x4xf32> 521681f929fSNicolas Vasilache /// %vb = vector.extractvalue %b[0] : vector<2x4xf32> 522681f929fSNicolas Vasilache /// %vc = vector.extractvalue %c[0] : vector<2x4xf32> 523681f929fSNicolas Vasilache /// %vd = vector.fma %va, %vb, %vc : vector<4xf32> 524681f929fSNicolas Vasilache /// %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32> 525681f929fSNicolas Vasilache /// %va2 = vector.extractvalue %a2[1] : vector<2x4xf32> 526681f929fSNicolas Vasilache /// %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32> 527681f929fSNicolas Vasilache /// %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32> 528681f929fSNicolas Vasilache /// %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32> 529681f929fSNicolas Vasilache /// %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32> 530681f929fSNicolas Vasilache /// // %r3 holds the final value. 531681f929fSNicolas Vasilache /// ``` 532681f929fSNicolas Vasilache class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> { 533681f929fSNicolas Vasilache public: 534681f929fSNicolas Vasilache using OpRewritePattern<FMAOp>::OpRewritePattern; 535681f929fSNicolas Vasilache 5363145427dSRiver Riddle LogicalResult matchAndRewrite(FMAOp op, 537681f929fSNicolas Vasilache PatternRewriter &rewriter) const override { 538681f929fSNicolas Vasilache auto vType = op.getVectorType(); 539681f929fSNicolas Vasilache if (vType.getRank() < 2) 5403145427dSRiver Riddle return failure(); 541681f929fSNicolas Vasilache 542681f929fSNicolas Vasilache auto loc = op.getLoc(); 543681f929fSNicolas Vasilache auto elemType = vType.getElementType(); 544681f929fSNicolas Vasilache Value zero = rewriter.create<ConstantOp>(loc, elemType, 545681f929fSNicolas Vasilache rewriter.getZeroAttr(elemType)); 546681f929fSNicolas Vasilache Value desc = rewriter.create<SplatOp>(loc, vType, zero); 547681f929fSNicolas Vasilache for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) { 548681f929fSNicolas Vasilache Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i); 549681f929fSNicolas Vasilache Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i); 550681f929fSNicolas Vasilache Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i); 551681f929fSNicolas Vasilache Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC); 552681f929fSNicolas Vasilache desc = rewriter.create<InsertOp>(loc, fma, desc, i); 553681f929fSNicolas Vasilache } 554681f929fSNicolas Vasilache rewriter.replaceOp(op, desc); 5553145427dSRiver Riddle return success(); 556681f929fSNicolas Vasilache } 557681f929fSNicolas Vasilache }; 558681f929fSNicolas Vasilache 5592d515e49SNicolas Vasilache // When ranks are different, InsertStridedSlice needs to extract a properly 5602d515e49SNicolas Vasilache // ranked vector from the destination vector into which to insert. This pattern 5612d515e49SNicolas Vasilache // only takes care of this part and forwards the rest of the conversion to 5622d515e49SNicolas Vasilache // another pattern that converts InsertStridedSlice for operands of the same 5632d515e49SNicolas Vasilache // rank. 5642d515e49SNicolas Vasilache // 5652d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors 5662d515e49SNicolas Vasilache // have different ranks. In this case: 5672d515e49SNicolas Vasilache // 1. the proper subvector is extracted from the destination vector 5682d515e49SNicolas Vasilache // 2. a new InsertStridedSlice op is created to insert the source in the 5692d515e49SNicolas Vasilache // destination subvector 5702d515e49SNicolas Vasilache // 3. the destination subvector is inserted back in the proper place 5712d515e49SNicolas Vasilache // 4. the op is replaced by the result of step 3. 5722d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a 5732d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`. 5742d515e49SNicolas Vasilache class VectorInsertStridedSliceOpDifferentRankRewritePattern 5752d515e49SNicolas Vasilache : public OpRewritePattern<InsertStridedSliceOp> { 5762d515e49SNicolas Vasilache public: 5772d515e49SNicolas Vasilache using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 5782d515e49SNicolas Vasilache 5793145427dSRiver Riddle LogicalResult matchAndRewrite(InsertStridedSliceOp op, 5802d515e49SNicolas Vasilache PatternRewriter &rewriter) const override { 5812d515e49SNicolas Vasilache auto srcType = op.getSourceVectorType(); 5822d515e49SNicolas Vasilache auto dstType = op.getDestVectorType(); 5832d515e49SNicolas Vasilache 5842d515e49SNicolas Vasilache if (op.offsets().getValue().empty()) 5853145427dSRiver Riddle return failure(); 5862d515e49SNicolas Vasilache 5872d515e49SNicolas Vasilache auto loc = op.getLoc(); 5882d515e49SNicolas Vasilache int64_t rankDiff = dstType.getRank() - srcType.getRank(); 5892d515e49SNicolas Vasilache assert(rankDiff >= 0); 5902d515e49SNicolas Vasilache if (rankDiff == 0) 5913145427dSRiver Riddle return failure(); 5922d515e49SNicolas Vasilache 5932d515e49SNicolas Vasilache int64_t rankRest = dstType.getRank() - rankDiff; 5942d515e49SNicolas Vasilache // Extract / insert the subvector of matching rank and InsertStridedSlice 5952d515e49SNicolas Vasilache // on it. 5962d515e49SNicolas Vasilache Value extracted = 5972d515e49SNicolas Vasilache rewriter.create<ExtractOp>(loc, op.dest(), 5982d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/0, 5992d515e49SNicolas Vasilache /*dropFront=*/rankRest)); 6002d515e49SNicolas Vasilache // A different pattern will kick in for InsertStridedSlice with matching 6012d515e49SNicolas Vasilache // ranks. 6022d515e49SNicolas Vasilache auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>( 6032d515e49SNicolas Vasilache loc, op.source(), extracted, 6042d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/rankDiff), 605c8fc76a9Saartbik getI64SubArray(op.strides(), /*dropFront=*/0)); 6062d515e49SNicolas Vasilache rewriter.replaceOpWithNewOp<InsertOp>( 6072d515e49SNicolas Vasilache op, stridedSliceInnerOp.getResult(), op.dest(), 6082d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/0, 6092d515e49SNicolas Vasilache /*dropFront=*/rankRest)); 6103145427dSRiver Riddle return success(); 6112d515e49SNicolas Vasilache } 6122d515e49SNicolas Vasilache }; 6132d515e49SNicolas Vasilache 6142d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors 6152d515e49SNicolas Vasilache // have the same rank. In this case, we reduce 6162d515e49SNicolas Vasilache // 1. the proper subvector is extracted from the destination vector 6172d515e49SNicolas Vasilache // 2. a new InsertStridedSlice op is created to insert the source in the 6182d515e49SNicolas Vasilache // destination subvector 6192d515e49SNicolas Vasilache // 3. the destination subvector is inserted back in the proper place 6202d515e49SNicolas Vasilache // 4. the op is replaced by the result of step 3. 6212d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a 6222d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`. 6232d515e49SNicolas Vasilache class VectorInsertStridedSliceOpSameRankRewritePattern 6242d515e49SNicolas Vasilache : public OpRewritePattern<InsertStridedSliceOp> { 6252d515e49SNicolas Vasilache public: 6262d515e49SNicolas Vasilache using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 6272d515e49SNicolas Vasilache 6283145427dSRiver Riddle LogicalResult matchAndRewrite(InsertStridedSliceOp op, 6292d515e49SNicolas Vasilache PatternRewriter &rewriter) const override { 6302d515e49SNicolas Vasilache auto srcType = op.getSourceVectorType(); 6312d515e49SNicolas Vasilache auto dstType = op.getDestVectorType(); 6322d515e49SNicolas Vasilache 6332d515e49SNicolas Vasilache if (op.offsets().getValue().empty()) 6343145427dSRiver Riddle return failure(); 6352d515e49SNicolas Vasilache 6362d515e49SNicolas Vasilache int64_t rankDiff = dstType.getRank() - srcType.getRank(); 6372d515e49SNicolas Vasilache assert(rankDiff >= 0); 6382d515e49SNicolas Vasilache if (rankDiff != 0) 6393145427dSRiver Riddle return failure(); 6402d515e49SNicolas Vasilache 6412d515e49SNicolas Vasilache if (srcType == dstType) { 6422d515e49SNicolas Vasilache rewriter.replaceOp(op, op.source()); 6433145427dSRiver Riddle return success(); 6442d515e49SNicolas Vasilache } 6452d515e49SNicolas Vasilache 6462d515e49SNicolas Vasilache int64_t offset = 6472d515e49SNicolas Vasilache op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 6482d515e49SNicolas Vasilache int64_t size = srcType.getShape().front(); 6492d515e49SNicolas Vasilache int64_t stride = 6502d515e49SNicolas Vasilache op.strides().getValue().front().cast<IntegerAttr>().getInt(); 6512d515e49SNicolas Vasilache 6522d515e49SNicolas Vasilache auto loc = op.getLoc(); 6532d515e49SNicolas Vasilache Value res = op.dest(); 6542d515e49SNicolas Vasilache // For each slice of the source vector along the most major dimension. 6552d515e49SNicolas Vasilache for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 6562d515e49SNicolas Vasilache off += stride, ++idx) { 6572d515e49SNicolas Vasilache // 1. extract the proper subvector (or element) from source 6582d515e49SNicolas Vasilache Value extractedSource = extractOne(rewriter, loc, op.source(), idx); 6592d515e49SNicolas Vasilache if (extractedSource.getType().isa<VectorType>()) { 6602d515e49SNicolas Vasilache // 2. If we have a vector, extract the proper subvector from destination 6612d515e49SNicolas Vasilache // Otherwise we are at the element level and no need to recurse. 6622d515e49SNicolas Vasilache Value extractedDest = extractOne(rewriter, loc, op.dest(), off); 6632d515e49SNicolas Vasilache // 3. Reduce the problem to lowering a new InsertStridedSlice op with 6642d515e49SNicolas Vasilache // smaller rank. 665bd1ccfe6SRiver Riddle extractedSource = rewriter.create<InsertStridedSliceOp>( 6662d515e49SNicolas Vasilache loc, extractedSource, extractedDest, 6672d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /* dropFront=*/1), 6682d515e49SNicolas Vasilache getI64SubArray(op.strides(), /* dropFront=*/1)); 6692d515e49SNicolas Vasilache } 6702d515e49SNicolas Vasilache // 4. Insert the extractedSource into the res vector. 6712d515e49SNicolas Vasilache res = insertOne(rewriter, loc, extractedSource, res, off); 6722d515e49SNicolas Vasilache } 6732d515e49SNicolas Vasilache 6742d515e49SNicolas Vasilache rewriter.replaceOp(op, res); 6753145427dSRiver Riddle return success(); 6762d515e49SNicolas Vasilache } 677bd1ccfe6SRiver Riddle /// This pattern creates recursive InsertStridedSliceOp, but the recursion is 678bd1ccfe6SRiver Riddle /// bounded as the rank is strictly decreasing. 679bd1ccfe6SRiver Riddle bool hasBoundedRewriteRecursion() const final { return true; } 6802d515e49SNicolas Vasilache }; 6812d515e49SNicolas Vasilache 682870c1fd4SAlex Zinenko class VectorTypeCastOpConversion : public ConvertToLLVMPattern { 6835c0c51a9SNicolas Vasilache public: 6845c0c51a9SNicolas Vasilache explicit VectorTypeCastOpConversion(MLIRContext *context, 6855c0c51a9SNicolas Vasilache LLVMTypeConverter &typeConverter) 686870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::TypeCastOp::getOperationName(), context, 6875c0c51a9SNicolas Vasilache typeConverter) {} 6885c0c51a9SNicolas Vasilache 6893145427dSRiver Riddle LogicalResult 690e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 6915c0c51a9SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 6925c0c51a9SNicolas Vasilache auto loc = op->getLoc(); 6935c0c51a9SNicolas Vasilache vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op); 6945c0c51a9SNicolas Vasilache MemRefType sourceMemRefType = 6952bdf33ccSRiver Riddle castOp.getOperand().getType().cast<MemRefType>(); 6965c0c51a9SNicolas Vasilache MemRefType targetMemRefType = 6972bdf33ccSRiver Riddle castOp.getResult().getType().cast<MemRefType>(); 6985c0c51a9SNicolas Vasilache 6995c0c51a9SNicolas Vasilache // Only static shape casts supported atm. 7005c0c51a9SNicolas Vasilache if (!sourceMemRefType.hasStaticShape() || 7015c0c51a9SNicolas Vasilache !targetMemRefType.hasStaticShape()) 7023145427dSRiver Riddle return failure(); 7035c0c51a9SNicolas Vasilache 7045c0c51a9SNicolas Vasilache auto llvmSourceDescriptorTy = 7052bdf33ccSRiver Riddle operands[0].getType().dyn_cast<LLVM::LLVMType>(); 7065c0c51a9SNicolas Vasilache if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy()) 7073145427dSRiver Riddle return failure(); 7085c0c51a9SNicolas Vasilache MemRefDescriptor sourceMemRef(operands[0]); 7095c0c51a9SNicolas Vasilache 7100f04384dSAlex Zinenko auto llvmTargetDescriptorTy = typeConverter.convertType(targetMemRefType) 7115c0c51a9SNicolas Vasilache .dyn_cast_or_null<LLVM::LLVMType>(); 7125c0c51a9SNicolas Vasilache if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy()) 7133145427dSRiver Riddle return failure(); 7145c0c51a9SNicolas Vasilache 7155c0c51a9SNicolas Vasilache int64_t offset; 7165c0c51a9SNicolas Vasilache SmallVector<int64_t, 4> strides; 7175c0c51a9SNicolas Vasilache auto successStrides = 7185c0c51a9SNicolas Vasilache getStridesAndOffset(sourceMemRefType, strides, offset); 7195c0c51a9SNicolas Vasilache bool isContiguous = (strides.back() == 1); 7205c0c51a9SNicolas Vasilache if (isContiguous) { 7215c0c51a9SNicolas Vasilache auto sizes = sourceMemRefType.getShape(); 7225c0c51a9SNicolas Vasilache for (int index = 0, e = strides.size() - 2; index < e; ++index) { 7235c0c51a9SNicolas Vasilache if (strides[index] != strides[index + 1] * sizes[index + 1]) { 7245c0c51a9SNicolas Vasilache isContiguous = false; 7255c0c51a9SNicolas Vasilache break; 7265c0c51a9SNicolas Vasilache } 7275c0c51a9SNicolas Vasilache } 7285c0c51a9SNicolas Vasilache } 7295c0c51a9SNicolas Vasilache // Only contiguous source tensors supported atm. 7305c0c51a9SNicolas Vasilache if (failed(successStrides) || !isContiguous) 7313145427dSRiver Riddle return failure(); 7325c0c51a9SNicolas Vasilache 7330f04384dSAlex Zinenko auto int64Ty = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect()); 7345c0c51a9SNicolas Vasilache 7355c0c51a9SNicolas Vasilache // Create descriptor. 7365c0c51a9SNicolas Vasilache auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy); 7375c0c51a9SNicolas Vasilache Type llvmTargetElementTy = desc.getElementType(); 7385c0c51a9SNicolas Vasilache // Set allocated ptr. 739e62a6956SRiver Riddle Value allocated = sourceMemRef.allocatedPtr(rewriter, loc); 7405c0c51a9SNicolas Vasilache allocated = 7415c0c51a9SNicolas Vasilache rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated); 7425c0c51a9SNicolas Vasilache desc.setAllocatedPtr(rewriter, loc, allocated); 7435c0c51a9SNicolas Vasilache // Set aligned ptr. 744e62a6956SRiver Riddle Value ptr = sourceMemRef.alignedPtr(rewriter, loc); 7455c0c51a9SNicolas Vasilache ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr); 7465c0c51a9SNicolas Vasilache desc.setAlignedPtr(rewriter, loc, ptr); 7475c0c51a9SNicolas Vasilache // Fill offset 0. 7485c0c51a9SNicolas Vasilache auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0); 7495c0c51a9SNicolas Vasilache auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr); 7505c0c51a9SNicolas Vasilache desc.setOffset(rewriter, loc, zero); 7515c0c51a9SNicolas Vasilache 7525c0c51a9SNicolas Vasilache // Fill size and stride descriptors in memref. 7535c0c51a9SNicolas Vasilache for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) { 7545c0c51a9SNicolas Vasilache int64_t index = indexedSize.index(); 7555c0c51a9SNicolas Vasilache auto sizeAttr = 7565c0c51a9SNicolas Vasilache rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value()); 7575c0c51a9SNicolas Vasilache auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr); 7585c0c51a9SNicolas Vasilache desc.setSize(rewriter, loc, index, size); 7595c0c51a9SNicolas Vasilache auto strideAttr = 7605c0c51a9SNicolas Vasilache rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]); 7615c0c51a9SNicolas Vasilache auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr); 7625c0c51a9SNicolas Vasilache desc.setStride(rewriter, loc, index, stride); 7635c0c51a9SNicolas Vasilache } 7645c0c51a9SNicolas Vasilache 7655c0c51a9SNicolas Vasilache rewriter.replaceOp(op, {desc}); 7663145427dSRiver Riddle return success(); 7675c0c51a9SNicolas Vasilache } 7685c0c51a9SNicolas Vasilache }; 7695c0c51a9SNicolas Vasilache 770a23f1902SWen-Heng (Jack) Chung LogicalResult getLLVMTypeAndAlignment(LLVMTypeConverter &typeConverter, 771a23f1902SWen-Heng (Jack) Chung Type type, LLVM::LLVMType &llvmType, 772a23f1902SWen-Heng (Jack) Chung unsigned &align) { 773a23f1902SWen-Heng (Jack) Chung auto convertedType = typeConverter.convertType(type); 774a23f1902SWen-Heng (Jack) Chung if (!convertedType) 775a23f1902SWen-Heng (Jack) Chung return failure(); 776a23f1902SWen-Heng (Jack) Chung 777a23f1902SWen-Heng (Jack) Chung llvmType = convertedType.template cast<LLVM::LLVMType>(); 778a23f1902SWen-Heng (Jack) Chung auto dataLayout = typeConverter.getDialect()->getLLVMModule().getDataLayout(); 779a23f1902SWen-Heng (Jack) Chung align = dataLayout.getPrefTypeAlignment(llvmType.getUnderlyingType()); 780a23f1902SWen-Heng (Jack) Chung return success(); 781a23f1902SWen-Heng (Jack) Chung } 782a23f1902SWen-Heng (Jack) Chung 7831870e787SNicolas Vasilache LogicalResult 7841870e787SNicolas Vasilache replaceTransferOpWithLoadOrStore(ConversionPatternRewriter &rewriter, 7851870e787SNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 7861870e787SNicolas Vasilache TransferReadOp xferOp, 7871870e787SNicolas Vasilache ArrayRef<Value> operands, Value dataPtr) { 7881870e787SNicolas Vasilache LLVM::LLVMType vecTy; 7891870e787SNicolas Vasilache unsigned align; 7901870e787SNicolas Vasilache if (failed(getLLVMTypeAndAlignment(typeConverter, xferOp.getVectorType(), 7911870e787SNicolas Vasilache vecTy, align))) 7921870e787SNicolas Vasilache return failure(); 7931870e787SNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::LoadOp>(xferOp, dataPtr); 7941870e787SNicolas Vasilache return success(); 7951870e787SNicolas Vasilache } 7961870e787SNicolas Vasilache 7971870e787SNicolas Vasilache LogicalResult replaceTransferOpWithMasked(ConversionPatternRewriter &rewriter, 7981870e787SNicolas Vasilache LLVMTypeConverter &typeConverter, 7991870e787SNicolas Vasilache Location loc, TransferReadOp xferOp, 8001870e787SNicolas Vasilache ArrayRef<Value> operands, 8011870e787SNicolas Vasilache Value dataPtr, Value mask) { 8028345b86dSNicolas Vasilache auto toLLVMTy = [&](Type t) { return typeConverter.convertType(t); }; 8038345b86dSNicolas Vasilache VectorType fillType = xferOp.getVectorType(); 8048345b86dSNicolas Vasilache Value fill = rewriter.create<SplatOp>(loc, fillType, xferOp.padding()); 8058345b86dSNicolas Vasilache fill = rewriter.create<LLVM::DialectCastOp>(loc, toLLVMTy(fillType), fill); 8068345b86dSNicolas Vasilache 807a23f1902SWen-Heng (Jack) Chung LLVM::LLVMType vecTy; 808a23f1902SWen-Heng (Jack) Chung unsigned align; 809a99f62c4SAlex Zinenko if (failed(getLLVMTypeAndAlignment(typeConverter, xferOp.getVectorType(), 810a23f1902SWen-Heng (Jack) Chung vecTy, align))) 811a99f62c4SAlex Zinenko return failure(); 812a99f62c4SAlex Zinenko 8138345b86dSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>( 8141870e787SNicolas Vasilache xferOp, vecTy, dataPtr, mask, ValueRange{fill}, 815a23f1902SWen-Heng (Jack) Chung rewriter.getI32IntegerAttr(align)); 816a99f62c4SAlex Zinenko return success(); 8178345b86dSNicolas Vasilache } 8188345b86dSNicolas Vasilache 8191870e787SNicolas Vasilache LogicalResult 8201870e787SNicolas Vasilache replaceTransferOpWithLoadOrStore(ConversionPatternRewriter &rewriter, 8211870e787SNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 8221870e787SNicolas Vasilache TransferWriteOp xferOp, 8231870e787SNicolas Vasilache ArrayRef<Value> operands, Value dataPtr) { 8248345b86dSNicolas Vasilache auto adaptor = TransferWriteOpOperandAdaptor(operands); 8251870e787SNicolas Vasilache LLVM::LLVMType vecTy; 8261870e787SNicolas Vasilache unsigned align; 8271870e787SNicolas Vasilache if (failed(getLLVMTypeAndAlignment(typeConverter, xferOp.getVectorType(), 8281870e787SNicolas Vasilache vecTy, align))) 8291870e787SNicolas Vasilache return failure(); 8301870e787SNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::StoreOp>(xferOp, adaptor.vector(), dataPtr); 8311870e787SNicolas Vasilache return success(); 8321870e787SNicolas Vasilache } 833a23f1902SWen-Heng (Jack) Chung 8341870e787SNicolas Vasilache LogicalResult replaceTransferOpWithMasked(ConversionPatternRewriter &rewriter, 8351870e787SNicolas Vasilache LLVMTypeConverter &typeConverter, 8361870e787SNicolas Vasilache Location loc, TransferWriteOp xferOp, 8371870e787SNicolas Vasilache ArrayRef<Value> operands, 8381870e787SNicolas Vasilache Value dataPtr, Value mask) { 8391870e787SNicolas Vasilache auto adaptor = TransferWriteOpOperandAdaptor(operands); 840a23f1902SWen-Heng (Jack) Chung LLVM::LLVMType vecTy; 841a23f1902SWen-Heng (Jack) Chung unsigned align; 842a99f62c4SAlex Zinenko if (failed(getLLVMTypeAndAlignment(typeConverter, xferOp.getVectorType(), 843a23f1902SWen-Heng (Jack) Chung vecTy, align))) 844a99f62c4SAlex Zinenko return failure(); 845a99f62c4SAlex Zinenko 8468345b86dSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>( 8471870e787SNicolas Vasilache xferOp, adaptor.vector(), dataPtr, mask, 8481870e787SNicolas Vasilache rewriter.getI32IntegerAttr(align)); 849a99f62c4SAlex Zinenko return success(); 8508345b86dSNicolas Vasilache } 8518345b86dSNicolas Vasilache 8528345b86dSNicolas Vasilache static TransferReadOpOperandAdaptor 8538345b86dSNicolas Vasilache getTransferOpAdapter(TransferReadOp xferOp, ArrayRef<Value> operands) { 8548345b86dSNicolas Vasilache return TransferReadOpOperandAdaptor(operands); 8558345b86dSNicolas Vasilache } 8568345b86dSNicolas Vasilache 8578345b86dSNicolas Vasilache static TransferWriteOpOperandAdaptor 8588345b86dSNicolas Vasilache getTransferOpAdapter(TransferWriteOp xferOp, ArrayRef<Value> operands) { 8598345b86dSNicolas Vasilache return TransferWriteOpOperandAdaptor(operands); 8608345b86dSNicolas Vasilache } 8618345b86dSNicolas Vasilache 862b2c79c50SNicolas Vasilache bool isMinorIdentity(AffineMap map, unsigned rank) { 863b2c79c50SNicolas Vasilache if (map.getNumResults() < rank) 864b2c79c50SNicolas Vasilache return false; 865b2c79c50SNicolas Vasilache unsigned startDim = map.getNumDims() - rank; 866b2c79c50SNicolas Vasilache for (unsigned i = 0; i < rank; ++i) 867b2c79c50SNicolas Vasilache if (map.getResult(i) != getAffineDimExpr(startDim + i, map.getContext())) 868b2c79c50SNicolas Vasilache return false; 869b2c79c50SNicolas Vasilache return true; 870b2c79c50SNicolas Vasilache } 871b2c79c50SNicolas Vasilache 8728345b86dSNicolas Vasilache /// Conversion pattern that converts a 1-D vector transfer read/write op in a 8738345b86dSNicolas Vasilache /// sequence of: 874be16075bSWen-Heng (Jack) Chung /// 1. Bitcast or addrspacecast to vector form. 8758345b86dSNicolas Vasilache /// 2. Create an offsetVector = [ offset + 0 .. offset + vector_length - 1 ]. 8768345b86dSNicolas Vasilache /// 3. Create a mask where offsetVector is compared against memref upper bound. 8778345b86dSNicolas Vasilache /// 4. Rewrite op as a masked read or write. 8788345b86dSNicolas Vasilache template <typename ConcreteOp> 8798345b86dSNicolas Vasilache class VectorTransferConversion : public ConvertToLLVMPattern { 8808345b86dSNicolas Vasilache public: 8818345b86dSNicolas Vasilache explicit VectorTransferConversion(MLIRContext *context, 8828345b86dSNicolas Vasilache LLVMTypeConverter &typeConv) 8838345b86dSNicolas Vasilache : ConvertToLLVMPattern(ConcreteOp::getOperationName(), context, 8848345b86dSNicolas Vasilache typeConv) {} 8858345b86dSNicolas Vasilache 8868345b86dSNicolas Vasilache LogicalResult 8878345b86dSNicolas Vasilache matchAndRewrite(Operation *op, ArrayRef<Value> operands, 8888345b86dSNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 8898345b86dSNicolas Vasilache auto xferOp = cast<ConcreteOp>(op); 8908345b86dSNicolas Vasilache auto adaptor = getTransferOpAdapter(xferOp, operands); 891b2c79c50SNicolas Vasilache 892b2c79c50SNicolas Vasilache if (xferOp.getVectorType().getRank() > 1 || 893b2c79c50SNicolas Vasilache llvm::size(xferOp.indices()) == 0) 8948345b86dSNicolas Vasilache return failure(); 895b2c79c50SNicolas Vasilache if (!isMinorIdentity(xferOp.permutation_map(), 896b2c79c50SNicolas Vasilache xferOp.getVectorType().getRank())) 8978345b86dSNicolas Vasilache return failure(); 8988345b86dSNicolas Vasilache 8998345b86dSNicolas Vasilache auto toLLVMTy = [&](Type t) { return typeConverter.convertType(t); }; 9008345b86dSNicolas Vasilache 9018345b86dSNicolas Vasilache Location loc = op->getLoc(); 9028345b86dSNicolas Vasilache Type i64Type = rewriter.getIntegerType(64); 9038345b86dSNicolas Vasilache MemRefType memRefType = xferOp.getMemRefType(); 9048345b86dSNicolas Vasilache 9058345b86dSNicolas Vasilache // 1. Get the source/dst address as an LLVM vector pointer. 906be16075bSWen-Heng (Jack) Chung // The vector pointer would always be on address space 0, therefore 907be16075bSWen-Heng (Jack) Chung // addrspacecast shall be used when source/dst memrefs are not on 908be16075bSWen-Heng (Jack) Chung // address space 0. 9098345b86dSNicolas Vasilache // TODO: support alignment when possible. 9108345b86dSNicolas Vasilache Value dataPtr = getDataPtr(loc, memRefType, adaptor.memref(), 9118345b86dSNicolas Vasilache adaptor.indices(), rewriter, getModule()); 9128345b86dSNicolas Vasilache auto vecTy = 9138345b86dSNicolas Vasilache toLLVMTy(xferOp.getVectorType()).template cast<LLVM::LLVMType>(); 914be16075bSWen-Heng (Jack) Chung Value vectorDataPtr; 915be16075bSWen-Heng (Jack) Chung if (memRefType.getMemorySpace() == 0) 916be16075bSWen-Heng (Jack) Chung vectorDataPtr = 9178345b86dSNicolas Vasilache rewriter.create<LLVM::BitcastOp>(loc, vecTy.getPointerTo(), dataPtr); 918be16075bSWen-Heng (Jack) Chung else 919be16075bSWen-Heng (Jack) Chung vectorDataPtr = rewriter.create<LLVM::AddrSpaceCastOp>( 920be16075bSWen-Heng (Jack) Chung loc, vecTy.getPointerTo(), dataPtr); 9218345b86dSNicolas Vasilache 9221870e787SNicolas Vasilache if (!xferOp.isMaskedDim(0)) 9231870e787SNicolas Vasilache return replaceTransferOpWithLoadOrStore(rewriter, typeConverter, loc, 9241870e787SNicolas Vasilache xferOp, operands, vectorDataPtr); 9251870e787SNicolas Vasilache 9268345b86dSNicolas Vasilache // 2. Create a vector with linear indices [ 0 .. vector_length - 1 ]. 9278345b86dSNicolas Vasilache unsigned vecWidth = vecTy.getVectorNumElements(); 9288345b86dSNicolas Vasilache VectorType vectorCmpType = VectorType::get(vecWidth, i64Type); 9298345b86dSNicolas Vasilache SmallVector<int64_t, 8> indices; 9308345b86dSNicolas Vasilache indices.reserve(vecWidth); 9318345b86dSNicolas Vasilache for (unsigned i = 0; i < vecWidth; ++i) 9328345b86dSNicolas Vasilache indices.push_back(i); 9338345b86dSNicolas Vasilache Value linearIndices = rewriter.create<ConstantOp>( 9348345b86dSNicolas Vasilache loc, vectorCmpType, 9358345b86dSNicolas Vasilache DenseElementsAttr::get(vectorCmpType, ArrayRef<int64_t>(indices))); 9368345b86dSNicolas Vasilache linearIndices = rewriter.create<LLVM::DialectCastOp>( 9378345b86dSNicolas Vasilache loc, toLLVMTy(vectorCmpType), linearIndices); 9388345b86dSNicolas Vasilache 9398345b86dSNicolas Vasilache // 3. Create offsetVector = [ offset + 0 .. offset + vector_length - 1 ]. 940b2c79c50SNicolas Vasilache // TODO(ntv, ajcbik): when the leaf transfer rank is k > 1 we need the last 941b2c79c50SNicolas Vasilache // `k` dimensions here. 942b2c79c50SNicolas Vasilache unsigned lastIndex = llvm::size(xferOp.indices()) - 1; 943b2c79c50SNicolas Vasilache Value offsetIndex = *(xferOp.indices().begin() + lastIndex); 944b2c79c50SNicolas Vasilache offsetIndex = rewriter.create<IndexCastOp>(loc, i64Type, offsetIndex); 9458345b86dSNicolas Vasilache Value base = rewriter.create<SplatOp>(loc, vectorCmpType, offsetIndex); 9468345b86dSNicolas Vasilache Value offsetVector = rewriter.create<AddIOp>(loc, base, linearIndices); 9478345b86dSNicolas Vasilache 9488345b86dSNicolas Vasilache // 4. Let dim the memref dimension, compute the vector comparison mask: 9498345b86dSNicolas Vasilache // [ offset + 0 .. offset + vector_length - 1 ] < [ dim .. dim ] 950b2c79c50SNicolas Vasilache Value dim = rewriter.create<DimOp>(loc, xferOp.memref(), lastIndex); 951b2c79c50SNicolas Vasilache dim = rewriter.create<IndexCastOp>(loc, i64Type, dim); 9528345b86dSNicolas Vasilache dim = rewriter.create<SplatOp>(loc, vectorCmpType, dim); 9538345b86dSNicolas Vasilache Value mask = 9548345b86dSNicolas Vasilache rewriter.create<CmpIOp>(loc, CmpIPredicate::slt, offsetVector, dim); 9558345b86dSNicolas Vasilache mask = rewriter.create<LLVM::DialectCastOp>(loc, toLLVMTy(mask.getType()), 9568345b86dSNicolas Vasilache mask); 9578345b86dSNicolas Vasilache 9588345b86dSNicolas Vasilache // 5. Rewrite as a masked read / write. 9591870e787SNicolas Vasilache return replaceTransferOpWithMasked(rewriter, typeConverter, loc, xferOp, 960a99f62c4SAlex Zinenko operands, vectorDataPtr, mask); 9618345b86dSNicolas Vasilache } 9628345b86dSNicolas Vasilache }; 9638345b86dSNicolas Vasilache 964870c1fd4SAlex Zinenko class VectorPrintOpConversion : public ConvertToLLVMPattern { 965d9b500d3SAart Bik public: 966d9b500d3SAart Bik explicit VectorPrintOpConversion(MLIRContext *context, 967d9b500d3SAart Bik LLVMTypeConverter &typeConverter) 968870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::PrintOp::getOperationName(), context, 969d9b500d3SAart Bik typeConverter) {} 970d9b500d3SAart Bik 971d9b500d3SAart Bik // Proof-of-concept lowering implementation that relies on a small 972d9b500d3SAart Bik // runtime support library, which only needs to provide a few 973d9b500d3SAart Bik // printing methods (single value for all data types, opening/closing 974d9b500d3SAart Bik // bracket, comma, newline). The lowering fully unrolls a vector 975d9b500d3SAart Bik // in terms of these elementary printing operations. The advantage 976d9b500d3SAart Bik // of this approach is that the library can remain unaware of all 977d9b500d3SAart Bik // low-level implementation details of vectors while still supporting 978d9b500d3SAart Bik // output of any shaped and dimensioned vector. Due to full unrolling, 979d9b500d3SAart Bik // this approach is less suited for very large vectors though. 980d9b500d3SAart Bik // 981d9b500d3SAart Bik // TODO(ajcbik): rely solely on libc in future? something else? 982d9b500d3SAart Bik // 9833145427dSRiver Riddle LogicalResult 984e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 985d9b500d3SAart Bik ConversionPatternRewriter &rewriter) const override { 986d9b500d3SAart Bik auto printOp = cast<vector::PrintOp>(op); 987d9b500d3SAart Bik auto adaptor = vector::PrintOpOperandAdaptor(operands); 988d9b500d3SAart Bik Type printType = printOp.getPrintType(); 989d9b500d3SAart Bik 9900f04384dSAlex Zinenko if (typeConverter.convertType(printType) == nullptr) 9913145427dSRiver Riddle return failure(); 992d9b500d3SAart Bik 993d9b500d3SAart Bik // Make sure element type has runtime support (currently just Float/Double). 994d9b500d3SAart Bik VectorType vectorType = printType.dyn_cast<VectorType>(); 995d9b500d3SAart Bik Type eltType = vectorType ? vectorType.getElementType() : printType; 996d9b500d3SAart Bik int64_t rank = vectorType ? vectorType.getRank() : 0; 997d9b500d3SAart Bik Operation *printer; 9986937251fSaartbik if (eltType.isSignlessInteger(1)) 9996937251fSaartbik printer = getPrintI1(op); 10006937251fSaartbik else if (eltType.isSignlessInteger(32)) 1001e52414b1Saartbik printer = getPrintI32(op); 100235b68527SLei Zhang else if (eltType.isSignlessInteger(64)) 1003e52414b1Saartbik printer = getPrintI64(op); 1004e52414b1Saartbik else if (eltType.isF32()) 1005d9b500d3SAart Bik printer = getPrintFloat(op); 1006d9b500d3SAart Bik else if (eltType.isF64()) 1007d9b500d3SAart Bik printer = getPrintDouble(op); 1008d9b500d3SAart Bik else 10093145427dSRiver Riddle return failure(); 1010d9b500d3SAart Bik 1011d9b500d3SAart Bik // Unroll vector into elementary print calls. 1012d9b500d3SAart Bik emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank); 1013d9b500d3SAart Bik emitCall(rewriter, op->getLoc(), getPrintNewline(op)); 1014d9b500d3SAart Bik rewriter.eraseOp(op); 10153145427dSRiver Riddle return success(); 1016d9b500d3SAart Bik } 1017d9b500d3SAart Bik 1018d9b500d3SAart Bik private: 1019d9b500d3SAart Bik void emitRanks(ConversionPatternRewriter &rewriter, Operation *op, 1020e62a6956SRiver Riddle Value value, VectorType vectorType, Operation *printer, 1021d9b500d3SAart Bik int64_t rank) const { 1022d9b500d3SAart Bik Location loc = op->getLoc(); 1023d9b500d3SAart Bik if (rank == 0) { 1024d9b500d3SAart Bik emitCall(rewriter, loc, printer, value); 1025d9b500d3SAart Bik return; 1026d9b500d3SAart Bik } 1027d9b500d3SAart Bik 1028d9b500d3SAart Bik emitCall(rewriter, loc, getPrintOpen(op)); 1029d9b500d3SAart Bik Operation *printComma = getPrintComma(op); 1030d9b500d3SAart Bik int64_t dim = vectorType.getDimSize(0); 1031d9b500d3SAart Bik for (int64_t d = 0; d < dim; ++d) { 1032d9b500d3SAart Bik auto reducedType = 1033d9b500d3SAart Bik rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr; 10340f04384dSAlex Zinenko auto llvmType = typeConverter.convertType( 1035d9b500d3SAart Bik rank > 1 ? reducedType : vectorType.getElementType()); 1036e62a6956SRiver Riddle Value nestedVal = 10370f04384dSAlex Zinenko extractOne(rewriter, typeConverter, loc, value, llvmType, rank, d); 1038d9b500d3SAart Bik emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1); 1039d9b500d3SAart Bik if (d != dim - 1) 1040d9b500d3SAart Bik emitCall(rewriter, loc, printComma); 1041d9b500d3SAart Bik } 1042d9b500d3SAart Bik emitCall(rewriter, loc, getPrintClose(op)); 1043d9b500d3SAart Bik } 1044d9b500d3SAart Bik 1045d9b500d3SAart Bik // Helper to emit a call. 1046d9b500d3SAart Bik static void emitCall(ConversionPatternRewriter &rewriter, Location loc, 1047d9b500d3SAart Bik Operation *ref, ValueRange params = ValueRange()) { 1048d9b500d3SAart Bik rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{}, 1049d9b500d3SAart Bik rewriter.getSymbolRefAttr(ref), params); 1050d9b500d3SAart Bik } 1051d9b500d3SAart Bik 1052d9b500d3SAart Bik // Helper for printer method declaration (first hit) and lookup. 1053d9b500d3SAart Bik static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect, 1054d9b500d3SAart Bik StringRef name, ArrayRef<LLVM::LLVMType> params) { 1055d9b500d3SAart Bik auto module = op->getParentOfType<ModuleOp>(); 1056d9b500d3SAart Bik auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name); 1057d9b500d3SAart Bik if (func) 1058d9b500d3SAart Bik return func; 1059d9b500d3SAart Bik OpBuilder moduleBuilder(module.getBodyRegion()); 1060d9b500d3SAart Bik return moduleBuilder.create<LLVM::LLVMFuncOp>( 1061d9b500d3SAart Bik op->getLoc(), name, 1062d9b500d3SAart Bik LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect), 1063d9b500d3SAart Bik params, /*isVarArg=*/false)); 1064d9b500d3SAart Bik } 1065d9b500d3SAart Bik 1066d9b500d3SAart Bik // Helpers for method names. 10676937251fSaartbik Operation *getPrintI1(Operation *op) const { 10686937251fSaartbik LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 10696937251fSaartbik return getPrint(op, dialect, "print_i1", 10706937251fSaartbik LLVM::LLVMType::getInt1Ty(dialect)); 10716937251fSaartbik } 1072e52414b1Saartbik Operation *getPrintI32(Operation *op) const { 10730f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1074e52414b1Saartbik return getPrint(op, dialect, "print_i32", 1075e52414b1Saartbik LLVM::LLVMType::getInt32Ty(dialect)); 1076e52414b1Saartbik } 1077e52414b1Saartbik Operation *getPrintI64(Operation *op) const { 10780f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1079e52414b1Saartbik return getPrint(op, dialect, "print_i64", 1080e52414b1Saartbik LLVM::LLVMType::getInt64Ty(dialect)); 1081e52414b1Saartbik } 1082d9b500d3SAart Bik Operation *getPrintFloat(Operation *op) const { 10830f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1084d9b500d3SAart Bik return getPrint(op, dialect, "print_f32", 1085d9b500d3SAart Bik LLVM::LLVMType::getFloatTy(dialect)); 1086d9b500d3SAart Bik } 1087d9b500d3SAart Bik Operation *getPrintDouble(Operation *op) const { 10880f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1089d9b500d3SAart Bik return getPrint(op, dialect, "print_f64", 1090d9b500d3SAart Bik LLVM::LLVMType::getDoubleTy(dialect)); 1091d9b500d3SAart Bik } 1092d9b500d3SAart Bik Operation *getPrintOpen(Operation *op) const { 10930f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_open", {}); 1094d9b500d3SAart Bik } 1095d9b500d3SAart Bik Operation *getPrintClose(Operation *op) const { 10960f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_close", {}); 1097d9b500d3SAart Bik } 1098d9b500d3SAart Bik Operation *getPrintComma(Operation *op) const { 10990f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_comma", {}); 1100d9b500d3SAart Bik } 1101d9b500d3SAart Bik Operation *getPrintNewline(Operation *op) const { 11020f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_newline", {}); 1103d9b500d3SAart Bik } 1104d9b500d3SAart Bik }; 1105d9b500d3SAart Bik 1106334a4159SReid Tatge /// Progressive lowering of ExtractStridedSliceOp to either: 110765678d93SNicolas Vasilache /// 1. extractelement + insertelement for the 1-D case 110865678d93SNicolas Vasilache /// 2. extract + optional strided_slice + insert for the n-D case. 1109334a4159SReid Tatge class VectorStridedSliceOpConversion 1110334a4159SReid Tatge : public OpRewritePattern<ExtractStridedSliceOp> { 111165678d93SNicolas Vasilache public: 1112334a4159SReid Tatge using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 111365678d93SNicolas Vasilache 1114334a4159SReid Tatge LogicalResult matchAndRewrite(ExtractStridedSliceOp op, 111565678d93SNicolas Vasilache PatternRewriter &rewriter) const override { 111665678d93SNicolas Vasilache auto dstType = op.getResult().getType().cast<VectorType>(); 111765678d93SNicolas Vasilache 111865678d93SNicolas Vasilache assert(!op.offsets().getValue().empty() && "Unexpected empty offsets"); 111965678d93SNicolas Vasilache 112065678d93SNicolas Vasilache int64_t offset = 112165678d93SNicolas Vasilache op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 112265678d93SNicolas Vasilache int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt(); 112365678d93SNicolas Vasilache int64_t stride = 112465678d93SNicolas Vasilache op.strides().getValue().front().cast<IntegerAttr>().getInt(); 112565678d93SNicolas Vasilache 112665678d93SNicolas Vasilache auto loc = op.getLoc(); 112765678d93SNicolas Vasilache auto elemType = dstType.getElementType(); 112835b68527SLei Zhang assert(elemType.isSignlessIntOrIndexOrFloat()); 112965678d93SNicolas Vasilache Value zero = rewriter.create<ConstantOp>(loc, elemType, 113065678d93SNicolas Vasilache rewriter.getZeroAttr(elemType)); 113165678d93SNicolas Vasilache Value res = rewriter.create<SplatOp>(loc, dstType, zero); 113265678d93SNicolas Vasilache for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 113365678d93SNicolas Vasilache off += stride, ++idx) { 113465678d93SNicolas Vasilache Value extracted = extractOne(rewriter, loc, op.vector(), off); 113565678d93SNicolas Vasilache if (op.offsets().getValue().size() > 1) { 1136334a4159SReid Tatge extracted = rewriter.create<ExtractStridedSliceOp>( 113765678d93SNicolas Vasilache loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1), 113865678d93SNicolas Vasilache getI64SubArray(op.sizes(), /* dropFront=*/1), 113965678d93SNicolas Vasilache getI64SubArray(op.strides(), /* dropFront=*/1)); 114065678d93SNicolas Vasilache } 114165678d93SNicolas Vasilache res = insertOne(rewriter, loc, extracted, res, idx); 114265678d93SNicolas Vasilache } 114365678d93SNicolas Vasilache rewriter.replaceOp(op, {res}); 11443145427dSRiver Riddle return success(); 114565678d93SNicolas Vasilache } 1146334a4159SReid Tatge /// This pattern creates recursive ExtractStridedSliceOp, but the recursion is 1147bd1ccfe6SRiver Riddle /// bounded as the rank is strictly decreasing. 1148bd1ccfe6SRiver Riddle bool hasBoundedRewriteRecursion() const final { return true; } 114965678d93SNicolas Vasilache }; 115065678d93SNicolas Vasilache 1151df186507SBenjamin Kramer } // namespace 1152df186507SBenjamin Kramer 11535c0c51a9SNicolas Vasilache /// Populate the given list with patterns that convert from Vector to LLVM. 11545c0c51a9SNicolas Vasilache void mlir::populateVectorToLLVMConversionPatterns( 11555c0c51a9SNicolas Vasilache LLVMTypeConverter &converter, OwningRewritePatternList &patterns) { 115665678d93SNicolas Vasilache MLIRContext *ctx = converter.getDialect()->getContext(); 11578345b86dSNicolas Vasilache // clang-format off 1158681f929fSNicolas Vasilache patterns.insert<VectorFMAOpNDRewritePattern, 1159681f929fSNicolas Vasilache VectorInsertStridedSliceOpDifferentRankRewritePattern, 11602d515e49SNicolas Vasilache VectorInsertStridedSliceOpSameRankRewritePattern, 11612d515e49SNicolas Vasilache VectorStridedSliceOpConversion>(ctx); 11628345b86dSNicolas Vasilache patterns 1163186709c6Saartbik .insert<VectorReductionOpConversion, 11648345b86dSNicolas Vasilache VectorShuffleOpConversion, 11658345b86dSNicolas Vasilache VectorExtractElementOpConversion, 11668345b86dSNicolas Vasilache VectorExtractOpConversion, 11678345b86dSNicolas Vasilache VectorFMAOp1DConversion, 11688345b86dSNicolas Vasilache VectorInsertElementOpConversion, 11698345b86dSNicolas Vasilache VectorInsertOpConversion, 11708345b86dSNicolas Vasilache VectorPrintOpConversion, 11718345b86dSNicolas Vasilache VectorTransferConversion<TransferReadOp>, 11728345b86dSNicolas Vasilache VectorTransferConversion<TransferWriteOp>, 11738345b86dSNicolas Vasilache VectorTypeCastOpConversion>(ctx, converter); 11748345b86dSNicolas Vasilache // clang-format on 11755c0c51a9SNicolas Vasilache } 11765c0c51a9SNicolas Vasilache 117763b683a8SNicolas Vasilache void mlir::populateVectorToLLVMMatrixConversionPatterns( 117863b683a8SNicolas Vasilache LLVMTypeConverter &converter, OwningRewritePatternList &patterns) { 117963b683a8SNicolas Vasilache MLIRContext *ctx = converter.getDialect()->getContext(); 118063b683a8SNicolas Vasilache patterns.insert<VectorMatmulOpConversion>(ctx, converter); 1181*c295a65dSaartbik patterns.insert<VectorFlatTransposeOpConversion>(ctx, converter); 118263b683a8SNicolas Vasilache } 118363b683a8SNicolas Vasilache 11845c0c51a9SNicolas Vasilache namespace { 1185722f909fSRiver Riddle struct LowerVectorToLLVMPass 11861834ad4aSRiver Riddle : public ConvertVectorToLLVMBase<LowerVectorToLLVMPass> { 1187722f909fSRiver Riddle void runOnOperation() override; 11885c0c51a9SNicolas Vasilache }; 11895c0c51a9SNicolas Vasilache } // namespace 11905c0c51a9SNicolas Vasilache 1191722f909fSRiver Riddle void LowerVectorToLLVMPass::runOnOperation() { 1192078776a6Saartbik // Perform progressive lowering of operations on slices and 1193b21c7999Saartbik // all contraction operations. Also applies folding and DCE. 1194459cf6e5Saartbik { 11955c0c51a9SNicolas Vasilache OwningRewritePatternList patterns; 1196b1c688dbSaartbik populateVectorToVectorCanonicalizationPatterns(patterns, &getContext()); 1197459cf6e5Saartbik populateVectorSlicesLoweringPatterns(patterns, &getContext()); 1198b21c7999Saartbik populateVectorContractLoweringPatterns(patterns, &getContext()); 1199a5b9316bSUday Bondhugula applyPatternsAndFoldGreedily(getOperation(), patterns); 1200459cf6e5Saartbik } 1201459cf6e5Saartbik 1202459cf6e5Saartbik // Convert to the LLVM IR dialect. 12035c0c51a9SNicolas Vasilache LLVMTypeConverter converter(&getContext()); 1204459cf6e5Saartbik OwningRewritePatternList patterns; 120563b683a8SNicolas Vasilache populateVectorToLLVMMatrixConversionPatterns(converter, patterns); 12065c0c51a9SNicolas Vasilache populateVectorToLLVMConversionPatterns(converter, patterns); 1207bbf3ef85SNicolas Vasilache populateVectorToLLVMMatrixConversionPatterns(converter, patterns); 12085c0c51a9SNicolas Vasilache populateStdToLLVMConversionPatterns(converter, patterns); 12095c0c51a9SNicolas Vasilache 12102a00ae39STim Shen LLVMConversionTarget target(getContext()); 12115c0c51a9SNicolas Vasilache target.addDynamicallyLegalOp<FuncOp>( 12125c0c51a9SNicolas Vasilache [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); }); 1213722f909fSRiver Riddle if (failed(applyPartialConversion(getOperation(), target, patterns, 1214722f909fSRiver Riddle &converter))) { 12155c0c51a9SNicolas Vasilache signalPassFailure(); 12165c0c51a9SNicolas Vasilache } 12175c0c51a9SNicolas Vasilache } 12185c0c51a9SNicolas Vasilache 121980aca1eaSRiver Riddle std::unique_ptr<OperationPass<ModuleOp>> mlir::createConvertVectorToLLVMPass() { 12202fae7878SNicolas Vasilache return std::make_unique<LowerVectorToLLVMPass>(); 12215c0c51a9SNicolas Vasilache } 1222