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 
14 #include "PassDetail.h"
15 #include "mlir/Analysis/LoopAnalysis.h"
16 #include "mlir/Analysis/NestedMatcher.h"
17 #include "mlir/Analysis/SliceAnalysis.h"
18 #include "mlir/Analysis/Utils.h"
19 #include "mlir/Dialect/Affine/IR/AffineOps.h"
20 #include "mlir/Dialect/Affine/Passes.h"
21 #include "mlir/Dialect/StandardOps/IR/Ops.h"
22 #include "mlir/Dialect/Vector/VectorOps.h"
23 #include "mlir/Dialect/Vector/VectorUtils.h"
24 #include "mlir/IR/AffineExpr.h"
25 #include "mlir/IR/Builders.h"
26 #include "mlir/IR/Location.h"
27 #include "mlir/IR/Types.h"
28 #include "mlir/Support/Functional.h"
29 #include "mlir/Support/LLVM.h"
30 #include "mlir/Transforms/FoldUtils.h"
31 
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 
40 using namespace mlir;
41 
42 ///
43 /// Implements a high-level vectorization strategy on a Function.
44 /// The abstraction used is that of super-vectors, which provide a single,
45 /// compact, representation in the vector types, information that is expected
46 /// to reduce the impact of the phase ordering problem
47 ///
48 /// Vector granularity:
49 /// ===================
50 /// This pass is designed to perform vectorization at a super-vector
51 /// granularity. A super-vector is loosely defined as a vector type that is a
52 /// multiple of a "good" vector size so the HW can efficiently implement a set
53 /// of high-level primitives. Multiple is understood along any dimension; e.g.
54 /// both vector<16xf32> and vector<2x8xf32> are valid super-vectors for a
55 /// vector<8xf32> HW vector. Note that a "good vector size so the HW can
56 /// efficiently implement a set of high-level primitives" is not necessarily an
57 /// integer multiple of actual hardware registers. We leave details of this
58 /// distinction unspecified for now.
59 ///
60 /// Some may prefer the terminology a "tile of HW vectors". In this case, one
61 /// should note that super-vectors implement an "always full tile" abstraction.
62 /// They guarantee no partial-tile separation is necessary by relying on a
63 /// high-level copy-reshape abstraction that we call vector.transfer. This
64 /// copy-reshape operations is also responsible for performing layout
65 /// transposition if necessary. In the general case this will require a scoped
66 /// allocation in some notional local memory.
67 ///
68 /// Whatever the mental model one prefers to use for this abstraction, the key
69 /// point is that we burn into a single, compact, representation in the vector
70 /// types, information that is expected to reduce the impact of the phase
71 /// ordering problem. Indeed, a vector type conveys information that:
72 ///   1. the associated loops have dependency semantics that do not prevent
73 ///      vectorization;
74 ///   2. the associate loops have been sliced in chunks of static sizes that are
75 ///      compatible with vector sizes (i.e. similar to unroll-and-jam);
76 ///   3. the inner loops, in the unroll-and-jam analogy of 2, are captured by
77 ///   the
78 ///      vector type and no vectorization hampering transformations can be
79 ///      applied to them anymore;
80 ///   4. the underlying memrefs are accessed in some notional contiguous way
81 ///      that allows loading into vectors with some amount of spatial locality;
82 /// In other words, super-vectorization provides a level of separation of
83 /// concern by way of opacity to subsequent passes. This has the effect of
84 /// encapsulating and propagating vectorization constraints down the list of
85 /// passes until we are ready to lower further.
86 ///
87 /// For a particular target, a notion of minimal n-d vector size will be
88 /// specified and vectorization targets a multiple of those. In the following
89 /// paragraph, let "k ." represent "a multiple of", to be understood as a
90 /// multiple in the same dimension (e.g. vector<16 x k . 128> summarizes
91 /// vector<16 x 128>, vector<16 x 256>, vector<16 x 1024>, etc).
92 ///
93 /// Some non-exhaustive notable super-vector sizes of interest include:
94 ///   - CPU: vector<k . HW_vector_size>,
95 ///          vector<k' . core_count x k . HW_vector_size>,
96 ///          vector<socket_count x k' . core_count x k . HW_vector_size>;
97 ///   - GPU: vector<k . warp_size>,
98 ///          vector<k . warp_size x float2>,
99 ///          vector<k . warp_size x float4>,
100 ///          vector<k . warp_size x 4 x 4x 4> (for tensor_core sizes).
101 ///
102 /// Loops and operations are emitted that operate on those super-vector shapes.
103 /// Subsequent lowering passes will materialize to actual HW vector sizes. These
104 /// passes are expected to be (gradually) more target-specific.
105 ///
106 /// At a high level, a vectorized load in a loop will resemble:
107 /// ```mlir
108 ///   affine.for %i = ? to ? step ? {
109 ///     %v_a = vector.transfer_read A[%i] : memref<?xf32>, vector<128xf32>
110 ///   }
111 /// ```
112 /// It is the responsibility of the implementation of vector.transfer_read to
113 /// materialize vector registers from the original scalar memrefs. A later (more
114 /// target-dependent) lowering pass will materialize to actual HW vector sizes.
115 /// This lowering may be occur at different times:
116 ///   1. at the MLIR level into a combination of loops, unrolling, DmaStartOp +
117 ///      DmaWaitOp + vectorized operations for data transformations and shuffle;
118 ///      thus opening opportunities for unrolling and pipelining. This is an
119 ///      instance of library call "whiteboxing"; or
120 ///   2. later in the a target-specific lowering pass or hand-written library
121 ///      call; achieving full separation of concerns. This is an instance of
122 ///      library call; or
123 ///   3. a mix of both, e.g. based on a model.
124 /// In the future, these operations will expose a contract to constrain the
125 /// search on vectorization patterns and sizes.
126 ///
127 /// Occurrence of super-vectorization in the compiler flow:
128 /// =======================================================
129 /// This is an active area of investigation. We start with 2 remarks to position
130 /// super-vectorization in the context of existing ongoing work: LLVM VPLAN
131 /// and LLVM SLP Vectorizer.
132 ///
133 /// LLVM VPLAN:
134 /// -----------
135 /// The astute reader may have noticed that in the limit, super-vectorization
136 /// can be applied at a similar time and with similar objectives than VPLAN.
137 /// For instance, in the case of a traditional, polyhedral compilation-flow (for
138 /// instance, the PPCG project uses ISL to provide dependence analysis,
139 /// multi-level(scheduling + tiling), lifting footprint to fast memory,
140 /// communication synthesis, mapping, register optimizations) and before
141 /// unrolling. When vectorization is applied at this *late* level in a typical
142 /// polyhedral flow, and is instantiated with actual hardware vector sizes,
143 /// super-vectorization is expected to match (or subsume) the type of patterns
144 /// that LLVM's VPLAN aims at targeting. The main difference here is that MLIR
145 /// is higher level and our implementation should be significantly simpler. Also
146 /// note that in this mode, recursive patterns are probably a bit of an overkill
147 /// although it is reasonable to expect that mixing a bit of outer loop and
148 /// inner loop vectorization + unrolling will provide interesting choices to
149 /// MLIR.
150 ///
151 /// LLVM SLP Vectorizer:
152 /// --------------------
153 /// Super-vectorization however is not meant to be usable in a similar fashion
154 /// to the SLP vectorizer. The main difference lies in the information that
155 /// both vectorizers use: super-vectorization examines contiguity of memory
156 /// references along fastest varying dimensions and loops with recursive nested
157 /// patterns capturing imperfectly-nested loop nests; the SLP vectorizer, on
158 /// the other hand, performs flat pattern matching inside a single unrolled loop
159 /// body and stitches together pieces of load and store operations into full
160 /// 1-D vectors. We envision that the SLP vectorizer is a good way to capture
161 /// innermost loop, control-flow dependent patterns that super-vectorization may
162 /// not be able to capture easily. In other words, super-vectorization does not
163 /// aim at replacing the SLP vectorizer and the two solutions are complementary.
164 ///
165 /// Ongoing investigations:
166 /// -----------------------
167 /// We discuss the following *early* places where super-vectorization is
168 /// applicable and touch on the expected benefits and risks . We list the
169 /// opportunities in the context of the traditional polyhedral compiler flow
170 /// described in PPCG. There are essentially 6 places in the MLIR pass pipeline
171 /// we expect to experiment with super-vectorization:
172 /// 1. Right after language lowering to MLIR: this is the earliest time where
173 ///    super-vectorization is expected to be applied. At this level, all the
174 ///    language/user/library-level annotations are available and can be fully
175 ///    exploited. Examples include loop-type annotations (such as parallel,
176 ///    reduction, scan, dependence distance vector, vectorizable) as well as
177 ///    memory access annotations (such as non-aliasing writes guaranteed,
178 ///    indirect accesses that are permutations by construction) accesses or
179 ///    that a particular operation is prescribed atomic by the user. At this
180 ///    level, anything that enriches what dependence analysis can do should be
181 ///    aggressively exploited. At this level we are close to having explicit
182 ///    vector types in the language, except we do not impose that burden on the
183 ///    programmer/library: we derive information from scalar code + annotations.
184 /// 2. After dependence analysis and before polyhedral scheduling: the
185 ///    information that supports vectorization does not need to be supplied by a
186 ///    higher level of abstraction. Traditional dependence analysis is available
187 ///    in MLIR and will be used to drive vectorization and cost models.
188 ///
189 /// Let's pause here and remark that applying super-vectorization as described
190 /// in 1. and 2. presents clear opportunities and risks:
191 ///   - the opportunity is that vectorization is burned in the type system and
192 ///   is protected from the adverse effect of loop scheduling, tiling, loop
193 ///   interchange and all passes downstream. Provided that subsequent passes are
194 ///   able to operate on vector types; the vector shapes, associated loop
195 ///   iterator properties, alignment, and contiguity of fastest varying
196 ///   dimensions are preserved until we lower the super-vector types. We expect
197 ///   this to significantly rein in on the adverse effects of phase ordering.
198 ///   - the risks are that a. all passes after super-vectorization have to work
199 ///   on elemental vector types (not that this is always true, wherever
200 ///   vectorization is applied) and b. that imposing vectorization constraints
201 ///   too early may be overall detrimental to loop fusion, tiling and other
202 ///   transformations because the dependence distances are coarsened when
203 ///   operating on elemental vector types. For this reason, the pattern
204 ///   profitability analysis should include a component that also captures the
205 ///   maximal amount of fusion available under a particular pattern. This is
206 ///   still at the stage of rough ideas but in this context, search is our
207 ///   friend as the Tensor Comprehensions and auto-TVM contributions
208 ///   demonstrated previously.
209 /// Bottom-line is we do not yet have good answers for the above but aim at
210 /// making it easy to answer such questions.
211 ///
212 /// Back to our listing, the last places where early super-vectorization makes
213 /// sense are:
214 /// 3. right after polyhedral-style scheduling: PLUTO-style algorithms are known
215 ///    to improve locality, parallelism and be configurable (e.g. max-fuse,
216 ///    smart-fuse etc). They can also have adverse effects on contiguity
217 ///    properties that are required for vectorization but the vector.transfer
218 ///    copy-reshape-pad-transpose abstraction is expected to help recapture
219 ///    these properties.
220 /// 4. right after polyhedral-style scheduling+tiling;
221 /// 5. right after scheduling+tiling+rescheduling: points 4 and 5 represent
222 ///    probably the most promising places because applying tiling achieves a
223 ///    separation of concerns that allows rescheduling to worry less about
224 ///    locality and more about parallelism and distribution (e.g. min-fuse).
225 ///
226 /// At these levels the risk-reward looks different: on one hand we probably
227 /// lost a good deal of language/user/library-level annotation; on the other
228 /// hand we gained parallelism and locality through scheduling and tiling.
229 /// However we probably want to ensure tiling is compatible with the
230 /// full-tile-only abstraction used in super-vectorization or suffer the
231 /// consequences. It is too early to place bets on what will win but we expect
232 /// super-vectorization to be the right abstraction to allow exploring at all
233 /// these levels. And again, search is our friend.
234 ///
235 /// Lastly, we mention it again here:
236 /// 6. as a MLIR-based alternative to VPLAN.
237 ///
238 /// Lowering, unrolling, pipelining:
239 /// ================================
240 /// TODO(ntv): point to the proper places.
241 ///
242 /// Algorithm:
243 /// ==========
244 /// The algorithm proceeds in a few steps:
245 ///  1. defining super-vectorization patterns and matching them on the tree of
246 ///     AffineForOp. A super-vectorization pattern is defined as a recursive
247 ///     data structures that matches and captures nested, imperfectly-nested
248 ///     loops that have a. conformable loop annotations attached (e.g. parallel,
249 ///     reduction, vectorizable, ...) as well as b. all contiguous load/store
250 ///     operations along a specified minor dimension (not necessarily the
251 ///     fastest varying) ;
252 ///  2. analyzing those patterns for profitability (TODO(ntv): and
253 ///     interference);
254 ///  3. Then, for each pattern in order:
255 ///    a. applying iterative rewriting of the loop and the load operations in
256 ///       DFS postorder. Rewriting is implemented by coarsening the loops and
257 ///       turning load operations into opaque vector.transfer_read ops;
258 ///    b. keeping track of the load operations encountered as "roots" and the
259 ///       store operations as "terminals";
260 ///    c. traversing the use-def chains starting from the roots and iteratively
261 ///       propagating vectorized values. Scalar values that are encountered
262 ///       during this process must come from outside the scope of the current
263 ///       pattern (TODO(ntv): enforce this and generalize). Such a scalar value
264 ///       is vectorized only if it is a constant (into a vector splat). The
265 ///       non-constant case is not supported for now and results in the pattern
266 ///       failing to vectorize;
267 ///    d. performing a second traversal on the terminals (store ops) to
268 ///       rewriting the scalar value they write to memory into vector form.
269 ///       If the scalar value has been vectorized previously, we simply replace
270 ///       it by its vector form. Otherwise, if the scalar value is a constant,
271 ///       it is vectorized into a splat. In all other cases, vectorization for
272 ///       the pattern currently fails.
273 ///    e. if everything under the root AffineForOp in the current pattern
274 ///       vectorizes properly, we commit that loop to the IR. Otherwise we
275 ///       discard it and restore a previously cloned version of the loop. Thanks
276 ///       to the recursive scoping nature of matchers and captured patterns,
277 ///       this is transparently achieved by a simple RAII implementation.
278 ///    f. vectorization is applied on the next pattern in the list. Because
279 ///       pattern interference avoidance is not yet implemented and that we do
280 ///       not support further vectorizing an already vector load we need to
281 ///       re-verify that the pattern is still vectorizable. This is expected to
282 ///       make cost models more difficult to write and is subject to improvement
283 ///       in the future.
284 ///
285 /// Points c. and d. above are worth additional comment. In most passes that
286 /// do not change the type of operands, it is usually preferred to eagerly
287 /// `replaceAllUsesWith`. Unfortunately this does not work for vectorization
288 /// because during the use-def chain traversal, all the operands of an operation
289 /// must be available in vector form. Trying to propagate eagerly makes the IR
290 /// temporarily invalid and results in errors such as:
291 ///   `vectorize.mlir:308:13: error: 'addf' op requires the same type for all
292 ///   operands and results
293 ///      %s5 = addf %a5, %b5 : f32`
294 ///
295 /// Lastly, we show a minimal example for which use-def chains rooted in load /
296 /// vector.transfer_read are not enough. This is what motivated splitting
297 /// terminal processing out of the use-def chains starting from loads. In the
298 /// following snippet, there is simply no load::
299 /// ```mlir
300 /// func @fill(%A : memref<128xf32>) -> () {
301 ///   %f1 = constant 1.0 : f32
302 ///   affine.for %i0 = 0 to 32 {
303 ///     affine.store %f1, %A[%i0] : memref<128xf32, 0>
304 ///   }
305 ///   return
306 /// }
307 /// ```
308 ///
309 /// Choice of loop transformation to support the algorithm:
310 /// =======================================================
311 /// The choice of loop transformation to apply for coarsening vectorized loops
312 /// is still subject to exploratory tradeoffs. In particular, say we want to
313 /// vectorize by a factor 128, we want to transform the following input:
314 /// ```mlir
315 ///   affine.for %i = %M to %N {
316 ///     %a = affine.load %A[%i] : memref<?xf32>
317 ///   }
318 /// ```
319 ///
320 /// Traditionally, one would vectorize late (after scheduling, tiling,
321 /// memory promotion etc) say after stripmining (and potentially unrolling in
322 /// the case of LLVM's SLP vectorizer):
323 /// ```mlir
324 ///   affine.for %i = floor(%M, 128) to ceil(%N, 128) {
325 ///     affine.for %ii = max(%M, 128 * %i) to min(%N, 128*%i + 127) {
326 ///       %a = affine.load %A[%ii] : memref<?xf32>
327 ///     }
328 ///   }
329 /// ```
330 ///
331 /// Instead, we seek to vectorize early and freeze vector types before
332 /// scheduling, so we want to generate a pattern that resembles:
333 /// ```mlir
334 ///   affine.for %i = ? to ? step ? {
335 ///     %v_a = vector.transfer_read %A[%i] : memref<?xf32>, vector<128xf32>
336 ///   }
337 /// ```
338 ///
339 /// i. simply dividing the lower / upper bounds by 128 creates issues
340 ///    when representing expressions such as ii + 1 because now we only
341 ///    have access to original values that have been divided. Additional
342 ///    information is needed to specify accesses at below-128 granularity;
343 /// ii. another alternative is to coarsen the loop step but this may have
344 ///    consequences on dependence analysis and fusability of loops: fusable
345 ///    loops probably need to have the same step (because we don't want to
346 ///    stripmine/unroll to enable fusion).
347 /// As a consequence, we choose to represent the coarsening using the loop
348 /// step for now and reevaluate in the future. Note that we can renormalize
349 /// loop steps later if/when we have evidence that they are problematic.
350 ///
351 /// For the simple strawman example above, vectorizing for a 1-D vector
352 /// abstraction of size 128 returns code similar to:
353 /// ```mlir
354 ///   affine.for %i = %M to %N step 128 {
355 ///     %v_a = vector.transfer_read %A[%i] : memref<?xf32>, vector<128xf32>
356 ///   }
357 /// ```
358 ///
359 /// Unsupported cases, extensions, and work in progress (help welcome :-) ):
360 /// ========================================================================
361 ///   1. lowering to concrete vector types for various HW;
362 ///   2. reduction support;
363 ///   3. non-effecting padding during vector.transfer_read and filter during
364 ///      vector.transfer_write;
365 ///   4. misalignment support vector.transfer_read / vector.transfer_write
366 ///      (hopefully without read-modify-writes);
367 ///   5. control-flow support;
368 ///   6. cost-models, heuristics and search;
369 ///   7. Op implementation, extensions and implication on memref views;
370 ///   8. many TODOs left around.
371 ///
372 /// Examples:
373 /// =========
374 /// Consider the following Function:
375 /// ```mlir
376 /// func @vector_add_2d(%M : index, %N : index) -> f32 {
377 ///   %A = alloc (%M, %N) : memref<?x?xf32, 0>
378 ///   %B = alloc (%M, %N) : memref<?x?xf32, 0>
379 ///   %C = alloc (%M, %N) : memref<?x?xf32, 0>
380 ///   %f1 = constant 1.0 : f32
381 ///   %f2 = constant 2.0 : f32
382 ///   affine.for %i0 = 0 to %M {
383 ///     affine.for %i1 = 0 to %N {
384 ///       // non-scoped %f1
385 ///       affine.store %f1, %A[%i0, %i1] : memref<?x?xf32, 0>
386 ///     }
387 ///   }
388 ///   affine.for %i2 = 0 to %M {
389 ///     affine.for %i3 = 0 to %N {
390 ///       // non-scoped %f2
391 ///       affine.store %f2, %B[%i2, %i3] : memref<?x?xf32, 0>
392 ///     }
393 ///   }
394 ///   affine.for %i4 = 0 to %M {
395 ///     affine.for %i5 = 0 to %N {
396 ///       %a5 = affine.load %A[%i4, %i5] : memref<?x?xf32, 0>
397 ///       %b5 = affine.load %B[%i4, %i5] : memref<?x?xf32, 0>
398 ///       %s5 = addf %a5, %b5 : f32
399 ///       // non-scoped %f1
400 ///       %s6 = addf %s5, %f1 : f32
401 ///       // non-scoped %f2
402 ///       %s7 = addf %s5, %f2 : f32
403 ///       // diamond dependency.
404 ///       %s8 = addf %s7, %s6 : f32
405 ///       affine.store %s8, %C[%i4, %i5] : memref<?x?xf32, 0>
406 ///     }
407 ///   }
408 ///   %c7 = constant 7 : index
409 ///   %c42 = constant 42 : index
410 ///   %res = load %C[%c7, %c42] : memref<?x?xf32, 0>
411 ///   return %res : f32
412 /// }
413 /// ```
414 ///
415 /// The -affine-vectorize pass with the following arguments:
416 /// ```
417 /// -affine-vectorize="virtual-vector-size=256 test-fastest-varying=0"
418 /// ```
419 ///
420 /// produces this standard innermost-loop vectorized code:
421 /// ```mlir
422 /// func @vector_add_2d(%arg0 : index, %arg1 : index) -> f32 {
423 ///   %0 = alloc(%arg0, %arg1) : memref<?x?xf32>
424 ///   %1 = alloc(%arg0, %arg1) : memref<?x?xf32>
425 ///   %2 = alloc(%arg0, %arg1) : memref<?x?xf32>
426 ///   %cst = constant 1.0 : f32
427 ///   %cst_0 = constant 2.0 : f32
428 ///   affine.for %i0 = 0 to %arg0 {
429 ///     affine.for %i1 = 0 to %arg1 step 256 {
430 ///       %cst_1 = constant dense<vector<256xf32>, 1.0> :
431 ///                vector<256xf32>
432 ///       vector.transfer_write %cst_1, %0[%i0, %i1] :
433 ///                vector<256xf32>, memref<?x?xf32>
434 ///     }
435 ///   }
436 ///   affine.for %i2 = 0 to %arg0 {
437 ///     affine.for %i3 = 0 to %arg1 step 256 {
438 ///       %cst_2 = constant dense<vector<256xf32>, 2.0> :
439 ///                vector<256xf32>
440 ///       vector.transfer_write %cst_2, %1[%i2, %i3] :
441 ///                vector<256xf32>, memref<?x?xf32>
442 ///     }
443 ///   }
444 ///   affine.for %i4 = 0 to %arg0 {
445 ///     affine.for %i5 = 0 to %arg1 step 256 {
446 ///       %3 = vector.transfer_read %0[%i4, %i5] :
447 ///            memref<?x?xf32>, vector<256xf32>
448 ///       %4 = vector.transfer_read %1[%i4, %i5] :
449 ///            memref<?x?xf32>, vector<256xf32>
450 ///       %5 = addf %3, %4 : vector<256xf32>
451 ///       %cst_3 = constant dense<vector<256xf32>, 1.0> :
452 ///                vector<256xf32>
453 ///       %6 = addf %5, %cst_3 : vector<256xf32>
454 ///       %cst_4 = constant dense<vector<256xf32>, 2.0> :
455 ///                vector<256xf32>
456 ///       %7 = addf %5, %cst_4 : vector<256xf32>
457 ///       %8 = addf %7, %6 : vector<256xf32>
458 ///       vector.transfer_write %8, %2[%i4, %i5] :
459 ///                vector<256xf32>, memref<?x?xf32>
460 ///     }
461 ///   }
462 ///   %c7 = constant 7 : index
463 ///   %c42 = constant 42 : index
464 ///   %9 = load %2[%c7, %c42] : memref<?x?xf32>
465 ///   return %9 : f32
466 /// }
467 /// ```
468 ///
469 /// The -affine-vectorize pass with the following arguments:
470 /// ```
471 /// -affine-vectorize="virtual-vector-size=32,256 test-fastest-varying=1,0"
472 /// ```
473 ///
474 /// produces this more interesting mixed outer-innermost-loop vectorized code:
475 /// ```mlir
476 /// func @vector_add_2d(%arg0 : index, %arg1 : index) -> f32 {
477 ///   %0 = alloc(%arg0, %arg1) : memref<?x?xf32>
478 ///   %1 = alloc(%arg0, %arg1) : memref<?x?xf32>
479 ///   %2 = alloc(%arg0, %arg1) : memref<?x?xf32>
480 ///   %cst = constant 1.0 : f32
481 ///   %cst_0 = constant 2.0 : f32
482 ///   affine.for %i0 = 0 to %arg0 step 32 {
483 ///     affine.for %i1 = 0 to %arg1 step 256 {
484 ///       %cst_1 = constant dense<vector<32x256xf32>, 1.0> :
485 ///                vector<32x256xf32>
486 ///       vector.transfer_write %cst_1, %0[%i0, %i1] :
487 ///                vector<32x256xf32>, memref<?x?xf32>
488 ///     }
489 ///   }
490 ///   affine.for %i2 = 0 to %arg0 step 32 {
491 ///     affine.for %i3 = 0 to %arg1 step 256 {
492 ///       %cst_2 = constant dense<vector<32x256xf32>, 2.0> :
493 ///                vector<32x256xf32>
494 ///       vector.transfer_write %cst_2, %1[%i2, %i3] :
495 ///                vector<32x256xf32>, memref<?x?xf32>
496 ///     }
497 ///   }
498 ///   affine.for %i4 = 0 to %arg0 step 32 {
499 ///     affine.for %i5 = 0 to %arg1 step 256 {
500 ///       %3 = vector.transfer_read %0[%i4, %i5] :
501 ///                memref<?x?xf32> vector<32x256xf32>
502 ///       %4 = vector.transfer_read %1[%i4, %i5] :
503 ///                memref<?x?xf32>, vector<32x256xf32>
504 ///       %5 = addf %3, %4 : vector<32x256xf32>
505 ///       %cst_3 = constant dense<vector<32x256xf32>, 1.0> :
506 ///                vector<32x256xf32>
507 ///       %6 = addf %5, %cst_3 : vector<32x256xf32>
508 ///       %cst_4 = constant dense<vector<32x256xf32>, 2.0> :
509 ///                vector<32x256xf32>
510 ///       %7 = addf %5, %cst_4 : vector<32x256xf32>
511 ///       %8 = addf %7, %6 : vector<32x256xf32>
512 ///       vector.transfer_write %8, %2[%i4, %i5] :
513 ///                vector<32x256xf32>, memref<?x?xf32>
514 ///     }
515 ///   }
516 ///   %c7 = constant 7 : index
517 ///   %c42 = constant 42 : index
518 ///   %9 = load %2[%c7, %c42] : memref<?x?xf32>
519 ///   return %9 : f32
520 /// }
521 /// ```
522 ///
523 /// Of course, much more intricate n-D imperfectly-nested patterns can be
524 /// vectorized too and specified in a fully declarative fashion.
525 
526 #define DEBUG_TYPE "early-vect"
527 
528 using functional::makePtrDynCaster;
529 using functional::map;
530 using llvm::dbgs;
531 using llvm::SetVector;
532 
533 /// Forward declaration.
534 static FilterFunctionType
535 isVectorizableLoopPtrFactory(const DenseSet<Operation *> &parallelLoops,
536                              int fastestVaryingMemRefDimension);
537 
538 /// Creates a vectorization pattern from the command line arguments.
539 /// Up to 3-D patterns are supported.
540 /// If the command line argument requests a pattern of higher order, returns an
541 /// empty pattern list which will conservatively result in no vectorization.
542 static std::vector<NestedPattern>
543 makePatterns(const DenseSet<Operation *> &parallelLoops, int vectorRank,
544              ArrayRef<int64_t> fastestVaryingPattern) {
545   using matcher::For;
546   int64_t d0 = fastestVaryingPattern.empty() ? -1 : fastestVaryingPattern[0];
547   int64_t d1 = fastestVaryingPattern.size() < 2 ? -1 : fastestVaryingPattern[1];
548   int64_t d2 = fastestVaryingPattern.size() < 3 ? -1 : fastestVaryingPattern[2];
549   switch (vectorRank) {
550   case 1:
551     return {For(isVectorizableLoopPtrFactory(parallelLoops, d0))};
552   case 2:
553     return {For(isVectorizableLoopPtrFactory(parallelLoops, d0),
554                 For(isVectorizableLoopPtrFactory(parallelLoops, d1)))};
555   case 3:
556     return {For(isVectorizableLoopPtrFactory(parallelLoops, d0),
557                 For(isVectorizableLoopPtrFactory(parallelLoops, d1),
558                     For(isVectorizableLoopPtrFactory(parallelLoops, d2))))};
559   default: {
560     return std::vector<NestedPattern>();
561   }
562   }
563 }
564 
565 static NestedPattern &vectorTransferPattern() {
566   static auto pattern = matcher::Op([](Operation &op) {
567     return isa<vector::TransferReadOp>(op) || isa<vector::TransferWriteOp>(op);
568   });
569   return pattern;
570 }
571 
572 namespace {
573 
574 /// Base state for the vectorize pass.
575 /// Command line arguments are preempted by non-empty pass arguments.
576 struct Vectorize : public AffineVectorizeBase<Vectorize> {
577   Vectorize() = default;
578   Vectorize(ArrayRef<int64_t> virtualVectorSize);
579   void runOnFunction() override;
580 };
581 
582 } // end anonymous namespace
583 
584 Vectorize::Vectorize(ArrayRef<int64_t> virtualVectorSize) {
585   vectorSizes = virtualVectorSize;
586 }
587 
588 /////// TODO(ntv): Hoist to a VectorizationStrategy.cpp when appropriate.
589 /////////
590 namespace {
591 
592 struct VectorizationStrategy {
593   SmallVector<int64_t, 8> vectorSizes;
594   DenseMap<Operation *, unsigned> loopToVectorDim;
595 };
596 
597 } // end anonymous namespace
598 
599 static void vectorizeLoopIfProfitable(Operation *loop, unsigned depthInPattern,
600                                       unsigned patternDepth,
601                                       VectorizationStrategy *strategy) {
602   assert(patternDepth > depthInPattern &&
603          "patternDepth is greater than depthInPattern");
604   if (patternDepth - depthInPattern > strategy->vectorSizes.size()) {
605     // Don't vectorize this loop
606     return;
607   }
608   strategy->loopToVectorDim[loop] =
609       strategy->vectorSizes.size() - (patternDepth - depthInPattern);
610 }
611 
612 /// Implements a simple strawman strategy for vectorization.
613 /// Given a matched pattern `matches` of depth `patternDepth`, this strategy
614 /// greedily assigns the fastest varying dimension ** of the vector ** to the
615 /// innermost loop in the pattern.
616 /// When coupled with a pattern that looks for the fastest varying dimension in
617 /// load/store MemRefs, this creates a generic vectorization strategy that works
618 /// for any loop in a hierarchy (outermost, innermost or intermediate).
619 ///
620 /// TODO(ntv): In the future we should additionally increase the power of the
621 /// profitability analysis along 3 directions:
622 ///   1. account for loop extents (both static and parametric + annotations);
623 ///   2. account for data layout permutations;
624 ///   3. account for impact of vectorization on maximal loop fusion.
625 /// Then we can quantify the above to build a cost model and search over
626 /// strategies.
627 static LogicalResult analyzeProfitability(ArrayRef<NestedMatch> matches,
628                                           unsigned depthInPattern,
629                                           unsigned patternDepth,
630                                           VectorizationStrategy *strategy) {
631   for (auto m : matches) {
632     if (failed(analyzeProfitability(m.getMatchedChildren(), depthInPattern + 1,
633                                     patternDepth, strategy))) {
634       return failure();
635     }
636     vectorizeLoopIfProfitable(m.getMatchedOperation(), depthInPattern,
637                               patternDepth, strategy);
638   }
639   return success();
640 }
641 
642 ///// end TODO(ntv): Hoist to a VectorizationStrategy.cpp when appropriate /////
643 
644 namespace {
645 
646 struct VectorizationState {
647   /// Adds an entry of pre/post vectorization operations in the state.
648   void registerReplacement(Operation *key, Operation *value);
649   /// When the current vectorization pattern is successful, this erases the
650   /// operations that were marked for erasure in the proper order and resets
651   /// the internal state for the next pattern.
652   void finishVectorizationPattern();
653 
654   // In-order tracking of original Operation that have been vectorized.
655   // Erase in reverse order.
656   SmallVector<Operation *, 16> toErase;
657   // Set of Operation that have been vectorized (the values in the
658   // vectorizationMap for hashed access). The vectorizedSet is used in
659   // particular to filter the operations that have already been vectorized by
660   // this pattern, when iterating over nested loops in this pattern.
661   DenseSet<Operation *> vectorizedSet;
662   // Map of old scalar Operation to new vectorized Operation.
663   DenseMap<Operation *, Operation *> vectorizationMap;
664   // Map of old scalar Value to new vectorized Value.
665   DenseMap<Value, Value> replacementMap;
666   // The strategy drives which loop to vectorize by which amount.
667   const VectorizationStrategy *strategy;
668   // Use-def roots. These represent the starting points for the worklist in the
669   // vectorizeNonTerminals function. They consist of the subset of load
670   // operations that have been vectorized. They can be retrieved from
671   // `vectorizationMap` but it is convenient to keep track of them in a separate
672   // data structure.
673   DenseSet<Operation *> roots;
674   // Terminal operations for the worklist in the vectorizeNonTerminals
675   // function. They consist of the subset of store operations that have been
676   // vectorized. They can be retrieved from `vectorizationMap` but it is
677   // convenient to keep track of them in a separate data structure. Since they
678   // do not necessarily belong to use-def chains starting from loads (e.g
679   // storing a constant), we need to handle them in a post-pass.
680   DenseSet<Operation *> terminals;
681   // Checks that the type of `op` is AffineStoreOp and adds it to the terminals
682   // set.
683   void registerTerminal(Operation *op);
684   // Folder used to factor out constant creation.
685   OperationFolder *folder;
686 
687 private:
688   void registerReplacement(Value key, Value value);
689 };
690 
691 } // end namespace
692 
693 void VectorizationState::registerReplacement(Operation *key, Operation *value) {
694   LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ commit vectorized op: ");
695   LLVM_DEBUG(key->print(dbgs()));
696   LLVM_DEBUG(dbgs() << "  into  ");
697   LLVM_DEBUG(value->print(dbgs()));
698   assert(key->getNumResults() == 1 && "already registered");
699   assert(value->getNumResults() == 1 && "already registered");
700   assert(vectorizedSet.count(value) == 0 && "already registered");
701   assert(vectorizationMap.count(key) == 0 && "already registered");
702   toErase.push_back(key);
703   vectorizedSet.insert(value);
704   vectorizationMap.insert(std::make_pair(key, value));
705   registerReplacement(key->getResult(0), value->getResult(0));
706   if (isa<AffineLoadOp>(key)) {
707     assert(roots.count(key) == 0 && "root was already inserted previously");
708     roots.insert(key);
709   }
710 }
711 
712 void VectorizationState::registerTerminal(Operation *op) {
713   assert(isa<AffineStoreOp>(op) && "terminal must be a AffineStoreOp");
714   assert(terminals.count(op) == 0 &&
715          "terminal was already inserted previously");
716   terminals.insert(op);
717 }
718 
719 void VectorizationState::finishVectorizationPattern() {
720   while (!toErase.empty()) {
721     auto *op = toErase.pop_back_val();
722     LLVM_DEBUG(dbgs() << "\n[early-vect] finishVectorizationPattern erase: ");
723     LLVM_DEBUG(op->print(dbgs()));
724     op->erase();
725   }
726 }
727 
728 void VectorizationState::registerReplacement(Value key, Value value) {
729   assert(replacementMap.count(key) == 0 && "replacement already registered");
730   replacementMap.insert(std::make_pair(key, value));
731 }
732 
733 // Apply 'map' with 'mapOperands' returning resulting values in 'results'.
734 static void computeMemoryOpIndices(Operation *op, AffineMap map,
735                                    ValueRange mapOperands,
736                                    SmallVectorImpl<Value> &results) {
737   OpBuilder builder(op);
738   for (auto resultExpr : map.getResults()) {
739     auto singleResMap =
740         AffineMap::get(map.getNumDims(), map.getNumSymbols(), resultExpr);
741     auto afOp =
742         builder.create<AffineApplyOp>(op->getLoc(), singleResMap, mapOperands);
743     results.push_back(afOp);
744   }
745 }
746 
747 ////// TODO(ntv): Hoist to a VectorizationMaterialize.cpp when appropriate. ////
748 
749 /// Handles the vectorization of load and store MLIR operations.
750 ///
751 /// AffineLoadOp operations are the roots of the vectorizeNonTerminals call.
752 /// They are vectorized immediately. The resulting vector.transfer_read is
753 /// immediately registered to replace all uses of the AffineLoadOp in this
754 /// pattern's scope.
755 ///
756 /// AffineStoreOp are the terminals of the vectorizeNonTerminals call. They
757 /// need to be vectorized late once all the use-def chains have been traversed.
758 /// Additionally, they may have ssa-values operands which come from outside the
759 /// scope of the current pattern.
760 /// Such special cases force us to delay the vectorization of the stores until
761 /// the last step. Here we merely register the store operation.
762 template <typename LoadOrStoreOpPointer>
763 static LogicalResult vectorizeRootOrTerminal(Value iv,
764                                              LoadOrStoreOpPointer memoryOp,
765                                              VectorizationState *state) {
766   auto memRefType = memoryOp.getMemRef().getType().template cast<MemRefType>();
767 
768   auto elementType = memRefType.getElementType();
769   // TODO(ntv): ponder whether we want to further vectorize a vector value.
770   assert(VectorType::isValidElementType(elementType) &&
771          "Not a valid vector element type");
772   auto vectorType = VectorType::get(state->strategy->vectorSizes, elementType);
773 
774   // Materialize a MemRef with 1 vector.
775   auto *opInst = memoryOp.getOperation();
776   // For now, vector.transfers must be aligned, operate only on indices with an
777   // identity subset of AffineMap and do not change layout.
778   // TODO(ntv): increase the expressiveness power of vector.transfer operations
779   // as needed by various targets.
780   if (auto load = dyn_cast<AffineLoadOp>(opInst)) {
781     OpBuilder b(opInst);
782     ValueRange mapOperands = load.getMapOperands();
783     SmallVector<Value, 8> indices;
784     indices.reserve(load.getMemRefType().getRank());
785     if (load.getAffineMap() !=
786         b.getMultiDimIdentityMap(load.getMemRefType().getRank())) {
787       computeMemoryOpIndices(opInst, load.getAffineMap(), mapOperands, indices);
788     } else {
789       indices.append(mapOperands.begin(), mapOperands.end());
790     }
791     auto permutationMap =
792         makePermutationMap(opInst, indices, state->strategy->loopToVectorDim);
793     if (!permutationMap)
794       return LogicalResult::Failure;
795     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ permutationMap: ");
796     LLVM_DEBUG(permutationMap.print(dbgs()));
797     auto transfer = b.create<vector::TransferReadOp>(
798         opInst->getLoc(), vectorType, memoryOp.getMemRef(), indices,
799         AffineMapAttr::get(permutationMap),
800         // TODO(b/144455320) add a proper padding value, not just 0.0 : f32
801         state->folder->create<ConstantFloatOp>(b, opInst->getLoc(),
802                                                APFloat(0.0f), b.getF32Type()));
803     state->registerReplacement(opInst, transfer.getOperation());
804   } else {
805     state->registerTerminal(opInst);
806   }
807   return success();
808 }
809 /// end TODO(ntv): Hoist to a VectorizationMaterialize.cpp when appropriate. ///
810 
811 /// Coarsens the loops bounds and transforms all remaining load and store
812 /// operations into the appropriate vector.transfer.
813 static LogicalResult vectorizeAffineForOp(AffineForOp loop, int64_t step,
814                                           VectorizationState *state) {
815   using namespace functional;
816   loop.setStep(step);
817 
818   FilterFunctionType notVectorizedThisPattern = [state](Operation &op) {
819     if (!matcher::isLoadOrStore(op)) {
820       return false;
821     }
822     return state->vectorizationMap.count(&op) == 0 &&
823            state->vectorizedSet.count(&op) == 0 &&
824            state->roots.count(&op) == 0 && state->terminals.count(&op) == 0;
825   };
826   auto loadAndStores = matcher::Op(notVectorizedThisPattern);
827   SmallVector<NestedMatch, 8> loadAndStoresMatches;
828   loadAndStores.match(loop.getOperation(), &loadAndStoresMatches);
829   for (auto ls : loadAndStoresMatches) {
830     auto *opInst = ls.getMatchedOperation();
831     auto load = dyn_cast<AffineLoadOp>(opInst);
832     auto store = dyn_cast<AffineStoreOp>(opInst);
833     LLVM_DEBUG(opInst->print(dbgs()));
834     LogicalResult result =
835         load ? vectorizeRootOrTerminal(loop.getInductionVar(), load, state)
836              : vectorizeRootOrTerminal(loop.getInductionVar(), store, state);
837     if (failed(result)) {
838       return failure();
839     }
840   }
841   return success();
842 }
843 
844 /// Returns a FilterFunctionType that can be used in NestedPattern to match a
845 /// loop whose underlying load/store accesses are either invariant or all
846 // varying along the `fastestVaryingMemRefDimension`.
847 static FilterFunctionType
848 isVectorizableLoopPtrFactory(const DenseSet<Operation *> &parallelLoops,
849                              int fastestVaryingMemRefDimension) {
850   return [&parallelLoops, fastestVaryingMemRefDimension](Operation &forOp) {
851     auto loop = cast<AffineForOp>(forOp);
852     auto parallelIt = parallelLoops.find(loop);
853     if (parallelIt == parallelLoops.end())
854       return false;
855     int memRefDim = -1;
856     auto vectorizableBody =
857         isVectorizableLoopBody(loop, &memRefDim, vectorTransferPattern());
858     if (!vectorizableBody)
859       return false;
860     return memRefDim == -1 || fastestVaryingMemRefDimension == -1 ||
861            memRefDim == fastestVaryingMemRefDimension;
862   };
863 }
864 
865 /// Apply vectorization of `loop` according to `state`. This is only triggered
866 /// if all vectorizations in `childrenMatches` have already succeeded
867 /// recursively in DFS post-order.
868 static LogicalResult
869 vectorizeLoopsAndLoadsRecursively(NestedMatch oneMatch,
870                                   VectorizationState *state) {
871   auto *loopInst = oneMatch.getMatchedOperation();
872   auto loop = cast<AffineForOp>(loopInst);
873   auto childrenMatches = oneMatch.getMatchedChildren();
874 
875   // 1. DFS postorder recursion, if any of my children fails, I fail too.
876   for (auto m : childrenMatches) {
877     if (failed(vectorizeLoopsAndLoadsRecursively(m, state))) {
878       return failure();
879     }
880   }
881 
882   // 2. This loop may have been omitted from vectorization for various reasons
883   // (e.g. due to the performance model or pattern depth > vector size).
884   auto it = state->strategy->loopToVectorDim.find(loopInst);
885   if (it == state->strategy->loopToVectorDim.end()) {
886     return success();
887   }
888 
889   // 3. Actual post-order transformation.
890   auto vectorDim = it->second;
891   assert(vectorDim < state->strategy->vectorSizes.size() &&
892          "vector dim overflow");
893   //   a. get actual vector size
894   auto vectorSize = state->strategy->vectorSizes[vectorDim];
895   //   b. loop transformation for early vectorization is still subject to
896   //     exploratory tradeoffs (see top of the file). Apply coarsening, i.e.:
897   //        | ub -> ub
898   //        | step -> step * vectorSize
899   LLVM_DEBUG(dbgs() << "\n[early-vect] vectorizeForOp by " << vectorSize
900                     << " : ");
901   LLVM_DEBUG(loopInst->print(dbgs()));
902   return vectorizeAffineForOp(loop, loop.getStep() * vectorSize, state);
903 }
904 
905 /// Tries to transform a scalar constant into a vector splat of that constant.
906 /// Returns the vectorized splat operation if the constant is a valid vector
907 /// element type.
908 /// If `type` is not a valid vector type or if the scalar constant is not a
909 /// valid vector element type, returns nullptr.
910 static Value vectorizeConstant(Operation *op, ConstantOp constant, Type type) {
911   if (!type || !type.isa<VectorType>() ||
912       !VectorType::isValidElementType(constant.getType())) {
913     return nullptr;
914   }
915   OpBuilder b(op);
916   Location loc = op->getLoc();
917   auto vectorType = type.cast<VectorType>();
918   auto attr = DenseElementsAttr::get(vectorType, constant.getValue());
919   auto *constantOpInst = constant.getOperation();
920 
921   OperationState state(loc, constantOpInst->getName().getStringRef(), {},
922                        {vectorType}, {b.getNamedAttr("value", attr)});
923 
924   return b.createOperation(state)->getResult(0);
925 }
926 
927 /// Tries to vectorize a given operand `op` of Operation `op` during
928 /// def-chain propagation or during terminal vectorization, by applying the
929 /// following logic:
930 /// 1. if the defining operation is part of the vectorizedSet (i.e. vectorized
931 ///    useby -def propagation), `op` is already in the proper vector form;
932 /// 2. otherwise, the `op` may be in some other vector form that fails to
933 ///    vectorize atm (i.e. broadcasting required), returns nullptr to indicate
934 ///    failure;
935 /// 3. if the `op` is a constant, returns the vectorized form of the constant;
936 /// 4. non-constant scalars are currently non-vectorizable, in particular to
937 ///    guard against vectorizing an index which may be loop-variant and needs
938 ///    special handling.
939 ///
940 /// In particular this logic captures some of the use cases where definitions
941 /// that are not scoped under the current pattern are needed to vectorize.
942 /// One such example is top level function constants that need to be splatted.
943 ///
944 /// Returns an operand that has been vectorized to match `state`'s strategy if
945 /// vectorization is possible with the above logic. Returns nullptr otherwise.
946 ///
947 /// TODO(ntv): handle more complex cases.
948 static Value vectorizeOperand(Value operand, Operation *op,
949                               VectorizationState *state) {
950   LLVM_DEBUG(dbgs() << "\n[early-vect]vectorize operand: " << operand);
951   // 1. If this value has already been vectorized this round, we are done.
952   if (state->vectorizedSet.count(operand.getDefiningOp()) > 0) {
953     LLVM_DEBUG(dbgs() << " -> already vector operand");
954     return operand;
955   }
956   // 1.b. Delayed on-demand replacement of a use.
957   //    Note that we cannot just call replaceAllUsesWith because it may result
958   //    in ops with mixed types, for ops whose operands have not all yet
959   //    been vectorized. This would be invalid IR.
960   auto it = state->replacementMap.find(operand);
961   if (it != state->replacementMap.end()) {
962     auto res = it->second;
963     LLVM_DEBUG(dbgs() << "-> delayed replacement by: " << res);
964     return res;
965   }
966   // 2. TODO(ntv): broadcast needed.
967   if (operand.getType().isa<VectorType>()) {
968     LLVM_DEBUG(dbgs() << "-> non-vectorizable");
969     return nullptr;
970   }
971   // 3. vectorize constant.
972   if (auto constant = dyn_cast_or_null<ConstantOp>(operand.getDefiningOp())) {
973     return vectorizeConstant(
974         op, constant,
975         VectorType::get(state->strategy->vectorSizes, operand.getType()));
976   }
977   // 4. currently non-vectorizable.
978   LLVM_DEBUG(dbgs() << "-> non-vectorizable: " << operand);
979   return nullptr;
980 }
981 
982 /// Encodes Operation-specific behavior for vectorization. In general we assume
983 /// that all operands of an op must be vectorized but this is not always true.
984 /// In the future, it would be nice to have a trait that describes how a
985 /// particular operation vectorizes. For now we implement the case distinction
986 /// here.
987 /// Returns a vectorized form of an operation or nullptr if vectorization fails.
988 // TODO(ntv): consider adding a trait to Op to describe how it gets vectorized.
989 // Maybe some Ops are not vectorizable or require some tricky logic, we cannot
990 // do one-off logic here; ideally it would be TableGen'd.
991 static Operation *vectorizeOneOperation(Operation *opInst,
992                                         VectorizationState *state) {
993   // Sanity checks.
994   assert(!isa<AffineLoadOp>(opInst) &&
995          "all loads must have already been fully vectorized independently");
996   assert(!isa<vector::TransferReadOp>(opInst) &&
997          "vector.transfer_read cannot be further vectorized");
998   assert(!isa<vector::TransferWriteOp>(opInst) &&
999          "vector.transfer_write cannot be further vectorized");
1000 
1001   if (auto store = dyn_cast<AffineStoreOp>(opInst)) {
1002     OpBuilder b(opInst);
1003     auto memRef = store.getMemRef();
1004     auto value = store.getValueToStore();
1005     auto vectorValue = vectorizeOperand(value, opInst, state);
1006     if (!vectorValue)
1007       return nullptr;
1008 
1009     ValueRange mapOperands = store.getMapOperands();
1010     SmallVector<Value, 8> indices;
1011     indices.reserve(store.getMemRefType().getRank());
1012     if (store.getAffineMap() !=
1013         b.getMultiDimIdentityMap(store.getMemRefType().getRank())) {
1014       computeMemoryOpIndices(opInst, store.getAffineMap(), mapOperands,
1015                              indices);
1016     } else {
1017       indices.append(mapOperands.begin(), mapOperands.end());
1018     }
1019 
1020     auto permutationMap =
1021         makePermutationMap(opInst, indices, state->strategy->loopToVectorDim);
1022     if (!permutationMap)
1023       return nullptr;
1024     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ permutationMap: ");
1025     LLVM_DEBUG(permutationMap.print(dbgs()));
1026     auto transfer = b.create<vector::TransferWriteOp>(
1027         opInst->getLoc(), vectorValue, memRef, indices,
1028         AffineMapAttr::get(permutationMap));
1029     auto *res = transfer.getOperation();
1030     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ vectorized store: " << *res);
1031     // "Terminals" (i.e. AffineStoreOps) are erased on the spot.
1032     opInst->erase();
1033     return res;
1034   }
1035   if (opInst->getNumRegions() != 0)
1036     return nullptr;
1037 
1038   SmallVector<Type, 8> vectorTypes;
1039   for (auto v : opInst->getResults()) {
1040     vectorTypes.push_back(
1041         VectorType::get(state->strategy->vectorSizes, v.getType()));
1042   }
1043   SmallVector<Value, 8> vectorOperands;
1044   for (auto v : opInst->getOperands()) {
1045     vectorOperands.push_back(vectorizeOperand(v, opInst, state));
1046   }
1047   // Check whether a single operand is null. If so, vectorization failed.
1048   bool success = llvm::all_of(vectorOperands, [](Value op) { return op; });
1049   if (!success) {
1050     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ an operand failed vectorize");
1051     return nullptr;
1052   }
1053 
1054   // Create a clone of the op with the proper operands and return types.
1055   // TODO(ntv): The following assumes there is always an op with a fixed
1056   // name that works both in scalar mode and vector mode.
1057   // TODO(ntv): Is it worth considering an Operation.clone operation which
1058   // changes the type so we can promote an Operation with less boilerplate?
1059   OpBuilder b(opInst);
1060   OperationState newOp(opInst->getLoc(), opInst->getName().getStringRef(),
1061                        vectorOperands, vectorTypes, opInst->getAttrs(),
1062                        /*successors=*/{},
1063                        /*regions=*/{}, opInst->hasResizableOperandsList());
1064   return b.createOperation(newOp);
1065 }
1066 
1067 /// Iterates over the forward slice from the loads in the vectorization pattern
1068 /// and rewrites them using their vectorized counterpart by:
1069 ///   1. Create the forward slice starting from the loads in the vectorization
1070 ///   pattern.
1071 ///   2. Topologically sorts the forward slice.
1072 ///   3. For each operation in the slice, create the vector form of this
1073 ///   operation, replacing each operand by a replacement operands retrieved from
1074 ///   replacementMap. If any such replacement is missing, vectorization fails.
1075 static LogicalResult vectorizeNonTerminals(VectorizationState *state) {
1076   // 1. create initial worklist with the uses of the roots.
1077   SetVector<Operation *> worklist;
1078   // Note: state->roots have already been vectorized and must not be vectorized
1079   // again. This fits `getForwardSlice` which does not insert `op` in the
1080   // result.
1081   // Note: we have to exclude terminals because some of their defs may not be
1082   // nested under the vectorization pattern (e.g. constants defined in an
1083   // encompassing scope).
1084   // TODO(ntv): Use a backward slice for terminals, avoid special casing and
1085   // merge implementations.
1086   for (auto *op : state->roots) {
1087     getForwardSlice(op, &worklist, [state](Operation *op) {
1088       return state->terminals.count(op) == 0; // propagate if not terminal
1089     });
1090   }
1091   // We merged multiple slices, topological order may not hold anymore.
1092   worklist = topologicalSort(worklist);
1093 
1094   for (unsigned i = 0; i < worklist.size(); ++i) {
1095     auto *op = worklist[i];
1096     LLVM_DEBUG(dbgs() << "\n[early-vect] vectorize use: ");
1097     LLVM_DEBUG(op->print(dbgs()));
1098 
1099     // Create vector form of the operation.
1100     // Insert it just before op, on success register op as replaced.
1101     auto *vectorizedInst = vectorizeOneOperation(op, state);
1102     if (!vectorizedInst) {
1103       return failure();
1104     }
1105 
1106     // 3. Register replacement for future uses in the scope.
1107     //    Note that we cannot just call replaceAllUsesWith because it may
1108     //    result in ops with mixed types, for ops whose operands have not all
1109     //    yet been vectorized. This would be invalid IR.
1110     state->registerReplacement(op, vectorizedInst);
1111   }
1112   return success();
1113 }
1114 
1115 /// Vectorization is a recursive procedure where anything below can fail.
1116 /// The root match thus needs to maintain a clone for handling failure.
1117 /// Each root may succeed independently but will otherwise clean after itself if
1118 /// anything below it fails.
1119 static LogicalResult vectorizeRootMatch(NestedMatch m,
1120                                         VectorizationStrategy *strategy) {
1121   auto loop = cast<AffineForOp>(m.getMatchedOperation());
1122   OperationFolder folder(loop.getContext());
1123   VectorizationState state;
1124   state.strategy = strategy;
1125   state.folder = &folder;
1126 
1127   // Since patterns are recursive, they can very well intersect.
1128   // Since we do not want a fully greedy strategy in general, we decouple
1129   // pattern matching, from profitability analysis, from application.
1130   // As a consequence we must check that each root pattern is still
1131   // vectorizable. If a pattern is not vectorizable anymore, we just skip it.
1132   // TODO(ntv): implement a non-greedy profitability analysis that keeps only
1133   // non-intersecting patterns.
1134   if (!isVectorizableLoopBody(loop, vectorTransferPattern())) {
1135     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ loop is not vectorizable");
1136     return failure();
1137   }
1138 
1139   /// Sets up error handling for this root loop. This is how the root match
1140   /// maintains a clone for handling failure and restores the proper state via
1141   /// RAII.
1142   auto *loopInst = loop.getOperation();
1143   OpBuilder builder(loopInst);
1144   auto clonedLoop = cast<AffineForOp>(builder.clone(*loopInst));
1145   struct Guard {
1146     LogicalResult failure() {
1147       loop.getInductionVar().replaceAllUsesWith(clonedLoop.getInductionVar());
1148       loop.erase();
1149       return mlir::failure();
1150     }
1151     LogicalResult success() {
1152       clonedLoop.erase();
1153       return mlir::success();
1154     }
1155     AffineForOp loop;
1156     AffineForOp clonedLoop;
1157   } guard{loop, clonedLoop};
1158 
1159   //////////////////////////////////////////////////////////////////////////////
1160   // Start vectorizing.
1161   // From now on, any error triggers the scope guard above.
1162   //////////////////////////////////////////////////////////////////////////////
1163   // 1. Vectorize all the loops matched by the pattern, recursively.
1164   // This also vectorizes the roots (AffineLoadOp) as well as registers the
1165   // terminals (AffineStoreOp) for post-processing vectorization (we need to
1166   // wait for all use-def chains into them to be vectorized first).
1167   if (failed(vectorizeLoopsAndLoadsRecursively(m, &state))) {
1168     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ failed root vectorizeLoop");
1169     return guard.failure();
1170   }
1171 
1172   // 2. Vectorize operations reached by use-def chains from root except the
1173   // terminals (store operations) that need to be post-processed separately.
1174   // TODO(ntv): add more as we expand.
1175   if (failed(vectorizeNonTerminals(&state))) {
1176     LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ failed vectorizeNonTerminals");
1177     return guard.failure();
1178   }
1179 
1180   // 3. Post-process terminals.
1181   // Note: we have to post-process terminals because some of their defs may not
1182   // be nested under the vectorization pattern (e.g. constants defined in an
1183   // encompassing scope).
1184   // TODO(ntv): Use a backward slice for terminals, avoid special casing and
1185   // merge implementations.
1186   for (auto *op : state.terminals) {
1187     if (!vectorizeOneOperation(op, &state)) { // nullptr == failure
1188       LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ failed to vectorize terminals");
1189       return guard.failure();
1190     }
1191   }
1192 
1193   // 4. Finish this vectorization pattern.
1194   LLVM_DEBUG(dbgs() << "\n[early-vect]+++++ success vectorizing pattern");
1195   state.finishVectorizationPattern();
1196   return guard.success();
1197 }
1198 
1199 /// Applies vectorization to the current Function by searching over a bunch of
1200 /// predetermined patterns.
1201 void Vectorize::runOnFunction() {
1202   FuncOp f = getFunction();
1203   if (!fastestVaryingPattern.empty() &&
1204       fastestVaryingPattern.size() != vectorSizes.size()) {
1205     f.emitRemark("Fastest varying pattern specified with different size than "
1206                  "the vector size.");
1207     return signalPassFailure();
1208   }
1209 
1210   // Thread-safe RAII local context, BumpPtrAllocator freed on exit.
1211   NestedPatternContext mlContext;
1212 
1213   DenseSet<Operation *> parallelLoops;
1214   f.walk([&parallelLoops](AffineForOp loop) {
1215     if (isLoopParallel(loop))
1216       parallelLoops.insert(loop);
1217   });
1218 
1219   for (auto &pat :
1220        makePatterns(parallelLoops, vectorSizes.size(), fastestVaryingPattern)) {
1221     LLVM_DEBUG(dbgs() << "\n******************************************");
1222     LLVM_DEBUG(dbgs() << "\n******************************************");
1223     LLVM_DEBUG(dbgs() << "\n[early-vect] new pattern on Function\n");
1224     LLVM_DEBUG(f.print(dbgs()));
1225     unsigned patternDepth = pat.getDepth();
1226 
1227     SmallVector<NestedMatch, 8> matches;
1228     pat.match(f, &matches);
1229     // Iterate over all the top-level matches and vectorize eagerly.
1230     // This automatically prunes intersecting matches.
1231     for (auto m : matches) {
1232       VectorizationStrategy strategy;
1233       // TODO(ntv): depending on profitability, elect to reduce the vector size.
1234       strategy.vectorSizes.assign(vectorSizes.begin(), vectorSizes.end());
1235       if (failed(analyzeProfitability(m.getMatchedChildren(), 1, patternDepth,
1236                                       &strategy))) {
1237         continue;
1238       }
1239       vectorizeLoopIfProfitable(m.getMatchedOperation(), 0, patternDepth,
1240                                 &strategy);
1241       // TODO(ntv): if pattern does not apply, report it; alter the
1242       // cost/benefit.
1243       vectorizeRootMatch(m, &strategy);
1244       // TODO(ntv): some diagnostics if failure to vectorize occurs.
1245     }
1246   }
1247   LLVM_DEBUG(dbgs() << "\n");
1248 }
1249 
1250 std::unique_ptr<OperationPass<FuncOp>>
1251 mlir::createSuperVectorizePass(ArrayRef<int64_t> virtualVectorSize) {
1252   return std::make_unique<Vectorize>(virtualVectorSize);
1253 }
1254 std::unique_ptr<OperationPass<FuncOp>> mlir::createSuperVectorizePass() {
1255   return std::make_unique<Vectorize>();
1256 }
1257