MLIR 24.0.0git
VectorToSCF.cpp
Go to the documentation of this file.
1//===- VectorToSCF.cpp - Convert vector to SCF dialect ----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements lowering of vector transfer operations to SCF.
10//
11//===----------------------------------------------------------------------===//
12
13#include <numeric>
14#include <optional>
15
17
26#include "mlir/IR/Builders.h"
27#include "mlir/Pass/Pass.h"
29#include "llvm/ADT/STLExtras.h"
30
31namespace mlir {
32#define GEN_PASS_DEF_CONVERTVECTORTOSCF
33#include "mlir/Conversion/Passes.h.inc"
34} // namespace mlir
35
36using namespace mlir;
37using vector::TransferReadOp;
38using vector::TransferWriteOp;
39
40namespace {
41
42/// Attribute name used for labeling transfer ops during progressive lowering.
43static const char kPassLabel[] = "__vector_to_scf_lowering__";
44
45/// Return true if this transfer op operates on a source tensor.
46static bool isTensorOp(VectorTransferOpInterface xferOp) {
47 if (isa<RankedTensorType>(xferOp.getShapedType())) {
48 if (isa<vector::TransferWriteOp>(xferOp)) {
49 // TransferWriteOps on tensors have a result.
50 assert(xferOp->getNumResults() > 0);
51 }
52 return true;
53 }
54 return false;
55}
56
57/// Patterns that inherit from this struct have access to
58/// VectorTransferToSCFOptions.
59template <typename OpTy>
60struct VectorToSCFPattern : public OpRewritePattern<OpTy> {
61 explicit VectorToSCFPattern(MLIRContext *context,
62 VectorTransferToSCFOptions opt)
63 : OpRewritePattern<OpTy>(context), options(opt) {}
64
65 LogicalResult checkLowerTensors(VectorTransferOpInterface xferOp,
66 PatternRewriter &rewriter) const {
67 if (isTensorOp(xferOp) && !options.lowerTensors) {
68 return rewriter.notifyMatchFailure(
69 xferOp, "lowering tensor transfers is disabled");
70 }
71 return success();
72 }
73
74 VectorTransferToSCFOptions options;
75};
76
77/// Given a vector transfer op, calculate which dimension of the `source`
78/// memref should be unpacked in the next application of TransferOpConversion.
79/// A return value of std::nullopt indicates a broadcast.
80template <typename OpTy>
81static std::optional<int64_t> unpackedDim(OpTy xferOp) {
82 // TODO: support 0-d corner case.
83 assert(xferOp.getTransferRank() > 0 && "unexpected 0-d transfer");
84 auto map = xferOp.getPermutationMap();
85 if (auto expr = dyn_cast<AffineDimExpr>(map.getResult(0))) {
86 return expr.getPosition();
87 }
88 assert(xferOp.isBroadcastDim(0) &&
89 "Expected AffineDimExpr or AffineConstantExpr");
90 return std::nullopt;
91}
92
93/// Compute the permutation map for the new (N-1)-D vector transfer op. This
94/// map is identical to the current permutation map, but the first result is
95/// omitted.
96template <typename OpTy>
97static AffineMap unpackedPermutationMap(OpBuilder &b, OpTy xferOp) {
98 // TODO: support 0-d corner case.
99 assert(xferOp.getTransferRank() > 0 && "unexpected 0-d transfer");
100 auto map = xferOp.getPermutationMap();
101 return AffineMap::get(map.getNumDims(), 0, map.getResults().drop_front(),
102 b.getContext());
103}
104
105/// Calculate the indices for the new vector transfer op.
106///
107/// E.g.: transfer_read %A[%a, %b, %c, %d] ... : vector<5x4x3xf32> ...
108/// --> transfer_read %A[%a, %b + iv, %c, %d] ... vector<4x3f32>
109/// ^^^^^^
110/// `iv` is the iteration variable of the (new) surrounding loop.
111template <typename OpTy>
112static void getXferIndices(OpBuilder &b, OpTy xferOp, Value iv,
114 typename OpTy::Adaptor adaptor(xferOp);
115 // Corresponding memref dim of the vector dim that is unpacked.
116 auto dim = unpackedDim(xferOp);
117 auto prevIndices = adaptor.getIndices();
118 indices.append(prevIndices.begin(), prevIndices.end());
119
120 Location loc = xferOp.getLoc();
121 bool isBroadcast = !dim.has_value();
122 if (!isBroadcast) {
123 AffineExpr d0, d1;
124 bindDims(xferOp.getContext(), d0, d1);
125 Value offset = adaptor.getIndices()[*dim];
126 indices[*dim] =
127 affine::makeComposedAffineApply(b, loc, d0 + d1, {offset, iv});
128 }
129}
130
131static void maybeYieldValue(OpBuilder &b, Location loc, bool hasRetVal,
132 Value value) {
133 if (hasRetVal) {
134 assert(value && "Expected non-empty value");
135 scf::YieldOp::create(b, loc, value);
136 } else {
137 scf::YieldOp::create(b, loc);
138 }
139}
140
141/// Generates a boolean Value that is true if the iv-th bit in xferOp's mask
142/// is set to true. No such check is generated under following circumstances:
143/// * xferOp does not have a mask.
144/// * xferOp's mask is not 1D. (In case of (N>1)-D, a subvector of the mask is
145/// computed and attached to the new transfer op in the pattern.)
146/// * The to-be-unpacked dim of xferOp is a broadcast.
147template <typename OpTy>
148static Value generateMaskCheck(OpBuilder &b, OpTy xferOp, Value iv) {
149 if (!xferOp.getMask())
150 return Value();
151 if (xferOp.getMaskType().getRank() != 1)
152 return Value();
153 if (xferOp.isBroadcastDim(0))
154 return Value();
155
156 Location loc = xferOp.getLoc();
157 return vector::ExtractOp::create(b, loc, xferOp.getMask(), iv);
158}
159
160/// Helper function TransferOpConversion and TransferOp1dConversion.
161/// Generate an in-bounds check if the transfer op may go out-of-bounds on the
162/// specified dimension `dim` with the loop iteration variable `iv`.
163/// E.g., when unpacking dimension 0 from:
164/// ```
165/// %vec = vector.transfer_read %A[%a, %b] %cst
166/// : vector<5x4xf32>, memref<?x?xf32>
167/// ```
168/// An if check similar to this will be generated inside the loop:
169/// ```
170/// %d = memref.dim %A, %c0 : memref<?x?xf32>
171/// if (%a + iv < %d) {
172/// (in-bounds case)
173/// } else {
174/// (out-of-bounds case)
175/// }
176/// ```
177///
178/// If the transfer is 1D and has a mask, this function generates a more complex
179/// check also accounts for potentially masked out elements.
180///
181/// This function variant returns the value returned by `inBoundsCase` or
182/// `outOfBoundsCase`. The MLIR type of the return value must be specified in
183/// `resultTypes`.
184template <typename OpTy>
185static Value generateInBoundsCheck(
186 OpBuilder &b, OpTy xferOp, Value iv, std::optional<int64_t> dim,
187 TypeRange resultTypes,
188 function_ref<Value(OpBuilder &, Location)> inBoundsCase,
189 function_ref<Value(OpBuilder &, Location)> outOfBoundsCase = nullptr) {
190 bool hasRetVal = !resultTypes.empty();
191 Value cond; // Condition to be built...
192
193 // Condition check 1: Access in-bounds?
194 bool isBroadcast = !dim; // No in-bounds check for broadcasts.
195 Location loc = xferOp.getLoc();
196 ImplicitLocOpBuilder lb(xferOp.getLoc(), b);
197 if (!xferOp.isDimInBounds(0) && !isBroadcast) {
198 Value memrefDim = vector::createOrFoldDimOp(b, loc, xferOp.getBase(), *dim);
199 AffineExpr d0, d1;
200 bindDims(xferOp.getContext(), d0, d1);
201 Value base = xferOp.getIndices()[*dim];
202 Value memrefIdx =
203 affine::makeComposedAffineApply(b, loc, d0 + d1, {base, iv});
204 cond = arith::CmpIOp::create(lb, arith::CmpIPredicate::sgt, memrefDim,
205 memrefIdx);
206 }
207
208 // Condition check 2: Masked in?
209 if (auto maskCond = generateMaskCheck(b, xferOp, iv)) {
210 if (cond)
211 cond = arith::AndIOp::create(lb, cond, maskCond);
212 else
213 cond = maskCond;
214 }
215
216 // If the condition is non-empty, generate an SCF::IfOp.
217 if (cond) {
218 auto check = scf::IfOp::create(
219 lb, cond,
220 /*thenBuilder=*/
221 [&](OpBuilder &b, Location loc) {
222 maybeYieldValue(b, loc, hasRetVal, inBoundsCase(b, loc));
223 },
224 /*elseBuilder=*/
225 [&](OpBuilder &b, Location loc) {
226 if (outOfBoundsCase) {
227 maybeYieldValue(b, loc, hasRetVal, outOfBoundsCase(b, loc));
228 } else {
229 scf::YieldOp::create(b, loc);
230 }
231 });
232
233 return hasRetVal ? check.getResult(0) : Value();
234 }
235
236 // Condition is empty, no need for an SCF::IfOp.
237 return inBoundsCase(b, loc);
238}
239
240/// In this function variant, `inBoundsCase` and `outOfBoundsCase` do not have
241/// a return value. Consequently, this function does not have a return value.
242template <typename OpTy>
243static void generateInBoundsCheck(
244 OpBuilder &b, OpTy xferOp, Value iv, std::optional<int64_t> dim,
245 function_ref<void(OpBuilder &, Location)> inBoundsCase,
246 function_ref<void(OpBuilder &, Location)> outOfBoundsCase = nullptr) {
247 generateInBoundsCheck(
248 b, xferOp, iv, dim, /*resultTypes=*/TypeRange(),
249 /*inBoundsCase=*/
250 [&](OpBuilder &b, Location loc) {
251 inBoundsCase(b, loc);
252 return Value();
253 },
254 /*outOfBoundsCase=*/
255 [&](OpBuilder &b, Location loc) {
256 if (outOfBoundsCase)
257 outOfBoundsCase(b, loc);
258 return Value();
259 });
260}
261
262/// Given an ArrayAttr, return a copy where the first element is dropped.
263static ArrayAttr dropFirstElem(OpBuilder &b, ArrayAttr attr) {
264 if (!attr)
265 return attr;
266 return ArrayAttr::get(b.getContext(), attr.getValue().drop_front());
267}
268
269/// Add the pass label to a vector transfer op if its rank is not the target
270/// rank.
271template <typename OpTy>
272static void maybeApplyPassLabel(OpBuilder &b, OpTy newXferOp,
273 unsigned targetRank) {
274 if (newXferOp.getVectorType().getRank() > targetRank)
275 newXferOp->setDiscardableAttr(kPassLabel, b.getUnitAttr());
276}
277
278namespace lowering_n_d {
279
280/// Helper data structure for data and mask buffers.
281struct BufferAllocs {
282 Value dataBuffer;
283 Value maskBuffer;
284};
285
286// TODO: Parallelism and threadlocal considerations with a ParallelScope trait.
287static Operation *getAutomaticAllocationScope(Operation *op) {
288 Operation *scope =
290 assert(scope && "Expected op to be inside automatic allocation scope");
291 return scope;
292}
293
294/// Allocate temporary buffers for data (vector) and mask (if present).
295template <typename OpTy>
296static BufferAllocs allocBuffers(OpBuilder &b, OpTy xferOp) {
297 Location loc = xferOp.getLoc();
299 Operation *scope = getAutomaticAllocationScope(xferOp);
300 assert(scope->getNumRegions() == 1 &&
301 "AutomaticAllocationScope with >1 regions");
302 b.setInsertionPointToStart(&scope->getRegion(0).front());
303
304 BufferAllocs result;
305 auto bufferType = MemRefType::get({}, xferOp.getVectorType());
306 result.dataBuffer = memref::AllocaOp::create(b, loc, bufferType);
307
308 if (xferOp.getMask()) {
309 auto maskType = MemRefType::get({}, xferOp.getMask().getType());
310 auto maskBuffer = memref::AllocaOp::create(b, loc, maskType);
311 b.setInsertionPoint(xferOp);
312 memref::StoreOp::create(b, loc, xferOp.getMask(), maskBuffer);
313 result.maskBuffer =
314 memref::LoadOp::create(b, loc, maskBuffer, ValueRange());
315 }
316
317 return result;
318}
319
320/// Given a MemRefType with VectorType element type, unpack one dimension from
321/// the VectorType into the MemRefType.
322///
323/// E.g.: memref<9xvector<5x6xf32>> --> memref<9x5xvector<6xf32>>
324static FailureOr<MemRefType> unpackOneDim(MemRefType type) {
325 auto vectorType = dyn_cast<VectorType>(type.getElementType());
326 // Vectors with leading scalable dims are not supported.
327 // It may be possible to support these in future by using dynamic memref dims.
328 if (vectorType.getScalableDims().front())
329 return failure();
330 auto memrefShape = type.getShape();
331 SmallVector<int64_t, 8> newMemrefShape;
332 newMemrefShape.append(memrefShape.begin(), memrefShape.end());
333 newMemrefShape.push_back(vectorType.getDimSize(0));
334 return MemRefType::get(newMemrefShape,
335 VectorType::Builder(vectorType).dropDim(0));
336}
337
338/// Given a transfer op, find the memref from which the mask is loaded. This
339/// is similar to Strategy<TransferWriteOp>::getBuffer.
340template <typename OpTy>
341static Value getMaskBuffer(OpTy xferOp) {
342 assert(xferOp.getMask() && "Expected that transfer op has mask");
343 auto loadOp = xferOp.getMask().template getDefiningOp<memref::LoadOp>();
344 assert(loadOp && "Expected transfer op mask produced by LoadOp");
345 return loadOp.getMemRef();
346}
347
348/// Codegen strategy, depending on the operation.
349template <typename OpTy>
350struct Strategy;
351
352/// Code strategy for vector TransferReadOp.
353template <>
354struct Strategy<TransferReadOp> {
355 /// Find the StoreOp that is used for writing the current TransferReadOp's
356 /// result to the temporary buffer allocation.
357 static memref::StoreOp getStoreOp(TransferReadOp xferOp) {
358 assert(xferOp->hasOneUse() && "Expected exactly one use of TransferReadOp");
359 auto storeOp = dyn_cast<memref::StoreOp>((*xferOp->use_begin()).getOwner());
360 assert(storeOp && "Expected TransferReadOp result used by StoreOp");
361 return storeOp;
362 }
363
364 /// Find the temporary buffer allocation. All labeled TransferReadOps are
365 /// used like this, where %buf is either the buffer allocation or a type cast
366 /// of the buffer allocation:
367 /// ```
368 /// %vec = vector.transfer_read ... { __vector_to_scf_lowering__ } ...
369 /// memref.store %vec, %buf[...] ...
370 /// ```
371 static Value getBuffer(TransferReadOp xferOp) {
372 return getStoreOp(xferOp).getMemRef();
373 }
374
375 /// Retrieve the indices of the current StoreOp that stores into the buffer.
376 static void getBufferIndices(TransferReadOp xferOp,
378 auto storeOp = getStoreOp(xferOp);
379 auto prevIndices = memref::StoreOpAdaptor(storeOp).getIndices();
380 indices.append(prevIndices.begin(), prevIndices.end());
381 }
382
383 /// Rewrite the TransferReadOp, assuming that there are no out-of-bounds
384 /// accesses on the to-be-unpacked dimension.
385 ///
386 /// 1. Generate a new (N-1)-d TransferReadOp using the loop iteration
387 /// variable `iv`.
388 /// 2. Store the result into the (already `vector.type_cast`ed) buffer.
389 ///
390 /// E.g.:
391 /// ```
392 /// %vec = vector.transfer_read %A[%a+%i, %b, %c], %cst
393 /// : memref<?x?x?xf32>, vector<4x3xf32>
394 /// memref.store %vec, %buf[%i] : memref<5xvector<4x3xf32>>
395 /// ```
396 /// Is rewritten to:
397 /// ```
398 /// %casted = vector.type_cast %buf
399 /// : memref<5xvector<4x3xf32>> to memref<5x4xvector<3xf32>>
400 /// for %j = 0 to 4 {
401 /// %vec = vector.transfer_read %A[%a+%i, %b+%j, %c], %cst
402 /// : memref<?x?x?xf32>, vector<3xf32>
403 /// memref.store %vec, %casted[%i, %j] : memref<5x4xvector<3xf32>>
404 /// }
405 /// ```
406 ///
407 /// Note: The loop and type cast are generated in TransferOpConversion.
408 /// The original TransferReadOp and store op are deleted in `cleanup`.
409 /// Note: The `mask` operand is set in TransferOpConversion.
410 static TransferReadOp rewriteOp(OpBuilder &b,
412 TransferReadOp xferOp, Value buffer, Value iv,
413 ValueRange /*loopState*/) {
414 SmallVector<Value, 8> storeIndices;
415 getBufferIndices(xferOp, storeIndices);
416 storeIndices.push_back(iv);
417
418 SmallVector<Value, 8> xferIndices;
419 getXferIndices(b, xferOp, iv, xferIndices);
420
421 Location loc = xferOp.getLoc();
422 auto bufferType = dyn_cast<ShapedType>(buffer.getType());
423 auto vecType = dyn_cast<VectorType>(bufferType.getElementType());
424 auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
425 auto newXferOp = vector::TransferReadOp::create(
426 b, loc, vecType, xferOp.getBase(), xferIndices,
427 AffineMapAttr::get(unpackedPermutationMap(b, xferOp)),
428 xferOp.getPadding(), Value(), inBoundsAttr);
429
430 maybeApplyPassLabel(b, newXferOp, options.targetRank);
431
432 memref::StoreOp::create(b, loc, newXferOp.getVector(), buffer,
433 storeIndices);
434 return newXferOp;
435 }
436
437 /// Handle out-of-bounds accesses on the to-be-unpacked dimension: Write
438 /// padding value to the temporary buffer.
439 static Value handleOutOfBoundsDim(OpBuilder &b, TransferReadOp xferOp,
440 Value buffer, Value iv,
441 ValueRange /*loopState*/) {
442 SmallVector<Value, 8> storeIndices;
443 getBufferIndices(xferOp, storeIndices);
444 storeIndices.push_back(iv);
445
446 Location loc = xferOp.getLoc();
447 auto bufferType = dyn_cast<ShapedType>(buffer.getType());
448 auto vecType = dyn_cast<VectorType>(bufferType.getElementType());
449 auto vec =
450 vector::BroadcastOp::create(b, loc, vecType, xferOp.getPadding());
451 memref::StoreOp::create(b, loc, vec, buffer, storeIndices);
452
453 return Value();
454 }
455
456 /// Cleanup after rewriting the op.
457 static void cleanup(PatternRewriter &rewriter, TransferReadOp xferOp,
458 scf::ForOp /*forOp*/) {
459 rewriter.eraseOp(getStoreOp(xferOp));
460 rewriter.eraseOp(xferOp);
461 }
462
463 /// Return the initial loop state for the generated scf.for loop.
464 static Value initialLoopState(TransferReadOp xferOp) { return Value(); }
465};
466
467/// Codegen strategy for vector TransferWriteOp.
468template <>
469struct Strategy<TransferWriteOp> {
470 /// Find the temporary buffer allocation. All labeled TransferWriteOps are
471 /// used like this, where %buf is either the buffer allocation or a type cast
472 /// of the buffer allocation:
473 /// ```
474 /// %vec = memref.load %buf[...] ...
475 /// vector.transfer_write %vec ... { __vector_to_scf_lowering__ } ...
476 /// ```
477 static Value getBuffer(TransferWriteOp xferOp) {
478 auto loadOp = xferOp.getVector().getDefiningOp<memref::LoadOp>();
479 assert(loadOp && "Expected transfer op vector produced by LoadOp");
480 return loadOp.getMemRef();
481 }
482
483 /// Retrieve the indices of the current LoadOp that loads from the buffer.
484 static void getBufferIndices(TransferWriteOp xferOp,
486 auto loadOp = xferOp.getVector().getDefiningOp<memref::LoadOp>();
487 auto prevIndices = memref::LoadOpAdaptor(loadOp).getIndices();
488 indices.append(prevIndices.begin(), prevIndices.end());
489 }
490
491 /// Rewrite the TransferWriteOp, assuming that there are no out-of-bounds
492 /// accesses on the to-be-unpacked dimension.
493 ///
494 /// 1. Load an (N-1)-d vector from the (already `vector.type_cast`ed) buffer,
495 /// using the loop iteration variable `iv`.
496 /// 2. Generate a new (N-1)-d TransferWriteOp, writing the loaded vector back
497 /// to memory.
498 ///
499 /// Note: For more details, see comments on Strategy<TransferReadOp>.
500 static TransferWriteOp rewriteOp(OpBuilder &b,
502 TransferWriteOp xferOp, Value buffer,
503 Value iv, ValueRange loopState) {
504 SmallVector<Value, 8> loadIndices;
505 getBufferIndices(xferOp, loadIndices);
506 loadIndices.push_back(iv);
507
508 SmallVector<Value, 8> xferIndices;
509 getXferIndices(b, xferOp, iv, xferIndices);
510
511 Location loc = xferOp.getLoc();
512 auto vec = memref::LoadOp::create(b, loc, buffer, loadIndices);
513 auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
514 auto source = loopState.empty() ? xferOp.getBase() : loopState[0];
515 Type type = isTensorOp(xferOp) ? xferOp.getShapedType() : Type();
516 auto newXferOp = vector::TransferWriteOp::create(
517 b, loc, type, vec, source, xferIndices,
518 AffineMapAttr::get(unpackedPermutationMap(b, xferOp)), Value(),
519 inBoundsAttr);
520
521 maybeApplyPassLabel(b, newXferOp, options.targetRank);
522
523 return newXferOp;
524 }
525
526 /// Handle out-of-bounds accesses on the to-be-unpacked dimension.
527 static Value handleOutOfBoundsDim(OpBuilder &b, TransferWriteOp xferOp,
528 Value buffer, Value iv,
529 ValueRange loopState) {
530 return isTensorOp(xferOp) ? loopState[0] : Value();
531 }
532
533 /// Cleanup after rewriting the op.
534 static void cleanup(PatternRewriter &rewriter, TransferWriteOp xferOp,
535 scf::ForOp forOp) {
536 if (isTensorOp(xferOp)) {
537 assert(forOp->getNumResults() == 1 && "Expected one for loop result");
538 rewriter.replaceOp(xferOp, forOp->getResult(0));
539 } else {
540 rewriter.eraseOp(xferOp);
541 }
542 }
543
544 /// Return the initial loop state for the generated scf.for loop.
545 static Value initialLoopState(TransferWriteOp xferOp) {
546 return isTensorOp(xferOp) ? xferOp.getBase() : Value();
547 }
548};
549
550template <typename OpTy>
551static LogicalResult checkPrepareXferOp(OpTy xferOp, PatternRewriter &rewriter,
553 if (xferOp->hasDiscardableAttr(kPassLabel))
554 return rewriter.notifyMatchFailure(
555 xferOp, "kPassLabel is present (vector-to-scf lowering in progress)");
556 if (xferOp.getVectorType().getRank() <= options.targetRank)
557 return rewriter.notifyMatchFailure(
558 xferOp, "xferOp vector rank <= transformation target rank");
559 if (xferOp.getVectorType().getScalableDims().front())
560 return rewriter.notifyMatchFailure(
561 xferOp, "Unpacking of the leading dimension into the memref is not yet "
562 "supported for scalable dims");
563 if (isTensorOp(xferOp) && !options.lowerTensors)
564 return rewriter.notifyMatchFailure(
565 xferOp, "Unpacking for tensors has been disabled.");
566 if (xferOp.getVectorType().getElementType() !=
567 xferOp.getShapedType().getElementType())
568 return rewriter.notifyMatchFailure(
569 xferOp, "Mismatching source and destination element types.");
570 Operation *op = xferOp.getOperation();
572 return rewriter.notifyMatchFailure(
573 xferOp, "xferOp is not inside an automatic allocation scope");
574
575 return success();
576}
577
578/// Prepare a TransferReadOp for progressive lowering.
579///
580/// 1. Allocate a temporary buffer.
581/// 2. Label the TransferReadOp, marking it eligible for progressive lowering.
582/// 3. Store the result of the TransferReadOp into the temporary buffer.
583/// 4. Load the result from the temporary buffer and replace all uses of the
584/// original TransferReadOp with this load.
585///
586/// E.g.:
587/// ```
588/// %vec = vector.transfer_read %A[%a, %b, %c], %cst
589/// : vector<5x4xf32>, memref<?x?x?xf32>
590/// ```
591/// is rewritten to:
592/// ```
593/// %0 = memref.alloca() : memref<vector<5x4xf32>>
594/// %1 = vector.transfer_read %A[%a, %b, %c], %cst
595/// { __vector_to_scf_lowering__ } : vector<5x4xf32>, memref<?x?x?xf32>
596/// memref.store %1, %0[] : memref<vector<5x4xf32>>
597/// %vec = memref.load %0[] : memref<vector<5x4xf32>>
598/// ```
599///
600/// Note: A second temporary buffer may be allocated for the `mask` operand.
601struct PrepareTransferReadConversion
602 : public VectorToSCFPattern<TransferReadOp> {
603 using VectorToSCFPattern<TransferReadOp>::VectorToSCFPattern;
604
605 LogicalResult matchAndRewrite(TransferReadOp xferOp,
606 PatternRewriter &rewriter) const override {
607 if (checkPrepareXferOp(xferOp, rewriter, options).failed())
608 return rewriter.notifyMatchFailure(
609 xferOp, "checkPrepareXferOp conditions not met!");
610
611 auto buffers = allocBuffers(rewriter, xferOp);
612 auto *newXfer = rewriter.clone(*xferOp.getOperation());
613 newXfer->setDiscardableAttr(kPassLabel, rewriter.getUnitAttr());
614 if (xferOp.getMask()) {
615 dyn_cast<TransferReadOp>(newXfer).getMaskMutable().assign(
616 buffers.maskBuffer);
617 }
618
619 Location loc = xferOp.getLoc();
620 memref::StoreOp::create(rewriter, loc, newXfer->getResult(0),
621 buffers.dataBuffer);
622 rewriter.replaceOpWithNewOp<memref::LoadOp>(xferOp, buffers.dataBuffer,
623 ValueRange{});
624
625 return success();
626 }
627};
628
629/// Prepare a TransferWriteOp for progressive lowering.
630///
631/// 1. Allocate a temporary buffer.
632/// 2. Store the vector into the buffer.
633/// 3. Load the vector from the buffer again.
634/// 4. Use the loaded vector as a TransferWriteOp operand and label the op,
635/// marking it eligible for progressive lowering via TransferOpConversion.
636///
637/// E.g.:
638/// ```
639/// vector.transfer_write %vec, %A[%a, %b, %c]
640/// : vector<5x4xf32>, memref<?x?x?xf32>
641/// ```
642/// is rewritten to:
643/// ```
644/// %0 = memref.alloca() : memref<vector<5x4xf32>>
645/// memref.store %vec, %0[] : memref<vector<5x4xf32>>
646/// %1 = memref.load %0[] : memref<vector<5x4xf32>>
647/// vector.transfer_write %1, %A[%a, %b, %c] { __vector_to_scf_lowering__ }
648/// : vector<5x4xf32>, memref<?x?x?xf32>
649/// ```
650///
651/// Note: A second temporary buffer may be allocated for the `mask` operand.
652struct PrepareTransferWriteConversion
653 : public VectorToSCFPattern<TransferWriteOp> {
654 using VectorToSCFPattern<TransferWriteOp>::VectorToSCFPattern;
655
656 LogicalResult matchAndRewrite(TransferWriteOp xferOp,
657 PatternRewriter &rewriter) const override {
658 if (checkPrepareXferOp(xferOp, rewriter, options).failed())
659 return rewriter.notifyMatchFailure(
660 xferOp, "checkPrepareXferOp conditions not met!");
661
662 Location loc = xferOp.getLoc();
663 auto buffers = allocBuffers(rewriter, xferOp);
664 memref::StoreOp::create(rewriter, loc, xferOp.getVector(),
665 buffers.dataBuffer);
666 auto loadedVec =
667 memref::LoadOp::create(rewriter, loc, buffers.dataBuffer, ValueRange{});
668 rewriter.modifyOpInPlace(xferOp, [&]() {
669 xferOp.getValueToStoreMutable().assign(loadedVec);
670 xferOp->setDiscardableAttr(kPassLabel, rewriter.getUnitAttr());
671 });
672
673 if (xferOp.getMask()) {
674 rewriter.modifyOpInPlace(xferOp, [&]() {
675 xferOp.getMaskMutable().assign(buffers.maskBuffer);
676 });
677 }
678
679 return success();
680 }
681};
682
683/// Decompose a n-D PrintOp into a loop of elementary/scalar prints. This allows
684/// printing both 1D scalable vectors and n-D fixed size vectors.
685///
686/// E.g.:
687/// ```
688/// vector.print %v : vector<[4]xi32>
689/// ```
690/// is rewritten to:
691/// ```
692/// %c0 = arith.constant 0 : index
693/// %c4 = arith.constant 4 : index
694/// %c1 = arith.constant 1 : index
695/// %vscale = vector.vscale
696/// %length = arith.muli %vscale, %c4 : index
697/// %lastIndex = arith.subi %length, %c1 : index
698/// vector.print punctuation <open>
699/// scf.for %i = %c0 to %length step %c1 {
700/// %el = vector.extract %v[%i] : i32 from vector<[4]xi32>
701/// vector.print %el : i32 punctuation <no_punctuation>
702/// %notLastIndex = arith.cmpi ult, %i, %lastIndex : index
703/// scf.if %notLastIndex {
704/// vector.print punctuation <comma>
705/// }
706/// }
707/// vector.print punctuation <close>
708/// vector.print
709/// ```
710struct DecomposePrintOpConversion : public VectorToSCFPattern<vector::PrintOp> {
711 using VectorToSCFPattern<vector::PrintOp>::VectorToSCFPattern;
712 LogicalResult matchAndRewrite(vector::PrintOp printOp,
713 PatternRewriter &rewriter) const override {
714 if (!printOp.getSource())
715 return failure();
716
717 VectorType vectorType = dyn_cast<VectorType>(printOp.getPrintType());
718 if (!vectorType)
719 return failure();
720
721 // Currently >= 2D scalable vectors are not supported.
722 // These can't be lowered to LLVM (as LLVM does not support scalable vectors
723 // of scalable vectors), and due to limitations of current ops can't be
724 // indexed with SSA values or flattened. This may change after
725 // https://reviews.llvm.org/D155034, though there still needs to be a path
726 // for lowering to LLVM.
727 if (vectorType.getRank() > 1 && vectorType.isScalable())
728 return failure();
729
730 auto loc = printOp.getLoc();
731 auto value = printOp.getSource();
732
733 if (auto intTy = dyn_cast<IntegerType>(vectorType.getElementType())) {
734 // Oddly sized integers are (somewhat) buggy on a lot of backends, so to
735 // avoid issues extend them to a more standard size.
736 // https://github.com/llvm/llvm-project/issues/30613
737 auto width = intTy.getWidth();
738 auto legalWidth = llvm::NextPowerOf2(std::max(8u, width) - 1);
739 auto legalIntTy = IntegerType::get(rewriter.getContext(), legalWidth,
740 intTy.getSignedness());
741 // arith can only take signless integers, so we must cast back and forth.
742 auto signlessSourceVectorType =
743 vectorType.cloneWith({}, getIntTypeWithSignlessSemantics(intTy));
744 auto signlessTargetVectorType =
745 vectorType.cloneWith({}, getIntTypeWithSignlessSemantics(legalIntTy));
746 auto targetVectorType = vectorType.cloneWith({}, legalIntTy);
747 value = vector::BitCastOp::create(rewriter, loc, signlessSourceVectorType,
748 value);
749 if (value.getType() != signlessTargetVectorType) {
750 if (width == 1 || intTy.isUnsigned())
751 value = arith::ExtUIOp::create(rewriter, loc,
752 signlessTargetVectorType, value);
753 else
754 value = arith::ExtSIOp::create(rewriter, loc,
755 signlessTargetVectorType, value);
756 }
757 value = vector::BitCastOp::create(rewriter, loc, targetVectorType, value);
758 vectorType = targetVectorType;
759 }
760
761 auto scalableDimensions = vectorType.getScalableDims();
762 auto shape = vectorType.getShape();
763 constexpr int64_t singletonShape[] = {1};
764 if (vectorType.getRank() == 0)
765 shape = singletonShape;
766
767 if (vectorType.getRank() != 1) {
768 // Flatten n-D vectors to 1D. This is done to allow indexing with a
769 // non-constant value.
770 int64_t flatLength = llvm::product_of(shape);
771 auto flatVectorType =
772 VectorType::get({flatLength}, vectorType.getElementType());
773 value = vector::ShapeCastOp::create(rewriter, loc, flatVectorType, value);
774 }
775
776 vector::PrintOp firstClose;
777 SmallVector<Value, 8> loopIndices;
778 for (unsigned d = 0; d < shape.size(); d++) {
779 // Setup loop bounds and step.
780 Value lowerBound = arith::ConstantIndexOp::create(rewriter, loc, 0);
781 Value upperBound =
782 arith::ConstantIndexOp::create(rewriter, loc, shape[d]);
783 Value step = arith::ConstantIndexOp::create(rewriter, loc, 1);
784 if (!scalableDimensions.empty() && scalableDimensions[d]) {
785 auto vscale = vector::VectorScaleOp::create(rewriter, loc,
786 rewriter.getIndexType());
787 upperBound = arith::MulIOp::create(rewriter, loc, upperBound, vscale);
788 }
789 auto lastIndex = arith::SubIOp::create(rewriter, loc, upperBound, step);
790
791 // Create a loop to print the elements surrounded by parentheses.
792 vector::PrintOp::create(rewriter, loc, vector::PrintPunctuation::Open);
793 auto loop =
794 scf::ForOp::create(rewriter, loc, lowerBound, upperBound, step);
795 auto printClose = vector::PrintOp::create(
796 rewriter, loc, vector::PrintPunctuation::Close);
797 if (!firstClose)
798 firstClose = printClose;
799
800 auto loopIdx = loop.getInductionVar();
801 loopIndices.push_back(loopIdx);
802
803 // Print a comma after all but the last element.
804 rewriter.setInsertionPointToStart(loop.getBody());
805 auto notLastIndex = arith::CmpIOp::create(
806 rewriter, loc, arith::CmpIPredicate::ult, loopIdx, lastIndex);
807 scf::IfOp::create(rewriter, loc, notLastIndex,
808 [&](OpBuilder &builder, Location loc) {
809 vector::PrintOp::create(
810 builder, loc, vector::PrintPunctuation::Comma);
811 scf::YieldOp::create(builder, loc);
812 });
813
814 rewriter.setInsertionPointToStart(loop.getBody());
815 }
816
817 // Compute the flattened index.
818 // Note: For the > rank 1 vectors this assumes non-scalable.
819 Value flatIndex;
820 auto currentStride = 1;
821 for (int d = shape.size() - 1; d >= 0; d--) {
822 auto stride =
823 arith::ConstantIndexOp::create(rewriter, loc, currentStride);
824 auto index = arith::MulIOp::create(rewriter, loc, stride, loopIndices[d]);
825 if (flatIndex)
826 flatIndex = arith::AddIOp::create(rewriter, loc, flatIndex, index);
827 else
828 flatIndex = index;
829 currentStride *= shape[d];
830 }
831
832 // Print the scalar elements in the inner most loop.
833 auto element = vector::ExtractOp::create(rewriter, loc, value, flatIndex);
834 vector::PrintOp::create(rewriter, loc, element,
835 vector::PrintPunctuation::NoPunctuation);
836
837 rewriter.setInsertionPointAfter(firstClose);
838 vector::PrintOp::create(rewriter, loc, printOp.getPunctuation());
839 rewriter.eraseOp(printOp);
840 return success();
841 }
842
843 static IntegerType getIntTypeWithSignlessSemantics(IntegerType intTy) {
844 return IntegerType::get(intTy.getContext(), intTy.getWidth(),
845 IntegerType::Signless);
846 };
847};
848
849/// Progressive lowering of vector transfer ops: Unpack one dimension.
850///
851/// 1. Unpack one dimension from the current buffer type and cast the buffer
852/// to that new type. E.g.:
853/// ```
854/// %vec = memref.load %0[%1] : memref<5xvector<4x3xf32>>
855/// vector.transfer_write %vec ...
856/// ```
857/// The following cast is generated:
858/// ```
859/// %casted = vector.type_cast %0
860/// : memref<5xvector<4x3xf32>> to memref<5x4xvector<3xf32>>
861/// ```
862/// 2. Generate a for loop and rewrite the transfer op according to the
863/// corresponding Strategy<OpTy>. If the to-be-unpacked dimension can be
864/// out-of-bounds, generate an if-check and handle both cases separately.
865/// 3. Clean up according to the corresponding Strategy<OpTy>.
866///
867/// Note: If the transfer op is a TransferWriteOp and operates on a tensor
868/// source (as opposed to a memref source), then each iteration of the generated
869/// scf.for loop yields the new tensor value. E.g.:
870/// ```
871/// %result = scf.for i = 0 to 5 {
872/// %0 = memref.load %buffer[i] : memref<5xvector<4x3xf32>>
873/// %1 = vector.transfer_write %0, %source[...]
874/// : vector<4x3xf32>, tensor<5x4x3xf32>
875/// scf.yield %1 : tensor<5x4x3xf32>
876/// }
877/// ```
878template <typename OpTy>
879struct TransferOpConversion : public VectorToSCFPattern<OpTy> {
880 using VectorToSCFPattern<OpTy>::VectorToSCFPattern;
881
882 void initialize() {
883 // This pattern recursively unpacks one dimension at a time. The recursion
884 // bounded as the rank is strictly decreasing.
885 this->setHasBoundedRewriteRecursion();
886 }
887
888 static void getMaskBufferLoadIndices(OpTy xferOp, Value castedMaskBuffer,
889 SmallVectorImpl<Value> &loadIndices,
890 Value iv) {
891 assert(xferOp.getMask() && "Expected transfer op to have mask");
892
893 // Add load indices from the previous iteration.
894 // The mask buffer depends on the permutation map, which makes determining
895 // the indices quite complex, so this is why we need to "look back" to the
896 // previous iteration to find the right indices.
897 Value maskBuffer = getMaskBuffer(xferOp);
898 for (Operation *user : maskBuffer.getUsers()) {
899 // If there is no previous load op, then the indices are empty.
900 if (auto loadOp = dyn_cast<memref::LoadOp>(user)) {
901 Operation::operand_range prevIndices = loadOp.getIndices();
902 loadIndices.append(prevIndices.begin(), prevIndices.end());
903 break;
904 }
905 }
906
907 // In case of broadcast: Use same indices to load from memref
908 // as before.
909 if (!xferOp.isBroadcastDim(0))
910 loadIndices.push_back(iv);
911 }
912
913 LogicalResult matchAndRewrite(OpTy xferOp,
914 PatternRewriter &rewriter) const override {
915 if (!xferOp->hasDiscardableAttr(kPassLabel))
916 return rewriter.notifyMatchFailure(
917 xferOp, "kPassLabel is present (progressing lowering in progress)");
918
919 // Find and cast data buffer. How the buffer can be found depends on OpTy.
920 ImplicitLocOpBuilder locB(xferOp.getLoc(), rewriter);
921 Value dataBuffer = Strategy<OpTy>::getBuffer(xferOp);
922 auto dataBufferType = dyn_cast<MemRefType>(dataBuffer.getType());
923 FailureOr<MemRefType> castedDataType = unpackOneDim(dataBufferType);
924 if (failed(castedDataType))
925 return rewriter.notifyMatchFailure(xferOp,
926 "Failed to unpack one vector dim.");
927
928 auto castedDataBuffer =
929 vector::TypeCastOp::create(locB, *castedDataType, dataBuffer);
930
931 // If the xferOp has a mask: Find and cast mask buffer.
932 Value castedMaskBuffer;
933 if (xferOp.getMask()) {
934 Value maskBuffer = getMaskBuffer(xferOp);
935 if (xferOp.isBroadcastDim(0) || xferOp.getMaskType().getRank() == 1) {
936 // Do not unpack a dimension of the mask, if:
937 // * To-be-unpacked transfer op dimension is a broadcast.
938 // * Mask is 1D, i.e., the mask cannot be further unpacked.
939 // (That means that all remaining dimensions of the transfer op must
940 // be broadcasted.)
941 castedMaskBuffer = maskBuffer;
942 } else {
943 // It's safe to assume the mask buffer can be unpacked if the data
944 // buffer was unpacked.
945 auto maskBufferType = cast<MemRefType>(maskBuffer.getType());
946 MemRefType castedMaskType = *unpackOneDim(maskBufferType);
947 castedMaskBuffer =
948 vector::TypeCastOp::create(locB, castedMaskType, maskBuffer);
949 }
950 }
951
952 // Loop bounds and step.
953 auto lb = arith::ConstantIndexOp::create(locB, 0);
955 locB, castedDataType->getDimSize(castedDataType->getRank() - 1));
956 auto step = arith::ConstantIndexOp::create(locB, 1);
957 // TransferWriteOps that operate on tensors return the modified tensor and
958 // require a loop state.
959 auto loopState = Strategy<OpTy>::initialLoopState(xferOp);
960
961 // Generate for loop.
962 auto result = scf::ForOp::create(
963 locB, lb, ub, step, loopState ? ValueRange(loopState) : ValueRange(),
964 [&](OpBuilder &b, Location loc, Value iv, ValueRange loopState) {
965 Type stateType = loopState.empty() ? Type() : loopState[0].getType();
966
967 auto result = generateInBoundsCheck(
968 b, xferOp, iv, unpackedDim(xferOp),
969 stateType ? TypeRange(stateType) : TypeRange(),
970 /*inBoundsCase=*/
971 [&](OpBuilder &b, Location loc) {
972 // Create new transfer op.
973 OpTy newXfer = Strategy<OpTy>::rewriteOp(
974 b, this->options, xferOp, castedDataBuffer, iv, loopState);
975
976 // If old transfer op has a mask: Set mask on new transfer op.
977 // Special case: If the mask of the old transfer op is 1D and
978 // the unpacked dim is not a broadcast, no mask is needed on
979 // the new transfer op.
980 if (xferOp.getMask() && (xferOp.isBroadcastDim(0) ||
981 xferOp.getMaskType().getRank() > 1)) {
983 b.setInsertionPoint(newXfer); // Insert load before newXfer.
984
985 SmallVector<Value, 8> loadIndices;
986 getMaskBufferLoadIndices(xferOp, castedMaskBuffer,
987 loadIndices, iv);
988 auto mask = memref::LoadOp::create(b, loc, castedMaskBuffer,
989 loadIndices);
990 rewriter.modifyOpInPlace(newXfer, [&]() {
991 newXfer.getMaskMutable().assign(mask);
992 });
993 }
994
995 return loopState.empty() ? Value() : newXfer->getResult(0);
996 },
997 /*outOfBoundsCase=*/
998 [&](OpBuilder &b, Location /*loc*/) {
999 return Strategy<OpTy>::handleOutOfBoundsDim(
1000 b, xferOp, castedDataBuffer, iv, loopState);
1001 });
1002
1003 maybeYieldValue(b, loc, !loopState.empty(), result);
1004 });
1005
1006 Strategy<OpTy>::cleanup(rewriter, xferOp, result);
1007 return success();
1008 }
1009};
1010
1011/// Retrieves the dimensions sizes of a mask. Currently supports CreateMaskOp
1012/// and ConstantMaskOp.
1013template <typename VscaleConstantBuilder>
1014static FailureOr<SmallVector<OpFoldResult>>
1015getMaskDimSizes(Value mask, VscaleConstantBuilder &createVscaleMultiple) {
1016 if (!mask)
1018 if (auto createMaskOp = mask.getDefiningOp<vector::CreateMaskOp>()) {
1019 return llvm::map_to_vector(createMaskOp.getOperands(), [](Value dimSize) {
1020 return OpFoldResult(dimSize);
1021 });
1022 }
1023 if (auto constantMask = mask.getDefiningOp<vector::ConstantMaskOp>()) {
1024 int dimIdx = 0;
1025 VectorType maskType = constantMask.getVectorType();
1026 auto indexType = IndexType::get(mask.getContext());
1027 return llvm::map_to_vector(
1028 constantMask.getMaskDimSizes(), [&](int64_t dimSize) {
1029 // A scalable dim in a constant_mask means vscale x dimSize.
1030 if (maskType.getScalableDims()[dimIdx++])
1031 return OpFoldResult(createVscaleMultiple(dimSize));
1032 return OpFoldResult(IntegerAttr::get(indexType, dimSize));
1033 });
1034 }
1035 return failure();
1036}
1037
1038/// Scalable vector lowering of transfer_write(transpose). This lowering only
1039/// supports rank 2 (scalable) vectors, but can be used in conjunction with
1040/// `UnrollTransferWriteConversion` to support n-D cases. The unroll conversion
1041/// unrolls until the first scalable dimension.
1042///
1043/// Example:
1044///
1045/// BEFORE:
1046/// ```mlir
1047/// %transpose = vector.transpose %vec, [1, 0]
1048/// : vector<4x[4]xf32> to vector<[4]x4xf32>
1049/// vector.transfer_write %transpose, %dest[%i, %j] {in_bounds = [true, true]}
1050/// : vector<[4]x4xf32>, memref<?x?xf32>
1051/// ```
1052///
1053/// AFTER:
1054/// ```mlir
1055/// %c1 = arith.constant 1 : index
1056/// %c4 = arith.constant 4 : index
1057/// %c0 = arith.constant 0 : index
1058/// %0 = vector.extract %arg0[0] : vector<[4]xf32> from vector<4x[4]xf32>
1059/// %1 = vector.extract %arg0[1] : vector<[4]xf32> from vector<4x[4]xf32>
1060/// %2 = vector.extract %arg0[2] : vector<[4]xf32> from vector<4x[4]xf32>
1061/// %3 = vector.extract %arg0[3] : vector<[4]xf32> from vector<4x[4]xf32>
1062/// %vscale = vector.vscale
1063/// %c4_vscale = arith.muli %vscale, %c4 : index
1064/// scf.for %idx = %c0 to %c4_vscale step %c1 {
1065/// %4 = vector.extract %0[%idx] : f32 from vector<[4]xf32>
1066/// %5 = vector.extract %1[%idx] : f32 from vector<[4]xf32>
1067/// %6 = vector.extract %2[%idx] : f32 from vector<[4]xf32>
1068/// %7 = vector.extract %3[%idx] : f32 from vector<[4]xf32>
1069/// %slice_i = affine.apply #map(%idx)[%i]
1070/// %slice = vector.from_elements %4, %5, %6, %7 : vector<4xf32>
1071/// vector.transfer_write %slice, %arg1[%slice_i, %j] {in_bounds = [true]}
1072/// : vector<4xf32>, memref<?x?xf32>
1073/// }
1074/// ```
1075struct ScalableTransposeTransferWriteConversion
1076 : VectorToSCFPattern<vector::TransferWriteOp> {
1077 using VectorToSCFPattern::VectorToSCFPattern;
1078
1079 LogicalResult matchAndRewrite(TransferWriteOp writeOp,
1080 PatternRewriter &rewriter) const override {
1081 if (failed(checkLowerTensors(writeOp, rewriter)))
1082 return failure();
1083
1084 VectorType vectorType = writeOp.getVectorType();
1085
1086 // Note: By comparing the scalable dims to an ArrayRef of length two this
1087 // implicitly checks the rank (is also two).
1088 ArrayRef<bool> scalableFlags = vectorType.getScalableDims();
1089 if (scalableFlags != ArrayRef<bool>{true, false}) {
1090 return rewriter.notifyMatchFailure(
1091 writeOp, "expected vector of the form vector<[N]xMxty>");
1092 }
1093
1094 auto permutationMap = writeOp.getPermutationMap();
1095 if (!permutationMap.isIdentity()) {
1096 return rewriter.notifyMatchFailure(
1097 writeOp, "non-identity permutations are unsupported (lower first)");
1098 }
1099
1100 // Note: This pattern is only lowering the leading dimension (to a loop),
1101 // so we only check if the leading dimension is in bounds. The in-bounds
1102 // attribute for the trailing dimension will be propagated.
1103 if (!writeOp.isDimInBounds(0)) {
1104 return rewriter.notifyMatchFailure(
1105 writeOp, "out-of-bounds dims are unsupported (use masking)");
1106 }
1107
1108 Value vector = writeOp.getVector();
1109 auto transposeOp = vector.getDefiningOp<vector::TransposeOp>();
1110 if (!transposeOp ||
1111 transposeOp.getPermutation() != ArrayRef<int64_t>{1, 0}) {
1112 return rewriter.notifyMatchFailure(writeOp, "source not transpose");
1113 }
1114
1115 auto loc = writeOp.getLoc();
1116 auto createVscaleMultiple =
1117 vector::makeVscaleConstantBuilder(rewriter, loc);
1118
1119 auto maskDims = getMaskDimSizes(writeOp.getMask(), createVscaleMultiple);
1120 if (failed(maskDims)) {
1121 return rewriter.notifyMatchFailure(writeOp,
1122 "failed to resolve mask dims");
1123 }
1124
1125 int64_t fixedDimSize = vectorType.getDimSize(1);
1126 auto fixedDimOffsets = llvm::seq(fixedDimSize);
1127
1128 // Extract all slices from the source of the transpose.
1129 auto transposeSource = transposeOp.getVector();
1130 SmallVector<Value> transposeSourceSlices =
1131 llvm::map_to_vector(fixedDimOffsets, [&](int64_t idx) -> Value {
1132 return vector::ExtractOp::create(rewriter, loc, transposeSource, idx);
1133 });
1134
1135 // Loop bounds and step.
1136 auto lb = arith::ConstantIndexOp::create(rewriter, loc, 0);
1137 auto ub =
1138 maskDims->empty()
1139 ? Value(createVscaleMultiple(vectorType.getDimSize(0)))
1140 : vector::getAsValues(rewriter, loc, maskDims->front()).front();
1141 auto step = arith::ConstantIndexOp::create(rewriter, loc, 1);
1142
1143 // Generate a new mask for the slice.
1144 VectorType sliceType = VectorType::Builder(vectorType).dropDim(0);
1145 Value sliceMask = nullptr;
1146 if (!maskDims->empty()) {
1147 sliceMask = vector::CreateMaskOp::create(
1148 rewriter, loc, sliceType.clone(rewriter.getI1Type()),
1149 ArrayRef<OpFoldResult>(*maskDims).drop_front());
1150 }
1151
1152 Value initDest = isTensorOp(writeOp) ? writeOp.getBase() : Value{};
1153 ValueRange initLoopArgs = initDest ? initDest : ValueRange{};
1154 auto result = scf::ForOp::create(
1155 rewriter, loc, lb, ub, step, initLoopArgs,
1156 [&](OpBuilder &b, Location loc, Value iv, ValueRange loopIterArgs) {
1157 // Indices for the new transfer op.
1158 SmallVector<Value, 8> xferIndices;
1159 getXferIndices(b, writeOp, iv, xferIndices);
1160
1161 // Extract a transposed slice from the source vector.
1162 SmallVector<Value> transposeElements =
1163 llvm::map_to_vector(fixedDimOffsets, [&](int64_t idx) -> Value {
1164 return vector::ExtractOp::create(
1165 b, loc, transposeSourceSlices[idx], iv);
1166 });
1167 auto sliceVec = vector::FromElementsOp::create(b, loc, sliceType,
1168 transposeElements);
1169
1170 // Create the transfer_write for the slice.
1171 Value dest =
1172 loopIterArgs.empty() ? writeOp.getBase() : loopIterArgs.front();
1173 auto newWriteOp = vector::TransferWriteOp::create(
1174 b, loc, sliceVec, dest, xferIndices,
1175 ArrayRef<bool>(writeOp.getInBoundsValues()).drop_front());
1176 if (sliceMask)
1177 newWriteOp.getMaskMutable().assign(sliceMask);
1178
1179 // Yield from the loop.
1180 scf::YieldOp::create(b, loc,
1181 loopIterArgs.empty() ? ValueRange{}
1182 : newWriteOp.getResult());
1183 });
1184
1185 if (isTensorOp(writeOp))
1186 rewriter.replaceOp(writeOp, result);
1187 else
1188 rewriter.eraseOp(writeOp);
1189
1190 return success();
1191 }
1192};
1193
1194} // namespace lowering_n_d
1195
1197
1198/// If the original transfer op has a mask, compute the mask of the new transfer
1199/// op (for the current iteration `i`) and assign it.
1200template <typename OpTy>
1201static void maybeAssignMask(OpBuilder &b, OpTy xferOp, OpTy newXferOp,
1202 int64_t i) {
1203 if (!xferOp.getMask())
1204 return;
1205
1206 if (xferOp.isBroadcastDim(0)) {
1207 // To-be-unpacked dimension is a broadcast, which does not have a
1208 // corresponding mask dimension. Mask attribute remains unchanged.
1209 newXferOp.getMaskMutable().assign(xferOp.getMask());
1210 return;
1211 }
1212
1213 if (xferOp.getMaskType().getRank() > 1) {
1214 // Unpack one dimension of the mask.
1216 b.setInsertionPoint(newXferOp); // Insert load before newXfer.
1217
1219 Location loc = xferOp.getLoc();
1220 auto newMask = vector::ExtractOp::create(b, loc, xferOp.getMask(), indices);
1221 newXferOp.getMaskMutable().assign(newMask);
1222 }
1223
1224 // If we end up here: The mask of the old transfer op is 1D and the unpacked
1225 // dim is not a broadcast, so no mask is needed on the new transfer op.
1226 // `generateInBoundsCheck` will have evaluated the mask already.
1227}
1228
1229/// Progressive lowering of vector TransferReadOp with unrolling: Unpack one
1230/// dimension. This is similar to TransferOpConversion<TransferReadOp>, but no
1231/// memref buffer is allocated and the SCF loop is fully unrolled.
1232///
1233/// ```
1234/// E.g.:
1235/// ```
1236/// %vec = vector.transfer_read %A[%a, %b, %c], %padding
1237/// : memref<?x?x?xf32>, vector<5x4xf32>
1238/// ```
1239/// is rewritten to IR such as (simplified):
1240/// ```
1241/// %v_init = splat %padding : vector<5x4xf32>
1242/// %tmp0 = vector.transfer_read %A[%a, %b, %c], %padding
1243/// : memref<?x?x?xf32>, vector<4xf32>
1244/// %v0 = vector.insert %tmp0, %v_init[0] : vector<4xf32> into vector<5x4xf32>
1245/// %tmp1 = vector.transfer_read %A[%a, %b + 1, %c], %padding
1246/// : memref<?x?x?xf32>, vector<4xf32>
1247/// %v1 = vector.insert %tmp1, %v0[1] : vector<4xf32> into vector<5x4xf32>
1248/// ...
1249/// %tmp4 = vector.transfer_read %A[%a, %b + 4, %c], %padding
1250/// : memref<?x?x?xf32>, vector<4xf32>
1251/// %vec = vector.insert %tmp1, %v3[4] : vector<4xf32> into vector<5x4xf32>
1252/// ```
1253///
1254/// Note: As an optimization, if the result of the original TransferReadOp
1255/// was directly inserted into another vector, no new %v_init vector is created.
1256/// Instead, the new TransferReadOp results are inserted into that vector.
1257struct UnrollTransferReadConversion
1258 : public VectorToSCFPattern<TransferReadOp> {
1259 using VectorToSCFPattern<TransferReadOp>::VectorToSCFPattern;
1260
1261 void initialize() {
1262 // This pattern recursively unpacks one dimension at a time. The recursion
1263 // bounded as the rank is strictly decreasing.
1264 setHasBoundedRewriteRecursion();
1265 }
1266
1267 /// Get or build the vector into which the newly created TransferReadOp
1268 /// results are inserted.
1269 Value buildResultVector(PatternRewriter &rewriter,
1270 TransferReadOp xferOp) const {
1271 if (auto insertOp = getInsertOp(xferOp))
1272 return insertOp.getDest();
1273 Location loc = xferOp.getLoc();
1274 return vector::BroadcastOp::create(rewriter, loc, xferOp.getVectorType(),
1275 xferOp.getPadding());
1276 }
1277
1278 /// If the result of the TransferReadOp has exactly one user, which is a
1279 /// vector::InsertOp, return that operation.
1280 vector::InsertOp getInsertOp(TransferReadOp xferOp) const {
1281 if (xferOp->hasOneUse()) {
1282 Operation *xferOpUser = *xferOp->getUsers().begin();
1283 if (auto insertOp = dyn_cast<vector::InsertOp>(xferOpUser))
1284 return insertOp;
1285 }
1286
1287 return vector::InsertOp();
1288 }
1289
1290 /// If the result of the TransferReadOp has exactly one user, which is a
1291 /// vector::InsertOp, return that operation's indices.
1292 void getInsertionIndices(TransferReadOp xferOp,
1294 if (auto insertOp = getInsertOp(xferOp)) {
1295 auto pos = insertOp.getMixedPosition();
1296 indices.append(pos.begin(), pos.end());
1297 }
1298 }
1299
1300 /// Rewrite the op: Unpack one dimension. Can handle masks, out-of-bounds
1301 /// accesses, and broadcasts and transposes in permutation maps.
1302 LogicalResult matchAndRewrite(TransferReadOp xferOp,
1303 PatternRewriter &rewriter) const override {
1304 if (xferOp.getVectorType().getRank() <= options.targetRank)
1305 return rewriter.notifyMatchFailure(
1306 xferOp, "vector rank is less or equal to target rank");
1307 if (failed(checkLowerTensors(xferOp, rewriter)))
1308 return failure();
1309 if (xferOp.getVectorType().getElementType() !=
1310 xferOp.getShapedType().getElementType())
1311 return rewriter.notifyMatchFailure(
1312 xferOp, "not yet supported: element type mismatch");
1313 auto xferVecType = xferOp.getVectorType();
1314 if (xferVecType.getScalableDims()[0]) {
1315 return rewriter.notifyMatchFailure(
1316 xferOp, "scalable dimensions cannot be unrolled at compile time");
1317 }
1318
1319 auto insertOp = getInsertOp(xferOp);
1320 auto vec = buildResultVector(rewriter, xferOp);
1321 auto vecType = dyn_cast<VectorType>(vec.getType());
1322
1323 VectorType newXferVecType = VectorType::Builder(xferVecType).dropDim(0);
1324
1325 int64_t dimSize = xferVecType.getShape()[0];
1326
1327 // Generate fully unrolled loop of transfer ops.
1328 Location loc = xferOp.getLoc();
1329 for (int64_t i = 0; i < dimSize; ++i) {
1330 Value iv = arith::ConstantIndexOp::create(rewriter, loc, i);
1331
1332 // FIXME: Rename this lambda - it does much more than just
1333 // in-bounds-check generation.
1334 vec = generateInBoundsCheck(
1335 rewriter, xferOp, iv, unpackedDim(xferOp), TypeRange(vecType),
1336 /*inBoundsCase=*/
1337 [&](OpBuilder &b, Location loc) {
1338 // Indices for the new transfer op.
1339 SmallVector<Value, 8> xferIndices;
1340 getXferIndices(b, xferOp, iv, xferIndices);
1341
1342 // Indices for the new vector.insert op.
1343 SmallVector<OpFoldResult, 8> insertionIndices;
1344 getInsertionIndices(xferOp, insertionIndices);
1345 insertionIndices.push_back(rewriter.getIndexAttr(i));
1346
1347 auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
1348
1349 auto newXferOp = vector::TransferReadOp::create(
1350 b, loc, newXferVecType, xferOp.getBase(), xferIndices,
1351 AffineMapAttr::get(unpackedPermutationMap(b, xferOp)),
1352 xferOp.getPadding(), Value(), inBoundsAttr);
1353 maybeAssignMask(b, xferOp, newXferOp, i);
1354
1355 Value valToInser = newXferOp.getResult();
1356 if (newXferVecType.getRank() == 0) {
1357 // vector.insert does not accept rank-0 as the non-indexed
1358 // argument. Extract the scalar before inserting.
1359 valToInser = vector::ExtractOp::create(b, loc, valToInser,
1361 }
1362 return vector::InsertOp::create(b, loc, valToInser, vec,
1363 insertionIndices);
1364 },
1365 /*outOfBoundsCase=*/
1366 [&](OpBuilder &b, Location loc) {
1367 // Loop through original (unmodified) vector.
1368 return vec;
1369 });
1370 }
1371
1372 if (insertOp) {
1373 // Rewrite single user of the old TransferReadOp, which was an InsertOp.
1374 rewriter.replaceOp(insertOp, vec);
1375 rewriter.eraseOp(xferOp);
1376 } else {
1377 rewriter.replaceOp(xferOp, vec);
1378 }
1379
1380 return success();
1381 }
1382};
1383
1384/// Progressive lowering of vector TransferWriteOp with unrolling: Unpack one
1385/// dimension. This is similar to TransferOpConversion<TransferWriteOp>, but no
1386/// memref buffer is allocated and the SCF loop is fully unrolled.
1387///
1388/// ```
1389/// E.g.:
1390/// ```
1391/// vector.transfer_write %vec, %A[%a, %b, %c]
1392/// : vector<5x4xf32>, memref<?x?x?xf32>
1393/// ```
1394/// is rewritten to IR such as (simplified):
1395/// ```
1396/// %v0 = vector.extract %vec[0] : vector<4xf32> from vector<5x4xf32>
1397/// vector.transfer_write %v0, %A[%a, %b, %c] : vector<4xf32>, memref<...>
1398/// %v1 = vector.extract %vec[1] : vector<4xf32> from vector<5x4xf32>
1399/// vector.transfer_write %v1, %A[%a, %b + 1, %c] : vector<4xf32>, memref<...>
1400/// ...
1401/// %v4 = vector.extract %vec[4] : vector<4xf32> from vector<5x4xf32>
1402/// vector.transfer_write %v4, %A[%a, %b + 4, %c] : vector<4xf32>, memref<...>
1403/// ```
1404///
1405/// Note: As an optimization, if the vector of the original TransferWriteOp
1406/// was directly extracted from another vector via an ExtractOp `a`, extract
1407/// the vectors for the newly generated TransferWriteOps from `a`'s input. By
1408/// doing so, `a` may become dead, and the number of ExtractOps generated during
1409/// recursive application of this pattern will be minimal.
1410struct UnrollTransferWriteConversion
1411 : public VectorToSCFPattern<TransferWriteOp> {
1412 using VectorToSCFPattern<TransferWriteOp>::VectorToSCFPattern;
1413
1414 void initialize() {
1415 // This pattern recursively unpacks one dimension at a time. The recursion
1416 // bounded as the rank is strictly decreasing.
1417 setHasBoundedRewriteRecursion();
1418 }
1419
1420 /// Return the vector from which newly generated ExtracOps will extract.
1421 Value getDataVector(TransferWriteOp xferOp) const {
1422 if (auto extractOp = getExtractOp(xferOp))
1423 return extractOp.getSource();
1424 return xferOp.getVector();
1425 }
1426
1427 /// If the input of the given TransferWriteOp is an ExtractOp, return it.
1428 vector::ExtractOp getExtractOp(TransferWriteOp xferOp) const {
1429 if (auto *op = xferOp.getVector().getDefiningOp())
1430 return dyn_cast<vector::ExtractOp>(op);
1431 return vector::ExtractOp();
1432 }
1433
1434 /// If the input of the given TransferWriteOp is an ExtractOp, return its
1435 /// indices.
1436 void getExtractionIndices(TransferWriteOp xferOp,
1438 if (auto extractOp = getExtractOp(xferOp)) {
1439 auto pos = extractOp.getMixedPosition();
1440 indices.append(pos.begin(), pos.end());
1441 }
1442 }
1443
1444 /// Rewrite the op: Unpack one dimension. Can handle masks, out-of-bounds
1445 /// accesses, and broadcasts and transposes in permutation maps.
1446 LogicalResult matchAndRewrite(TransferWriteOp xferOp,
1447 PatternRewriter &rewriter) const override {
1448 VectorType inputVectorTy = xferOp.getVectorType();
1449
1450 if (inputVectorTy.getRank() <= options.targetRank)
1451 return failure();
1452
1453 if (failed(checkLowerTensors(xferOp, rewriter)))
1454 return failure();
1455 // Transfer ops that modify the element type are not supported atm.
1456 if (inputVectorTy.getElementType() !=
1457 xferOp.getShapedType().getElementType())
1458 return failure();
1459
1460 auto vec = getDataVector(xferOp);
1461 if (inputVectorTy.getScalableDims()[0]) {
1462 // Cannot unroll a scalable dimension at compile time.
1463 return failure();
1464 }
1465
1466 int64_t dimSize = inputVectorTy.getShape()[0];
1467 Value source = xferOp.getBase(); // memref or tensor to be written to.
1468 auto sourceType = isTensorOp(xferOp) ? xferOp.getShapedType() : Type();
1469
1470 // Generate fully unrolled loop of transfer ops.
1471 Location loc = xferOp.getLoc();
1472 for (int64_t i = 0; i < dimSize; ++i) {
1473 Value iv = arith::ConstantIndexOp::create(rewriter, loc, i);
1474
1475 auto updatedSource = generateInBoundsCheck(
1476 rewriter, xferOp, iv, unpackedDim(xferOp),
1477 isTensorOp(xferOp) ? TypeRange(sourceType) : TypeRange(),
1478 /*inBoundsCase=*/
1479 [&](OpBuilder &b, Location loc) {
1480 // Indices for the new transfer op.
1481 SmallVector<Value, 8> xferIndices;
1482 getXferIndices(b, xferOp, iv, xferIndices);
1483
1484 // Indices for the new vector.extract op.
1485 SmallVector<OpFoldResult, 8> extractionIndices;
1486 getExtractionIndices(xferOp, extractionIndices);
1487 extractionIndices.push_back(b.getI64IntegerAttr(i));
1488
1489 auto extracted =
1490 vector::ExtractOp::create(b, loc, vec, extractionIndices);
1491 auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
1492 Value xferVec;
1493 if (inputVectorTy.getRank() == 1) {
1494 // When target-rank=0, unrolling would causes the vector input
1495 // argument into `transfer_write` to become a scalar. We solve
1496 // this by broadcasting the scalar to a 0D vector.
1497 xferVec = vector::BroadcastOp::create(
1498 b, loc, VectorType::get({}, extracted.getType()), extracted);
1499 } else {
1500 xferVec = extracted;
1501 }
1502 auto newXferOp = vector::TransferWriteOp::create(
1503 b, loc, sourceType, xferVec, source, xferIndices,
1504 AffineMapAttr::get(unpackedPermutationMap(b, xferOp)), Value(),
1505 inBoundsAttr);
1506
1507 maybeAssignMask(b, xferOp, newXferOp, i);
1508
1509 return isTensorOp(xferOp) ? newXferOp->getResult(0) : Value();
1510 },
1511 /*outOfBoundsCase=*/
1512 [&](OpBuilder &b, Location loc) {
1513 return isTensorOp(xferOp) ? source : Value();
1514 });
1515
1516 if (isTensorOp(xferOp))
1517 source = updatedSource;
1518 }
1519
1520 if (isTensorOp(xferOp))
1521 rewriter.replaceOp(xferOp, source);
1522 else
1523 rewriter.eraseOp(xferOp);
1524
1525 return success();
1526 }
1527};
1528
1529} // namespace lowering_n_d_unrolled
1530
1531namespace lowering_1_d {
1532
1533/// Compute the indices into the memref for the LoadOp/StoreOp generated as
1534/// part of TransferOp1dConversion. Return the memref dimension on which
1535/// the transfer is operating. A return value of std::nullopt indicates a
1536/// broadcast.
1537template <typename OpTy>
1538static std::optional<int64_t>
1539get1dMemrefIndices(OpBuilder &b, OpTy xferOp, Value iv,
1540 SmallVector<Value, 8> &memrefIndices) {
1541 auto indices = xferOp.getIndices();
1542 auto map = xferOp.getPermutationMap();
1543 assert(xferOp.getTransferRank() > 0 && "unexpected 0-d transfer");
1544
1545 memrefIndices.append(indices.begin(), indices.end());
1546 assert(map.getNumResults() == 1 &&
1547 "Expected 1 permutation map result for 1D transfer");
1548 if (auto expr = dyn_cast<AffineDimExpr>(map.getResult(0))) {
1549 Location loc = xferOp.getLoc();
1550 auto dim = expr.getPosition();
1551 AffineExpr d0, d1;
1552 bindDims(xferOp.getContext(), d0, d1);
1553 Value offset = memrefIndices[dim];
1554 memrefIndices[dim] =
1555 affine::makeComposedAffineApply(b, loc, d0 + d1, {offset, iv});
1556 return dim;
1557 }
1558
1559 assert(xferOp.isBroadcastDim(0) &&
1560 "Expected AffineDimExpr or AffineConstantExpr");
1561 return std::nullopt;
1562}
1563
1564/// Codegen strategy for TransferOp1dConversion, depending on the
1565/// operation.
1566template <typename OpTy>
1567struct Strategy1d;
1568
1569/// Codegen strategy for TransferReadOp.
1570template <>
1571struct Strategy1d<TransferReadOp> {
1572 static void generateForLoopBody(OpBuilder &b, Location loc,
1573 TransferReadOp xferOp, Value iv,
1574 ValueRange loopState) {
1576 auto dim = get1dMemrefIndices(b, xferOp, iv, indices);
1577 auto vec = loopState[0];
1578
1579 // In case of out-of-bounds access, leave `vec` as is (was initialized with
1580 // padding value).
1581 auto nextVec = generateInBoundsCheck(
1582 b, xferOp, iv, dim, TypeRange(xferOp.getVectorType()),
1583 /*inBoundsCase=*/
1584 [&](OpBuilder &b, Location loc) {
1585 Value val = memref::LoadOp::create(b, loc, xferOp.getBase(), indices);
1586 return vector::InsertOp::create(b, loc, val, vec, iv);
1587 },
1588 /*outOfBoundsCase=*/
1589 [&](OpBuilder & /*b*/, Location loc) { return vec; });
1590 scf::YieldOp::create(b, loc, nextVec);
1591 }
1592
1593 static Value initialLoopState(OpBuilder &b, TransferReadOp xferOp) {
1594 // Inititalize vector with padding value.
1595 Location loc = xferOp.getLoc();
1596 return vector::BroadcastOp::create(b, loc, xferOp.getVectorType(),
1597 xferOp.getPadding());
1598 }
1599};
1600
1601/// Codegen strategy for TransferWriteOp.
1602template <>
1603struct Strategy1d<TransferWriteOp> {
1604 static void generateForLoopBody(OpBuilder &b, Location loc,
1605 TransferWriteOp xferOp, Value iv,
1606 ValueRange /*loopState*/) {
1608 auto dim = get1dMemrefIndices(b, xferOp, iv, indices);
1609
1610 // Nothing to do in case of out-of-bounds access.
1611 generateInBoundsCheck(
1612 b, xferOp, iv, dim,
1613 /*inBoundsCase=*/[&](OpBuilder &b, Location loc) {
1614 auto val = vector::ExtractOp::create(b, loc, xferOp.getVector(), iv);
1615 memref::StoreOp::create(b, loc, val, xferOp.getBase(), indices);
1616 });
1617 scf::YieldOp::create(b, loc);
1618 }
1619
1620 static Value initialLoopState(OpBuilder &b, TransferWriteOp xferOp) {
1621 return Value();
1622 }
1623};
1624
1625/// Lower a 1D vector transfer op to SCF using scalar loads/stores. This is
1626/// necessary in cases where a 1D vector transfer op cannot be lowered into
1627/// vector load/stores due to non-unit strides or broadcasts:
1628///
1629/// * Transfer dimension is not the last memref dimension
1630/// * Transfer dimension is a broadcast (i.e., scalar load + broadcast)
1631/// * Memref has a layout map with non-unit stride on the last dimension
1632///
1633/// This pattern generates IR as follows:
1634///
1635/// 1. Generate a for loop iterating over each vector element.
1636/// 2. Inside the loop, generate a InsertElementOp or ExtractElementOp,
1637/// depending on OpTy.
1638///
1639/// TODO: In some cases (no masking, etc.), LLVM::MatrixColumnMajorLoadOp
1640/// can be generated instead of TransferOp1dConversion. Add such a pattern
1641/// to ConvertVectorToLLVM.
1642///
1643/// E.g.:
1644/// ```
1645/// vector.transfer_write %vec, %A[%a, %b]
1646/// {permutation_map = affine_map<(d0, d1) -> (d0)>, in_bounds = [true]}
1647/// : vector<9xf32>, memref<?x?xf32>
1648/// ```
1649/// Is rewritten to approximately the following pseudo-IR:
1650/// ```
1651/// for i = 0 to 9 {
1652/// %t = vector.extract %vec[i] : f32 from vector<9xf32>
1653/// memref.store %t, %arg0[%a + i, %b] : memref<?x?xf32>
1654/// }
1655/// ```
1656template <typename OpTy>
1657struct TransferOp1dConversion : public VectorToSCFPattern<OpTy> {
1658 using VectorToSCFPattern<OpTy>::VectorToSCFPattern;
1659
1660 LogicalResult matchAndRewrite(OpTy xferOp,
1661 PatternRewriter &rewriter) const override {
1662 // TODO: support 0-d corner case.
1663 if (xferOp.getTransferRank() == 0)
1664 return failure();
1665 auto map = xferOp.getPermutationMap();
1666 auto memRefType = dyn_cast<MemRefType>(xferOp.getShapedType());
1667
1668 if (!memRefType)
1669 return failure();
1670 if (xferOp.getVectorType().getRank() != 1)
1671 return failure();
1672 if (map.isMinorIdentity() && memRefType.isLastDimUnitStride())
1673 return failure(); // Handled by ConvertVectorToLLVM
1674
1675 // Loop bounds, step, state...
1676 Location loc = xferOp.getLoc();
1677 auto vecType = xferOp.getVectorType();
1678 auto lb = arith::ConstantIndexOp::create(rewriter, loc, 0);
1679 Value ub =
1680 arith::ConstantIndexOp::create(rewriter, loc, vecType.getDimSize(0));
1681 if (vecType.isScalable()) {
1682 Value vscale =
1683 vector::VectorScaleOp::create(rewriter, loc, rewriter.getIndexType());
1684 ub = arith::MulIOp::create(rewriter, loc, ub, vscale);
1685 }
1686 auto step = arith::ConstantIndexOp::create(rewriter, loc, 1);
1687 auto loopState = Strategy1d<OpTy>::initialLoopState(rewriter, xferOp);
1688
1689 // Generate for loop.
1690 rewriter.replaceOpWithNewOp<scf::ForOp>(
1691 xferOp, lb, ub, step, loopState ? ValueRange(loopState) : ValueRange(),
1692 [&](OpBuilder &b, Location loc, Value iv, ValueRange loopState) {
1693 Strategy1d<OpTy>::generateForLoopBody(b, loc, xferOp, iv, loopState);
1694 });
1695
1696 return success();
1697 }
1698};
1699
1700} // namespace lowering_1_d
1701} // namespace
1702
1705 if (options.unroll) {
1706 patterns.add<lowering_n_d_unrolled::UnrollTransferReadConversion,
1707 lowering_n_d_unrolled::UnrollTransferWriteConversion>(
1708 patterns.getContext(), options);
1709 } else {
1710 patterns.add<lowering_n_d::PrepareTransferReadConversion,
1711 lowering_n_d::PrepareTransferWriteConversion,
1712 lowering_n_d::TransferOpConversion<TransferReadOp>,
1713 lowering_n_d::TransferOpConversion<TransferWriteOp>>(
1714 patterns.getContext(), options);
1715 }
1716 if (options.lowerScalable) {
1717 patterns.add<lowering_n_d::ScalableTransposeTransferWriteConversion>(
1718 patterns.getContext(), options);
1719 }
1720 if (options.targetRank == 1) {
1721 patterns.add<lowering_1_d::TransferOp1dConversion<TransferReadOp>,
1722 lowering_1_d::TransferOp1dConversion<TransferWriteOp>>(
1723 patterns.getContext(), options);
1724 }
1725 patterns.add<lowering_n_d::DecomposePrintOpConversion>(patterns.getContext(),
1726 options);
1727}
1728
1729namespace {
1730
1731struct ConvertVectorToSCFPass
1732 : public impl::ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
1733 ConvertVectorToSCFPass() = default;
1734 ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
1735 this->fullUnroll = options.unroll;
1736 this->targetRank = options.targetRank;
1737 this->lowerTensors = options.lowerTensors;
1738 this->lowerScalable = options.lowerScalable;
1739 }
1740
1741 void runOnOperation() override {
1742 VectorTransferToSCFOptions options;
1743 options.unroll = fullUnroll;
1744 options.targetRank = targetRank;
1745 options.lowerTensors = lowerTensors;
1746 options.lowerScalable = lowerScalable;
1747
1748 // Lower permutation maps first.
1749 RewritePatternSet lowerTransferPatterns(&getContext());
1751 lowerTransferPatterns);
1752 (void)applyPatternsGreedily(getOperation(),
1753 std::move(lowerTransferPatterns));
1754
1755 RewritePatternSet patterns(&getContext());
1757 (void)applyPatternsGreedily(getOperation(), std::move(patterns));
1758 }
1759};
1760
1761} // namespace
1762
1763std::unique_ptr<Pass>
1765 return std::make_unique<ConvertVectorToSCFPass>(options);
1766}
return success()
MLIR_CRUNNERUTILS_EXPORT void printClose()
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
b getContext())
static llvm::ManagedStatic< PassManagerOptions > options
static void printOp(llvm::raw_ostream &os, Operation *op, OpPrintingFlags &flags)
Definition Unit.cpp:18
static void getXferIndices(RewriterBase &rewriter, TransferOpType xferOp, AffineMap offsetMap, ArrayRef< Value > dimValues, SmallVector< Value, 4 > &indices)
For a vector TransferOpType xferOp, an empty indices vector, and an AffineMap representing offsets to...
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: () -> ().
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
UnitAttr getUnitAttr()
Definition Builders.cpp:106
IntegerType getI1Type()
Definition Builders.cpp:61
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
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
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
A trait of region holding operations that define a new scope for automatic allocations,...
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:738
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:512
Operation * getParentWithTrait()
Returns the closest surrounding parent operation with trait Trait.
Definition Operation.h:273
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition Operation.h:726
OperandRange operand_range
Definition Operation.h:396
user_range getUsers()
Returns a range of all users.
Definition Operation.h:925
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Block & front()
Definition Region.h:65
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
type_range getType() const
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
user_range getUsers() const
Definition Value.h:218
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
This is a builder type that keeps local references to arguments.
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:398
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...
void populateVectorTransferPermutationMapLoweringPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of transfer read/write lowering patterns that simplify the permutation map (e....
Value createOrFoldDimOp(OpBuilder &b, Location loc, Value source, int64_t dim)
Helper function that creates a memref::DimOp or tensor::DimOp depending on the type of source.
SmallVector< Value > getAsValues(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > foldResults)
Convert foldResults into Values.
auto makeVscaleConstantBuilder(PatternRewriter &rewriter, Location loc)
Returns a functor (int64_t -> Value) which returns a constant vscale multiple.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:310
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:311
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
void populateVectorToSCFConversionPatterns(RewritePatternSet &patterns, const VectorTransferToSCFOptions &options=VectorTransferToSCFOptions())
Collect a set of patterns to convert from the Vector dialect to SCF + func.
std::unique_ptr< Pass > createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options=VectorTransferToSCFOptions())
Create a pass to convert a subset of vector ops to SCF.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:147
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
When lowering an N-d vector transfer op to an (N-1)-d vector transfer op, a temporary buffer is creat...
Definition VectorToSCF.h:52