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 
115c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h"
125c0c51a9SNicolas Vasilache #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h"
135c0c51a9SNicolas Vasilache #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
1465678d93SNicolas Vasilache #include "mlir/Dialect/StandardOps/Ops.h"
155c0c51a9SNicolas Vasilache #include "mlir/Dialect/VectorOps/VectorOps.h"
165c0c51a9SNicolas Vasilache #include "mlir/IR/Attributes.h"
175c0c51a9SNicolas Vasilache #include "mlir/IR/Builders.h"
185c0c51a9SNicolas Vasilache #include "mlir/IR/MLIRContext.h"
195c0c51a9SNicolas Vasilache #include "mlir/IR/Module.h"
205c0c51a9SNicolas Vasilache #include "mlir/IR/Operation.h"
215c0c51a9SNicolas Vasilache #include "mlir/IR/PatternMatch.h"
225c0c51a9SNicolas Vasilache #include "mlir/IR/StandardTypes.h"
235c0c51a9SNicolas Vasilache #include "mlir/IR/Types.h"
245c0c51a9SNicolas Vasilache #include "mlir/Pass/Pass.h"
255c0c51a9SNicolas Vasilache #include "mlir/Pass/PassManager.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 
129870c1fd4SAlex Zinenko class VectorBroadcastOpConversion : public ConvertToLLVMPattern {
130b36aaeafSAart Bik public:
131b36aaeafSAart Bik   explicit VectorBroadcastOpConversion(MLIRContext *context,
132b36aaeafSAart Bik                                        LLVMTypeConverter &typeConverter)
133870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::BroadcastOp::getOperationName(), context,
134b36aaeafSAart Bik                              typeConverter) {}
135b36aaeafSAart Bik 
136b36aaeafSAart Bik   PatternMatchResult
137e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
138b36aaeafSAart Bik                   ConversionPatternRewriter &rewriter) const override {
139b36aaeafSAart Bik     auto broadcastOp = cast<vector::BroadcastOp>(op);
140b36aaeafSAart Bik     VectorType dstVectorType = broadcastOp.getVectorType();
1410f04384dSAlex Zinenko     if (typeConverter.convertType(dstVectorType) == nullptr)
142b36aaeafSAart Bik       return matchFailure();
143b36aaeafSAart Bik     // Rewrite when the full vector type can be lowered (which
144b36aaeafSAart Bik     // implies all 'reduced' types can be lowered too).
1451c81adf3SAart Bik     auto adaptor = vector::BroadcastOpOperandAdaptor(operands);
146b36aaeafSAart Bik     VectorType srcVectorType =
147b36aaeafSAart Bik         broadcastOp.getSourceType().dyn_cast<VectorType>();
148b36aaeafSAart Bik     rewriter.replaceOp(
1491c81adf3SAart Bik         op, expandRanks(adaptor.source(), // source value to be expanded
150b36aaeafSAart Bik                         op->getLoc(),     // location of original broadcast
151b36aaeafSAart Bik                         srcVectorType, dstVectorType, rewriter));
152b36aaeafSAart Bik     return matchSuccess();
153b36aaeafSAart Bik   }
154b36aaeafSAart Bik 
155b36aaeafSAart Bik private:
156b36aaeafSAart Bik   // Expands the given source value over all the ranks, as defined
157b36aaeafSAart Bik   // by the source and destination type (a null source type denotes
158b36aaeafSAart Bik   // expansion from a scalar value into a vector).
159b36aaeafSAart Bik   //
160b36aaeafSAart Bik   // TODO(ajcbik): consider replacing this one-pattern lowering
161b36aaeafSAart Bik   //               with a two-pattern lowering using other vector
162b36aaeafSAart Bik   //               ops once all insert/extract/shuffle operations
163fc817b09SKazuaki Ishizaki   //               are available with lowering implementation.
164b36aaeafSAart Bik   //
165e62a6956SRiver Riddle   Value expandRanks(Value value, Location loc, VectorType srcVectorType,
166b36aaeafSAart Bik                     VectorType dstVectorType,
167b36aaeafSAart Bik                     ConversionPatternRewriter &rewriter) const {
168b36aaeafSAart Bik     assert((dstVectorType != nullptr) && "invalid result type in broadcast");
169b36aaeafSAart Bik     // Determine rank of source and destination.
170b36aaeafSAart Bik     int64_t srcRank = srcVectorType ? srcVectorType.getRank() : 0;
171b36aaeafSAart Bik     int64_t dstRank = dstVectorType.getRank();
172b36aaeafSAart Bik     int64_t curDim = dstVectorType.getDimSize(0);
173b36aaeafSAart Bik     if (srcRank < dstRank)
174b36aaeafSAart Bik       // Duplicate this rank.
175b36aaeafSAart Bik       return duplicateOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
176b36aaeafSAart Bik                               curDim, rewriter);
177b36aaeafSAart Bik     // If all trailing dimensions are the same, the broadcast consists of
178b36aaeafSAart Bik     // simply passing through the source value and we are done. Otherwise,
179b36aaeafSAart Bik     // any non-matching dimension forces a stretch along this rank.
180b36aaeafSAart Bik     assert((srcVectorType != nullptr) && (srcRank > 0) &&
181b36aaeafSAart Bik            (srcRank == dstRank) && "invalid rank in broadcast");
182b36aaeafSAart Bik     for (int64_t r = 0; r < dstRank; r++) {
183b36aaeafSAart Bik       if (srcVectorType.getDimSize(r) != dstVectorType.getDimSize(r)) {
184b36aaeafSAart Bik         return stretchOneRank(value, loc, srcVectorType, dstVectorType, dstRank,
185b36aaeafSAart Bik                               curDim, rewriter);
186b36aaeafSAart Bik       }
187b36aaeafSAart Bik     }
188b36aaeafSAart Bik     return value;
189b36aaeafSAart Bik   }
190b36aaeafSAart Bik 
191b36aaeafSAart Bik   // Picks the best way to duplicate a single rank. For the 1-D case, a
192b36aaeafSAart Bik   // single insert-elt/shuffle is the most efficient expansion. For higher
193b36aaeafSAart Bik   // dimensions, however, we need dim x insert-values on a new broadcast
194b36aaeafSAart Bik   // with one less leading dimension, which will be lowered "recursively"
195b36aaeafSAart Bik   // to matching LLVM IR.
196b36aaeafSAart Bik   // For example:
197b36aaeafSAart Bik   //   v = broadcast s : f32 to vector<4x2xf32>
198b36aaeafSAart Bik   // becomes:
199b36aaeafSAart Bik   //   x = broadcast s : f32 to vector<2xf32>
200b36aaeafSAart Bik   //   v = [x,x,x,x]
201b36aaeafSAart Bik   // becomes:
202b36aaeafSAart Bik   //   x = [s,s]
203b36aaeafSAart Bik   //   v = [x,x,x,x]
204e62a6956SRiver Riddle   Value duplicateOneRank(Value value, Location loc, VectorType srcVectorType,
205e62a6956SRiver Riddle                          VectorType dstVectorType, int64_t rank, int64_t dim,
206b36aaeafSAart Bik                          ConversionPatternRewriter &rewriter) const {
2070f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(dstVectorType);
208b36aaeafSAart Bik     assert((llvmType != nullptr) && "unlowerable vector type");
209b36aaeafSAart Bik     if (rank == 1) {
210e62a6956SRiver Riddle       Value undef = rewriter.create<LLVM::UndefOp>(loc, llvmType);
2110f04384dSAlex Zinenko       Value expand = insertOne(rewriter, typeConverter, loc, undef, value,
2120f04384dSAlex Zinenko                                llvmType, rank, 0);
213b36aaeafSAart Bik       SmallVector<int32_t, 4> zeroValues(dim, 0);
214b36aaeafSAart Bik       return rewriter.create<LLVM::ShuffleVectorOp>(
215b36aaeafSAart Bik           loc, expand, undef, rewriter.getI32ArrayAttr(zeroValues));
216b36aaeafSAart Bik     }
217e62a6956SRiver Riddle     Value expand = expandRanks(value, loc, srcVectorType,
2189826fe5cSAart Bik                                reducedVectorTypeFront(dstVectorType), rewriter);
219e62a6956SRiver Riddle     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
220b36aaeafSAart Bik     for (int64_t d = 0; d < dim; ++d) {
2210f04384dSAlex Zinenko       result = insertOne(rewriter, typeConverter, loc, result, expand, llvmType,
2220f04384dSAlex Zinenko                          rank, d);
223b36aaeafSAart Bik     }
224b36aaeafSAart Bik     return result;
225b36aaeafSAart Bik   }
226b36aaeafSAart Bik 
227b36aaeafSAart Bik   // Picks the best way to stretch a single rank. For the 1-D case, a
228b36aaeafSAart Bik   // single insert-elt/shuffle is the most efficient expansion when at
229b36aaeafSAart Bik   // a stretch. Otherwise, every dimension needs to be expanded
230b36aaeafSAart Bik   // individually and individually inserted in the resulting vector.
231b36aaeafSAart Bik   // For example:
232b36aaeafSAart Bik   //   v = broadcast w : vector<4x1x2xf32> to vector<4x2x2xf32>
233b36aaeafSAart Bik   // becomes:
234b36aaeafSAart Bik   //   a = broadcast w[0] : vector<1x2xf32> to vector<2x2xf32>
235b36aaeafSAart Bik   //   b = broadcast w[1] : vector<1x2xf32> to vector<2x2xf32>
236b36aaeafSAart Bik   //   c = broadcast w[2] : vector<1x2xf32> to vector<2x2xf32>
237b36aaeafSAart Bik   //   d = broadcast w[3] : vector<1x2xf32> to vector<2x2xf32>
238b36aaeafSAart Bik   //   v = [a,b,c,d]
239b36aaeafSAart Bik   // becomes:
240b36aaeafSAart Bik   //   x = broadcast w[0][0] : vector<2xf32> to vector <2x2xf32>
241b36aaeafSAart Bik   //   y = broadcast w[1][0] : vector<2xf32> to vector <2x2xf32>
242b36aaeafSAart Bik   //   a = [x, y]
243b36aaeafSAart Bik   //   etc.
244e62a6956SRiver Riddle   Value stretchOneRank(Value value, Location loc, VectorType srcVectorType,
245e62a6956SRiver Riddle                        VectorType dstVectorType, int64_t rank, int64_t dim,
246b36aaeafSAart Bik                        ConversionPatternRewriter &rewriter) const {
2470f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(dstVectorType);
248b36aaeafSAart Bik     assert((llvmType != nullptr) && "unlowerable vector type");
249e62a6956SRiver Riddle     Value result = rewriter.create<LLVM::UndefOp>(loc, llvmType);
250b36aaeafSAart Bik     bool atStretch = dim != srcVectorType.getDimSize(0);
251b36aaeafSAart Bik     if (rank == 1) {
2521c81adf3SAart Bik       assert(atStretch);
2530f04384dSAlex Zinenko       Type redLlvmType =
2540f04384dSAlex Zinenko           typeConverter.convertType(dstVectorType.getElementType());
255e62a6956SRiver Riddle       Value one =
2560f04384dSAlex Zinenko           extractOne(rewriter, typeConverter, loc, value, redLlvmType, rank, 0);
2570f04384dSAlex Zinenko       Value expand = insertOne(rewriter, typeConverter, loc, result, one,
2580f04384dSAlex Zinenko                                llvmType, rank, 0);
259b36aaeafSAart Bik       SmallVector<int32_t, 4> zeroValues(dim, 0);
260b36aaeafSAart Bik       return rewriter.create<LLVM::ShuffleVectorOp>(
261b36aaeafSAart Bik           loc, expand, result, rewriter.getI32ArrayAttr(zeroValues));
262b36aaeafSAart Bik     }
2639826fe5cSAart Bik     VectorType redSrcType = reducedVectorTypeFront(srcVectorType);
2649826fe5cSAart Bik     VectorType redDstType = reducedVectorTypeFront(dstVectorType);
2650f04384dSAlex Zinenko     Type redLlvmType = typeConverter.convertType(redSrcType);
266b36aaeafSAart Bik     for (int64_t d = 0; d < dim; ++d) {
267b36aaeafSAart Bik       int64_t pos = atStretch ? 0 : d;
2680f04384dSAlex Zinenko       Value one = extractOne(rewriter, typeConverter, loc, value, redLlvmType,
2690f04384dSAlex Zinenko                              rank, pos);
270e62a6956SRiver Riddle       Value expand = expandRanks(one, loc, redSrcType, redDstType, rewriter);
2710f04384dSAlex Zinenko       result = insertOne(rewriter, typeConverter, loc, result, expand, llvmType,
2720f04384dSAlex Zinenko                          rank, d);
273b36aaeafSAart Bik     }
274b36aaeafSAart Bik     return result;
275b36aaeafSAart Bik   }
2761c81adf3SAart Bik };
277b36aaeafSAart Bik 
278870c1fd4SAlex Zinenko class VectorReductionOpConversion : public ConvertToLLVMPattern {
279e83b7b99Saartbik public:
280e83b7b99Saartbik   explicit VectorReductionOpConversion(MLIRContext *context,
281e83b7b99Saartbik                                        LLVMTypeConverter &typeConverter)
282870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ReductionOp::getOperationName(), context,
283e83b7b99Saartbik                              typeConverter) {}
284e83b7b99Saartbik 
285e83b7b99Saartbik   PatternMatchResult
286e83b7b99Saartbik   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
287e83b7b99Saartbik                   ConversionPatternRewriter &rewriter) const override {
288e83b7b99Saartbik     auto reductionOp = cast<vector::ReductionOp>(op);
289e83b7b99Saartbik     auto kind = reductionOp.kind();
290e83b7b99Saartbik     Type eltType = reductionOp.dest().getType();
2910f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(eltType);
292*35b68527SLei Zhang     if (eltType.isSignlessInteger(32) || eltType.isSignlessInteger(64)) {
293e83b7b99Saartbik       // Integer reductions: add/mul/min/max/and/or/xor.
294e83b7b99Saartbik       if (kind == "add")
295e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_add>(
296e83b7b99Saartbik             op, llvmType, operands[0]);
297e83b7b99Saartbik       else if (kind == "mul")
298e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_mul>(
299e83b7b99Saartbik             op, llvmType, operands[0]);
300e83b7b99Saartbik       else if (kind == "min")
301e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smin>(
302e83b7b99Saartbik             op, llvmType, operands[0]);
303e83b7b99Saartbik       else if (kind == "max")
304e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_smax>(
305e83b7b99Saartbik             op, llvmType, operands[0]);
306e83b7b99Saartbik       else if (kind == "and")
307e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_and>(
308e83b7b99Saartbik             op, llvmType, operands[0]);
309e83b7b99Saartbik       else if (kind == "or")
310e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_or>(
311e83b7b99Saartbik             op, llvmType, operands[0]);
312e83b7b99Saartbik       else if (kind == "xor")
313e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_xor>(
314e83b7b99Saartbik             op, llvmType, operands[0]);
315e83b7b99Saartbik       else
316e83b7b99Saartbik         return matchFailure();
317e83b7b99Saartbik       return matchSuccess();
318e83b7b99Saartbik 
319e83b7b99Saartbik     } else if (eltType.isF32() || eltType.isF64()) {
320e83b7b99Saartbik       // Floating-point reductions: add/mul/min/max
321e83b7b99Saartbik       if (kind == "add") {
322e83b7b99Saartbik         Value zero = rewriter.create<LLVM::ConstantOp>(
323e83b7b99Saartbik             op->getLoc(), llvmType, rewriter.getZeroAttr(eltType));
324e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fadd>(
325e83b7b99Saartbik             op, llvmType, zero, operands[0]);
326e83b7b99Saartbik       } else if (kind == "mul") {
327e83b7b99Saartbik         Value one = rewriter.create<LLVM::ConstantOp>(
328e83b7b99Saartbik             op->getLoc(), llvmType, rewriter.getFloatAttr(eltType, 1.0));
329e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fmul>(
330e83b7b99Saartbik             op, llvmType, one, operands[0]);
331e83b7b99Saartbik       } else if (kind == "min")
332e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmin>(
333e83b7b99Saartbik             op, llvmType, operands[0]);
334e83b7b99Saartbik       else if (kind == "max")
335e83b7b99Saartbik         rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_fmax>(
336e83b7b99Saartbik             op, llvmType, operands[0]);
337e83b7b99Saartbik       else
338e83b7b99Saartbik         return matchFailure();
339e83b7b99Saartbik       return matchSuccess();
340e83b7b99Saartbik     }
341e83b7b99Saartbik     return matchFailure();
342e83b7b99Saartbik   }
343e83b7b99Saartbik };
344e83b7b99Saartbik 
345b21c7999Saartbik // TODO(ajcbik): merge Reduction and ReductionV2
346870c1fd4SAlex Zinenko class VectorReductionV2OpConversion : public ConvertToLLVMPattern {
347b21c7999Saartbik public:
348b21c7999Saartbik   explicit VectorReductionV2OpConversion(MLIRContext *context,
349b21c7999Saartbik                                          LLVMTypeConverter &typeConverter)
350870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ReductionV2Op::getOperationName(), context,
351b21c7999Saartbik                              typeConverter) {}
352b21c7999Saartbik   PatternMatchResult
353b21c7999Saartbik   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
354b21c7999Saartbik                   ConversionPatternRewriter &rewriter) const override {
355b21c7999Saartbik     auto reductionOp = cast<vector::ReductionV2Op>(op);
356b21c7999Saartbik     auto kind = reductionOp.kind();
357b21c7999Saartbik     Type eltType = reductionOp.dest().getType();
3580f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(eltType);
359b21c7999Saartbik     if (kind == "add") {
360b21c7999Saartbik       rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fadd>(
361b21c7999Saartbik           op, llvmType, operands[1], operands[0]);
362b21c7999Saartbik       return matchSuccess();
363b21c7999Saartbik     } else if (kind == "mul") {
364b21c7999Saartbik       rewriter.replaceOpWithNewOp<LLVM::experimental_vector_reduce_v2_fmul>(
365b21c7999Saartbik           op, llvmType, operands[1], operands[0]);
366b21c7999Saartbik       return matchSuccess();
367b21c7999Saartbik     }
368b21c7999Saartbik     return matchFailure();
369b21c7999Saartbik   }
370b21c7999Saartbik };
371b21c7999Saartbik 
372870c1fd4SAlex Zinenko class VectorShuffleOpConversion : public ConvertToLLVMPattern {
3731c81adf3SAart Bik public:
3741c81adf3SAart Bik   explicit VectorShuffleOpConversion(MLIRContext *context,
3751c81adf3SAart Bik                                      LLVMTypeConverter &typeConverter)
376870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ShuffleOp::getOperationName(), context,
3771c81adf3SAart Bik                              typeConverter) {}
3781c81adf3SAart Bik 
3791c81adf3SAart Bik   PatternMatchResult
380e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
3811c81adf3SAart Bik                   ConversionPatternRewriter &rewriter) const override {
3821c81adf3SAart Bik     auto loc = op->getLoc();
3831c81adf3SAart Bik     auto adaptor = vector::ShuffleOpOperandAdaptor(operands);
3841c81adf3SAart Bik     auto shuffleOp = cast<vector::ShuffleOp>(op);
3851c81adf3SAart Bik     auto v1Type = shuffleOp.getV1VectorType();
3861c81adf3SAart Bik     auto v2Type = shuffleOp.getV2VectorType();
3871c81adf3SAart Bik     auto vectorType = shuffleOp.getVectorType();
3880f04384dSAlex Zinenko     Type llvmType = typeConverter.convertType(vectorType);
3891c81adf3SAart Bik     auto maskArrayAttr = shuffleOp.mask();
3901c81adf3SAart Bik 
3911c81adf3SAart Bik     // Bail if result type cannot be lowered.
3921c81adf3SAart Bik     if (!llvmType)
3931c81adf3SAart Bik       return matchFailure();
3941c81adf3SAart Bik 
3951c81adf3SAart Bik     // Get rank and dimension sizes.
3961c81adf3SAart Bik     int64_t rank = vectorType.getRank();
3971c81adf3SAart Bik     assert(v1Type.getRank() == rank);
3981c81adf3SAart Bik     assert(v2Type.getRank() == rank);
3991c81adf3SAart Bik     int64_t v1Dim = v1Type.getDimSize(0);
4001c81adf3SAart Bik 
4011c81adf3SAart Bik     // For rank 1, where both operands have *exactly* the same vector type,
4021c81adf3SAart Bik     // there is direct shuffle support in LLVM. Use it!
4031c81adf3SAart Bik     if (rank == 1 && v1Type == v2Type) {
404e62a6956SRiver Riddle       Value shuffle = rewriter.create<LLVM::ShuffleVectorOp>(
4051c81adf3SAart Bik           loc, adaptor.v1(), adaptor.v2(), maskArrayAttr);
4061c81adf3SAart Bik       rewriter.replaceOp(op, shuffle);
4071c81adf3SAart Bik       return matchSuccess();
408b36aaeafSAart Bik     }
409b36aaeafSAart Bik 
4101c81adf3SAart Bik     // For all other cases, insert the individual values individually.
411e62a6956SRiver Riddle     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
4121c81adf3SAart Bik     int64_t insPos = 0;
4131c81adf3SAart Bik     for (auto en : llvm::enumerate(maskArrayAttr)) {
4141c81adf3SAart Bik       int64_t extPos = en.value().cast<IntegerAttr>().getInt();
415e62a6956SRiver Riddle       Value value = adaptor.v1();
4161c81adf3SAart Bik       if (extPos >= v1Dim) {
4171c81adf3SAart Bik         extPos -= v1Dim;
4181c81adf3SAart Bik         value = adaptor.v2();
419b36aaeafSAart Bik       }
4200f04384dSAlex Zinenko       Value extract = extractOne(rewriter, typeConverter, loc, value, llvmType,
4210f04384dSAlex Zinenko                                  rank, extPos);
4220f04384dSAlex Zinenko       insert = insertOne(rewriter, typeConverter, loc, insert, extract,
4230f04384dSAlex Zinenko                          llvmType, rank, insPos++);
4241c81adf3SAart Bik     }
4251c81adf3SAart Bik     rewriter.replaceOp(op, insert);
4261c81adf3SAart Bik     return matchSuccess();
427b36aaeafSAart Bik   }
428b36aaeafSAart Bik };
429b36aaeafSAart Bik 
430870c1fd4SAlex Zinenko class VectorExtractElementOpConversion : public ConvertToLLVMPattern {
431cd5dab8aSAart Bik public:
432cd5dab8aSAart Bik   explicit VectorExtractElementOpConversion(MLIRContext *context,
433cd5dab8aSAart Bik                                             LLVMTypeConverter &typeConverter)
434870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ExtractElementOp::getOperationName(),
435870c1fd4SAlex Zinenko                              context, typeConverter) {}
436cd5dab8aSAart Bik 
437cd5dab8aSAart Bik   PatternMatchResult
438e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
439cd5dab8aSAart Bik                   ConversionPatternRewriter &rewriter) const override {
440cd5dab8aSAart Bik     auto adaptor = vector::ExtractElementOpOperandAdaptor(operands);
441cd5dab8aSAart Bik     auto extractEltOp = cast<vector::ExtractElementOp>(op);
442cd5dab8aSAart Bik     auto vectorType = extractEltOp.getVectorType();
4430f04384dSAlex Zinenko     auto llvmType = typeConverter.convertType(vectorType.getElementType());
444cd5dab8aSAart Bik 
445cd5dab8aSAart Bik     // Bail if result type cannot be lowered.
446cd5dab8aSAart Bik     if (!llvmType)
447cd5dab8aSAart Bik       return matchFailure();
448cd5dab8aSAart Bik 
449cd5dab8aSAart Bik     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
450cd5dab8aSAart Bik         op, llvmType, adaptor.vector(), adaptor.position());
451cd5dab8aSAart Bik     return matchSuccess();
452cd5dab8aSAart Bik   }
453cd5dab8aSAart Bik };
454cd5dab8aSAart Bik 
455870c1fd4SAlex Zinenko class VectorExtractOpConversion : public ConvertToLLVMPattern {
4565c0c51a9SNicolas Vasilache public:
4579826fe5cSAart Bik   explicit VectorExtractOpConversion(MLIRContext *context,
4585c0c51a9SNicolas Vasilache                                      LLVMTypeConverter &typeConverter)
459870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::ExtractOp::getOperationName(), context,
4605c0c51a9SNicolas Vasilache                              typeConverter) {}
4615c0c51a9SNicolas Vasilache 
4625c0c51a9SNicolas Vasilache   PatternMatchResult
463e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
4645c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
4655c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
466d37f2725SAart Bik     auto adaptor = vector::ExtractOpOperandAdaptor(operands);
467d37f2725SAart Bik     auto extractOp = cast<vector::ExtractOp>(op);
4689826fe5cSAart Bik     auto vectorType = extractOp.getVectorType();
4692bdf33ccSRiver Riddle     auto resultType = extractOp.getResult().getType();
4700f04384dSAlex Zinenko     auto llvmResultType = typeConverter.convertType(resultType);
4715c0c51a9SNicolas Vasilache     auto positionArrayAttr = extractOp.position();
4729826fe5cSAart Bik 
4739826fe5cSAart Bik     // Bail if result type cannot be lowered.
4749826fe5cSAart Bik     if (!llvmResultType)
4759826fe5cSAart Bik       return matchFailure();
4769826fe5cSAart Bik 
4775c0c51a9SNicolas Vasilache     // One-shot extraction of vector from array (only requires extractvalue).
4785c0c51a9SNicolas Vasilache     if (resultType.isa<VectorType>()) {
479e62a6956SRiver Riddle       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
4805c0c51a9SNicolas Vasilache           loc, llvmResultType, adaptor.vector(), positionArrayAttr);
4815c0c51a9SNicolas Vasilache       rewriter.replaceOp(op, extracted);
4825c0c51a9SNicolas Vasilache       return matchSuccess();
4835c0c51a9SNicolas Vasilache     }
4845c0c51a9SNicolas Vasilache 
4859826fe5cSAart Bik     // Potential extraction of 1-D vector from array.
4865c0c51a9SNicolas Vasilache     auto *context = op->getContext();
487e62a6956SRiver Riddle     Value extracted = adaptor.vector();
4885c0c51a9SNicolas Vasilache     auto positionAttrs = positionArrayAttr.getValue();
4895c0c51a9SNicolas Vasilache     if (positionAttrs.size() > 1) {
4909826fe5cSAart Bik       auto oneDVectorType = reducedVectorTypeBack(vectorType);
4915c0c51a9SNicolas Vasilache       auto nMinusOnePositionAttrs =
4925c0c51a9SNicolas Vasilache           ArrayAttr::get(positionAttrs.drop_back(), context);
4935c0c51a9SNicolas Vasilache       extracted = rewriter.create<LLVM::ExtractValueOp>(
4940f04384dSAlex Zinenko           loc, typeConverter.convertType(oneDVectorType), extracted,
4955c0c51a9SNicolas Vasilache           nMinusOnePositionAttrs);
4965c0c51a9SNicolas Vasilache     }
4975c0c51a9SNicolas Vasilache 
4985c0c51a9SNicolas Vasilache     // Remaining extraction of element from 1-D LLVM vector
4995c0c51a9SNicolas Vasilache     auto position = positionAttrs.back().cast<IntegerAttr>();
5000f04384dSAlex Zinenko     auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
5011d47564aSAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
5025c0c51a9SNicolas Vasilache     extracted =
5035c0c51a9SNicolas Vasilache         rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant);
5045c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, extracted);
5055c0c51a9SNicolas Vasilache 
5065c0c51a9SNicolas Vasilache     return matchSuccess();
5075c0c51a9SNicolas Vasilache   }
5085c0c51a9SNicolas Vasilache };
5095c0c51a9SNicolas Vasilache 
510681f929fSNicolas Vasilache /// Conversion pattern that turns a vector.fma on a 1-D vector
511681f929fSNicolas Vasilache /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion.
512681f929fSNicolas Vasilache /// This does not match vectors of n >= 2 rank.
513681f929fSNicolas Vasilache ///
514681f929fSNicolas Vasilache /// Example:
515681f929fSNicolas Vasilache /// ```
516681f929fSNicolas Vasilache ///  vector.fma %a, %a, %a : vector<8xf32>
517681f929fSNicolas Vasilache /// ```
518681f929fSNicolas Vasilache /// is converted to:
519681f929fSNicolas Vasilache /// ```
520681f929fSNicolas Vasilache ///  llvm.intr.fma %va, %va, %va:
521681f929fSNicolas Vasilache ///    (!llvm<"<8 x float>">, !llvm<"<8 x float>">, !llvm<"<8 x float>">)
522681f929fSNicolas Vasilache ///    -> !llvm<"<8 x float>">
523681f929fSNicolas Vasilache /// ```
524870c1fd4SAlex Zinenko class VectorFMAOp1DConversion : public ConvertToLLVMPattern {
525681f929fSNicolas Vasilache public:
526681f929fSNicolas Vasilache   explicit VectorFMAOp1DConversion(MLIRContext *context,
527681f929fSNicolas Vasilache                                    LLVMTypeConverter &typeConverter)
528870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::FMAOp::getOperationName(), context,
529681f929fSNicolas Vasilache                              typeConverter) {}
530681f929fSNicolas Vasilache 
531681f929fSNicolas Vasilache   PatternMatchResult
532681f929fSNicolas Vasilache   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
533681f929fSNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
534681f929fSNicolas Vasilache     auto adaptor = vector::FMAOpOperandAdaptor(operands);
535681f929fSNicolas Vasilache     vector::FMAOp fmaOp = cast<vector::FMAOp>(op);
536681f929fSNicolas Vasilache     VectorType vType = fmaOp.getVectorType();
537681f929fSNicolas Vasilache     if (vType.getRank() != 1)
538681f929fSNicolas Vasilache       return matchFailure();
539681f929fSNicolas Vasilache     rewriter.replaceOpWithNewOp<LLVM::FMAOp>(op, adaptor.lhs(), adaptor.rhs(),
540681f929fSNicolas Vasilache                                              adaptor.acc());
541681f929fSNicolas Vasilache     return matchSuccess();
542681f929fSNicolas Vasilache   }
543681f929fSNicolas Vasilache };
544681f929fSNicolas Vasilache 
545870c1fd4SAlex Zinenko class VectorInsertElementOpConversion : public ConvertToLLVMPattern {
546cd5dab8aSAart Bik public:
547cd5dab8aSAart Bik   explicit VectorInsertElementOpConversion(MLIRContext *context,
548cd5dab8aSAart Bik                                            LLVMTypeConverter &typeConverter)
549870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::InsertElementOp::getOperationName(),
550870c1fd4SAlex Zinenko                              context, typeConverter) {}
551cd5dab8aSAart Bik 
552cd5dab8aSAart Bik   PatternMatchResult
553e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
554cd5dab8aSAart Bik                   ConversionPatternRewriter &rewriter) const override {
555cd5dab8aSAart Bik     auto adaptor = vector::InsertElementOpOperandAdaptor(operands);
556cd5dab8aSAart Bik     auto insertEltOp = cast<vector::InsertElementOp>(op);
557cd5dab8aSAart Bik     auto vectorType = insertEltOp.getDestVectorType();
5580f04384dSAlex Zinenko     auto llvmType = typeConverter.convertType(vectorType);
559cd5dab8aSAart Bik 
560cd5dab8aSAart Bik     // Bail if result type cannot be lowered.
561cd5dab8aSAart Bik     if (!llvmType)
562cd5dab8aSAart Bik       return matchFailure();
563cd5dab8aSAart Bik 
564cd5dab8aSAart Bik     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
565cd5dab8aSAart Bik         op, llvmType, adaptor.dest(), adaptor.source(), adaptor.position());
566cd5dab8aSAart Bik     return matchSuccess();
567cd5dab8aSAart Bik   }
568cd5dab8aSAart Bik };
569cd5dab8aSAart Bik 
570870c1fd4SAlex Zinenko class VectorInsertOpConversion : public ConvertToLLVMPattern {
5719826fe5cSAart Bik public:
5729826fe5cSAart Bik   explicit VectorInsertOpConversion(MLIRContext *context,
5739826fe5cSAart Bik                                     LLVMTypeConverter &typeConverter)
574870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::InsertOp::getOperationName(), context,
5759826fe5cSAart Bik                              typeConverter) {}
5769826fe5cSAart Bik 
5779826fe5cSAart Bik   PatternMatchResult
578e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
5799826fe5cSAart Bik                   ConversionPatternRewriter &rewriter) const override {
5809826fe5cSAart Bik     auto loc = op->getLoc();
5819826fe5cSAart Bik     auto adaptor = vector::InsertOpOperandAdaptor(operands);
5829826fe5cSAart Bik     auto insertOp = cast<vector::InsertOp>(op);
5839826fe5cSAart Bik     auto sourceType = insertOp.getSourceType();
5849826fe5cSAart Bik     auto destVectorType = insertOp.getDestVectorType();
5850f04384dSAlex Zinenko     auto llvmResultType = typeConverter.convertType(destVectorType);
5869826fe5cSAart Bik     auto positionArrayAttr = insertOp.position();
5879826fe5cSAart Bik 
5889826fe5cSAart Bik     // Bail if result type cannot be lowered.
5899826fe5cSAart Bik     if (!llvmResultType)
5909826fe5cSAart Bik       return matchFailure();
5919826fe5cSAart Bik 
5929826fe5cSAart Bik     // One-shot insertion of a vector into an array (only requires insertvalue).
5939826fe5cSAart Bik     if (sourceType.isa<VectorType>()) {
594e62a6956SRiver Riddle       Value inserted = rewriter.create<LLVM::InsertValueOp>(
5959826fe5cSAart Bik           loc, llvmResultType, adaptor.dest(), adaptor.source(),
5969826fe5cSAart Bik           positionArrayAttr);
5979826fe5cSAart Bik       rewriter.replaceOp(op, inserted);
5989826fe5cSAart Bik       return matchSuccess();
5999826fe5cSAart Bik     }
6009826fe5cSAart Bik 
6019826fe5cSAart Bik     // Potential extraction of 1-D vector from array.
6029826fe5cSAart Bik     auto *context = op->getContext();
603e62a6956SRiver Riddle     Value extracted = adaptor.dest();
6049826fe5cSAart Bik     auto positionAttrs = positionArrayAttr.getValue();
6059826fe5cSAart Bik     auto position = positionAttrs.back().cast<IntegerAttr>();
6069826fe5cSAart Bik     auto oneDVectorType = destVectorType;
6079826fe5cSAart Bik     if (positionAttrs.size() > 1) {
6089826fe5cSAart Bik       oneDVectorType = reducedVectorTypeBack(destVectorType);
6099826fe5cSAart Bik       auto nMinusOnePositionAttrs =
6109826fe5cSAart Bik           ArrayAttr::get(positionAttrs.drop_back(), context);
6119826fe5cSAart Bik       extracted = rewriter.create<LLVM::ExtractValueOp>(
6120f04384dSAlex Zinenko           loc, typeConverter.convertType(oneDVectorType), extracted,
6139826fe5cSAart Bik           nMinusOnePositionAttrs);
6149826fe5cSAart Bik     }
6159826fe5cSAart Bik 
6169826fe5cSAart Bik     // Insertion of an element into a 1-D LLVM vector.
6170f04384dSAlex Zinenko     auto i64Type = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
6181d47564aSAart Bik     auto constant = rewriter.create<LLVM::ConstantOp>(loc, i64Type, position);
619e62a6956SRiver Riddle     Value inserted = rewriter.create<LLVM::InsertElementOp>(
6200f04384dSAlex Zinenko         loc, typeConverter.convertType(oneDVectorType), extracted,
6210f04384dSAlex Zinenko         adaptor.source(), constant);
6229826fe5cSAart Bik 
6239826fe5cSAart Bik     // Potential insertion of resulting 1-D vector into array.
6249826fe5cSAart Bik     if (positionAttrs.size() > 1) {
6259826fe5cSAart Bik       auto nMinusOnePositionAttrs =
6269826fe5cSAart Bik           ArrayAttr::get(positionAttrs.drop_back(), context);
6279826fe5cSAart Bik       inserted = rewriter.create<LLVM::InsertValueOp>(loc, llvmResultType,
6289826fe5cSAart Bik                                                       adaptor.dest(), inserted,
6299826fe5cSAart Bik                                                       nMinusOnePositionAttrs);
6309826fe5cSAart Bik     }
6319826fe5cSAart Bik 
6329826fe5cSAart Bik     rewriter.replaceOp(op, inserted);
6339826fe5cSAart Bik     return matchSuccess();
6349826fe5cSAart Bik   }
6359826fe5cSAart Bik };
6369826fe5cSAart Bik 
637681f929fSNicolas Vasilache /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1.
638681f929fSNicolas Vasilache ///
639681f929fSNicolas Vasilache /// Example:
640681f929fSNicolas Vasilache /// ```
641681f929fSNicolas Vasilache ///   %d = vector.fma %a, %b, %c : vector<2x4xf32>
642681f929fSNicolas Vasilache /// ```
643681f929fSNicolas Vasilache /// is rewritten into:
644681f929fSNicolas Vasilache /// ```
645681f929fSNicolas Vasilache ///  %r = splat %f0: vector<2x4xf32>
646681f929fSNicolas Vasilache ///  %va = vector.extractvalue %a[0] : vector<2x4xf32>
647681f929fSNicolas Vasilache ///  %vb = vector.extractvalue %b[0] : vector<2x4xf32>
648681f929fSNicolas Vasilache ///  %vc = vector.extractvalue %c[0] : vector<2x4xf32>
649681f929fSNicolas Vasilache ///  %vd = vector.fma %va, %vb, %vc : vector<4xf32>
650681f929fSNicolas Vasilache ///  %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32>
651681f929fSNicolas Vasilache ///  %va2 = vector.extractvalue %a2[1] : vector<2x4xf32>
652681f929fSNicolas Vasilache ///  %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32>
653681f929fSNicolas Vasilache ///  %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32>
654681f929fSNicolas Vasilache ///  %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32>
655681f929fSNicolas Vasilache ///  %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32>
656681f929fSNicolas Vasilache ///  // %r3 holds the final value.
657681f929fSNicolas Vasilache /// ```
658681f929fSNicolas Vasilache class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> {
659681f929fSNicolas Vasilache public:
660681f929fSNicolas Vasilache   using OpRewritePattern<FMAOp>::OpRewritePattern;
661681f929fSNicolas Vasilache 
662681f929fSNicolas Vasilache   PatternMatchResult matchAndRewrite(FMAOp op,
663681f929fSNicolas Vasilache                                      PatternRewriter &rewriter) const override {
664681f929fSNicolas Vasilache     auto vType = op.getVectorType();
665681f929fSNicolas Vasilache     if (vType.getRank() < 2)
666681f929fSNicolas Vasilache       return matchFailure();
667681f929fSNicolas Vasilache 
668681f929fSNicolas Vasilache     auto loc = op.getLoc();
669681f929fSNicolas Vasilache     auto elemType = vType.getElementType();
670681f929fSNicolas Vasilache     Value zero = rewriter.create<ConstantOp>(loc, elemType,
671681f929fSNicolas Vasilache                                              rewriter.getZeroAttr(elemType));
672681f929fSNicolas Vasilache     Value desc = rewriter.create<SplatOp>(loc, vType, zero);
673681f929fSNicolas Vasilache     for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) {
674681f929fSNicolas Vasilache       Value extrLHS = rewriter.create<ExtractOp>(loc, op.lhs(), i);
675681f929fSNicolas Vasilache       Value extrRHS = rewriter.create<ExtractOp>(loc, op.rhs(), i);
676681f929fSNicolas Vasilache       Value extrACC = rewriter.create<ExtractOp>(loc, op.acc(), i);
677681f929fSNicolas Vasilache       Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC);
678681f929fSNicolas Vasilache       desc = rewriter.create<InsertOp>(loc, fma, desc, i);
679681f929fSNicolas Vasilache     }
680681f929fSNicolas Vasilache     rewriter.replaceOp(op, desc);
681681f929fSNicolas Vasilache     return matchSuccess();
682681f929fSNicolas Vasilache   }
683681f929fSNicolas Vasilache };
684681f929fSNicolas Vasilache 
6852d515e49SNicolas Vasilache // When ranks are different, InsertStridedSlice needs to extract a properly
6862d515e49SNicolas Vasilache // ranked vector from the destination vector into which to insert. This pattern
6872d515e49SNicolas Vasilache // only takes care of this part and forwards the rest of the conversion to
6882d515e49SNicolas Vasilache // another pattern that converts InsertStridedSlice for operands of the same
6892d515e49SNicolas Vasilache // rank.
6902d515e49SNicolas Vasilache //
6912d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors
6922d515e49SNicolas Vasilache // have different ranks. In this case:
6932d515e49SNicolas Vasilache //   1. the proper subvector is extracted from the destination vector
6942d515e49SNicolas Vasilache //   2. a new InsertStridedSlice op is created to insert the source in the
6952d515e49SNicolas Vasilache //   destination subvector
6962d515e49SNicolas Vasilache //   3. the destination subvector is inserted back in the proper place
6972d515e49SNicolas Vasilache //   4. the op is replaced by the result of step 3.
6982d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a
6992d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`.
7002d515e49SNicolas Vasilache class VectorInsertStridedSliceOpDifferentRankRewritePattern
7012d515e49SNicolas Vasilache     : public OpRewritePattern<InsertStridedSliceOp> {
7022d515e49SNicolas Vasilache public:
7032d515e49SNicolas Vasilache   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
7042d515e49SNicolas Vasilache 
7052d515e49SNicolas Vasilache   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
7062d515e49SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
7072d515e49SNicolas Vasilache     auto srcType = op.getSourceVectorType();
7082d515e49SNicolas Vasilache     auto dstType = op.getDestVectorType();
7092d515e49SNicolas Vasilache 
7102d515e49SNicolas Vasilache     if (op.offsets().getValue().empty())
7112d515e49SNicolas Vasilache       return matchFailure();
7122d515e49SNicolas Vasilache 
7132d515e49SNicolas Vasilache     auto loc = op.getLoc();
7142d515e49SNicolas Vasilache     int64_t rankDiff = dstType.getRank() - srcType.getRank();
7152d515e49SNicolas Vasilache     assert(rankDiff >= 0);
7162d515e49SNicolas Vasilache     if (rankDiff == 0)
7172d515e49SNicolas Vasilache       return matchFailure();
7182d515e49SNicolas Vasilache 
7192d515e49SNicolas Vasilache     int64_t rankRest = dstType.getRank() - rankDiff;
7202d515e49SNicolas Vasilache     // Extract / insert the subvector of matching rank and InsertStridedSlice
7212d515e49SNicolas Vasilache     // on it.
7222d515e49SNicolas Vasilache     Value extracted =
7232d515e49SNicolas Vasilache         rewriter.create<ExtractOp>(loc, op.dest(),
7242d515e49SNicolas Vasilache                                    getI64SubArray(op.offsets(), /*dropFront=*/0,
7252d515e49SNicolas Vasilache                                                   /*dropFront=*/rankRest));
7262d515e49SNicolas Vasilache     // A different pattern will kick in for InsertStridedSlice with matching
7272d515e49SNicolas Vasilache     // ranks.
7282d515e49SNicolas Vasilache     auto stridedSliceInnerOp = rewriter.create<InsertStridedSliceOp>(
7292d515e49SNicolas Vasilache         loc, op.source(), extracted,
7302d515e49SNicolas Vasilache         getI64SubArray(op.offsets(), /*dropFront=*/rankDiff),
731c8fc76a9Saartbik         getI64SubArray(op.strides(), /*dropFront=*/0));
7322d515e49SNicolas Vasilache     rewriter.replaceOpWithNewOp<InsertOp>(
7332d515e49SNicolas Vasilache         op, stridedSliceInnerOp.getResult(), op.dest(),
7342d515e49SNicolas Vasilache         getI64SubArray(op.offsets(), /*dropFront=*/0,
7352d515e49SNicolas Vasilache                        /*dropFront=*/rankRest));
7362d515e49SNicolas Vasilache     return matchSuccess();
7372d515e49SNicolas Vasilache   }
7382d515e49SNicolas Vasilache };
7392d515e49SNicolas Vasilache 
7402d515e49SNicolas Vasilache // RewritePattern for InsertStridedSliceOp where source and destination vectors
7412d515e49SNicolas Vasilache // have the same rank. In this case, we reduce
7422d515e49SNicolas Vasilache //   1. the proper subvector is extracted from the destination vector
7432d515e49SNicolas Vasilache //   2. a new InsertStridedSlice op is created to insert the source in the
7442d515e49SNicolas Vasilache //   destination subvector
7452d515e49SNicolas Vasilache //   3. the destination subvector is inserted back in the proper place
7462d515e49SNicolas Vasilache //   4. the op is replaced by the result of step 3.
7472d515e49SNicolas Vasilache // The new InsertStridedSlice from step 2. will be picked up by a
7482d515e49SNicolas Vasilache // `VectorInsertStridedSliceOpSameRankRewritePattern`.
7492d515e49SNicolas Vasilache class VectorInsertStridedSliceOpSameRankRewritePattern
7502d515e49SNicolas Vasilache     : public OpRewritePattern<InsertStridedSliceOp> {
7512d515e49SNicolas Vasilache public:
7522d515e49SNicolas Vasilache   using OpRewritePattern<InsertStridedSliceOp>::OpRewritePattern;
7532d515e49SNicolas Vasilache 
7542d515e49SNicolas Vasilache   PatternMatchResult matchAndRewrite(InsertStridedSliceOp op,
7552d515e49SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
7562d515e49SNicolas Vasilache     auto srcType = op.getSourceVectorType();
7572d515e49SNicolas Vasilache     auto dstType = op.getDestVectorType();
7582d515e49SNicolas Vasilache 
7592d515e49SNicolas Vasilache     if (op.offsets().getValue().empty())
7602d515e49SNicolas Vasilache       return matchFailure();
7612d515e49SNicolas Vasilache 
7622d515e49SNicolas Vasilache     int64_t rankDiff = dstType.getRank() - srcType.getRank();
7632d515e49SNicolas Vasilache     assert(rankDiff >= 0);
7642d515e49SNicolas Vasilache     if (rankDiff != 0)
7652d515e49SNicolas Vasilache       return matchFailure();
7662d515e49SNicolas Vasilache 
7672d515e49SNicolas Vasilache     if (srcType == dstType) {
7682d515e49SNicolas Vasilache       rewriter.replaceOp(op, op.source());
7692d515e49SNicolas Vasilache       return matchSuccess();
7702d515e49SNicolas Vasilache     }
7712d515e49SNicolas Vasilache 
7722d515e49SNicolas Vasilache     int64_t offset =
7732d515e49SNicolas Vasilache         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
7742d515e49SNicolas Vasilache     int64_t size = srcType.getShape().front();
7752d515e49SNicolas Vasilache     int64_t stride =
7762d515e49SNicolas Vasilache         op.strides().getValue().front().cast<IntegerAttr>().getInt();
7772d515e49SNicolas Vasilache 
7782d515e49SNicolas Vasilache     auto loc = op.getLoc();
7792d515e49SNicolas Vasilache     Value res = op.dest();
7802d515e49SNicolas Vasilache     // For each slice of the source vector along the most major dimension.
7812d515e49SNicolas Vasilache     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
7822d515e49SNicolas Vasilache          off += stride, ++idx) {
7832d515e49SNicolas Vasilache       // 1. extract the proper subvector (or element) from source
7842d515e49SNicolas Vasilache       Value extractedSource = extractOne(rewriter, loc, op.source(), idx);
7852d515e49SNicolas Vasilache       if (extractedSource.getType().isa<VectorType>()) {
7862d515e49SNicolas Vasilache         // 2. If we have a vector, extract the proper subvector from destination
7872d515e49SNicolas Vasilache         // Otherwise we are at the element level and no need to recurse.
7882d515e49SNicolas Vasilache         Value extractedDest = extractOne(rewriter, loc, op.dest(), off);
7892d515e49SNicolas Vasilache         // 3. Reduce the problem to lowering a new InsertStridedSlice op with
7902d515e49SNicolas Vasilache         // smaller rank.
7912d515e49SNicolas Vasilache         InsertStridedSliceOp insertStridedSliceOp =
7922d515e49SNicolas Vasilache             rewriter.create<InsertStridedSliceOp>(
7932d515e49SNicolas Vasilache                 loc, extractedSource, extractedDest,
7942d515e49SNicolas Vasilache                 getI64SubArray(op.offsets(), /* dropFront=*/1),
7952d515e49SNicolas Vasilache                 getI64SubArray(op.strides(), /* dropFront=*/1));
7962d515e49SNicolas Vasilache         // Call matchAndRewrite recursively from within the pattern. This
7972d515e49SNicolas Vasilache         // circumvents the current limitation that a given pattern cannot
7982d515e49SNicolas Vasilache         // be called multiple times by the PatternRewrite infrastructure (to
7992d515e49SNicolas Vasilache         // avoid infinite recursion, but in this case, infinite recursion
8002d515e49SNicolas Vasilache         // cannot happen because the rank is strictly decreasing).
8012d515e49SNicolas Vasilache         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
8022d515e49SNicolas Vasilache         // a potential function that must decrease and allow the same pattern
8032d515e49SNicolas Vasilache         // multiple times.
8042d515e49SNicolas Vasilache         auto success = matchAndRewrite(insertStridedSliceOp, rewriter);
8052d515e49SNicolas Vasilache         (void)success;
8062d515e49SNicolas Vasilache         assert(success && "Unexpected failure");
8072d515e49SNicolas Vasilache         extractedSource = insertStridedSliceOp;
8082d515e49SNicolas Vasilache       }
8092d515e49SNicolas Vasilache       // 4. Insert the extractedSource into the res vector.
8102d515e49SNicolas Vasilache       res = insertOne(rewriter, loc, extractedSource, res, off);
8112d515e49SNicolas Vasilache     }
8122d515e49SNicolas Vasilache 
8132d515e49SNicolas Vasilache     rewriter.replaceOp(op, res);
8142d515e49SNicolas Vasilache     return matchSuccess();
8152d515e49SNicolas Vasilache   }
8162d515e49SNicolas Vasilache };
8172d515e49SNicolas Vasilache 
818870c1fd4SAlex Zinenko class VectorOuterProductOpConversion : public ConvertToLLVMPattern {
8195c0c51a9SNicolas Vasilache public:
8205c0c51a9SNicolas Vasilache   explicit VectorOuterProductOpConversion(MLIRContext *context,
8215c0c51a9SNicolas Vasilache                                           LLVMTypeConverter &typeConverter)
822870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::OuterProductOp::getOperationName(),
823870c1fd4SAlex Zinenko                              context, typeConverter) {}
8245c0c51a9SNicolas Vasilache 
8255c0c51a9SNicolas Vasilache   PatternMatchResult
826e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
8275c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
8285c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
8295c0c51a9SNicolas Vasilache     auto adaptor = vector::OuterProductOpOperandAdaptor(operands);
8305c0c51a9SNicolas Vasilache     auto *ctx = op->getContext();
8312bdf33ccSRiver Riddle     auto vLHS = adaptor.lhs().getType().cast<LLVM::LLVMType>();
8322bdf33ccSRiver Riddle     auto vRHS = adaptor.rhs().getType().cast<LLVM::LLVMType>();
8335c0c51a9SNicolas Vasilache     auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements();
8345c0c51a9SNicolas Vasilache     auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements();
8350f04384dSAlex Zinenko     auto llvmArrayOfVectType = typeConverter.convertType(
8362bdf33ccSRiver Riddle         cast<vector::OuterProductOp>(op).getResult().getType());
837e62a6956SRiver Riddle     Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType);
838e62a6956SRiver Riddle     Value a = adaptor.lhs(), b = adaptor.rhs();
839e62a6956SRiver Riddle     Value acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front();
840e62a6956SRiver Riddle     SmallVector<Value, 8> lhs, accs;
8415c0c51a9SNicolas Vasilache     lhs.reserve(rankLHS);
8425c0c51a9SNicolas Vasilache     accs.reserve(rankLHS);
8435c0c51a9SNicolas Vasilache     for (unsigned d = 0, e = rankLHS; d < e; ++d) {
8445c0c51a9SNicolas Vasilache       // shufflevector explicitly requires i32.
8455c0c51a9SNicolas Vasilache       auto attr = rewriter.getI32IntegerAttr(d);
8465c0c51a9SNicolas Vasilache       SmallVector<Attribute, 4> bcastAttr(rankRHS, attr);
8475c0c51a9SNicolas Vasilache       auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx);
848e62a6956SRiver Riddle       Value aD = nullptr, accD = nullptr;
8495c0c51a9SNicolas Vasilache       // 1. Broadcast the element a[d] into vector aD.
8505c0c51a9SNicolas Vasilache       aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr);
8515c0c51a9SNicolas Vasilache       // 2. If acc is present, extract 1-d vector acc[d] into accD.
8525c0c51a9SNicolas Vasilache       if (acc)
8535c0c51a9SNicolas Vasilache         accD = rewriter.create<LLVM::ExtractValueOp>(
8545c0c51a9SNicolas Vasilache             loc, vRHS, acc, rewriter.getI64ArrayAttr(d));
8555c0c51a9SNicolas Vasilache       // 3. Compute aD outer b (plus accD, if relevant).
856e62a6956SRiver Riddle       Value aOuterbD =
857499ad458SNicolas Vasilache           accD
858499ad458SNicolas Vasilache               ? rewriter.create<LLVM::FMAOp>(loc, vRHS, aD, b, accD).getResult()
8595c0c51a9SNicolas Vasilache               : rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult();
8605c0c51a9SNicolas Vasilache       // 4. Insert as value `d` in the descriptor.
8615c0c51a9SNicolas Vasilache       desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType,
8625c0c51a9SNicolas Vasilache                                                   desc, aOuterbD,
8635c0c51a9SNicolas Vasilache                                                   rewriter.getI64ArrayAttr(d));
8645c0c51a9SNicolas Vasilache     }
8655c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, desc);
8665c0c51a9SNicolas Vasilache     return matchSuccess();
8675c0c51a9SNicolas Vasilache   }
8685c0c51a9SNicolas Vasilache };
8695c0c51a9SNicolas Vasilache 
870870c1fd4SAlex Zinenko class VectorTypeCastOpConversion : public ConvertToLLVMPattern {
8715c0c51a9SNicolas Vasilache public:
8725c0c51a9SNicolas Vasilache   explicit VectorTypeCastOpConversion(MLIRContext *context,
8735c0c51a9SNicolas Vasilache                                       LLVMTypeConverter &typeConverter)
874870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::TypeCastOp::getOperationName(), context,
8755c0c51a9SNicolas Vasilache                              typeConverter) {}
8765c0c51a9SNicolas Vasilache 
8775c0c51a9SNicolas Vasilache   PatternMatchResult
878e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
8795c0c51a9SNicolas Vasilache                   ConversionPatternRewriter &rewriter) const override {
8805c0c51a9SNicolas Vasilache     auto loc = op->getLoc();
8815c0c51a9SNicolas Vasilache     vector::TypeCastOp castOp = cast<vector::TypeCastOp>(op);
8825c0c51a9SNicolas Vasilache     MemRefType sourceMemRefType =
8832bdf33ccSRiver Riddle         castOp.getOperand().getType().cast<MemRefType>();
8845c0c51a9SNicolas Vasilache     MemRefType targetMemRefType =
8852bdf33ccSRiver Riddle         castOp.getResult().getType().cast<MemRefType>();
8865c0c51a9SNicolas Vasilache 
8875c0c51a9SNicolas Vasilache     // Only static shape casts supported atm.
8885c0c51a9SNicolas Vasilache     if (!sourceMemRefType.hasStaticShape() ||
8895c0c51a9SNicolas Vasilache         !targetMemRefType.hasStaticShape())
8905c0c51a9SNicolas Vasilache       return matchFailure();
8915c0c51a9SNicolas Vasilache 
8925c0c51a9SNicolas Vasilache     auto llvmSourceDescriptorTy =
8932bdf33ccSRiver Riddle         operands[0].getType().dyn_cast<LLVM::LLVMType>();
8945c0c51a9SNicolas Vasilache     if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy())
8955c0c51a9SNicolas Vasilache       return matchFailure();
8965c0c51a9SNicolas Vasilache     MemRefDescriptor sourceMemRef(operands[0]);
8975c0c51a9SNicolas Vasilache 
8980f04384dSAlex Zinenko     auto llvmTargetDescriptorTy = typeConverter.convertType(targetMemRefType)
8995c0c51a9SNicolas Vasilache                                       .dyn_cast_or_null<LLVM::LLVMType>();
9005c0c51a9SNicolas Vasilache     if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy())
9015c0c51a9SNicolas Vasilache       return matchFailure();
9025c0c51a9SNicolas Vasilache 
9035c0c51a9SNicolas Vasilache     int64_t offset;
9045c0c51a9SNicolas Vasilache     SmallVector<int64_t, 4> strides;
9055c0c51a9SNicolas Vasilache     auto successStrides =
9065c0c51a9SNicolas Vasilache         getStridesAndOffset(sourceMemRefType, strides, offset);
9075c0c51a9SNicolas Vasilache     bool isContiguous = (strides.back() == 1);
9085c0c51a9SNicolas Vasilache     if (isContiguous) {
9095c0c51a9SNicolas Vasilache       auto sizes = sourceMemRefType.getShape();
9105c0c51a9SNicolas Vasilache       for (int index = 0, e = strides.size() - 2; index < e; ++index) {
9115c0c51a9SNicolas Vasilache         if (strides[index] != strides[index + 1] * sizes[index + 1]) {
9125c0c51a9SNicolas Vasilache           isContiguous = false;
9135c0c51a9SNicolas Vasilache           break;
9145c0c51a9SNicolas Vasilache         }
9155c0c51a9SNicolas Vasilache       }
9165c0c51a9SNicolas Vasilache     }
9175c0c51a9SNicolas Vasilache     // Only contiguous source tensors supported atm.
9185c0c51a9SNicolas Vasilache     if (failed(successStrides) || !isContiguous)
9195c0c51a9SNicolas Vasilache       return matchFailure();
9205c0c51a9SNicolas Vasilache 
9210f04384dSAlex Zinenko     auto int64Ty = LLVM::LLVMType::getInt64Ty(typeConverter.getDialect());
9225c0c51a9SNicolas Vasilache 
9235c0c51a9SNicolas Vasilache     // Create descriptor.
9245c0c51a9SNicolas Vasilache     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
9255c0c51a9SNicolas Vasilache     Type llvmTargetElementTy = desc.getElementType();
9265c0c51a9SNicolas Vasilache     // Set allocated ptr.
927e62a6956SRiver Riddle     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
9285c0c51a9SNicolas Vasilache     allocated =
9295c0c51a9SNicolas Vasilache         rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated);
9305c0c51a9SNicolas Vasilache     desc.setAllocatedPtr(rewriter, loc, allocated);
9315c0c51a9SNicolas Vasilache     // Set aligned ptr.
932e62a6956SRiver Riddle     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
9335c0c51a9SNicolas Vasilache     ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr);
9345c0c51a9SNicolas Vasilache     desc.setAlignedPtr(rewriter, loc, ptr);
9355c0c51a9SNicolas Vasilache     // Fill offset 0.
9365c0c51a9SNicolas Vasilache     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
9375c0c51a9SNicolas Vasilache     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
9385c0c51a9SNicolas Vasilache     desc.setOffset(rewriter, loc, zero);
9395c0c51a9SNicolas Vasilache 
9405c0c51a9SNicolas Vasilache     // Fill size and stride descriptors in memref.
9415c0c51a9SNicolas Vasilache     for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) {
9425c0c51a9SNicolas Vasilache       int64_t index = indexedSize.index();
9435c0c51a9SNicolas Vasilache       auto sizeAttr =
9445c0c51a9SNicolas Vasilache           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
9455c0c51a9SNicolas Vasilache       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
9465c0c51a9SNicolas Vasilache       desc.setSize(rewriter, loc, index, size);
9475c0c51a9SNicolas Vasilache       auto strideAttr =
9485c0c51a9SNicolas Vasilache           rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]);
9495c0c51a9SNicolas Vasilache       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
9505c0c51a9SNicolas Vasilache       desc.setStride(rewriter, loc, index, stride);
9515c0c51a9SNicolas Vasilache     }
9525c0c51a9SNicolas Vasilache 
9535c0c51a9SNicolas Vasilache     rewriter.replaceOp(op, {desc});
9545c0c51a9SNicolas Vasilache     return matchSuccess();
9555c0c51a9SNicolas Vasilache   }
9565c0c51a9SNicolas Vasilache };
9575c0c51a9SNicolas Vasilache 
958870c1fd4SAlex Zinenko class VectorPrintOpConversion : public ConvertToLLVMPattern {
959d9b500d3SAart Bik public:
960d9b500d3SAart Bik   explicit VectorPrintOpConversion(MLIRContext *context,
961d9b500d3SAart Bik                                    LLVMTypeConverter &typeConverter)
962870c1fd4SAlex Zinenko       : ConvertToLLVMPattern(vector::PrintOp::getOperationName(), context,
963d9b500d3SAart Bik                              typeConverter) {}
964d9b500d3SAart Bik 
965d9b500d3SAart Bik   // Proof-of-concept lowering implementation that relies on a small
966d9b500d3SAart Bik   // runtime support library, which only needs to provide a few
967d9b500d3SAart Bik   // printing methods (single value for all data types, opening/closing
968d9b500d3SAart Bik   // bracket, comma, newline). The lowering fully unrolls a vector
969d9b500d3SAart Bik   // in terms of these elementary printing operations. The advantage
970d9b500d3SAart Bik   // of this approach is that the library can remain unaware of all
971d9b500d3SAart Bik   // low-level implementation details of vectors while still supporting
972d9b500d3SAart Bik   // output of any shaped and dimensioned vector. Due to full unrolling,
973d9b500d3SAart Bik   // this approach is less suited for very large vectors though.
974d9b500d3SAart Bik   //
975d9b500d3SAart Bik   // TODO(ajcbik): rely solely on libc in future? something else?
976d9b500d3SAart Bik   //
977d9b500d3SAart Bik   PatternMatchResult
978e62a6956SRiver Riddle   matchAndRewrite(Operation *op, ArrayRef<Value> operands,
979d9b500d3SAart Bik                   ConversionPatternRewriter &rewriter) const override {
980d9b500d3SAart Bik     auto printOp = cast<vector::PrintOp>(op);
981d9b500d3SAart Bik     auto adaptor = vector::PrintOpOperandAdaptor(operands);
982d9b500d3SAart Bik     Type printType = printOp.getPrintType();
983d9b500d3SAart Bik 
9840f04384dSAlex Zinenko     if (typeConverter.convertType(printType) == nullptr)
985d9b500d3SAart Bik       return matchFailure();
986d9b500d3SAart Bik 
987d9b500d3SAart Bik     // Make sure element type has runtime support (currently just Float/Double).
988d9b500d3SAart Bik     VectorType vectorType = printType.dyn_cast<VectorType>();
989d9b500d3SAart Bik     Type eltType = vectorType ? vectorType.getElementType() : printType;
990d9b500d3SAart Bik     int64_t rank = vectorType ? vectorType.getRank() : 0;
991d9b500d3SAart Bik     Operation *printer;
992*35b68527SLei Zhang     if (eltType.isSignlessInteger(32))
993e52414b1Saartbik       printer = getPrintI32(op);
994*35b68527SLei Zhang     else if (eltType.isSignlessInteger(64))
995e52414b1Saartbik       printer = getPrintI64(op);
996e52414b1Saartbik     else if (eltType.isF32())
997d9b500d3SAart Bik       printer = getPrintFloat(op);
998d9b500d3SAart Bik     else if (eltType.isF64())
999d9b500d3SAart Bik       printer = getPrintDouble(op);
1000d9b500d3SAart Bik     else
1001d9b500d3SAart Bik       return matchFailure();
1002d9b500d3SAart Bik 
1003d9b500d3SAart Bik     // Unroll vector into elementary print calls.
1004d9b500d3SAart Bik     emitRanks(rewriter, op, adaptor.source(), vectorType, printer, rank);
1005d9b500d3SAart Bik     emitCall(rewriter, op->getLoc(), getPrintNewline(op));
1006d9b500d3SAart Bik     rewriter.eraseOp(op);
1007d9b500d3SAart Bik     return matchSuccess();
1008d9b500d3SAart Bik   }
1009d9b500d3SAart Bik 
1010d9b500d3SAart Bik private:
1011d9b500d3SAart Bik   void emitRanks(ConversionPatternRewriter &rewriter, Operation *op,
1012e62a6956SRiver Riddle                  Value value, VectorType vectorType, Operation *printer,
1013d9b500d3SAart Bik                  int64_t rank) const {
1014d9b500d3SAart Bik     Location loc = op->getLoc();
1015d9b500d3SAart Bik     if (rank == 0) {
1016d9b500d3SAart Bik       emitCall(rewriter, loc, printer, value);
1017d9b500d3SAart Bik       return;
1018d9b500d3SAart Bik     }
1019d9b500d3SAart Bik 
1020d9b500d3SAart Bik     emitCall(rewriter, loc, getPrintOpen(op));
1021d9b500d3SAart Bik     Operation *printComma = getPrintComma(op);
1022d9b500d3SAart Bik     int64_t dim = vectorType.getDimSize(0);
1023d9b500d3SAart Bik     for (int64_t d = 0; d < dim; ++d) {
1024d9b500d3SAart Bik       auto reducedType =
1025d9b500d3SAart Bik           rank > 1 ? reducedVectorTypeFront(vectorType) : nullptr;
10260f04384dSAlex Zinenko       auto llvmType = typeConverter.convertType(
1027d9b500d3SAart Bik           rank > 1 ? reducedType : vectorType.getElementType());
1028e62a6956SRiver Riddle       Value nestedVal =
10290f04384dSAlex Zinenko           extractOne(rewriter, typeConverter, loc, value, llvmType, rank, d);
1030d9b500d3SAart Bik       emitRanks(rewriter, op, nestedVal, reducedType, printer, rank - 1);
1031d9b500d3SAart Bik       if (d != dim - 1)
1032d9b500d3SAart Bik         emitCall(rewriter, loc, printComma);
1033d9b500d3SAart Bik     }
1034d9b500d3SAart Bik     emitCall(rewriter, loc, getPrintClose(op));
1035d9b500d3SAart Bik   }
1036d9b500d3SAart Bik 
1037d9b500d3SAart Bik   // Helper to emit a call.
1038d9b500d3SAart Bik   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
1039d9b500d3SAart Bik                        Operation *ref, ValueRange params = ValueRange()) {
1040d9b500d3SAart Bik     rewriter.create<LLVM::CallOp>(loc, ArrayRef<Type>{},
1041d9b500d3SAart Bik                                   rewriter.getSymbolRefAttr(ref), params);
1042d9b500d3SAart Bik   }
1043d9b500d3SAart Bik 
1044d9b500d3SAart Bik   // Helper for printer method declaration (first hit) and lookup.
1045d9b500d3SAart Bik   static Operation *getPrint(Operation *op, LLVM::LLVMDialect *dialect,
1046d9b500d3SAart Bik                              StringRef name, ArrayRef<LLVM::LLVMType> params) {
1047d9b500d3SAart Bik     auto module = op->getParentOfType<ModuleOp>();
1048d9b500d3SAart Bik     auto func = module.lookupSymbol<LLVM::LLVMFuncOp>(name);
1049d9b500d3SAart Bik     if (func)
1050d9b500d3SAart Bik       return func;
1051d9b500d3SAart Bik     OpBuilder moduleBuilder(module.getBodyRegion());
1052d9b500d3SAart Bik     return moduleBuilder.create<LLVM::LLVMFuncOp>(
1053d9b500d3SAart Bik         op->getLoc(), name,
1054d9b500d3SAart Bik         LLVM::LLVMType::getFunctionTy(LLVM::LLVMType::getVoidTy(dialect),
1055d9b500d3SAart Bik                                       params, /*isVarArg=*/false));
1056d9b500d3SAart Bik   }
1057d9b500d3SAart Bik 
1058d9b500d3SAart Bik   // Helpers for method names.
1059e52414b1Saartbik   Operation *getPrintI32(Operation *op) const {
10600f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1061e52414b1Saartbik     return getPrint(op, dialect, "print_i32",
1062e52414b1Saartbik                     LLVM::LLVMType::getInt32Ty(dialect));
1063e52414b1Saartbik   }
1064e52414b1Saartbik   Operation *getPrintI64(Operation *op) const {
10650f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1066e52414b1Saartbik     return getPrint(op, dialect, "print_i64",
1067e52414b1Saartbik                     LLVM::LLVMType::getInt64Ty(dialect));
1068e52414b1Saartbik   }
1069d9b500d3SAart Bik   Operation *getPrintFloat(Operation *op) const {
10700f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1071d9b500d3SAart Bik     return getPrint(op, dialect, "print_f32",
1072d9b500d3SAart Bik                     LLVM::LLVMType::getFloatTy(dialect));
1073d9b500d3SAart Bik   }
1074d9b500d3SAart Bik   Operation *getPrintDouble(Operation *op) const {
10750f04384dSAlex Zinenko     LLVM::LLVMDialect *dialect = typeConverter.getDialect();
1076d9b500d3SAart Bik     return getPrint(op, dialect, "print_f64",
1077d9b500d3SAart Bik                     LLVM::LLVMType::getDoubleTy(dialect));
1078d9b500d3SAart Bik   }
1079d9b500d3SAart Bik   Operation *getPrintOpen(Operation *op) const {
10800f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_open", {});
1081d9b500d3SAart Bik   }
1082d9b500d3SAart Bik   Operation *getPrintClose(Operation *op) const {
10830f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_close", {});
1084d9b500d3SAart Bik   }
1085d9b500d3SAart Bik   Operation *getPrintComma(Operation *op) const {
10860f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_comma", {});
1087d9b500d3SAart Bik   }
1088d9b500d3SAart Bik   Operation *getPrintNewline(Operation *op) const {
10890f04384dSAlex Zinenko     return getPrint(op, typeConverter.getDialect(), "print_newline", {});
1090d9b500d3SAart Bik   }
1091d9b500d3SAart Bik };
1092d9b500d3SAart Bik 
109365678d93SNicolas Vasilache /// Progressive lowering of StridedSliceOp to either:
109465678d93SNicolas Vasilache ///   1. extractelement + insertelement for the 1-D case
109565678d93SNicolas Vasilache ///   2. extract + optional strided_slice + insert for the n-D case.
10962d515e49SNicolas Vasilache class VectorStridedSliceOpConversion : public OpRewritePattern<StridedSliceOp> {
109765678d93SNicolas Vasilache public:
109865678d93SNicolas Vasilache   using OpRewritePattern<StridedSliceOp>::OpRewritePattern;
109965678d93SNicolas Vasilache 
110065678d93SNicolas Vasilache   PatternMatchResult matchAndRewrite(StridedSliceOp op,
110165678d93SNicolas Vasilache                                      PatternRewriter &rewriter) const override {
110265678d93SNicolas Vasilache     auto dstType = op.getResult().getType().cast<VectorType>();
110365678d93SNicolas Vasilache 
110465678d93SNicolas Vasilache     assert(!op.offsets().getValue().empty() && "Unexpected empty offsets");
110565678d93SNicolas Vasilache 
110665678d93SNicolas Vasilache     int64_t offset =
110765678d93SNicolas Vasilache         op.offsets().getValue().front().cast<IntegerAttr>().getInt();
110865678d93SNicolas Vasilache     int64_t size = op.sizes().getValue().front().cast<IntegerAttr>().getInt();
110965678d93SNicolas Vasilache     int64_t stride =
111065678d93SNicolas Vasilache         op.strides().getValue().front().cast<IntegerAttr>().getInt();
111165678d93SNicolas Vasilache 
111265678d93SNicolas Vasilache     auto loc = op.getLoc();
111365678d93SNicolas Vasilache     auto elemType = dstType.getElementType();
1114*35b68527SLei Zhang     assert(elemType.isSignlessIntOrIndexOrFloat());
111565678d93SNicolas Vasilache     Value zero = rewriter.create<ConstantOp>(loc, elemType,
111665678d93SNicolas Vasilache                                              rewriter.getZeroAttr(elemType));
111765678d93SNicolas Vasilache     Value res = rewriter.create<SplatOp>(loc, dstType, zero);
111865678d93SNicolas Vasilache     for (int64_t off = offset, e = offset + size * stride, idx = 0; off < e;
111965678d93SNicolas Vasilache          off += stride, ++idx) {
112065678d93SNicolas Vasilache       Value extracted = extractOne(rewriter, loc, op.vector(), off);
112165678d93SNicolas Vasilache       if (op.offsets().getValue().size() > 1) {
112265678d93SNicolas Vasilache         StridedSliceOp stridedSliceOp = rewriter.create<StridedSliceOp>(
112365678d93SNicolas Vasilache             loc, extracted, getI64SubArray(op.offsets(), /* dropFront=*/1),
112465678d93SNicolas Vasilache             getI64SubArray(op.sizes(), /* dropFront=*/1),
112565678d93SNicolas Vasilache             getI64SubArray(op.strides(), /* dropFront=*/1));
112665678d93SNicolas Vasilache         // Call matchAndRewrite recursively from within the pattern. This
112765678d93SNicolas Vasilache         // circumvents the current limitation that a given pattern cannot
112865678d93SNicolas Vasilache         // be called multiple times by the PatternRewrite infrastructure (to
112965678d93SNicolas Vasilache         // avoid infinite recursion, but in this case, infinite recursion
113065678d93SNicolas Vasilache         // cannot happen because the rank is strictly decreasing).
113165678d93SNicolas Vasilache         // TODO(rriddle, nicolasvasilache) Implement something like a hook for
113265678d93SNicolas Vasilache         // a potential function that must decrease and allow the same pattern
113365678d93SNicolas Vasilache         // multiple times.
113465678d93SNicolas Vasilache         auto success = matchAndRewrite(stridedSliceOp, rewriter);
113565678d93SNicolas Vasilache         (void)success;
113665678d93SNicolas Vasilache         assert(success && "Unexpected failure");
113765678d93SNicolas Vasilache         extracted = stridedSliceOp;
113865678d93SNicolas Vasilache       }
113965678d93SNicolas Vasilache       res = insertOne(rewriter, loc, extracted, res, idx);
114065678d93SNicolas Vasilache     }
114165678d93SNicolas Vasilache     rewriter.replaceOp(op, {res});
114265678d93SNicolas Vasilache     return matchSuccess();
114365678d93SNicolas Vasilache   }
114465678d93SNicolas Vasilache };
114565678d93SNicolas Vasilache 
1146df186507SBenjamin Kramer } // namespace
1147df186507SBenjamin Kramer 
11485c0c51a9SNicolas Vasilache /// Populate the given list with patterns that convert from Vector to LLVM.
11495c0c51a9SNicolas Vasilache void mlir::populateVectorToLLVMConversionPatterns(
11505c0c51a9SNicolas Vasilache     LLVMTypeConverter &converter, OwningRewritePatternList &patterns) {
115165678d93SNicolas Vasilache   MLIRContext *ctx = converter.getDialect()->getContext();
1152681f929fSNicolas Vasilache   patterns.insert<VectorFMAOpNDRewritePattern,
1153681f929fSNicolas Vasilache                   VectorInsertStridedSliceOpDifferentRankRewritePattern,
11542d515e49SNicolas Vasilache                   VectorInsertStridedSliceOpSameRankRewritePattern,
11552d515e49SNicolas Vasilache                   VectorStridedSliceOpConversion>(ctx);
1156e83b7b99Saartbik   patterns.insert<VectorBroadcastOpConversion, VectorReductionOpConversion,
1157b21c7999Saartbik                   VectorReductionV2OpConversion, VectorShuffleOpConversion,
1158b21c7999Saartbik                   VectorExtractElementOpConversion, VectorExtractOpConversion,
1159b21c7999Saartbik                   VectorFMAOp1DConversion, VectorInsertElementOpConversion,
1160b21c7999Saartbik                   VectorInsertOpConversion, VectorOuterProductOpConversion,
1161b21c7999Saartbik                   VectorTypeCastOpConversion, VectorPrintOpConversion>(
1162b21c7999Saartbik       ctx, converter);
11635c0c51a9SNicolas Vasilache }
11645c0c51a9SNicolas Vasilache 
11655c0c51a9SNicolas Vasilache namespace {
11665c0c51a9SNicolas Vasilache struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> {
11675c0c51a9SNicolas Vasilache   void runOnModule() override;
11685c0c51a9SNicolas Vasilache };
11695c0c51a9SNicolas Vasilache } // namespace
11705c0c51a9SNicolas Vasilache 
11715c0c51a9SNicolas Vasilache void LowerVectorToLLVMPass::runOnModule() {
1172b21c7999Saartbik   // Perform progressive lowering of operations on "slices" and
1173b21c7999Saartbik   // all contraction operations. Also applies folding and DCE.
1174459cf6e5Saartbik   {
11755c0c51a9SNicolas Vasilache     OwningRewritePatternList patterns;
1176459cf6e5Saartbik     populateVectorSlicesLoweringPatterns(patterns, &getContext());
1177b21c7999Saartbik     populateVectorContractLoweringPatterns(patterns, &getContext());
1178459cf6e5Saartbik     applyPatternsGreedily(getModule(), patterns);
1179459cf6e5Saartbik   }
1180459cf6e5Saartbik 
1181459cf6e5Saartbik   // Convert to the LLVM IR dialect.
11825c0c51a9SNicolas Vasilache   LLVMTypeConverter converter(&getContext());
1183459cf6e5Saartbik   OwningRewritePatternList patterns;
11845c0c51a9SNicolas Vasilache   populateVectorToLLVMConversionPatterns(converter, patterns);
11855c0c51a9SNicolas Vasilache   populateStdToLLVMConversionPatterns(converter, patterns);
11865c0c51a9SNicolas Vasilache 
11875c0c51a9SNicolas Vasilache   ConversionTarget target(getContext());
11885c0c51a9SNicolas Vasilache   target.addLegalDialect<LLVM::LLVMDialect>();
11895c0c51a9SNicolas Vasilache   target.addDynamicallyLegalOp<FuncOp>(
11905c0c51a9SNicolas Vasilache       [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); });
11915c0c51a9SNicolas Vasilache   if (failed(
11925c0c51a9SNicolas Vasilache           applyPartialConversion(getModule(), target, patterns, &converter))) {
11935c0c51a9SNicolas Vasilache     signalPassFailure();
11945c0c51a9SNicolas Vasilache   }
11955c0c51a9SNicolas Vasilache }
11965c0c51a9SNicolas Vasilache 
11975c0c51a9SNicolas Vasilache OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() {
11985c0c51a9SNicolas Vasilache   return new LowerVectorToLLVMPass();
11995c0c51a9SNicolas Vasilache }
12005c0c51a9SNicolas Vasilache 
12015c0c51a9SNicolas Vasilache static PassRegistration<LowerVectorToLLVMPass>
12025c0c51a9SNicolas Vasilache     pass("convert-vector-to-llvm",
12035c0c51a9SNicolas Vasilache          "Lower the operations from the vector dialect into the LLVM dialect");
1204