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 151870c1fd4SAlex Zinenko class VectorReductionOpConversion : public ConvertToLLVMPattern { 152e83b7b99Saartbik public: 153e83b7b99Saartbik explicit VectorReductionOpConversion(MLIRContext *context, 154e83b7b99Saartbik LLVMTypeConverter &typeConverter) 155870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ReductionOp::getOperationName(), context, 156e83b7b99Saartbik typeConverter) {} 157e83b7b99Saartbik 1583145427dSRiver Riddle LogicalResult 159e83b7b99Saartbik matchAndRewrite(Operation *op, ArrayRef<Value> operands, 160e83b7b99Saartbik ConversionPatternRewriter &rewriter) const override { 161e83b7b99Saartbik auto reductionOp = cast<vector::ReductionOp>(op); 162e83b7b99Saartbik auto kind = reductionOp.kind(); 163e83b7b99Saartbik Type eltType = reductionOp.dest().getType(); 1640f04384dSAlex Zinenko Type llvmType = typeConverter.convertType(eltType); 16535b68527SLei Zhang if (eltType.isSignlessInteger(32) || eltType.isSignlessInteger(64)) { 166e83b7b99Saartbik // Integer reductions: add/mul/min/max/and/or/xor. 167e83b7b99Saartbik if (kind == "add") 168e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_add>( 169e83b7b99Saartbik op, llvmType, operands[0]); 170e83b7b99Saartbik else if (kind == "mul") 171e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_mul>( 172e83b7b99Saartbik op, llvmType, operands[0]); 173e83b7b99Saartbik else if (kind == "min") 174e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smin>( 175e83b7b99Saartbik op, llvmType, operands[0]); 176e83b7b99Saartbik else if (kind == "max") 177e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smax>( 178e83b7b99Saartbik op, llvmType, operands[0]); 179e83b7b99Saartbik else if (kind == "and") 180e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_and>( 181e83b7b99Saartbik op, llvmType, operands[0]); 182e83b7b99Saartbik else if (kind == "or") 183e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_or>( 184e83b7b99Saartbik op, llvmType, operands[0]); 185e83b7b99Saartbik else if (kind == "xor") 186e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_xor>( 187e83b7b99Saartbik op, llvmType, operands[0]); 188e83b7b99Saartbik else 1893145427dSRiver Riddle return failure(); 1903145427dSRiver Riddle return success(); 191e83b7b99Saartbik 192e83b7b99Saartbik } else if (eltType.isF32() || eltType.isF64()) { 193e83b7b99Saartbik // Floating-point reductions: add/mul/min/max 194e83b7b99Saartbik if (kind == "add") { 1950d924700Saartbik // Optional accumulator (or zero). 1960d924700Saartbik Value acc = operands.size() > 1 ? operands[1] 1970d924700Saartbik : rewriter.create<LLVM::ConstantOp>( 1980d924700Saartbik op->getLoc(), llvmType, 1990d924700Saartbik rewriter.getZeroAttr(eltType)); 200e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fadd>( 2010d924700Saartbik op, llvmType, acc, operands[0]); 202e83b7b99Saartbik } else if (kind == "mul") { 2030d924700Saartbik // Optional accumulator (or one). 2040d924700Saartbik Value acc = operands.size() > 1 2050d924700Saartbik ? operands[1] 2060d924700Saartbik : rewriter.create<LLVM::ConstantOp>( 2070d924700Saartbik op->getLoc(), llvmType, 2080d924700Saartbik rewriter.getFloatAttr(eltType, 1.0)); 209e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fmul>( 2100d924700Saartbik op, llvmType, acc, operands[0]); 211e83b7b99Saartbik } else if (kind == "min") 212e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmin>( 213e83b7b99Saartbik op, llvmType, operands[0]); 214e83b7b99Saartbik else if (kind == "max") 215e83b7b99Saartbik rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmax>( 216e83b7b99Saartbik op, llvmType, operands[0]); 217e83b7b99Saartbik else 2183145427dSRiver Riddle return failure(); 2193145427dSRiver Riddle return success(); 220e83b7b99Saartbik } 2213145427dSRiver Riddle return failure(); 222e83b7b99Saartbik } 223e83b7b99Saartbik }; 224e83b7b99Saartbik 225870c1fd4SAlex Zinenko class VectorShuffleOpConversion : public ConvertToLLVMPattern { 2261c81adf3SAart Bik public: 2271c81adf3SAart Bik explicit VectorShuffleOpConversion(MLIRContext *context, 2281c81adf3SAart Bik LLVMTypeConverter &typeConverter) 229870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ShuffleOp::getOperationName(), context, 2301c81adf3SAart Bik typeConverter) {} 2311c81adf3SAart Bik 2323145427dSRiver Riddle LogicalResult 233e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 2341c81adf3SAart Bik ConversionPatternRewriter &rewriter) const override { 2351c81adf3SAart Bik auto loc = op->getLoc(); 2361c81adf3SAart Bik auto adaptor = vector::ShuffleOpOperandAdaptor(operands); 2371c81adf3SAart Bik auto shuffleOp = cast<vector::ShuffleOp>(op); 2381c81adf3SAart Bik auto v1Type = shuffleOp.getV1VectorType(); 2391c81adf3SAart Bik auto v2Type = shuffleOp.getV2VectorType(); 2401c81adf3SAart Bik auto vectorType = shuffleOp.getVectorType(); 2410f04384dSAlex Zinenko Type llvmType = typeConverter.convertType(vectorType); 2421c81adf3SAart Bik auto maskArrayAttr = shuffleOp.mask(); 2431c81adf3SAart Bik 2441c81adf3SAart Bik // Bail if result type cannot be lowered. 2451c81adf3SAart Bik if (!llvmType) 2463145427dSRiver Riddle return failure(); 2471c81adf3SAart Bik 2481c81adf3SAart Bik // Get rank and dimension sizes. 2491c81adf3SAart Bik int64_t rank = vectorType.getRank(); 2501c81adf3SAart Bik assert(v1Type.getRank() == rank); 2511c81adf3SAart Bik assert(v2Type.getRank() == rank); 2521c81adf3SAart Bik int64_t v1Dim = v1Type.getDimSize(0); 2531c81adf3SAart Bik 2541c81adf3SAart Bik // For rank 1, where both operands have *exactly* the same vector type, 2551c81adf3SAart Bik // there is direct shuffle support in LLVM. Use it! 2561c81adf3SAart Bik if (rank == 1 && v1Type == v2Type) { 257e62a6956SRiver Riddle Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>( 2581c81adf3SAart Bik loc, adaptor.v1(), adaptor.v2(), maskArrayAttr); 2591c81adf3SAart Bik rewriter.replaceOp(op, shuffle); 2603145427dSRiver Riddle return success(); 261b36aaeafSAart Bik } 262b36aaeafSAart Bik 2631c81adf3SAart Bik // For all other cases, insert the individual values individually. 264e62a6956SRiver Riddle Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType); 2651c81adf3SAart Bik int64_t insPos = 0; 2661c81adf3SAart Bik for (auto en : llvm::enumerate(maskArrayAttr)) { 2671c81adf3SAart Bik int64_t extPos = en.value().cast<IntegerAttr>().getInt(); 268e62a6956SRiver Riddle Value value = adaptor.v1(); 2691c81adf3SAart Bik if (extPos >= v1Dim) { 2701c81adf3SAart Bik extPos -= v1Dim; 2711c81adf3SAart Bik value = adaptor.v2(); 272b36aaeafSAart Bik } 2730f04384dSAlex Zinenko Value extract = extractOne(rewriter, typeConverter, loc, value, llvmType, 2740f04384dSAlex Zinenko rank, extPos); 2750f04384dSAlex Zinenko insert = insertOne(rewriter, typeConverter, loc, insert, extract, 2760f04384dSAlex Zinenko llvmType, rank, insPos++); 2771c81adf3SAart Bik } 2781c81adf3SAart Bik rewriter.replaceOp(op, insert); 2793145427dSRiver Riddle return success(); 280b36aaeafSAart Bik } 281b36aaeafSAart Bik }; 282b36aaeafSAart Bik 283870c1fd4SAlex Zinenko class VectorExtractElementOpConversion : public ConvertToLLVMPattern { 284cd5dab8aSAart Bik public: 285cd5dab8aSAart Bik explicit VectorExtractElementOpConversion(MLIRContext *context, 286cd5dab8aSAart Bik LLVMTypeConverter &typeConverter) 287870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ExtractElementOp::getOperationName(), 288870c1fd4SAlex Zinenko context, typeConverter) {} 289cd5dab8aSAart Bik 2903145427dSRiver Riddle LogicalResult 291e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 292cd5dab8aSAart Bik ConversionPatternRewriter &rewriter) const override { 293cd5dab8aSAart Bik auto adaptor = vector::ExtractElementOpOperandAdaptor(operands); 294cd5dab8aSAart Bik auto extractEltOp = cast<vector::ExtractElementOp>(op); 295cd5dab8aSAart Bik auto vectorType = extractEltOp.getVectorType(); 2960f04384dSAlex Zinenko auto llvmType = typeConverter.convertType(vectorType.getElementType()); 297cd5dab8aSAart Bik 298cd5dab8aSAart Bik // Bail if result type cannot be lowered. 299cd5dab8aSAart Bik if (!llvmType) 3003145427dSRiver Riddle return failure(); 301cd5dab8aSAart Bik 302cd5dab8aSAart Bik rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>( 303cd5dab8aSAart Bik op, llvmType, adaptor.vector(), adaptor.position()); 3043145427dSRiver Riddle return success(); 305cd5dab8aSAart Bik } 306cd5dab8aSAart Bik }; 307cd5dab8aSAart Bik 308870c1fd4SAlex Zinenko class VectorExtractOpConversion : public ConvertToLLVMPattern { 3095c0c51a9SNicolas Vasilache public: 3109826fe5cSAart Bik explicit VectorExtractOpConversion(MLIRContext *context, 3115c0c51a9SNicolas Vasilache LLVMTypeConverter &typeConverter) 312870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::ExtractOp::getOperationName(), context, 3135c0c51a9SNicolas Vasilache typeConverter) {} 3145c0c51a9SNicolas Vasilache 3153145427dSRiver Riddle LogicalResult 316e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 3175c0c51a9SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 3185c0c51a9SNicolas Vasilache auto loc = op->getLoc(); 319d37f2725SAart Bik auto adaptor = vector::ExtractOpOperandAdaptor(operands); 320d37f2725SAart Bik auto extractOp = cast<vector::ExtractOp>(op); 3219826fe5cSAart Bik auto vectorType = extractOp.getVectorType(); 3222bdf33ccSRiver Riddle auto resultType = extractOp.getResult().getType(); 3230f04384dSAlex Zinenko auto llvmResultType = typeConverter.convertType(resultType); 3245c0c51a9SNicolas Vasilache auto positionArrayAttr = extractOp.position(); 3259826fe5cSAart Bik 3269826fe5cSAart Bik // Bail if result type cannot be lowered. 3279826fe5cSAart Bik if (!llvmResultType) 3283145427dSRiver Riddle return failure(); 3299826fe5cSAart Bik 3305c0c51a9SNicolas Vasilache // One-shot extraction of vector from array (only requires extractvalue). 3315c0c51a9SNicolas Vasilache if (resultType.isa<VectorType>()) { 332e62a6956SRiver Riddle Value extracted = rewriter.create<LLVM::ExtractValueOp>( 3335c0c51a9SNicolas Vasilache loc, llvmResultType, adaptor.vector(), positionArrayAttr); 3345c0c51a9SNicolas Vasilache rewriter.replaceOp(op, extracted); 3353145427dSRiver Riddle return success(); 3365c0c51a9SNicolas Vasilache } 3375c0c51a9SNicolas Vasilache 3389826fe5cSAart Bik // Potential extraction of 1-D vector from array. 3395c0c51a9SNicolas Vasilache auto *context = op->getContext(); 340e62a6956SRiver Riddle Value extracted = adaptor.vector(); 3415c0c51a9SNicolas Vasilache auto positionAttrs = positionArrayAttr.getValue(); 3425c0c51a9SNicolas Vasilache if (positionAttrs.size() > 1) { 3439826fe5cSAart Bik auto oneDVectorType = reducedVectorTypeBack(vectorType); 3445c0c51a9SNicolas Vasilache auto nMinusOnePositionAttrs = 3455c0c51a9SNicolas Vasilache ArrayAttr::get(positionAttrs.drop_back(), context); 3465c0c51a9SNicolas Vasilache extracted = rewriter.create<LLVM::ExtractValueOp>( 3470f04384dSAlex Zinenko loc, typeConverter.convertType(oneDVectorType), extracted, 3485c0c51a9SNicolas Vasilache nMinusOnePositionAttrs); 3495c0c51a9SNicolas Vasilache } 3505c0c51a9SNicolas Vasilache 3515c0c51a9SNicolas Vasilache // Remaining extraction of element from 1-D LLVM vector 3525c0c51a9SNicolas Vasilache auto position = positionAttrs.back().cast<IntegerAttr>(); 3530f04384dSAlex Zinenko auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect()); 3541d47564aSAart Bik auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 3555c0c51a9SNicolas Vasilache extracted = 3565c0c51a9SNicolas Vasilache rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant); 3575c0c51a9SNicolas Vasilache rewriter.replaceOp(op, extracted); 3585c0c51a9SNicolas Vasilache 3593145427dSRiver Riddle return success(); 3605c0c51a9SNicolas Vasilache } 3615c0c51a9SNicolas Vasilache }; 3625c0c51a9SNicolas Vasilache 363681f929fSNicolas Vasilache /// Conversion pattern that turns a vector.fma on a 1-D vector 364681f929fSNicolas Vasilache /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion. 365681f929fSNicolas Vasilache /// This does not match vectors of n >= 2 rank. 366681f929fSNicolas Vasilache /// 367681f929fSNicolas Vasilache /// Example: 368681f929fSNicolas Vasilache /// ``` 369681f929fSNicolas Vasilache /// vector.fma %a, %a, %a : vector<8xf32> 370681f929fSNicolas Vasilache /// ``` 371681f929fSNicolas Vasilache /// is converted to: 372681f929fSNicolas Vasilache /// ``` 373681f929fSNicolas Vasilache /// llvm.intr.fma %va, %va, %va: 374681f929fSNicolas Vasilache /// (!llvm<"<8 x float>">, !llvm<"<8 x float>">, !llvm<"<8 x float>">) 375681f929fSNicolas Vasilache /// -> !llvm<"<8 x float>"> 376681f929fSNicolas Vasilache /// ``` 377870c1fd4SAlex Zinenko class VectorFMAOp1DConversion : public ConvertToLLVMPattern { 378681f929fSNicolas Vasilache public: 379681f929fSNicolas Vasilache explicit VectorFMAOp1DConversion(MLIRContext *context, 380681f929fSNicolas Vasilache LLVMTypeConverter &typeConverter) 381870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::FMAOp::getOperationName(), context, 382681f929fSNicolas Vasilache typeConverter) {} 383681f929fSNicolas Vasilache 3843145427dSRiver Riddle LogicalResult 385681f929fSNicolas Vasilache matchAndRewrite(Operation *op, ArrayRef<Value> operands, 386681f929fSNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 387681f929fSNicolas Vasilache auto adaptor = vector::FMAOpOperandAdaptor(operands); 388681f929fSNicolas Vasilache vector::FMAOp fmaOp = cast<vector::FMAOp>(op); 389681f929fSNicolas Vasilache VectorType vType = fmaOp.getVectorType(); 390681f929fSNicolas Vasilache if (vType.getRank() != 1) 3913145427dSRiver Riddle return failure(); 392681f929fSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::FMAOp>(op, adaptor.lhs(), adaptor.rhs(), 393681f929fSNicolas Vasilache adaptor.acc()); 3943145427dSRiver Riddle return success(); 395681f929fSNicolas Vasilache } 396681f929fSNicolas Vasilache }; 397681f929fSNicolas Vasilache 398870c1fd4SAlex Zinenko class VectorInsertElementOpConversion : public ConvertToLLVMPattern { 399cd5dab8aSAart Bik public: 400cd5dab8aSAart Bik explicit VectorInsertElementOpConversion(MLIRContext *context, 401cd5dab8aSAart Bik LLVMTypeConverter &typeConverter) 402870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::InsertElementOp::getOperationName(), 403870c1fd4SAlex Zinenko context, typeConverter) {} 404cd5dab8aSAart Bik 4053145427dSRiver Riddle LogicalResult 406e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 407cd5dab8aSAart Bik ConversionPatternRewriter &rewriter) const override { 408cd5dab8aSAart Bik auto adaptor = vector::InsertElementOpOperandAdaptor(operands); 409cd5dab8aSAart Bik auto insertEltOp = cast<vector::InsertElementOp>(op); 410cd5dab8aSAart Bik auto vectorType = insertEltOp.getDestVectorType(); 4110f04384dSAlex Zinenko auto llvmType = typeConverter.convertType(vectorType); 412cd5dab8aSAart Bik 413cd5dab8aSAart Bik // Bail if result type cannot be lowered. 414cd5dab8aSAart Bik if (!llvmType) 4153145427dSRiver Riddle return failure(); 416cd5dab8aSAart Bik 417cd5dab8aSAart Bik rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>( 418cd5dab8aSAart Bik op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position()); 4193145427dSRiver Riddle return success(); 420cd5dab8aSAart Bik } 421cd5dab8aSAart Bik }; 422cd5dab8aSAart Bik 423870c1fd4SAlex Zinenko class VectorInsertOpConversion : public ConvertToLLVMPattern { 4249826fe5cSAart Bik public: 4259826fe5cSAart Bik explicit VectorInsertOpConversion(MLIRContext *context, 4269826fe5cSAart Bik LLVMTypeConverter &typeConverter) 427870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::InsertOp::getOperationName(), context, 4289826fe5cSAart Bik typeConverter) {} 4299826fe5cSAart Bik 4303145427dSRiver Riddle LogicalResult 431e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 4329826fe5cSAart Bik ConversionPatternRewriter &rewriter) const override { 4339826fe5cSAart Bik auto loc = op->getLoc(); 4349826fe5cSAart Bik auto adaptor = vector::InsertOpOperandAdaptor(operands); 4359826fe5cSAart Bik auto insertOp = cast<vector::InsertOp>(op); 4369826fe5cSAart Bik auto sourceType = insertOp.getSourceType(); 4379826fe5cSAart Bik auto destVectorType = insertOp.getDestVectorType(); 4380f04384dSAlex Zinenko auto llvmResultType = typeConverter.convertType(destVectorType); 4399826fe5cSAart Bik auto positionArrayAttr = insertOp.position(); 4409826fe5cSAart Bik 4419826fe5cSAart Bik // Bail if result type cannot be lowered. 4429826fe5cSAart Bik if (!llvmResultType) 4433145427dSRiver Riddle return failure(); 4449826fe5cSAart Bik 4459826fe5cSAart Bik // One-shot insertion of a vector into an array (only requires insertvalue). 4469826fe5cSAart Bik if (sourceType.isa<VectorType>()) { 447e62a6956SRiver Riddle Value inserted = rewriter.create<LLVM::InsertValueOp>( 4489826fe5cSAart Bik loc, llvmResultType, adaptor.dest(), adaptor.source(), 4499826fe5cSAart Bik positionArrayAttr); 4509826fe5cSAart Bik rewriter.replaceOp(op, inserted); 4513145427dSRiver Riddle return success(); 4529826fe5cSAart Bik } 4539826fe5cSAart Bik 4549826fe5cSAart Bik // Potential extraction of 1-D vector from array. 4559826fe5cSAart Bik auto *context = op->getContext(); 456e62a6956SRiver Riddle Value extracted = adaptor.dest(); 4579826fe5cSAart Bik auto positionAttrs = positionArrayAttr.getValue(); 4589826fe5cSAart Bik auto position = positionAttrs.back().cast<IntegerAttr>(); 4599826fe5cSAart Bik auto oneDVectorType = destVectorType; 4609826fe5cSAart Bik if (positionAttrs.size() > 1) { 4619826fe5cSAart Bik oneDVectorType = reducedVectorTypeBack(destVectorType); 4629826fe5cSAart Bik auto nMinusOnePositionAttrs = 4639826fe5cSAart Bik ArrayAttr::get(positionAttrs.drop_back(), context); 4649826fe5cSAart Bik extracted = rewriter.create<LLVM::ExtractValueOp>( 4650f04384dSAlex Zinenko loc, typeConverter.convertType(oneDVectorType), extracted, 4669826fe5cSAart Bik nMinusOnePositionAttrs); 4679826fe5cSAart Bik } 4689826fe5cSAart Bik 4699826fe5cSAart Bik // Insertion of an element into a 1-D LLVM vector. 4700f04384dSAlex Zinenko auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect()); 4711d47564aSAart Bik auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position); 472e62a6956SRiver Riddle Value inserted = rewriter.create<LLVM::InsertElementOp>( 4730f04384dSAlex Zinenko loc, typeConverter.convertType(oneDVectorType), extracted, 4740f04384dSAlex Zinenko adaptor.source(), constant); 4759826fe5cSAart Bik 4769826fe5cSAart Bik // Potential insertion of resulting 1-D vector into array. 4779826fe5cSAart Bik if (positionAttrs.size() > 1) { 4789826fe5cSAart Bik auto nMinusOnePositionAttrs = 4799826fe5cSAart Bik ArrayAttr::get(positionAttrs.drop_back(), context); 4809826fe5cSAart Bik inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType, 4819826fe5cSAart Bik adaptor.dest(), inserted, 4829826fe5cSAart Bik nMinusOnePositionAttrs); 4839826fe5cSAart Bik } 4849826fe5cSAart Bik 4859826fe5cSAart Bik rewriter.replaceOp(op, inserted); 4863145427dSRiver Riddle return success(); 4879826fe5cSAart Bik } 4889826fe5cSAart Bik }; 4899826fe5cSAart Bik 490681f929fSNicolas Vasilache /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1. 491681f929fSNicolas Vasilache /// 492681f929fSNicolas Vasilache /// Example: 493681f929fSNicolas Vasilache /// ``` 494681f929fSNicolas Vasilache /// %d = vector.fma %a, %b, %c : vector<2x4xf32> 495681f929fSNicolas Vasilache /// ``` 496681f929fSNicolas Vasilache /// is rewritten into: 497681f929fSNicolas Vasilache /// ``` 498681f929fSNicolas Vasilache /// %r = splat %f0: vector<2x4xf32> 499681f929fSNicolas Vasilache /// %va = vector.extractvalue %a[0] : vector<2x4xf32> 500681f929fSNicolas Vasilache /// %vb = vector.extractvalue %b[0] : vector<2x4xf32> 501681f929fSNicolas Vasilache /// %vc = vector.extractvalue %c[0] : vector<2x4xf32> 502681f929fSNicolas Vasilache /// %vd = vector.fma %va, %vb, %vc : vector<4xf32> 503681f929fSNicolas Vasilache /// %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32> 504681f929fSNicolas Vasilache /// %va2 = vector.extractvalue %a2[1] : vector<2x4xf32> 505681f929fSNicolas Vasilache /// %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32> 506681f929fSNicolas Vasilache /// %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32> 507681f929fSNicolas Vasilache /// %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32> 508681f929fSNicolas Vasilache /// %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32> 509681f929fSNicolas Vasilache /// // %r3 holds the final value. 510681f929fSNicolas Vasilache /// ``` 511681f929fSNicolas Vasilache class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> { 512681f929fSNicolas Vasilache public: 513681f929fSNicolas Vasilache using OpRewritePattern<FMAOp>::OpRewritePattern; 514681f929fSNicolas Vasilache 5153145427dSRiver Riddle LogicalResult matchAndRewrite(FMAOp op, 516681f929fSNicolas Vasilache PatternRewriter &rewriter) const override { 517681f929fSNicolas Vasilache auto vType = op.getVectorType(); 518681f929fSNicolas Vasilache if (vType.getRank() < 2) 5193145427dSRiver Riddle return failure(); 520681f929fSNicolas Vasilache 521681f929fSNicolas Vasilache auto loc = op.getLoc(); 522681f929fSNicolas Vasilache auto elemType = vType.getElementType(); 523681f929fSNicolas Vasilache Value zero = rewriter.create<ConstantOp>(loc, elemType, 524681f929fSNicolas Vasilache rewriter.getZeroAttr(elemType)); 525681f929fSNicolas Vasilache Value desc = rewriter.create<SplatOp>(loc, vType, zero); 526681f929fSNicolas Vasilache for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) { 527681f929fSNicolas Vasilache Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i); 528681f929fSNicolas Vasilache Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i); 529681f929fSNicolas Vasilache Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i); 530681f929fSNicolas Vasilache Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC); 531681f929fSNicolas Vasilache desc = rewriter.create<InsertOp>(loc, fma, desc, i); 532681f929fSNicolas Vasilache } 533681f929fSNicolas Vasilache rewriter.replaceOp(op, desc); 5343145427dSRiver Riddle return success(); 535681f929fSNicolas Vasilache } 536681f929fSNicolas Vasilache }; 537681f929fSNicolas Vasilache 5382d515e49SNicolas Vasilache // When ranks are different, InsertStridedSlice needs to extract a properly 5392d515e49SNicolas Vasilache // ranked vector from the destination vector into which to insert. This pattern 5402d515e49SNicolas Vasilache // only takes care of this part and forwards the rest of the conversion to 5412d515e49SNicolas Vasilache // another pattern that converts InsertStridedSlice for operands of the same 5422d515e49SNicolas Vasilache // rank. 5432d515e49SNicolas Vasilache // 5442d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors 5452d515e49SNicolas Vasilache // have different ranks. In this case: 5462d515e49SNicolas Vasilache // 1. the proper subvector is extracted from the destination vector 5472d515e49SNicolas Vasilache // 2. a new InsertStridedSlice op is created to insert the source in the 5482d515e49SNicolas Vasilache // destination subvector 5492d515e49SNicolas Vasilache // 3. the destination subvector is inserted back in the proper place 5502d515e49SNicolas Vasilache // 4. the op is replaced by the result of step 3. 5512d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a 5522d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`. 5532d515e49SNicolas Vasilache class VectorInsertStridedSliceOpDifferentRankRewritePattern 5542d515e49SNicolas Vasilache : public OpRewritePattern<InsertStridedSliceOp> { 5552d515e49SNicolas Vasilache public: 5562d515e49SNicolas Vasilache using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 5572d515e49SNicolas Vasilache 5583145427dSRiver Riddle LogicalResult matchAndRewrite(InsertStridedSliceOp op, 5592d515e49SNicolas Vasilache PatternRewriter &rewriter) const override { 5602d515e49SNicolas Vasilache auto srcType = op.getSourceVectorType(); 5612d515e49SNicolas Vasilache auto dstType = op.getDestVectorType(); 5622d515e49SNicolas Vasilache 5632d515e49SNicolas Vasilache if (op.offsets().getValue().empty()) 5643145427dSRiver Riddle return failure(); 5652d515e49SNicolas Vasilache 5662d515e49SNicolas Vasilache auto loc = op.getLoc(); 5672d515e49SNicolas Vasilache int64_t rankDiff = dstType.getRank() - srcType.getRank(); 5682d515e49SNicolas Vasilache assert(rankDiff >= 0); 5692d515e49SNicolas Vasilache if (rankDiff == 0) 5703145427dSRiver Riddle return failure(); 5712d515e49SNicolas Vasilache 5722d515e49SNicolas Vasilache int64_t rankRest = dstType.getRank() - rankDiff; 5732d515e49SNicolas Vasilache // Extract / insert the subvector of matching rank and InsertStridedSlice 5742d515e49SNicolas Vasilache // on it. 5752d515e49SNicolas Vasilache Value extracted = 5762d515e49SNicolas Vasilache rewriter.create<ExtractOp>(loc, op.dest(), 5772d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/0, 5782d515e49SNicolas Vasilache /*dropFront=*/rankRest)); 5792d515e49SNicolas Vasilache // A different pattern will kick in for InsertStridedSlice with matching 5802d515e49SNicolas Vasilache // ranks. 5812d515e49SNicolas Vasilache auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>( 5822d515e49SNicolas Vasilache loc, op.source(), extracted, 5832d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/rankDiff), 584c8fc76a9Saartbik getI64SubArray(op.strides(), /*dropFront=*/0)); 5852d515e49SNicolas Vasilache rewriter.replaceOpWithNewOp<InsertOp>( 5862d515e49SNicolas Vasilache op, stridedSliceInnerOp.getResult(), op.dest(), 5872d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /*dropFront=*/0, 5882d515e49SNicolas Vasilache /*dropFront=*/rankRest)); 5893145427dSRiver Riddle return success(); 5902d515e49SNicolas Vasilache } 5912d515e49SNicolas Vasilache }; 5922d515e49SNicolas Vasilache 5932d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors 5942d515e49SNicolas Vasilache // have the same rank. In this case, we reduce 5952d515e49SNicolas Vasilache // 1. the proper subvector is extracted from the destination vector 5962d515e49SNicolas Vasilache // 2. a new InsertStridedSlice op is created to insert the source in the 5972d515e49SNicolas Vasilache // destination subvector 5982d515e49SNicolas Vasilache // 3. the destination subvector is inserted back in the proper place 5992d515e49SNicolas Vasilache // 4. the op is replaced by the result of step 3. 6002d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a 6012d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`. 6022d515e49SNicolas Vasilache class VectorInsertStridedSliceOpSameRankRewritePattern 6032d515e49SNicolas Vasilache : public OpRewritePattern<InsertStridedSliceOp> { 6042d515e49SNicolas Vasilache public: 6052d515e49SNicolas Vasilache using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern; 6062d515e49SNicolas Vasilache 6073145427dSRiver Riddle LogicalResult matchAndRewrite(InsertStridedSliceOp op, 6082d515e49SNicolas Vasilache PatternRewriter &rewriter) const override { 6092d515e49SNicolas Vasilache auto srcType = op.getSourceVectorType(); 6102d515e49SNicolas Vasilache auto dstType = op.getDestVectorType(); 6112d515e49SNicolas Vasilache 6122d515e49SNicolas Vasilache if (op.offsets().getValue().empty()) 6133145427dSRiver Riddle return failure(); 6142d515e49SNicolas Vasilache 6152d515e49SNicolas Vasilache int64_t rankDiff = dstType.getRank() - srcType.getRank(); 6162d515e49SNicolas Vasilache assert(rankDiff >= 0); 6172d515e49SNicolas Vasilache if (rankDiff != 0) 6183145427dSRiver Riddle return failure(); 6192d515e49SNicolas Vasilache 6202d515e49SNicolas Vasilache if (srcType == dstType) { 6212d515e49SNicolas Vasilache rewriter.replaceOp(op, op.source()); 6223145427dSRiver Riddle return success(); 6232d515e49SNicolas Vasilache } 6242d515e49SNicolas Vasilache 6252d515e49SNicolas Vasilache int64_t offset = 6262d515e49SNicolas Vasilache op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 6272d515e49SNicolas Vasilache int64_t size = srcType.getShape().front(); 6282d515e49SNicolas Vasilache int64_t stride = 6292d515e49SNicolas Vasilache op.strides().getValue().front().cast<IntegerAttr>().getInt(); 6302d515e49SNicolas Vasilache 6312d515e49SNicolas Vasilache auto loc = op.getLoc(); 6322d515e49SNicolas Vasilache Value res = op.dest(); 6332d515e49SNicolas Vasilache // For each slice of the source vector along the most major dimension. 6342d515e49SNicolas Vasilache for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 6352d515e49SNicolas Vasilache off += stride, ++idx) { 6362d515e49SNicolas Vasilache // 1. extract the proper subvector (or element) from source 6372d515e49SNicolas Vasilache Value extractedSource = extractOne(rewriter, loc, op.source(), idx); 6382d515e49SNicolas Vasilache if (extractedSource.getType().isa<VectorType>()) { 6392d515e49SNicolas Vasilache // 2. If we have a vector, extract the proper subvector from destination 6402d515e49SNicolas Vasilache // Otherwise we are at the element level and no need to recurse. 6412d515e49SNicolas Vasilache Value extractedDest = extractOne(rewriter, loc, op.dest(), off); 6422d515e49SNicolas Vasilache // 3. Reduce the problem to lowering a new InsertStridedSlice op with 6432d515e49SNicolas Vasilache // smaller rank. 644bd1ccfe6SRiver Riddle extractedSource = rewriter.create<InsertStridedSliceOp>( 6452d515e49SNicolas Vasilache loc, extractedSource, extractedDest, 6462d515e49SNicolas Vasilache getI64SubArray(op.offsets(), /* dropFront=*/1), 6472d515e49SNicolas Vasilache getI64SubArray(op.strides(), /* dropFront=*/1)); 6482d515e49SNicolas Vasilache } 6492d515e49SNicolas Vasilache // 4. Insert the extractedSource into the res vector. 6502d515e49SNicolas Vasilache res = insertOne(rewriter, loc, extractedSource, res, off); 6512d515e49SNicolas Vasilache } 6522d515e49SNicolas Vasilache 6532d515e49SNicolas Vasilache rewriter.replaceOp(op, res); 6543145427dSRiver Riddle return success(); 6552d515e49SNicolas Vasilache } 656bd1ccfe6SRiver Riddle /// This pattern creates recursive InsertStridedSliceOp, but the recursion is 657bd1ccfe6SRiver Riddle /// bounded as the rank is strictly decreasing. 658bd1ccfe6SRiver Riddle bool hasBoundedRewriteRecursion() const final { return true; } 6592d515e49SNicolas Vasilache }; 6602d515e49SNicolas Vasilache 661870c1fd4SAlex Zinenko class VectorTypeCastOpConversion : public ConvertToLLVMPattern { 6625c0c51a9SNicolas Vasilache public: 6635c0c51a9SNicolas Vasilache explicit VectorTypeCastOpConversion(MLIRContext *context, 6645c0c51a9SNicolas Vasilache LLVMTypeConverter &typeConverter) 665870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::TypeCastOp::getOperationName(), context, 6665c0c51a9SNicolas Vasilache typeConverter) {} 6675c0c51a9SNicolas Vasilache 6683145427dSRiver Riddle LogicalResult 669e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 6705c0c51a9SNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 6715c0c51a9SNicolas Vasilache auto loc = op->getLoc(); 6725c0c51a9SNicolas Vasilache vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op); 6735c0c51a9SNicolas Vasilache MemRefType sourceMemRefType = 6742bdf33ccSRiver Riddle castOp.getOperand().getType().cast<MemRefType>(); 6755c0c51a9SNicolas Vasilache MemRefType targetMemRefType = 6762bdf33ccSRiver Riddle castOp.getResult().getType().cast<MemRefType>(); 6775c0c51a9SNicolas Vasilache 6785c0c51a9SNicolas Vasilache // Only static shape casts supported atm. 6795c0c51a9SNicolas Vasilache if (!sourceMemRefType.hasStaticShape() || 6805c0c51a9SNicolas Vasilache !targetMemRefType.hasStaticShape()) 6813145427dSRiver Riddle return failure(); 6825c0c51a9SNicolas Vasilache 6835c0c51a9SNicolas Vasilache auto llvmSourceDescriptorTy = 6842bdf33ccSRiver Riddle operands[0].getType().dyn_cast<LLVM::LLVMType>(); 6855c0c51a9SNicolas Vasilache if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy()) 6863145427dSRiver Riddle return failure(); 6875c0c51a9SNicolas Vasilache MemRefDescriptor sourceMemRef(operands[0]); 6885c0c51a9SNicolas Vasilache 6890f04384dSAlex Zinenko auto llvmTargetDescriptorTy = typeConverter.convertType(targetMemRefType) 6905c0c51a9SNicolas Vasilache .dyn_cast_or_null<LLVM::LLVMType>(); 6915c0c51a9SNicolas Vasilache if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy()) 6923145427dSRiver Riddle return failure(); 6935c0c51a9SNicolas Vasilache 6945c0c51a9SNicolas Vasilache int64_t offset; 6955c0c51a9SNicolas Vasilache SmallVector<int64_t, 4> strides; 6965c0c51a9SNicolas Vasilache auto successStrides = 6975c0c51a9SNicolas Vasilache getStridesAndOffset(sourceMemRefType, strides, offset); 6985c0c51a9SNicolas Vasilache bool isContiguous = (strides.back() == 1); 6995c0c51a9SNicolas Vasilache if (isContiguous) { 7005c0c51a9SNicolas Vasilache auto sizes = sourceMemRefType.getShape(); 7015c0c51a9SNicolas Vasilache for (int index = 0, e = strides.size() - 2; index < e; ++index) { 7025c0c51a9SNicolas Vasilache if (strides[index] != strides[index + 1] * sizes[index + 1]) { 7035c0c51a9SNicolas Vasilache isContiguous = false; 7045c0c51a9SNicolas Vasilache break; 7055c0c51a9SNicolas Vasilache } 7065c0c51a9SNicolas Vasilache } 7075c0c51a9SNicolas Vasilache } 7085c0c51a9SNicolas Vasilache // Only contiguous source tensors supported atm. 7095c0c51a9SNicolas Vasilache if (failed(successStrides) || !isContiguous) 7103145427dSRiver Riddle return failure(); 7115c0c51a9SNicolas Vasilache 7120f04384dSAlex Zinenko auto int64Ty = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect()); 7135c0c51a9SNicolas Vasilache 7145c0c51a9SNicolas Vasilache // Create descriptor. 7155c0c51a9SNicolas Vasilache auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy); 7165c0c51a9SNicolas Vasilache Type llvmTargetElementTy = desc.getElementType(); 7175c0c51a9SNicolas Vasilache // Set allocated ptr. 718e62a6956SRiver Riddle Value allocated = sourceMemRef.allocatedPtr(rewriter, loc); 7195c0c51a9SNicolas Vasilache allocated = 7205c0c51a9SNicolas Vasilache rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated); 7215c0c51a9SNicolas Vasilache desc.setAllocatedPtr(rewriter, loc, allocated); 7225c0c51a9SNicolas Vasilache // Set aligned ptr. 723e62a6956SRiver Riddle Value ptr = sourceMemRef.alignedPtr(rewriter, loc); 7245c0c51a9SNicolas Vasilache ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr); 7255c0c51a9SNicolas Vasilache desc.setAlignedPtr(rewriter, loc, ptr); 7265c0c51a9SNicolas Vasilache // Fill offset 0. 7275c0c51a9SNicolas Vasilache auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0); 7285c0c51a9SNicolas Vasilache auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr); 7295c0c51a9SNicolas Vasilache desc.setOffset(rewriter, loc, zero); 7305c0c51a9SNicolas Vasilache 7315c0c51a9SNicolas Vasilache // Fill size and stride descriptors in memref. 7325c0c51a9SNicolas Vasilache for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) { 7335c0c51a9SNicolas Vasilache int64_t index = indexedSize.index(); 7345c0c51a9SNicolas Vasilache auto sizeAttr = 7355c0c51a9SNicolas Vasilache rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value()); 7365c0c51a9SNicolas Vasilache auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr); 7375c0c51a9SNicolas Vasilache desc.setSize(rewriter, loc, index, size); 7385c0c51a9SNicolas Vasilache auto strideAttr = 7395c0c51a9SNicolas Vasilache rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]); 7405c0c51a9SNicolas Vasilache auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr); 7415c0c51a9SNicolas Vasilache desc.setStride(rewriter, loc, index, stride); 7425c0c51a9SNicolas Vasilache } 7435c0c51a9SNicolas Vasilache 7445c0c51a9SNicolas Vasilache rewriter.replaceOp(op, {desc}); 7453145427dSRiver Riddle return success(); 7465c0c51a9SNicolas Vasilache } 7475c0c51a9SNicolas Vasilache }; 7485c0c51a9SNicolas Vasilache 7498345b86dSNicolas Vasilache template <typename ConcreteOp> 750a99f62c4SAlex Zinenko LogicalResult replaceTransferOp(ConversionPatternRewriter &rewriter, 7518345b86dSNicolas Vasilache LLVMTypeConverter &typeConverter, Location loc, 752a99f62c4SAlex Zinenko Operation *op, ArrayRef<Value> operands, 753a99f62c4SAlex Zinenko Value dataPtr, Value mask); 7548345b86dSNicolas Vasilache 755a23f1902SWen-Heng (Jack) Chung LogicalResult getLLVMTypeAndAlignment(LLVMTypeConverter &typeConverter, 756a23f1902SWen-Heng (Jack) Chung Type type, LLVM::LLVMType &llvmType, 757a23f1902SWen-Heng (Jack) Chung unsigned &align) { 758a23f1902SWen-Heng (Jack) Chung auto convertedType = typeConverter.convertType(type); 759a23f1902SWen-Heng (Jack) Chung if (!convertedType) 760a23f1902SWen-Heng (Jack) Chung return failure(); 761a23f1902SWen-Heng (Jack) Chung 762a23f1902SWen-Heng (Jack) Chung llvmType = convertedType.template cast<LLVM::LLVMType>(); 763a23f1902SWen-Heng (Jack) Chung auto dataLayout = typeConverter.getDialect()->getLLVMModule().getDataLayout(); 764a23f1902SWen-Heng (Jack) Chung align = dataLayout.getPrefTypeAlignment(llvmType.getUnderlyingType()); 765a23f1902SWen-Heng (Jack) Chung return success(); 766a23f1902SWen-Heng (Jack) Chung } 767a23f1902SWen-Heng (Jack) Chung 7688345b86dSNicolas Vasilache template <> 769a99f62c4SAlex Zinenko LogicalResult replaceTransferOp<TransferReadOp>( 770a99f62c4SAlex Zinenko ConversionPatternRewriter &rewriter, LLVMTypeConverter &typeConverter, 771a99f62c4SAlex Zinenko Location loc, Operation *op, ArrayRef<Value> operands, Value dataPtr, 7728345b86dSNicolas Vasilache Value mask) { 7738345b86dSNicolas Vasilache auto xferOp = cast<TransferReadOp>(op); 7748345b86dSNicolas Vasilache auto toLLVMTy = [&](Type t) { return typeConverter.convertType(t); }; 7758345b86dSNicolas Vasilache VectorType fillType = xferOp.getVectorType(); 7768345b86dSNicolas Vasilache Value fill = rewriter.create<SplatOp>(loc, fillType, xferOp.padding()); 7778345b86dSNicolas Vasilache fill = rewriter.create<LLVM::DialectCastOp>(loc, toLLVMTy(fillType), fill); 7788345b86dSNicolas Vasilache 779a23f1902SWen-Heng (Jack) Chung LLVM::LLVMType vecTy; 780a23f1902SWen-Heng (Jack) Chung unsigned align; 781a99f62c4SAlex Zinenko if (failed(getLLVMTypeAndAlignment(typeConverter, xferOp.getVectorType(), 782a23f1902SWen-Heng (Jack) Chung vecTy, align))) 783a99f62c4SAlex Zinenko return failure(); 784a99f62c4SAlex Zinenko 7858345b86dSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>( 7868345b86dSNicolas Vasilache op, vecTy, dataPtr, mask, ValueRange{fill}, 787a23f1902SWen-Heng (Jack) Chung rewriter.getI32IntegerAttr(align)); 788a99f62c4SAlex Zinenko return success(); 7898345b86dSNicolas Vasilache } 7908345b86dSNicolas Vasilache 7918345b86dSNicolas Vasilache template <> 792a99f62c4SAlex Zinenko LogicalResult replaceTransferOp<TransferWriteOp>( 793a99f62c4SAlex Zinenko ConversionPatternRewriter &rewriter, LLVMTypeConverter &typeConverter, 794a99f62c4SAlex Zinenko Location loc, Operation *op, ArrayRef<Value> operands, Value dataPtr, 7958345b86dSNicolas Vasilache Value mask) { 7968345b86dSNicolas Vasilache auto adaptor = TransferWriteOpOperandAdaptor(operands); 797a23f1902SWen-Heng (Jack) Chung 798a23f1902SWen-Heng (Jack) Chung auto xferOp = cast<TransferWriteOp>(op); 799a23f1902SWen-Heng (Jack) Chung LLVM::LLVMType vecTy; 800a23f1902SWen-Heng (Jack) Chung unsigned align; 801a99f62c4SAlex Zinenko if (failed(getLLVMTypeAndAlignment(typeConverter, xferOp.getVectorType(), 802a23f1902SWen-Heng (Jack) Chung vecTy, align))) 803a99f62c4SAlex Zinenko return failure(); 804a99f62c4SAlex Zinenko 8058345b86dSNicolas Vasilache rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>( 806a23f1902SWen-Heng (Jack) Chung op, adaptor.vector(), dataPtr, mask, rewriter.getI32IntegerAttr(align)); 807a99f62c4SAlex Zinenko return success(); 8088345b86dSNicolas Vasilache } 8098345b86dSNicolas Vasilache 8108345b86dSNicolas Vasilache static TransferReadOpOperandAdaptor 8118345b86dSNicolas Vasilache getTransferOpAdapter(TransferReadOp xferOp, ArrayRef<Value> operands) { 8128345b86dSNicolas Vasilache return TransferReadOpOperandAdaptor(operands); 8138345b86dSNicolas Vasilache } 8148345b86dSNicolas Vasilache 8158345b86dSNicolas Vasilache static TransferWriteOpOperandAdaptor 8168345b86dSNicolas Vasilache getTransferOpAdapter(TransferWriteOp xferOp, ArrayRef<Value> operands) { 8178345b86dSNicolas Vasilache return TransferWriteOpOperandAdaptor(operands); 8188345b86dSNicolas Vasilache } 8198345b86dSNicolas Vasilache 820b2c79c50SNicolas Vasilache bool isMinorIdentity(AffineMap map, unsigned rank) { 821b2c79c50SNicolas Vasilache if (map.getNumResults() < rank) 822b2c79c50SNicolas Vasilache return false; 823b2c79c50SNicolas Vasilache unsigned startDim = map.getNumDims() - rank; 824b2c79c50SNicolas Vasilache for (unsigned i = 0; i < rank; ++i) 825b2c79c50SNicolas Vasilache if (map.getResult(i) != getAffineDimExpr(startDim + i, map.getContext())) 826b2c79c50SNicolas Vasilache return false; 827b2c79c50SNicolas Vasilache return true; 828b2c79c50SNicolas Vasilache } 829b2c79c50SNicolas Vasilache 8308345b86dSNicolas Vasilache /// Conversion pattern that converts a 1-D vector transfer read/write op in a 8318345b86dSNicolas Vasilache /// sequence of: 832be16075bSWen-Heng (Jack) Chung /// 1. Bitcast or addrspacecast to vector form. 8338345b86dSNicolas Vasilache /// 2. Create an offsetVector = [ offset + 0 .. offset + vector_length - 1 ]. 8348345b86dSNicolas Vasilache /// 3. Create a mask where offsetVector is compared against memref upper bound. 8358345b86dSNicolas Vasilache /// 4. Rewrite op as a masked read or write. 8368345b86dSNicolas Vasilache template <typename ConcreteOp> 8378345b86dSNicolas Vasilache class VectorTransferConversion : public ConvertToLLVMPattern { 8388345b86dSNicolas Vasilache public: 8398345b86dSNicolas Vasilache explicit VectorTransferConversion(MLIRContext *context, 8408345b86dSNicolas Vasilache LLVMTypeConverter &typeConv) 8418345b86dSNicolas Vasilache : ConvertToLLVMPattern(ConcreteOp::getOperationName(), context, 8428345b86dSNicolas Vasilache typeConv) {} 8438345b86dSNicolas Vasilache 8448345b86dSNicolas Vasilache LogicalResult 8458345b86dSNicolas Vasilache matchAndRewrite(Operation *op, ArrayRef<Value> operands, 8468345b86dSNicolas Vasilache ConversionPatternRewriter &rewriter) const override { 8478345b86dSNicolas Vasilache auto xferOp = cast<ConcreteOp>(op); 8488345b86dSNicolas Vasilache auto adaptor = getTransferOpAdapter(xferOp, operands); 849b2c79c50SNicolas Vasilache 850b2c79c50SNicolas Vasilache if (xferOp.getVectorType().getRank() > 1 || 851b2c79c50SNicolas Vasilache llvm::size(xferOp.indices()) == 0) 8528345b86dSNicolas Vasilache return failure(); 853b2c79c50SNicolas Vasilache if (!isMinorIdentity(xferOp.permutation_map(), 854b2c79c50SNicolas Vasilache xferOp.getVectorType().getRank())) 8558345b86dSNicolas Vasilache return failure(); 8568345b86dSNicolas Vasilache 8578345b86dSNicolas Vasilache auto toLLVMTy = [&](Type t) { return typeConverter.convertType(t); }; 8588345b86dSNicolas Vasilache 8598345b86dSNicolas Vasilache Location loc = op->getLoc(); 8608345b86dSNicolas Vasilache Type i64Type = rewriter.getIntegerType(64); 8618345b86dSNicolas Vasilache MemRefType memRefType = xferOp.getMemRefType(); 8628345b86dSNicolas Vasilache 8638345b86dSNicolas Vasilache // 1. Get the source/dst address as an LLVM vector pointer. 864be16075bSWen-Heng (Jack) Chung // The vector pointer would always be on address space 0, therefore 865be16075bSWen-Heng (Jack) Chung // addrspacecast shall be used when source/dst memrefs are not on 866be16075bSWen-Heng (Jack) Chung // address space 0. 8678345b86dSNicolas Vasilache // TODO: support alignment when possible. 8688345b86dSNicolas Vasilache Value dataPtr = getDataPtr(loc, memRefType, adaptor.memref(), 8698345b86dSNicolas Vasilache adaptor.indices(), rewriter, getModule()); 8708345b86dSNicolas Vasilache auto vecTy = 8718345b86dSNicolas Vasilache toLLVMTy(xferOp.getVectorType()).template cast<LLVM::LLVMType>(); 872be16075bSWen-Heng (Jack) Chung Value vectorDataPtr; 873be16075bSWen-Heng (Jack) Chung if (memRefType.getMemorySpace() == 0) 874be16075bSWen-Heng (Jack) Chung vectorDataPtr = 8758345b86dSNicolas Vasilache rewriter.create<LLVM::BitcastOp>(loc, vecTy.getPointerTo(), dataPtr); 876be16075bSWen-Heng (Jack) Chung else 877be16075bSWen-Heng (Jack) Chung vectorDataPtr = rewriter.create<LLVM::AddrSpaceCastOp>( 878be16075bSWen-Heng (Jack) Chung loc, vecTy.getPointerTo(), dataPtr); 8798345b86dSNicolas Vasilache 8808345b86dSNicolas Vasilache // 2. Create a vector with linear indices [ 0 .. vector_length - 1 ]. 8818345b86dSNicolas Vasilache unsigned vecWidth = vecTy.getVectorNumElements(); 8828345b86dSNicolas Vasilache VectorType vectorCmpType = VectorType::get(vecWidth, i64Type); 8838345b86dSNicolas Vasilache SmallVector<int64_t, 8> indices; 8848345b86dSNicolas Vasilache indices.reserve(vecWidth); 8858345b86dSNicolas Vasilache for (unsigned i = 0; i < vecWidth; ++i) 8868345b86dSNicolas Vasilache indices.push_back(i); 8878345b86dSNicolas Vasilache Value linearIndices = rewriter.create<ConstantOp>( 8888345b86dSNicolas Vasilache loc, vectorCmpType, 8898345b86dSNicolas Vasilache DenseElementsAttr::get(vectorCmpType, ArrayRef<int64_t>(indices))); 8908345b86dSNicolas Vasilache linearIndices = rewriter.create<LLVM::DialectCastOp>( 8918345b86dSNicolas Vasilache loc, toLLVMTy(vectorCmpType), linearIndices); 8928345b86dSNicolas Vasilache 8938345b86dSNicolas Vasilache // 3. Create offsetVector = [ offset + 0 .. offset + vector_length - 1 ]. 894b2c79c50SNicolas Vasilache // TODO(ntv, ajcbik): when the leaf transfer rank is k > 1 we need the last 895b2c79c50SNicolas Vasilache // `k` dimensions here. 896b2c79c50SNicolas Vasilache unsigned lastIndex = llvm::size(xferOp.indices()) - 1; 897b2c79c50SNicolas Vasilache Value offsetIndex = *(xferOp.indices().begin() + lastIndex); 898b2c79c50SNicolas Vasilache offsetIndex = rewriter.create<IndexCastOp>(loc, i64Type, offsetIndex); 8998345b86dSNicolas Vasilache Value base = rewriter.create<SplatOp>(loc, vectorCmpType, offsetIndex); 9008345b86dSNicolas Vasilache Value offsetVector = rewriter.create<AddIOp>(loc, base, linearIndices); 9018345b86dSNicolas Vasilache 9028345b86dSNicolas Vasilache // 4. Let dim the memref dimension, compute the vector comparison mask: 9038345b86dSNicolas Vasilache // [ offset + 0 .. offset + vector_length - 1 ] < [ dim .. dim ] 904b2c79c50SNicolas Vasilache Value dim = rewriter.create<DimOp>(loc, xferOp.memref(), lastIndex); 905b2c79c50SNicolas Vasilache dim = rewriter.create<IndexCastOp>(loc, i64Type, dim); 9068345b86dSNicolas Vasilache dim = rewriter.create<SplatOp>(loc, vectorCmpType, dim); 9078345b86dSNicolas Vasilache Value mask = 9088345b86dSNicolas Vasilache rewriter.create<CmpIOp>(loc, CmpIPredicate::slt, offsetVector, dim); 9098345b86dSNicolas Vasilache mask = rewriter.create<LLVM::DialectCastOp>(loc, toLLVMTy(mask.getType()), 9108345b86dSNicolas Vasilache mask); 9118345b86dSNicolas Vasilache 9128345b86dSNicolas Vasilache // 5. Rewrite as a masked read / write. 913a99f62c4SAlex Zinenko return replaceTransferOp<ConcreteOp>(rewriter, typeConverter, loc, op, 914a99f62c4SAlex Zinenko operands, vectorDataPtr, mask); 9158345b86dSNicolas Vasilache } 9168345b86dSNicolas Vasilache }; 9178345b86dSNicolas Vasilache 918870c1fd4SAlex Zinenko class VectorPrintOpConversion : public ConvertToLLVMPattern { 919d9b500d3SAart Bik public: 920d9b500d3SAart Bik explicit VectorPrintOpConversion(MLIRContext *context, 921d9b500d3SAart Bik LLVMTypeConverter &typeConverter) 922870c1fd4SAlex Zinenko : ConvertToLLVMPattern(vector::PrintOp::getOperationName(), context, 923d9b500d3SAart Bik typeConverter) {} 924d9b500d3SAart Bik 925d9b500d3SAart Bik // Proof-of-concept lowering implementation that relies on a small 926d9b500d3SAart Bik // runtime support library, which only needs to provide a few 927d9b500d3SAart Bik // printing methods (single value for all data types, opening/closing 928d9b500d3SAart Bik // bracket, comma, newline). The lowering fully unrolls a vector 929d9b500d3SAart Bik // in terms of these elementary printing operations. The advantage 930d9b500d3SAart Bik // of this approach is that the library can remain unaware of all 931d9b500d3SAart Bik // low-level implementation details of vectors while still supporting 932d9b500d3SAart Bik // output of any shaped and dimensioned vector. Due to full unrolling, 933d9b500d3SAart Bik // this approach is less suited for very large vectors though. 934d9b500d3SAart Bik // 935d9b500d3SAart Bik // TODO(ajcbik): rely solely on libc in future? something else? 936d9b500d3SAart Bik // 9373145427dSRiver Riddle LogicalResult 938e62a6956SRiver Riddle matchAndRewrite(Operation *op, ArrayRef<Value> operands, 939d9b500d3SAart Bik ConversionPatternRewriter &rewriter) const override { 940d9b500d3SAart Bik auto printOp = cast<vector::PrintOp>(op); 941d9b500d3SAart Bik auto adaptor = vector::PrintOpOperandAdaptor(operands); 942d9b500d3SAart Bik Type printType = printOp.getPrintType(); 943d9b500d3SAart Bik 9440f04384dSAlex Zinenko if (typeConverter.convertType(printType) == nullptr) 9453145427dSRiver Riddle return failure(); 946d9b500d3SAart Bik 947d9b500d3SAart Bik // Make sure element type has runtime support (currently just Float/Double). 948d9b500d3SAart Bik VectorType vectorType = printType.dyn_cast<VectorType>(); 949d9b500d3SAart Bik Type eltType = vectorType ? vectorType.getElementType() : printType; 950d9b500d3SAart Bik int64_t rank = vectorType ? vectorType.getRank() : 0; 951d9b500d3SAart Bik Operation *printer; 9526937251fSaartbik if (eltType.isSignlessInteger(1)) 9536937251fSaartbik printer = getPrintI1(op); 9546937251fSaartbik else if (eltType.isSignlessInteger(32)) 955e52414b1Saartbik printer = getPrintI32(op); 95635b68527SLei Zhang else if (eltType.isSignlessInteger(64)) 957e52414b1Saartbik printer = getPrintI64(op); 958e52414b1Saartbik else if (eltType.isF32()) 959d9b500d3SAart Bik printer = getPrintFloat(op); 960d9b500d3SAart Bik else if (eltType.isF64()) 961d9b500d3SAart Bik printer = getPrintDouble(op); 962d9b500d3SAart Bik else 9633145427dSRiver Riddle return failure(); 964d9b500d3SAart Bik 965d9b500d3SAart Bik // Unroll vector into elementary print calls. 966d9b500d3SAart Bik emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank); 967d9b500d3SAart Bik emitCall(rewriter, op->getLoc(), getPrintNewline(op)); 968d9b500d3SAart Bik rewriter.eraseOp(op); 9693145427dSRiver Riddle return success(); 970d9b500d3SAart Bik } 971d9b500d3SAart Bik 972d9b500d3SAart Bik private: 973d9b500d3SAart Bik void emitRanks(ConversionPatternRewriter &rewriter, Operation *op, 974e62a6956SRiver Riddle Value value, VectorType vectorType, Operation *printer, 975d9b500d3SAart Bik int64_t rank) const { 976d9b500d3SAart Bik Location loc = op->getLoc(); 977d9b500d3SAart Bik if (rank == 0) { 978d9b500d3SAart Bik emitCall(rewriter, loc, printer, value); 979d9b500d3SAart Bik return; 980d9b500d3SAart Bik } 981d9b500d3SAart Bik 982d9b500d3SAart Bik emitCall(rewriter, loc, getPrintOpen(op)); 983d9b500d3SAart Bik Operation *printComma = getPrintComma(op); 984d9b500d3SAart Bik int64_t dim = vectorType.getDimSize(0); 985d9b500d3SAart Bik for (int64_t d = 0; d < dim; ++d) { 986d9b500d3SAart Bik auto reducedType = 987d9b500d3SAart Bik rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr; 9880f04384dSAlex Zinenko auto llvmType = typeConverter.convertType( 989d9b500d3SAart Bik rank > 1 ? reducedType : vectorType.getElementType()); 990e62a6956SRiver Riddle Value nestedVal = 9910f04384dSAlex Zinenko extractOne(rewriter, typeConverter, loc, value, llvmType, rank, d); 992d9b500d3SAart Bik emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1); 993d9b500d3SAart Bik if (d != dim - 1) 994d9b500d3SAart Bik emitCall(rewriter, loc, printComma); 995d9b500d3SAart Bik } 996d9b500d3SAart Bik emitCall(rewriter, loc, getPrintClose(op)); 997d9b500d3SAart Bik } 998d9b500d3SAart Bik 999d9b500d3SAart Bik // Helper to emit a call. 1000d9b500d3SAart Bik static void emitCall(ConversionPatternRewriter &rewriter, Location loc, 1001d9b500d3SAart Bik Operation *ref, ValueRange params = ValueRange()) { 1002d9b500d3SAart Bik rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{}, 1003d9b500d3SAart Bik rewriter.getSymbolRefAttr(ref), params); 1004d9b500d3SAart Bik } 1005d9b500d3SAart Bik 1006d9b500d3SAart Bik // Helper for printer method declaration (first hit) and lookup. 1007d9b500d3SAart Bik static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect, 1008d9b500d3SAart Bik StringRef name, ArrayRef<LLVM::LLVMType> params) { 1009d9b500d3SAart Bik auto module = op->getParentOfType<ModuleOp>(); 1010d9b500d3SAart Bik auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name); 1011d9b500d3SAart Bik if (func) 1012d9b500d3SAart Bik return func; 1013d9b500d3SAart Bik OpBuilder moduleBuilder(module.getBodyRegion()); 1014d9b500d3SAart Bik return moduleBuilder.create<LLVM::LLVMFuncOp>( 1015d9b500d3SAart Bik op->getLoc(), name, 1016d9b500d3SAart Bik LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect), 1017d9b500d3SAart Bik params, /*isVarArg=*/false)); 1018d9b500d3SAart Bik } 1019d9b500d3SAart Bik 1020d9b500d3SAart Bik // Helpers for method names. 10216937251fSaartbik Operation *getPrintI1(Operation *op) const { 10226937251fSaartbik LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 10236937251fSaartbik return getPrint(op, dialect, "print_i1", 10246937251fSaartbik LLVM::LLVMType::getInt1Ty(dialect)); 10256937251fSaartbik } 1026e52414b1Saartbik Operation *getPrintI32(Operation *op) const { 10270f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1028e52414b1Saartbik return getPrint(op, dialect, "print_i32", 1029e52414b1Saartbik LLVM::LLVMType::getInt32Ty(dialect)); 1030e52414b1Saartbik } 1031e52414b1Saartbik Operation *getPrintI64(Operation *op) const { 10320f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1033e52414b1Saartbik return getPrint(op, dialect, "print_i64", 1034e52414b1Saartbik LLVM::LLVMType::getInt64Ty(dialect)); 1035e52414b1Saartbik } 1036d9b500d3SAart Bik Operation *getPrintFloat(Operation *op) const { 10370f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1038d9b500d3SAart Bik return getPrint(op, dialect, "print_f32", 1039d9b500d3SAart Bik LLVM::LLVMType::getFloatTy(dialect)); 1040d9b500d3SAart Bik } 1041d9b500d3SAart Bik Operation *getPrintDouble(Operation *op) const { 10420f04384dSAlex Zinenko LLVM::LLVMDialect *dialect = typeConverter.getDialect(); 1043d9b500d3SAart Bik return getPrint(op, dialect, "print_f64", 1044d9b500d3SAart Bik LLVM::LLVMType::getDoubleTy(dialect)); 1045d9b500d3SAart Bik } 1046d9b500d3SAart Bik Operation *getPrintOpen(Operation *op) const { 10470f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_open", {}); 1048d9b500d3SAart Bik } 1049d9b500d3SAart Bik Operation *getPrintClose(Operation *op) const { 10500f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_close", {}); 1051d9b500d3SAart Bik } 1052d9b500d3SAart Bik Operation *getPrintComma(Operation *op) const { 10530f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_comma", {}); 1054d9b500d3SAart Bik } 1055d9b500d3SAart Bik Operation *getPrintNewline(Operation *op) const { 10560f04384dSAlex Zinenko return getPrint(op, typeConverter.getDialect(), "print_newline", {}); 1057d9b500d3SAart Bik } 1058d9b500d3SAart Bik }; 1059d9b500d3SAart Bik 1060334a4159SReid Tatge /// Progressive lowering of ExtractStridedSliceOp to either: 106165678d93SNicolas Vasilache /// 1. extractelement + insertelement for the 1-D case 106265678d93SNicolas Vasilache /// 2. extract + optional strided_slice + insert for the n-D case. 1063334a4159SReid Tatge class VectorStridedSliceOpConversion 1064334a4159SReid Tatge : public OpRewritePattern<ExtractStridedSliceOp> { 106565678d93SNicolas Vasilache public: 1066334a4159SReid Tatge using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 106765678d93SNicolas Vasilache 1068334a4159SReid Tatge LogicalResult matchAndRewrite(ExtractStridedSliceOp op, 106965678d93SNicolas Vasilache PatternRewriter &rewriter) const override { 107065678d93SNicolas Vasilache auto dstType = op.getResult().getType().cast<VectorType>(); 107165678d93SNicolas Vasilache 107265678d93SNicolas Vasilache assert(!op.offsets().getValue().empty() && "Unexpected empty offsets"); 107365678d93SNicolas Vasilache 107465678d93SNicolas Vasilache int64_t offset = 107565678d93SNicolas Vasilache op.offsets().getValue().front().cast<IntegerAttr>().getInt(); 107665678d93SNicolas Vasilache int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt(); 107765678d93SNicolas Vasilache int64_t stride = 107865678d93SNicolas Vasilache op.strides().getValue().front().cast<IntegerAttr>().getInt(); 107965678d93SNicolas Vasilache 108065678d93SNicolas Vasilache auto loc = op.getLoc(); 108165678d93SNicolas Vasilache auto elemType = dstType.getElementType(); 108235b68527SLei Zhang assert(elemType.isSignlessIntOrIndexOrFloat()); 108365678d93SNicolas Vasilache Value zero = rewriter.create<ConstantOp>(loc, elemType, 108465678d93SNicolas Vasilache rewriter.getZeroAttr(elemType)); 108565678d93SNicolas Vasilache Value res = rewriter.create<SplatOp>(loc, dstType, zero); 108665678d93SNicolas Vasilache for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e; 108765678d93SNicolas Vasilache off += stride, ++idx) { 108865678d93SNicolas Vasilache Value extracted = extractOne(rewriter, loc, op.vector(), off); 108965678d93SNicolas Vasilache if (op.offsets().getValue().size() > 1) { 1090334a4159SReid Tatge extracted = rewriter.create<ExtractStridedSliceOp>( 109165678d93SNicolas Vasilache loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1), 109265678d93SNicolas Vasilache getI64SubArray(op.sizes(), /* dropFront=*/1), 109365678d93SNicolas Vasilache getI64SubArray(op.strides(), /* dropFront=*/1)); 109465678d93SNicolas Vasilache } 109565678d93SNicolas Vasilache res = insertOne(rewriter, loc, extracted, res, idx); 109665678d93SNicolas Vasilache } 109765678d93SNicolas Vasilache rewriter.replaceOp(op, {res}); 10983145427dSRiver Riddle return success(); 109965678d93SNicolas Vasilache } 1100334a4159SReid Tatge /// This pattern creates recursive ExtractStridedSliceOp, but the recursion is 1101bd1ccfe6SRiver Riddle /// bounded as the rank is strictly decreasing. 1102bd1ccfe6SRiver Riddle bool hasBoundedRewriteRecursion() const final { return true; } 110365678d93SNicolas Vasilache }; 110465678d93SNicolas Vasilache 1105df186507SBenjamin Kramer } // namespace 1106df186507SBenjamin Kramer 11075c0c51a9SNicolas Vasilache /// Populate the given list with patterns that convert from Vector to LLVM. 11085c0c51a9SNicolas Vasilache void mlir::populateVectorToLLVMConversionPatterns( 11095c0c51a9SNicolas Vasilache LLVMTypeConverter &converter, OwningRewritePatternList &patterns) { 111065678d93SNicolas Vasilache MLIRContext *ctx = converter.getDialect()->getContext(); 11118345b86dSNicolas Vasilache // clang-format off 1112681f929fSNicolas Vasilache patterns.insert<VectorFMAOpNDRewritePattern, 1113681f929fSNicolas Vasilache VectorInsertStridedSliceOpDifferentRankRewritePattern, 11142d515e49SNicolas Vasilache VectorInsertStridedSliceOpSameRankRewritePattern, 11152d515e49SNicolas Vasilache VectorStridedSliceOpConversion>(ctx); 11168345b86dSNicolas Vasilache patterns 1117186709c6Saartbik .insert<VectorReductionOpConversion, 11188345b86dSNicolas Vasilache VectorShuffleOpConversion, 11198345b86dSNicolas Vasilache VectorExtractElementOpConversion, 11208345b86dSNicolas Vasilache VectorExtractOpConversion, 11218345b86dSNicolas Vasilache VectorFMAOp1DConversion, 11228345b86dSNicolas Vasilache VectorInsertElementOpConversion, 11238345b86dSNicolas Vasilache VectorInsertOpConversion, 11248345b86dSNicolas Vasilache VectorPrintOpConversion, 11258345b86dSNicolas Vasilache VectorTransferConversion<TransferReadOp>, 11268345b86dSNicolas Vasilache VectorTransferConversion<TransferWriteOp>, 11278345b86dSNicolas Vasilache VectorTypeCastOpConversion>(ctx, converter); 11288345b86dSNicolas Vasilache // clang-format on 11295c0c51a9SNicolas Vasilache } 11305c0c51a9SNicolas Vasilache 113163b683a8SNicolas Vasilache void mlir::populateVectorToLLVMMatrixConversionPatterns( 113263b683a8SNicolas Vasilache LLVMTypeConverter &converter, OwningRewritePatternList &patterns) { 113363b683a8SNicolas Vasilache MLIRContext *ctx = converter.getDialect()->getContext(); 113463b683a8SNicolas Vasilache patterns.insert<VectorMatmulOpConversion>(ctx, converter); 113563b683a8SNicolas Vasilache } 113663b683a8SNicolas Vasilache 11375c0c51a9SNicolas Vasilache namespace { 1138722f909fSRiver Riddle struct LowerVectorToLLVMPass 11391834ad4aSRiver Riddle : public ConvertVectorToLLVMBase<LowerVectorToLLVMPass> { 1140722f909fSRiver Riddle void runOnOperation() override; 11415c0c51a9SNicolas Vasilache }; 11425c0c51a9SNicolas Vasilache } // namespace 11435c0c51a9SNicolas Vasilache 1144722f909fSRiver Riddle void LowerVectorToLLVMPass::runOnOperation() { 1145078776a6Saartbik // Perform progressive lowering of operations on slices and 1146b21c7999Saartbik // all contraction operations. Also applies folding and DCE. 1147459cf6e5Saartbik { 11485c0c51a9SNicolas Vasilache OwningRewritePatternList patterns; 1149*b1c688dbSaartbik populateVectorToVectorCanonicalizationPatterns(patterns, &getContext()); 1150459cf6e5Saartbik populateVectorSlicesLoweringPatterns(patterns, &getContext()); 1151b21c7999Saartbik populateVectorContractLoweringPatterns(patterns, &getContext()); 1152a5b9316bSUday Bondhugula applyPatternsAndFoldGreedily(getOperation(), patterns); 1153459cf6e5Saartbik } 1154459cf6e5Saartbik 1155459cf6e5Saartbik // Convert to the LLVM IR dialect. 11565c0c51a9SNicolas Vasilache LLVMTypeConverter converter(&getContext()); 1157459cf6e5Saartbik OwningRewritePatternList patterns; 115863b683a8SNicolas Vasilache populateVectorToLLVMMatrixConversionPatterns(converter, patterns); 11595c0c51a9SNicolas Vasilache populateVectorToLLVMConversionPatterns(converter, patterns); 1160bbf3ef85SNicolas Vasilache populateVectorToLLVMMatrixConversionPatterns(converter, patterns); 11615c0c51a9SNicolas Vasilache populateStdToLLVMConversionPatterns(converter, patterns); 11625c0c51a9SNicolas Vasilache 11632a00ae39STim Shen LLVMConversionTarget target(getContext()); 11645c0c51a9SNicolas Vasilache target.addDynamicallyLegalOp<FuncOp>( 11655c0c51a9SNicolas Vasilache [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); }); 1166722f909fSRiver Riddle if (failed(applyPartialConversion(getOperation(), target, patterns, 1167722f909fSRiver Riddle &converter))) { 11685c0c51a9SNicolas Vasilache signalPassFailure(); 11695c0c51a9SNicolas Vasilache } 11705c0c51a9SNicolas Vasilache } 11715c0c51a9SNicolas Vasilache 117280aca1eaSRiver Riddle std::unique_ptr<OperationPass<ModuleOp>> mlir::createConvertVectorToLLVMPass() { 11732fae7878SNicolas Vasilache return std::make_unique<LowerVectorToLLVMPass>(); 11745c0c51a9SNicolas Vasilache } 1175