MLIR-AIE 1.4.6.dev
AIEDecomposeLargeDmaBd.cpp
Go to the documentation of this file.
1//===- AIEDecomposeLargeDmaBd.cpp -------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// Decomposes oversized non-contiguous aiex.npu.dma_memcpy_nd ops and task-path
9// aie.dma_bd ops into one or more hardware-legal ND transfers before
10// aie-dma-to-npu / aie-dma-tasks-to-npu lowering.
11//
12//===----------------------------------------------------------------------===//
13
19
20#include "mlir/Dialect/MemRef/IR/MemRef.h"
21#include "mlir/Dialect/SCF/IR/SCF.h"
22#include "mlir/Dialect/Utils/StaticValueUtils.h"
23#include "mlir/IR/PatternMatch.h"
24#include "mlir/Interfaces/SideEffectInterfaces.h"
25#include "mlir/Pass/Pass.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/ADT/SetVector.h"
28#include "llvm/Support/raw_ostream.h"
29
30#include <limits>
31#include <numeric>
32#include <set>
33#include <string>
34
35namespace xilinx::AIEX {
36#define GEN_PASS_DEF_AIEDECOMPOSELARGEDMABD
37#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
38} // namespace xilinx::AIEX
39
40using namespace mlir;
41using namespace xilinx;
42using namespace xilinx::AIEX;
43
44namespace {
45
46// `op`'s pattern, innermost first, when its offsets, sizes and strides are
47// constant.
48static std::optional<NdDmaPattern> constantPattern(NpuDmaMemcpyNdOp op) {
49 std::optional<SmallVector<int64_t>> offsets =
50 getConstantIntValues(op.getMixedOffsets());
51 std::optional<SmallVector<int64_t>> sizes =
52 getConstantIntValues(op.getMixedSizes());
53 std::optional<SmallVector<int64_t>> strides =
54 getConstantIntValues(op.getMixedStrides());
55 if (!offsets || !sizes || !strides)
56 return std::nullopt;
57 NdDmaPattern pattern;
58 pattern.offsets.assign(offsets->rbegin(), offsets->rend());
59 pattern.sizes.assign(sizes->rbegin(), sizes->rend());
60 pattern.strides.assign(strides->rbegin(), strides->rend());
61 return pattern;
62}
63
64static SmallVector<int64_t, 4> toOuter(ArrayRef<int64_t> inner) {
65 return llvm::map_to_vector(llvm::reverse(inner), [](int64_t v) { return v; });
66}
67
68static int64_t flatOffsetFromPattern(int64_t baseFlatOffset,
69 const NdDmaPattern &pattern) {
70 int64_t flat = baseFlatOffset + pattern.baseOffset;
71 for (unsigned k = 0; k < 4; ++k)
72 flat += pattern.offsets[k] * pattern.strides[k];
73 return flat;
74}
75
76static int64_t lenFromInnermost3(ArrayRef<int64_t> sizesInnermostFirst) {
77 int64_t len = 1;
78 for (unsigned i = 0; i < 3; ++i)
79 len *= sizesInnermostFirst[i];
80 return len;
81}
82
83static AIE::BDDimLayoutArrayAttr outerDimsAttr(MLIRContext *ctx,
84 ArrayRef<int64_t> outerSizes,
85 ArrayRef<int64_t> outerStrides) {
86 SmallVector<AIE::BDDimLayoutAttr> dims;
87 dims.reserve(outerSizes.size());
88 for (auto [s, t] : llvm::zip(outerSizes, outerStrides))
89 dims.push_back(AIE::BDDimLayoutAttr::get(ctx, static_cast<uint32_t>(s),
90 static_cast<uint32_t>(t)));
91 return AIE::BDDimLayoutArrayAttr::get(ctx, dims);
92}
93
94static void updateTaskBdInPlace(AIE::DMABDOp bd, int32_t offset, int32_t len,
95 ArrayRef<int64_t> outerSizes,
96 ArrayRef<int64_t> outerStrides) {
97 bd.getOffsetMutable().clear();
98 bd.setStaticOffset(offset);
99 bd.getLenMutable().clear();
100 bd.setStaticLen(len);
101 bd.getSizesMutable().clear();
102 bd.getStridesMutable().clear();
103 bd.setStaticSizes(DenseI64ArrayAttr::get(bd.getContext(), outerSizes));
104 bd.setStaticStrides(DenseI64ArrayAttr::get(bd.getContext(), outerStrides));
105}
106
107static AIE::DMABDOp createTaskBd(RewriterBase &rewriter, Location loc,
108 AIE::DMABDOp tmpl, int32_t offset, int32_t len,
109 ArrayRef<int64_t> outerSizes,
110 ArrayRef<int64_t> outerStrides) {
111 auto dims = outerDimsAttr(rewriter.getContext(), outerSizes, outerStrides);
112 auto bd =
113 AIE::DMABDOp::create(rewriter, loc, tmpl.getBuffer(), offset, len, dims);
114 if (tmpl.getPacketAttr())
115 bd.setPacketAttr(tmpl.getPacketAttr());
116 if (tmpl.getBurstLengthAttr())
117 bd.setBurstLengthAttr(tmpl.getBurstLengthAttr());
118 if (tmpl.getAxcacheAttr())
119 bd.setAxcacheAttr(tmpl.getAxcacheAttr());
120 if (tmpl.getOffsetParameterAttr())
121 bd.setOffsetParameterAttr(tmpl.getOffsetParameterAttr());
122 // out_of_order_id is not copied because slicing an OoO BD is rejected above.
123 return bd;
124}
125
126// How many executions one pass over a task BD's pattern takes: one per index
127// of its iteration dimensions, all of them past d2.
128static int64_t iterationCount(const NdDmaPattern &pattern) {
129 int64_t count = 1;
130 for (int64_t size : llvm::drop_begin(pattern.sizes, 3))
131 count *= size;
132 return count;
133}
134
135// The factor by which decomposition scaled the executions of a pass, num/den
136// in lowest terms: a pass over the original takes `iterations` executions,
137// and over `after` one per index of its iteration dimension. Below one, the
138// executions merged, `after`'s inner dimensions taking in one the original
139// iterated over.
140struct IterationScale {
141 int64_t num = 1;
142 int64_t den = 1;
143
144 bool isOne() const { return num == den; }
145 // Whether `runs` executions of the original are whole executions of the
146 // rewrite.
147 bool divides(int64_t runs) const { return runs % den == 0; }
148 int64_t apply(int64_t runs) const { return runs / den * num; }
149 std::string str() const {
150 return den == 1 ? std::to_string(num)
151 : std::to_string(num) + "/" + std::to_string(den);
152 }
153};
154
155static IterationScale iterationScale(int64_t iterations,
156 const NdDmaPattern &after) {
157 int64_t common = std::gcd(after.sizes[3], iterations);
158 return {after.sizes[3] / common, iterations / common};
159}
160
161static unsigned countTaskBds(DMAConfigureTaskLike taskOp) {
162 unsigned n = 0;
163 taskOp->walk([&](AIE::DMABDOp) { ++n; });
164 return n;
165}
166
167static bool isUnderRuntimeControlFlow(AIE::DMABDOp op) {
168 auto seq = op->getParentOfType<AIE::RuntimeSequenceOp>();
169 if (!seq)
170 return false;
171 for (Operation *parent = op->getParentOp(); parent && parent != seq;
172 parent = parent->getParentOp()) {
173 if (isa<scf::ForOp, scf::WhileOp, scf::IfOp>(parent))
174 return true;
175 }
176 return false;
177}
178
179// The task, tile, channel and direction a runtime descriptor runs on.
180static std::optional<
181 std::tuple<AIE::TileOp, DMAConfigureTaskLike, int, AIE::DMAChannelDir>>
182resolveTaskAndTile(AIE::DMABDOp op) {
183 if (auto cfg = op->getParentOfType<DMAConfigureTaskOp>()) {
184 // Decomposition is a shape rewrite, so an unplaced tile is not an error
185 // here: skip the descriptor until placement has run.
186 AIE::TileOp tile = cfg.tryGetTileOp();
187 if (!tile)
188 return std::nullopt;
189 return std::make_tuple(tile, cast<DMAConfigureTaskLike>(*cfg),
190 static_cast<int>(cfg.getChannel()),
191 cfg.getDirection());
192 }
193 if (auto cfgFor = op->getParentOfType<DMAConfigureTaskForOp>()) {
194 AIE::DeviceOp dev = op->getParentOfType<AIE::DeviceOp>();
195 if (!dev)
196 return std::nullopt;
197 auto allocOp = AIE::ShimDMAAllocationOp::getForSymbol(
198 dev, cfgFor.getAlloc().getRootReference());
199 if (!allocOp)
200 return std::nullopt;
201 AIE::TileOp tile = allocOp.getTileOp();
202 if (!tile)
203 return std::nullopt;
204 return std::make_tuple(tile, cast<DMAConfigureTaskLike>(*cfgFor),
205 static_cast<int>(allocOp.getChannelIndex()),
206 allocOp.getChannelDir());
207 }
208 return std::nullopt;
209}
210
211static NpuDmaMemcpyNdOp createDecomposedOp(RewriterBase &rewriter,
212 NpuDmaMemcpyNdOp op,
213 const NdDmaPattern &pattern,
214 int64_t id, bool issueToken) {
215 assert(pattern.baseOffset == 0 &&
216 "a memcpy pattern has no peeled dimensions");
217 auto newOp = NpuDmaMemcpyNdOp::create(
218 rewriter, op.getLoc(), op, toOuter(pattern.offsets),
219 toOuter(pattern.sizes), toOuter(pattern.strides));
220 newOp.setIdAttr(rewriter.getI64IntegerAttr(id));
221 newOp.setIssueTokenAttr(rewriter.getBoolAttr(issueToken));
222 return newOp;
223}
224
225static int64_t allocateNextId(NpuDmaMemcpyNdOp op, int64_t startId,
226 llvm::DenseSet<int64_t> &usedIds) {
227 int64_t id = startId;
228 while (usedIds.contains(id))
229 ++id;
230 usedIds.insert(id);
231 return id;
232}
233
234// The starts splitIntoTasks emits, until orderSlices has placed them.
235struct Slices {
236 struct Start {
237 int64_t group, index, count;
238 };
239 llvm::DenseMap<Operation *, Start> starts;
240 // The configures of the slices after the first, which orderSlices moves up
241 // to their first start.
242 llvm::DenseSet<Operation *> lateTasks;
243 llvm::SetVector<Block *> blocks;
244 int64_t nextGroup = 0;
245};
246
247// Why the slices of `bd` cannot go out as one task each, or nullopt if they
248// can. Every use of the task has to be one splitIntoTasks rewrites, and every
249// start has to run whole passes over the pattern, a pass being one execution
250// per index of the `iterations`-long iteration dimension: the slices of a pass
251// are issued in turn, so a partial pass has no slice boundary to stop at.
252static std::optional<std::string>
253whyNotSeparateTasks(AIE::DMABDOp bd, DMAConfigureTaskLike taskOp,
254 int64_t iterations) {
255 std::string why;
256 llvm::raw_string_ostream os(why);
257 if (bd.getBdIdVal()) {
258 os << "the descriptor's bd_id is a runtime value";
259 return why;
260 }
261 if (taskOp.getRepeatCountVal()) {
262 os << "the task's repeat count is a runtime value";
263 return why;
264 }
265 for (Operation *user : taskOp->getResult(0).getUsers()) {
266 if (!isa<DMAStartTaskOp, DMAAwaitTaskOp, DMAFreeTaskOp>(user)) {
267 os << "the task is used by '" << user->getName() << "'";
268 return why;
269 }
270 if (user->getBlock() != taskOp->getBlock()) {
271 os << "the task is used outside the block that configures it";
272 return why;
273 }
274 auto start = dyn_cast<DMAStartTaskOp>(user);
275 if (!start)
276 continue;
277 if (start.getRepeatCountVal()) {
278 os << "a start's repeat count is a runtime value";
279 return why;
280 }
281 if (start.hasRepeatParameter()) {
282 os << "a start's repeat count is a scratchpad parameter";
283 return why;
284 }
285 std::optional<uint32_t> rc = start.getRepeatCount();
286 int64_t runs = static_cast<int64_t>(rc ? *rc : taskOp.getRepeatCount());
287 ++runs;
288 if (runs % iterations != 0) {
289 os << "a start runs it " << runs
290 << " times, not a whole number of passes over its " << iterations
291 << "-long iteration dimension";
292 return why;
293 }
294 }
295 return std::nullopt;
296}
297
298// Issue the slices of `bd` as one single-descriptor task each. The task
299// becomes the first slice and the others are configured right after it, until
300// orderSlices moves each up to its first start. Only the last slice issues the
301// task's token, so an await of the task becomes an await of the last slice,
302// and a free frees every slice. Each start becomes a
303// group of consecutive starts, every slice once per pass, which orderSlices
304// then interleaves with the starts around it.
305static void splitIntoTasks(RewriterBase &rewriter, AIE::DMABDOp bd,
306 DMAConfigureTaskLike taskOp,
307 ArrayRef<NdDmaPattern> slices,
308 int64_t baseFlatOffset, int64_t iterations,
309 Slices &state) {
310 bool token = taskOp.getIssueToken();
311 int64_t taskRuns = static_cast<int64_t>(taskOp.getRepeatCount()) + 1;
312 SmallVector<Operation *> users(taskOp->getResult(0).getUsers());
313
314 SmallVector<DMAConfigureTaskLike> tasks{taskOp};
315 rewriter.setInsertionPointAfter(taskOp);
316 for (size_t i = 1; i < slices.size(); ++i) {
317 tasks.push_back(cast<DMAConfigureTaskLike>(rewriter.clone(*taskOp)));
318 state.lateTasks.insert(tasks.back());
319 }
320
321 for (auto it : llvm::enumerate(slices)) {
322 size_t i = it.index();
323 const NdDmaPattern &sub = it.value();
324 DMAConfigureTaskLike task = tasks[i];
325 AIE::DMABDOp sliceBd = bd;
326 if (i > 0)
327 task->walk([&](AIE::DMABDOp b) { sliceBd = b; });
328 int64_t flatOffset = flatOffsetFromPattern(baseFlatOffset, sub);
329 int32_t len = static_cast<int32_t>(lenFromInnermost3(sub.sizes));
330 rewriter.modifyOpInPlace(sliceBd, [&]() {
331 updateTaskBdInPlace(sliceBd, static_cast<int32_t>(flatOffset), len,
332 toOuter(sub.sizes), toOuter(sub.strides));
333 // A pinned id stays with the first slice, as in a chain.
334 if (i > 0)
335 sliceBd.removeBdIdAttr();
336 });
337 rewriter.modifyOpInPlace(task, [&]() {
338 // One pass over the slice is one execution per index of its own
339 // iteration dimension.
340 task.setRepeatCount(static_cast<uint32_t>(sub.sizes[3] - 1));
341 task.setIssueToken(token && i + 1 == slices.size());
342 });
343 }
344
345 for (Operation *user : users) {
346 if (auto await = dyn_cast<DMAAwaitTaskOp>(user)) {
347 rewriter.modifyOpInPlace(await, [&]() {
348 await.getTaskMutable().assign(tasks.back()->getResult(0));
349 });
350 continue;
351 }
352 if (auto free = dyn_cast<DMAFreeTaskOp>(user)) {
353 rewriter.setInsertionPointAfter(free);
354 for (DMAConfigureTaskLike task : llvm::drop_begin(tasks))
355 DMAFreeTaskOp::create(rewriter, free.getLoc(), task->getResult(0));
356 continue;
357 }
358 auto start = cast<DMAStartTaskOp>(user);
359 std::optional<uint32_t> rc = start.getRepeatCount();
360 int64_t runs = rc ? static_cast<int64_t>(*rc) + 1 : taskRuns;
361 int64_t count = runs / iterations * static_cast<int64_t>(slices.size());
362 int64_t group = state.nextGroup++;
363 // Only the last start of the last slice may issue the token: an earlier
364 // pass's would complete an await before the transfer has.
365 bool startToken = token && !start.getNoToken();
366 auto mark = [&](DMAStartTaskOp s, int64_t index) {
367 state.starts[s] = {group, index, count};
368 };
369 rewriter.modifyOpInPlace(start, [&]() { start.removeRepeatCountAttr(); });
370 mark(start, 0);
371 state.blocks.insert(start->getBlock());
372 rewriter.setInsertionPointAfter(start);
373 for (int64_t k = 1; k < count; ++k) {
374 size_t i = static_cast<size_t>(k) % slices.size();
375 bool withholds =
376 token && i + 1 == slices.size() && (!startToken || k + 1 != count);
377 auto s = DMAStartTaskOp::create(
378 rewriter, start.getLoc(), tasks[i]->getResult(0),
379 /*repeat_count=*/nullptr, /*repeat_count_val=*/nullptr,
380 /*no_token=*/withholds ? rewriter.getUnitAttr() : nullptr,
381 /*repeat_parameter=*/nullptr, /*repeat_state_table_idx=*/nullptr);
382 mark(s, k);
383 }
384 }
385}
386
387using ChannelKey = DmaQueueModel::ChannelKey;
388
389// The channel a start pushes onto, or nullopt when its task is not a configure
390// on a placed tile this pass can read.
391static std::optional<ChannelKey> channelOf(DMAStartTaskOp start) {
392 Operation *def = start.getTask().getDefiningOp();
393 if (auto cfg = dyn_cast_or_null<DMAConfigureTaskOp>(def)) {
394 if (cfg.tryGetTileOp())
395 return DmaQueueModel::keyOf(cfg);
396 return std::nullopt;
397 }
398 auto cfgFor = dyn_cast_or_null<DMAConfigureTaskForOp>(def);
399 if (!cfgFor)
400 return std::nullopt;
401 auto dev = cfgFor->getParentOfType<AIE::DeviceOp>();
402 auto alloc = dev ? AIE::ShimDMAAllocationOp::getForSymbol(
403 dev, cfgFor.getAlloc().getRootReference())
404 : AIE::ShimDMAAllocationOp();
405 if (!alloc || !alloc.getTileOp())
406 return std::nullopt;
407 return DmaQueueModel::keyOf(alloc);
408}
409
410// Interleave the slices splitIntoTasks emitted with the starts around them.
411// Later slices wait for earlier ones to finish (see
412// aie-assign-runtime-sequence-bd-ids), so a counterpart transfer left behind
413// all of them (a core's input for an output, say) would deadlock.
414//
415// A round runs from one start up to the next start on a channel it already
416// used. Each start's first slice keeps its place; later ones follow the
417// round's last start, ordered by index / size, ties in program order. Slices
418// move past configures, RTP writes and lock sets, which never wait. Any other
419// effect ends a round: an await, sync, poll, untracked push, free of an
420// unplaced slice, or a write32/blockwrite (either may be a push).
421static void orderSlices(Block &block, Slices &state) {
422 struct Pending {
423 DMAStartTaskOp start;
424 int64_t index, count, head;
425 };
426 SmallVector<Pending> pending;
427 llvm::DenseSet<Value> pendingTasks;
428 std::set<ChannelKey> round;
429 llvm::DenseMap<int64_t, int64_t> headOfGroup;
430 Operation *anchor = nullptr;
431 int64_t heads = 0;
432
433 auto flush = [&]() {
434 llvm::stable_sort(pending, [](const Pending &a, const Pending &b) {
435 int64_t lhs = a.index * b.count;
436 int64_t rhs = b.index * a.count;
437 return lhs != rhs ? lhs < rhs : a.head < b.head;
438 });
439 Operation *after = anchor;
440 for (Pending &p : pending) {
441 p.start->moveAfter(after);
442 after = p.start;
443 // Configure a slice only once it is due, so that the descriptors it
444 // takes are not held while earlier slices wait: the BD-ID pass can take
445 // descriptors back only from started tasks.
446 Operation *task = p.start.getTask().getDefiningOp();
447 if (task && state.lateTasks.erase(task))
448 task->moveBefore(p.start);
449 }
450 pending.clear();
451 pendingTasks.clear();
452 round.clear();
453 headOfGroup.clear();
454 anchor = nullptr;
455 };
456
457 for (Operation &op : llvm::make_early_inc_range(block)) {
458 if (auto start = dyn_cast<DMAStartTaskOp>(op)) {
459 std::optional<ChannelKey> channel = channelOf(start);
460 auto it = state.starts.find(start);
461 std::optional<Slices::Start> slice;
462 if (it != state.starts.end())
463 slice = it->second;
464 if (channel && slice && slice->index > 0) {
465 auto head = headOfGroup.find(slice->group);
466 if (head != headOfGroup.end()) {
467 pending.push_back({start, slice->index, slice->count, head->second});
468 pendingTasks.insert(start.getTask());
469 continue;
470 }
471 }
472 if (!channel || round.count(*channel))
473 flush();
474 if (!channel)
475 continue;
476 round.insert(*channel);
477 if (slice)
478 headOfGroup[slice->group] = heads;
479 ++heads;
480 anchor = &op;
481 continue;
482 }
483 if (auto free = dyn_cast<DMAFreeTaskOp>(op)) {
484 if (pendingTasks.contains(free.getTask()))
485 flush();
486 continue;
487 }
488 if (isa<DMAConfigureTaskOp, DMAConfigureTaskForOp, NpuWriteRTPOp,
489 SetLockOp>(op) ||
490 isMemoryEffectFree(&op))
491 continue;
492 flush();
493 }
494 flush();
495}
496
497static void decomposeMemcpy(RewriterBase &rewriter, NpuDmaMemcpyNdOp op) {
498 std::optional<NdDmaPattern> constant = constantPattern(op);
499 if (!constant)
500 return;
501 // A runtime length stays whole; see DMABDOp::verify.
502 if (op.getLengthParameterAttr() || op.getLengthStateTableIdxAttr())
503 return;
504
505 const NdDmaPattern &pattern = *constant;
506 if (isContiguousTransfer(pattern.sizes, pattern.strides))
507 return;
508
509 AIE::DeviceOp dev = op->getParentOfType<AIE::DeviceOp>();
510 if (!dev)
511 return;
512
513 auto allocOp = AIE::ShimDMAAllocationOp::getForSymbol(
514 dev, op.getMetadata().getRootReference());
515 if (!allocOp)
516 return;
517
518 AIE::TileOp tile = allocOp.getTileOp();
519 if (!tile)
520 return;
521
522 int col = tile.getCol();
523 int row = tile.getRow();
524 const AIE::AIETargetModel &targetModel = AIE::getTargetModel(op);
525 auto bufferType = cast<BaseMemRefType>(op.getMemref().getType());
526
527 if (patternPassesVerification(op, bufferType, targetModel, col, row, pattern))
528 return;
529
530 auto decomposed =
531 decomposeNdDmaPattern(op, bufferType, pattern, targetModel, col, row);
532 // failed() already guards both dereferences below via short-circuit /
533 // prior control flow; the checker just doesn't associate FailureOr's
534 // failed()/succeeded() idiom with the std::optional base it derives from.
535 if (failed(decomposed) ||
536 decomposed->empty()) // NOLINT(bugprone-unchecked-optional-access)
537 return;
538 // Bind a plain reference now that decomposed is known non-failed and
539 // non-empty, so nothing past this point looks like an optional access.
540 SmallVector<NdDmaPattern> &bds =
541 *decomposed; // NOLINT(bugprone-unchecked-optional-access)
542 if (bds.size() > targetModel.getNumBDs(col, row))
543 return;
544
545 rewriter.setInsertionPoint(op);
546 if (bds.size() == 1) {
547 rewriter.replaceOpWithNewOp<NpuDmaMemcpyNdOp>(
548 op, op, toOuter(bds.front().offsets), toOuter(bds.front().sizes),
549 toOuter(bds.front().strides));
550 return;
551 }
552
553 llvm::DenseSet<int64_t> usedIds;
554 if (auto seq = op->getParentOfType<AIE::RuntimeSequenceOp>()) {
555 seq.walk([&](NpuDmaMemcpyNdOp other) {
556 if (other == op)
557 return;
558 if (other.getMetadata() == op.getMetadata())
559 usedIds.insert(other.getId());
560 });
561 }
562
563 int64_t nextId = op.getId();
564 for (auto [idx, subPattern] : llvm::enumerate(bds)) {
565 bool last = idx + 1 == bds.size();
566 int64_t id = allocateNextId(op, nextId, usedIds);
567 nextId = id + 1;
568 createDecomposedOp(rewriter, op, subPattern, id,
569 last && op.getIssueToken());
570 }
571 rewriter.eraseOp(op);
572}
573
574// Rewrites a task's descriptor into legal ones. Fails only after reporting why
575// it cannot.
576static LogicalResult decomposeTaskBd(RewriterBase &rewriter, AIE::DMABDOp op,
577 Slices &slices) {
578 auto taskAndTile = resolveTaskAndTile(op);
579 if (!taskAndTile)
580 return success();
581
582 AIE::TileOp tile = std::get<0>(*taskAndTile);
583 DMAConfigureTaskLike taskOp = std::get<1>(*taskAndTile);
584 int channel = std::get<2>(*taskAndTile);
585 AIE::DMAChannelDir dir = std::get<3>(*taskAndTile);
586
587 // A descriptor with more dimensions than a BD has cannot be lowered as it
588 // is, so where this pass cannot reduce it, it says why.
589 bool tooManyDims = op.getMixedSizes().size() > kNdDmaDims;
590 auto cannotReduce = [&]() {
591 return op.emitOpError()
592 << "has " << op.getMixedSizes().size()
593 << " dimensions, and a buffer descriptor holds " << kNdDmaDims
594 << "; the extra ones can only be split off ";
595 };
596 int col = tile.getCol();
597 int row = tile.getRow();
598 const AIE::AIETargetModel &targetModel = AIE::getTargetModel(op);
599 FailureOr<TaskBdDecomposition> plan =
600 decomposeTaskBdPattern(op, targetModel, col, row);
601 if (failed(plan)) {
602 if (tooManyDims)
603 return cannotReduce()
604 << "a descriptor whose offset, length, sizes and strides are "
605 "all constant and that has no padding";
606 return success();
607 }
608 if (countTaskBds(taskOp) != 1) {
609 if (tooManyDims)
610 return cannotReduce() << "a task's only descriptor";
611 return success();
612 }
613 // A descriptor takes its locks once per execution, which decomposition
614 // regroups, and a slice of its own would take none.
615 bool takesLocks = false;
616 taskOp->walk([&](AIE::UseLockOp) { takesLocks = true; });
617 if (takesLocks) {
618 if (tooManyDims)
619 return cannotReduce() << "a descriptor that takes no locks";
620 return success();
621 }
622 // A runtime length stays whole; see DMABDOp::verify.
623 if (op.getLengthParameterAttr() || op.getLengthStateTableIdxAttr())
624 return success();
625
626 if (plan->legal) // NOLINT(bugprone-unchecked-optional-access)
627 return success();
628
629 // Iteration uses the outermost ND slot, so there is no free dimension to
630 // factor into, and chain-slicing has no defined iteration semantics.
631 if (op.getIteration())
632 return op.emitOpError()
633 << "buffer descriptor with the iteration attribute is too large "
634 "to lower and cannot be decomposed";
635
636 // One pass over the pattern, in executions of the descriptor.
637 int64_t iterations =
638 iterationCount(plan->pass); // NOLINT(bugprone-unchecked-optional-access)
639 // Bind a plain reference now that plan is known non-failed, so nothing past
640 // this point looks like an optional access.
641 SmallVector<NdDmaPattern> &bds =
642 plan->pieces; // NOLINT(bugprone-unchecked-optional-access)
643 if (bds.empty()) {
644 if (tooManyDims)
645 return op.emitOpError()
646 << "has " << op.getMixedSizes().size()
647 << " dimensions, and no split into at most " << kMaxNdDmaPieces
648 << " descriptors of " << kNdDmaDims << " fits this tile";
649 return success();
650 }
651
652 int64_t baseFlatOffset = op.getConstantOffset().value_or(0);
653
654 if (bds.size() == 1) {
655 const NdDmaPattern &sub = bds.front();
656 int64_t flatOffset = flatOffsetFromPattern(baseFlatOffset, sub);
657 auto outerSizes = toOuter(sub.sizes);
658 auto outerStrides = toOuter(sub.strides);
659 // len covers one BD invocation, so it tracks the innermost three
660 // dimensions only. Rewriting in place can move extent into the fourth
661 // (repeat) dimension -- e.g. an innermost run too long for the wrap
662 // field factors out an extra dimension and pushes the outermost one into
663 // the repeat slot -- so len has to be recomputed alongside the shape.
664 int32_t len = static_cast<int32_t>(lenFromInnermost3(sub.sizes));
665
666 IterationScale scale = iterationScale(iterations, sub);
667 int64_t runs = 0;
668 if (!scale.isOne()) {
669 if (taskOp.getRepeatCountVal())
670 return op.emitOpError()
671 << "cannot decompose a buffer descriptor whose repeat count "
672 "is a runtime value: decomposition needs to scale it by "
673 << scale.str();
674 // A scaled count past what one queue push carries is fine: the BD-ID
675 // pass issues it as several starts. Only the attribute width limits
676 // it. Widen before multiplying: the accessor returns int32_t, so the
677 // addition alone would overflow in int and wrap past this check.
678 // Merged executions need every start to run whole ones.
679 auto check = [&](Operation *at, int64_t repeat, StringRef runner,
680 StringRef count) -> LogicalResult {
681 int64_t before = repeat + 1;
682 if (!scale.divides(before))
683 return at->emitOpError()
684 << "cannot decompose: it merges every " << scale.den
685 << " executions of the buffer descriptor into " << scale.num
686 << ", and " << runner << " runs it " << before << " times";
687 int64_t after = scale.apply(before);
688 if (after - 1 > std::numeric_limits<int32_t>::max())
689 return at->emitOpError()
690 << "decomposition scales " << count << " by " << scale.str()
691 << " to " << (after - 1) << ", beyond a 32-bit repeat_count";
692 return success();
693 };
694 runs = taskOp.getRepeatCount() + int64_t{1};
695 if (failed(check(op, runs - 1, "the task", "the repeat count")))
696 return failure();
697 // A start that overrides the task's count repeats the same BD, so it
698 // scales by the same factor.
699 for (Operation *user : taskOp->getResult(0).getUsers()) {
700 auto start = dyn_cast<DMAStartTaskOp>(user);
701 if (!start)
702 continue;
703 if (start.getRepeatCountVal() || start.hasRepeatParameter())
704 return start.emitOpError()
705 << "cannot decompose a buffer descriptor this start repeats "
706 "a runtime number of times: decomposition needs to scale "
707 "the count by "
708 << scale.str();
709 if (IntegerAttr rc = start.getRepeatCountAttr())
710 if (failed(check(start, rc.getInt(), "this start",
711 "this start's repeat count")))
712 return failure();
713 }
714 runs = scale.apply(runs);
715 }
716
717 rewriter.modifyOpInPlace(op, [&]() {
718 updateTaskBdInPlace(op, static_cast<int32_t>(flatOffset), len, outerSizes,
719 outerStrides);
720 });
721 if (!scale.isOne()) {
722 rewriter.modifyOpInPlace(taskOp, [&]() {
723 taskOp.setRepeatCount(static_cast<uint32_t>(runs - 1));
724 });
725 for (Operation *user : taskOp->getResult(0).getUsers())
726 if (auto start = dyn_cast<DMAStartTaskOp>(user))
727 if (IntegerAttr rc = start.getRepeatCountAttr())
728 rewriter.modifyOpInPlace(start, [&]() {
729 start.setRepeatCountAttr(
730 rewriter.getI32IntegerAttr(scale.apply(rc.getInt() + 1) - 1));
731 });
732 }
733 return success();
734 }
735
736 // A split would make every slice reuse the one out_of_order_id slot.
737 // TODO: BD iteration plus padding may enable this feature.
738 if (op.getOutOfOrderId().has_value())
739 return op.emitOpError() << "splitting an out-of-order buffer descriptor "
740 "into multiple descriptors is not implemented";
741
742 // Every member of a chain runs once per task execution, so the one
743 // queue-push repeat count is shared by all of them. A slice that also wants
744 // its own iteration factor needs a private repeat, which only a task of
745 // its own has. A chain also holds all of its descriptors until it
746 // finishes, so past the queue depth the slices go out as separate tasks,
747 // whose descriptors aie-assign-runtime-sequence-bd-ids can recycle one by
748 // one.
749 bool sharedRepeat = llvm::all_of(bds, [&](const NdDmaPattern &sub) {
750 return iterationScale(iterations, sub).isOne();
751 });
752 bool chainFits =
753 sharedRepeat &&
754 bds.size() <= targetModel.getNumBDsForChannel(col, row, channel, dir);
755 uint32_t depth = targetModel.getDmaTaskQueueDepth();
756 if (!chainFits || (depth > 0 && bds.size() > depth)) {
757 // The dynamic BD pool allocates a chain under runtime control flow, but
758 // separate tasks there are left whole.
759 if (isUnderRuntimeControlFlow(op)) {
760 if (tooManyDims)
761 return cannotReduce()
762 << "outside runtime control flow, since its " << bds.size()
763 << " pieces have to be separate tasks";
764 op.emitRemark() << "deferring decomposition into " << bds.size()
765 << " separate tasks under runtime control flow";
766 return success();
767 }
768 std::optional<std::string> why =
769 whyNotSeparateTasks(op, taskOp, iterations);
770 if (!why) {
771 splitIntoTasks(rewriter, op, taskOp, bds, baseFlatOffset, iterations,
772 slices);
773 return success();
774 }
775 if (!sharedRepeat)
776 return op.emitOpError()
777 << "cannot split this buffer descriptor: its slices need "
778 "per-descriptor repeat counts, which a chain shares, and "
779 "they cannot be separate tasks because "
780 << *why;
781 if (!chainFits)
782 return op.emitOpError()
783 << "cannot split this buffer descriptor: its " << bds.size()
784 << " slices outnumber the "
785 << targetModel.getNumBDsForChannel(col, row, channel, dir)
786 << " buffer descriptors its channel reaches, and they cannot be "
787 "separate tasks "
788 "because "
789 << *why;
790 }
791
792 Region *body = &taskOp.getBody();
793 if (body->empty())
794 return success();
795
796 SmallVector<Block *> blocks;
797 blocks.push_back(op->getBlock());
798 for (unsigned i = 1; i < bds.size(); ++i)
799 blocks.push_back(rewriter.createBlock(body));
800
801 for (auto [idx, subPattern] : llvm::enumerate(bds)) {
802 Block *block = blocks[idx];
803 int64_t flatOffset = flatOffsetFromPattern(baseFlatOffset, subPattern);
804 auto outerSizes = toOuter(subPattern.sizes);
805 auto outerStrides = toOuter(subPattern.strides);
806 int32_t len = static_cast<int32_t>(lenFromInnermost3(subPattern.sizes));
807
808 if (idx == 0) {
809 rewriter.modifyOpInPlace(op, [&]() {
810 updateTaskBdInPlace(op, static_cast<int32_t>(flatOffset), len,
811 outerSizes, outerStrides);
812 });
813 Operation *oldTerm = block->getTerminator();
814 rewriter.setInsertionPoint(oldTerm);
815 if (idx + 1 < bds.size())
816 AIE::NextBDOp::create(rewriter, op.getLoc(), blocks[idx + 1]);
817 else
818 AIE::EndOp::create(rewriter, op.getLoc());
819 rewriter.eraseOp(oldTerm);
820 } else {
821 rewriter.setInsertionPointToStart(block);
822 createTaskBd(rewriter, op.getLoc(), op, static_cast<int32_t>(flatOffset),
823 len, outerSizes, outerStrides);
824 rewriter.setInsertionPointToEnd(block);
825 if (idx + 1 < bds.size())
826 AIE::NextBDOp::create(rewriter, op.getLoc(), blocks[idx + 1]);
827 else
828 AIE::EndOp::create(rewriter, op.getLoc());
829 }
830 }
831
832 return success();
833}
834
835struct AIEDecomposeLargeDmaBdPass
836 : xilinx::AIEX::impl::AIEDecomposeLargeDmaBdBase<
837 AIEDecomposeLargeDmaBdPass> {
838 void runOnOperation() override {
839 AIE::DeviceOp device = getOperation();
840 IRRewriter rewriter(&getContext());
841 SmallVector<NpuDmaMemcpyNdOp> memcpys;
842 SmallVector<AIE::DMABDOp> bds;
843 device.walk([&](Operation *op) {
844 if (auto memcpy = dyn_cast<NpuDmaMemcpyNdOp>(op))
845 memcpys.push_back(memcpy);
846 else if (auto bd = dyn_cast<AIE::DMABDOp>(op))
847 bds.push_back(bd);
848 });
849 for (NpuDmaMemcpyNdOp memcpy : memcpys)
850 decomposeMemcpy(rewriter, memcpy);
851 Slices slices;
852 bool failed = false;
853 for (AIE::DMABDOp bd : bds)
854 failed |= mlir::failed(decomposeTaskBd(rewriter, bd, slices));
855 if (failed)
856 return signalPassFailure();
857 for (Block *block : slices.blocks)
858 orderSlices(*block, slices);
859 }
860};
861
862} // namespace
863
864std::unique_ptr<OperationPass<AIE::DeviceOp>>
866 return std::make_unique<AIEDecomposeLargeDmaBdPass>();
867}
std::array< int, 4 > ChannelKey
{col, row, direction, channel}.
static ChannelKey keyOf(AIE::TileOp tile, AIE::DMAChannelDir direction, int64_t channel)
uint32_t getNumBDsForChannel(int col, int row, int channel, DMAChannelDir dir) const
virtual uint32_t getDmaTaskQueueDepth() const =0
Return how many DMA tasks a single channel's task queue holds (unsupported = 0).
virtual uint32_t getNumBDs(AIETileType tileType) const =0
Return the size of the BD id space of a tile type (see getTotalNumBDs()).
bool isContiguousTransfer(llvm::ArrayRef< int64_t > sizes, llvm::ArrayRef< int64_t > strides)
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIEDecomposeLargeDmaBdPass()
mlir::FailureOr< llvm::SmallVector< NdDmaPattern > > decomposeNdDmaPattern(mlir::Operation *forOp, mlir::BaseMemRefType referencedBufType, const NdDmaPattern &pattern, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow)
Decompose an illegal pattern into one or more legal sub-patterns that move the same data.
mlir::FailureOr< TaskBdDecomposition > decomposeTaskBdPattern(xilinx::AIE::DMABDOp bd, const xilinx::AIE::AIETargetModel &targetModel, int tileCol, int tileRow)
Plan the split of bd, a runtime task's descriptor, on tile (tileCol, tileRow).
bool patternPassesVerification(mlir::Operation *forOp, mlir::BaseMemRefType referencedBufType, const xilinx::AIE::AIETargetModel &tm, int tileCol, int tileRow, const NdDmaPattern &pattern, bool skipTransformationChecks=false)
Returns true when the pattern passes verifyStridesWraps for the given tile and memref element type.
const AIETargetModel & getTargetModel(mlir::Operation *op)
Innermost-first ND access pattern (d0..d3 / repeat), matching the convention used by verifyStridesWra...
llvm::SmallVector< int64_t, kNdDmaDims > sizes
int64_t baseOffset
Elements added to the address the offsets give.
llvm::SmallVector< int64_t, kNdDmaDims > offsets
llvm::SmallVector< int64_t, kNdDmaDims > strides