MLIR 24.0.0git
SuperVectorize.cpp
Go to the documentation of this file.
1//===- SuperVectorize.cpp - Vectorize Pass Impl ---------------------------===//
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// This file implements vectorization of loops, operations and data types to
10// a target-independent, n-D super-vector abstraction.
11//
12//===----------------------------------------------------------------------===//
13
15
26#include "mlir/IR/IRMapping.h"
27#include "mlir/Pass/Pass.h"
28#include "mlir/Support/LLVM.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/Support/Debug.h"
31#include <optional>
32
33namespace mlir {
34namespace affine {
35#define GEN_PASS_DEF_AFFINEVECTORIZE
36#include "mlir/Dialect/Affine/Transforms/Passes.h.inc"
37} // namespace affine
38} // namespace mlir
39
40using namespace mlir;
41using namespace affine;
42using namespace vector;
43
44///
45/// Implements a high-level vectorization strategy on a Function.
46/// The abstraction used is that of super-vectors, which provide a single,
47/// compact, representation in the vector types, information that is expected
48/// to reduce the impact of the phase ordering problem
49///
50/// Vector granularity:
51/// ===================
52/// This pass is designed to perform vectorization at a super-vector
53/// granularity. A super-vector is loosely defined as a vector type that is a
54/// multiple of a "good" vector size so the HW can efficiently implement a set
55/// of high-level primitives. Multiple is understood along any dimension; e.g.
56/// both vector<16xf32> and vector<2x8xf32> are valid super-vectors for a
57/// vector<8xf32> HW vector. Note that a "good vector size so the HW can
58/// efficiently implement a set of high-level primitives" is not necessarily an
59/// integer multiple of actual hardware registers. We leave details of this
60/// distinction unspecified for now.
61///
62/// Some may prefer the terminology a "tile of HW vectors". In this case, one
63/// should note that super-vectors implement an "always full tile" abstraction.
64/// They guarantee no partial-tile separation is necessary by relying on a
65/// high-level copy-reshape abstraction that we call vector.transfer. This
66/// copy-reshape operations is also responsible for performing layout
67/// transposition if necessary. In the general case this will require a scoped
68/// allocation in some notional local memory.
69///
70/// Whatever the mental model one prefers to use for this abstraction, the key
71/// point is that we burn into a single, compact, representation in the vector
72/// types, information that is expected to reduce the impact of the phase
73/// ordering problem. Indeed, a vector type conveys information that:
74/// 1. the associated loops have dependency semantics that do not prevent
75/// vectorization;
76/// 2. the associate loops have been sliced in chunks of static sizes that are
77/// compatible with vector sizes (i.e. similar to unroll-and-jam);
78/// 3. the inner loops, in the unroll-and-jam analogy of 2, are captured by
79/// the
80/// vector type and no vectorization hampering transformations can be
81/// applied to them anymore;
82/// 4. the underlying memrefs are accessed in some notional contiguous way
83/// that allows loading into vectors with some amount of spatial locality;
84/// In other words, super-vectorization provides a level of separation of
85/// concern by way of opacity to subsequent passes. This has the effect of
86/// encapsulating and propagating vectorization constraints down the list of
87/// passes until we are ready to lower further.
88///
89/// For a particular target, a notion of minimal n-d vector size will be
90/// specified and vectorization targets a multiple of those. In the following
91/// paragraph, let "k ." represent "a multiple of", to be understood as a
92/// multiple in the same dimension (e.g. vector<16 x k . 128> summarizes
93/// vector<16 x 128>, vector<16 x 256>, vector<16 x 1024>, etc).
94///
95/// Some non-exhaustive notable super-vector sizes of interest include:
96/// - CPU: vector<k . HW_vector_size>,
97/// vector<k' . core_count x k . HW_vector_size>,
98/// vector<socket_count x k' . core_count x k . HW_vector_size>;
99/// - GPU: vector<k . warp_size>,
100/// vector<k . warp_size x float2>,
101/// vector<k . warp_size x float4>,
102/// vector<k . warp_size x 4 x 4x 4> (for tensor_core sizes).
103///
104/// Loops and operations are emitted that operate on those super-vector shapes.
105/// Subsequent lowering passes will materialize to actual HW vector sizes. These
106/// passes are expected to be (gradually) more target-specific.
107///
108/// At a high level, a vectorized load in a loop will resemble:
109/// ```mlir
110/// affine.for %i = ? to ? step ? {
111/// %v_a = vector.transfer_read A[%i] : memref<?xf32>, vector<128xf32>
112/// }
113/// ```
114/// It is the responsibility of the implementation of vector.transfer_read to
115/// materialize vector registers from the original scalar memrefs. A later (more
116/// target-dependent) lowering pass will materialize to actual HW vector sizes.
117/// This lowering may be occur at different times:
118/// 1. at the MLIR level into a combination of loops, unrolling, DmaStartOp +
119/// DmaWaitOp + vectorized operations for data transformations and shuffle;
120/// thus opening opportunities for unrolling and pipelining. This is an
121/// instance of library call "whiteboxing"; or
122/// 2. later in the a target-specific lowering pass or hand-written library
123/// call; achieving full separation of concerns. This is an instance of
124/// library call; or
125/// 3. a mix of both, e.g. based on a model.
126/// In the future, these operations will expose a contract to constrain the
127/// search on vectorization patterns and sizes.
128///
129/// Each transfer is emitted under a `vector.mask` that enables the lanes inside
130/// the memref. The examples in this file leave the mask out.
131///
132/// Occurrence of super-vectorization in the compiler flow:
133/// =======================================================
134/// This is an active area of investigation. We start with 2 remarks to position
135/// super-vectorization in the context of existing ongoing work: LLVM VPLAN
136/// and LLVM SLP Vectorizer.
137///
138/// LLVM VPLAN:
139/// -----------
140/// The astute reader may have noticed that in the limit, super-vectorization
141/// can be applied at a similar time and with similar objectives than VPLAN.
142/// For instance, in the case of a traditional, polyhedral compilation-flow (for
143/// instance, the PPCG project uses ISL to provide dependence analysis,
144/// multi-level(scheduling + tiling), lifting footprint to fast memory,
145/// communication synthesis, mapping, register optimizations) and before
146/// unrolling. When vectorization is applied at this *late* level in a typical
147/// polyhedral flow, and is instantiated with actual hardware vector sizes,
148/// super-vectorization is expected to match (or subsume) the type of patterns
149/// that LLVM's VPLAN aims at targeting. The main difference here is that MLIR
150/// is higher level and our implementation should be significantly simpler. Also
151/// note that in this mode, recursive patterns are probably a bit of an overkill
152/// although it is reasonable to expect that mixing a bit of outer loop and
153/// inner loop vectorization + unrolling will provide interesting choices to
154/// MLIR.
155///
156/// LLVM SLP Vectorizer:
157/// --------------------
158/// Super-vectorization however is not meant to be usable in a similar fashion
159/// to the SLP vectorizer. The main difference lies in the information that
160/// both vectorizers use: super-vectorization examines contiguity of memory
161/// references along fastest varying dimensions and loops with recursive nested
162/// patterns capturing imperfectly-nested loop nests; the SLP vectorizer, on
163/// the other hand, performs flat pattern matching inside a single unrolled loop
164/// body and stitches together pieces of load and store operations into full
165/// 1-D vectors. We envision that the SLP vectorizer is a good way to capture
166/// innermost loop, control-flow dependent patterns that super-vectorization may
167/// not be able to capture easily. In other words, super-vectorization does not
168/// aim at replacing the SLP vectorizer and the two solutions are complementary.
169///
170/// Ongoing investigations:
171/// -----------------------
172/// We discuss the following *early* places where super-vectorization is
173/// applicable and touch on the expected benefits and risks . We list the
174/// opportunities in the context of the traditional polyhedral compiler flow
175/// described in PPCG. There are essentially 6 places in the MLIR pass pipeline
176/// we expect to experiment with super-vectorization:
177/// 1. Right after language lowering to MLIR: this is the earliest time where
178/// super-vectorization is expected to be applied. At this level, all the
179/// language/user/library-level annotations are available and can be fully
180/// exploited. Examples include loop-type annotations (such as parallel,
181/// reduction, scan, dependence distance vector, vectorizable) as well as
182/// memory access annotations (such as non-aliasing writes guaranteed,
183/// indirect accesses that are permutations by construction) accesses or
184/// that a particular operation is prescribed atomic by the user. At this
185/// level, anything that enriches what dependence analysis can do should be
186/// aggressively exploited. At this level we are close to having explicit
187/// vector types in the language, except we do not impose that burden on the
188/// programmer/library: we derive information from scalar code + annotations.
189/// 2. After dependence analysis and before polyhedral scheduling: the
190/// information that supports vectorization does not need to be supplied by a
191/// higher level of abstraction. Traditional dependence analysis is available
192/// in MLIR and will be used to drive vectorization and cost models.
193///
194/// Let's pause here and remark that applying super-vectorization as described
195/// in 1. and 2. presents clear opportunities and risks:
196/// - the opportunity is that vectorization is burned in the type system and
197/// is protected from the adverse effect of loop scheduling, tiling, loop
198/// interchange and all passes downstream. Provided that subsequent passes are
199/// able to operate on vector types; the vector shapes, associated loop
200/// iterator properties, alignment, and contiguity of fastest varying
201/// dimensions are preserved until we lower the super-vector types. We expect
202/// this to significantly rein in on the adverse effects of phase ordering.
203/// - the risks are that a. all passes after super-vectorization have to work
204/// on elemental vector types (not that this is always true, wherever
205/// vectorization is applied) and b. that imposing vectorization constraints
206/// too early may be overall detrimental to loop fusion, tiling and other
207/// transformations because the dependence distances are coarsened when
208/// operating on elemental vector types. For this reason, the pattern
209/// profitability analysis should include a component that also captures the
210/// maximal amount of fusion available under a particular pattern. This is
211/// still at the stage of rough ideas but in this context, search is our
212/// friend as the Tensor Comprehensions and auto-TVM contributions
213/// demonstrated previously.
214/// Bottom-line is we do not yet have good answers for the above but aim at
215/// making it easy to answer such questions.
216///
217/// Back to our listing, the last places where early super-vectorization makes
218/// sense are:
219/// 3. right after polyhedral-style scheduling: PLUTO-style algorithms are known
220/// to improve locality, parallelism and be configurable (e.g. max-fuse,
221/// smart-fuse etc). They can also have adverse effects on contiguity
222/// properties that are required for vectorization but the vector.transfer
223/// copy-reshape-pad-transpose abstraction is expected to help recapture
224/// these properties.
225/// 4. right after polyhedral-style scheduling+tiling;
226/// 5. right after scheduling+tiling+rescheduling: points 4 and 5 represent
227/// probably the most promising places because applying tiling achieves a
228/// separation of concerns that allows rescheduling to worry less about
229/// locality and more about parallelism and distribution (e.g. min-fuse).
230///
231/// At these levels the risk-reward looks different: on one hand we probably
232/// lost a good deal of language/user/library-level annotation; on the other
233/// hand we gained parallelism and locality through scheduling and tiling.
234/// However we probably want to ensure tiling is compatible with the
235/// full-tile-only abstraction used in super-vectorization or suffer the
236/// consequences. It is too early to place bets on what will win but we expect
237/// super-vectorization to be the right abstraction to allow exploring at all
238/// these levels. And again, search is our friend.
239///
240/// Lastly, we mention it again here:
241/// 6. as a MLIR-based alternative to VPLAN.
242///
243/// Lowering, unrolling, pipelining:
244/// ================================
245/// TODO: point to the proper places.
246///
247/// Algorithm:
248/// ==========
249/// The algorithm proceeds in a few steps:
250/// 1. defining super-vectorization patterns and matching them on the tree of
251/// AffineForOp. A super-vectorization pattern is defined as a recursive
252/// data structures that matches and captures nested, imperfectly-nested
253/// loops that have a. conformable loop annotations attached (e.g. parallel,
254/// reduction, vectorizable, ...) as well as b. all contiguous load/store
255/// operations along a specified minor dimension (not necessarily the
256/// fastest varying) ;
257/// 2. analyzing those patterns for profitability (TODO: and
258/// interference);
259/// 3. then, for each pattern in order:
260/// a. applying iterative rewriting of the loops and all their nested
261/// operations in topological order. Rewriting is implemented by
262/// coarsening the loops and converting operations and operands to their
263/// vector forms. Processing operations in topological order is relatively
264/// simple due to the structured nature of the control-flow
265/// representation. This order ensures that all the operands of a given
266/// operation have been vectorized before the operation itself in a single
267/// traversal, except for operands defined outside of the loop nest. The
268/// algorithm can convert the following operations to their vector form:
269/// * Affine load and store operations are converted to opaque vector
270/// transfer read and write operations.
271/// * Scalar constant operations/operands are converted to vector
272/// constant operations (splat).
273/// * Uniform operands (only induction variables of loops not mapped to
274/// a vector dimension, or operands defined outside of the loop nest
275/// for now) are broadcasted to a vector.
276/// TODO: Support more uniform cases.
277/// * Affine for operations with 'iter_args' are vectorized by
278/// vectorizing their 'iter_args' operands and results.
279/// TODO: Support more complex loops with divergent lbs and/or ubs.
280/// * The remaining operations in the loop nest are vectorized by
281/// widening their scalar types to vector types.
282/// b. if everything under the root AffineForOp in the current pattern
283/// is vectorized properly, we commit that loop to the IR and remove the
284/// scalar loop. Otherwise, we discard the vectorized loop and keep the
285/// original scalar loop.
286/// c. vectorization is applied on the next pattern in the list. Because
287/// pattern interference avoidance is not yet implemented and that we do
288/// not support further vectorizing an already vector load we need to
289/// re-verify that the pattern is still vectorizable. This is expected to
290/// make cost models more difficult to write and is subject to improvement
291/// in the future.
292///
293/// Choice of loop transformation to support the algorithm:
294/// =======================================================
295/// The choice of loop transformation to apply for coarsening vectorized loops
296/// is still subject to exploratory tradeoffs. In particular, say we want to
297/// vectorize by a factor 128, we want to transform the following input:
298/// ```mlir
299/// affine.for %i = %M to %N {
300/// %a = affine.load %A[%i] : memref<?xf32>
301/// }
302/// ```
303///
304/// Traditionally, one would vectorize late (after scheduling, tiling,
305/// memory promotion etc) say after stripmining (and potentially unrolling in
306/// the case of LLVM's SLP vectorizer):
307/// ```mlir
308/// affine.for %i = floor(%M, 128) to ceil(%N, 128) {
309/// affine.for %ii = max(%M, 128 * %i) to min(%N, 128*%i + 127) {
310/// %a = affine.load %A[%ii] : memref<?xf32>
311/// }
312/// }
313/// ```
314///
315/// Instead, we seek to vectorize early and freeze vector types before
316/// scheduling, so we want to generate a pattern that resembles:
317/// ```mlir
318/// affine.for %i = ? to ? step ? {
319/// %v_a = vector.transfer_read %A[%i] : memref<?xf32>, vector<128xf32>
320/// }
321/// ```
322///
323/// i. simply dividing the lower / upper bounds by 128 creates issues
324/// when representing expressions such as ii + 1 because now we only
325/// have access to original values that have been divided. Additional
326/// information is needed to specify accesses at below-128 granularity;
327/// ii. another alternative is to coarsen the loop step but this may have
328/// consequences on dependence analysis and fusability of loops: fusable
329/// loops probably need to have the same step (because we don't want to
330/// stripmine/unroll to enable fusion).
331/// As a consequence, we choose to represent the coarsening using the loop
332/// step for now and reevaluate in the future. Note that we can renormalize
333/// loop steps later if/when we have evidence that they are problematic.
334///
335/// For the simple strawman example above, vectorizing for a 1-D vector
336/// abstraction of size 128 returns code similar to:
337/// ```mlir
338/// affine.for %i = %M to %N step 128 {
339/// %v_a = vector.transfer_read %A[%i] : memref<?xf32>, vector<128xf32>
340/// }
341/// ```
342///
343/// Unsupported cases, extensions, and work in progress (help welcome :-) ):
344/// ========================================================================
345/// 1. lowering to concrete vector types for various HW;
346/// 2. reduction support for n-D vectorization and non-unit steps;
347/// 3. non-effecting padding during vector.transfer_read and filter during
348/// vector.transfer_write;
349/// 4. misalignment support vector.transfer_read / vector.transfer_write
350/// (hopefully without read-modify-writes);
351/// 5. control-flow support;
352/// 6. cost-models, heuristics and search;
353/// 7. Op implementation, extensions and implication on memref views;
354/// 8. many TODOs left around.
355///
356/// Examples:
357/// =========
358/// Consider the following Function:
359/// ```mlir
360/// func @vector_add_2d(%M : index, %N : index) -> f32 {
361/// %A = alloc (%M, %N) : memref<?x?xf32, 0>
362/// %B = alloc (%M, %N) : memref<?x?xf32, 0>
363/// %C = alloc (%M, %N) : memref<?x?xf32, 0>
364/// %f1 = arith.constant 1.0 : f32
365/// %f2 = arith.constant 2.0 : f32
366/// affine.for %i0 = 0 to %M {
367/// affine.for %i1 = 0 to %N {
368/// // non-scoped %f1
369/// affine.store %f1, %A[%i0, %i1] : memref<?x?xf32, 0>
370/// }
371/// }
372/// affine.for %i2 = 0 to %M {
373/// affine.for %i3 = 0 to %N {
374/// // non-scoped %f2
375/// affine.store %f2, %B[%i2, %i3] : memref<?x?xf32, 0>
376/// }
377/// }
378/// affine.for %i4 = 0 to %M {
379/// affine.for %i5 = 0 to %N {
380/// %a5 = affine.load %A[%i4, %i5] : memref<?x?xf32, 0>
381/// %b5 = affine.load %B[%i4, %i5] : memref<?x?xf32, 0>
382/// %s5 = arith.addf %a5, %b5 : f32
383/// // non-scoped %f1
384/// %s6 = arith.addf %s5, %f1 : f32
385/// // non-scoped %f2
386/// %s7 = arith.addf %s5, %f2 : f32
387/// // diamond dependency.
388/// %s8 = arith.addf %s7, %s6 : f32
389/// affine.store %s8, %C[%i4, %i5] : memref<?x?xf32, 0>
390/// }
391/// }
392/// %c7 = arith.constant 7 : index
393/// %c42 = arith.constant 42 : index
394/// %res = load %C[%c7, %c42] : memref<?x?xf32, 0>
395/// return %res : f32
396/// }
397/// ```
398///
399/// The -affine-super-vectorize pass with the following arguments:
400/// ```
401/// -affine-super-vectorize="virtual-vector-size=256 test-fastest-varying=0"
402/// ```
403///
404/// produces this standard innermost-loop vectorized code:
405/// ```mlir
406/// func @vector_add_2d(%arg0 : index, %arg1 : index) -> f32 {
407/// %0 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
408/// %1 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
409/// %2 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
410/// %cst = arith.constant 1.0 : f32
411/// %cst_0 = arith.constant 2.0 : f32
412/// affine.for %i0 = 0 to %arg0 {
413/// affine.for %i1 = 0 to %arg1 step 256 {
414/// %cst_1 = arith.constant dense<vector<256xf32>, 1.0> :
415/// vector<256xf32>
416/// vector.transfer_write %cst_1, %0[%i0, %i1] :
417/// vector<256xf32>, memref<?x?xf32>
418/// }
419/// }
420/// affine.for %i2 = 0 to %arg0 {
421/// affine.for %i3 = 0 to %arg1 step 256 {
422/// %cst_2 = arith.constant dense<vector<256xf32>, 2.0> :
423/// vector<256xf32>
424/// vector.transfer_write %cst_2, %1[%i2, %i3] :
425/// vector<256xf32>, memref<?x?xf32>
426/// }
427/// }
428/// affine.for %i4 = 0 to %arg0 {
429/// affine.for %i5 = 0 to %arg1 step 256 {
430/// %3 = vector.transfer_read %0[%i4, %i5] :
431/// memref<?x?xf32>, vector<256xf32>
432/// %4 = vector.transfer_read %1[%i4, %i5] :
433/// memref<?x?xf32>, vector<256xf32>
434/// %5 = arith.addf %3, %4 : vector<256xf32>
435/// %cst_3 = arith.constant dense<vector<256xf32>, 1.0> :
436/// vector<256xf32>
437/// %6 = arith.addf %5, %cst_3 : vector<256xf32>
438/// %cst_4 = arith.constant dense<vector<256xf32>, 2.0> :
439/// vector<256xf32>
440/// %7 = arith.addf %5, %cst_4 : vector<256xf32>
441/// %8 = arith.addf %7, %6 : vector<256xf32>
442/// vector.transfer_write %8, %2[%i4, %i5] :
443/// vector<256xf32>, memref<?x?xf32>
444/// }
445/// }
446/// %c7 = arith.constant 7 : index
447/// %c42 = arith.constant 42 : index
448/// %9 = load %2[%c7, %c42] : memref<?x?xf32>
449/// return %9 : f32
450/// }
451/// ```
452///
453/// The -affine-super-vectorize pass with the following arguments:
454/// ```
455/// -affine-super-vectorize="virtual-vector-size=32,256 \
456/// test-fastest-varying=1,0"
457/// ```
458///
459/// produces this more interesting mixed outer-innermost-loop vectorized code:
460/// ```mlir
461/// func @vector_add_2d(%arg0 : index, %arg1 : index) -> f32 {
462/// %0 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
463/// %1 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
464/// %2 = memref.alloc(%arg0, %arg1) : memref<?x?xf32>
465/// %cst = arith.constant 1.0 : f32
466/// %cst_0 = arith.constant 2.0 : f32
467/// affine.for %i0 = 0 to %arg0 step 32 {
468/// affine.for %i1 = 0 to %arg1 step 256 {
469/// %cst_1 = arith.constant dense<vector<32x256xf32>, 1.0> :
470/// vector<32x256xf32>
471/// vector.transfer_write %cst_1, %0[%i0, %i1] :
472/// vector<32x256xf32>, memref<?x?xf32>
473/// }
474/// }
475/// affine.for %i2 = 0 to %arg0 step 32 {
476/// affine.for %i3 = 0 to %arg1 step 256 {
477/// %cst_2 = arith.constant dense<vector<32x256xf32>, 2.0> :
478/// vector<32x256xf32>
479/// vector.transfer_write %cst_2, %1[%i2, %i3] :
480/// vector<32x256xf32>, memref<?x?xf32>
481/// }
482/// }
483/// affine.for %i4 = 0 to %arg0 step 32 {
484/// affine.for %i5 = 0 to %arg1 step 256 {
485/// %3 = vector.transfer_read %0[%i4, %i5] :
486/// memref<?x?xf32> vector<32x256xf32>
487/// %4 = vector.transfer_read %1[%i4, %i5] :
488/// memref<?x?xf32>, vector<32x256xf32>
489/// %5 = arith.addf %3, %4 : vector<32x256xf32>
490/// %cst_3 = arith.constant dense<vector<32x256xf32>, 1.0> :
491/// vector<32x256xf32>
492/// %6 = arith.addf %5, %cst_3 : vector<32x256xf32>
493/// %cst_4 = arith.constant dense<vector<32x256xf32>, 2.0> :
494/// vector<32x256xf32>
495/// %7 = arith.addf %5, %cst_4 : vector<32x256xf32>
496/// %8 = arith.addf %7, %6 : vector<32x256xf32>
497/// vector.transfer_write %8, %2[%i4, %i5] :
498/// vector<32x256xf32>, memref<?x?xf32>
499/// }
500/// }
501/// %c7 = arith.constant 7 : index
502/// %c42 = arith.constant 42 : index
503/// %9 = load %2[%c7, %c42] : memref<?x?xf32>
504/// return %9 : f32
505/// }
506/// ```
507///
508/// Of course, much more intricate n-D imperfectly-nested patterns can be
509/// vectorized too and specified in a fully declarative fashion.
510///
511/// Reduction:
512/// ==========
513/// Vectorizing reduction loops along the reduction dimension is supported if:
514/// - the reduction kind is supported,
515/// - the vectorization is 1-D, and
516/// - the step size of the loop equals to one.
517///
518/// Comparing to the non-vector-dimension case, two additional things are done
519/// during vectorization of such loops:
520/// - The resulting vector returned from the loop is reduced to a scalar using
521/// `vector.reduction`.
522/// - In some cases a mask is applied to the vector yielded at the end of the
523/// loop to prevent garbage values from being written to the accumulator.
524///
525/// Reduction vectorization is switched off by default, it can be enabled by
526/// passing a map from loops to reductions to utility functions, or by passing
527/// `vectorize-reductions=true` to the vectorization pass.
528///
529/// Consider the following example:
530/// ```mlir
531/// func @vecred(%in: memref<512xf32>) -> f32 {
532/// %cst = arith.constant 0.000000e+00 : f32
533/// %sum = affine.for %i = 0 to 500 iter_args(%part_sum = %cst) -> (f32) {
534/// %ld = affine.load %in[%i] : memref<512xf32>
535/// %cos = math.cos %ld : f32
536/// %add = arith.addf %part_sum, %cos : f32
537/// affine.yield %add : f32
538/// }
539/// return %sum : f32
540/// }
541/// ```
542///
543/// The -affine-super-vectorize pass with the following arguments:
544/// ```
545/// -affine-super-vectorize="virtual-vector-size=128 test-fastest-varying=0 \
546/// vectorize-reductions=true"
547/// ```
548/// produces the following output:
549/// ```mlir
550/// #map = affine_map<(d0) -> (-d0 + 500)>
551/// func @vecred(%arg0: memref<512xf32>) -> f32 {
552/// %cst = arith.constant 0.000000e+00 : f32
553/// %cst_0 = arith.constant dense<0.000000e+00> : vector<128xf32>
554/// %0 = affine.for %arg1 = 0 to 500 step 128 iter_args(%arg2 = %cst_0)
555/// -> (vector<128xf32>) {
556/// // %2 is the number of iterations left in the original loop.
557/// %2 = affine.apply #map(%arg1)
558/// %3 = vector.create_mask %2 : vector<128xi1>
559/// %cst_1 = arith.constant 0.000000e+00 : f32
560/// %4 = vector.transfer_read %arg0[%arg1], %cst_1 :
561/// memref<512xf32>, vector<128xf32>
562/// %5 = math.cos %4 : vector<128xf32>
563/// %6 = arith.addf %arg2, %5 : vector<128xf32>
564/// // We filter out the effect of last 12 elements using the mask.
565/// %7 = select %3, %6, %arg2 : vector<128xi1>, vector<128xf32>
566/// affine.yield %7 : vector<128xf32>
567/// }
568/// %1 = vector.reduction <add>, %0 : vector<128xf32> into f32
569/// return %1 : f32
570/// }
571/// ```
572///
573/// Note that because of loop misalignment we needed to apply a mask to prevent
574/// last 12 elements from affecting the final result. The mask is full of ones
575/// in every iteration except for the last one, in which it has the form
576/// `11...100...0` with 116 ones and 12 zeros.
577
578#define DEBUG_TYPE "early-vect"
579
580using llvm::dbgs;
581
582/// Forward declaration.
585 int fastestVaryingMemRefDimension);
586
587/// Creates a vectorization pattern from the command line arguments.
588/// Up to 3-D patterns are supported.
589/// If the command line argument requests a pattern of higher order, returns an
590/// empty pattern list which will conservatively result in no vectorization.
591static std::optional<NestedPattern>
592makePattern(const DenseSet<Operation *> &parallelLoops, int vectorRank,
593 ArrayRef<int64_t> fastestVaryingPattern) {
595 int64_t d0 = fastestVaryingPattern.empty() ? -1 : fastestVaryingPattern[0];
596 int64_t d1 = fastestVaryingPattern.size() < 2 ? -1 : fastestVaryingPattern[1];
597 int64_t d2 = fastestVaryingPattern.size() < 3 ? -1 : fastestVaryingPattern[2];
598 switch (vectorRank) {
599 case 1:
600 return For(isVectorizableLoopPtrFactory(parallelLoops, d0));
601 case 2:
602 return For(isVectorizableLoopPtrFactory(parallelLoops, d0),
603 For(isVectorizableLoopPtrFactory(parallelLoops, d1)));
604 case 3:
605 return For(isVectorizableLoopPtrFactory(parallelLoops, d0),
606 For(isVectorizableLoopPtrFactory(parallelLoops, d1),
607 For(isVectorizableLoopPtrFactory(parallelLoops, d2))));
608 default: {
609 return std::nullopt;
610 }
611 }
612}
613
615 static auto pattern = affine::matcher::Op(
616 llvm::IsaPred<vector::TransferReadOp, vector::TransferWriteOp>);
617 return pattern;
618}
619
620namespace {
621
622/// Base state for the vectorize pass.
623/// Command line arguments are preempted by non-empty pass arguments.
624struct Vectorize : public affine::impl::AffineVectorizeBase<Vectorize> {
625 using Base::Base;
626
627 void runOnOperation() override;
628};
629
630} // namespace
631
632static void vectorizeLoopIfProfitable(Operation *loop, unsigned depthInPattern,
633 unsigned patternDepth,
634 VectorizationStrategy *strategy) {
635 assert(patternDepth > depthInPattern &&
636 "patternDepth is greater than depthInPattern");
637 if (patternDepth - depthInPattern > strategy->vectorSizes.size()) {
638 // Don't vectorize this loop
639 return;
640 }
641 strategy->loopToVectorDim[loop] =
642 strategy->vectorSizes.size() - (patternDepth - depthInPattern);
643}
644
645/// Implements a simple strawman strategy for vectorization.
646/// Given a matched pattern `matches` of depth `patternDepth`, this strategy
647/// greedily assigns the fastest varying dimension ** of the vector ** to the
648/// innermost loop in the pattern.
649/// When coupled with a pattern that looks for the fastest varying dimension in
650/// load/store MemRefs, this creates a generic vectorization strategy that works
651/// for any loop in a hierarchy (outermost, innermost or intermediate).
652///
653/// TODO: In the future we should additionally increase the power of the
654/// profitability analysis along 3 directions:
655/// 1. account for loop extents (both static and parametric + annotations);
656/// 2. account for data layout permutations;
657/// 3. account for impact of vectorization on maximal loop fusion.
658/// Then we can quantify the above to build a cost model and search over
659/// strategies.
660static LogicalResult analyzeProfitability(ArrayRef<NestedMatch> matches,
661 unsigned depthInPattern,
662 unsigned patternDepth,
663 VectorizationStrategy *strategy) {
664 for (auto m : matches) {
665 if (failed(analyzeProfitability(m.getMatchedChildren(), depthInPattern + 1,
666 patternDepth, strategy))) {
667 return failure();
668 }
669 vectorizeLoopIfProfitable(m.getMatchedOperation(), depthInPattern,
670 patternDepth, strategy);
671 }
672 return success();
673}
674
675///// end TODO: Hoist to a VectorizationStrategy.cpp when appropriate /////
676
677namespace {
678
679struct VectorizationState {
680
681 VectorizationState(MLIRContext *context) : builder(context) {}
682
683 /// Registers the vector replacement of a scalar operation and its result
684 /// values. Both operations must have the same number of results.
685 ///
686 /// This utility is used to register the replacement for the vast majority of
687 /// the vectorized operations.
688 ///
689 /// Example:
690 /// * 'replaced': %0 = arith.addf %1, %2 : f32
691 /// * 'replacement': %0 = arith.addf %1, %2 : vector<128xf32>
692 void registerOpVectorReplacement(Operation *replaced, Operation *replacement);
693
694 /// Registers the vector replacement of a scalar value. The replacement
695 /// operation should have a single result, which replaces the scalar value.
696 ///
697 /// This utility is used to register the vector replacement of block arguments
698 /// and operation results which are not directly vectorized (i.e., their
699 /// scalar version still exists after vectorization), like uniforms.
700 ///
701 /// Example:
702 /// * 'replaced': block argument or operation outside of the vectorized
703 /// loop.
704 /// * 'replacement': %0 = vector.broadcast %1 : f32 to vector<128xf32>
705 void registerValueVectorReplacement(Value replaced, Operation *replacement);
706
707 /// Registers the vector replacement of a block argument (e.g., iter_args).
708 ///
709 /// Example:
710 /// * 'replaced': 'iter_arg' block argument.
711 /// * 'replacement': vectorized 'iter_arg' block argument.
712 void registerBlockArgVectorReplacement(BlockArgument replaced,
713 BlockArgument replacement);
714
715 /// Registers the scalar replacement of a scalar value. 'replacement' must be
716 /// scalar.
717 ///
718 /// This utility is used to register the replacement of block arguments
719 /// or affine.apply results that are within the loop be vectorized and will
720 /// continue being scalar within the vector loop.
721 ///
722 /// Example:
723 /// * 'replaced': induction variable of a loop to be vectorized.
724 /// * 'replacement': new induction variable in the new vector loop.
725 void registerValueScalarReplacement(Value replaced, Value replacement);
726
727 /// Registers the scalar replacement of a scalar result returned from a
728 /// reduction loop. 'replacement' must be scalar.
729 ///
730 /// This utility is used to register the replacement for scalar results of
731 /// vectorized reduction loops with iter_args.
732 ///
733 /// Example 2:
734 /// * 'replaced': %0 = affine.for %i = 0 to 512 iter_args(%x = ...) -> (f32)
735 /// * 'replacement': %1 = vector.reduction <add>, %0 : vector<4xf32> into
736 /// f32
737 void registerLoopResultScalarReplacement(Value replaced, Value replacement);
738
739 /// Returns in 'replacedVals' the scalar replacement for values in
740 /// 'inputVals'.
741 void getScalarValueReplacementsFor(ValueRange inputVals,
742 SmallVectorImpl<Value> &replacedVals);
743
744 /// Erases the scalar loop nest after its successful vectorization.
745 void finishVectorizationPattern(AffineForOp rootLoop);
746
747 // Used to build and insert all the new operations created. The insertion
748 // point is preserved and updated along the vectorization process.
749 OpBuilder builder;
750
751 // Maps input scalar operations to their vector counterparts.
752 DenseMap<Operation *, Operation *> opVectorReplacement;
753 // Maps input scalar values to their vector counterparts.
754 IRMapping valueVectorReplacement;
755 // Maps input scalar values to their new scalar counterparts in the vector
756 // loop nest.
757 IRMapping valueScalarReplacement;
758 // Maps results of reduction loops to their new scalar counterparts.
759 DenseMap<Value, Value> loopResultScalarReplacement;
760
761 // Maps the newly created vector loops to their vector dimension.
762 DenseMap<Operation *, unsigned> vecLoopToVecDim;
763
764 // Maps the new vectorized loops to the corresponding vector masks if it is
765 // required.
766 DenseMap<Operation *, Value> vecLoopToMask;
767
768 // The strategy drives which loop to vectorize by which amount.
769 const VectorizationStrategy *strategy = nullptr;
770
771private:
772 /// Internal implementation to map input scalar values to new vector or scalar
773 /// values.
774 void registerValueVectorReplacementImpl(Value replaced, Value replacement);
775};
776
777} // namespace
778
779/// Registers the vector replacement of a scalar operation and its result
780/// values. Both operations must have the same number of results.
781///
782/// This utility is used to register the replacement for the vast majority of
783/// the vectorized operations.
784///
785/// Example:
786/// * 'replaced': %0 = arith.addf %1, %2 : f32
787/// * 'replacement': %0 = arith.addf %1, %2 : vector<128xf32>
788void VectorizationState::registerOpVectorReplacement(Operation *replaced,
790 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ commit vectorized op:\n");
791 LLVM_DEBUG(dbgs() << *replaced << "\n");
792 LLVM_DEBUG(dbgs() << "into\n");
793 LLVM_DEBUG(dbgs() << *replacement << "\n");
794
795 assert(replaced->getNumResults() == replacement->getNumResults() &&
796 "Unexpected replaced and replacement results");
797 assert(opVectorReplacement.count(replaced) == 0 && "already registered");
798 opVectorReplacement[replaced] = replacement;
799
800 for (auto resultTuple :
801 llvm::zip(replaced->getResults(), replacement->getResults()))
802 registerValueVectorReplacementImpl(std::get<0>(resultTuple),
803 std::get<1>(resultTuple));
804}
805
806/// Registers the vector replacement of a scalar value. The replacement
807/// operation should have a single result, which replaces the scalar value.
808///
809/// This utility is used to register the vector replacement of block arguments
810/// and operation results which are not directly vectorized (i.e., their
811/// scalar version still exists after vectorization), like uniforms.
812///
813/// Example:
814/// * 'replaced': block argument or operation result defined outside of the
815/// vectorized loop.
816/// * 'replacement': %0 = vector.broadcast %1 : f32 to vector<128xf32>
817void VectorizationState::registerValueVectorReplacement(
818 Value replaced, Operation *replacement) {
819 assert(replacement->getNumResults() == 1 &&
820 "Expected single-result replacement");
821 registerValueVectorReplacementImpl(replaced, replacement->getResult(0));
822}
823
824/// Registers the vector replacement of a block argument (e.g., iter_args).
825///
826/// Example:
827/// * 'replaced': 'iter_arg' block argument.
828/// * 'replacement': vectorized 'iter_arg' block argument.
829void VectorizationState::registerBlockArgVectorReplacement(
830 BlockArgument replaced, BlockArgument replacement) {
831 registerValueVectorReplacementImpl(replaced, replacement);
832}
833
834void VectorizationState::registerValueVectorReplacementImpl(Value replaced,
835 Value replacement) {
836 assert(!valueVectorReplacement.contains(replaced) &&
837 "Vector replacement already registered");
838 assert(isa<VectorType>(replacement.getType()) &&
839 "Expected vector type in vector replacement");
840 valueVectorReplacement.map(replaced, replacement);
841}
842
843/// Registers the scalar replacement of a scalar value. 'replacement' must be
844/// scalar.
845///
846/// This utility is used to register the replacement of block arguments
847/// or affine.apply results that are within the loop be vectorized and will
848/// continue being scalar within the vector loop.
849///
850/// Example:
851/// * 'replaced': induction variable of a loop to be vectorized.
852/// * 'replacement': new induction variable in the new vector loop.
853void VectorizationState::registerValueScalarReplacement(Value replaced,
854 Value replacement) {
855 assert(!valueScalarReplacement.contains(replaced) &&
856 "Scalar value replacement already registered");
857 assert(!isa<VectorType>(replacement.getType()) &&
858 "Expected scalar type in scalar replacement");
859 valueScalarReplacement.map(replaced, replacement);
860}
861
862/// Registers the scalar replacement of a scalar result returned from a
863/// reduction loop. 'replacement' must be scalar.
864///
865/// This utility is used to register the replacement for scalar results of
866/// vectorized reduction loops with iter_args.
867///
868/// Example 2:
869/// * 'replaced': %0 = affine.for %i = 0 to 512 iter_args(%x = ...) -> (f32)
870/// * 'replacement': %1 = vector.reduction <add>, %0 : vector<4xf32> into f32
871void VectorizationState::registerLoopResultScalarReplacement(
872 Value replaced, Value replacement) {
873 assert(isa<AffineForOp>(replaced.getDefiningOp()));
874 assert(loopResultScalarReplacement.count(replaced) == 0 &&
875 "already registered");
876 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ will replace a result of the loop "
877 "with scalar: "
878 << replacement);
879 loopResultScalarReplacement[replaced] = replacement;
880}
881
882/// Returns in 'replacedVals' the scalar replacement for values in 'inputVals'.
883void VectorizationState::getScalarValueReplacementsFor(
884 ValueRange inputVals, SmallVectorImpl<Value> &replacedVals) {
885 for (Value inputVal : inputVals)
886 replacedVals.push_back(valueScalarReplacement.lookupOrDefault(inputVal));
887}
888
889/// Erases a loop nest, including all its nested operations.
890static void eraseLoopNest(AffineForOp forOp) {
891 LLVM_DEBUG(dbgs() << "[early-vect]+++++ erasing:\n" << forOp << "\n");
892 forOp.erase();
893}
894
895/// Recursively erases the users of the results of 'op'.
896static void eraseUsers(Operation *op) {
897 while (!op->use_empty()) {
898 Operation *user = *op->user_begin();
899 eraseUsers(user);
900 LLVM_DEBUG(dbgs() << "[early-vect]+++++ erasing user:\n" << *user << "\n");
901 user->erase();
902 }
903}
904
905/// Erases the scalar loop nest after its successful vectorization.
906void VectorizationState::finishVectorizationPattern(AffineForOp rootLoop) {
907 LLVM_DEBUG(dbgs() << "\n[early-vect] Finalizing vectorization\n");
908 eraseLoopNest(rootLoop);
909}
910
911// Apply 'map' with 'mapOperands' returning resulting values in 'results'.
913 ValueRange mapOperands,
914 VectorizationState &state,
915 SmallVectorImpl<Value> &results) {
916 for (auto resultExpr : map.getResults()) {
917 auto singleResMap =
918 AffineMap::get(map.getNumDims(), map.getNumSymbols(), resultExpr);
919 auto afOp = AffineApplyOp::create(state.builder, op->getLoc(), singleResMap,
920 mapOperands);
921 results.push_back(afOp);
922 }
923}
924
925/// Returns a FilterFunctionType that can be used in NestedPattern to match a
926/// loop whose underlying load/store accesses are either invariant or all
927// varying along the `fastestVaryingMemRefDimension`.
930 int fastestVaryingMemRefDimension) {
931 return [&parallelLoops, fastestVaryingMemRefDimension](Operation &forOp) {
932 auto loop = cast<AffineForOp>(forOp);
933 if (!parallelLoops.contains(loop))
934 return false;
935 int memRefDim = -1;
936 auto vectorizableBody =
938 if (!vectorizableBody)
939 return false;
940 return memRefDim == -1 || fastestVaryingMemRefDimension == -1 ||
941 memRefDim == fastestVaryingMemRefDimension;
942 };
943}
944
945/// Returns the vector type resulting from applying the provided vectorization
946/// strategy on the scalar type.
947static VectorType getVectorType(Type scalarTy,
948 const VectorizationStrategy *strategy) {
949 assert(!isa<VectorType>(scalarTy) && "Expected scalar type");
950 return VectorType::get(strategy->vectorSizes, scalarTy);
951}
952
953/// Tries to transform a scalar constant into a vector constant. Returns the
954/// vector constant if the scalar type is valid vector element type. Returns
955/// nullptr, otherwise.
956static arith::ConstantOp vectorizeConstant(arith::ConstantOp constOp,
957 VectorizationState &state) {
958 Type scalarTy = constOp.getType();
959 if (!VectorType::isValidElementType(scalarTy))
960 return nullptr;
961
962 auto vecTy = getVectorType(scalarTy, state.strategy);
963 auto vecAttr = DenseElementsAttr::get(vecTy, constOp.getValue());
964
965 OpBuilder::InsertionGuard guard(state.builder);
966 Operation *parentOp = state.builder.getInsertionBlock()->getParentOp();
967 // Find the innermost vectorized ancestor loop to insert the vector constant.
968 while (parentOp && !state.vecLoopToVecDim.count(parentOp))
969 parentOp = parentOp->getParentOp();
970 assert(parentOp && state.vecLoopToVecDim.count(parentOp) &&
971 isa<AffineForOp>(parentOp) && "Expected a vectorized for op");
972 auto vecForOp = cast<AffineForOp>(parentOp);
973 state.builder.setInsertionPointToStart(vecForOp.getBody());
974 auto newConstOp =
975 arith::ConstantOp::create(state.builder, constOp.getLoc(), vecAttr);
976
977 // Register vector replacement for future uses in the scope.
978 state.registerOpVectorReplacement(constOp, newConstOp);
979
980 // Index-typed constants are also used as scalar indices in vectorized memory
981 // operations (e.g., as operands to vector.transfer_read/write). Register a
982 // scalar replacement so that getScalarValueReplacementsFor can find a live
983 // value in the vectorized loop body instead of falling back to the original
984 // constant, which will be erased along with the scalar loop.
985 if (isa<IndexType>(scalarTy)) {
986 auto scalarConstOp = arith::ConstantOp::create(
987 state.builder, constOp.getLoc(), constOp.getValue());
988 state.registerValueScalarReplacement(constOp.getResult(),
989 scalarConstOp.getResult());
990 }
991
992 return newConstOp;
993}
994
995/// We have no need to vectorize affine.apply. However, we still need to
996/// generate it and replace the operands with values in valueScalarReplacement.
997static Operation *vectorizeAffineApplyOp(AffineApplyOp applyOp,
998 VectorizationState &state) {
999 SmallVector<Value, 8> updatedOperands;
1000 for (Value operand : applyOp.getOperands()) {
1001 if (state.valueVectorReplacement.contains(operand)) {
1002 LLVM_DEBUG(
1003 dbgs() << "\n[early-vect]+++++ affine.apply on vector operand\n");
1004 return nullptr;
1005 }
1006 Value updatedOperand = state.valueScalarReplacement.lookupOrNull(operand);
1007 if (!updatedOperand)
1008 updatedOperand = operand;
1009 updatedOperands.push_back(updatedOperand);
1010 }
1011
1012 auto newApplyOp = AffineApplyOp::create(
1013 state.builder, applyOp.getLoc(), applyOp.getAffineMap(), updatedOperands);
1014
1015 // Register the new affine.apply result.
1016 state.registerValueScalarReplacement(applyOp.getResult(),
1017 newApplyOp.getResult());
1018 return newApplyOp;
1019}
1020
1021/// Creates a constant vector filled with the neutral elements of the given
1022/// reduction. The scalar type of vector elements will be taken from
1023/// `oldOperand`.
1024static arith::ConstantOp createInitialVector(arith::AtomicRMWKind reductionKind,
1025 Value oldOperand,
1026 VectorizationState &state) {
1027 Type scalarTy = oldOperand.getType();
1028 if (!VectorType::isValidElementType(scalarTy))
1029 return nullptr;
1030
1031 Attribute valueAttr = getIdentityValueAttr(
1032 reductionKind, scalarTy, state.builder, oldOperand.getLoc());
1033 auto vecTy = getVectorType(scalarTy, state.strategy);
1034 auto vecAttr = DenseElementsAttr::get(vecTy, valueAttr);
1035 auto newConstOp =
1036 arith::ConstantOp::create(state.builder, oldOperand.getLoc(), vecAttr);
1037
1038 return newConstOp;
1039}
1040
1041/// Creates a mask used to filter out garbage elements in the last iteration
1042/// of unaligned loops. If a mask is not required then `nullptr` is returned.
1043/// The mask will be a vector of booleans representing meaningful vector
1044/// elements in the current iteration. It is filled with ones for each iteration
1045/// except for the last one, where it has the form `11...100...0` with the
1046/// number of ones equal to the number of meaningful elements (i.e. the number
1047/// of iterations that would be left in the original loop).
1048static Value createMask(AffineForOp vecForOp, VectorizationState &state) {
1049 assert(state.strategy->vectorSizes.size() == 1 &&
1050 "Creating a mask non-1-D vectors is not supported.");
1051 assert(vecForOp.getStep() == state.strategy->vectorSizes[0] &&
1052 "Creating a mask for loops with non-unit original step size is not "
1053 "supported.");
1054
1055 // Check if we have already created the mask.
1056 if (Value mask = state.vecLoopToMask.lookup(vecForOp))
1057 return mask;
1058
1059 // If the loop has constant bounds and the original number of iterations is
1060 // divisable by the vector size then we don't need a mask.
1061 if (vecForOp.hasConstantBounds()) {
1062 int64_t originalTripCount =
1063 vecForOp.getConstantUpperBound() - vecForOp.getConstantLowerBound();
1064 if (originalTripCount % vecForOp.getStepAsInt() == 0)
1065 return nullptr;
1066 }
1067
1068 OpBuilder::InsertionGuard guard(state.builder);
1069 state.builder.setInsertionPointToStart(vecForOp.getBody());
1070
1071 // We generate the mask using the `vector.create_mask` operation which accepts
1072 // the number of meaningful elements (i.e. the length of the prefix of 1s).
1073 // To compute the number of meaningful elements we subtract the current value
1074 // of the iteration variable from the upper bound of the loop. Example:
1075 //
1076 // // 500 is the upper bound of the loop
1077 // #map = affine_map<(d0) -> (500 - d0)>
1078 // %elems_left = affine.apply #map(%iv)
1079 // %mask = vector.create_mask %elems_left : vector<128xi1>
1080
1081 Location loc = vecForOp.getLoc();
1082
1083 // First we get the upper bound of the loop using `affine.apply` or
1084 // `affine.min`.
1085 AffineMap ubMap = vecForOp.getUpperBoundMap();
1086 Value ub;
1087 if (ubMap.getNumResults() == 1)
1088 ub = AffineApplyOp::create(state.builder, loc, vecForOp.getUpperBoundMap(),
1089 vecForOp.getUpperBoundOperands());
1090 else
1091 ub = AffineMinOp::create(state.builder, loc, vecForOp.getUpperBoundMap(),
1092 vecForOp.getUpperBoundOperands());
1093 // Then we compute the number of (original) iterations left in the loop.
1094 AffineExpr subExpr =
1095 state.builder.getAffineDimExpr(0) - state.builder.getAffineDimExpr(1);
1096 Value itersLeft =
1097 makeComposedAffineApply(state.builder, loc, AffineMap::get(2, 0, subExpr),
1098 {ub, vecForOp.getInductionVar()});
1099 // If the affine maps were successfully composed then `ub` is unneeded.
1100 if (ub.use_empty())
1101 ub.getDefiningOp()->erase();
1102 // Finally we create the mask.
1103 Type maskTy = VectorType::get(state.strategy->vectorSizes,
1104 state.builder.getIntegerType(1));
1105 Value mask =
1106 vector::CreateMaskOp::create(state.builder, loc, maskTy, itersLeft);
1107
1108 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ creating a mask:\n"
1109 << itersLeft << "\n"
1110 << mask << "\n");
1111
1112 state.vecLoopToMask[vecForOp] = mask;
1113 return mask;
1114}
1115
1116/// Returns true if the provided value is vector uniform given the vectorization
1117/// strategy.
1118// TODO: For now, only values that are induction variables of loops not in
1119// `loopToVectorDim` or invariants to all the loops in the vectorization
1120// strategy are considered vector uniforms.
1121static bool isUniformDefinition(Value value,
1122 const VectorizationStrategy *strategy) {
1123 AffineForOp forOp = getForInductionVarOwner(value);
1124 if (forOp && strategy->loopToVectorDim.count(forOp) == 0)
1125 return true;
1126
1127 for (auto loopToDim : strategy->loopToVectorDim) {
1128 auto loop = cast<AffineForOp>(loopToDim.first);
1129 if (!loop.isDefinedOutsideOfLoop(value))
1130 return false;
1131 }
1132
1133 return value.getType().isIntOrIndexOrFloat();
1134}
1135
1136/// Generates a broadcast op for the provided uniform value using the
1137/// vectorization strategy in 'state'.
1139 VectorizationState &state) {
1140 OpBuilder::InsertionGuard guard(state.builder);
1141 Value uniformScalarRepl =
1142 state.valueScalarReplacement.lookupOrDefault(uniformVal);
1143 state.builder.setInsertionPointAfterValue(uniformScalarRepl);
1144
1145 auto vectorTy = getVectorType(uniformVal.getType(), state.strategy);
1146 auto bcastOp = BroadcastOp::create(state.builder, uniformVal.getLoc(),
1147 vectorTy, uniformScalarRepl);
1148 state.registerValueVectorReplacement(uniformVal, bcastOp);
1149 return bcastOp;
1150}
1151
1152/// Tries to vectorize a given `operand` by applying the following logic:
1153/// 1. if the defining operation has been already vectorized, `operand` is
1154/// already in the proper vector form;
1155/// 2. if the `operand` is a constant, returns the vectorized form of the
1156/// constant;
1157/// 3. if the `operand` is uniform, returns a vector broadcast of the `op`;
1158/// 4. otherwise, the vectorization of `operand` is not supported.
1159/// Newly created vector operations are registered in `state` as replacement
1160/// for their scalar counterparts.
1161/// In particular this logic captures some of the use cases where definitions
1162/// that are not scoped under the current pattern are needed to vectorize.
1163/// One such example is top level function constants that need to be splatted.
1164///
1165/// Returns an operand that has been vectorized to match `state`'s strategy if
1166/// vectorization is possible with the above logic. Returns nullptr otherwise.
1167///
1168/// TODO: handle more complex cases.
1169static Value vectorizeOperand(Value operand, VectorizationState &state) {
1170 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ vectorize operand: " << operand);
1171 // If this value is already vectorized, we are done.
1172 if (Value vecRepl = state.valueVectorReplacement.lookupOrNull(operand)) {
1173 LLVM_DEBUG(dbgs() << " -> already vectorized: " << vecRepl);
1174 return vecRepl;
1175 }
1176
1177 // An vector operand that is not in the replacement map should never reach
1178 // this point. Reaching this point could mean that the code was already
1179 // vectorized and we shouldn't try to vectorize already vectorized code.
1180 assert(!isa<VectorType>(operand.getType()) &&
1181 "Vector op not found in replacement map");
1182
1183 // Vectorize constant.
1184 if (auto constOp = operand.getDefiningOp<arith::ConstantOp>()) {
1185 auto vecConstant = vectorizeConstant(constOp, state);
1186 LLVM_DEBUG(dbgs() << "-> constant: " << vecConstant);
1187 return vecConstant.getResult();
1188 }
1189
1190 // Vectorize uniform values.
1191 if (isUniformDefinition(operand, state.strategy)) {
1192 Operation *vecUniform = vectorizeUniform(operand, state);
1193 LLVM_DEBUG(dbgs() << "-> uniform: " << *vecUniform);
1194 return vecUniform->getResult(0);
1195 }
1196
1197 // Check for unsupported block argument scenarios. A supported block argument
1198 // should have been vectorized already.
1199 if (!operand.getDefiningOp())
1200 LLVM_DEBUG(dbgs() << "-> unsupported block argument\n");
1201 else
1202 // Generic unsupported case.
1203 LLVM_DEBUG(dbgs() << "-> non-vectorizable\n");
1204
1205 return nullptr;
1206}
1207
1208/// Returns true if any vectorized loop IV drives more than one index.
1211 const DenseMap<Operation *, unsigned> &loopToVectorDim) {
1212 for (auto &kvp : loopToVectorDim) {
1213 AffineForOp forOp = cast<AffineForOp>(kvp.first);
1214 // Find which indices are invariant w.r.t. this loop IV.
1215 llvm::DenseSet<Value> invariants =
1216 affine::getInvariantAccesses(forOp.getInductionVar(), indices);
1217 // Count how many vary (i.e. are not invariant).
1218 unsigned nonInvariant = 0;
1219 for (Value idx : indices) {
1220 if (invariants.count(idx))
1221 continue;
1222
1223 if (++nonInvariant > 1) {
1224 LLVM_DEBUG(dbgs() << "[early‑vect] Bail out: IV "
1225 << forOp.getInductionVar() << " drives "
1226 << nonInvariant << " indices\n");
1227 return true;
1228 }
1229 }
1230 }
1231 return false;
1232}
1233
1234/// Vectorizes an affine load with the vectorization strategy in 'state' by
1235/// generating a 'vector.transfer_read' op with the proper permutation map
1236/// inferred from the indices of the load. The new 'vector.transfer_read' is
1237/// registered as replacement of the scalar load. Returns the newly created
1238/// 'vector.transfer_read' if vectorization was successful. Returns nullptr,
1239/// otherwise.
1240static Operation *vectorizeAffineLoad(AffineLoadOp loadOp,
1241 VectorizationState &state) {
1242 MemRefType memRefType = loadOp.getMemRefType();
1243 Type elementType = memRefType.getElementType();
1244 auto vectorType = VectorType::get(state.strategy->vectorSizes, elementType);
1245
1246 // Replace map operands with operands from the vector loop nest.
1247 SmallVector<Value, 8> mapOperands;
1248 state.getScalarValueReplacementsFor(loadOp.getMapOperands(), mapOperands);
1249
1250 // Compute indices for the transfer op. AffineApplyOp's may be generated.
1252 indices.reserve(memRefType.getRank());
1253 if (loadOp.getAffineMap() !=
1254 state.builder.getMultiDimIdentityMap(memRefType.getRank())) {
1255 // Check the operand in loadOp affine map does not come from AffineApplyOp.
1256 for (auto op : mapOperands) {
1257 if (op.getDefiningOp<AffineApplyOp>())
1258 return nullptr;
1259 }
1260 computeMemoryOpIndices(loadOp, loadOp.getAffineMap(), mapOperands, state,
1261 indices);
1262 } else {
1263 indices.append(mapOperands.begin(), mapOperands.end());
1264 }
1265
1266 if (isIVMappedToMultipleIndices(indices, state.vecLoopToVecDim))
1267 return nullptr;
1268
1269 // Compute permutation map using the information of new vector loops.
1270 auto permutationMap = makePermutationMap(state.builder.getInsertionBlock(),
1271 indices, state.vecLoopToVecDim);
1272 if (!permutationMap) {
1273 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ can't compute permutationMap\n");
1274 return nullptr;
1275 }
1276 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ permutationMap: ");
1277 LLVM_DEBUG(permutationMap.print(dbgs()));
1278
1279 Value transferVal = createReadOrMaskedRead(
1280 state.builder, loadOp.getLoc(), loadOp.getMemRef(), vectorType,
1281 /*padValue=*/std::nullopt, /*useInBoundsInsteadOfMasking=*/false, indices,
1282 permutationMap);
1283 Operation *transfer = transferVal.getDefiningOp();
1284
1285 // Register replacement for future uses in the scope.
1286 state.registerOpVectorReplacement(loadOp, transfer);
1287 return transfer;
1288}
1289
1290/// Vectorizes an affine store with the vectorization strategy in 'state' by
1291/// generating a 'vector.transfer_write' op with the proper permutation map
1292/// inferred from the indices of the store. The new 'vector.transfer_store' is
1293/// registered as replacement of the scalar load. Returns the newly created
1294/// 'vector.transfer_write' if vectorization was successful. Returns nullptr,
1295/// otherwise.
1296static Operation *vectorizeAffineStore(AffineStoreOp storeOp,
1297 VectorizationState &state) {
1298 MemRefType memRefType = storeOp.getMemRefType();
1299 Value vectorValue = vectorizeOperand(storeOp.getValueToStore(), state);
1300 if (!vectorValue)
1301 return nullptr;
1302
1303 // Replace map operands with operands from the vector loop nest.
1304 SmallVector<Value, 8> mapOperands;
1305 state.getScalarValueReplacementsFor(storeOp.getMapOperands(), mapOperands);
1306
1307 // Compute indices for the transfer op. AffineApplyOp's may be generated.
1309 indices.reserve(memRefType.getRank());
1310 if (storeOp.getAffineMap() !=
1311 state.builder.getMultiDimIdentityMap(memRefType.getRank()))
1312 computeMemoryOpIndices(storeOp, storeOp.getAffineMap(), mapOperands, state,
1313 indices);
1314 else
1315 indices.append(mapOperands.begin(), mapOperands.end());
1316
1317 if (isIVMappedToMultipleIndices(indices, state.vecLoopToVecDim))
1318 return nullptr;
1319
1320 // Compute permutation map using the information of new vector loops.
1321 auto permutationMap = makePermutationMap(state.builder.getInsertionBlock(),
1322 indices, state.vecLoopToVecDim);
1323 if (!permutationMap)
1324 return nullptr;
1325 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ permutationMap: ");
1326 LLVM_DEBUG(permutationMap.print(dbgs()));
1327
1328 // A transfer_write with a broadcast dimension (constant expr in the
1329 // permutation map) is invalid. Bail out to avoid producing invalid IR.
1330 if (llvm::any_of(permutationMap.getResults(),
1331 llvm::IsaPred<AffineConstantExpr>)) {
1332 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ store permutation map has "
1333 "broadcast dims, bailing out\n");
1334 return nullptr;
1335 }
1336
1338 state.builder, storeOp.getLoc(), vectorValue, storeOp.getMemRef(),
1339 SmallVector<Value>(indices.begin(), indices.end()),
1340 /*useInBoundsInsteadOfMasking=*/false, permutationMap);
1341 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ vectorized store: " << *transfer);
1342
1343 // Register replacement for future uses in the scope.
1344 state.registerOpVectorReplacement(storeOp, transfer);
1345 return transfer;
1346}
1347
1348/// Returns true if `value` is a constant equal to the neutral element of the
1349/// given vectorizable reduction.
1350static bool isNeutralElementConst(arith::AtomicRMWKind reductionKind,
1351 Value value, VectorizationState &state) {
1352 Type scalarTy = value.getType();
1353 if (!VectorType::isValidElementType(scalarTy))
1354 return false;
1355 Attribute valueAttr = getIdentityValueAttr(reductionKind, scalarTy,
1356 state.builder, value.getLoc());
1357 if (auto constOp = value.getDefiningOp<arith::ConstantOp>())
1358 return constOp.getValue() == valueAttr;
1359 return false;
1360}
1361
1362/// Vectorizes a loop with the vectorization strategy in 'state'. A new loop is
1363/// created and registered as replacement for the scalar loop. The builder's
1364/// insertion point is set to the new loop's body so that subsequent vectorized
1365/// operations are inserted into the new loop. If the loop is a vector
1366/// dimension, the step of the newly created loop will reflect the vectorization
1367/// factor used to vectorized that dimension.
1368static Operation *vectorizeAffineForOp(AffineForOp forOp,
1369 VectorizationState &state) {
1370 const VectorizationStrategy &strategy = *state.strategy;
1371 auto loopToVecDimIt = strategy.loopToVectorDim.find(forOp);
1372 bool isLoopVecDim = loopToVecDimIt != strategy.loopToVectorDim.end();
1373
1374 // TODO: Vectorization of reduction loops is not supported for non-unit steps.
1375 if (isLoopVecDim && forOp.getNumIterOperands() > 0 && forOp.getStep() != 1) {
1376 LLVM_DEBUG(
1377 dbgs()
1378 << "\n[early-vect]+++++ unsupported step size for reduction loop: "
1379 << forOp.getStep() << "\n");
1380 return nullptr;
1381 }
1382
1383 // If we are vectorizing a vector dimension, compute a new step for the new
1384 // vectorized loop using the vectorization factor for the vector dimension.
1385 // Otherwise, propagate the step of the scalar loop.
1386 unsigned newStep;
1387 if (isLoopVecDim) {
1388 unsigned vectorDim = loopToVecDimIt->second;
1389 assert(vectorDim < strategy.vectorSizes.size() && "vector dim overflow");
1390 int64_t forOpVecFactor = strategy.vectorSizes[vectorDim];
1391 newStep = forOp.getStepAsInt() * forOpVecFactor;
1392 } else {
1393 newStep = forOp.getStepAsInt();
1394 }
1395
1396 // Get information about reduction kinds.
1397 ArrayRef<LoopReduction> reductions;
1398 if (isLoopVecDim && forOp.getNumIterOperands() > 0) {
1399 auto it = strategy.reductionLoops.find(forOp);
1400 assert(it != strategy.reductionLoops.end() &&
1401 "Reduction descriptors not found when vectorizing a reduction loop");
1402 reductions = it->second;
1403 assert(reductions.size() == forOp.getNumIterOperands() &&
1404 "The size of reductions array must match the number of iter_args");
1405 }
1406
1407 // Vectorize 'iter_args'.
1408 SmallVector<Value, 8> vecIterOperands;
1409 if (!isLoopVecDim) {
1410 for (auto operand : forOp.getInits())
1411 vecIterOperands.push_back(vectorizeOperand(operand, state));
1412 } else {
1413 // For reduction loops we need to pass a vector of neutral elements as an
1414 // initial value of the accumulator. We will add the original initial value
1415 // later.
1416 for (auto redAndOperand : llvm::zip(reductions, forOp.getInits())) {
1417 vecIterOperands.push_back(createInitialVector(
1418 std::get<0>(redAndOperand).kind, std::get<1>(redAndOperand), state));
1419 }
1420 }
1421
1422 // Replace bound operands with their scalar replacements. This is required
1423 // when the bounds reference an outer loop's induction variable, which will
1424 // be replaced (and eventually erased) once the scalar loop nest is removed.
1425 SmallVector<Value, 8> lbOperands, ubOperands;
1426 state.getScalarValueReplacementsFor(forOp.getLowerBoundOperands(),
1427 lbOperands);
1428 state.getScalarValueReplacementsFor(forOp.getUpperBoundOperands(),
1429 ubOperands);
1430 auto vecForOp = AffineForOp::create(
1431 state.builder, forOp.getLoc(), lbOperands, forOp.getLowerBoundMap(),
1432 ubOperands, forOp.getUpperBoundMap(), newStep, vecIterOperands,
1433 /*bodyBuilder=*/[](OpBuilder &, Location, Value, ValueRange) {
1434 // Make sure we don't create a default terminator in the loop body as
1435 // the proper terminator will be added during vectorization.
1436 });
1437
1438 // Register loop-related replacements:
1439 // 1) The new vectorized loop is registered as vector replacement of the
1440 // scalar loop.
1441 // 2) The new iv of the vectorized loop is registered as scalar replacement
1442 // since a scalar copy of the iv will prevail in the vectorized loop.
1443 // TODO: A vector replacement will also be added in the future when
1444 // vectorization of linear ops is supported.
1445 // 3) The new 'iter_args' region arguments are registered as vector
1446 // replacements since they have been vectorized.
1447 // 4) If the loop performs a reduction along the vector dimension, a
1448 // `vector.reduction` or similar op is inserted for each resulting value
1449 // of the loop and its scalar value replaces the corresponding scalar
1450 // result of the loop.
1451 state.registerOpVectorReplacement(forOp, vecForOp);
1452 state.registerValueScalarReplacement(forOp.getInductionVar(),
1453 vecForOp.getInductionVar());
1454 for (auto iterTuple :
1455 llvm ::zip(forOp.getRegionIterArgs(), vecForOp.getRegionIterArgs()))
1456 state.registerBlockArgVectorReplacement(std::get<0>(iterTuple),
1457 std::get<1>(iterTuple));
1458
1459 if (isLoopVecDim) {
1460 for (unsigned i = 0; i < vecForOp.getNumIterOperands(); ++i) {
1461 // First, we reduce the vector returned from the loop into a scalar.
1462 Value reducedRes =
1463 getVectorReductionOp(reductions[i].kind, state.builder,
1464 vecForOp.getLoc(), vecForOp.getResult(i));
1465 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ creating a vector reduction: "
1466 << reducedRes);
1467 // Then we combine it with the original (scalar) initial value unless it
1468 // is equal to the neutral element of the reduction.
1469 Value origInit = forOp.getOperand(forOp.getNumControlOperands() + i);
1470 Value finalRes = reducedRes;
1471 if (!isNeutralElementConst(reductions[i].kind, origInit, state))
1472 finalRes =
1473 arith::getReductionOp(reductions[i].kind, state.builder,
1474 reducedRes.getLoc(), reducedRes, origInit);
1475 state.registerLoopResultScalarReplacement(forOp.getResult(i), finalRes);
1476 }
1477 }
1478
1479 if (isLoopVecDim)
1480 state.vecLoopToVecDim[vecForOp] = loopToVecDimIt->second;
1481
1482 // Change insertion point so that upcoming vectorized instructions are
1483 // inserted into the vectorized loop's body.
1484 state.builder.setInsertionPointToStart(vecForOp.getBody());
1485
1486 // If this is a reduction loop then we may need to create a mask to filter out
1487 // garbage in the last iteration.
1488 if (isLoopVecDim && forOp.getNumIterOperands() > 0)
1489 createMask(vecForOp, state);
1490
1491 return vecForOp;
1492}
1493
1494/// Vectorizes arbitrary operation by plain widening. We apply generic type
1495/// widening of all its results and retrieve the vector counterparts for all its
1496/// operands.
1497static Operation *widenOp(Operation *op, VectorizationState &state) {
1498 SmallVector<Type, 8> vectorTypes;
1499 for (Value result : op->getResults())
1500 vectorTypes.push_back(
1501 VectorType::get(state.strategy->vectorSizes, result.getType()));
1502
1503 SmallVector<Value, 8> vectorOperands;
1504 for (Value operand : op->getOperands()) {
1505 Value vecOperand = vectorizeOperand(operand, state);
1506 if (!vecOperand) {
1507 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ an operand failed vectorize\n");
1508 return nullptr;
1509 }
1510 vectorOperands.push_back(vecOperand);
1511 }
1512
1513 // Create a clone of the op with the proper operands and return types.
1514 // TODO: The following assumes there is always an op with a fixed
1515 // name that works both in scalar mode and vector mode.
1516 // TODO: Is it worth considering an Operation.clone operation which
1517 // changes the type so we can promote an Operation with less boilerplate?
1518 OperationState vecState(op->getLoc(), op->getName(), vectorOperands,
1519 vectorTypes,
1520 op->getDiscardableAttrDictionary().getValue());
1522 Operation *vecOp = state.builder.create(vecState);
1523 state.registerOpVectorReplacement(op, vecOp);
1524 return vecOp;
1525}
1526
1527/// Vectorizes a yield operation by widening its types. The builder's insertion
1528/// point is set after the vectorized parent op to continue vectorizing the
1529/// operations after the parent op. When vectorizing a reduction loop a mask may
1530/// be used to prevent adding garbage values to the accumulator.
1531static Operation *vectorizeAffineYieldOp(AffineYieldOp yieldOp,
1532 VectorizationState &state) {
1533 Operation *newYieldOp = widenOp(yieldOp, state);
1534 Operation *newParentOp = state.builder.getInsertionBlock()->getParentOp();
1535
1536 // If there is a mask for this loop then we must prevent garbage values from
1537 // being added to the accumulator by inserting `select` operations, for
1538 // example:
1539 //
1540 // %val_masked = select %mask, %val, %neutralCst : vector<128xi1>,
1541 // vector<128xf32>
1542 // %res = arith.addf %acc, %val_masked : vector<128xf32>
1543 // affine.yield %res : vector<128xf32>
1544 //
1545 if (Value mask = state.vecLoopToMask.lookup(newParentOp)) {
1546 state.builder.setInsertionPoint(newYieldOp);
1547 for (unsigned i = 0; i < newYieldOp->getNumOperands(); ++i) {
1548 SmallVector<Operation *> combinerOps;
1549 Value reducedVal = matchReduction(
1550 cast<AffineForOp>(newParentOp).getRegionIterArgs(), i, combinerOps);
1551 assert(reducedVal && "expect non-null value for parallel reduction loop");
1552 assert(combinerOps.size() == 1 && "expect only one combiner op");
1553 // IterOperands are neutral element vectors.
1554 Value neutralVal = cast<AffineForOp>(newParentOp).getInits()[i];
1555 state.builder.setInsertionPoint(combinerOps.back());
1556 Value maskedReducedVal = arith::SelectOp::create(
1557 state.builder, reducedVal.getLoc(), mask, reducedVal, neutralVal);
1558 LLVM_DEBUG(
1559 dbgs() << "\n[early-vect]+++++ masking an input to a binary op that"
1560 "produces value for a yield Op: "
1561 << maskedReducedVal);
1562 combinerOps.back()->replaceUsesOfWith(reducedVal, maskedReducedVal);
1563 }
1564 }
1565
1566 state.builder.setInsertionPointAfter(newParentOp);
1567 return newYieldOp;
1568}
1569
1570/// Encodes Operation-specific behavior for vectorization. In general we
1571/// assume that all operands of an op must be vectorized but this is not
1572/// always true. In the future, it would be nice to have a trait that
1573/// describes how a particular operation vectorizes. For now we implement the
1574/// case distinction here. Returns a vectorized form of an operation or
1575/// nullptr if vectorization fails.
1576// TODO: consider adding a trait to Op to describe how it gets vectorized.
1577// Maybe some Ops are not vectorizable or require some tricky logic, we cannot
1578// do one-off logic here; ideally it would be TableGen'd.
1580 VectorizationState &state) {
1581 // Sanity checks.
1582 assert(!isa<vector::TransferReadOp>(op) &&
1583 "vector.transfer_read cannot be further vectorized");
1584 assert(!isa<vector::TransferWriteOp>(op) &&
1585 "vector.transfer_write cannot be further vectorized");
1586
1587 if (auto loadOp = dyn_cast<AffineLoadOp>(op))
1588 return vectorizeAffineLoad(loadOp, state);
1589 if (auto storeOp = dyn_cast<AffineStoreOp>(op))
1590 return vectorizeAffineStore(storeOp, state);
1591 if (auto forOp = dyn_cast<AffineForOp>(op))
1592 return vectorizeAffineForOp(forOp, state);
1593 if (auto yieldOp = dyn_cast<AffineYieldOp>(op))
1594 return vectorizeAffineYieldOp(yieldOp, state);
1595 if (auto constant = dyn_cast<arith::ConstantOp>(op))
1596 return vectorizeConstant(constant, state);
1597 if (auto applyOp = dyn_cast<AffineApplyOp>(op))
1598 return vectorizeAffineApplyOp(applyOp, state);
1599
1600 // Other ops with regions are not supported.
1601 if (op->getNumRegions() != 0)
1602 return nullptr;
1603
1604 return widenOp(op, state);
1605}
1606
1607/// Recursive implementation to convert all the nested loops in 'match' to a 2D
1608/// vector container that preserves the relative nesting level of each loop with
1609/// respect to the others in 'match'. 'currentLevel' is the nesting level that
1610/// will be assigned to the loop in the current 'match'.
1611static void
1612getMatchedAffineLoopsRec(NestedMatch match, unsigned currentLevel,
1613 std::vector<SmallVector<AffineForOp, 2>> &loops) {
1614 // Add a new empty level to the output if it doesn't exist already.
1615 assert(currentLevel <= loops.size() && "Unexpected currentLevel");
1616 if (currentLevel == loops.size())
1617 loops.emplace_back();
1618
1619 // Add current match and recursively visit its children.
1620 loops[currentLevel].push_back(cast<AffineForOp>(match.getMatchedOperation()));
1621 for (auto childMatch : match.getMatchedChildren()) {
1622 getMatchedAffineLoopsRec(childMatch, currentLevel + 1, loops);
1623 }
1624}
1625
1626/// Converts all the nested loops in 'match' to a 2D vector container that
1627/// preserves the relative nesting level of each loop with respect to the others
1628/// in 'match'. This means that every loop in 'loops[i]' will have a parent loop
1629/// in 'loops[i-1]'. A loop in 'loops[i]' may or may not have a child loop in
1630/// 'loops[i+1]'.
1631static void
1633 std::vector<SmallVector<AffineForOp, 2>> &loops) {
1634 getMatchedAffineLoopsRec(match, /*currLoopDepth=*/0, loops);
1635}
1636
1637/// Internal implementation to vectorize affine loops from a single loop nest
1638/// using an n-D vectorization strategy.
1639static LogicalResult
1641 const VectorizationStrategy &strategy) {
1642 assert(loops[0].size() == 1 && "Expected single root loop");
1643 AffineForOp rootLoop = loops[0][0];
1644 VectorizationState state(rootLoop.getContext());
1645 state.builder.setInsertionPointAfter(rootLoop);
1646 state.strategy = &strategy;
1647
1648 // Since patterns are recursive, they can very well intersect.
1649 // Since we do not want a fully greedy strategy in general, we decouple
1650 // pattern matching, from profitability analysis, from application.
1651 // As a consequence we must check that each root pattern is still
1652 // vectorizable. If a pattern is not vectorizable anymore, we just skip it.
1653 // TODO: implement a non-greedy profitability analysis that keeps only
1654 // non-intersecting patterns.
1656 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ loop is not vectorizable");
1657 return failure();
1658 }
1659
1660 //////////////////////////////////////////////////////////////////////////////
1661 // Vectorize the scalar loop nest following a topological order. A new vector
1662 // loop nest with the vectorized operations is created along the process. If
1663 // vectorization succeeds, the scalar loop nest is erased. If vectorization
1664 // fails, the vector loop nest is erased and the scalar loop nest is not
1665 // modified.
1666 //////////////////////////////////////////////////////////////////////////////
1667
1668 auto opVecResult = rootLoop.walk<WalkOrder::PreOrder>([&](Operation *op) {
1669 LLVM_DEBUG(dbgs() << "[early-vect]+++++ Vectorizing: " << *op);
1670 Operation *vectorOp = vectorizeOneOperation(op, state);
1671 if (!vectorOp) {
1672 LLVM_DEBUG(
1673 dbgs() << "[early-vect]+++++ failed vectorizing the operation: "
1674 << *op << "\n");
1675 return WalkResult::interrupt();
1676 }
1677
1678 return WalkResult::advance();
1679 });
1680
1681 if (opVecResult.wasInterrupted()) {
1682 LLVM_DEBUG(dbgs() << "[early-vect]+++++ failed vectorization for: "
1683 << rootLoop << "\n");
1684 // Erase vector loop nest if it was created, and all its users.
1685 auto vecRootLoopIt = state.opVectorReplacement.find(rootLoop);
1686 if (vecRootLoopIt != state.opVectorReplacement.end()) {
1687 auto vecRootLoop = cast<AffineForOp>(vecRootLoopIt->second);
1688 eraseUsers(vecRootLoop);
1689 eraseLoopNest(vecRootLoop);
1690 }
1691
1692 return failure();
1693 }
1694
1695 // Replace results of reduction loops with the scalar values computed using
1696 // `vector.reduction` or similar ops.
1697 for (auto resPair : state.loopResultScalarReplacement)
1698 resPair.first.replaceAllUsesWith(resPair.second);
1699
1700 assert(state.opVectorReplacement.count(rootLoop) == 1 &&
1701 "Expected vector replacement for loop nest");
1702 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ success vectorizing pattern");
1703 LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ vectorization result:\n"
1704 << *state.opVectorReplacement[rootLoop]);
1705
1706 // Finish this vectorization pattern.
1707 state.finishVectorizationPattern(rootLoop);
1708 return success();
1709}
1710
1711/// Extracts the matched loops and vectorizes them following a topological
1712/// order. A new vector loop nest will be created if vectorization succeeds. The
1713/// original loop nest won't be modified in any case.
1714static LogicalResult vectorizeRootMatch(NestedMatch m,
1715 const VectorizationStrategy &strategy) {
1716 std::vector<SmallVector<AffineForOp, 2>> loopsToVectorize;
1717 getMatchedAffineLoops(m, loopsToVectorize);
1718 return vectorizeLoopNest(loopsToVectorize, strategy);
1719}
1720
1721/// Traverses all the loop matches and classifies them into intersection
1722/// buckets. Two matches intersect if any of them encloses the other one. A
1723/// match intersects with a bucket if the match intersects with the root
1724/// (outermost) loop in that bucket.
1726 ArrayRef<NestedMatch> matches,
1727 std::vector<SmallVector<NestedMatch, 8>> &intersectionBuckets) {
1728 assert(intersectionBuckets.empty() && "Expected empty output");
1729 // Keeps track of the root (outermost) loop of each bucket.
1730 SmallVector<AffineForOp, 8> bucketRoots;
1731
1732 for (const NestedMatch &match : matches) {
1733 AffineForOp matchRoot = cast<AffineForOp>(match.getMatchedOperation());
1734 bool intersects = false;
1735 for (int i = 0, end = intersectionBuckets.size(); i < end; ++i) {
1736 AffineForOp bucketRoot = bucketRoots[i];
1737 // Add match to the bucket if the bucket root encloses the match root.
1738 if (bucketRoot->isAncestor(matchRoot)) {
1739 intersectionBuckets[i].push_back(match);
1740 intersects = true;
1741 break;
1742 }
1743 // Add match to the bucket if the match root encloses the bucket root. The
1744 // match root becomes the new bucket root.
1745 if (matchRoot->isAncestor(bucketRoot)) {
1746 bucketRoots[i] = matchRoot;
1747 intersectionBuckets[i].push_back(match);
1748 intersects = true;
1749 break;
1750 }
1751 }
1752
1753 // Match doesn't intersect with any existing bucket. Create a new bucket for
1754 // it.
1755 if (!intersects) {
1756 bucketRoots.push_back(matchRoot);
1757 intersectionBuckets.emplace_back();
1758 intersectionBuckets.back().push_back(match);
1759 }
1760 }
1761}
1762
1763/// Internal implementation to vectorize affine loops in 'loops' using the n-D
1764/// vectorization factors in 'vectorSizes'. By default, each vectorization
1765/// factor is applied inner-to-outer to the loops of each loop nest.
1766/// 'fastestVaryingPattern' can be optionally used to provide a different loop
1767/// vectorization order. `reductionLoops` can be provided to specify loops which
1768/// can be vectorized along the reduction dimension.
1769static void vectorizeLoops(Operation *parentOp, DenseSet<Operation *> &loops,
1770 ArrayRef<int64_t> vectorSizes,
1771 ArrayRef<int64_t> fastestVaryingPattern,
1772 const ReductionLoopMap &reductionLoops) {
1773 assert((reductionLoops.empty() || vectorSizes.size() == 1) &&
1774 "Vectorizing reductions is supported only for 1-D vectors");
1775
1776 // Compute 1-D, 2-D or 3-D loop pattern to be matched on the target loops.
1777 std::optional<NestedPattern> pattern =
1778 makePattern(loops, vectorSizes.size(), fastestVaryingPattern);
1779 if (!pattern) {
1780 LLVM_DEBUG(dbgs() << "\n[early-vect] pattern couldn't be computed\n");
1781 return;
1782 }
1783
1784 LLVM_DEBUG(dbgs() << "\n******************************************");
1785 LLVM_DEBUG(dbgs() << "\n******************************************");
1786 LLVM_DEBUG(dbgs() << "\n[early-vect] new pattern on parent op\n");
1787 LLVM_DEBUG(dbgs() << *parentOp << "\n");
1788
1789 unsigned patternDepth = pattern->getDepth();
1790
1791 // Compute all the pattern matches and classify them into buckets of
1792 // intersecting matches.
1794 pattern->match(parentOp, &allMatches);
1795 std::vector<SmallVector<NestedMatch, 8>> intersectionBuckets;
1796 computeIntersectionBuckets(allMatches, intersectionBuckets);
1797
1798 // Iterate over all buckets and vectorize the matches eagerly. We can only
1799 // vectorize one match from each bucket since all the matches within a bucket
1800 // intersect.
1801 for (auto &intersectingMatches : intersectionBuckets) {
1802 for (NestedMatch &match : intersectingMatches) {
1803 VectorizationStrategy strategy;
1804 // TODO: depending on profitability, elect to reduce the vector size.
1805 strategy.vectorSizes.assign(vectorSizes.begin(), vectorSizes.end());
1806 strategy.reductionLoops = reductionLoops;
1807 if (failed(analyzeProfitability(match.getMatchedChildren(), 1,
1808 patternDepth, &strategy))) {
1809 continue;
1810 }
1811 vectorizeLoopIfProfitable(match.getMatchedOperation(), 0, patternDepth,
1812 &strategy);
1813 // Vectorize match. Skip the rest of intersecting matches in the bucket if
1814 // vectorization succeeded.
1815 // TODO: if pattern does not apply, report it; alter the cost/benefit.
1816 // TODO: some diagnostics if failure to vectorize occurs.
1817 if (succeeded(vectorizeRootMatch(match, strategy)))
1818 break;
1819 }
1820 }
1821
1822 LLVM_DEBUG(dbgs() << "\n");
1823}
1824
1825void affine::vectorizeChildAffineLoops(
1826 Operation *parentOp, bool vectorizeReductions,
1827 ArrayRef<int64_t> vectorSizes, ArrayRef<int64_t> fastestVaryingPattern) {
1828 DenseSet<Operation *> parallelLoops;
1829 ReductionLoopMap reductionLoops;
1830
1831 // If 'vectorize-reduction=true' is provided, we also populate the
1832 // `reductionLoops` map.
1833 if (vectorizeReductions) {
1834 parentOp->walk([&parallelLoops, &reductionLoops](AffineForOp loop) {
1835 SmallVector<LoopReduction, 2> reductions;
1836 if (isLoopParallel(loop, &reductions)) {
1837 parallelLoops.insert(loop);
1838 // If it's not a reduction loop, adding it to the map is not necessary.
1839 if (!reductions.empty())
1840 reductionLoops[loop] = reductions;
1841 }
1842 });
1843 } else {
1844 parentOp->walk([&parallelLoops](AffineForOp loop) {
1845 if (isLoopParallel(loop))
1846 parallelLoops.insert(loop);
1847 });
1848 }
1849
1850 // Thread-safe RAII local context, BumpPtrAllocator freed on exit.
1851 NestedPatternContext mlContext;
1852 vectorizeLoops(parentOp, parallelLoops, vectorSizes, fastestVaryingPattern,
1853 reductionLoops);
1854}
1855
1856/// Applies vectorization to the current function by searching over a bunch of
1857/// predetermined patterns.
1858void Vectorize::runOnOperation() {
1859 func::FuncOp f = getOperation();
1860 if (vectorSizes.empty()) {
1861 f.emitError("The 'virtual-vector-size' option must be specified.");
1862 return signalPassFailure();
1863 }
1864
1865 if (llvm::any_of(vectorSizes, [](int64_t size) { return size <= 0; })) {
1866 f.emitError(
1867 "The 'virtual-vector-size' option must contain only positive values.");
1868 return signalPassFailure();
1869 }
1870
1871 if (!fastestVaryingPattern.empty() &&
1872 fastestVaryingPattern.size() != vectorSizes.size()) {
1873 f.emitRemark("Fastest varying pattern specified with different size than "
1874 "the vector size.");
1875 return signalPassFailure();
1876 }
1877
1878 if (vectorizeReductions && vectorSizes.size() != 1) {
1879 f.emitError("Vectorizing reductions is supported only for 1-D vectors.");
1880 return signalPassFailure();
1881 }
1882
1883 vectorizeChildAffineLoops(f, vectorizeReductions, vectorSizes,
1884 fastestVaryingPattern);
1885}
1886
1887/// Verify that affine loops in 'loops' meet the nesting criteria expected by
1888/// SuperVectorizer:
1889/// * There must be at least one loop.
1890/// * There must be a single root loop (nesting level 0).
1891/// * Each loop at a given nesting level must be nested in a loop from a
1892/// previous nesting level.
1893static LogicalResult
1895 // Expected at least one loop.
1896 if (loops.empty())
1897 return failure();
1898
1899 // Expected only one root loop.
1900 if (loops[0].size() != 1)
1901 return failure();
1902
1903 // Traverse loops outer-to-inner to check some invariants.
1904 for (int i = 1, end = loops.size(); i < end; ++i) {
1905 for (AffineForOp loop : loops[i]) {
1906 // Check that each loop at this level is nested in one of the loops from
1907 // the previous level.
1908 if (none_of(loops[i - 1], [&](AffineForOp maybeParent) {
1909 return maybeParent->isProperAncestor(loop);
1910 }))
1911 return failure();
1912
1913 // Check that each loop at this level is not nested in another loop from
1914 // this level.
1915 for (AffineForOp sibling : loops[i]) {
1916 if (sibling->isProperAncestor(loop))
1917 return failure();
1918 }
1919 }
1920 }
1921
1922 return success();
1923}
1924
1925/// External utility to vectorize affine loops in 'loops' using the n-D
1926/// vectorization factors in 'vectorSizes'. By default, each vectorization
1927/// factor is applied inner-to-outer to the loops of each loop nest.
1928/// 'fastestVaryingPattern' can be optionally used to provide a different loop
1929/// vectorization order.
1930/// If `reductionLoops` is not empty, the given reduction loops may be
1931/// vectorized along the reduction dimension.
1932/// TODO: Vectorizing reductions is supported only for 1-D vectorization.
1933void mlir::affine::vectorizeAffineLoops(
1934 Operation *parentOp, DenseSet<Operation *> &loops,
1935 ArrayRef<int64_t> vectorSizes, ArrayRef<int64_t> fastestVaryingPattern,
1936 const ReductionLoopMap &reductionLoops) {
1937 // Thread-safe RAII local context, BumpPtrAllocator freed on exit.
1938 NestedPatternContext mlContext;
1939 vectorizeLoops(parentOp, loops, vectorSizes, fastestVaryingPattern,
1940 reductionLoops);
1941}
1942
1943/// External utility to vectorize affine loops from a single loop nest using an
1944/// n-D vectorization strategy (see doc in VectorizationStrategy definition).
1945/// Loops are provided in a 2D vector container. The first dimension represents
1946/// the nesting level relative to the loops to be vectorized. The second
1947/// dimension contains the loops. This means that:
1948/// a) every loop in 'loops[i]' must have a parent loop in 'loops[i-1]',
1949/// b) a loop in 'loops[i]' may or may not have a child loop in 'loops[i+1]'.
1950///
1951/// For example, for the following loop nest:
1952///
1953/// func @vec2d(%in0: memref<64x128x512xf32>, %in1: memref<64x128x128xf32>,
1954/// %out0: memref<64x128x512xf32>,
1955/// %out1: memref<64x128x128xf32>) {
1956/// affine.for %i0 = 0 to 64 {
1957/// affine.for %i1 = 0 to 128 {
1958/// affine.for %i2 = 0 to 512 {
1959/// %ld = affine.load %in0[%i0, %i1, %i2] : memref<64x128x512xf32>
1960/// affine.store %ld, %out0[%i0, %i1, %i2] : memref<64x128x512xf32>
1961/// }
1962/// affine.for %i3 = 0 to 128 {
1963/// %ld = affine.load %in1[%i0, %i1, %i3] : memref<64x128x128xf32>
1964/// affine.store %ld, %out1[%i0, %i1, %i3] : memref<64x128x128xf32>
1965/// }
1966/// }
1967/// }
1968/// return
1969/// }
1970///
1971/// loops = {{%i0}, {%i2, %i3}}, to vectorize the outermost and the two
1972/// innermost loops;
1973/// loops = {{%i1}, {%i2, %i3}}, to vectorize the middle and the two innermost
1974/// loops;
1975/// loops = {{%i2}}, to vectorize only the first innermost loop;
1976/// loops = {{%i3}}, to vectorize only the second innermost loop;
1977/// loops = {{%i1}}, to vectorize only the middle loop.
1978LogicalResult mlir::affine::vectorizeAffineLoopNest(
1979 std::vector<SmallVector<AffineForOp, 2>> &loops,
1980 const VectorizationStrategy &strategy) {
1981 // Thread-safe RAII local context, BumpPtrAllocator freed on exit.
1982 NestedPatternContext mlContext;
1983 if (failed(verifyLoopNesting(loops)))
1984 return failure();
1985 return vectorizeLoopNest(loops, strategy);
1986}
return success()
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static Operation * vectorizeUniform(Value uniformVal, VectorizationState &state)
Generates a broadcast op for the provided uniform value using the vectorization strategy in 'state'.
static std::optional< NestedPattern > makePattern(const DenseSet< Operation * > &parallelLoops, int vectorRank, ArrayRef< int64_t > fastestVaryingPattern)
Creates a vectorization pattern from the command line arguments.
static LogicalResult vectorizeRootMatch(NestedMatch m, const VectorizationStrategy &strategy)
Extracts the matched loops and vectorizes them following a topological order.
static void vectorizeLoopIfProfitable(Operation *loop, unsigned depthInPattern, unsigned patternDepth, VectorizationStrategy *strategy)
static LogicalResult verifyLoopNesting(const std::vector< SmallVector< AffineForOp, 2 > > &loops)
Verify that affine loops in 'loops' meet the nesting criteria expected by SuperVectorizer:
static Operation * vectorizeOneOperation(Operation *op, VectorizationState &state)
Encodes Operation-specific behavior for vectorization.
static bool isNeutralElementConst(arith::AtomicRMWKind reductionKind, Value value, VectorizationState &state)
Returns true if value is a constant equal to the neutral element of the given vectorizable reduction.
static void eraseUsers(Operation *op)
Recursively erases the users of the results of 'op'.
static LogicalResult vectorizeLoopNest(std::vector< SmallVector< AffineForOp, 2 > > &loops, const VectorizationStrategy &strategy)
Internal implementation to vectorize affine loops from a single loop nest using an n-D vectorization ...
static Operation * vectorizeAffineLoad(AffineLoadOp loadOp, VectorizationState &state)
Vectorizes an affine load with the vectorization strategy in 'state' by generating a 'vector....
static Operation * vectorizeAffineForOp(AffineForOp forOp, VectorizationState &state)
Vectorizes a loop with the vectorization strategy in 'state'.
static Operation * vectorizeAffineApplyOp(AffineApplyOp applyOp, VectorizationState &state)
We have no need to vectorize affine.apply.
static LogicalResult analyzeProfitability(ArrayRef< NestedMatch > matches, unsigned depthInPattern, unsigned patternDepth, VectorizationStrategy *strategy)
Implements a simple strawman strategy for vectorization.
static FilterFunctionType isVectorizableLoopPtrFactory(const DenseSet< Operation * > &parallelLoops, int fastestVaryingMemRefDimension)
Forward declaration.
static bool isIVMappedToMultipleIndices(ArrayRef< Value > indices, const DenseMap< Operation *, unsigned > &loopToVectorDim)
Returns true if any vectorized loop IV drives more than one index.
static arith::ConstantOp vectorizeConstant(arith::ConstantOp constOp, VectorizationState &state)
Tries to transform a scalar constant into a vector constant.
static bool isUniformDefinition(Value value, const VectorizationStrategy *strategy)
Returns true if the provided value is vector uniform given the vectorization strategy.
static void eraseLoopNest(AffineForOp forOp)
Erases a loop nest, including all its nested operations.
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
static void getMatchedAffineLoops(NestedMatch match, std::vector< SmallVector< AffineForOp, 2 > > &loops)
Converts all the nested loops in 'match' to a 2D vector container that preserves the relative nesting...
static Value vectorizeOperand(Value operand, VectorizationState &state)
Tries to vectorize a given operand by applying the following logic:
static void getMatchedAffineLoopsRec(NestedMatch match, unsigned currentLevel, std::vector< SmallVector< AffineForOp, 2 > > &loops)
Recursive implementation to convert all the nested loops in 'match' to a 2D vector container that pre...
static Operation * vectorizeAffineYieldOp(AffineYieldOp yieldOp, VectorizationState &state)
Vectorizes a yield operation by widening its types.
static arith::ConstantOp createInitialVector(arith::AtomicRMWKind reductionKind, Value oldOperand, VectorizationState &state)
Creates a constant vector filled with the neutral elements of the given reduction.
static Operation * widenOp(Operation *op, VectorizationState &state)
Vectorizes arbitrary operation by plain widening.
static Operation * vectorizeAffineStore(AffineStoreOp storeOp, VectorizationState &state)
Vectorizes an affine store with the vectorization strategy in 'state' by generating a 'vector....
static NestedPattern & vectorTransferPattern()
static void vectorizeLoops(Operation *parentOp, DenseSet< Operation * > &loops, ArrayRef< int64_t > vectorSizes, ArrayRef< int64_t > fastestVaryingPattern, const ReductionLoopMap &reductionLoops)
Internal implementation to vectorize affine loops in 'loops' using the n-D vectorization factors in '...
static void computeMemoryOpIndices(Operation *op, AffineMap map, ValueRange mapOperands, VectorizationState &state, SmallVectorImpl< Value > &results)
static void computeIntersectionBuckets(ArrayRef< NestedMatch > matches, std::vector< SmallVector< NestedMatch, 8 > > &intersectionBuckets)
Traverses all the loop matches and classifies them into intersection buckets.
static Value createMask(AffineForOp vecForOp, VectorizationState &state)
Creates a mask used to filter out garbage elements in the last iteration of unaligned loops.
static AffineMap makePermutationMap(ArrayRef< Value > indices, const DenseMap< Operation *, unsigned > &enclosingLoopToVectorDim)
Constructs a permutation map from memref indices to vector dimension.
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
unsigned getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
Attributes are known-constant values of operations.
Definition Attributes.h:25
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:396
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:65
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
bool contains(T from) const
Checks to see if a mapping for 'from' exists.
Definition IRMapping.h:51
auto lookupOrNull(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:58
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
Definition Builders.h:445
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition Builders.h:424
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition Builders.cpp:466
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool use_empty()
Returns true if this operation has no uses.
Definition Operation.h:906
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:728
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
unsigned getNumOperands()
Definition Operation.h:373
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
result_range getResults()
Definition Operation.h:442
user_iterator user_begin()
Definition Operation.h:923
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
An NestedPattern captures nested patterns in the IR.
ArrayRef< NestedMatch > getMatchedChildren()
Operation * getMatchedOperation() const
NestedPattern For(const NestedPattern &child)
NestedPattern Op(FilterFunctionType filter=defaultFilterFunction)
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
DenseMap< Operation *, SmallVector< LoopReduction, 2 > > ReductionLoopMap
Definition Utils.h:43
bool isVectorizableLoopBody(AffineForOp loop, NestedPattern &vectorTransferMatcher)
Checks whether the loop is structurally vectorizable; i.e.:
DenseSet< Value, DenseMapInfo< Value > > getInvariantAccesses(Value iv, ArrayRef< Value > indices)
Given an induction variable iv of type AffineForOp and indices of type IndexType, returns the set of ...
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
std::function< bool(Operation &)> FilterFunctionType
A NestedPattern is a nested operation walker that:
Value getReductionOp(AtomicRMWKind op, OpBuilder &builder, Location loc, Value lhs, Value rhs)
Returns the value obtained by applying the reduction operation kind associated with a binary AtomicRM...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Operation * createWriteOrMaskedWrite(OpBuilder &builder, Location loc, Value vecToStore, Value dest, SmallVector< Value > writeIndices={}, bool useInBoundsInsteadOfMasking=false, AffineMap permutationMap=AffineMap())
Create a TransferWriteOp of vecToStore into dest.
Value createReadOrMaskedRead(OpBuilder &builder, Location loc, Value source, const VectorType &vecToReadTy, std::optional< Value > padValue=std::nullopt, bool useInBoundsInsteadOfMasking=false, ArrayRef< Value > indices={}, AffineMap permutationMap=AffineMap())
Creates a TransferReadOp from source.
Value getVectorReductionOp(arith::AtomicRMWKind op, OpBuilder &builder, Location loc, Value vector)
Returns the value obtained by reducing the vector into a scalar using the operation kind associated w...
Include the generated interface declarations.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
Value matchReduction(ArrayRef< BlockArgument > iterCarriedArgs, unsigned redPos, SmallVectorImpl< Operation * > &combinerOps)
Utility to match a generic reduction given a list of iteration-carried arguments, iterCarriedArgs and...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
VectorizationState(RewriterBase &rewriter)
This represents an operation in an abstracted form, suitable for use with the builder APIs.
Attribute propertiesAttr
This Attribute is used to opaquely construct the properties of the operation.