xref: /llvm-project/mlir/lib/Conversion/VectorToLLVM/ConvertVectorToLLVM.cpp (revision c1b8c6cf41df4a148e7a89c3a3c7e8049b0a47af)
1 //===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h"
10 
11 #include "mlir/Conversion/ArithCommon/AttrToLLVMConverter.h"
12 #include "mlir/Conversion/LLVMCommon/PrintCallHelper.h"
13 #include "mlir/Conversion/LLVMCommon/TypeConverter.h"
14 #include "mlir/Conversion/LLVMCommon/VectorPattern.h"
15 #include "mlir/Dialect/Arith/IR/Arith.h"
16 #include "mlir/Dialect/Arith/Utils/Utils.h"
17 #include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
18 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
19 #include "mlir/Dialect/MemRef/IR/MemRef.h"
20 #include "mlir/Dialect/Vector/IR/VectorOps.h"
21 #include "mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h"
22 #include "mlir/Dialect/Vector/Transforms/LoweringPatterns.h"
23 #include "mlir/Dialect/Vector/Transforms/VectorTransforms.h"
24 #include "mlir/IR/BuiltinAttributes.h"
25 #include "mlir/IR/BuiltinTypeInterfaces.h"
26 #include "mlir/IR/BuiltinTypes.h"
27 #include "mlir/IR/TypeUtilities.h"
28 #include "mlir/Target/LLVMIR/TypeToLLVM.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/Support/Casting.h"
32 #include <optional>
33 
34 using namespace mlir;
35 using namespace mlir::vector;
36 
37 // Helper to reduce vector type by *all* but one rank at back.
38 static VectorType reducedVectorTypeBack(VectorType tp) {
39   assert((tp.getRank() > 1) && "unlowerable vector type");
40   return VectorType::get(tp.getShape().take_back(), tp.getElementType(),
41                          tp.getScalableDims().take_back());
42 }
43 
44 // Helper that picks the proper sequence for inserting.
45 static Value insertOne(ConversionPatternRewriter &rewriter,
46                        const LLVMTypeConverter &typeConverter, Location loc,
47                        Value val1, Value val2, Type llvmType, int64_t rank,
48                        int64_t pos) {
49   assert(rank > 0 && "0-D vector corner case should have been handled already");
50   if (rank == 1) {
51     auto idxType = rewriter.getIndexType();
52     auto constant = rewriter.create<LLVM::ConstantOp>(
53         loc, typeConverter.convertType(idxType),
54         rewriter.getIntegerAttr(idxType, pos));
55     return rewriter.create<LLVM::InsertElementOp>(loc, llvmType, val1, val2,
56                                                   constant);
57   }
58   return rewriter.create<LLVM::InsertValueOp>(loc, val1, val2, pos);
59 }
60 
61 // Helper that picks the proper sequence for extracting.
62 static Value extractOne(ConversionPatternRewriter &rewriter,
63                         const LLVMTypeConverter &typeConverter, Location loc,
64                         Value val, Type llvmType, int64_t rank, int64_t pos) {
65   if (rank <= 1) {
66     auto idxType = rewriter.getIndexType();
67     auto constant = rewriter.create<LLVM::ConstantOp>(
68         loc, typeConverter.convertType(idxType),
69         rewriter.getIntegerAttr(idxType, pos));
70     return rewriter.create<LLVM::ExtractElementOp>(loc, llvmType, val,
71                                                    constant);
72   }
73   return rewriter.create<LLVM::ExtractValueOp>(loc, val, pos);
74 }
75 
76 // Helper that returns data layout alignment of a memref.
77 LogicalResult getMemRefAlignment(const LLVMTypeConverter &typeConverter,
78                                  MemRefType memrefType, unsigned &align) {
79   Type elementTy = typeConverter.convertType(memrefType.getElementType());
80   if (!elementTy)
81     return failure();
82 
83   // TODO: this should use the MLIR data layout when it becomes available and
84   // stop depending on translation.
85   llvm::LLVMContext llvmContext;
86   align = LLVM::TypeToLLVMIRTranslator(llvmContext)
87               .getPreferredAlignment(elementTy, typeConverter.getDataLayout());
88   return success();
89 }
90 
91 // Check if the last stride is non-unit and has a valid memory space.
92 static LogicalResult isMemRefTypeSupported(MemRefType memRefType,
93                                            const LLVMTypeConverter &converter) {
94   if (!isLastMemrefDimUnitStride(memRefType))
95     return failure();
96   if (failed(converter.getMemRefAddressSpace(memRefType)))
97     return failure();
98   return success();
99 }
100 
101 // Add an index vector component to a base pointer.
102 static Value getIndexedPtrs(ConversionPatternRewriter &rewriter, Location loc,
103                             const LLVMTypeConverter &typeConverter,
104                             MemRefType memRefType, Value llvmMemref, Value base,
105                             Value index, uint64_t vLen) {
106   assert(succeeded(isMemRefTypeSupported(memRefType, typeConverter)) &&
107          "unsupported memref type");
108   auto pType = MemRefDescriptor(llvmMemref).getElementPtrType();
109   auto ptrsType = LLVM::getFixedVectorType(pType, vLen);
110   return rewriter.create<LLVM::GEPOp>(
111       loc, ptrsType, typeConverter.convertType(memRefType.getElementType()),
112       base, index);
113 }
114 
115 /// Convert `foldResult` into a Value. Integer attribute is converted to
116 /// an LLVM constant op.
117 static Value getAsLLVMValue(OpBuilder &builder, Location loc,
118                             OpFoldResult foldResult) {
119   if (auto attr = foldResult.dyn_cast<Attribute>()) {
120     auto intAttr = cast<IntegerAttr>(attr);
121     return builder.create<LLVM::ConstantOp>(loc, intAttr).getResult();
122   }
123 
124   return foldResult.get<Value>();
125 }
126 
127 namespace {
128 
129 /// Trivial Vector to LLVM conversions
130 using VectorScaleOpConversion =
131     OneToOneConvertToLLVMPattern<vector::VectorScaleOp, LLVM::vscale>;
132 
133 /// Conversion pattern for a vector.bitcast.
134 class VectorBitCastOpConversion
135     : public ConvertOpToLLVMPattern<vector::BitCastOp> {
136 public:
137   using ConvertOpToLLVMPattern<vector::BitCastOp>::ConvertOpToLLVMPattern;
138 
139   LogicalResult
140   matchAndRewrite(vector::BitCastOp bitCastOp, OpAdaptor adaptor,
141                   ConversionPatternRewriter &rewriter) const override {
142     // Only 0-D and 1-D vectors can be lowered to LLVM.
143     VectorType resultTy = bitCastOp.getResultVectorType();
144     if (resultTy.getRank() > 1)
145       return failure();
146     Type newResultTy = typeConverter->convertType(resultTy);
147     rewriter.replaceOpWithNewOp<LLVM::BitcastOp>(bitCastOp, newResultTy,
148                                                  adaptor.getOperands()[0]);
149     return success();
150   }
151 };
152 
153 /// Conversion pattern for a vector.matrix_multiply.
154 /// This is lowered directly to the proper llvm.intr.matrix.multiply.
155 class VectorMatmulOpConversion
156     : public ConvertOpToLLVMPattern<vector::MatmulOp> {
157 public:
158   using ConvertOpToLLVMPattern<vector::MatmulOp>::ConvertOpToLLVMPattern;
159 
160   LogicalResult
161   matchAndRewrite(vector::MatmulOp matmulOp, OpAdaptor adaptor,
162                   ConversionPatternRewriter &rewriter) const override {
163     rewriter.replaceOpWithNewOp<LLVM::MatrixMultiplyOp>(
164         matmulOp, typeConverter->convertType(matmulOp.getRes().getType()),
165         adaptor.getLhs(), adaptor.getRhs(), matmulOp.getLhsRows(),
166         matmulOp.getLhsColumns(), matmulOp.getRhsColumns());
167     return success();
168   }
169 };
170 
171 /// Conversion pattern for a vector.flat_transpose.
172 /// This is lowered directly to the proper llvm.intr.matrix.transpose.
173 class VectorFlatTransposeOpConversion
174     : public ConvertOpToLLVMPattern<vector::FlatTransposeOp> {
175 public:
176   using ConvertOpToLLVMPattern<vector::FlatTransposeOp>::ConvertOpToLLVMPattern;
177 
178   LogicalResult
179   matchAndRewrite(vector::FlatTransposeOp transOp, OpAdaptor adaptor,
180                   ConversionPatternRewriter &rewriter) const override {
181     rewriter.replaceOpWithNewOp<LLVM::MatrixTransposeOp>(
182         transOp, typeConverter->convertType(transOp.getRes().getType()),
183         adaptor.getMatrix(), transOp.getRows(), transOp.getColumns());
184     return success();
185   }
186 };
187 
188 /// Overloaded utility that replaces a vector.load, vector.store,
189 /// vector.maskedload and vector.maskedstore with their respective LLVM
190 /// couterparts.
191 static void replaceLoadOrStoreOp(vector::LoadOp loadOp,
192                                  vector::LoadOpAdaptor adaptor,
193                                  VectorType vectorTy, Value ptr, unsigned align,
194                                  ConversionPatternRewriter &rewriter) {
195   rewriter.replaceOpWithNewOp<LLVM::LoadOp>(loadOp, vectorTy, ptr, align,
196                                             /*volatile_=*/false,
197                                             loadOp.getNontemporal());
198 }
199 
200 static void replaceLoadOrStoreOp(vector::MaskedLoadOp loadOp,
201                                  vector::MaskedLoadOpAdaptor adaptor,
202                                  VectorType vectorTy, Value ptr, unsigned align,
203                                  ConversionPatternRewriter &rewriter) {
204   rewriter.replaceOpWithNewOp<LLVM::MaskedLoadOp>(
205       loadOp, vectorTy, ptr, adaptor.getMask(), adaptor.getPassThru(), align);
206 }
207 
208 static void replaceLoadOrStoreOp(vector::StoreOp storeOp,
209                                  vector::StoreOpAdaptor adaptor,
210                                  VectorType vectorTy, Value ptr, unsigned align,
211                                  ConversionPatternRewriter &rewriter) {
212   rewriter.replaceOpWithNewOp<LLVM::StoreOp>(storeOp, adaptor.getValueToStore(),
213                                              ptr, align, /*volatile_=*/false,
214                                              storeOp.getNontemporal());
215 }
216 
217 static void replaceLoadOrStoreOp(vector::MaskedStoreOp storeOp,
218                                  vector::MaskedStoreOpAdaptor adaptor,
219                                  VectorType vectorTy, Value ptr, unsigned align,
220                                  ConversionPatternRewriter &rewriter) {
221   rewriter.replaceOpWithNewOp<LLVM::MaskedStoreOp>(
222       storeOp, adaptor.getValueToStore(), ptr, adaptor.getMask(), align);
223 }
224 
225 /// Conversion pattern for a vector.load, vector.store, vector.maskedload, and
226 /// vector.maskedstore.
227 template <class LoadOrStoreOp>
228 class VectorLoadStoreConversion : public ConvertOpToLLVMPattern<LoadOrStoreOp> {
229 public:
230   using ConvertOpToLLVMPattern<LoadOrStoreOp>::ConvertOpToLLVMPattern;
231 
232   LogicalResult
233   matchAndRewrite(LoadOrStoreOp loadOrStoreOp,
234                   typename LoadOrStoreOp::Adaptor adaptor,
235                   ConversionPatternRewriter &rewriter) const override {
236     // Only 1-D vectors can be lowered to LLVM.
237     VectorType vectorTy = loadOrStoreOp.getVectorType();
238     if (vectorTy.getRank() > 1)
239       return failure();
240 
241     auto loc = loadOrStoreOp->getLoc();
242     MemRefType memRefTy = loadOrStoreOp.getMemRefType();
243 
244     // Resolve alignment.
245     unsigned align;
246     if (failed(getMemRefAlignment(*this->getTypeConverter(), memRefTy, align)))
247       return failure();
248 
249     // Resolve address.
250     auto vtype = cast<VectorType>(
251         this->typeConverter->convertType(loadOrStoreOp.getVectorType()));
252     Value dataPtr = this->getStridedElementPtr(loc, memRefTy, adaptor.getBase(),
253                                                adaptor.getIndices(), rewriter);
254     replaceLoadOrStoreOp(loadOrStoreOp, adaptor, vtype, dataPtr, align,
255                          rewriter);
256     return success();
257   }
258 };
259 
260 /// Conversion pattern for a vector.gather.
261 class VectorGatherOpConversion
262     : public ConvertOpToLLVMPattern<vector::GatherOp> {
263 public:
264   using ConvertOpToLLVMPattern<vector::GatherOp>::ConvertOpToLLVMPattern;
265 
266   LogicalResult
267   matchAndRewrite(vector::GatherOp gather, OpAdaptor adaptor,
268                   ConversionPatternRewriter &rewriter) const override {
269     MemRefType memRefType = dyn_cast<MemRefType>(gather.getBaseType());
270     assert(memRefType && "The base should be bufferized");
271 
272     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
273       return failure();
274 
275     auto loc = gather->getLoc();
276 
277     // Resolve alignment.
278     unsigned align;
279     if (failed(getMemRefAlignment(*getTypeConverter(), memRefType, align)))
280       return failure();
281 
282     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
283                                      adaptor.getIndices(), rewriter);
284     Value base = adaptor.getBase();
285 
286     auto llvmNDVectorTy = adaptor.getIndexVec().getType();
287     // Handle the simple case of 1-D vector.
288     if (!isa<LLVM::LLVMArrayType>(llvmNDVectorTy)) {
289       auto vType = gather.getVectorType();
290       // Resolve address.
291       Value ptrs = getIndexedPtrs(rewriter, loc, *this->getTypeConverter(),
292                                   memRefType, base, ptr, adaptor.getIndexVec(),
293                                   /*vLen=*/vType.getDimSize(0));
294       // Replace with the gather intrinsic.
295       rewriter.replaceOpWithNewOp<LLVM::masked_gather>(
296           gather, typeConverter->convertType(vType), ptrs, adaptor.getMask(),
297           adaptor.getPassThru(), rewriter.getI32IntegerAttr(align));
298       return success();
299     }
300 
301     const LLVMTypeConverter &typeConverter = *this->getTypeConverter();
302     auto callback = [align, memRefType, base, ptr, loc, &rewriter,
303                      &typeConverter](Type llvm1DVectorTy,
304                                      ValueRange vectorOperands) {
305       // Resolve address.
306       Value ptrs = getIndexedPtrs(
307           rewriter, loc, typeConverter, memRefType, base, ptr,
308           /*index=*/vectorOperands[0],
309           LLVM::getVectorNumElements(llvm1DVectorTy).getFixedValue());
310       // Create the gather intrinsic.
311       return rewriter.create<LLVM::masked_gather>(
312           loc, llvm1DVectorTy, ptrs, /*mask=*/vectorOperands[1],
313           /*passThru=*/vectorOperands[2], rewriter.getI32IntegerAttr(align));
314     };
315     SmallVector<Value> vectorOperands = {
316         adaptor.getIndexVec(), adaptor.getMask(), adaptor.getPassThru()};
317     return LLVM::detail::handleMultidimensionalVectors(
318         gather, vectorOperands, *getTypeConverter(), callback, rewriter);
319   }
320 };
321 
322 /// Conversion pattern for a vector.scatter.
323 class VectorScatterOpConversion
324     : public ConvertOpToLLVMPattern<vector::ScatterOp> {
325 public:
326   using ConvertOpToLLVMPattern<vector::ScatterOp>::ConvertOpToLLVMPattern;
327 
328   LogicalResult
329   matchAndRewrite(vector::ScatterOp scatter, OpAdaptor adaptor,
330                   ConversionPatternRewriter &rewriter) const override {
331     auto loc = scatter->getLoc();
332     MemRefType memRefType = scatter.getMemRefType();
333 
334     if (failed(isMemRefTypeSupported(memRefType, *this->getTypeConverter())))
335       return failure();
336 
337     // Resolve alignment.
338     unsigned align;
339     if (failed(getMemRefAlignment(*getTypeConverter(), memRefType, align)))
340       return failure();
341 
342     // Resolve address.
343     VectorType vType = scatter.getVectorType();
344     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
345                                      adaptor.getIndices(), rewriter);
346     Value ptrs = getIndexedPtrs(
347         rewriter, loc, *this->getTypeConverter(), memRefType, adaptor.getBase(),
348         ptr, adaptor.getIndexVec(), /*vLen=*/vType.getDimSize(0));
349 
350     // Replace with the scatter intrinsic.
351     rewriter.replaceOpWithNewOp<LLVM::masked_scatter>(
352         scatter, adaptor.getValueToStore(), ptrs, adaptor.getMask(),
353         rewriter.getI32IntegerAttr(align));
354     return success();
355   }
356 };
357 
358 /// Conversion pattern for a vector.expandload.
359 class VectorExpandLoadOpConversion
360     : public ConvertOpToLLVMPattern<vector::ExpandLoadOp> {
361 public:
362   using ConvertOpToLLVMPattern<vector::ExpandLoadOp>::ConvertOpToLLVMPattern;
363 
364   LogicalResult
365   matchAndRewrite(vector::ExpandLoadOp expand, OpAdaptor adaptor,
366                   ConversionPatternRewriter &rewriter) const override {
367     auto loc = expand->getLoc();
368     MemRefType memRefType = expand.getMemRefType();
369 
370     // Resolve address.
371     auto vtype = typeConverter->convertType(expand.getVectorType());
372     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
373                                      adaptor.getIndices(), rewriter);
374 
375     rewriter.replaceOpWithNewOp<LLVM::masked_expandload>(
376         expand, vtype, ptr, adaptor.getMask(), adaptor.getPassThru());
377     return success();
378   }
379 };
380 
381 /// Conversion pattern for a vector.compressstore.
382 class VectorCompressStoreOpConversion
383     : public ConvertOpToLLVMPattern<vector::CompressStoreOp> {
384 public:
385   using ConvertOpToLLVMPattern<vector::CompressStoreOp>::ConvertOpToLLVMPattern;
386 
387   LogicalResult
388   matchAndRewrite(vector::CompressStoreOp compress, OpAdaptor adaptor,
389                   ConversionPatternRewriter &rewriter) const override {
390     auto loc = compress->getLoc();
391     MemRefType memRefType = compress.getMemRefType();
392 
393     // Resolve address.
394     Value ptr = getStridedElementPtr(loc, memRefType, adaptor.getBase(),
395                                      adaptor.getIndices(), rewriter);
396 
397     rewriter.replaceOpWithNewOp<LLVM::masked_compressstore>(
398         compress, adaptor.getValueToStore(), ptr, adaptor.getMask());
399     return success();
400   }
401 };
402 
403 /// Reduction neutral classes for overloading.
404 class ReductionNeutralZero {};
405 class ReductionNeutralIntOne {};
406 class ReductionNeutralFPOne {};
407 class ReductionNeutralAllOnes {};
408 class ReductionNeutralSIntMin {};
409 class ReductionNeutralUIntMin {};
410 class ReductionNeutralSIntMax {};
411 class ReductionNeutralUIntMax {};
412 class ReductionNeutralFPMin {};
413 class ReductionNeutralFPMax {};
414 
415 /// Create the reduction neutral zero value.
416 static Value createReductionNeutralValue(ReductionNeutralZero neutral,
417                                          ConversionPatternRewriter &rewriter,
418                                          Location loc, Type llvmType) {
419   return rewriter.create<LLVM::ConstantOp>(loc, llvmType,
420                                            rewriter.getZeroAttr(llvmType));
421 }
422 
423 /// Create the reduction neutral integer one value.
424 static Value createReductionNeutralValue(ReductionNeutralIntOne neutral,
425                                          ConversionPatternRewriter &rewriter,
426                                          Location loc, Type llvmType) {
427   return rewriter.create<LLVM::ConstantOp>(
428       loc, llvmType, rewriter.getIntegerAttr(llvmType, 1));
429 }
430 
431 /// Create the reduction neutral fp one value.
432 static Value createReductionNeutralValue(ReductionNeutralFPOne neutral,
433                                          ConversionPatternRewriter &rewriter,
434                                          Location loc, Type llvmType) {
435   return rewriter.create<LLVM::ConstantOp>(
436       loc, llvmType, rewriter.getFloatAttr(llvmType, 1.0));
437 }
438 
439 /// Create the reduction neutral all-ones value.
440 static Value createReductionNeutralValue(ReductionNeutralAllOnes neutral,
441                                          ConversionPatternRewriter &rewriter,
442                                          Location loc, Type llvmType) {
443   return rewriter.create<LLVM::ConstantOp>(
444       loc, llvmType,
445       rewriter.getIntegerAttr(
446           llvmType, llvm::APInt::getAllOnes(llvmType.getIntOrFloatBitWidth())));
447 }
448 
449 /// Create the reduction neutral signed int minimum value.
450 static Value createReductionNeutralValue(ReductionNeutralSIntMin neutral,
451                                          ConversionPatternRewriter &rewriter,
452                                          Location loc, Type llvmType) {
453   return rewriter.create<LLVM::ConstantOp>(
454       loc, llvmType,
455       rewriter.getIntegerAttr(llvmType, llvm::APInt::getSignedMinValue(
456                                             llvmType.getIntOrFloatBitWidth())));
457 }
458 
459 /// Create the reduction neutral unsigned int minimum value.
460 static Value createReductionNeutralValue(ReductionNeutralUIntMin neutral,
461                                          ConversionPatternRewriter &rewriter,
462                                          Location loc, Type llvmType) {
463   return rewriter.create<LLVM::ConstantOp>(
464       loc, llvmType,
465       rewriter.getIntegerAttr(llvmType, llvm::APInt::getMinValue(
466                                             llvmType.getIntOrFloatBitWidth())));
467 }
468 
469 /// Create the reduction neutral signed int maximum value.
470 static Value createReductionNeutralValue(ReductionNeutralSIntMax neutral,
471                                          ConversionPatternRewriter &rewriter,
472                                          Location loc, Type llvmType) {
473   return rewriter.create<LLVM::ConstantOp>(
474       loc, llvmType,
475       rewriter.getIntegerAttr(llvmType, llvm::APInt::getSignedMaxValue(
476                                             llvmType.getIntOrFloatBitWidth())));
477 }
478 
479 /// Create the reduction neutral unsigned int maximum value.
480 static Value createReductionNeutralValue(ReductionNeutralUIntMax neutral,
481                                          ConversionPatternRewriter &rewriter,
482                                          Location loc, Type llvmType) {
483   return rewriter.create<LLVM::ConstantOp>(
484       loc, llvmType,
485       rewriter.getIntegerAttr(llvmType, llvm::APInt::getMaxValue(
486                                             llvmType.getIntOrFloatBitWidth())));
487 }
488 
489 /// Create the reduction neutral fp minimum value.
490 static Value createReductionNeutralValue(ReductionNeutralFPMin neutral,
491                                          ConversionPatternRewriter &rewriter,
492                                          Location loc, Type llvmType) {
493   auto floatType = cast<FloatType>(llvmType);
494   return rewriter.create<LLVM::ConstantOp>(
495       loc, llvmType,
496       rewriter.getFloatAttr(
497           llvmType, llvm::APFloat::getQNaN(floatType.getFloatSemantics(),
498                                            /*Negative=*/false)));
499 }
500 
501 /// Create the reduction neutral fp maximum value.
502 static Value createReductionNeutralValue(ReductionNeutralFPMax neutral,
503                                          ConversionPatternRewriter &rewriter,
504                                          Location loc, Type llvmType) {
505   auto floatType = cast<FloatType>(llvmType);
506   return rewriter.create<LLVM::ConstantOp>(
507       loc, llvmType,
508       rewriter.getFloatAttr(
509           llvmType, llvm::APFloat::getQNaN(floatType.getFloatSemantics(),
510                                            /*Negative=*/true)));
511 }
512 
513 /// Returns `accumulator` if it has a valid value. Otherwise, creates and
514 /// returns a new accumulator value using `ReductionNeutral`.
515 template <class ReductionNeutral>
516 static Value getOrCreateAccumulator(ConversionPatternRewriter &rewriter,
517                                     Location loc, Type llvmType,
518                                     Value accumulator) {
519   if (accumulator)
520     return accumulator;
521 
522   return createReductionNeutralValue(ReductionNeutral(), rewriter, loc,
523                                      llvmType);
524 }
525 
526 /// Creates a constant value with the 1-D vector shape provided in `llvmType`.
527 /// This is used as effective vector length by some intrinsics supporting
528 /// dynamic vector lengths at runtime.
529 static Value createVectorLengthValue(ConversionPatternRewriter &rewriter,
530                                      Location loc, Type llvmType) {
531   VectorType vType = cast<VectorType>(llvmType);
532   auto vShape = vType.getShape();
533   assert(vShape.size() == 1 && "Unexpected multi-dim vector type");
534 
535   return rewriter.create<LLVM::ConstantOp>(
536       loc, rewriter.getI32Type(),
537       rewriter.getIntegerAttr(rewriter.getI32Type(), vShape[0]));
538 }
539 
540 /// Helper method to lower a `vector.reduction` op that performs an arithmetic
541 /// operation like add,mul, etc.. `VectorOp` is the LLVM vector intrinsic to use
542 /// and `ScalarOp` is the scalar operation used to add the accumulation value if
543 /// non-null.
544 template <class LLVMRedIntrinOp, class ScalarOp>
545 static Value createIntegerReductionArithmeticOpLowering(
546     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
547     Value vectorOperand, Value accumulator) {
548 
549   Value result = rewriter.create<LLVMRedIntrinOp>(loc, llvmType, vectorOperand);
550 
551   if (accumulator)
552     result = rewriter.create<ScalarOp>(loc, accumulator, result);
553   return result;
554 }
555 
556 /// Helper method to lower a `vector.reduction` operation that performs
557 /// a comparison operation like `min`/`max`. `VectorOp` is the LLVM vector
558 /// intrinsic to use and `predicate` is the predicate to use to compare+combine
559 /// the accumulator value if non-null.
560 template <class LLVMRedIntrinOp>
561 static Value createIntegerReductionComparisonOpLowering(
562     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
563     Value vectorOperand, Value accumulator, LLVM::ICmpPredicate predicate) {
564   Value result = rewriter.create<LLVMRedIntrinOp>(loc, llvmType, vectorOperand);
565   if (accumulator) {
566     Value cmp =
567         rewriter.create<LLVM::ICmpOp>(loc, predicate, accumulator, result);
568     result = rewriter.create<LLVM::SelectOp>(loc, cmp, accumulator, result);
569   }
570   return result;
571 }
572 
573 namespace {
574 template <typename Source>
575 struct VectorToScalarMapper;
576 template <>
577 struct VectorToScalarMapper<LLVM::vector_reduce_fmaximum> {
578   using Type = LLVM::MaximumOp;
579 };
580 template <>
581 struct VectorToScalarMapper<LLVM::vector_reduce_fminimum> {
582   using Type = LLVM::MinimumOp;
583 };
584 template <>
585 struct VectorToScalarMapper<LLVM::vector_reduce_fmax> {
586   using Type = LLVM::MaxNumOp;
587 };
588 template <>
589 struct VectorToScalarMapper<LLVM::vector_reduce_fmin> {
590   using Type = LLVM::MinNumOp;
591 };
592 } // namespace
593 
594 template <class LLVMRedIntrinOp>
595 static Value createFPReductionComparisonOpLowering(
596     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
597     Value vectorOperand, Value accumulator, LLVM::FastmathFlagsAttr fmf) {
598   Value result =
599       rewriter.create<LLVMRedIntrinOp>(loc, llvmType, vectorOperand, fmf);
600 
601   if (accumulator) {
602     result =
603         rewriter.create<typename VectorToScalarMapper<LLVMRedIntrinOp>::Type>(
604             loc, result, accumulator);
605   }
606 
607   return result;
608 }
609 
610 /// Reduction neutral classes for overloading
611 class MaskNeutralFMaximum {};
612 class MaskNeutralFMinimum {};
613 
614 /// Get the mask neutral floating point maximum value
615 static llvm::APFloat
616 getMaskNeutralValue(MaskNeutralFMaximum,
617                     const llvm::fltSemantics &floatSemantics) {
618   return llvm::APFloat::getSmallest(floatSemantics, /*Negative=*/true);
619 }
620 /// Get the mask neutral floating point minimum value
621 static llvm::APFloat
622 getMaskNeutralValue(MaskNeutralFMinimum,
623                     const llvm::fltSemantics &floatSemantics) {
624   return llvm::APFloat::getLargest(floatSemantics, /*Negative=*/false);
625 }
626 
627 /// Create the mask neutral floating point MLIR vector constant
628 template <typename MaskNeutral>
629 static Value createMaskNeutralValue(ConversionPatternRewriter &rewriter,
630                                     Location loc, Type llvmType,
631                                     Type vectorType) {
632   const auto &floatSemantics = cast<FloatType>(llvmType).getFloatSemantics();
633   auto value = getMaskNeutralValue(MaskNeutral{}, floatSemantics);
634   auto denseValue =
635       DenseElementsAttr::get(vectorType.cast<ShapedType>(), value);
636   return rewriter.create<LLVM::ConstantOp>(loc, vectorType, denseValue);
637 }
638 
639 /// Lowers masked `fmaximum` and `fminimum` reductions using the non-masked
640 /// intrinsics. It is a workaround to overcome the lack of masked intrinsics for
641 /// `fmaximum`/`fminimum`.
642 /// More information: https://github.com/llvm/llvm-project/issues/64940
643 template <class LLVMRedIntrinOp, class MaskNeutral>
644 static Value
645 lowerMaskedReductionWithRegular(ConversionPatternRewriter &rewriter,
646                                 Location loc, Type llvmType,
647                                 Value vectorOperand, Value accumulator,
648                                 Value mask, LLVM::FastmathFlagsAttr fmf) {
649   const Value vectorMaskNeutral = createMaskNeutralValue<MaskNeutral>(
650       rewriter, loc, llvmType, vectorOperand.getType());
651   const Value selectedVectorByMask = rewriter.create<LLVM::SelectOp>(
652       loc, mask, vectorOperand, vectorMaskNeutral);
653   return createFPReductionComparisonOpLowering<LLVMRedIntrinOp>(
654       rewriter, loc, llvmType, selectedVectorByMask, accumulator, fmf);
655 }
656 
657 template <class LLVMRedIntrinOp, class ReductionNeutral>
658 static Value
659 lowerReductionWithStartValue(ConversionPatternRewriter &rewriter, Location loc,
660                              Type llvmType, Value vectorOperand,
661                              Value accumulator, LLVM::FastmathFlagsAttr fmf) {
662   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
663                                                          llvmType, accumulator);
664   return rewriter.create<LLVMRedIntrinOp>(loc, llvmType,
665                                           /*startValue=*/accumulator,
666                                           vectorOperand, fmf);
667 }
668 
669 /// Overloaded methods to lower a *predicated* reduction to an llvm instrinsic
670 /// that requires a start value. This start value format spans across fp
671 /// reductions without mask and all the masked reduction intrinsics.
672 template <class LLVMVPRedIntrinOp, class ReductionNeutral>
673 static Value
674 lowerPredicatedReductionWithStartValue(ConversionPatternRewriter &rewriter,
675                                        Location loc, Type llvmType,
676                                        Value vectorOperand, Value accumulator) {
677   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
678                                                          llvmType, accumulator);
679   return rewriter.create<LLVMVPRedIntrinOp>(loc, llvmType,
680                                             /*startValue=*/accumulator,
681                                             vectorOperand);
682 }
683 
684 template <class LLVMVPRedIntrinOp, class ReductionNeutral>
685 static Value lowerPredicatedReductionWithStartValue(
686     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
687     Value vectorOperand, Value accumulator, Value mask) {
688   accumulator = getOrCreateAccumulator<ReductionNeutral>(rewriter, loc,
689                                                          llvmType, accumulator);
690   Value vectorLength =
691       createVectorLengthValue(rewriter, loc, vectorOperand.getType());
692   return rewriter.create<LLVMVPRedIntrinOp>(loc, llvmType,
693                                             /*startValue=*/accumulator,
694                                             vectorOperand, mask, vectorLength);
695 }
696 
697 template <class LLVMIntVPRedIntrinOp, class IntReductionNeutral,
698           class LLVMFPVPRedIntrinOp, class FPReductionNeutral>
699 static Value lowerPredicatedReductionWithStartValue(
700     ConversionPatternRewriter &rewriter, Location loc, Type llvmType,
701     Value vectorOperand, Value accumulator, Value mask) {
702   if (llvmType.isIntOrIndex())
703     return lowerPredicatedReductionWithStartValue<LLVMIntVPRedIntrinOp,
704                                                   IntReductionNeutral>(
705         rewriter, loc, llvmType, vectorOperand, accumulator, mask);
706 
707   // FP dispatch.
708   return lowerPredicatedReductionWithStartValue<LLVMFPVPRedIntrinOp,
709                                                 FPReductionNeutral>(
710       rewriter, loc, llvmType, vectorOperand, accumulator, mask);
711 }
712 
713 /// Conversion pattern for all vector reductions.
714 class VectorReductionOpConversion
715     : public ConvertOpToLLVMPattern<vector::ReductionOp> {
716 public:
717   explicit VectorReductionOpConversion(const LLVMTypeConverter &typeConv,
718                                        bool reassociateFPRed)
719       : ConvertOpToLLVMPattern<vector::ReductionOp>(typeConv),
720         reassociateFPReductions(reassociateFPRed) {}
721 
722   LogicalResult
723   matchAndRewrite(vector::ReductionOp reductionOp, OpAdaptor adaptor,
724                   ConversionPatternRewriter &rewriter) const override {
725     auto kind = reductionOp.getKind();
726     Type eltType = reductionOp.getDest().getType();
727     Type llvmType = typeConverter->convertType(eltType);
728     Value operand = adaptor.getVector();
729     Value acc = adaptor.getAcc();
730     Location loc = reductionOp.getLoc();
731 
732     if (eltType.isIntOrIndex()) {
733       // Integer reductions: add/mul/min/max/and/or/xor.
734       Value result;
735       switch (kind) {
736       case vector::CombiningKind::ADD:
737         result =
738             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_add,
739                                                        LLVM::AddOp>(
740                 rewriter, loc, llvmType, operand, acc);
741         break;
742       case vector::CombiningKind::MUL:
743         result =
744             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_mul,
745                                                        LLVM::MulOp>(
746                 rewriter, loc, llvmType, operand, acc);
747         break;
748       case vector::CombiningKind::MINUI:
749         result = createIntegerReductionComparisonOpLowering<
750             LLVM::vector_reduce_umin>(rewriter, loc, llvmType, operand, acc,
751                                       LLVM::ICmpPredicate::ule);
752         break;
753       case vector::CombiningKind::MINSI:
754         result = createIntegerReductionComparisonOpLowering<
755             LLVM::vector_reduce_smin>(rewriter, loc, llvmType, operand, acc,
756                                       LLVM::ICmpPredicate::sle);
757         break;
758       case vector::CombiningKind::MAXUI:
759         result = createIntegerReductionComparisonOpLowering<
760             LLVM::vector_reduce_umax>(rewriter, loc, llvmType, operand, acc,
761                                       LLVM::ICmpPredicate::uge);
762         break;
763       case vector::CombiningKind::MAXSI:
764         result = createIntegerReductionComparisonOpLowering<
765             LLVM::vector_reduce_smax>(rewriter, loc, llvmType, operand, acc,
766                                       LLVM::ICmpPredicate::sge);
767         break;
768       case vector::CombiningKind::AND:
769         result =
770             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_and,
771                                                        LLVM::AndOp>(
772                 rewriter, loc, llvmType, operand, acc);
773         break;
774       case vector::CombiningKind::OR:
775         result =
776             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_or,
777                                                        LLVM::OrOp>(
778                 rewriter, loc, llvmType, operand, acc);
779         break;
780       case vector::CombiningKind::XOR:
781         result =
782             createIntegerReductionArithmeticOpLowering<LLVM::vector_reduce_xor,
783                                                        LLVM::XOrOp>(
784                 rewriter, loc, llvmType, operand, acc);
785         break;
786       default:
787         return failure();
788       }
789       rewriter.replaceOp(reductionOp, result);
790 
791       return success();
792     }
793 
794     if (!isa<FloatType>(eltType))
795       return failure();
796 
797     arith::FastMathFlagsAttr fMFAttr = reductionOp.getFastMathFlagsAttr();
798     LLVM::FastmathFlagsAttr fmf = LLVM::FastmathFlagsAttr::get(
799         reductionOp.getContext(),
800         convertArithFastMathFlagsToLLVM(fMFAttr.getValue()));
801     fmf = LLVM::FastmathFlagsAttr::get(
802         reductionOp.getContext(),
803         fmf.getValue() | (reassociateFPReductions ? LLVM::FastmathFlags::reassoc
804                                                   : LLVM::FastmathFlags::none));
805 
806     // Floating-point reductions: add/mul/min/max
807     Value result;
808     if (kind == vector::CombiningKind::ADD) {
809       result = lowerReductionWithStartValue<LLVM::vector_reduce_fadd,
810                                             ReductionNeutralZero>(
811           rewriter, loc, llvmType, operand, acc, fmf);
812     } else if (kind == vector::CombiningKind::MUL) {
813       result = lowerReductionWithStartValue<LLVM::vector_reduce_fmul,
814                                             ReductionNeutralFPOne>(
815           rewriter, loc, llvmType, operand, acc, fmf);
816     } else if (kind == vector::CombiningKind::MINIMUMF) {
817       result =
818           createFPReductionComparisonOpLowering<LLVM::vector_reduce_fminimum>(
819               rewriter, loc, llvmType, operand, acc, fmf);
820     } else if (kind == vector::CombiningKind::MAXIMUMF) {
821       result =
822           createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmaximum>(
823               rewriter, loc, llvmType, operand, acc, fmf);
824     } else if (kind == vector::CombiningKind::MINNUMF) {
825       result = createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmin>(
826           rewriter, loc, llvmType, operand, acc, fmf);
827     } else if (kind == vector::CombiningKind::MAXNUMF) {
828       result = createFPReductionComparisonOpLowering<LLVM::vector_reduce_fmax>(
829           rewriter, loc, llvmType, operand, acc, fmf);
830     } else
831       return failure();
832 
833     rewriter.replaceOp(reductionOp, result);
834     return success();
835   }
836 
837 private:
838   const bool reassociateFPReductions;
839 };
840 
841 /// Base class to convert a `vector.mask` operation while matching traits
842 /// of the maskable operation nested inside. A `VectorMaskOpConversionBase`
843 /// instance matches against a `vector.mask` operation. The `matchAndRewrite`
844 /// method performs a second match against the maskable operation `MaskedOp`.
845 /// Finally, it invokes the virtual method `matchAndRewriteMaskableOp` to be
846 /// implemented by the concrete conversion classes. This method can match
847 /// against specific traits of the `vector.mask` and the maskable operation. It
848 /// must replace the `vector.mask` operation.
849 template <class MaskedOp>
850 class VectorMaskOpConversionBase
851     : public ConvertOpToLLVMPattern<vector::MaskOp> {
852 public:
853   using ConvertOpToLLVMPattern<vector::MaskOp>::ConvertOpToLLVMPattern;
854 
855   LogicalResult
856   matchAndRewrite(vector::MaskOp maskOp, OpAdaptor adaptor,
857                   ConversionPatternRewriter &rewriter) const final {
858     // Match against the maskable operation kind.
859     auto maskedOp = llvm::dyn_cast_or_null<MaskedOp>(maskOp.getMaskableOp());
860     if (!maskedOp)
861       return failure();
862     return matchAndRewriteMaskableOp(maskOp, maskedOp, rewriter);
863   }
864 
865 protected:
866   virtual LogicalResult
867   matchAndRewriteMaskableOp(vector::MaskOp maskOp,
868                             vector::MaskableOpInterface maskableOp,
869                             ConversionPatternRewriter &rewriter) const = 0;
870 };
871 
872 class MaskedReductionOpConversion
873     : public VectorMaskOpConversionBase<vector::ReductionOp> {
874 
875 public:
876   using VectorMaskOpConversionBase<
877       vector::ReductionOp>::VectorMaskOpConversionBase;
878 
879   LogicalResult matchAndRewriteMaskableOp(
880       vector::MaskOp maskOp, MaskableOpInterface maskableOp,
881       ConversionPatternRewriter &rewriter) const override {
882     auto reductionOp = cast<ReductionOp>(maskableOp.getOperation());
883     auto kind = reductionOp.getKind();
884     Type eltType = reductionOp.getDest().getType();
885     Type llvmType = typeConverter->convertType(eltType);
886     Value operand = reductionOp.getVector();
887     Value acc = reductionOp.getAcc();
888     Location loc = reductionOp.getLoc();
889 
890     arith::FastMathFlagsAttr fMFAttr = reductionOp.getFastMathFlagsAttr();
891     LLVM::FastmathFlagsAttr fmf = LLVM::FastmathFlagsAttr::get(
892         reductionOp.getContext(),
893         convertArithFastMathFlagsToLLVM(fMFAttr.getValue()));
894 
895     Value result;
896     switch (kind) {
897     case vector::CombiningKind::ADD:
898       result = lowerPredicatedReductionWithStartValue<
899           LLVM::VPReduceAddOp, ReductionNeutralZero, LLVM::VPReduceFAddOp,
900           ReductionNeutralZero>(rewriter, loc, llvmType, operand, acc,
901                                 maskOp.getMask());
902       break;
903     case vector::CombiningKind::MUL:
904       result = lowerPredicatedReductionWithStartValue<
905           LLVM::VPReduceMulOp, ReductionNeutralIntOne, LLVM::VPReduceFMulOp,
906           ReductionNeutralFPOne>(rewriter, loc, llvmType, operand, acc,
907                                  maskOp.getMask());
908       break;
909     case vector::CombiningKind::MINUI:
910       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceUMinOp,
911                                                       ReductionNeutralUIntMax>(
912           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
913       break;
914     case vector::CombiningKind::MINSI:
915       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceSMinOp,
916                                                       ReductionNeutralSIntMax>(
917           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
918       break;
919     case vector::CombiningKind::MAXUI:
920       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceUMaxOp,
921                                                       ReductionNeutralUIntMin>(
922           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
923       break;
924     case vector::CombiningKind::MAXSI:
925       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceSMaxOp,
926                                                       ReductionNeutralSIntMin>(
927           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
928       break;
929     case vector::CombiningKind::AND:
930       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceAndOp,
931                                                       ReductionNeutralAllOnes>(
932           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
933       break;
934     case vector::CombiningKind::OR:
935       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceOrOp,
936                                                       ReductionNeutralZero>(
937           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
938       break;
939     case vector::CombiningKind::XOR:
940       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceXorOp,
941                                                       ReductionNeutralZero>(
942           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
943       break;
944     case vector::CombiningKind::MINNUMF:
945       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceFMinOp,
946                                                       ReductionNeutralFPMax>(
947           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
948       break;
949     case vector::CombiningKind::MAXNUMF:
950       result = lowerPredicatedReductionWithStartValue<LLVM::VPReduceFMaxOp,
951                                                       ReductionNeutralFPMin>(
952           rewriter, loc, llvmType, operand, acc, maskOp.getMask());
953       break;
954     case CombiningKind::MAXIMUMF:
955       result = lowerMaskedReductionWithRegular<LLVM::vector_reduce_fmaximum,
956                                                MaskNeutralFMaximum>(
957           rewriter, loc, llvmType, operand, acc, maskOp.getMask(), fmf);
958       break;
959     case CombiningKind::MINIMUMF:
960       result = lowerMaskedReductionWithRegular<LLVM::vector_reduce_fminimum,
961                                                MaskNeutralFMinimum>(
962           rewriter, loc, llvmType, operand, acc, maskOp.getMask(), fmf);
963       break;
964     }
965 
966     // Replace `vector.mask` operation altogether.
967     rewriter.replaceOp(maskOp, result);
968     return success();
969   }
970 };
971 
972 class VectorShuffleOpConversion
973     : public ConvertOpToLLVMPattern<vector::ShuffleOp> {
974 public:
975   using ConvertOpToLLVMPattern<vector::ShuffleOp>::ConvertOpToLLVMPattern;
976 
977   LogicalResult
978   matchAndRewrite(vector::ShuffleOp shuffleOp, OpAdaptor adaptor,
979                   ConversionPatternRewriter &rewriter) const override {
980     auto loc = shuffleOp->getLoc();
981     auto v1Type = shuffleOp.getV1VectorType();
982     auto v2Type = shuffleOp.getV2VectorType();
983     auto vectorType = shuffleOp.getResultVectorType();
984     Type llvmType = typeConverter->convertType(vectorType);
985     auto maskArrayAttr = shuffleOp.getMask();
986 
987     // Bail if result type cannot be lowered.
988     if (!llvmType)
989       return failure();
990 
991     // Get rank and dimension sizes.
992     int64_t rank = vectorType.getRank();
993 #ifndef NDEBUG
994     bool wellFormed0DCase =
995         v1Type.getRank() == 0 && v2Type.getRank() == 0 && rank == 1;
996     bool wellFormedNDCase =
997         v1Type.getRank() == rank && v2Type.getRank() == rank;
998     assert((wellFormed0DCase || wellFormedNDCase) && "op is not well-formed");
999 #endif
1000 
1001     // For rank 0 and 1, where both operands have *exactly* the same vector
1002     // type, there is direct shuffle support in LLVM. Use it!
1003     if (rank <= 1 && v1Type == v2Type) {
1004       Value llvmShuffleOp = rewriter.create<LLVM::ShuffleVectorOp>(
1005           loc, adaptor.getV1(), adaptor.getV2(),
1006           LLVM::convertArrayToIndices<int32_t>(maskArrayAttr));
1007       rewriter.replaceOp(shuffleOp, llvmShuffleOp);
1008       return success();
1009     }
1010 
1011     // For all other cases, insert the individual values individually.
1012     int64_t v1Dim = v1Type.getDimSize(0);
1013     Type eltType;
1014     if (auto arrayType = dyn_cast<LLVM::LLVMArrayType>(llvmType))
1015       eltType = arrayType.getElementType();
1016     else
1017       eltType = cast<VectorType>(llvmType).getElementType();
1018     Value insert = rewriter.create<LLVM::UndefOp>(loc, llvmType);
1019     int64_t insPos = 0;
1020     for (const auto &en : llvm::enumerate(maskArrayAttr)) {
1021       int64_t extPos = cast<IntegerAttr>(en.value()).getInt();
1022       Value value = adaptor.getV1();
1023       if (extPos >= v1Dim) {
1024         extPos -= v1Dim;
1025         value = adaptor.getV2();
1026       }
1027       Value extract = extractOne(rewriter, *getTypeConverter(), loc, value,
1028                                  eltType, rank, extPos);
1029       insert = insertOne(rewriter, *getTypeConverter(), loc, insert, extract,
1030                          llvmType, rank, insPos++);
1031     }
1032     rewriter.replaceOp(shuffleOp, insert);
1033     return success();
1034   }
1035 };
1036 
1037 class VectorExtractElementOpConversion
1038     : public ConvertOpToLLVMPattern<vector::ExtractElementOp> {
1039 public:
1040   using ConvertOpToLLVMPattern<
1041       vector::ExtractElementOp>::ConvertOpToLLVMPattern;
1042 
1043   LogicalResult
1044   matchAndRewrite(vector::ExtractElementOp extractEltOp, OpAdaptor adaptor,
1045                   ConversionPatternRewriter &rewriter) const override {
1046     auto vectorType = extractEltOp.getSourceVectorType();
1047     auto llvmType = typeConverter->convertType(vectorType.getElementType());
1048 
1049     // Bail if result type cannot be lowered.
1050     if (!llvmType)
1051       return failure();
1052 
1053     if (vectorType.getRank() == 0) {
1054       Location loc = extractEltOp.getLoc();
1055       auto idxType = rewriter.getIndexType();
1056       auto zero = rewriter.create<LLVM::ConstantOp>(
1057           loc, typeConverter->convertType(idxType),
1058           rewriter.getIntegerAttr(idxType, 0));
1059       rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
1060           extractEltOp, llvmType, adaptor.getVector(), zero);
1061       return success();
1062     }
1063 
1064     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
1065         extractEltOp, llvmType, adaptor.getVector(), adaptor.getPosition());
1066     return success();
1067   }
1068 };
1069 
1070 class VectorExtractOpConversion
1071     : public ConvertOpToLLVMPattern<vector::ExtractOp> {
1072 public:
1073   using ConvertOpToLLVMPattern<vector::ExtractOp>::ConvertOpToLLVMPattern;
1074 
1075   LogicalResult
1076   matchAndRewrite(vector::ExtractOp extractOp, OpAdaptor adaptor,
1077                   ConversionPatternRewriter &rewriter) const override {
1078     auto loc = extractOp->getLoc();
1079     auto resultType = extractOp.getResult().getType();
1080     auto llvmResultType = typeConverter->convertType(resultType);
1081     // Bail if result type cannot be lowered.
1082     if (!llvmResultType)
1083       return failure();
1084 
1085     SmallVector<OpFoldResult> positionVec;
1086     for (auto [idx, pos] : llvm::enumerate(extractOp.getMixedPosition())) {
1087       if (pos.is<Value>())
1088         // Make sure we use the value that has been already converted to LLVM.
1089         positionVec.push_back(adaptor.getDynamicPosition()[idx]);
1090       else
1091         positionVec.push_back(pos);
1092     }
1093 
1094     // Extract entire vector. Should be handled by folder, but just to be safe.
1095     ArrayRef<OpFoldResult> position(positionVec);
1096     if (position.empty()) {
1097       rewriter.replaceOp(extractOp, adaptor.getVector());
1098       return success();
1099     }
1100 
1101     // One-shot extraction of vector from array (only requires extractvalue).
1102     if (isa<VectorType>(resultType)) {
1103       if (extractOp.hasDynamicPosition())
1104         return failure();
1105 
1106       Value extracted = rewriter.create<LLVM::ExtractValueOp>(
1107           loc, adaptor.getVector(), getAsIntegers(position));
1108       rewriter.replaceOp(extractOp, extracted);
1109       return success();
1110     }
1111 
1112     // Potential extraction of 1-D vector from array.
1113     Value extracted = adaptor.getVector();
1114     if (position.size() > 1) {
1115       if (extractOp.hasDynamicPosition())
1116         return failure();
1117 
1118       SmallVector<int64_t> nMinusOnePosition =
1119           getAsIntegers(position.drop_back());
1120       extracted = rewriter.create<LLVM::ExtractValueOp>(loc, extracted,
1121                                                         nMinusOnePosition);
1122     }
1123 
1124     Value lastPosition = getAsLLVMValue(rewriter, loc, position.back());
1125     // Remaining extraction of element from 1-D LLVM vector.
1126     rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(extractOp, extracted,
1127                                                         lastPosition);
1128     return success();
1129   }
1130 };
1131 
1132 /// Conversion pattern that turns a vector.fma on a 1-D vector
1133 /// into an llvm.intr.fmuladd. This is a trivial 1-1 conversion.
1134 /// This does not match vectors of n >= 2 rank.
1135 ///
1136 /// Example:
1137 /// ```
1138 ///  vector.fma %a, %a, %a : vector<8xf32>
1139 /// ```
1140 /// is converted to:
1141 /// ```
1142 ///  llvm.intr.fmuladd %va, %va, %va:
1143 ///    (!llvm."<8 x f32>">, !llvm<"<8 x f32>">, !llvm<"<8 x f32>">)
1144 ///    -> !llvm."<8 x f32>">
1145 /// ```
1146 class VectorFMAOp1DConversion : public ConvertOpToLLVMPattern<vector::FMAOp> {
1147 public:
1148   using ConvertOpToLLVMPattern<vector::FMAOp>::ConvertOpToLLVMPattern;
1149 
1150   LogicalResult
1151   matchAndRewrite(vector::FMAOp fmaOp, OpAdaptor adaptor,
1152                   ConversionPatternRewriter &rewriter) const override {
1153     VectorType vType = fmaOp.getVectorType();
1154     if (vType.getRank() > 1)
1155       return failure();
1156 
1157     rewriter.replaceOpWithNewOp<LLVM::FMulAddOp>(
1158         fmaOp, adaptor.getLhs(), adaptor.getRhs(), adaptor.getAcc());
1159     return success();
1160   }
1161 };
1162 
1163 class VectorInsertElementOpConversion
1164     : public ConvertOpToLLVMPattern<vector::InsertElementOp> {
1165 public:
1166   using ConvertOpToLLVMPattern<vector::InsertElementOp>::ConvertOpToLLVMPattern;
1167 
1168   LogicalResult
1169   matchAndRewrite(vector::InsertElementOp insertEltOp, OpAdaptor adaptor,
1170                   ConversionPatternRewriter &rewriter) const override {
1171     auto vectorType = insertEltOp.getDestVectorType();
1172     auto llvmType = typeConverter->convertType(vectorType);
1173 
1174     // Bail if result type cannot be lowered.
1175     if (!llvmType)
1176       return failure();
1177 
1178     if (vectorType.getRank() == 0) {
1179       Location loc = insertEltOp.getLoc();
1180       auto idxType = rewriter.getIndexType();
1181       auto zero = rewriter.create<LLVM::ConstantOp>(
1182           loc, typeConverter->convertType(idxType),
1183           rewriter.getIntegerAttr(idxType, 0));
1184       rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1185           insertEltOp, llvmType, adaptor.getDest(), adaptor.getSource(), zero);
1186       return success();
1187     }
1188 
1189     rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1190         insertEltOp, llvmType, adaptor.getDest(), adaptor.getSource(),
1191         adaptor.getPosition());
1192     return success();
1193   }
1194 };
1195 
1196 class VectorInsertOpConversion
1197     : public ConvertOpToLLVMPattern<vector::InsertOp> {
1198 public:
1199   using ConvertOpToLLVMPattern<vector::InsertOp>::ConvertOpToLLVMPattern;
1200 
1201   LogicalResult
1202   matchAndRewrite(vector::InsertOp insertOp, OpAdaptor adaptor,
1203                   ConversionPatternRewriter &rewriter) const override {
1204     auto loc = insertOp->getLoc();
1205     auto sourceType = insertOp.getSourceType();
1206     auto destVectorType = insertOp.getDestVectorType();
1207     auto llvmResultType = typeConverter->convertType(destVectorType);
1208     // Bail if result type cannot be lowered.
1209     if (!llvmResultType)
1210       return failure();
1211 
1212     SmallVector<OpFoldResult> positionVec;
1213     for (auto [idx, pos] : llvm::enumerate(insertOp.getMixedPosition())) {
1214       if (pos.is<Value>())
1215         // Make sure we use the value that has been already converted to LLVM.
1216         positionVec.push_back(adaptor.getDynamicPosition()[idx]);
1217       else
1218         positionVec.push_back(pos);
1219     }
1220 
1221     // Overwrite entire vector with value. Should be handled by folder, but
1222     // just to be safe.
1223     ArrayRef<OpFoldResult> position(positionVec);
1224     if (position.empty()) {
1225       rewriter.replaceOp(insertOp, adaptor.getSource());
1226       return success();
1227     }
1228 
1229     // One-shot insertion of a vector into an array (only requires insertvalue).
1230     if (isa<VectorType>(sourceType)) {
1231       if (insertOp.hasDynamicPosition())
1232         return failure();
1233 
1234       Value inserted = rewriter.create<LLVM::InsertValueOp>(
1235           loc, adaptor.getDest(), adaptor.getSource(), getAsIntegers(position));
1236       rewriter.replaceOp(insertOp, inserted);
1237       return success();
1238     }
1239 
1240     // Potential extraction of 1-D vector from array.
1241     Value extracted = adaptor.getDest();
1242     auto oneDVectorType = destVectorType;
1243     if (position.size() > 1) {
1244       if (insertOp.hasDynamicPosition())
1245         return failure();
1246 
1247       oneDVectorType = reducedVectorTypeBack(destVectorType);
1248       extracted = rewriter.create<LLVM::ExtractValueOp>(
1249           loc, extracted, getAsIntegers(position.drop_back()));
1250     }
1251 
1252     // Insertion of an element into a 1-D LLVM vector.
1253     Value inserted = rewriter.create<LLVM::InsertElementOp>(
1254         loc, typeConverter->convertType(oneDVectorType), extracted,
1255         adaptor.getSource(), getAsLLVMValue(rewriter, loc, position.back()));
1256 
1257     // Potential insertion of resulting 1-D vector into array.
1258     if (position.size() > 1) {
1259       if (insertOp.hasDynamicPosition())
1260         return failure();
1261 
1262       inserted = rewriter.create<LLVM::InsertValueOp>(
1263           loc, adaptor.getDest(), inserted,
1264           getAsIntegers(position.drop_back()));
1265     }
1266 
1267     rewriter.replaceOp(insertOp, inserted);
1268     return success();
1269   }
1270 };
1271 
1272 /// Lower vector.scalable.insert ops to LLVM vector.insert
1273 struct VectorScalableInsertOpLowering
1274     : public ConvertOpToLLVMPattern<vector::ScalableInsertOp> {
1275   using ConvertOpToLLVMPattern<
1276       vector::ScalableInsertOp>::ConvertOpToLLVMPattern;
1277 
1278   LogicalResult
1279   matchAndRewrite(vector::ScalableInsertOp insOp, OpAdaptor adaptor,
1280                   ConversionPatternRewriter &rewriter) const override {
1281     rewriter.replaceOpWithNewOp<LLVM::vector_insert>(
1282         insOp, adaptor.getDest(), adaptor.getSource(), adaptor.getPos());
1283     return success();
1284   }
1285 };
1286 
1287 /// Lower vector.scalable.extract ops to LLVM vector.extract
1288 struct VectorScalableExtractOpLowering
1289     : public ConvertOpToLLVMPattern<vector::ScalableExtractOp> {
1290   using ConvertOpToLLVMPattern<
1291       vector::ScalableExtractOp>::ConvertOpToLLVMPattern;
1292 
1293   LogicalResult
1294   matchAndRewrite(vector::ScalableExtractOp extOp, OpAdaptor adaptor,
1295                   ConversionPatternRewriter &rewriter) const override {
1296     rewriter.replaceOpWithNewOp<LLVM::vector_extract>(
1297         extOp, typeConverter->convertType(extOp.getResultVectorType()),
1298         adaptor.getSource(), adaptor.getPos());
1299     return success();
1300   }
1301 };
1302 
1303 /// Rank reducing rewrite for n-D FMA into (n-1)-D FMA where n > 1.
1304 ///
1305 /// Example:
1306 /// ```
1307 ///   %d = vector.fma %a, %b, %c : vector<2x4xf32>
1308 /// ```
1309 /// is rewritten into:
1310 /// ```
1311 ///  %r = splat %f0: vector<2x4xf32>
1312 ///  %va = vector.extractvalue %a[0] : vector<2x4xf32>
1313 ///  %vb = vector.extractvalue %b[0] : vector<2x4xf32>
1314 ///  %vc = vector.extractvalue %c[0] : vector<2x4xf32>
1315 ///  %vd = vector.fma %va, %vb, %vc : vector<4xf32>
1316 ///  %r2 = vector.insertvalue %vd, %r[0] : vector<4xf32> into vector<2x4xf32>
1317 ///  %va2 = vector.extractvalue %a2[1] : vector<2x4xf32>
1318 ///  %vb2 = vector.extractvalue %b2[1] : vector<2x4xf32>
1319 ///  %vc2 = vector.extractvalue %c2[1] : vector<2x4xf32>
1320 ///  %vd2 = vector.fma %va2, %vb2, %vc2 : vector<4xf32>
1321 ///  %r3 = vector.insertvalue %vd2, %r2[1] : vector<4xf32> into vector<2x4xf32>
1322 ///  // %r3 holds the final value.
1323 /// ```
1324 class VectorFMAOpNDRewritePattern : public OpRewritePattern<FMAOp> {
1325 public:
1326   using OpRewritePattern<FMAOp>::OpRewritePattern;
1327 
1328   void initialize() {
1329     // This pattern recursively unpacks one dimension at a time. The recursion
1330     // bounded as the rank is strictly decreasing.
1331     setHasBoundedRewriteRecursion();
1332   }
1333 
1334   LogicalResult matchAndRewrite(FMAOp op,
1335                                 PatternRewriter &rewriter) const override {
1336     auto vType = op.getVectorType();
1337     if (vType.getRank() < 2)
1338       return failure();
1339 
1340     auto loc = op.getLoc();
1341     auto elemType = vType.getElementType();
1342     Value zero = rewriter.create<arith::ConstantOp>(
1343         loc, elemType, rewriter.getZeroAttr(elemType));
1344     Value desc = rewriter.create<vector::SplatOp>(loc, vType, zero);
1345     for (int64_t i = 0, e = vType.getShape().front(); i != e; ++i) {
1346       Value extrLHS = rewriter.create<ExtractOp>(loc, op.getLhs(), i);
1347       Value extrRHS = rewriter.create<ExtractOp>(loc, op.getRhs(), i);
1348       Value extrACC = rewriter.create<ExtractOp>(loc, op.getAcc(), i);
1349       Value fma = rewriter.create<FMAOp>(loc, extrLHS, extrRHS, extrACC);
1350       desc = rewriter.create<InsertOp>(loc, fma, desc, i);
1351     }
1352     rewriter.replaceOp(op, desc);
1353     return success();
1354   }
1355 };
1356 
1357 /// Returns the strides if the memory underlying `memRefType` has a contiguous
1358 /// static layout.
1359 static std::optional<SmallVector<int64_t, 4>>
1360 computeContiguousStrides(MemRefType memRefType) {
1361   int64_t offset;
1362   SmallVector<int64_t, 4> strides;
1363   if (failed(getStridesAndOffset(memRefType, strides, offset)))
1364     return std::nullopt;
1365   if (!strides.empty() && strides.back() != 1)
1366     return std::nullopt;
1367   // If no layout or identity layout, this is contiguous by definition.
1368   if (memRefType.getLayout().isIdentity())
1369     return strides;
1370 
1371   // Otherwise, we must determine contiguity form shapes. This can only ever
1372   // work in static cases because MemRefType is underspecified to represent
1373   // contiguous dynamic shapes in other ways than with just empty/identity
1374   // layout.
1375   auto sizes = memRefType.getShape();
1376   for (int index = 0, e = strides.size() - 1; index < e; ++index) {
1377     if (ShapedType::isDynamic(sizes[index + 1]) ||
1378         ShapedType::isDynamic(strides[index]) ||
1379         ShapedType::isDynamic(strides[index + 1]))
1380       return std::nullopt;
1381     if (strides[index] != strides[index + 1] * sizes[index + 1])
1382       return std::nullopt;
1383   }
1384   return strides;
1385 }
1386 
1387 class VectorTypeCastOpConversion
1388     : public ConvertOpToLLVMPattern<vector::TypeCastOp> {
1389 public:
1390   using ConvertOpToLLVMPattern<vector::TypeCastOp>::ConvertOpToLLVMPattern;
1391 
1392   LogicalResult
1393   matchAndRewrite(vector::TypeCastOp castOp, OpAdaptor adaptor,
1394                   ConversionPatternRewriter &rewriter) const override {
1395     auto loc = castOp->getLoc();
1396     MemRefType sourceMemRefType =
1397         cast<MemRefType>(castOp.getOperand().getType());
1398     MemRefType targetMemRefType = castOp.getType();
1399 
1400     // Only static shape casts supported atm.
1401     if (!sourceMemRefType.hasStaticShape() ||
1402         !targetMemRefType.hasStaticShape())
1403       return failure();
1404 
1405     auto llvmSourceDescriptorTy =
1406         dyn_cast<LLVM::LLVMStructType>(adaptor.getOperands()[0].getType());
1407     if (!llvmSourceDescriptorTy)
1408       return failure();
1409     MemRefDescriptor sourceMemRef(adaptor.getOperands()[0]);
1410 
1411     auto llvmTargetDescriptorTy = dyn_cast_or_null<LLVM::LLVMStructType>(
1412         typeConverter->convertType(targetMemRefType));
1413     if (!llvmTargetDescriptorTy)
1414       return failure();
1415 
1416     // Only contiguous source buffers supported atm.
1417     auto sourceStrides = computeContiguousStrides(sourceMemRefType);
1418     if (!sourceStrides)
1419       return failure();
1420     auto targetStrides = computeContiguousStrides(targetMemRefType);
1421     if (!targetStrides)
1422       return failure();
1423     // Only support static strides for now, regardless of contiguity.
1424     if (llvm::any_of(*targetStrides, ShapedType::isDynamic))
1425       return failure();
1426 
1427     auto int64Ty = IntegerType::get(rewriter.getContext(), 64);
1428 
1429     // Create descriptor.
1430     auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy);
1431     // Set allocated ptr.
1432     Value allocated = sourceMemRef.allocatedPtr(rewriter, loc);
1433     desc.setAllocatedPtr(rewriter, loc, allocated);
1434 
1435     // Set aligned ptr.
1436     Value ptr = sourceMemRef.alignedPtr(rewriter, loc);
1437     desc.setAlignedPtr(rewriter, loc, ptr);
1438     // Fill offset 0.
1439     auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0);
1440     auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr);
1441     desc.setOffset(rewriter, loc, zero);
1442 
1443     // Fill size and stride descriptors in memref.
1444     for (const auto &indexedSize :
1445          llvm::enumerate(targetMemRefType.getShape())) {
1446       int64_t index = indexedSize.index();
1447       auto sizeAttr =
1448           rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value());
1449       auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr);
1450       desc.setSize(rewriter, loc, index, size);
1451       auto strideAttr = rewriter.getIntegerAttr(rewriter.getIndexType(),
1452                                                 (*targetStrides)[index]);
1453       auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr);
1454       desc.setStride(rewriter, loc, index, stride);
1455     }
1456 
1457     rewriter.replaceOp(castOp, {desc});
1458     return success();
1459   }
1460 };
1461 
1462 /// Conversion pattern for a `vector.create_mask` (1-D scalable vectors only).
1463 /// Non-scalable versions of this operation are handled in Vector Transforms.
1464 class VectorCreateMaskOpRewritePattern
1465     : public OpRewritePattern<vector::CreateMaskOp> {
1466 public:
1467   explicit VectorCreateMaskOpRewritePattern(MLIRContext *context,
1468                                             bool enableIndexOpt)
1469       : OpRewritePattern<vector::CreateMaskOp>(context),
1470         force32BitVectorIndices(enableIndexOpt) {}
1471 
1472   LogicalResult matchAndRewrite(vector::CreateMaskOp op,
1473                                 PatternRewriter &rewriter) const override {
1474     auto dstType = op.getType();
1475     if (dstType.getRank() != 1 || !cast<VectorType>(dstType).isScalable())
1476       return failure();
1477     IntegerType idxType =
1478         force32BitVectorIndices ? rewriter.getI32Type() : rewriter.getI64Type();
1479     auto loc = op->getLoc();
1480     Value indices = rewriter.create<LLVM::StepVectorOp>(
1481         loc, LLVM::getVectorType(idxType, dstType.getShape()[0],
1482                                  /*isScalable=*/true));
1483     auto bound = getValueOrCreateCastToIndexLike(rewriter, loc, idxType,
1484                                                  op.getOperand(0));
1485     Value bounds = rewriter.create<SplatOp>(loc, indices.getType(), bound);
1486     Value comp = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt,
1487                                                 indices, bounds);
1488     rewriter.replaceOp(op, comp);
1489     return success();
1490   }
1491 
1492 private:
1493   const bool force32BitVectorIndices;
1494 };
1495 
1496 class VectorPrintOpConversion : public ConvertOpToLLVMPattern<vector::PrintOp> {
1497 public:
1498   using ConvertOpToLLVMPattern<vector::PrintOp>::ConvertOpToLLVMPattern;
1499 
1500   // Lowering implementation that relies on a small runtime support library,
1501   // which only needs to provide a few printing methods (single value for all
1502   // data types, opening/closing bracket, comma, newline). The lowering splits
1503   // the vector into elementary printing operations. The advantage of this
1504   // approach is that the library can remain unaware of all low-level
1505   // implementation details of vectors while still supporting output of any
1506   // shaped and dimensioned vector.
1507   //
1508   // Note: This lowering only handles scalars, n-D vectors are broken into
1509   // printing scalars in loops in VectorToSCF.
1510   //
1511   // TODO: rely solely on libc in future? something else?
1512   //
1513   LogicalResult
1514   matchAndRewrite(vector::PrintOp printOp, OpAdaptor adaptor,
1515                   ConversionPatternRewriter &rewriter) const override {
1516     auto parent = printOp->getParentOfType<ModuleOp>();
1517     if (!parent)
1518       return failure();
1519 
1520     auto loc = printOp->getLoc();
1521 
1522     if (auto value = adaptor.getSource()) {
1523       Type printType = printOp.getPrintType();
1524       if (isa<VectorType>(printType)) {
1525         // Vectors should be broken into elementary print ops in VectorToSCF.
1526         return failure();
1527       }
1528       if (failed(emitScalarPrint(rewriter, parent, loc, printType, value)))
1529         return failure();
1530     }
1531 
1532     auto punct = printOp.getPunctuation();
1533     if (auto stringLiteral = printOp.getStringLiteral()) {
1534       LLVM::createPrintStrCall(rewriter, loc, parent, "vector_print_str",
1535                                *stringLiteral, *getTypeConverter(),
1536                                /*addNewline=*/false);
1537     } else if (punct != PrintPunctuation::NoPunctuation) {
1538       emitCall(rewriter, printOp->getLoc(), [&] {
1539         switch (punct) {
1540         case PrintPunctuation::Close:
1541           return LLVM::lookupOrCreatePrintCloseFn(parent);
1542         case PrintPunctuation::Open:
1543           return LLVM::lookupOrCreatePrintOpenFn(parent);
1544         case PrintPunctuation::Comma:
1545           return LLVM::lookupOrCreatePrintCommaFn(parent);
1546         case PrintPunctuation::NewLine:
1547           return LLVM::lookupOrCreatePrintNewlineFn(parent);
1548         default:
1549           llvm_unreachable("unexpected punctuation");
1550         }
1551       }());
1552     }
1553 
1554     rewriter.eraseOp(printOp);
1555     return success();
1556   }
1557 
1558 private:
1559   enum class PrintConversion {
1560     // clang-format off
1561     None,
1562     ZeroExt64,
1563     SignExt64,
1564     Bitcast16
1565     // clang-format on
1566   };
1567 
1568   LogicalResult emitScalarPrint(ConversionPatternRewriter &rewriter,
1569                                 ModuleOp parent, Location loc, Type printType,
1570                                 Value value) const {
1571     if (typeConverter->convertType(printType) == nullptr)
1572       return failure();
1573 
1574     // Make sure element type has runtime support.
1575     PrintConversion conversion = PrintConversion::None;
1576     Operation *printer;
1577     if (printType.isF32()) {
1578       printer = LLVM::lookupOrCreatePrintF32Fn(parent);
1579     } else if (printType.isF64()) {
1580       printer = LLVM::lookupOrCreatePrintF64Fn(parent);
1581     } else if (printType.isF16()) {
1582       conversion = PrintConversion::Bitcast16; // bits!
1583       printer = LLVM::lookupOrCreatePrintF16Fn(parent);
1584     } else if (printType.isBF16()) {
1585       conversion = PrintConversion::Bitcast16; // bits!
1586       printer = LLVM::lookupOrCreatePrintBF16Fn(parent);
1587     } else if (printType.isIndex()) {
1588       printer = LLVM::lookupOrCreatePrintU64Fn(parent);
1589     } else if (auto intTy = dyn_cast<IntegerType>(printType)) {
1590       // Integers need a zero or sign extension on the operand
1591       // (depending on the source type) as well as a signed or
1592       // unsigned print method. Up to 64-bit is supported.
1593       unsigned width = intTy.getWidth();
1594       if (intTy.isUnsigned()) {
1595         if (width <= 64) {
1596           if (width < 64)
1597             conversion = PrintConversion::ZeroExt64;
1598           printer = LLVM::lookupOrCreatePrintU64Fn(parent);
1599         } else {
1600           return failure();
1601         }
1602       } else {
1603         assert(intTy.isSignless() || intTy.isSigned());
1604         if (width <= 64) {
1605           // Note that we *always* zero extend booleans (1-bit integers),
1606           // so that true/false is printed as 1/0 rather than -1/0.
1607           if (width == 1)
1608             conversion = PrintConversion::ZeroExt64;
1609           else if (width < 64)
1610             conversion = PrintConversion::SignExt64;
1611           printer = LLVM::lookupOrCreatePrintI64Fn(parent);
1612         } else {
1613           return failure();
1614         }
1615       }
1616     } else {
1617       return failure();
1618     }
1619 
1620     switch (conversion) {
1621     case PrintConversion::ZeroExt64:
1622       value = rewriter.create<arith::ExtUIOp>(
1623           loc, IntegerType::get(rewriter.getContext(), 64), value);
1624       break;
1625     case PrintConversion::SignExt64:
1626       value = rewriter.create<arith::ExtSIOp>(
1627           loc, IntegerType::get(rewriter.getContext(), 64), value);
1628       break;
1629     case PrintConversion::Bitcast16:
1630       value = rewriter.create<LLVM::BitcastOp>(
1631           loc, IntegerType::get(rewriter.getContext(), 16), value);
1632       break;
1633     case PrintConversion::None:
1634       break;
1635     }
1636     emitCall(rewriter, loc, printer, value);
1637     return success();
1638   }
1639 
1640   // Helper to emit a call.
1641   static void emitCall(ConversionPatternRewriter &rewriter, Location loc,
1642                        Operation *ref, ValueRange params = ValueRange()) {
1643     rewriter.create<LLVM::CallOp>(loc, TypeRange(), SymbolRefAttr::get(ref),
1644                                   params);
1645   }
1646 };
1647 
1648 /// The Splat operation is lowered to an insertelement + a shufflevector
1649 /// operation. Splat to only 0-d and 1-d vector result types are lowered.
1650 struct VectorSplatOpLowering : public ConvertOpToLLVMPattern<vector::SplatOp> {
1651   using ConvertOpToLLVMPattern<vector::SplatOp>::ConvertOpToLLVMPattern;
1652 
1653   LogicalResult
1654   matchAndRewrite(vector::SplatOp splatOp, OpAdaptor adaptor,
1655                   ConversionPatternRewriter &rewriter) const override {
1656     VectorType resultType = cast<VectorType>(splatOp.getType());
1657     if (resultType.getRank() > 1)
1658       return failure();
1659 
1660     // First insert it into an undef vector so we can shuffle it.
1661     auto vectorType = typeConverter->convertType(splatOp.getType());
1662     Value undef = rewriter.create<LLVM::UndefOp>(splatOp.getLoc(), vectorType);
1663     auto zero = rewriter.create<LLVM::ConstantOp>(
1664         splatOp.getLoc(),
1665         typeConverter->convertType(rewriter.getIntegerType(32)),
1666         rewriter.getZeroAttr(rewriter.getIntegerType(32)));
1667 
1668     // For 0-d vector, we simply do `insertelement`.
1669     if (resultType.getRank() == 0) {
1670       rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
1671           splatOp, vectorType, undef, adaptor.getInput(), zero);
1672       return success();
1673     }
1674 
1675     // For 1-d vector, we additionally do a `vectorshuffle`.
1676     auto v = rewriter.create<LLVM::InsertElementOp>(
1677         splatOp.getLoc(), vectorType, undef, adaptor.getInput(), zero);
1678 
1679     int64_t width = cast<VectorType>(splatOp.getType()).getDimSize(0);
1680     SmallVector<int32_t> zeroValues(width, 0);
1681 
1682     // Shuffle the value across the desired number of elements.
1683     rewriter.replaceOpWithNewOp<LLVM::ShuffleVectorOp>(splatOp, v, undef,
1684                                                        zeroValues);
1685     return success();
1686   }
1687 };
1688 
1689 /// The Splat operation is lowered to an insertelement + a shufflevector
1690 /// operation. Splat to only 2+-d vector result types are lowered by the
1691 /// SplatNdOpLowering, the 1-d case is handled by SplatOpLowering.
1692 struct VectorSplatNdOpLowering : public ConvertOpToLLVMPattern<SplatOp> {
1693   using ConvertOpToLLVMPattern<SplatOp>::ConvertOpToLLVMPattern;
1694 
1695   LogicalResult
1696   matchAndRewrite(SplatOp splatOp, OpAdaptor adaptor,
1697                   ConversionPatternRewriter &rewriter) const override {
1698     VectorType resultType = splatOp.getType();
1699     if (resultType.getRank() <= 1)
1700       return failure();
1701 
1702     // First insert it into an undef vector so we can shuffle it.
1703     auto loc = splatOp.getLoc();
1704     auto vectorTypeInfo =
1705         LLVM::detail::extractNDVectorTypeInfo(resultType, *getTypeConverter());
1706     auto llvmNDVectorTy = vectorTypeInfo.llvmNDVectorTy;
1707     auto llvm1DVectorTy = vectorTypeInfo.llvm1DVectorTy;
1708     if (!llvmNDVectorTy || !llvm1DVectorTy)
1709       return failure();
1710 
1711     // Construct returned value.
1712     Value desc = rewriter.create<LLVM::UndefOp>(loc, llvmNDVectorTy);
1713 
1714     // Construct a 1-D vector with the splatted value that we insert in all the
1715     // places within the returned descriptor.
1716     Value vdesc = rewriter.create<LLVM::UndefOp>(loc, llvm1DVectorTy);
1717     auto zero = rewriter.create<LLVM::ConstantOp>(
1718         loc, typeConverter->convertType(rewriter.getIntegerType(32)),
1719         rewriter.getZeroAttr(rewriter.getIntegerType(32)));
1720     Value v = rewriter.create<LLVM::InsertElementOp>(loc, llvm1DVectorTy, vdesc,
1721                                                      adaptor.getInput(), zero);
1722 
1723     // Shuffle the value across the desired number of elements.
1724     int64_t width = resultType.getDimSize(resultType.getRank() - 1);
1725     SmallVector<int32_t> zeroValues(width, 0);
1726     v = rewriter.create<LLVM::ShuffleVectorOp>(loc, v, v, zeroValues);
1727 
1728     // Iterate of linear index, convert to coords space and insert splatted 1-D
1729     // vector in each position.
1730     nDVectorIterate(vectorTypeInfo, rewriter, [&](ArrayRef<int64_t> position) {
1731       desc = rewriter.create<LLVM::InsertValueOp>(loc, desc, v, position);
1732     });
1733     rewriter.replaceOp(splatOp, desc);
1734     return success();
1735   }
1736 };
1737 
1738 /// Conversion pattern for a `vector.interleave`.
1739 /// This supports fixed-sized vectors and scalable vectors.
1740 struct VectorInterleaveOpLowering
1741     : public ConvertOpToLLVMPattern<vector::InterleaveOp> {
1742   using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern;
1743 
1744   LogicalResult
1745   matchAndRewrite(vector::InterleaveOp interleaveOp, OpAdaptor adaptor,
1746                   ConversionPatternRewriter &rewriter) const override {
1747     VectorType resultType = interleaveOp.getResultVectorType();
1748     // n-D interleaves should have been lowered already.
1749     if (resultType.getRank() != 1)
1750       return rewriter.notifyMatchFailure(interleaveOp,
1751                                          "InterleaveOp not rank 1");
1752     // If the result is rank 1, then this directly maps to LLVM.
1753     if (resultType.isScalable()) {
1754       rewriter.replaceOpWithNewOp<LLVM::experimental_vector_interleave2>(
1755           interleaveOp, typeConverter->convertType(resultType),
1756           adaptor.getLhs(), adaptor.getRhs());
1757       return success();
1758     }
1759     // Lower fixed-size interleaves to a shufflevector. While the
1760     // vector.interleave2 intrinsic supports fixed and scalable vectors, the
1761     // langref still recommends fixed-vectors use shufflevector, see:
1762     // https://llvm.org/docs/LangRef.html#id876.
1763     int64_t resultVectorSize = resultType.getNumElements();
1764     SmallVector<int32_t> interleaveShuffleMask;
1765     interleaveShuffleMask.reserve(resultVectorSize);
1766     for (int i = 0, end = resultVectorSize / 2; i < end; ++i) {
1767       interleaveShuffleMask.push_back(i);
1768       interleaveShuffleMask.push_back((resultVectorSize / 2) + i);
1769     }
1770     rewriter.replaceOpWithNewOp<LLVM::ShuffleVectorOp>(
1771         interleaveOp, adaptor.getLhs(), adaptor.getRhs(),
1772         interleaveShuffleMask);
1773     return success();
1774   }
1775 };
1776 
1777 } // namespace
1778 
1779 /// Populate the given list with patterns that convert from Vector to LLVM.
1780 void mlir::populateVectorToLLVMConversionPatterns(
1781     LLVMTypeConverter &converter, RewritePatternSet &patterns,
1782     bool reassociateFPReductions, bool force32BitVectorIndices) {
1783   MLIRContext *ctx = converter.getDialect()->getContext();
1784   patterns.add<VectorFMAOpNDRewritePattern>(ctx);
1785   populateVectorInsertExtractStridedSliceTransforms(patterns);
1786   patterns.add<VectorReductionOpConversion>(converter, reassociateFPReductions);
1787   patterns.add<VectorCreateMaskOpRewritePattern>(ctx, force32BitVectorIndices);
1788   patterns.add<VectorBitCastOpConversion, VectorShuffleOpConversion,
1789                VectorExtractElementOpConversion, VectorExtractOpConversion,
1790                VectorFMAOp1DConversion, VectorInsertElementOpConversion,
1791                VectorInsertOpConversion, VectorPrintOpConversion,
1792                VectorTypeCastOpConversion, VectorScaleOpConversion,
1793                VectorLoadStoreConversion<vector::LoadOp>,
1794                VectorLoadStoreConversion<vector::MaskedLoadOp>,
1795                VectorLoadStoreConversion<vector::StoreOp>,
1796                VectorLoadStoreConversion<vector::MaskedStoreOp>,
1797                VectorGatherOpConversion, VectorScatterOpConversion,
1798                VectorExpandLoadOpConversion, VectorCompressStoreOpConversion,
1799                VectorSplatOpLowering, VectorSplatNdOpLowering,
1800                VectorScalableInsertOpLowering, VectorScalableExtractOpLowering,
1801                MaskedReductionOpConversion, VectorInterleaveOpLowering>(
1802       converter);
1803   // Transfer ops with rank > 1 are handled by VectorToSCF.
1804   populateVectorTransferLoweringPatterns(patterns, /*maxTransferRank=*/1);
1805 }
1806 
1807 void mlir::populateVectorToLLVMMatrixConversionPatterns(
1808     LLVMTypeConverter &converter, RewritePatternSet &patterns) {
1809   patterns.add<VectorMatmulOpConversion>(converter);
1810   patterns.add<VectorFlatTransposeOpConversion>(converter);
1811 }
1812