MLIR 24.0.0git
VectorContractToAMXDotProduct.cpp
Go to the documentation of this file.
1//===- VectorContractToAMXDotProduct.cpp ----------------------------------===//
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
15
17#include "mlir/IR/Dominance.h"
19#include "llvm/Support/Casting.h"
20
21#include "mlir/Pass/Pass.h"
23
24using namespace mlir;
25using namespace mlir::vector;
26using namespace mlir::x86;
27
28namespace {
29// Return true if the operation is a constant dense element
30// attribute.
31static bool isZeroVectorConstant(Operation *op) {
32 auto constantOp = dyn_cast_if_present<arith::ConstantOp>(op);
33 if (!constantOp)
34 return false;
35
36 if (!isa<VectorType>(constantOp.getType()))
37 return false;
38
39 auto denseAttr = dyn_cast<DenseElementsAttr>(constantOp.getValue());
40 if (!denseAttr || !denseAttr.isSplat())
41 return false;
42
43 return isZeroIntegerOrFloat(denseAttr.getSplatValue<Attribute>());
44}
45
46// Recursively follows single-use values through scf.yield operations
47// and returns the first non-yield user result in the contraction chain.
49 if (v.getNumUses() != 1)
50 return nullptr;
51
52 OpOperand &use = *v.use_begin();
53 Operation *user = use.getOwner();
54
55 if (!isa<scf::YieldOp>(user))
56 return v;
57
58 auto yield = cast<scf::YieldOp>(user);
59 Operation *parent = yield->getParentOp();
60 unsigned idx = use.getOperandNumber();
61
62 return contractionUsersAfterYield(parent->getResult(idx));
63}
64
65// Function to collapse the last two dimension (k or n, and vnni) to help the
66// amx.tile_load to correctly load the packed element type.
67static Value collapseInnerDims(OpBuilder &builder, Location loc, Value input) {
68 ShapedType inputType = cast<ShapedType>(input.getType());
69 int64_t firstDimToCollapse = inputType.getRank() - 2;
70
71 if (inputType.getRank() == 1)
72 return input;
73
75 for (int64_t i = 0; i < firstDimToCollapse; ++i)
76 reassociation.push_back(ReassociationIndices{i});
77
78 ReassociationIndices collapsedIndices;
79 for (int64_t i = firstDimToCollapse; i < inputType.getRank(); ++i)
80 collapsedIndices.push_back(i);
81
82 reassociation.push_back(collapsedIndices);
83 return memref::CollapseShapeOp::create(builder, loc, input, reassociation);
84}
85
86// Check if a vector.contract operand has a memref read source.
87static bool isReadSrcMemref(Value operand) {
88 Operation *defOp = operand.getDefiningOp();
89 if (!defOp)
90 return false;
91
92 Value srcBuff;
94 .Case<TransferReadOp, LoadOp>(
95 [&](auto readOp) { srcBuff = readOp.getOperand(0); });
96
97 return srcBuff && isa<MemRefType>(srcBuff.getType());
98}
99
100// Return true if any of the values is a masked or out-of-bounds transfer_read,
101// which can't be replaced by a load.
102static bool hasMaskedOrOutOfBoundsRead(ArrayRef<Value> values) {
103 return llvm::any_of(values, [](Value value) {
104 auto readOp = value.getDefiningOp<TransferReadOp>();
105 return readOp && (readOp.getMask() || readOp.hasOutOfBoundsDim());
106 });
107}
108
109// Check if a vector.contract operand reads whole VNNI groups: the memref's
110// static innermost dim is the VNNI factor and the read starts at its origin.
111static bool isVnniOperandRead(Value operand, int64_t vnni) {
112 Operation *defOp = operand.getDefiningOp();
113 if (!defOp)
114 return false;
115
116 Value srcBuff;
117 OpFoldResult vnniIndex;
118 llvm::TypeSwitch<Operation *>(defOp).Case<TransferReadOp, LoadOp>(
119 [&](auto readOp) {
120 srcBuff = readOp.getBase();
121 vnniIndex = readOp.getIndices().back();
122 });
123
124 if (!srcBuff)
125 return false;
126 auto srcType = dyn_cast<MemRefType>(srcBuff.getType());
127 return srcType && srcType.getRank() > 0 &&
128 srcType.getShape().back() == vnni && isZeroInteger(vnniIndex);
129}
130
131// Replaces the indices of the two innermost dims of a VNNI operand by the
132// index of the dim they collapse into.
133static void collapseVnniIndices(OpBuilder &rewriter, Location loc,
135 Value inner = indices.pop_back_val();
136 Value cVnni = arith::ConstantIndexOp::create(rewriter, loc, vnni);
137 Value scaled = arith::MulIOp::create(rewriter, loc, indices.back(), cVnni);
138 indices.back() = arith::AddIOp::create(rewriter, loc, scaled, inner);
139}
140
141// Get the MemRef source and offset index for the operands of
142// vector.contract.
143static FailureOr<std::pair<Value, SmallVector<Value>>>
144getSrcIndxValue(OpBuilder &rewriter, Location loc, Value operand,
145 bool isNotAcc) {
146 Operation *defOp = operand.getDefiningOp();
147 if (!defOp)
148 return failure();
149
150 Value srcBuff;
153 .Case<TransferReadOp, LoadOp>([&](auto readOp) {
154 indexVals = SmallVector<OpFoldResult>(readOp.getIndices().begin(),
155 readOp.getIndices().end());
156 srcBuff = readOp.getOperand(0);
157 });
158
159 if (!srcBuff || !isa<MemRefType>(srcBuff.getType()))
160 return failure();
161
163 indices.reserve(indexVals.size());
164
165 for (OpFoldResult ofr : indexVals) {
166 indices.push_back(
167 mlir::getValueOrCreateConstantIndexOp(rewriter, loc, ofr));
168 }
169
170 if (isNotAcc) {
171 collapseVnniIndices(rewriter, loc, indices,
172 cast<MemRefType>(srcBuff.getType()).getShape().back());
173 srcBuff = collapseInnerDims(rewriter, loc, srcBuff);
174 }
175
176 return std::make_pair(srcBuff, indices);
177}
178
179// Function to validate the loop step value.
180static LogicalResult validateLoopStep(OpBuilder &rewriter, Value step,
181 int64_t value) {
182
183 auto cst = step.getDefiningOp<arith::ConstantIndexOp>();
184 if (!cst)
185 return failure();
186
187 if (cst.value() != value && cst.value() != 1)
188 return failure();
189
190 return success();
191}
192
193// Function to validate the vector.contract operation.
194static LogicalResult validateContractOps(OpBuilder &rewriter,
195 vector::ContractionOp contractOp,
196 unsigned int blockingFactor,
197 Value srcBuffLhs, Value srcBuffRhs,
198 bool srcValidate) {
199
200 if (srcValidate) {
201 // Get the MemRef buffer of LHS operand.
202 auto srcIndxLhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
203 contractOp.getLhs(), false);
204 if (failed(srcIndxLhs))
205 return failure();
206 auto [buffLhs, indicesLhs] = *srcIndxLhs;
207
208 // Get the MemRef buffer of RHS operand.
209 auto srcIndxRhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
210 contractOp.getRhs(), false);
211 if (failed(srcIndxRhs))
212 return failure();
213 auto [buffRhs, indicesRhs] = *srcIndxRhs;
214
215 // Return failure if the Memref buff didn't match.
216 if (buffLhs != srcBuffLhs)
217 return failure();
218
219 if (buffRhs != srcBuffRhs)
220 return failure();
221 }
222
223 if (!contractionUsersAfterYield(contractOp.getResult()))
224 return failure();
225
226 VectorType accTy = dyn_cast<VectorType>(contractOp.getAccType());
227 if (!accTy)
228 return failure();
229
230 // The Accumulator dims should be 16 or 1. Like <1x16x16> or <16x16>.
231 ArrayRef<int64_t> accShape = accTy.getShape();
232 SmallVector<int64_t> nonUnitDimAcc;
233 llvm::copy_if(accShape, std::back_inserter(nonUnitDimAcc),
234 [](int64_t dim) { return (dim != 16 && dim != 1); });
235
236 if (nonUnitDimAcc.size() != 0)
237 return failure();
238
239 // The LHS dims should be 16 or vnni or 1. Like <1x16x16x2> or
240 // <16x16x4>. The vnni dims should be 2 or 4.
241 VectorType lhsTy = contractOp.getLhsType();
242 ArrayRef<int64_t> lhsShape = lhsTy.getShape();
243 SmallVector<int64_t> nonUnitDimLhs;
244 llvm::copy_if(lhsShape, std::back_inserter(nonUnitDimLhs),
245 [](int64_t dim) { return (dim != 16 && dim != 1); });
246
247 if (nonUnitDimLhs.size() != 1)
248 return failure();
249
250 if (nonUnitDimLhs[0] != blockingFactor)
251 return failure();
252
253 // The RHS dims should be 16 or vnni or 1. Like <1x16x16x2> or
254 // <16x16x4>. The vnni dims should be 2 or 4.
255 VectorType rhsTy = contractOp.getRhsType();
256 ArrayRef<int64_t> rhsShape = rhsTy.getShape();
257 llvm::SmallVector<int64_t> nonUnitDimRhs;
258 llvm::copy_if(rhsShape, std::back_inserter(nonUnitDimRhs),
259 [](int64_t dim) { return (dim != 16 && dim != 1); });
260
261 if (nonUnitDimRhs.size() != 1)
262 return failure();
263
264 if (nonUnitDimRhs[0] != blockingFactor)
265 return failure();
266
267 return success();
268}
269
270// Traces an accumulator back through the iter_args of the given loops and
271// returns the first value that is not one of them, e.g., the init value of the
272// outermost loop or a value computed within the loops.
273static Value getLoopNestInit(Value acc, ArrayRef<scf::ForOp> loops) {
274 while (auto arg = dyn_cast<BlockArgument>(acc)) {
275 auto loop = dyn_cast_if_present<scf::ForOp>(arg.getOwner()->getParentOp());
276 if (!loop || !llvm::is_contained(loops, loop))
277 break;
278 OpOperand *init = loop.getTiedLoopInit(arg);
279 if (!init)
280 break;
281 acc = init->get();
282 }
283 return acc;
284}
285
286// Returns the loop index position to get mapped during the
287// MemRef type clone.
288static unsigned getIndexPosition(Value operand, scf::ForOp loop) {
289 Value iv = loop.getInductionVar();
290
291 Value srcBuff;
293 .Case<TransferReadOp, LoadOp>(
294 [&](auto readOp) { srcBuff = readOp.getOperand(0); });
295
296 auto subview = srcBuff.getDefiningOp<memref::SubViewOp>();
297 if (!subview)
298 return 0;
299
300 auto offsets = subview.getOffsets();
301
302 for (auto it : llvm::enumerate(offsets)) {
303 if (it.value() == iv)
304 return it.index();
305 }
306
307 return 0;
308}
309
310// Creates amx.tile_loads.
311static amx::TileLoadOp createTileLoads(OpBuilder &rewriter, Location loc,
312 Value operand, Value mat, Type ipType,
313 unsigned int offset, bool isVnni) {
314
315 auto srcIndx = getSrcIndxValue(rewriter, loc, operand, false);
316 auto [srcBuff, indices] = *srcIndx;
317 if (isVnni)
318 collapseVnniIndices(rewriter, loc, indices,
319 cast<MemRefType>(srcBuff.getType()).getShape().back());
320
321 amx::TileType tileType = amx::TileType::get({16, (16 * offset)}, ipType);
322 return amx::TileLoadOp::create(rewriter, loc, tileType, mat, indices);
323}
324
325static void performShuffle(OpBuilder &rewriter, Location loc, Value matB,
326 Type ipType, unsigned int offset, Value packedBuffer,
327 Value indxToStoreInBuffer) {
328
329 Value c0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
330 Value c16 = arith::ConstantIndexOp::create(rewriter, loc, 16);
331 SmallVector<Value> subviewOffset(
332 llvm::cast<MemRefType>(matB.getType()).getRank(), c0);
333
334 Value cStep = arith::ConstantIndexOp::create(rewriter, loc, offset);
335 Value cBound = arith::ConstantIndexOp::create(rewriter, loc, (16 * offset));
336 Value offsetIndx =
337 arith::ConstantIndexOp::create(rewriter, loc, (offset / 2));
338
339 scf::ForOp::create(
340 rewriter, loc, c0, cBound, cStep, ValueRange{},
341 [&](OpBuilder &nestedBuilder, Location loc, Value iv,
342 ValueRange iterArgs) {
343 subviewOffset[subviewOffset.size() - 2] = iv;
344
345 // Retrieve two rows of vector (32) for int8 and f8 type. For bf16/f16,
346 // retrieve one row of vector (32).
347 bool is16BitFloat = ipType.isBF16() || ipType.isF16();
348 auto vectorType = VectorType::get({2, (16 * (offset / 2))}, ipType);
349 if (is16BitFloat)
350 vectorType = VectorType::get((16 * offset), ipType);
351
352 int64_t srcRank = (dyn_cast<ShapedType>(matB.getType())).getRank();
353 Value padding = ub::PoisonOp::create(rewriter, loc, ipType);
354 auto map = AffineMap::getMinorIdentityMap(srcRank, vectorType.getRank(),
355 rewriter.getContext());
356 SmallVector<bool> inBounds(vectorType.getRank(), true);
357 Value vec1 = vector::TransferReadOp::create(
358 rewriter, loc, vectorType, matB, ValueRange(subviewOffset), padding,
359 map, inBounds);
360
361 if (!is16BitFloat)
362 vec1 = vector::ShapeCastOp::create(
363 rewriter, loc, VectorType::get((16 * offset), ipType), vec1);
364
365 // Increment the iv by 1 or 2 based on the type to load the next 32/64
366 // elements
367 Value incIV = arith::AddIOp::create(rewriter, loc, offsetIndx, iv);
368 subviewOffset[subviewOffset.size() - 2] = incIV;
369
370 Value vec2 = vector::TransferReadOp::create(
371 rewriter, loc, vectorType, matB, ValueRange(subviewOffset), padding,
372 map, inBounds);
373 if (!is16BitFloat)
374 vec2 = vector::ShapeCastOp::create(
375 rewriter, loc, VectorType::get((16 * offset), ipType), vec2);
376
377 vector::ShuffleOp writeVal1;
378 vector::ShuffleOp writeVal2;
379
380 if (is16BitFloat) {
381
382 writeVal1 = vector::ShuffleOp::create(
383 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
384 vec2,
385 ArrayRef<int64_t>{0, 32, 1, 33, 2, 34, 3, 35, 8, 40, 9,
386 41, 10, 42, 11, 43, 16, 48, 17, 49, 18, 50,
387 19, 51, 24, 56, 25, 57, 26, 58, 27, 59});
388
389 writeVal2 = vector::ShuffleOp::create(
390 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
391 vec2,
392 ArrayRef<int64_t>{4, 36, 5, 37, 6, 38, 7, 39, 12, 44, 13,
393 45, 14, 46, 15, 47, 20, 52, 21, 53, 22, 54,
394 23, 55, 28, 60, 29, 61, 30, 62, 31, 63});
395 }
396
397 if (ipType.isSignlessInteger(8) || ipType.isF8E5M2() ||
398 ipType.isF8E4M3FN()) {
399
400 writeVal1 = vector::ShuffleOp::create(
401 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
402 vec2,
404 0, 32, 64, 96, 1, 33, 65, 97, 2, 34, 66, 98, 3,
405 35, 67, 99, 8, 40, 72, 104, 9, 41, 73, 105, 10, 42,
406 74, 106, 11, 43, 75, 107, 16, 48, 80, 112, 17, 49, 81,
407 113, 18, 50, 82, 114, 19, 51, 83, 115, 24, 56, 88, 120,
408 25, 57, 89, 121, 26, 58, 90, 122, 27, 59, 91, 123});
409
410 writeVal2 = vector::ShuffleOp::create(
411 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
412 vec2,
414 4, 36, 68, 100, 5, 37, 69, 101, 6, 38, 70, 102, 7, 39,
415 71, 103, 12, 44, 76, 108, 13, 45, 77, 109, 14, 46, 78, 110,
416 15, 47, 79, 111, 20, 52, 84, 116, 21, 53, 85, 117, 22, 54,
417 86, 118, 23, 55, 87, 119, 28, 60, 92, 124, 29, 61, 93, 125,
418 30, 62, 94, 126, 31, 63, 95, 127});
419 }
420
421 // iv to store the shuffled elements
422 Value ivShuff1 = arith::DivUIOp::create(rewriter, loc, iv, cStep);
423 Value ivShuff2 = arith::AddIOp::create(rewriter, loc, ivShuff1, c16);
424
425 vector::StoreOp::create(rewriter, loc, writeVal1, packedBuffer,
426 ValueRange{indxToStoreInBuffer, ivShuff1, c0});
427 vector::StoreOp::create(rewriter, loc, writeVal2, packedBuffer,
428 ValueRange{indxToStoreInBuffer, ivShuff2, c0});
429
430 scf::YieldOp::create(nestedBuilder, loc);
431 });
432}
433
435packInputs(OpBuilder &rewriter, Location loc,
437 unsigned int offset, Value packedBuffer, bool pack,
438 Value indxToStoreInBuffer, Value indxToLoadFromMatB) {
439
441 Value c0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
442 Value c16 = arith::ConstantIndexOp::create(rewriter, loc, 16);
443
444 for (size_t j = 0; j < ops.size(); j++) {
445 for (size_t i = 0; i < ops.size(); i++) {
446
447 if (i != j && validatePairVectorContract(ops[j], ops[i], true, 16)) {
448
449 Operation *readOpRhs = ops[j].getRhs().getDefiningOp();
450 auto itRhs = readsToTileLoads.find(readOpRhs);
451 if (itRhs != readsToTileLoads.end()) {
452 continue;
453 }
454
455 if (pack) {
456 performShuffle(rewriter, loc, matB, ipType, offset, packedBuffer,
457 indxToStoreInBuffer);
458 }
459
460 amx::TileType tileType =
461 amx::TileType::get({16, (16 * offset)}, ipType);
462 auto loadRow1 =
463 amx::TileLoadOp::create(rewriter, loc, tileType, packedBuffer,
464 ValueRange{indxToLoadFromMatB, c0, c0});
465
466 auto loadRow2 =
467 amx::TileLoadOp::create(rewriter, loc, tileType, packedBuffer,
468 ValueRange{indxToLoadFromMatB, c16, c0});
469
470 readsToTileLoads.try_emplace(readOpRhs, loadRow1);
471 readsToTileLoads.try_emplace(ops[i].getRhs().getDefiningOp(), loadRow2);
472 }
473 }
474 }
475
476 return readsToTileLoads;
477}
478
479// Creates tiled amx dot-products.
481createTiledDp(OpBuilder &rewriter, Location loc,
483 Type ipType, Type opType, ValueRange accIterArgs,
484 unsigned int offset, bool isVnni, Value packedBuffer, bool pack,
485 Value indxToStoreInBuffer, Value indxToLoadFromMatB) {
486
487 if (isVnni) {
488 matA = collapseInnerDims(rewriter, loc, matA);
489 matB = collapseInnerDims(rewriter, loc, matB);
490 }
491
492 SmallVector<Value> accumulators;
493 // Stores the amx.tile_load operation vs it's equivalent vector tranfer_read
494 // or load operations.
496
497 // function call to online pack the input B matrix
498 if (!isVnni) {
499 readsToTileLoads =
500 packInputs(rewriter, loc, ops, matB, ipType, offset, packedBuffer, pack,
501 indxToStoreInBuffer, indxToLoadFromMatB);
502 }
503
504 // Iterate over the contraction operations and compute the tiled dot-product.
505 for (size_t i = 0; i < ops.size(); i++) {
506
507 Operation *readOpLhs = ops[i].getLhs().getDefiningOp();
508 amx::TileLoadOp tilesLhs;
509 auto itLhs = readsToTileLoads.find(readOpLhs);
510 if (itLhs != readsToTileLoads.end()) {
511 tilesLhs = itLhs->second;
512 } else {
513 tilesLhs = createTileLoads(rewriter, loc, ops[i].getLhs(), matA, ipType,
514 offset, isVnni);
515 readsToTileLoads.try_emplace(readOpLhs, tilesLhs);
516 }
517
518 Operation *readOpRhs = ops[i].getRhs().getDefiningOp();
519 amx::TileLoadOp tilesRhs;
520 auto itRhs = readsToTileLoads.find(readOpRhs);
521 if (itRhs != readsToTileLoads.end()) {
522 tilesRhs = itRhs->second;
523 } else {
524 tilesRhs = createTileLoads(rewriter, loc, ops[i].getRhs(), matB, ipType,
525 offset, isVnni);
526 readsToTileLoads.try_emplace(readOpRhs, tilesRhs);
527 }
528
529 auto accTileType = amx::TileType::get({16, 16}, opType);
530
531 Value dp;
532 if (isa<FloatType>(ipType))
533 dp = amx::TileMulFOp::create(rewriter, loc, accTileType, tilesLhs,
534 tilesRhs, accIterArgs[i]);
535
536 if (ipType.isSignlessInteger(8))
537 dp = amx::TileMulIOp::create(rewriter, loc, accTileType, tilesLhs,
538 tilesRhs, accIterArgs[i]);
539
540 accumulators.push_back(dp);
541 }
542 return accumulators;
543}
544
545static SmallVector<Value> createTileZeros(OpBuilder &rewriter, Location loc,
546 Type opType, scf::ForOp outerLoop,
547 int64_t size) {
548 OpBuilder::InsertionGuard guard(rewriter);
549 rewriter.setInsertionPoint(outerLoop);
550
551 SmallVector<Value> loopItrArgs;
552 auto zeroTileType = amx::TileType::get({16, 16}, opType);
553
554 for (int i = 0; i < size; i++) {
555 auto zeroTile = amx::TileZeroOp::create(rewriter, loc, zeroTileType);
556 loopItrArgs.push_back(zeroTile);
557 }
558 return loopItrArgs;
559}
560
561// Find memref source and indices of the accumulator tile for an AMX
562// contraction. Returns nullopt if the access is not suitable for AMX tile
563// load/store.
564static std::optional<std::pair<Value, SmallVector<Value>>>
565getAccTileAccess(Operation *op) {
566 if (!op)
567 return std::nullopt;
568
569 Value base;
570 VectorType vecTy;
572 if (auto transfer = dyn_cast<VectorTransferOpInterface>(op)) {
573 if (transfer.getMask() || transfer.hasOutOfBoundsDim() ||
574 !transfer.getPermutationMap().isMinorIdentity())
575 return std::nullopt;
576 base = transfer.getBase();
577 vecTy = transfer.getVectorType();
578 indices = transfer.getIndices();
579 } else if (auto load = dyn_cast<vector::LoadOp>(op)) {
580 base = load.getBase();
581 vecTy = load.getVectorType();
582 indices = load.getIndices();
583 } else if (auto store = dyn_cast<vector::StoreOp>(op)) {
584 base = store.getBase();
585 vecTy = store.getVectorType();
586 indices = store.getIndices();
587 } else {
588 return std::nullopt;
589 }
590
591 auto memrefTy = dyn_cast<MemRefType>(base.getType());
592 ArrayRef<int64_t> shape = vecTy.getShape();
593 if (!memrefTy || memrefTy.getRank() < 2 || !memrefTy.isLastDimUnitStride() ||
594 shape.size() < 2 || shape.end()[-1] != 16 || shape.end()[-2] != 16 ||
595 llvm::any_of(shape.drop_back(2), [](int64_t d) { return d != 1; }))
596 return std::nullopt;
597
598 return std::make_pair(base, SmallVector<Value>(indices));
599}
600
601// Returns the accumulator read and result write for each contraction if the
602// accumulator can be updated in place through direct AMX tile accesses.
603// If writeOnly is true, only the result writes are considered, and the read
604// accesses are ignored.
605static std::pair<std::optional<SmallVector<Operation *>>,
606 std::optional<SmallVector<Operation *>>>
607getInPlaceAccAccesses(ArrayRef<vector::ContractionOp> ops, bool writeOnly) {
608 SmallVector<Operation *> reads, writes;
609 for (vector::ContractionOp op : ops) {
611 if (!result || !result.hasOneUse())
612 return {std::nullopt, std::nullopt};
613 Operation *write = *result.user_begin();
614 if (!isa<vector::TransferWriteOp, vector::StoreOp>(write) ||
615 write->getOperand(0) != result || !getAccTileAccess(write))
616 return {std::nullopt, std::nullopt};
617 writes.push_back(write);
618
619 if (writeOnly)
620 continue;
621
623 if (!read || !getAccTileAccess(read))
624 return {std::nullopt, std::nullopt};
625 reads.push_back(read);
626 }
627
628 if (writeOnly)
629 return {std::nullopt, writes};
630 return std::make_pair(reads, writes);
631}
632
633// Loads the initial accumulator tiles before the given loop.
634static SmallVector<Value> createAccTileLoads(OpBuilder &rewriter, Location loc,
635 Type opType, scf::ForOp loop,
636 ArrayRef<Operation *> reads) {
637 OpBuilder::InsertionGuard guard(rewriter);
638 rewriter.setInsertionPoint(loop);
639 auto tileType = amx::TileType::get({16, 16}, opType);
640 SmallVector<Value> tiles;
641 for (Operation *read : reads) {
642 auto [base, indices] = *getAccTileAccess(read);
643 tiles.push_back(
644 amx::TileLoadOp::create(rewriter, loc, tileType, base, indices));
645 }
646 return tiles;
647}
648
649static Value getIndxToLoadStoreFromPckBuffer(OpBuilder &rewriter, Location loc,
650 Value ivInnerLoop,
651 Value ivOuterLoop,
652 bool isInnerLoopUBHasOddQuot,
653 bool isInnerLoopUBLarger,
654 bool pack, Value blockStride) {
655
656 Value c2 = arith::ConstantIndexOp::create(rewriter, loc, 2);
657
658 // `blockStride` is the reduction (K) loop step, i.e. the amount by which the
659 // induction variable advances for one K-block. Dividing the induction value
660 // by it yields the K-block index regardless of whether the loop counts
661 // K-elements (step == 16*blockingFactor) or pre-blocked K-tiles (step == 1).
662 Value quotientInnerLoop =
663 arith::DivUIOp::create(rewriter, loc, ivInnerLoop, blockStride);
664 Value remInnerLoop = arith::RemUIOp::create(
665 rewriter, loc, rewriter.getIndexType(), quotientInnerLoop, c2);
666
667 if (!isInnerLoopUBLarger && !pack) {
668 remInnerLoop = arith::RemUIOp::create(
669 rewriter, loc, rewriter.getIndexType(), ivOuterLoop, c2);
670 }
671
672 if (isInnerLoopUBHasOddQuot) {
673 auto remOuterLoop = arith::RemUIOp::create(
674 rewriter, loc, rewriter.getIndexType(), ivOuterLoop, c2);
675 auto remAdd = arith::AddIOp::create(rewriter, loc, rewriter.getIndexType(),
676 remInnerLoop, remOuterLoop);
677 remInnerLoop = arith::RemUIOp::create(rewriter, loc,
678 rewriter.getIndexType(), remAdd, c2);
679 }
680
681 return remInnerLoop;
682}
683
684static scf::ForOp
685createLoops(OpBuilder &rewriter, Location loc, Value lowerBound,
686 Value upperBound, Value step, SmallVector<Value> loopItrArgs,
687 Type ipType, Type opType, unsigned int blockingFactor, bool isVnni,
688 Operation *vectorOpLhs, Operation *vectorOpRhs,
689 vector::ContractionOp contractOp, scf::ForOp outerLoop,
690 scf::ForOp innerLoop, SmallVector<vector::ContractionOp> ops,
691 Value ivOuterLoop, Value packedBuffer, bool pack,
692 arith::ConstantIndexOp innerLoopIndex, bool isInnerLoopUBLarger,
693 bool isInnerLoopUBHasOddQuot) {
694
695 Value c0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
696 Value c1 = arith::ConstantIndexOp::create(rewriter, loc, 1);
697 Value c2 = arith::ConstantIndexOp::create(rewriter, loc, 2);
698
699 int64_t offset = 16 * blockingFactor;
700 if (auto cst = step.getDefiningOp<arith::ConstantIndexOp>())
701 offset = cst.value();
702
703 auto newLoop = scf::ForOp::create(
704 rewriter, loc, lowerBound, upperBound, step, loopItrArgs,
705 [&](OpBuilder &rewriterNewInnerLoop, Location locNewInnerLoop,
706 Value ivNewInnerLoop, ValueRange iterArgsNewInnerLoop) {
707 IRMapping mapping;
708 if (outerLoop)
709 mapping.map(vectorOpLhs->getOperand(
710 getIndexPosition(contractOp.getLhs(), outerLoop) + 1),
711 ivOuterLoop);
712
713 mapping.map(vectorOpLhs->getOperand(
714 getIndexPosition(contractOp.getLhs(), innerLoop) + 1),
715 ivNewInnerLoop);
716 auto lhsClone = rewriterNewInnerLoop.clone(*vectorOpLhs, mapping);
717
718 Value indxToStoreInBuffer = c0;
719 Value indxToLoadFromBuffer = c0;
720 if (!isVnni) {
721 if (outerLoop) {
722 if (innerLoopIndex.value() == 0) {
723 if (pack) {
724 ivNewInnerLoop = c0;
725 ivOuterLoop = arith::AddIOp::create(rewriter, locNewInnerLoop,
726 c1, ivOuterLoop);
727
728 if (!isInnerLoopUBLarger || isInnerLoopUBHasOddQuot) {
729 indxToStoreInBuffer = arith::RemUIOp::create(
730 rewriter, locNewInnerLoop, rewriter.getIndexType(),
731 ivOuterLoop, c2);
732 }
733
734 Value indxToLoadFromMatB = arith::AddIOp::create(
735 rewriter, loc, indxToStoreInBuffer, c1);
736 indxToLoadFromBuffer = arith::RemUIOp::create(
737 rewriter, loc, rewriter.getIndexType(), indxToLoadFromMatB,
738 c2);
739 }
740
741 } else {
743 rewriter, locNewInnerLoop, offset);
744 ivNewInnerLoop = arith::AddIOp::create(rewriter, locNewInnerLoop,
745 nLoadIndx, ivNewInnerLoop);
746 indxToStoreInBuffer = getIndxToLoadStoreFromPckBuffer(
747 rewriter, loc, ivNewInnerLoop, ivOuterLoop,
748 isInnerLoopUBHasOddQuot, isInnerLoopUBLarger, pack, step);
749 Value indxToLoadFromMatB =
750 arith::AddIOp::create(rewriter, loc, indxToStoreInBuffer, c1);
751 indxToLoadFromBuffer =
752 arith::RemUIOp::create(rewriter, loc, rewriter.getIndexType(),
753 indxToLoadFromMatB, c2);
754 }
755 } else {
756 if (pack) {
758 rewriter, locNewInnerLoop, offset);
759 ivNewInnerLoop = arith::AddIOp::create(rewriter, locNewInnerLoop,
760 nLoadIndx, ivNewInnerLoop);
761 Value quotient_K = arith::DivUIOp::create(
762 rewriter, loc, ivNewInnerLoop, nLoadIndx);
763 indxToStoreInBuffer = arith::RemUIOp::create(
764 rewriter, loc, rewriter.getIndexType(), quotient_K, c2);
765
766 Value indxToLoadFromMatB =
767 arith::AddIOp::create(rewriter, loc, indxToStoreInBuffer, c1);
768 indxToLoadFromBuffer =
769 arith::RemUIOp::create(rewriter, loc, rewriter.getIndexType(),
770 indxToLoadFromMatB, c2);
771 }
772 }
773 }
774 IRMapping rhsMapping;
775
776 Value matB;
777 Operation *rhsOp = vectorOpRhs;
778
779 // Clone for the subview type operations
780 if (rhsOp->getNumOperands() > 0) {
781
782 if (outerLoop) {
783 int64_t outerPos = getIndexPosition(contractOp.getRhs(), outerLoop);
784
785 if (outerPos >= 0) {
786 unsigned operandIdx = static_cast<unsigned>(outerPos + 1);
787
788 if (operandIdx < rhsOp->getNumOperands())
789 rhsMapping.map(rhsOp->getOperand(operandIdx), ivOuterLoop);
790 }
791 }
792
793 int64_t innerPos = getIndexPosition(contractOp.getRhs(), innerLoop);
794
795 if (innerPos >= 0) {
796 unsigned operandIdx = static_cast<unsigned>(innerPos + 1);
797
798 if (operandIdx < rhsOp->getNumOperands())
799 rhsMapping.map(rhsOp->getOperand(operandIdx), ivNewInnerLoop);
800 }
801
802 auto rhsClone = rewriterNewInnerLoop.clone(*rhsOp, rhsMapping);
803 matB = rhsClone->getResult(0);
804
805 } else {
806 // The mat B is of kind 'memref.get_global @__constant'
807 matB = rhsOp->getResult(0);
808 }
809
810 if (!isVnni) {
811 if (outerLoop) {
812 if (!pack) {
813 matB = Value();
814 indxToLoadFromBuffer = c0;
815 // Use the real spill-block induction value (== spillInnerLoop)
816 // together with the loop step so the computed ping-pong slot
817 // matches the prefetch store side for any number of register
818 // blocks, including odd counts (e.g. 96 = 3 blocks). Passing a
819 // constant here mis-parities the slot for odd block counts.
820 indxToLoadFromBuffer = getIndxToLoadStoreFromPckBuffer(
821 rewriter, loc, ivNewInnerLoop, ivOuterLoop,
822 isInnerLoopUBHasOddQuot, isInnerLoopUBLarger, pack, step);
823 }
824 } else {
825 if (!pack) {
827 rewriter, locNewInnerLoop, offset);
828 matB = Value();
829 Value quotient_K = arith::DivUIOp::create(
830 rewriter, loc, ivNewInnerLoop, nLoadIndx);
831 indxToLoadFromBuffer = arith::RemUIOp::create(
832 rewriter, loc, rewriter.getIndexType(), quotient_K, c2);
833 }
834 }
835 }
836 // compute tiled dot-product
837 SmallVector<Value> accumulators = createTiledDp(
838 rewriter, locNewInnerLoop, ops, lhsClone->getResult(0), matB,
839 ipType, opType, iterArgsNewInnerLoop, blockingFactor, isVnni,
840 packedBuffer, pack, indxToStoreInBuffer, indxToLoadFromBuffer);
841
842 scf::YieldOp::create(rewriterNewInnerLoop, locNewInnerLoop,
843 accumulators);
844 });
845
846 return newLoop;
847}
848
849// Implements tiled dot-product operation for a vector.contract operation or a
850// sequence of vector.contracts inside the reduction loops.
851//
852// For example:
853// Case 1: register blocked vector.contract with prepacked input
854// ```
855// vector.transfer_read %arg0 {{.}*} : memref<16x32x4xi8>, vector<16x16x4xi8>
856// vector.transfer_read %arg1 {{.}*} : memref<16x32x4xi8>, vector<16x16x4xi8>
857// vector.contract <16x16x4xi8>, <16x16x4xi8> into <16x16xi32>
858// vector.transfer_write arg2 {{.}*} : vector<16x16xi32>, memref<32x32xi32>
859// ```
860// to
861// ```
862// amx.tile_load %arg0 {{.}*} : memref<16x32x4xi8> into !amx.tile<16x64xi8>
863// amx.tile_load %arg1 {{.}*} : memref<16x32x4xi8> into !amx.tile<16x64xi8>
864// amx.tile_muli !amx.tile<16x64xi8> -> !amx.tile<16x16xi32>
865// amx.tile_store %arg2{{.}*} : memref<32x32xi32>, !amx.tile<16x16xi32>
866// ```
867//
868//
869// Case2: vector.contract with register blocked
870//
871// Output IR with online packing (with s/w pipeline advantage):
872// s/w pipeline: load, pack to VNNI, and store the B sub matrix
873// of the 0th batch-reduce and K iteration.
874// scf.for (0 to 31) {
875// - load 0th and 1st vector<32xbf16>, pack into VNNI, store the
876// first shuffle in 0th and 2nd shuffle in 16th index of the
877// buffer.
878// }
879// scf.for (0 to br-2) { batch-reduce loop
880// scf.for (0 to k-2) { K loop
881// - load A matrix
882// - scf.loop for s/w pipeline: load, pack to VNNI, and store the B sub
883// matrix for the next K loop iteration (c) load VNNI pack B matrix of K
884// iteration from the buffer (d) compute the tiled dot-product
885// }
886// Last iteration of the the K Loop (k-1) {
887// - load A matrix
888// - scf.loop for s/w pipeline: load, pack to VNNI, and store the B sub
889// matrix for the next batch-reduce + K loop iteration (c) load VNNI pack B
890// matrix of K iteration from the buffer (d) compute the tiled dot-product
891// }
892// }
893// Last iteration of the batch-reduce loop (br-1) {
894// scf.for (0 to k-2) { K loop
895// - load A matrix
896// - scf.loop for s/w pipeline: load, pack to VNNI, and store the B sub
897// matrix for the next K loop iteration (c) load VNNI pack B matrix of K
898// iteration from the buffer (d) compute the tiled dot-product
899// }
900// Last iteration of the the K Loop (k-1) {
901// - load A matrix
902// - load VNNI pack B matrix of K iteration from the buffer
903// - compute the tiled dot-product
904// }
905// }
906//
907// scf.for (0 to M)
908// scf.for (0 to N)
909// - Load the ith and i+1th acc
910// - Shuffle them as we packed using vpunpack
911// - Load C matrix and do arith.add with the shuffle
912// - Store back into C matrix
913struct VectorContractToAMXDotProduct : public AddContractionOpRewritePattern {
914 using Base::Base;
915
916 LogicalResult
917 matchAndRewriteAddContractOp(vector::ContractionOp contractOp,
918 PatternRewriter &rewriter) const override {
919
920 Type lhsElemTy = contractOp.getLhsType().getElementType();
921 unsigned int blockingFactor =
922 (lhsElemTy.isBF16() || lhsElemTy.isF16()) ? 2 : 4;
923 bool isVnni =
924 isInVnniLayout(contractOp.getOperation(),
925 contractOp.getIndexingMapsArray(), blockingFactor);
926
927 VectorType lhsTy = contractOp.getLhsType();
928 if (!lhsTy.getElementType().isBF16() && !lhsTy.getElementType().isF16() &&
929 !lhsTy.getElementType().isSignlessInteger(8) &&
930 !lhsTy.getElementType().isF8E4M3FN() &&
931 !lhsTy.getElementType().isF8E5M2())
932 return rewriter.notifyMatchFailure(
933 contractOp, "Only BF16/F16/Int8/F8 lowering is supported.");
934
935 if (lhsTy.getElementType() != contractOp.getRhsType().getElementType())
936 return rewriter.notifyMatchFailure(
937 contractOp, "Contraction should have same lhs and rhs type.");
938
939 VectorType accTy = dyn_cast<VectorType>(contractOp.getAccType());
940 if (!accTy)
941 return rewriter.notifyMatchFailure(contractOp, "Wrong accmulator type.");
942
943 if (((lhsTy.getElementType().isBF16() || lhsTy.getElementType().isF16() ||
944 lhsTy.getElementType().isF8E4M3FN() ||
945 lhsTy.getElementType().isF8E5M2()) &&
946 !accTy.getElementType().isF32()) ||
947 (lhsTy.getElementType().isSignlessInteger(8) &&
948 !accTy.getElementType().isSignlessInteger(32)))
949 return rewriter.notifyMatchFailure(
950 contractOp, "Only F32 for BF16/F16/F8 or Int32 for Int8 "
951 "accumulation type is supported.");
952
953 Operation *accReadOp =
954 traceToVectorReadLikeParentOperation(contractOp.getAcc());
955
956 // Only the contract result's first consumer is needed, not the final
957 // store. This keeps the lowering independent of the epilogue ops (truncf,
958 // bias add, ReLU, ...) that sit between the contraction and the write.
959 Value resultChainEnd = contractionUsersAfterYield(contractOp.getResult());
960
961 if (!accReadOp || !resultChainEnd)
962 return rewriter.notifyMatchFailure(
963 contractOp, "The ACC operand of the vector.contract should be a "
964 "transfer_read or a load. And, the result should have a "
965 "single-use chain to its consumer.");
966
967 bool isAccZeroVectorConstant = isZeroVectorConstant(accReadOp);
968
969 Block *resultBlock = resultChainEnd.user_begin()->getBlock();
970
971 Type ipType = rewriter.getBF16Type();
972 if (lhsTy.getElementType().isSignlessInteger(8))
973 ipType = rewriter.getIntegerType(8);
974
975 if (lhsTy.getElementType().isF16())
976 ipType = rewriter.getF16Type();
977
978 if (lhsTy.getElementType().isF8E4M3FN())
979 ipType = rewriter.getF8E4M3FNType();
980
981 if (lhsTy.getElementType().isF8E5M2())
982 ipType = rewriter.getF8E5M2Type();
983
984 Type opType = isa<FloatType>(ipType) ? Type(rewriter.getF32Type())
985 : Type(rewriter.getIntegerType(32));
986
987 if (accReadOp->getBlock() == contractOp->getBlock() &&
988 resultBlock != contractOp->getBlock())
989 return rewriter.notifyMatchFailure(
990 contractOp, "The accumulator store is in different block.");
991
992 if (accReadOp->getBlock() != contractOp->getBlock() &&
993 resultBlock == contractOp->getBlock())
994 return rewriter.notifyMatchFailure(
995 contractOp, "The accumulator read is in different block.");
996
997 if (!(isReadSrcMemref(contractOp.getLhs()) &&
998 isReadSrcMemref(contractOp.getRhs())))
999 return rewriter.notifyMatchFailure(
1000 contractOp, "The LHS or RHS src is not a MemRef type.");
1001
1002 if (isVnni && !(isVnniOperandRead(contractOp.getLhs(), blockingFactor) &&
1003 isVnniOperandRead(contractOp.getRhs(), blockingFactor)))
1004 return rewriter.notifyMatchFailure(
1005 contractOp, "The LHS or RHS src does not read whole VNNI groups.");
1006
1007 unsigned int dimValue = blockingFactor;
1008 if (!isVnni)
1009 dimValue = 16 * blockingFactor;
1010
1011 // Case 1: For just one VC rewrite. Where all accumulator read/write
1012 // within the same block.
1013 if (accReadOp->getBlock() == contractOp->getBlock() &&
1014 resultBlock == contractOp->getBlock()) {
1015
1016 if (!isReadSrcMemref(contractOp.getAcc()))
1017 return rewriter.notifyMatchFailure(contractOp,
1018 "The ACC src is not a MemRef type.");
1019
1020 if (hasMaskedOrOutOfBoundsRead(
1021 {contractOp.getLhs(), contractOp.getRhs(), contractOp.getAcc()}))
1022 return rewriter.notifyMatchFailure(
1023 contractOp, "The reads should be unmasked and in bounds.");
1024
1025 bool collapse = false;
1026 if (isVnni)
1027 collapse = true;
1028
1029 LogicalResult validate = validateContractOps(
1030 rewriter, contractOp, dimValue, Value(), Value(), false);
1031
1032 if (failed(validate))
1033 return rewriter.notifyMatchFailure(
1034 contractOp, "The contract operation doesn't satisfy the operands "
1035 "dimensions. M, N, and vnni dims are 16, 16, and 2/4. "
1036 "The rest dims should be 1. Op should have one user.");
1037
1038 Location loc = contractOp.getLoc();
1039
1040 auto srcIndxLhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1041 contractOp.getLhs(), collapse);
1042 if (failed(srcIndxLhs))
1043 return rewriter.notifyMatchFailure(contractOp,
1044 "Failed to get the LHS src.");
1045 auto [srcBuffLhs, indicesLhs] = *srcIndxLhs;
1046
1047 auto srcIndxRhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1048 contractOp.getRhs(), collapse);
1049 if (failed(srcIndxRhs))
1050 return rewriter.notifyMatchFailure(contractOp,
1051 "Failed to get the RHS src.");
1052 auto rhsSrc = *srcIndxRhs;
1053 auto srcBuffRhs = rhsSrc.first;
1054 auto indicesRhs = rhsSrc.second;
1055
1056 auto srcIndxAcc = getSrcIndxValue(rewriter, contractOp.getLoc(),
1057 contractOp.getAcc(), false);
1058 if (failed(srcIndxAcc))
1059 return rewriter.notifyMatchFailure(contractOp,
1060 "Failed to get the ACC src.");
1061 auto [srcBuffAcc, indicesAcc] = *srcIndxAcc;
1062
1063 Value c0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
1064
1065 // amx.tile_loads
1066 auto tileType = amx::TileType::get({16, (16 * blockingFactor)}, ipType);
1067 auto loadLhs = amx::TileLoadOp::create(rewriter, loc, tileType,
1068 srcBuffLhs, indicesLhs);
1069
1070 // Create the subview and then load.
1071 amx::TileLoadOp loadRhs;
1072 if (!isVnni) {
1073 VectorType vecTy;
1074 SmallVector<OpFoldResult> indexVals;
1075 llvm::TypeSwitch<Operation *>(contractOp.getRhs().getDefiningOp())
1076 .Case<TransferReadOp, LoadOp>([&](auto readOp) {
1077 indexVals = SmallVector<OpFoldResult>(readOp.getIndices().begin(),
1078 readOp.getIndices().end());
1079 vecTy = readOp.getType();
1080 });
1081 auto one = rewriter.getIndexAttr(1);
1082 SmallVector<OpFoldResult> strides(indexVals.size(), one);
1083 // A rank-reducing read drops leading unit dims. Append them back for
1084 // the subview.
1085 SmallVector<int64_t> subviewShape(indexVals.size() - vecTy.getRank(),
1086 1);
1087 llvm::append_range(subviewShape, vecTy.getShape());
1088 SmallVector<OpFoldResult> sizes =
1089 getAsIndexOpFoldResult(contractOp->getContext(), subviewShape);
1090 auto subview = memref::SubViewOp::create(rewriter, loc, srcBuffRhs,
1091 indexVals, sizes, strides);
1092 auto bufferType = MemRefType::get({16, (16 * blockingFactor)}, ipType);
1093 auto packedBuffer = memref::AllocaOp::create(rewriter, loc, bufferType);
1094
1095 // Create a loop that does online packing.
1096 Value step =
1097 arith::ConstantIndexOp::create(rewriter, loc, blockingFactor);
1098 Value uBound = arith::ConstantIndexOp::create(rewriter, loc,
1099 (blockingFactor * 16));
1100 Value nextLoadIndx =
1101 arith::ConstantIndexOp::create(rewriter, loc, (blockingFactor / 2));
1102 Value nextStoreIndx = arith::ConstantIndexOp::create(
1103 rewriter, loc, 16 * (blockingFactor / 2));
1104
1105 scf::ForOp::create(
1106 rewriter, loc, c0, uBound, step, ValueRange{},
1107 [&](OpBuilder &nestedBuilder, Location loc, Value iv,
1108 ValueRange iterArgs) {
1109 Value i1_load =
1110 arith::AddIOp::create(rewriter, loc, nextLoadIndx, iv);
1111
1112 // The source subview already accounts for the leading unit
1113 // dimensions.
1114 size_t numOffsets = indicesRhs.size();
1115 SmallVector<Value> indices(numOffsets, c0);
1116 indices[numOffsets - 2] = iv;
1117 auto vec1 = vector::LoadOp::create(
1118 rewriter, loc,
1119 VectorType::get(16 * (blockingFactor / 2), ipType), subview,
1120 indices);
1121
1122 indices[numOffsets - 2] = i1_load;
1123 auto vec2 = vector::LoadOp::create(
1124 rewriter, loc,
1125 VectorType::get(16 * (blockingFactor / 2), ipType), subview,
1126 indices);
1127
1128 vector::ShuffleOp writeVal1;
1129 vector::ShuffleOp writeVal2;
1130
1131 if (blockingFactor == 2) {
1132
1133 writeVal1 = vector::ShuffleOp::create(
1134 rewriter, loc, VectorType::get({16}, ipType), vec1, vec2,
1135 ArrayRef<int64_t>{0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21,
1136 6, 22, 7, 23});
1137
1138 writeVal2 = vector::ShuffleOp::create(
1139 rewriter, loc, VectorType::get({16}, ipType), vec1, vec2,
1140 ArrayRef<int64_t>{8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13,
1141 29, 14, 30, 15, 31});
1142 }
1143
1144 if (blockingFactor == 4) {
1145 writeVal1 = vector::ShuffleOp::create(
1146 rewriter, loc, VectorType::get({32}, ipType), vec1, vec2,
1147 ArrayRef<int64_t>{0, 16, 32, 48, 1, 17, 33, 49,
1148 2, 18, 34, 50, 3, 19, 35, 51,
1149 4, 20, 36, 52, 5, 21, 37, 53,
1150 6, 22, 38, 54, 7, 23, 39, 55});
1151
1152 writeVal2 = vector::ShuffleOp::create(
1153 rewriter, loc, VectorType::get({32}, ipType), vec1, vec2,
1154 ArrayRef<int64_t>{8, 24, 40, 56, 9, 25, 41, 57,
1155 10, 26, 42, 58, 11, 27, 43, 59,
1156 12, 28, 44, 60, 13, 29, 45, 61,
1157 14, 30, 46, 62, 15, 31, 47, 63});
1158 }
1159
1160 auto rem = arith::DivUIOp::create(
1161 rewriter, loc, rewriter.getIndexType(), iv, step);
1162
1163 vector::StoreOp::create(rewriter, loc, writeVal1, packedBuffer,
1164 ValueRange{rem, c0});
1165 vector::StoreOp::create(rewriter, loc, writeVal2, packedBuffer,
1166 ValueRange{rem, nextStoreIndx});
1167
1168 scf::YieldOp::create(nestedBuilder, loc);
1169 });
1170 loadRhs = amx::TileLoadOp::create(rewriter, loc, tileType, packedBuffer,
1171 ValueRange{c0, c0});
1172 } else {
1173
1174 loadRhs = amx::TileLoadOp::create(rewriter, loc, tileType, srcBuffRhs,
1175 indicesRhs);
1176 }
1177
1178 auto tileTypeAcc = amx::TileType::get({16, 16}, opType);
1179 auto loadAcc = amx::TileLoadOp::create(rewriter, loc, tileTypeAcc,
1180 srcBuffAcc, indicesAcc);
1181
1182 // Tiled dot-product.
1183 Value dp;
1184 if (isa<FloatType>(ipType))
1185 dp = amx::TileMulFOp::create(rewriter, loc, tileTypeAcc, loadLhs,
1186 loadRhs, loadAcc);
1187
1188 if (ipType.isSignlessInteger(8))
1189 dp = amx::TileMulIOp::create(rewriter, loc, tileTypeAcc, loadLhs,
1190 loadRhs, loadAcc);
1191
1192 auto bufferType = MemRefType::get({16, 16}, opType);
1193 auto resultBuffer = memref::AllocaOp::create(rewriter, loc, bufferType);
1194
1195 amx::TileStoreOp::create(rewriter, loc, resultBuffer, ValueRange{c0, c0},
1196 dp);
1197
1198 auto vectorType = VectorType::get({16, 16}, opType);
1199 int64_t srcRank =
1200 (dyn_cast<ShapedType>(resultBuffer.getType())).getRank();
1201 Value padding = ub::PoisonOp::create(rewriter, loc, opType);
1202 auto map = AffineMap::getMinorIdentityMap(srcRank, vectorType.getRank(),
1203 rewriter.getContext());
1204 SmallVector<bool> inBounds(vectorType.getRank(), true);
1205
1206 Value vecRow = vector::TransferReadOp::create(
1207 rewriter, loc, vectorType, resultBuffer, ValueRange{c0, c0}, padding,
1208 map, inBounds);
1209
1210 Value resultOp = contractionUsersAfterYield(contractOp.getResult());
1211 if (auto vecType = dyn_cast<VectorType>(resultOp.getType()))
1212 vecRow = vector::ShapeCastOp::create(rewriter, loc, vecType, vecRow);
1213
1214 rewriter.replaceAllUsesWith(resultOp, vecRow);
1215 return success();
1216 }
1217
1218 // Case 2: The acc are passed as iter args through the reduction loop.
1219 // We support, reduction loop depth until 2. TODO: Support for n-depth
1220 // reduction loop.
1221 // TODOs: Re-factor 2a and 2b.
1222 SmallVector<scf::ForOp> loopLists;
1223 Operation *current = contractOp;
1224 while (true) {
1225 Operation *parent = current->getParentOfType<scf::ForOp>();
1226
1227 if (!parent) {
1228 // The accumulator initialization can be hoisted above an enclosing
1229 // parallel region (scf.parallel/scf.forall) when the register tile
1230 // matches the problem size and the M/N register loops fold away. In
1231 // that case the reduction loop(s) collected so far are still valid to
1232 // rewrite, so stop climbing instead of bailing out.
1233 if (!loopLists.empty())
1234 break;
1235 return rewriter.notifyMatchFailure(
1236 contractOp,
1237 "Accumulator read and contract op not within scf.for op");
1238 }
1239
1240 loopLists.push_back(dyn_cast<scf::ForOp>(parent));
1241
1242 if (resultBlock == parent->getBlock()) {
1243 break;
1244 }
1245
1246 current = parent;
1247 }
1248
1249 if (loopLists.size() > 2 || loopLists.size() == 0)
1250 return rewriter.notifyMatchFailure(
1251 contractOp, "Rewrite is supported until reduction loop depth of 2.");
1252
1253 auto srcIndxLhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1254 contractOp.getLhs(), false);
1255 if (failed(srcIndxLhs))
1256 return rewriter.notifyMatchFailure(contractOp,
1257 "Failed to get the LHS src.");
1258 auto [srcBuffLhs, indicesLhs] = *srcIndxLhs;
1259
1260 auto srcIndxRhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1261 contractOp.getRhs(), false);
1262 if (failed(srcIndxRhs))
1263 return rewriter.notifyMatchFailure(contractOp,
1264 "Failed to get the RHS src.");
1265 auto [srcBuffRhs, indicesRhs] = *srcIndxRhs;
1266 Operation *vectorOpLhs;
1267 llvm::TypeSwitch<Operation *>(contractOp.getLhs().getDefiningOp())
1268 .Case<TransferReadOp, LoadOp>([&](auto readOp) {
1269 vectorOpLhs = readOp.getBase().getDefiningOp();
1270 });
1271
1272 Operation *vectorOpRhs;
1273 llvm::TypeSwitch<Operation *>(contractOp.getRhs().getDefiningOp())
1274 .Case<TransferReadOp, LoadOp>([&](auto readOp) {
1275 vectorOpRhs = readOp.getBase().getDefiningOp();
1276 });
1277
1278 if (!vectorOpLhs || !vectorOpRhs)
1279 return rewriter.notifyMatchFailure(
1280 contractOp, "Failed to find LHS or RHS read source operation");
1281
1282 // Retrive all the contaction operation within the loop.
1283 SmallVector<vector::ContractionOp> ops;
1284 // Accumulators whose initial value passed into the rewritten reduction
1285 // loops is neither read from memory nor zero, e.g. an iter_arg of an
1286 // enclosing loop. Paired with the index of their contraction in `ops`.
1287 SmallVector<std::pair<size_t, Value>> carriedAccs;
1288 for (Operation &op : loopLists[0].getBody()->getOperations()) {
1289
1290 if (auto contract = dyn_cast<vector::ContractionOp>(op)) {
1291 if (isVnni && !(isVnniOperandRead(contract.getLhs(), blockingFactor) &&
1292 isVnniOperandRead(contract.getRhs(), blockingFactor)))
1293 return rewriter.notifyMatchFailure(
1294 contractOp, "The LHS or RHS src of an associated contract "
1295 "operation does not read whole VNNI groups.");
1296
1297 LogicalResult validate = validateContractOps(
1298 rewriter, contract, dimValue, srcBuffLhs, srcBuffRhs, true);
1299
1300 if (failed(validate))
1301 return rewriter.notifyMatchFailure(
1302 contractOp,
1303 "The associated contract operations doesn't satisfy "
1304 "the re-write conditions either the dimensions are "
1305 "wrong or MemRef source are different or many users.");
1306
1307 Operation *contractReadOp =
1309
1310 if (isAccZeroVectorConstant != isZeroVectorConstant(contractReadOp))
1311 return rewriter.notifyMatchFailure(
1312 contractOp, "The input acc should be a zero constant or "
1313 "transfer_read for all contracts");
1314
1315 Value accInit = getLoopNestInit(contract.getAcc(), loopLists);
1316 if (hasMaskedOrOutOfBoundsRead(
1317 {contract.getLhs(), contract.getRhs(), accInit}))
1318 return rewriter.notifyMatchFailure(
1319 contractOp, "The reads of an associated contract operation "
1320 "should be unmasked and in bounds.");
1321 Operation *accInitOp = accInit.getDefiningOp();
1322 bool carried = !isa_and_present<TransferReadOp, LoadOp>(accInitOp) &&
1323 !isZeroVectorConstant(accInitOp);
1324 if (carried) {
1325 if (loopLists.back().getRegion().isAncestor(
1326 accInit.getParentRegion()))
1327 return rewriter.notifyMatchFailure(
1328 contractOp, "The accumulator should enter the reduction loops "
1329 "through their init args.");
1330 carriedAccs.emplace_back(ops.size(), accInit);
1331 }
1332
1333 ops.push_back(contract);
1334 }
1335 }
1336
1337 // The accumulators read from memory are added back to all the results at
1338 // once, so they can't be mixed with carried ones.
1339 if (!isAccZeroVectorConstant && !carriedAccs.empty() &&
1340 carriedAccs.size() != ops.size())
1341 return rewriter.notifyMatchFailure(
1342 contractOp, "The accumulators read from memory can't be mixed with "
1343 "carried in accumulators.");
1344
1345 if (!isVnni) {
1346 unsigned int pairCount = 0;
1347 for (size_t j = 0; j < ops.size(); j++) {
1348 for (size_t i = j; i < ops.size(); i++) {
1349 if (i != j && validatePairVectorContract(ops[j], ops[i], true, 16))
1350 pairCount = pairCount + 2;
1351 }
1352 }
1353
1354 if (pairCount != ops.size())
1355 return rewriter.notifyMatchFailure(
1356 contractOp, "Coudn't find the pair vector contract ");
1357 }
1358
1359 scf::ForOp innerLoop;
1360 scf::ForOp outerLoop;
1361
1362 // For VNNI layout, accumulator tiles stay in their original layout.
1363 // Load and store them back in place when possible.
1364 // Otherwise, start from zero tile and accumulate only the final result.
1365 std::optional<SmallVector<Operation *>> inPlaceAccReads, inPlaceAccWrites;
1366 if (isVnni)
1367 std::tie(inPlaceAccReads, inPlaceAccWrites) =
1368 getInPlaceAccAccesses(ops, /*writeOnly=*/isAccZeroVectorConstant);
1369 auto createInitTiles = [&](scf::ForOp loop) {
1370 if (inPlaceAccReads)
1371 return createAccTileLoads(rewriter, loop.getLoc(), opType, loop,
1372 *inPlaceAccReads);
1373 return createTileZeros(rewriter, loop.getLoc(), opType, loop, ops.size());
1374 };
1375
1376 scf::ForOp newLoop;
1377 // Case 2a: Reduction loop depth is 2.
1378 if (loopLists.size() == 2) {
1379 outerLoop = loopLists[1];
1380 innerLoop = loopLists[0];
1381
1382 LogicalResult validateOuterLoopStep =
1383 validateLoopStep(rewriter, outerLoop.getStep(), 1);
1384 if (failed(validateOuterLoopStep))
1385 return rewriter.notifyMatchFailure(contractOp, "Invalid loop step.");
1386
1387 int64_t stepValue = 16;
1388 if (!isVnni)
1389 stepValue = stepValue * blockingFactor;
1390 LogicalResult validateInnerLoopStep =
1391 validateLoopStep(rewriter, innerLoop.getStep(), stepValue);
1392 if (failed(validateInnerLoopStep))
1393 return rewriter.notifyMatchFailure(
1394 contractOp,
1395 "Invalid loop step. The step should be 32 for BF16/F16 and "
1396 "64 for Int8/F8.");
1397
1398 SmallVector<Value> loopItrArgs = createInitTiles(outerLoop);
1399 rewriter.setInsertionPoint(outerLoop);
1400
1401 if (isVnni) {
1402 newLoop = scf::ForOp::create(
1403 rewriter, outerLoop.getLoc(), outerLoop.getLowerBound(),
1404 outerLoop.getUpperBound(), outerLoop.getStep(), loopItrArgs,
1405 [&](OpBuilder &rewriterOuterLoop, Location locOuterLoop,
1406 Value ivOuterLoop, ValueRange iterArgsOuterLoop) {
1407 auto newInnerLoop = createLoops(
1408 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1409 innerLoop.getUpperBound(), innerLoop.getStep(),
1410 iterArgsOuterLoop, ipType, opType, blockingFactor, isVnni,
1411 vectorOpLhs, vectorOpRhs, contractOp, outerLoop, innerLoop,
1412 ops, ivOuterLoop, nullptr, true, nullptr, false, false);
1413
1414 scf::YieldOp::create(rewriterOuterLoop, locOuterLoop,
1415 newInnerLoop.getResults());
1416 });
1417
1418 } else {
1419
1420 bool isInnerLoopUBLarger = false;
1421 bool isInnerLoopUBHasOddQuot = false;
1422
1423 int64_t ubVal = 16 * blockingFactor;
1424 Value ub = innerLoop.getUpperBound();
1425 if (auto constOp = ub.getDefiningOp<arith::ConstantOp>()) {
1426 if (auto intAttr = dyn_cast<IntegerAttr>(constOp.getValue())) {
1427 ubVal = intAttr.getInt();
1428 }
1429 }
1430
1431 isInnerLoopUBLarger = ubVal > 16 * blockingFactor;
1432 isInnerLoopUBHasOddQuot =
1433 (((ubVal / (16 * blockingFactor)) % 2) == 1) && isInnerLoopUBLarger;
1434
1435 rewriter.setInsertionPoint(outerLoop);
1436
1437 auto c0 =
1438 arith::ConstantIndexOp::create(rewriter, outerLoop.getLoc(), 0);
1439 auto c1 =
1440 arith::ConstantIndexOp::create(rewriter, outerLoop.getLoc(), 1);
1441 auto spillLoopBound = arith::ConstantIndexOp::create(
1442 rewriter, outerLoop.getLoc(), 16 * blockingFactor);
1443
1444 Value spillOuterLoop = arith::SubIOp::create(
1445 rewriter, outerLoop.getLoc(), outerLoop.getUpperBound(), c1);
1446 Value spillInnerLoop =
1447 arith::SubIOp::create(rewriter, innerLoop.getLoc(),
1448 innerLoop.getUpperBound(), spillLoopBound);
1449 auto bufferType =
1450 MemRefType::get({2, 32, (blockingFactor * 16)}, ipType);
1451 auto packedBuffer =
1452 memref::AllocaOp::create(rewriter, outerLoop.getLoc(), bufferType);
1453
1454 // First Shuffling outside the reduction loops
1455 IRMapping rhsMapping;
1456 rhsMapping.map(
1457 vectorOpRhs->getOperand(
1458 getIndexPosition(contractOp.getRhs(), outerLoop) + 1),
1459 outerLoop.getLowerBound());
1460 rhsMapping.map(
1461 vectorOpRhs->getOperand(
1462 getIndexPosition(contractOp.getRhs(), innerLoop) + 1),
1463 innerLoop.getLowerBound());
1464 auto rhsClone = rewriter.clone(*vectorOpRhs, rhsMapping);
1465
1466 Value quotient_batch = arith::DivUIOp::create(
1467 rewriter, outerLoop.getLoc(), outerLoop.getLowerBound(),
1468 outerLoop.getStep());
1469 Value quotient_k = arith::DivUIOp::create(rewriter, outerLoop.getLoc(),
1470 innerLoop.getLowerBound(),
1471 innerLoop.getStep());
1472
1473 Value quotient_add = arith::AddIOp::create(rewriter, outerLoop.getLoc(),
1474 quotient_batch, quotient_k);
1475 Value c2 =
1476 arith::ConstantIndexOp::create(rewriter, outerLoop.getLoc(), 2);
1477 Value rem = arith::RemUIOp::create(rewriter, outerLoop.getLoc(),
1478 quotient_add, c2);
1479
1480 performShuffle(rewriter, outerLoop.getLoc(), rhsClone->getResult(0),
1481 ipType, blockingFactor, packedBuffer, rem);
1482
1483 // First Set of Loops
1484 auto newLoopNonSpill = scf::ForOp::create(
1485 rewriter, outerLoop.getLoc(), outerLoop.getLowerBound(),
1486 spillOuterLoop, outerLoop.getStep(), loopItrArgs,
1487 [&](OpBuilder &rewriterOuterLoop, Location locOuterLoop,
1488 Value ivOuterLoop, ValueRange iterArgsOuterLoop) {
1489 auto newInnerLoop1 = createLoops(
1490 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1491 spillInnerLoop, innerLoop.getStep(), iterArgsOuterLoop,
1492 ipType, opType, blockingFactor, isVnni, vectorOpLhs,
1493 vectorOpRhs, contractOp, outerLoop, innerLoop, ops,
1494 ivOuterLoop, packedBuffer, true, spillLoopBound,
1495 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1496
1497 auto newInnerLoop = createLoops(
1498 rewriter, innerLoop.getLoc(), spillInnerLoop,
1499 innerLoop.getUpperBound(), innerLoop.getStep(),
1500 newInnerLoop1.getResults(), ipType, opType, blockingFactor,
1501 isVnni, vectorOpLhs, vectorOpRhs, contractOp, outerLoop,
1502 innerLoop, ops, ivOuterLoop, packedBuffer, true, c0,
1503 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1504
1505 scf::YieldOp::create(rewriterOuterLoop, locOuterLoop,
1506 newInnerLoop.getResults());
1507 });
1508
1509 // Last set of Loops
1510 newLoop = scf::ForOp::create(
1511 rewriter, outerLoop.getLoc(), spillOuterLoop,
1512 outerLoop.getUpperBound(), outerLoop.getStep(),
1513 newLoopNonSpill.getResults(),
1514 [&](OpBuilder &rewriterOuterLoop, Location locOuterLoop,
1515 Value ivOuterLoop, ValueRange iterArgsOuterLoop) {
1516 auto newInnerLoop1 = createLoops(
1517 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1518 spillInnerLoop, innerLoop.getStep(), iterArgsOuterLoop,
1519 ipType, opType, blockingFactor, isVnni, vectorOpLhs,
1520 vectorOpRhs, contractOp, outerLoop, innerLoop, ops,
1521 ivOuterLoop, packedBuffer, true, spillLoopBound,
1522 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1523
1524 auto newInnerLoop = createLoops(
1525 rewriter, innerLoop.getLoc(), spillInnerLoop,
1526 innerLoop.getUpperBound(), innerLoop.getStep(),
1527 newInnerLoop1.getResults(), ipType, opType, blockingFactor,
1528 isVnni, vectorOpLhs, vectorOpRhs, contractOp, outerLoop,
1529 innerLoop, ops, ivOuterLoop, packedBuffer, false, c0,
1530 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1531
1532 scf::YieldOp::create(rewriterOuterLoop, locOuterLoop,
1533 newInnerLoop.getResults());
1534 });
1535 }
1536 }
1537
1538 // Case 2b: Reduction loop depth is 1.
1539 if (loopLists.size() == 1) {
1540
1541 innerLoop = loopLists[0];
1542 int64_t stepValue = 16;
1543 if (!isVnni)
1544 stepValue = stepValue * blockingFactor;
1545
1546 LogicalResult validateInnerLoopStep =
1547 validateLoopStep(rewriter, innerLoop.getStep(), stepValue);
1548 if (failed(validateInnerLoopStep))
1549 return rewriter.notifyMatchFailure(
1550 contractOp,
1551 "Invalid loop step. The step should be 32 for BF16/F16 and "
1552 "64 for Int8/F8 or 1 if it is rduction loop other than K.");
1553
1554 SmallVector<Value> loopItrArgs = createInitTiles(innerLoop);
1555 rewriter.setInsertionPoint(innerLoop);
1556
1557 if (isVnni) {
1558 newLoop = createLoops(
1559 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1560 innerLoop.getUpperBound(), innerLoop.getStep(), loopItrArgs, ipType,
1561 opType, blockingFactor, isVnni, vectorOpLhs, vectorOpRhs,
1562 contractOp, nullptr, innerLoop, ops, nullptr, nullptr, true,
1563 nullptr, false, false);
1564
1565 } else {
1566
1567 bool isInnerLoopUBLarger = false;
1568 bool isInnerLoopUBHasOddQuot = false;
1569
1570 int64_t ubVal = 16 * blockingFactor;
1571 Value ub = innerLoop.getUpperBound();
1572 if (auto constOp = ub.getDefiningOp<arith::ConstantOp>()) {
1573 if (auto intAttr = dyn_cast<IntegerAttr>(constOp.getValue())) {
1574 ubVal = intAttr.getInt();
1575 }
1576 }
1577
1578 isInnerLoopUBLarger = ubVal > 16 * blockingFactor;
1579 isInnerLoopUBHasOddQuot =
1580 (((ubVal / (16 * blockingFactor)) % 2) == 1) && isInnerLoopUBLarger;
1581
1582 rewriter.setInsertionPoint(innerLoop);
1583
1584 auto c0 =
1585 arith::ConstantIndexOp::create(rewriter, innerLoop.getLoc(), 0);
1586 int64_t offset = 16 * blockingFactor;
1587 if (auto cst =
1588 innerLoop.getStep().getDefiningOp<arith::ConstantIndexOp>())
1589 offset = cst.value();
1590
1591 auto spillLoopBound = arith::ConstantIndexOp::create(
1592 rewriter, innerLoop.getLoc(), offset);
1593 Value spillInnerLoop =
1594 arith::SubIOp::create(rewriter, innerLoop.getLoc(),
1595 innerLoop.getUpperBound(), spillLoopBound);
1596
1597 auto bufferType =
1598 MemRefType::get({2, 32, (blockingFactor * 16)}, ipType);
1599 auto packedBuffer =
1600 memref::AllocaOp::create(rewriter, innerLoop.getLoc(), bufferType);
1601
1602 // First Shuffling outside the reduction loops
1603 IRMapping rhsMapping;
1604 rhsMapping.map(
1605 vectorOpRhs->getOperand(
1606 getIndexPosition(contractOp.getRhs(), innerLoop) + 1),
1607 innerLoop.getLowerBound());
1608 auto rhsClone = rewriter.clone(*vectorOpRhs, rhsMapping);
1609
1610 Value quotient_k = arith::DivUIOp::create(rewriter, innerLoop.getLoc(),
1611 innerLoop.getLowerBound(),
1612 innerLoop.getStep());
1613 Value c2 =
1614 arith::ConstantIndexOp::create(rewriter, innerLoop.getLoc(), 2);
1615 Value rem = arith::RemUIOp::create(rewriter, innerLoop.getLoc(),
1616 quotient_k, c2);
1617
1618 performShuffle(rewriter, innerLoop.getLoc(), rhsClone->getResult(0),
1619 ipType, blockingFactor, packedBuffer, rem);
1620
1621 auto newLoopNonSpill = createLoops(
1622 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1623 spillInnerLoop, innerLoop.getStep(), loopItrArgs, ipType, opType,
1624 blockingFactor, isVnni, vectorOpLhs, vectorOpRhs, contractOp,
1625 nullptr, innerLoop, ops, nullptr, packedBuffer, true,
1626 spillLoopBound, isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1627
1628 newLoop = createLoops(rewriter, innerLoop.getLoc(), spillInnerLoop,
1629 innerLoop.getUpperBound(), innerLoop.getStep(),
1630 newLoopNonSpill.getResults(), ipType, opType,
1631 blockingFactor, isVnni, vectorOpLhs, vectorOpRhs,
1632 contractOp, nullptr, innerLoop, ops, nullptr,
1633 packedBuffer, false, c0, isInnerLoopUBLarger,
1634 isInnerLoopUBHasOddQuot);
1635 }
1636
1637 // This helps the final store back to the acc uses the same code for
1638 // the both reduction loop depth 1 or 2.
1639 outerLoop = innerLoop;
1640 }
1641
1642 // Copy the amx tile accumulation results to a MemRef buffer, add the
1643 // initial accumulation value, and store back to the C-Matrix
1644 Location loc = outerLoop.getLoc();
1645
1646 if (inPlaceAccWrites) {
1647 // The tiles already include the initial accumulator or were
1648 // zero-initialized: store each one where its contraction result was
1649 // written.
1650 for (auto [i, write] : llvm::enumerate(*inPlaceAccWrites)) {
1651 auto [base, indices] = *getAccTileAccess(write);
1652 rewriter.setInsertionPoint(write);
1653 amx::TileStoreOp::create(rewriter, write->getLoc(), base, indices,
1654 newLoop.getResult(i));
1655 rewriter.eraseOp(write);
1656 }
1657 return success();
1658 }
1659
1660 // Carried-in accumulators are added to the results instead.
1661 bool addAccFromMemory = !isAccZeroVectorConstant && carriedAccs.empty();
1662
1663 // Direct tile stores weren't possible, so we need a temporary buffer to
1664 // move tile register contents through memory.
1665 unsigned int M, N;
1666 Value srcBuffAcc;
1667 SmallVector<Value> indicesAcc;
1668
1669 if (addAccFromMemory) {
1670 // We accumulate onto a register tile in memory, hence we let the
1671 // temporary buffer match its shape.
1672 llvm::TypeSwitch<Operation *>(accReadOp).Case<TransferReadOp, LoadOp>(
1673 [&](auto readOp) {
1674 srcBuffAcc = readOp.getOperand(0);
1675
1676 auto indices = readOp.getIndices();
1677 indicesAcc.reserve(indices.size());
1678
1679 llvm::transform(indices, std::back_inserter(indicesAcc),
1680 [&](OpFoldResult ofr) {
1682 rewriter, loc, ofr);
1683 });
1684 });
1685 auto outputShapes = cast<MemRefType>(srcBuffAcc.getType()).getShape();
1686 M = outputShapes[outputShapes.size() - 2];
1687 N = outputShapes[outputShapes.size() - 1];
1688 } else {
1689 // Otherwise we can just pick a suitable shape to hold all result tiles.
1690 // For the VNNI-packed case, we pass the result from each tile register to
1691 // memory individually. For the online packing case, we ensure two tiles
1692 // are neighboring in the N-dimension to facilitate the shuffling.
1693 M = isVnni ? ops.size() * 16 : ops.size() / 2 * 16;
1694 N = isVnni ? 16 : 2 * 16;
1695 }
1696
1697 SmallVector<Value> dps = newLoop.getResults();
1698 auto bufferType = MemRefType::get({M, N}, opType);
1699 auto resultBuffer = memref::AllocaOp::create(rewriter, loc, bufferType);
1700
1701 // Store the amx tiled-dot product output into an MxN memref.
1702 for (unsigned int i = 0, k = 0; i < M; i = i + 16) {
1703 for (unsigned int j = 0; j < N; j = j + 16) {
1704 Value indexOp_i = arith::ConstantIndexOp::create(rewriter, loc, i);
1705 Value indexOp_j = arith::ConstantIndexOp::create(rewriter, loc, j);
1706 amx::TileStoreOp::create(rewriter, loc, resultBuffer,
1707 ValueRange{indexOp_i, indexOp_j}, dps[k]);
1708 k++;
1709 }
1710 }
1711
1712 auto c0 = arith::ConstantIndexOp::create(rewriter, loc, 0);
1713 auto c16 = arith::ConstantIndexOp::create(rewriter, loc, 16);
1714 auto one = arith::ConstantIndexOp::create(rewriter, loc, 1);
1715 auto mBound = arith::ConstantIndexOp::create(rewriter, loc, M);
1716
1717 if (!isVnni || addAccFromMemory) {
1718 // Create a loop that iterates over the MxN memref, retrieves two rows +
1719 // shuffles them, adds up the C element values and stores them to the temp
1720 // buffer.
1721 scf::ForOp::create(
1722 rewriter, loc, c0, mBound, one, ValueRange{},
1723 [&](OpBuilder &nestedBuilder, Location loc, Value iv,
1724 ValueRange iterArgs) {
1725 auto row = vector::LoadOp::create(rewriter, loc,
1726 VectorType::get(16, opType),
1727 resultBuffer, ValueRange{iv, c0});
1728
1729 auto row2 = vector::LoadOp::create(
1730 rewriter, loc, VectorType::get(16, opType), resultBuffer,
1731 ValueRange{iv, c16});
1732
1733 Value writeVal1 = row;
1734 Value writeVal2 = row2;
1735
1736 if (!isVnni) {
1737 writeVal1 = vector::ShuffleOp::create(
1738 rewriter, loc, VectorType::get(16, opType), row, row2,
1739 ArrayRef<int64_t>{0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20,
1740 21, 22, 23});
1741
1742 writeVal2 = vector::ShuffleOp::create(
1743 rewriter, loc, VectorType::get(16, opType), row, row2,
1744 ArrayRef<int64_t>{8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14,
1745 15, 28, 29, 30, 31});
1746 }
1747
1748 if (addAccFromMemory) {
1749 indicesAcc[indicesAcc.size() - 2] = iv;
1750 indicesAcc[indicesAcc.size() - 1] = c0;
1751
1752 Value valueCRow1 = vector::LoadOp::create(
1753 rewriter, loc, VectorType::get(16, opType), srcBuffAcc,
1754 indicesAcc);
1755 indicesAcc[indicesAcc.size() - 1] = c16;
1756
1757 Value valueCRow2 = vector::LoadOp::create(
1758 rewriter, loc, VectorType::get(16, opType), srcBuffAcc,
1759 indicesAcc);
1760
1761 if (isa<FloatType>(ipType)) {
1762 writeVal1 =
1763 arith::AddFOp::create(rewriter, loc, writeVal1, valueCRow1);
1764
1765 writeVal2 =
1766 arith::AddFOp::create(rewriter, loc, writeVal2, valueCRow2);
1767 }
1768
1769 if (ipType.isSignlessInteger(8)) {
1770 writeVal1 =
1771 arith::AddIOp::create(rewriter, loc, writeVal1, valueCRow1);
1772
1773 writeVal2 =
1774 arith::AddIOp::create(rewriter, loc, writeVal2, valueCRow2);
1775 }
1776 }
1777
1778 vector::StoreOp::create(rewriter, loc, writeVal1, resultBuffer,
1779 ValueRange{iv, c0});
1780 vector::StoreOp::create(rewriter, loc, writeVal2, resultBuffer,
1781 ValueRange{iv, c16});
1782
1783 scf::YieldOp::create(nestedBuilder, loc);
1784 });
1785 }
1786
1787 SmallVector<Value> writeResults;
1788 for (unsigned int i = 0; i < M; i = i + 16) {
1789 for (unsigned int j = 0; j < N; j = j + 16) {
1790 Value indexOp_i = arith::ConstantIndexOp::create(rewriter, loc, i);
1791 Value indexOp_j = arith::ConstantIndexOp::create(rewriter, loc, j);
1792
1793 auto vectorType = VectorType::get({16, 16}, opType);
1794
1795 int64_t srcRank =
1796 (dyn_cast<ShapedType>(resultBuffer.getType())).getRank();
1797 Value padding = ub::PoisonOp::create(rewriter, loc, opType);
1798 auto map = AffineMap::getMinorIdentityMap(srcRank, vectorType.getRank(),
1799 rewriter.getContext());
1800 SmallVector<bool> inBounds(vectorType.getRank(), true);
1801
1802 auto vec1 = vector::TransferReadOp::create(
1803 rewriter, loc, vectorType, resultBuffer,
1804 ValueRange{indexOp_i, indexOp_j}, padding, map, inBounds);
1805 writeResults.push_back(vec1);
1806 }
1807 }
1808
1809 for (auto [idx, acc] : carriedAccs) {
1810 Type resultType = writeResults[idx].getType();
1811 if (acc.getType() != resultType)
1812 acc = vector::ShapeCastOp::create(rewriter, loc, resultType, acc);
1813 if (isa<FloatType>(opType))
1814 writeResults[idx] =
1815 arith::AddFOp::create(rewriter, loc, writeResults[idx], acc);
1816 else
1817 writeResults[idx] =
1818 arith::AddIOp::create(rewriter, loc, writeResults[idx], acc);
1819 }
1820
1821 // Replace use of vector.contract with dot-products.
1822 for (size_t i = 0; i < ops.size(); i++) {
1823 vector::ContractionOp contOp = ops[i];
1824 Value vecRow = writeResults[i];
1825
1826 Value resultWriteOp = contractionUsersAfterYield(contOp.getResult());
1827 if (auto vecType = dyn_cast<VectorType>(resultWriteOp.getType()))
1828 vecRow = vector::ShapeCastOp::create(rewriter, loc, vecType,
1829 writeResults[i]);
1830
1831 rewriter.replaceAllUsesWith(resultWriteOp, vecRow);
1832 }
1833
1834 return success();
1835 }
1836};
1837} // namespace
1838
1840 RewritePatternSet &patterns) {
1841 patterns.add<VectorContractToAMXDotProduct>(patterns.getContext());
1842}
return success()
if(!isCopyOut)
auto load
static void contract(RootOrderingGraph &graph, ArrayRef< Value > cycle, const DenseMap< Value, unsigned > &parentDepths, DenseMap< Value, Value > &actualSource, DenseMap< Value, Value > &actualTarget)
Contracts the specified cycle in the given graph in-place.
static Value collapseInnerDims(PatternRewriter &rewriter, mlir::Location loc, Value input, int64_t firstDimToCollapse)
Creates a memref.collapse_shape collapsing all inner dimensions of the input starting at firstDimToCo...
#define rem(a, b)
static AffineMap getMinorIdentityMap(unsigned dims, unsigned results, MLIRContext *context)
Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions.
Attributes are known-constant values of operations.
Definition Attributes.h:25
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
FloatType getF32Type()
Definition Builders.cpp:51
FloatType getF8E5M2Type()
Definition Builders.cpp:43
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
FloatType getF16Type()
Definition Builders.cpp:47
FloatType getBF16Type()
Definition Builders.cpp:45
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
FloatType getF8E4M3FNType()
Definition Builders.cpp:41
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
IRValueT get() const
Return the current value being used by this operand.
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 setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
This class represents a single result from folding an operation.
This class represents an operand of an operation.
Definition Value.h:256
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:231
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
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
unsigned getNumOperands()
Definition Operation.h:373
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
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 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,...
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
bool isF8E5M2() const
Definition Types.cpp:45
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isF8E4M3FN() const
Definition Types.cpp:44
bool isF16() const
Definition Types.cpp:38
bool isBF16() const
Definition Types.cpp:37
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
user_iterator user_begin() const
Definition Value.h:216
unsigned getNumUses() const
This method computes the number of uses of this Value.
Definition Value.cpp:52
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
use_iterator use_begin() const
Definition Value.h:184
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:85
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
mlir::x86::AMXTileType TileType
Definition X86Dialect.h:33
bool isInVnniLayout(Operation *op, llvm::ArrayRef< AffineMap > indexingMaps, std::optional< unsigned > blockingFactor=std::nullopt)
Definition X86Utils.cpp:42
Value contractionUsersAfterYield(Value v)
Definition X86Utils.cpp:149
Operation * traceToVectorReadLikeParentOperation(Value v)
Definition X86Utils.cpp:173
bool validatePairVectorContract(vector::ContractionOp contractOp, vector::ContractionOp pairContOp, bool rhsHasMultipleNonUnitDims, int64_t nonUnitDimValue)
Definition X86Utils.cpp:391
void populateVectorContractToAMXDotProductPatterns(RewritePatternSet &patterns)
Include the generated interface declarations.
OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val)
Convert int64_t to integer attributes of index type and return them as OpFoldResult.
bool isZeroIntegerOrFloat(OpFoldResult v)
Return "true" if v is an integer/float value/attribute with constant value zero.
bool isZeroInteger(OpFoldResult v)
Return "true" if v is an integer value/attribute with constant value 0.
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
SmallVector< int64_t, 2 > ReassociationIndices
Definition Utils.h:27
Convenience wrapper for patterns that are only intended for default contractions, i....
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.