MLIR 24.0.0git
SparseVectorization.cpp
Go to the documentation of this file.
1//===- SparseVectorization.cpp - Vectorization of sparsified loops --------===//
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// A pass that converts loops generated by the sparsifier into a form that
10// can exploit SIMD instructions of the target architecture. Note that this pass
11// ensures the sparsifier can generate efficient SIMD (including ArmSVE
12// support) with proper separation of concerns as far as sparsification and
13// vectorization is concerned. However, this pass is not the final abstraction
14// level we want, and not the general vectorizer we want either. It forms a good
15// stepping stone for incremental future improvements though.
16//
17//===----------------------------------------------------------------------===//
18
19#include "Utils/CodegenUtils.h"
20#include "Utils/LoopEmitter.h"
21
30#include "mlir/IR/Matchers.h"
31
32using namespace mlir;
33using namespace mlir::sparse_tensor;
34
35namespace {
36
37/// Target SIMD properties:
38/// vectorLength: # packed data elements (viz. vector<16xf32> has length 16)
39/// enableVLAVectorization: enables scalable vectors (viz. ARMSve)
40/// enableSIMDIndex32: uses 32-bit indices in gather/scatter for efficiency
41struct VL {
42 unsigned vectorLength;
43 bool enableVLAVectorization;
44 bool enableSIMDIndex32;
45};
46
47/// Helper test for invariant argument (defined outside given block).
48static bool isInvariantArg(BlockArgument arg, Block *block) {
49 return arg.getOwner() != block;
50}
51
52/// Helper test for invariant value (defined outside given block).
53/// Handles both block arguments and operation results.
54static bool isInvariantValue(Value val, Block *block) {
55 if (auto arg = dyn_cast<BlockArgument>(val))
56 return isInvariantArg(arg, block);
57
58 return val.getDefiningOp()->getBlock() != block;
59}
60
61/// Returns true when `mem`'s most minor dimension has a statically known
62/// non-unit stride.
63///
64/// `genVectorLoad/genVectorStore` assume a contiguous
65/// `vector.maskedload/vector.maskedstore` is safe for consecutive loop
66/// indices, which breaks for a strided view extracting one component out
67/// of an interleaved (AoS) COO coordinate buffer.
68///
69/// Example:
70/// A `compressed(nonunique) + singleton` region stores coordinates as
71/// `[row0, col0, row1, col1, ...]`, so a 2-lane masked load of `col[0:2]`
72/// (offset=1) would read physical offsets {1, 2} = `[col0, row1]` instead
73/// of the intended {1, 3} = `[col0, col1]`: a silent miscompile.
74///
75/// NOTE: A stride that can't be proven non-unit by either means is assumed
76/// safe.
77static bool hasKnownNonUnitStride(Value mem) {
78 // sparse_tensor.coordinates isn't lowered to a concrete strided memref
79 // until sparse-tensor-codegen runs, so at this point its type
80 // still has a dynamic stride even when the true stride is already known
81 // from the tensor's encoding -- hence the special case below instead of
82 // trusting the memref type.
83 if (auto toCoords = mem.getDefiningOp<ToCoordinatesOp>()) {
84 SparseTensorType stt = getSparseTensorType(toCoords.getTensor());
85 Level cooStart = stt.getAoSCOOStart();
86 // A single trailing level (lvlRank - cooStart == 1) is not actually
87 // interleaved with anything else, so it degenerates to a contiguous
88 // buffer.
89 if (toCoords.getLevel() >= cooStart)
90 return stt.getLvlRank() - cooStart != 1;
91 return false;
92 }
93
94 auto memTp = dyn_cast<MemRefType>(mem.getType());
95 if (!memTp)
96 return false;
98 int64_t offset;
99 if (failed(memTp.getStridesAndOffset(strides, offset)))
100 return false;
101 return !strides.empty() && !ShapedType::isDynamic(strides.back()) &&
102 strides.back() != 1;
103}
104
105/// Constructs vector type for element type.
106static VectorType vectorType(VL vl, Type etp) {
107 return VectorType::get(vl.vectorLength, etp, vl.enableVLAVectorization);
108}
109
110/// Constructs vector type from a memref value.
111static VectorType vectorType(VL vl, Value mem) {
112 return vectorType(vl, getMemRefType(mem).getElementType());
113}
114
115/// Constructs vector iteration mask.
116static Value genVectorMask(PatternRewriter &rewriter, Location loc, VL vl,
117 Value iv, Value lo, Value hi, Value step) {
118 VectorType mtp = vectorType(vl, rewriter.getI1Type());
119 // Special case if the vector length evenly divides the trip count (for
120 // example, "for i = 0, 128, 16"). A constant all-true mask is generated
121 // so that all subsequent masked memory operations are immediately folded
122 // into unconditional memory operations.
123 IntegerAttr loInt, hiInt, stepInt;
124 if (matchPattern(lo, m_Constant(&loInt)) &&
125 matchPattern(hi, m_Constant(&hiInt)) &&
126 matchPattern(step, m_Constant(&stepInt))) {
127 if (((hiInt.getInt() - loInt.getInt()) % stepInt.getInt()) == 0) {
128 Value trueVal = constantI1(rewriter, loc, true);
129 return vector::BroadcastOp::create(rewriter, loc, mtp, trueVal);
130 }
131 }
132 // Otherwise, generate a vector mask that avoids overrunning the upperbound
133 // during vector execution. Here we rely on subsequent loop optimizations to
134 // avoid executing the mask in all iterations, for example, by splitting the
135 // loop into an unconditional vector loop and a scalar cleanup loop.
136 auto min = AffineMap::get(
137 /*dimCount=*/2, /*symbolCount=*/1,
138 {rewriter.getAffineSymbolExpr(0),
139 rewriter.getAffineDimExpr(0) - rewriter.getAffineDimExpr(1)},
140 rewriter.getContext());
141 Value end = rewriter.createOrFold<affine::AffineMinOp>(
142 loc, min, ValueRange{hi, iv, step});
143 return vector::CreateMaskOp::create(rewriter, loc, mtp, end);
144}
145
146/// Generates a vectorized invariant. Here we rely on subsequent loop
147/// optimizations to hoist the invariant broadcast out of the vector loop.
148static Value genVectorInvariantValue(PatternRewriter &rewriter, VL vl,
149 Value val) {
150 VectorType vtp = vectorType(vl, val.getType());
151 return vector::BroadcastOp::create(rewriter, val.getLoc(), vtp, val);
152}
153
154/// Generates a vectorized load lhs = a[ind[lo:hi]] or lhs = a[lo:hi],
155/// where 'lo' denotes the current index and 'hi = lo + vl - 1'. Note
156/// that the sparsifier can only generate indirect loads in
157/// the last index, i.e. back().
158static Value genVectorLoad(PatternRewriter &rewriter, Location loc, VL vl,
159 Value mem, ArrayRef<Value> idxs, Value vmask) {
160 VectorType vtp = vectorType(vl, mem);
161 Value pass = constantZero(rewriter, loc, vtp);
162 if (llvm::isa<VectorType>(idxs.back().getType())) {
163 SmallVector<Value> scalarArgs(idxs);
164 Value indexVec = idxs.back();
165 scalarArgs.back() = constantIndex(rewriter, loc, 0);
166 return vector::GatherOp::create(rewriter, loc, vtp, mem, scalarArgs,
167 indexVec, vmask, pass);
168 }
169 return vector::MaskedLoadOp::create(rewriter, loc, vtp, mem, idxs, vmask,
170 pass);
171}
172
173/// Generates a vectorized store a[ind[lo:hi]] = rhs or a[lo:hi] = rhs
174/// where 'lo' denotes the current index and 'hi = lo + vl - 1'. Note
175/// that the sparsifier can only generate indirect stores in
176/// the last index, i.e. back().
177static void genVectorStore(PatternRewriter &rewriter, Location loc, Value mem,
178 ArrayRef<Value> idxs, Value vmask, Value rhs) {
179 if (llvm::isa<VectorType>(idxs.back().getType())) {
180 SmallVector<Value> scalarArgs(idxs);
181 Value indexVec = idxs.back();
182 scalarArgs.back() = constantIndex(rewriter, loc, 0);
183 vector::ScatterOp::create(rewriter, loc, /*resultType=*/nullptr, mem,
184 scalarArgs, indexVec, vmask, rhs);
185 return;
186 }
187 vector::MaskedStoreOp::create(rewriter, loc, mem, idxs, vmask, rhs);
188}
189
190/// Detects a vectorizable reduction operations and returns the
191/// combining kind of reduction on success in `kind`.
192static bool isVectorizableReduction(Value red, Value iter,
193 vector::CombiningKind &kind) {
194 if (auto addf = red.getDefiningOp<arith::AddFOp>()) {
195 kind = vector::CombiningKind::ADD;
196 return addf->getOperand(0) == iter || addf->getOperand(1) == iter;
197 }
198 if (auto addi = red.getDefiningOp<arith::AddIOp>()) {
199 kind = vector::CombiningKind::ADD;
200 return addi->getOperand(0) == iter || addi->getOperand(1) == iter;
201 }
202 if (auto subf = red.getDefiningOp<arith::SubFOp>()) {
203 kind = vector::CombiningKind::ADD;
204 return subf->getOperand(0) == iter;
205 }
206 if (auto subi = red.getDefiningOp<arith::SubIOp>()) {
207 kind = vector::CombiningKind::ADD;
208 return subi->getOperand(0) == iter;
209 }
210 if (auto mulf = red.getDefiningOp<arith::MulFOp>()) {
211 kind = vector::CombiningKind::MUL;
212 return mulf->getOperand(0) == iter || mulf->getOperand(1) == iter;
213 }
214 if (auto muli = red.getDefiningOp<arith::MulIOp>()) {
215 kind = vector::CombiningKind::MUL;
216 return muli->getOperand(0) == iter || muli->getOperand(1) == iter;
217 }
218 if (auto andi = red.getDefiningOp<arith::AndIOp>()) {
219 kind = vector::CombiningKind::AND;
220 return andi->getOperand(0) == iter || andi->getOperand(1) == iter;
221 }
222 if (auto ori = red.getDefiningOp<arith::OrIOp>()) {
223 kind = vector::CombiningKind::OR;
224 return ori->getOperand(0) == iter || ori->getOperand(1) == iter;
225 }
226 if (auto xori = red.getDefiningOp<arith::XOrIOp>()) {
227 kind = vector::CombiningKind::XOR;
228 return xori->getOperand(0) == iter || xori->getOperand(1) == iter;
229 }
230 return false;
231}
232
233/// Generates an initial value for a vector reduction, following the scheme
234/// given in Chapter 5 of "The Software Vectorization Handbook", where the
235/// initial scalar value is correctly embedded in the vector reduction value,
236/// and a straightforward horizontal reduction will complete the operation.
237/// Value 'r' denotes the initial value of the reduction outside the loop.
238static Value genVectorReducInit(PatternRewriter &rewriter, Location loc,
239 Value red, Value iter, Value r,
240 VectorType vtp) {
241 vector::CombiningKind kind;
242 if (!isVectorizableReduction(red, iter, kind))
243 llvm_unreachable("unknown reduction");
244 switch (kind) {
245 case vector::CombiningKind::ADD:
246 case vector::CombiningKind::XOR:
247 // Initialize reduction vector to: | 0 | .. | 0 | r |
248 return vector::InsertOp::create(rewriter, loc, r,
249 constantZero(rewriter, loc, vtp),
250 constantIndex(rewriter, loc, 0));
251 case vector::CombiningKind::MUL:
252 // Initialize reduction vector to: | 1 | .. | 1 | r |
253 return vector::InsertOp::create(rewriter, loc, r,
254 constantOne(rewriter, loc, vtp),
255 constantIndex(rewriter, loc, 0));
256 case vector::CombiningKind::AND:
257 case vector::CombiningKind::OR:
258 // Initialize reduction vector to: | r | .. | r | r |
259 return vector::BroadcastOp::create(rewriter, loc, vtp, r);
260 default:
261 break;
262 }
263 llvm_unreachable("unknown reduction kind");
264}
265
266/// This method is called twice to analyze and rewrite the given subscripts.
267/// The first call (!codegen) does the analysis. Then, on success, the second
268/// call (codegen) yields the proper vector form in the output parameter
269/// vector 'idxs'. This mechanism ensures that analysis and rewriting code
270/// stay in sync. Note that the analyis part is simple because the sparsifier
271/// only generates relatively simple subscript expressions.
272///
273/// See https://llvm.org/docs/GetElementPtr.html for some background on
274/// the complications described below.
275///
276/// We need to generate a position/coordinate load from the sparse storage
277/// scheme. Narrower data types need to be zero extended before casting
278/// the value into the `index` type used for looping and indexing.
279///
280/// For the scalar case, subscripts simply zero extend narrower indices
281/// into 64-bit values before casting to an index type without a performance
282/// penalty. Indices that already are 64-bit, in theory, cannot express the
283/// full range since the LLVM backend defines addressing in terms of an
284/// unsigned pointer/signed index pair.
285static bool vectorizeSubscripts(PatternRewriter &rewriter, scf::ForOp forOp,
286 VL vl, ValueRange subs, bool codegen,
287 Value vmask, SmallVectorImpl<Value> &idxs) {
288 unsigned d = 0;
289 unsigned dim = subs.size();
290 Block *block = &forOp.getRegion().front();
291 for (auto sub : subs) {
292 bool innermost = ++d == dim;
293 // Invariant subscripts in outer dimensions simply pass through.
294 // Note that we rely on LICM to hoist loads where all subscripts
295 // are invariant in the innermost loop.
296 // Example:
297 // a[inv][i] for inv
298 if (isInvariantValue(sub, block)) {
299 if (innermost)
300 return false;
301 if (codegen)
302 idxs.push_back(sub);
303 continue; // success so far
304 }
305 // Invariant block arguments (including outer loop indices) in outer
306 // dimensions simply pass through. Direct loop indices in the
307 // innermost loop simply pass through as well.
308 // Example:
309 // a[i][j] for both i and j
310 if (auto arg = llvm::dyn_cast<BlockArgument>(sub)) {
311 if (isInvariantArg(arg, block) == innermost)
312 return false;
313 if (codegen)
314 idxs.push_back(sub);
315 continue; // success so far
316 }
317 // Look under the hood of casting.
318 auto cast = sub;
319 while (true) {
320 if (auto icast = cast.getDefiningOp<arith::IndexCastOp>())
321 cast = icast->getOperand(0);
322 else if (auto ecast = cast.getDefiningOp<arith::ExtUIOp>())
323 cast = ecast->getOperand(0);
324 else
325 break;
326 }
327 // Since the index vector is used in a subsequent gather/scatter
328 // operations, which effectively defines an unsigned pointer + signed
329 // index, we must zero extend the vector to an index width. For 8-bit
330 // and 16-bit values, an 32-bit index width suffices. For 32-bit values,
331 // zero extending the elements into 64-bit loses some performance since
332 // the 32-bit indexed gather/scatter is more efficient than the 64-bit
333 // index variant (if the negative 32-bit index space is unused, the
334 // enableSIMDIndex32 flag can preserve this performance). For 64-bit
335 // values, there is no good way to state that the indices are unsigned,
336 // which creates the potential of incorrect address calculations in the
337 // unlikely case we need such extremely large offsets.
338 // Example:
339 // a[ ind[i] ]
340 if (auto load = cast.getDefiningOp<memref::LoadOp>()) {
341 if (!innermost)
342 return false;
343 if (hasKnownNonUnitStride(load.getMemRef()))
344 return false;
345 if (codegen) {
346 SmallVector<Value> idxs2(load.getIndices()); // no need to analyze
347 Location loc = forOp.getLoc();
348 Value vload =
349 genVectorLoad(rewriter, loc, vl, load.getMemRef(), idxs2, vmask);
350 Type etp = llvm::cast<VectorType>(vload.getType()).getElementType();
351 if (!llvm::isa<IndexType>(etp)) {
352 if (etp.getIntOrFloatBitWidth() < 32)
353 vload = arith::ExtUIOp::create(
354 rewriter, loc, vectorType(vl, rewriter.getI32Type()), vload);
355 else if (etp.getIntOrFloatBitWidth() < 64 && !vl.enableSIMDIndex32)
356 vload = arith::ExtUIOp::create(
357 rewriter, loc, vectorType(vl, rewriter.getI64Type()), vload);
358 }
359 idxs.push_back(vload);
360 }
361 continue; // success so far
362 }
363 // Address calculation 'i = add inv, idx' (after LICM).
364 // Example:
365 // a[base + i]
366 if (auto load = cast.getDefiningOp<arith::AddIOp>()) {
367 Value inv = load.getOperand(0);
368 Value idx = load.getOperand(1);
369 // Swap non-invariant.
370 if (!isInvariantValue(inv, block)) {
371 inv = idx;
372 idx = load.getOperand(0);
373 }
374 // Inspect.
375 if (isInvariantValue(inv, block)) {
376 if (auto arg = llvm::dyn_cast<BlockArgument>(idx)) {
377 if (isInvariantArg(arg, block) || !innermost)
378 return false;
379 if (codegen)
380 idxs.push_back(
381 arith::AddIOp::create(rewriter, forOp.getLoc(), inv, idx));
382 continue; // success so far
383 }
384 }
385 }
386 return false;
387 }
388 return true;
389}
390
391#define UNAOP(xxx) \
392 if (auto x = dyn_cast<xxx>(def)) { \
393 if (codegen) { \
394 vexp = xxx::create(rewriter, loc, ValueRange{vx}, x.getProperties(), \
395 x->getDiscardableAttrDictionary().getValue()); \
396 } \
397 return true; \
398 }
399
400#define TYPEDUNAOP(xxx) \
401 if (auto x = dyn_cast<xxx>(def)) { \
402 if (codegen) { \
403 VectorType vtp = vectorType(vl, x.getType()); \
404 vexp = xxx::create(rewriter, loc, TypeRange{vtp}, ValueRange{vx}, \
405 x.getProperties(), \
406 x->getDiscardableAttrDictionary().getValue()); \
407 } \
408 return true; \
409 }
410
411#define BINOP(xxx) \
412 if (auto x = dyn_cast<xxx>(def)) { \
413 if (codegen) { \
414 vexp = xxx::create(rewriter, loc, ValueRange{vx, vy}, x.getProperties(), \
415 x->getDiscardableAttrDictionary().getValue()); \
416 } \
417 return true; \
418 }
419
420/// This method is called twice to analyze and rewrite the given expression.
421/// The first call (!codegen) does the analysis. Then, on success, the second
422/// call (codegen) yields the proper vector form in the output parameter 'vexp'.
423/// This mechanism ensures that analysis and rewriting code stay in sync. Note
424/// that the analyis part is simple because the sparsifier only generates
425/// relatively simple expressions inside the for-loops.
426static bool vectorizeExpr(PatternRewriter &rewriter, scf::ForOp forOp, VL vl,
427 Value exp, bool codegen, Value vmask, Value &vexp) {
428 Location loc = forOp.getLoc();
429 // Reject unsupported types.
430 if (!VectorType::isValidElementType(exp.getType()))
431 return false;
432 // A block argument is invariant/reduction/index.
433 if (auto arg = llvm::dyn_cast<BlockArgument>(exp)) {
434 if (arg == forOp.getInductionVar()) {
435 // We encountered a single, innermost index inside the computation,
436 // such as a[i] = i, which must convert to [i, i+1, ...].
437 if (codegen) {
438 VectorType vtp = vectorType(vl, arg.getType());
439 Value veci = vector::BroadcastOp::create(rewriter, loc, vtp, arg);
440 Value incr = vector::StepOp::create(rewriter, loc, vtp);
441 vexp = arith::AddIOp::create(rewriter, loc, veci, incr);
442 }
443 return true;
444 }
445 // An invariant or reduction. In both cases, we treat this as an
446 // invariant value, and rely on later replacing and folding to
447 // construct a proper reduction chain for the latter case.
448 if (codegen)
449 vexp = genVectorInvariantValue(rewriter, vl, exp);
450 return true;
451 }
452 // Something defined outside the loop-body is invariant.
453 Operation *def = exp.getDefiningOp();
454 Block *block = &forOp.getRegion().front();
455 if (def->getBlock() != block) {
456 if (codegen)
457 vexp = genVectorInvariantValue(rewriter, vl, exp);
458 return true;
459 }
460 // Proper load operations. These are either values involved in the
461 // actual computation, such as a[i] = b[i] becomes a[lo:hi] = b[lo:hi],
462 // or coordinate values inside the computation that are now fetched from
463 // the sparse storage coordinates arrays, such as a[i] = i becomes
464 // a[lo:hi] = ind[lo:hi], where 'lo' denotes the current index
465 // and 'hi = lo + vl - 1'.
466 if (auto load = dyn_cast<memref::LoadOp>(def)) {
467 if (hasKnownNonUnitStride(load.getMemRef()))
468 return false;
469 auto subs = load.getIndices();
471 if (vectorizeSubscripts(rewriter, forOp, vl, subs, codegen, vmask, idxs)) {
472 if (codegen)
473 vexp = genVectorLoad(rewriter, loc, vl, load.getMemRef(), idxs, vmask);
474 return true;
475 }
476 return false;
477 }
478 // Inside loop-body unary and binary operations. Note that it would be
479 // nicer if we could somehow test and build the operations in a more
480 // concise manner than just listing them all (although this way we know
481 // for certain that they can vectorize).
482 //
483 // TODO: avoid visiting CSEs multiple times
484 //
485 if (def->getNumOperands() == 1) {
486 Value vx;
487 if (vectorizeExpr(rewriter, forOp, vl, def->getOperand(0), codegen, vmask,
488 vx)) {
489 UNAOP(math::AbsFOp)
490 UNAOP(math::AbsIOp)
491 UNAOP(math::CeilOp)
492 UNAOP(math::FloorOp)
493 UNAOP(math::SqrtOp)
494 UNAOP(math::ExpM1Op)
495 UNAOP(math::Log1pOp)
496 UNAOP(math::SinOp)
497 UNAOP(math::TanhOp)
498 UNAOP(arith::NegFOp)
499 TYPEDUNAOP(arith::TruncFOp)
500 TYPEDUNAOP(arith::ExtFOp)
501 TYPEDUNAOP(arith::FPToSIOp)
502 TYPEDUNAOP(arith::FPToUIOp)
503 TYPEDUNAOP(arith::SIToFPOp)
504 TYPEDUNAOP(arith::UIToFPOp)
505 TYPEDUNAOP(arith::ExtSIOp)
506 TYPEDUNAOP(arith::ExtUIOp)
507 TYPEDUNAOP(arith::IndexCastOp)
508 TYPEDUNAOP(arith::TruncIOp)
509 TYPEDUNAOP(arith::BitcastOp)
510 // TODO: complex?
511 }
512 } else if (def->getNumOperands() == 2) {
513 Value vx, vy;
514 if (vectorizeExpr(rewriter, forOp, vl, def->getOperand(0), codegen, vmask,
515 vx) &&
516 vectorizeExpr(rewriter, forOp, vl, def->getOperand(1), codegen, vmask,
517 vy)) {
518 // We only accept shift-by-invariant (where the same shift factor applies
519 // to all packed elements). In the vector dialect, this is still
520 // represented with an expanded vector at the right-hand-side, however,
521 // so that we do not have to special case the code generation.
522 if (isa<arith::ShLIOp>(def) || isa<arith::ShRUIOp>(def) ||
523 isa<arith::ShRSIOp>(def)) {
524 Value shiftFactor = def->getOperand(1);
525 if (!isInvariantValue(shiftFactor, block))
526 return false;
527 }
528 // Generate code.
529 BINOP(arith::MulFOp)
530 BINOP(arith::MulIOp)
531 BINOP(arith::DivFOp)
532 BINOP(arith::DivSIOp)
533 BINOP(arith::DivUIOp)
534 BINOP(arith::AddFOp)
535 BINOP(arith::AddIOp)
536 BINOP(arith::SubFOp)
537 BINOP(arith::SubIOp)
538 BINOP(arith::AndIOp)
539 BINOP(arith::OrIOp)
540 BINOP(arith::XOrIOp)
541 BINOP(arith::ShLIOp)
542 BINOP(arith::ShRUIOp)
543 BINOP(arith::ShRSIOp)
544 // TODO: complex?
545 }
546 }
547 return false;
548}
549
550#undef UNAOP
551#undef TYPEDUNAOP
552#undef BINOP
553
554/// This method is called twice to analyze and rewrite the given for-loop.
555/// The first call (!codegen) does the analysis. Then, on success, the second
556/// call (codegen) rewriters the IR into vector form. This mechanism ensures
557/// that analysis and rewriting code stay in sync.
558static bool vectorizeStmt(PatternRewriter &rewriter, scf::ForOp forOp, VL vl,
559 bool codegen) {
560 Block &block = forOp.getRegion().front();
561 // For loops with single yield statement (as below) could be generated
562 // when custom reduce is used with unary operation.
563 // for (...)
564 // yield c_0
565 if (block.getOperations().size() <= 1)
566 return false;
567
568 Location loc = forOp.getLoc();
569 scf::YieldOp yield = cast<scf::YieldOp>(block.getTerminator());
570 auto &last = *++block.rbegin();
571 scf::ForOp forOpNew;
572
573 // Perform initial set up during codegen (we know that the first analysis
574 // pass was successful). For reductions, we need to construct a completely
575 // new for-loop, since the incoming and outgoing reduction type
576 // changes into SIMD form. For stores, we can simply adjust the stride
577 // and insert in the existing for-loop. In both cases, we set up a vector
578 // mask for all operations which takes care of confining vectors to
579 // the original iteration space (later cleanup loops or other
580 // optimizations can take care of those).
581 Value vmask;
582 if (codegen) {
583 Value step = constantIndex(rewriter, loc, vl.vectorLength);
584 if (vl.enableVLAVectorization) {
585 Value vscale =
586 vector::VectorScaleOp::create(rewriter, loc, rewriter.getIndexType());
587 step = arith::MulIOp::create(rewriter, loc, vscale, step);
588 }
589 if (!yield.getResults().empty()) {
590 Value init = forOp.getInitArgs()[0];
591 VectorType vtp = vectorType(vl, init.getType());
592 Value vinit = genVectorReducInit(rewriter, loc, yield->getOperand(0),
593 forOp.getRegionIterArg(0), init, vtp);
594 forOpNew =
595 scf::ForOp::create(rewriter, loc, forOp.getLowerBound(),
596 forOp.getUpperBound(), step, vinit,
597 /*bodyBuilder=*/nullptr, forOp.getUnsignedCmp());
598 forOpNew->setDiscardableAttr(
600 forOp->getDiscardableAttr(LoopEmitter::getLoopEmitterLoopAttrName()));
601 rewriter.setInsertionPointToStart(forOpNew.getBody());
602 } else {
603 rewriter.modifyOpInPlace(forOp, [&]() { forOp.setStep(step); });
604 rewriter.setInsertionPoint(yield);
605 }
606 vmask = genVectorMask(rewriter, loc, vl, forOp.getInductionVar(),
607 forOp.getLowerBound(), forOp.getUpperBound(), step);
608 }
609
610 // Sparse for-loops either are terminated by a non-empty yield operation
611 // (reduction loop) or otherwise by a store operation (pararallel loop).
612 if (!yield.getResults().empty()) {
613 // Analyze/vectorize reduction.
614 if (yield->getNumOperands() != 1)
615 return false;
616 Value red = yield->getOperand(0);
617 Value iter = forOp.getRegionIterArg(0);
618 vector::CombiningKind kind;
619 Value vrhs;
620 if (isVectorizableReduction(red, iter, kind) &&
621 vectorizeExpr(rewriter, forOp, vl, red, codegen, vmask, vrhs)) {
622 if (codegen) {
623 Value partial = forOpNew.getResult(0);
624 Value vpass = genVectorInvariantValue(rewriter, vl, iter);
625 Value vred = arith::SelectOp::create(rewriter, loc, vmask, vrhs, vpass);
626 scf::YieldOp::create(rewriter, loc, vred);
627 rewriter.setInsertionPointAfter(forOpNew);
628 Value vres = vector::ReductionOp::create(rewriter, loc, kind, partial);
629 // Now do some relinking (last one is not completely type safe
630 // but all bad ones are removed right away). This also folds away
631 // nop broadcast operations.
632 rewriter.replaceAllUsesWith(forOp.getResult(0), vres);
633 rewriter.replaceAllUsesWith(forOp.getInductionVar(),
634 forOpNew.getInductionVar());
635 rewriter.replaceAllUsesWith(forOp.getRegionIterArg(0),
636 forOpNew.getRegionIterArg(0));
637 rewriter.eraseOp(forOp);
638 }
639 return true;
640 }
641 } else if (auto store = dyn_cast<memref::StoreOp>(last)) {
642 // Analyze/vectorize store operation.
643 if (hasKnownNonUnitStride(store.getMemRef()))
644 return false;
645 auto subs = store.getIndices();
647 Value rhs = store.getValue();
648 Value vrhs;
649 if (vectorizeSubscripts(rewriter, forOp, vl, subs, codegen, vmask, idxs) &&
650 vectorizeExpr(rewriter, forOp, vl, rhs, codegen, vmask, vrhs)) {
651 if (codegen) {
652 genVectorStore(rewriter, loc, store.getMemRef(), idxs, vmask, vrhs);
653 rewriter.eraseOp(store);
654 }
655 return true;
656 }
657 }
658
659 assert(!codegen && "cannot call codegen when analysis failed");
660 return false;
661}
662
663/// Basic for-loop vectorizer.
664struct ForOpRewriter : public OpRewritePattern<scf::ForOp> {
665public:
666 using OpRewritePattern<scf::ForOp>::OpRewritePattern;
667
668 ForOpRewriter(MLIRContext *context, unsigned vectorLength,
669 bool enableVLAVectorization, bool enableSIMDIndex32)
670 : OpRewritePattern(context),
671 vl{vectorLength, enableVLAVectorization, enableSIMDIndex32} {}
672
673 LogicalResult matchAndRewrite(scf::ForOp op,
674 PatternRewriter &rewriter) const override {
675 // Check for single block, unit-stride for-loop that is generated by
676 // sparsifier, which means no data dependence analysis is required,
677 // and its loop-body is very restricted in form.
678 if (!op.getRegion().hasOneBlock() || !isOneInteger(op.getStep()) ||
679 !op->hasDiscardableAttr(LoopEmitter::getLoopEmitterLoopAttrName()))
680 return failure();
681 // Analyze (!codegen) and rewrite (codegen) loop-body.
682 if (vectorizeStmt(rewriter, op, vl, /*codegen=*/false) &&
683 vectorizeStmt(rewriter, op, vl, /*codegen=*/true))
684 return success();
685 return failure();
686 }
687
688private:
689 const VL vl;
690};
691
692static LogicalResult cleanReducChain(PatternRewriter &rewriter, Operation *op,
693 Value inp) {
694 if (auto redOp = inp.getDefiningOp<vector::ReductionOp>()) {
695 if (auto forOp = redOp.getVector().getDefiningOp<scf::ForOp>()) {
696 if (forOp->hasDiscardableAttr(
698 rewriter.replaceOp(op, redOp.getVector());
699 return success();
700 }
701 }
702 }
703 return failure();
704}
705
706/// Reduction chain cleanup.
707/// v = for { }
708/// s = vsum(v) v = for { }
709/// u = broadcast(s) -> for (v) { }
710/// for (u) { }
711struct ReducChainBroadcastRewriter
712 : public OpRewritePattern<vector::BroadcastOp> {
713public:
714 using OpRewritePattern<vector::BroadcastOp>::OpRewritePattern;
715
716 LogicalResult matchAndRewrite(vector::BroadcastOp op,
717 PatternRewriter &rewriter) const override {
718 return cleanReducChain(rewriter, op, op.getSource());
719 }
720};
721
722/// Reduction chain cleanup.
723/// v = for { }
724/// s = vsum(v) v = for { }
725/// u = insert(s) -> for (v) { }
726/// for (u) { }
727struct ReducChainInsertRewriter : public OpRewritePattern<vector::InsertOp> {
728public:
729 using OpRewritePattern<vector::InsertOp>::OpRewritePattern;
730
731 LogicalResult matchAndRewrite(vector::InsertOp op,
732 PatternRewriter &rewriter) const override {
733 return cleanReducChain(rewriter, op, op.getValueToStore());
734 }
735};
736} // namespace
737
738//===----------------------------------------------------------------------===//
739// Public method for populating vectorization rules.
740//===----------------------------------------------------------------------===//
741
742/// Populates the given patterns list with vectorization rules.
744 unsigned vectorLength,
745 bool enableVLAVectorization,
746 bool enableSIMDIndex32) {
747 assert(vectorLength > 0);
749 patterns.add<ForOpRewriter>(patterns.getContext(), vectorLength,
750 enableVLAVectorization, enableSIMDIndex32);
751 patterns.add<ReducChainInsertRewriter, ReducChainBroadcastRewriter>(
752 patterns.getContext());
753}
return success()
auto load
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
#define UNAOP(xxx)
#define BINOP(xxx)
#define TYPEDUNAOP(xxx)
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
This class represents an argument of a Block.
Definition Value.h:308
Block * getOwner() const
Returns the block that owns this argument.
Definition Value.h:317
Block represents an ordered list of Operations.
Definition Block.h:34
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
reverse_iterator rbegin()
Definition Block.h:170
AffineExpr getAffineSymbolExpr(unsigned position)
Definition Builders.cpp:377
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerType getI32Type()
Definition Builders.cpp:71
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
IntegerType getI1Type()
Definition Builders.cpp:61
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:377
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
unsigned getNumOperands()
Definition Operation.h:373
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
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.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static constexpr llvm::StringLiteral getLoopEmitterLoopAttrName()
A wrapper around RankedTensorType, which has three goals:
Level getLvlRank() const
Returns the level-rank.
Level getAoSCOOStart() const
Returns the starting level of this sparse tensor type for a trailing COO region that spans at least t...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Value constantIndex(OpBuilder &builder, Location loc, int64_t i)
Generates a constant of index type.
Value constantZero(OpBuilder &builder, Location loc, Type tp)
Generates a 0-valued constant of the given type.
Value constantOne(OpBuilder &builder, Location loc, Type tp)
Generates a 1-valued constant of the given type.
Value constantI1(OpBuilder &builder, Location loc, bool b)
Generates a constant of i1 type.
uint64_t Level
The type of level identifiers and level-ranks.
MemRefType getMemRefType(T &&t)
Convenience method to abbreviate casting getType().
SparseTensorType getSparseTensorType(Value val)
Convenience methods to obtain a SparseTensorType from a Value.
void populateVectorStepLoweringPatterns(RewritePatternSet &patterns, unsigned indexBitwidth=64, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
void populateSparseVectorizationPatterns(RewritePatternSet &patterns, unsigned vectorLength, bool enableVLAVectorization, bool enableSIMDIndex32)
Populates the given patterns list with vectorization rules.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
bool isOneInteger(OpFoldResult v)
Return true if v is an IntegerAttr with value 1.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...