MLIR 24.0.0git
VectorRewritePatterns.h
Go to the documentation of this file.
1//===- VectorRewritePatterns.h - Vector rewrite patterns --------*- C++ -*-===//
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#ifndef MLIR_DIALECT_VECTOR_TRANSFORMS_VECTORREWRITEPATTERNS_H
10#define MLIR_DIALECT_VECTOR_TRANSFORMS_VECTORREWRITEPATTERNS_H
11
12#include <optional>
13#include <utility>
14
18
19#include "mlir/Dialect/Vector/Transforms/VectorTransformsEnums.h.inc"
20
21namespace mlir {
22class ConversionTarget;
24class TypeConverter;
25
26namespace arith {
27class AndIOp;
29class TruncIOp;
30} // namespace arith
31
32namespace vector {
34
35/// Options that control the vector unrolling.
37 using FilterConstraintFnType = std::function<LogicalResult(Operation *op)>;
38 /// Callback function that indicates whether vector unrolling should be
39 /// attempted on the operation.
42 filterConstraint = std::move(constraint);
43 return *this;
44 }
45
47 std::function<std::optional<SmallVector<int64_t>>(Operation *op)>;
48 /// Function that returns the shape of the vector to unroll to for a given
49 /// operation. The unrolling is aborted if the function returns
50 /// `std::nullopt`.
53 nativeShape = std::move(fn);
54 return *this;
55 }
56
57 /// Set the native shape to use for unrolling.
60 nativeShape = [=](Operation *) -> std::optional<SmallVector<int64_t>> {
61 return tsShape;
62 };
63 return *this;
64 }
65
66 /// Function that returns the traversal order (in terms of "for loop order",
67 /// i.e. slowest varying dimension to fastest varying dimension) that should
68 /// be used when unrolling the given operation into units of the native vector
69 /// size.
71 std::function<std::optional<SmallVector<int64_t>>(Operation *op)>;
75 traversalOrderCallback = std::move(traversalOrderFn);
76 return *this;
77 }
78
79 /// Unrolling order for ContractionOp. In general, this could be used by
80 /// any other Op, but in practice it isn't and the name reflects that.
81 /// The user is responsible for making sure that the number of indices
82 /// matches the number of loops to be unrolled.
84 /// Controls whether to reverse the unrolling order.
86};
87
88/// Canonicalization of a `vector.contract %a, %b, %c` with row-major matmul
89/// semantics to a contraction with MMT semantics (matrix matrix multiplication
90/// with the RHS transposed). This specific form is meant to have the vector
91/// operands are organized such that the reduction dimension is contiguous.
92/// Example:
93/// ```
94/// vector.contract {indexing_maps = [affine_map<(m, n, k) -> (m, k)>,
95/// affine_map<(m, n, k) -> (n, k)>,
96/// affine_map<(m, n, k) -> (m, n)>],
97/// iterator_types = ["parallel", "parallel", "reduction"],
98/// kind = #vector.kind<add>} %a, %b, %c : ...
99/// ```
100///
101/// The `constraint` predicate is used to decide which `vector.contract` ops
102/// to filter out.
104 RewritePatternSet &patterns,
105 std::function<LogicalResult(vector::ContractionOp)> constraint =
106 [](vector::ContractionOp) { return success(); },
107 PatternBenefit = 1);
108
109/// Collect patterns to convert reduction op to vector.contract and fold
110/// transpose/broadcast ops into the contract.
111///
112/// The new contract keeps only the fast-math flags that both the multiply and
113/// the reduction carry. If `allowFastMathFlagLoss` is false, a multiply and a
114/// reduction with different flags are not converted, so no flag is lost.
116 RewritePatternSet &patterns, PatternBenefit benefit = 1,
117 bool allowFastMathFlagLoss = true);
118
119/// Populate `patterns` with the following patterns.
120///
121/// - VectorTransferFullPartialRewriter
122///
123/// Split a vector.transfer operation into an in-bounds (i.e., no out-of-bounds
124/// masking) fast path and a slow path.
125///
126/// Example (a 2-D vector.transfer_read):
127/// ```
128/// %1 = vector.transfer_read %0[...], %pad : memref<A...>, vector<...>
129/// ```
130/// is transformed into:
131/// ```
132/// %1:3 = scf.if (%inBounds) {
133/// // fast path, direct cast
134/// memref.cast %A: memref<A...> to compatibleMemRefType
135/// scf.yield %view : compatibleMemRefType, index, index
136/// } else {
137/// // slow path, not in-bounds vector.transfer or memref.copy.
138/// memref.cast %alloc: memref<B...> to compatibleMemRefType
139/// scf.yield %4 : compatibleMemRefType, index, index
140// }
141/// %0 = vector.transfer_read %1#0[%1#1, %1#2] {in_bounds = [true ... true]}
142/// ```
143/// where `alloc` is a top of the function alloca'ed buffer of one vector.
144///
145/// Preconditions:
146/// 1. `xferOp.permutation_map()` must be a minor identity map
147/// 2. the rank of the `xferOp.memref()` and the rank of the `xferOp.vector()`
148/// must be equal. This will be relaxed in the future but requires
149/// rank-reducing subviews.
151 RewritePatternSet &patterns, const VectorTransformsOptions &options);
152
153/// Collect a set of patterns to collapse the most inner unit dims in xfer Ops
154///
155/// These patters reduce the rank of the operands of vector transfer ops to
156/// operate on vectors without trailing unit dims. This helps reduce the rank of
157/// the operands, which can be helpful when lowering to dialects that only
158/// support 1D vector type such as LLVM.
160 PatternBenefit benefit = 1);
161
162/// Patterns that remove redundant Vector Ops by re-ordering them with
163/// e.g. elementwise Ops:
164/// ```
165/// %at = vector.transpose %a, [1, 0]: vector<4x2xf32> to vector<2x4xf32>
166/// %bt = vector.transpose %b, [1, 0]: vector<4x2xf32> to vector<2x4xf32>
167/// %r = arith.addf %at, %bt : vector<2x4xf32>
168/// ```
169/// gets converted to:
170/// ```
171/// %0 = arith.addf %a, %b : vector<4x2xf32>
172/// %r = vector.transpose %0, [1, 0] : vector<2x4xf32>
173/// ```
174/// At the moment, these patterns are limited to vector.broadcast and
175/// vector.transpose.
177 PatternBenefit benefit = 1);
178
179/// Patterns that remove redundant Vector Ops by merging them with load/store
180/// ops
181/// ```
182/// vector.load %arg0[%arg1] : memref<?xf32>, vector<4xf32>
183/// vector.extract %0[1] : f32 from vector<4xf32>
184/// ```
185/// Gets converted to:
186/// ```
187/// %c1 = arith.constant 1 : index
188/// %0 = arith.addi %arg1, %c1 overflow<nsw> : index
189/// %1 = memref.load %arg0[%0] : memref<?xf32>
190void populateSinkVectorMemOpsPatterns(RewritePatternSet &patterns,
191 PatternBenefit benefit = 1);
192
193/// Patterns that fold chained vector reductions. These patterns assume that
194/// elementwise operations (e.g., `arith.addf` with vector operands) are
195/// cheaper than vector reduction.
196/// Note that these patterns change the order of reduction which may not always
197/// produce bit-identical results on some floating point inputs.
198///
199/// Example:
200/// ```
201/// %a = vector.reduction <add> %x, %acc
202/// %b = vector.reduction <add> %y, %a
203/// ```
204/// is transformed into:
205/// ```
206/// %a = arith.addf %x, %y
207/// %b = vector.reduction <add> %a, %acc
208/// ```
209void populateChainedVectorReductionFoldingPatterns(RewritePatternSet &patterns,
210 PatternBenefit benefit = 1);
211
212/// Patterns to break down vector reductions into a series of arith reductions
213/// over vector elements. This is intended to be simplify code with reductions
214/// over small vector types and avoid more specialized reduction lowering when
215/// possible.
216///
217/// Example:
218/// ```
219/// %a = vector.reduction <add> %x : vector<2xf32> into f32
220/// ```
221/// is transformed into:
222/// ```
223/// %y = vector.extract %x[0] : f32 from vector<2xf32>
224/// %z = vector.extract %x[1] : f32 from vector<2xf32>
225/// %a = arith.addf %y, %z : f32
226/// ```
227void populateBreakDownVectorReductionPatterns(
228 RewritePatternSet &patterns, unsigned maxNumElementsToExtract = 2,
229 PatternBenefit benefit = 1);
230
231/// Populate `patterns` with the following patterns.
232///
233/// [DecomposeDifferentRankInsertStridedSlice]
234/// ==========================================
235/// RewritePattern for InsertStridedSliceOp where source and destination vectors
236/// have different ranks.
237///
238/// When ranks are different, InsertStridedSlice needs to extract a properly
239/// ranked vector from the destination vector into which to insert. This pattern
240/// only takes care of this extraction part and forwards the rest to
241/// [VectorInsertStridedSliceOpSameRankRewritePattern].
242///
243/// For a k-D source and n-D destination vector (k < n), we emit:
244/// 1. ExtractOp to extract the (unique) (n-1)-D subvector into which to
245/// insert the k-D source.
246/// 2. k-D -> (n-1)-D InsertStridedSlice op
247/// 3. InsertOp that is the reverse of 1.
248///
249/// [DecomposeNDExtractStridedSlice]
250/// ================================
251/// For such cases, we can rewrite it to ExtractOp + lower rank
252/// ExtractStridedSliceOp + InsertOp for the n-D case.
253void populateVectorInsertExtractStridedSliceDecompositionPatterns(
254 RewritePatternSet &patterns, PatternBenefit benefit = 1);
255
256/// Populate `patterns` with a pattern to breaks down 1-D extract_strided_slice
257/// ops into a chain of Extract ops to extract each element from the source, and
258/// then a chain of Insert ops to insert to the target vector.
259///
260/// If `controlFn` is not nullptr, the pattern will only be invoked on ops that
261/// `controlFn` returns true. Otherwise runs on ops.
262void populateVectorExtractStridedSliceToExtractInsertChainPatterns(
263 RewritePatternSet &patterns,
264 std::function<bool(ExtractStridedSliceOp)> controlFn = nullptr,
265 PatternBenefit benefit = 1);
266
267/// Populate `patterns` with a pattern to break down 1-D vector.bitcast ops
268/// based on the destination vector shape. Bitcasts from a lower bitwidth
269/// element type to a higher bitwidth one are extracted from the lower bitwidth
270/// based on the native destination vector shape and inserted based on the ratio
271/// of the bitwidths.
272///
273/// This acts as a last resort way to break down vector.bitcast ops to smaller
274/// vector sizes. Because this pattern composes until it is bitcasting to a
275/// single element of the higher bitwidth, the is an optional control function.
276/// If `controlFn` is not nullptr, the pattern will only apply to ops where
277/// `controlFn` returns true, otherwise applies to all bitcast ops.
278void populateBreakDownVectorBitCastOpPatterns(
279 RewritePatternSet &patterns,
280 std::function<bool(BitCastOp)> controlFn = nullptr,
281 PatternBenefit benefit = 1);
282
283/// Populate `patterns` with the following patterns.
284///
285/// Patterns in populateVectorInsertExtractStridedSliceDecompositionPatterns();
286///
287/// [ConvertSameRankInsertStridedSliceIntoShuffle]
288/// ==============================================
289/// RewritePattern for InsertStridedSliceOp where source and destination vectors
290/// have the same rank. For each outermost index in the slice:
291/// begin end stride
292/// [offset : offset+size*stride : stride]
293/// 1. ExtractOp one (k-1)-D source subvector and one (n-1)-D dest subvector.
294/// 2. InsertStridedSlice (k-1)-D into (n-1)-D
295/// 3. the destination subvector is inserted back in the proper place
296/// 3. InsertOp that is the reverse of 1.
297///
298/// [Convert1DExtractStridedSliceIntoShuffle]
299/// =========================================
300/// For such cases, we can lower it to a ShuffleOp.
301void populateVectorInsertExtractStridedSliceTransforms(
302 RewritePatternSet &patterns, PatternBenefit benefit = 1);
303
304/// Collect a set of pattern to unroll vector operations to a smaller shapes.
305/// `options` structure controls which operations are unrolled and the target
306/// shape.
307/// `op` is unrolled to the `targetShape` as follows, for each of its operands:
308/// 1. the unrolled type `unrolledVectorType` and number of unrolled instances
309/// `numUnrolledInstances` are computed from the `targetShape`. For now it is
310/// assumed the unrolling factors divide the vector sizes.
311/// 2. ExtractStridedSlice are created to break-up the vector operands.
312/// 3. the original op is cloned `numUnrolledInstances` times, once for each
313/// result.
314/// 4. InsertStridedSlice are inserted to re-assemble the slices into the
315/// original vectore shape.
316///
317/// Example:
318///
319/// opA(operand0, operand1) // numUnrolledInstances = 3
320///
321/// operand0 operand1
322/// | |
323/// fork fork
324/// <----------gather all fork ops --------->
325/// /|\ /|\
326/// f00 f01 f02 f10 f11 f12
327/// <---------- clone op 3 times --------->
328/// opA0(f00, f10), opA1(f01, f11), opA2(f02, f12)
329/// \ | /
330/// <-------------------- join ------------------------->
331///
332/// Other local patterns then kick in iteratively (including DCE) and compose
333/// to combine the ExtractStridedSlice/InsertStridedSlice.
334void populateVectorUnrollPatterns(RewritePatternSet &patterns,
335 const UnrollVectorOptions &options,
336 PatternBenefit benefit = 1);
337
338/// Compute indices for a transfer op slice.
339SmallVector<Value> sliceTransferIndices(ArrayRef<int64_t> elementOffsets,
341 AffineMap permutationMap, Location loc,
342 OpBuilder &builder);
343
344/// Unrolls 2 or more dimensional `vector.to_elements` ops by unrolling the
345/// outermost dimension of the operand.
346void populateVectorContractUnrollPatterns(RewritePatternSet &patterns,
347 const UnrollVectorOptions &options,
348 PatternBenefit benefit = 1);
349
350/// Unrolls 2 or more dimensional `vector.to_elements` ops by unrolling the
351/// outermost dimension of the operand.
352void populateVectorToElementsUnrollPatterns(RewritePatternSet &patterns,
353 PatternBenefit benefit = 1);
354
355/// Unrolls 2 or more dimensional `vector.from_elements` ops by unrolling the
356/// outermost dimension.
357void populateVectorFromElementsUnrollPatterns(RewritePatternSet &patterns,
358 PatternBenefit benefit = 1);
359
360/// Collect a set of leading one dimension removal patterns.
361///
362/// These patterns insert vector.shape_cast to remove leading one dimensions
363/// to expose more canonical forms of read/write/insert/extract operations.
364/// With them, there are more chances that we can cancel out extract-insert
365/// pairs or forward write-read pairs.
366void populateCastAwayVectorLeadingOneDimPatterns(RewritePatternSet &patterns,
367 PatternBenefit benefit = 1);
368
369/// Collect a set of one dimension removal patterns.
370///
371/// These patterns insert rank-reducing memref.subview ops to remove one
372/// dimensions. With them, there are more chances that we can avoid
373/// potentially expensive vector.shape_cast operations.
374void populateVectorTransferDropUnitDimsPatterns(RewritePatternSet &patterns,
375 PatternBenefit benefit = 1);
376
377/// Collect a set of patterns that use vector.shape_cast to help fold unit dims.
378///
379/// These patterns use vector.shape_cast to remove unit dims from e.g.
380/// arithmetic operations on Vectors. The newly inserted shape_casts will either
381/// cancel each other out or will be folded away when combined with other
382/// patterns.
383void populateDropUnitDimWithShapeCastPatterns(RewritePatternSet &patterns,
384 PatternBenefit benefit = 1);
385
386/// Collect a set of patterns to flatten n-D vector transfers on contiguous
387/// memref.
388///
389/// These patterns insert memref.collapse_shape + vector.shape_cast patterns
390/// to transform multiple small n-D transfers into a larger 1-D transfer where
391/// the memref contiguity properties allow it.
392///
393/// Flattening is only applied if the bitwidth of the trailing vector dimension
394/// is smaller or equal to `targetVectorBitwidth`.
395void populateFlattenVectorTransferPatterns(
396 RewritePatternSet &patterns,
397 unsigned targetVectorBitwidth = std::numeric_limits<unsigned>::max(),
398 PatternBenefit benefit = 1);
399
400/// Collect a set of patterns that bubble up/down bitcast ops.
401///
402/// These patterns move vector.bitcast ops to be before insert ops or after
403/// extract ops where suitable. With them, bitcast will happen on smaller
404/// vectors and there are more chances to share extract/insert ops.
405void populateBubbleVectorBitCastOpPatterns(RewritePatternSet &patterns,
406 PatternBenefit benefit = 1);
407
408/// These patterns materialize masks for various vector ops such as transfers.
409void populateVectorMaskMaterializationPatterns(RewritePatternSet &patterns,
410 bool force32BitVectorIndices,
411 PatternBenefit benefit = 1);
412
413/// Appends patterns for emulating vector operations over narrow types with ops
414/// over wider types. The `disableAtomicRMW` indicates whether to use a normal
415/// read-modify-write sequence instead of using `memref.generic_atomic_rmw` to
416/// perform subbyte storing. When `assumeAligned` is true, store offsets are
417/// assumed to be aligned to container element boundaries, so a store whose
418/// source vector fills whole container elements is emitted as a simple
419/// bitcast + store without checking the offset. Stores that are not divisible
420/// in size are rejected.
421void populateVectorNarrowTypeEmulationPatterns(
422 const arith::NarrowTypeEmulationConverter &typeConverter,
423 RewritePatternSet &patterns, bool disableAtomicRMW = false,
424 bool assumeAligned = false);
425
426/// Populates patterns for both MeMref flattening and Vector narrow type
427/// emulation.
428///
429/// Patterns for narrow-type-emulation require "flattened" MemRef(s), so this
430/// composite populate* method can be used for narrow-type-emulation for Ops
431/// operating on MemRef(s) that are rank > 2.
432void populateMemRefFlattenAndVectorNarrowTypeEmulationPatterns(
434 RewritePatternSet &patterns);
435
436/// Appends patterns for rewriting vector operations over narrow types with
437/// ops over wider types.
438/// Warning: these patterns currently only work for little endian targets.
439void populateVectorNarrowTypeRewritePatterns(RewritePatternSet &patterns,
440 PatternBenefit benefit = 1);
441
442/// Appends patterns for emulating a sub-byte vector transpose.
443void populateVectorTransposeNarrowTypeRewritePatterns(
444 RewritePatternSet &patterns, PatternBenefit benefit = 1);
445
446/// Initialize `typeConverter` and `conversionTarget` for vector linearization.
447///
448/// Definition: here 'linearization' means converting a single operation with
449/// 1+ vector operand/result of rank>1, into a new single operation whose
450/// vector operands and results are all of rank<=1.
451///
452/// This function registers (1) which operations are legal, and hence should not
453/// be linearized, (2) what the converted types are (rank-1 vectors) and how to
454/// materialze the conversion (with shape_cast)
455///
456/// Note: the set of legal operations can be extended by a user if for example
457/// certain rank>1 vectors are considered valid, by adding additional
458/// dynamically legal ops to `conversionTarget`.
459///
460/// Further note: the choice to use a dialect conversion design for
461/// linearization is to make it easy to reuse generic structural type
462/// conversions for linearizing scf/cf/func operations
463void populateForVectorLinearize(TypeConverter &typeConverter,
464 ConversionTarget &conversionTarget);
465
466/// Extends `conversionTarget` so that ops whose inner-most vector dimension is
467/// at least `targetBitWidth` bits wide (or has `index` elements) stay legal.
468/// Must be called after `populateForVectorLinearize`.
469void populateVectorLinearizeBitWidthTargetRules(
470 ConversionTarget &conversionTarget, unsigned targetBitWidth);
471
472/// Populates `patterns` for ND vector (N >= 2) linearization. This currently
473/// contains patterns for converting ConstantLike, Vectorizable, and
474/// vector::BitCast ops.
475void populateVectorLinearizeBasePatterns(const TypeConverter &,
476 const ConversionTarget &,
477 RewritePatternSet &patterns);
478
479/// Populates `patterns` for linearizing ND (N >= 2) vector operations
480/// to 1D vector shuffle operations.
481void populateVectorLinearizeShuffleLikeOpsPatterns(const TypeConverter &,
482 const ConversionTarget &,
483 RewritePatternSet &patterns);
484
485} // namespace vector
486} // namespace mlir
487
488#endif // MLIR_DIALECT_VECTOR_TRANSFORMS_VECTORREWRITEPATTERNS_H
return success()
static llvm::ManagedStatic< PassManagerOptions > options
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
Converts narrow integer or float types that are not supported by the target hardware to wider types.
void populateVectorReductionToContractPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1, bool allowFastMathFlagLoss=true)
Collect patterns to convert reduction op to vector.contract and fold transpose/broadcast ops into the...
void populateDropInnerMostUnitDimsXferOpPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of patterns to collapse the most inner unit dims in xfer Ops.
void populateVectorContractCanonicalizeMatmulToMMT(RewritePatternSet &patterns, std::function< LogicalResult(vector::ContractionOp)> constraint=[](vector::ContractionOp) { return success();}, PatternBenefit=1)
Canonicalization of a vector.contract a, b, c with row-major matmul semantics to a contraction with M...
void populateSinkVectorOpsPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Patterns that remove redundant Vector Ops by re-ordering them with e.g.
void populateVectorTransferFullPartialPatterns(RewritePatternSet &patterns, const VectorTransformsOptions &options)
Populate patterns with the following patterns.
Include the generated interface declarations.
Options that control the vector unrolling.
std::function< std::optional< SmallVector< int64_t > >(Operation *op)> UnrollTraversalOrderFnType
Function that returns the traversal order (in terms of "for loop order", i.e.
FilterConstraintFnType filterConstraint
Callback function that indicates whether vector unrolling should be attempted on the operation.
bool reverseDefaultTraversalOrder
Controls whether to reverse the unrolling order.
std::function< LogicalResult(Operation *op)> FilterConstraintFnType
NativeShapeFnType nativeShape
Function that returns the shape of the vector to unroll to for a given operation.
UnrollVectorOptions & setFilterConstraint(FilterConstraintFnType constraint)
UnrollVectorOptions & setNativeShape(ArrayRef< int64_t > shape)
Set the native shape to use for unrolling.
UnrollTraversalOrderFnType traversalOrderCallback
SmallVector< int64_t > unrollOrderForContractOp
Unrolling order for ContractionOp.
UnrollVectorOptions & setNativeShapeFn(NativeShapeFnType fn)
UnrollVectorOptions & setUnrollTraversalOrderFn(UnrollTraversalOrderFnType traversalOrderFn)
std::function< std::optional< SmallVector< int64_t > >(Operation *op)> NativeShapeFnType
Structure to control the behavior of vector transform patterns.