MLIR-AIE 1.4.6.dev
AIEAssignRuntimeSequenceBDIDs.cpp
Go to the documentation of this file.
1//===- AIEAssignRuntimeSequenceBDIDs.cpp ------------------------*- C++ -*-===//
2//
3// Copyright (C) 2024 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// Assigns buffer-descriptor (BD) IDs to the DMA tasks configured in a runtime
9// sequence.
10//
11// This pass runs on straight-line IR: --aie-unroll-runtime-sequence-loops has
12// unrolled every constant-trip scf.for, and canonicalization has folded every
13// constant-predicate scf.if, before this pass runs. So in the static path no
14// scf op survives to reach the allocator -- a rolled ping-pong over a constant
15// loop is just N straight-line configures whose ids ordinary liveness reuse
16// recycles. Any scf.for/scf.if still present is therefore runtime-valued, which
17// the static path cannot lower (the runtime sequence becomes a flat, branchless
18// NPU instruction stream); such forms are rejected here for the dynamic EmitC
19// path (Phase 2).
20//
21// aie-split-long-repeats has already made every start exactly one queue push.
22//
23// The per-channel resource checks before allocation (see the pass
24// description) are verifyChannelUsage, a single-pass per-channel count on the
25// straight-line IR; what an await there proves relies on checkTokensConsumed
26// (DmaQueueModel.h). reclaim-bds's "status poll already proves finished, or
27// one inserted to" is reclaimFor.
28//
29//===----------------------------------------------------------------------===//
30
37
38#include "mlir/Dialect/Arith/IR/Arith.h"
39#include "mlir/Dialect/SCF/IR/SCF.h"
40#include "mlir/Dialect/Utils/StaticValueUtils.h"
41#include "mlir/Pass/Pass.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/DenseSet.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Support/Threading.h"
47
48#include <array>
49#include <deque>
50#include <map>
51#include <set>
52
53namespace xilinx::AIEX {
54#define GEN_PASS_DEF_AIEASSIGNRUNTIMESEQUENCEBDIDS
55#define GEN_PASS_DEF_AIENORMALIZEDMATASKGROUPS
56#include "aie/Dialect/AIEX/Transforms/AIEXPasses.h.inc"
57} // namespace xilinx::AIEX
58
59using namespace mlir;
60using namespace xilinx;
61using namespace xilinx::AIEX;
62
63namespace {
64
65static DMAAwaitTaskOp taskTripleAwait(Operation *operation) {
66 auto configure = dyn_cast_or_null<DMAConfigureTaskLike>(operation);
67 if (!configure || !configure.getBody().hasOneBlock() ||
68 configure.getRepeatCount() || configure.getRepeatCountVal() ||
69 !configure.getIssueToken() || !operation->getResult(0).hasNUses(2))
70 return {};
71 if (auto concrete = dyn_cast<DMAConfigureTaskOp>(operation);
72 concrete && concrete.getOutOfOrder())
73 return {};
74 auto start = dyn_cast_or_null<DMAStartTaskOp>(operation->getNextNode());
75 auto await = start ? dyn_cast_or_null<DMAAwaitTaskOp>(start->getNextNode())
76 : DMAAwaitTaskOp();
77 if (!start || !await || start.getTask() != operation->getResult(0) ||
78 await.getTask() != operation->getResult(0) || start.getRepeatCount() ||
79 start.getRepeatCountVal() || start.getNoToken() ||
80 start.hasRepeatParameter())
81 return {};
82 Block &body = configure.getBody().front();
83 if (body.getNumArguments() || body.getOperations().size() != 2 ||
84 !isa<AIE::DMABDOp>(body.front()) || !isa<AIE::EndOp>(body.back()))
85 return {};
86 auto bd = cast<AIE::DMABDOp>(body.front());
87 return bd.getBdId() || bd.getNextBdId() ? DMAAwaitTaskOp() : await;
88}
89
90struct AIENormalizeDMATaskGroupsPass
91 : xilinx::AIEX::impl::AIENormalizeDMATaskGroupsBase<
92 AIENormalizeDMATaskGroupsPass> {
93 void runOnOperation() override {
94 getOperation().walk([](DMAAwaitTaskOp await) {
95 if (await.getDeferCompletion() &&
96 (taskTripleAwait(await.getTask().getDefiningOp()) != await ||
97 !taskTripleAwait(await->getNextNode())))
98 await.removeDeferCompletionAttr();
99 });
100 }
101};
102
103struct AIEAssignRuntimeSequenceBDIDsPass
104 : xilinx::AIEX::impl::AIEAssignRuntimeSequenceBDIDsBase<
105 AIEAssignRuntimeSequenceBDIDsPass> {
106 using Base = xilinx::AIEX::impl::AIEAssignRuntimeSequenceBDIDsBase<
107 AIEAssignRuntimeSequenceBDIDsPass>;
108 AIEAssignRuntimeSequenceBDIDsPass() = default;
109 AIEAssignRuntimeSequenceBDIDsPass(
110 const AIEAssignRuntimeSequenceBDIDsOptions &options)
111 : Base(options) {}
112
113 llvm::DenseMap<AIE::TileID, BdIdGenerator> gens;
114
115 // How to retire a copy still holding an id, by whether it issues a token.
116 static constexpr llvm::StringLiteral kWaitForToken =
117 "wait for it (aiex.npu.sync or aiex.npu.dma_wait on its channel, "
118 "consuming its token).";
119 static constexpr llvm::StringLiteral kNoTokenAdvice =
120 "it issues no token: set issue_token = true and wait for it, or await "
121 "a later token-issuing transfer on its channel.";
122
123 // Whether `op` writes array registers raw, at an address it does not fix or
124 // over one of `keys`' task queues, so pushing a task no count sees.
125 static bool writesQueue(Operation *op,
126 ArrayRef<DmaQueueModel::ChannelKey> keys) {
127 std::optional<uint32_t> first;
128 uint64_t bytes = 4;
129 if (auto write = dyn_cast<NpuWrite32Op>(op)) {
130 if (write.getBuffer())
131 return false;
132 first = write.getAbsoluteAddress();
133 } else if (auto write = dyn_cast<NpuMaskWrite32Op>(op)) {
134 if (write.getBuffer())
135 return false;
136 first = write.getAbsoluteAddress();
137 } else if (auto write = dyn_cast<NpuBlockWriteOp>(op)) {
138 if (write.getBuffer())
139 return false;
140 first = write.getAbsoluteAddress();
141 auto data = dyn_cast<MemRefType>(write.getData().getType());
142 if (!data || !data.hasStaticShape())
143 return true;
144 bytes = data.getNumElements() * data.getElementTypeBitWidth() / 8;
145 } else {
146 return false;
147 }
148 if (!first)
149 return true;
150 const AIETargetModel &tm =
151 op->getParentOfType<AIE::DeviceOp>().getTargetModel();
152 return llvm::any_of(keys, [&](const DmaQueueModel::ChannelKey &key) {
153 uint64_t queue = tm.getDmaQueueAddress(
154 key[0], key[1], key[3], static_cast<AIE::DMAChannelDir>(key[2]));
155 return queue >= *first && queue < *first + bytes;
156 });
157 }
158
159 AIE::DeviceOp configuredDevice;
160
161 // Reserves on `tile` the BD ids the static DMAs there hold: those of the
162 // device holding the sequence, the loaded device and the configured one.
163 //
164 // Known limitation: after a load_pdi of another device, this and
165 // loopingStartsOf read that sibling device's DMA programs, which races with
166 // the sibling's own nested pipeline (aie-dma-to-npu adds globals to its
167 // block) once devices run in parallel. The MLIR aiecc builds against runs
168 // them one at a time today. Splitting the nest does not help, since the pass
169 // manager merges adjacent device nests; a parallel build needs these
170 // summaries computed at module scope before the nest.
171 void reserveStaticBds(AIE::TileID tile, BdIdGenerator &gen) {
172 SmallVector<AIE::DeviceOp, 3> devices{getOperation()};
173 for (AIE::DeviceOp device : {loadedDevice, configuredDevice})
174 if (device)
175 devices.push_back(device);
176 // Reserve in the submitting channel's pool, or every pool without one.
177 gen.reserved.clear();
178 for (const AIEX::StaticBd &bd : AIEX::staticBdIds(devices, tile)) {
179 if (bd.channel)
180 gen.reserveBdId(bd.channel->first, bd.channel->second, bd.id);
181 else
182 gen.reserveBdId(bd.id);
183 }
184 }
185
186 // Keyed by (col, row), not the aie.tile op's own identity: two tile ops
187 // for one coordinate (accepted elsewhere, see runtime_vs_static_multi_
188 // tile.mlir) must share one generator, not bypass each other's claims.
189 BdIdGenerator &getGeneratorForTile(AIE::TileOp tile) {
190 AIE::TileID id = tile.getTileID();
191 auto it = gens.find(id);
192 if (it == gens.end()) {
193 AIE::DeviceOp device = tile->getParentOfType<AIE::DeviceOp>();
194 it = gens.insert({id, BdIdGenerator(tile.getCol(), tile.getRow(),
195 device.getTargetModel())})
196 .first;
197 reserveStaticBds(id, it->second);
198 }
199 return it->second;
200 }
201
202 void noteConfigured(SetDeviceOp context) {
203 llvm::SmallPtrSet<Operation *, 16> pending;
204 for (const auto &entry : liveByTile)
205 for (DMAConfigureTaskOp task : entry.second)
206 if (pushCounts.lookup(task).running)
207 pending.insert(task);
208 for (const auto &entry : loadState.holdsOn)
209 for (const auto &hold : entry.second)
210 pending.insert(hold.second.copy);
211 if (!pending.empty()) {
212 SmallVector<Operation *> transfers(pending.begin(), pending.end());
213 llvm::sort(transfers, [](Operation *left, Operation *right) {
214 return left->isBeforeInBlock(right);
215 });
216 auto diagnostic =
217 mlir::emitWarning(context.getLoc())
218 << "configures a device while runtime DMA transfers may still be in "
219 "flight; await their completion before reconfiguration";
220 diagnostic.attachNote(transfers.front()->getLoc())
221 << "unfinished transfer (" << transfers.size() << " pending)";
222 }
223 FlatSymbolRefAttr ref = context.getDeviceRefAttr();
224 auto device = SymbolTable::lookupNearestSymbolFrom<AIE::DeviceOp>(
225 getOperation()->getParentOp(), ref);
226 if (!device || device == configuredDevice)
227 return;
228 configuredDevice = device;
229 for (auto &[tile, tileGen] : gens) {
230 BdIdGenerator &gen = tileGen;
231 reserveStaticBds(tile, gen);
232 for (DMAConfigureTaskOp task : liveByTile.lookup(tile)) {
233 if (releasedTasks.contains(task) || knownComplete.contains(task) ||
234 provenFinished.contains(task))
235 continue;
236 std::optional<uint32_t> held;
237 task.walk([&](AIE::DMABDOp bd) {
238 if (!held && bd.getBdId() &&
239 gen.isReserved(task.getChannel(), task.getDirection(),
240 *bd.getBdId()))
241 held = *bd.getBdId();
242 });
243 if (!held)
244 continue;
245 auto diag = mlir::emitWarning(context.getLoc())
246 << "configures " << ref
247 << ", whose static DMAs take buffer descriptor ID " << *held
248 << " on tile (" << tile.col << "," << tile.row
249 << "), which a transfer not known to be finished holds";
250 diag.attachNote(task.getLoc()) << "the transfer is configured here";
251 }
252 }
253 }
254
255 // Each device's static aie.dma_starts whose BD chain never ends, by channel.
256 llvm::DenseMap<Operation *,
257 std::map<DmaQueueModel::ChannelKey, AIE::DMAStartOp>>
258 loopingStarts;
259 // Channels an aiex.dma_channel_reset drained since the latest load.
260 std::set<DmaQueueModel::ChannelKey> resetChannels;
261
262 std::map<DmaQueueModel::ChannelKey, AIE::DMAStartOp> &
263 loopingStartsOf(AIE::DeviceOp device) {
264 auto [it, inserted] = loopingStarts.try_emplace(device);
265 auto &starts = it->second;
266 if (!inserted)
267 return starts;
268 for (AIE::DmaBody program : device.getOps<AIE::DmaBody>()) {
269 AIE::TileID tile = program.getTileID();
270 program->walk([&](AIE::DMAStartOp start) {
271 if (start.getEndpoint())
272 return;
273 llvm::SmallPtrSet<Block *, 8> visited;
274 Block *bd = start.getDest();
275 while (bd && visited.insert(bd).second)
276 bd = bd->getNumSuccessors() == 1 ? bd->getSuccessor(0) : nullptr;
277 if (bd)
278 starts.try_emplace({tile.col, tile.row,
279 static_cast<int>(start.getChannelDir()),
280 start.getChannelIndex()},
281 start);
282 });
283 }
284 return starts;
285 }
286
287 // A task pushed behind a static program that never ends never runs. Only
288 // a named load tells which programs run; the sequence's own device does
289 // until the first load.
290 LogicalResult checkNotBehindLoop(DMAStartTaskOp start,
291 DMAConfigureTaskOp cfg) {
292 if (opaqueLoad)
293 return success();
295 if (resetChannels.count(key))
296 return success();
297 auto &starts =
298 loopingStartsOf(loadedDevice ? loadedDevice : getOperation());
299 auto it = starts.find(key);
300 if (it == starts.end())
301 return success();
302 InFlightDiagnostic diag =
303 start.emitOpError("starts a task on a channel whose static DMA "
304 "program loops forever, so the task never runs; "
305 "end that program's BD chain, or reset the channel "
306 "with aiex.dma_channel_reset first");
307 diag.attachNote(it->second.getLoc()) << "the program starts here";
308 return diag;
309 }
310
311 // The device the latest aiex.npu.load_pdi configured. A sequence that
312 // aie-materialize-runtime-sequences inlined runs on that device's static
313 // DMAs, which stay in it rather than in the device that holds the sequence.
314 AIE::DeviceOp loadedDevice;
315 // The latest aiex.npu.load_pdi, when it names no device in this module.
316 NpuLoadPdiOp opaqueLoad;
317 // Configures from before the latest aiex.npu.load_pdi.
318 llvm::SmallPtrSet<Operation *, 16> unloaded;
319
320 // A PDI load reconfigures the array, so the tasks configured so far no
321 // longer hold ids and allocation restarts around the new static BDs.
322 void noteLoadPdi(NpuLoadPdiOp load) {
323 loadedDevice = loadedBy(load);
324 opaqueLoad = loadedDevice ? NpuLoadPdiOp() : load;
325 configuredDevice = {};
326 resetChannels.clear();
327 for (auto &[tile, tasks] : liveByTile)
328 for (DMAConfigureTaskOp task : tasks)
329 unloaded.insert(task);
330 gens.clear();
331 liveByTile.clear();
332 pendingAwaitReleases.clear();
333 freedInFlight.clear();
334 loadState = {};
335 }
336
337 // Reject control flow the static path cannot lower. Constant-trip scf.for is
338 // unrolled and constant-predicate scf.if is folded before this pass, so any
339 // scf op here is runtime-valued and belongs to the dynamic EmitC path.
340 LogicalResult rejectRuntimeControlFlow(AIE::RuntimeSequenceOp seq) {
341 WalkResult wr = seq.walk([&](Operation *op) -> WalkResult {
342 if (isa<scf::ForOp, scf::IfOp, scf::WhileOp>(op)) {
343 op->emitOpError(
344 "Runtime-valued control flow in a runtime sequence is not "
345 "supported by this static BD-ID allocation pass. Either pass "
346 "only constant-valued predicates to scf.for and scf.if so "
347 "`aie-unroll-runtime-sequence-loops` can unroll/fold them, or "
348 "use the dynamic EmitC path instead.");
349 return WalkResult::interrupt();
350 }
351 return WalkResult::advance();
352 });
353 return failure(wr.wasInterrupted());
354 }
355
356 // Track the two per-channel resources a sequence can exhaust. Their failure
357 // modes differ: over-production costs the TCT FIFO no capacity (see
358 // checkTokensConsumed for what it costs later), but a push onto a full queue
359 // is dropped and its transfer never runs.
360 //
361 // Queue counting differs from token counting in three ways: every push takes
362 // a slot, not just issue_token ones; a non-token push is still retired
363 // implicitly, since in-order execution means awaiting a token drains
364 // everything queued ahead of it too; and a repeat_count does not multiply
365 // slots. rejectRuntimeControlFlow has already run, so one program-order pass
366 // over straight-line IR is exact.
367 LogicalResult verifyChannelUsage(AIE::RuntimeSequenceOp seq) {
368 using ChannelKey = DmaQueueModel::ChannelKey;
369
370 const AIETargetModel &tm =
371 seq->getParentOfType<AIE::DeviceOp>().getTargetModel();
372
373 std::map<ChannelKey, int> avail;
374 DmaQueueModel queue;
375
376 WalkResult wr = seq.walk([&](Operation *op) -> WalkResult {
377 if (auto start = dyn_cast<DMAStartTaskOp>(op)) {
378 DMAConfigureTaskOp cfg = start.getTaskOp();
379 if (!cfg)
380 return WalkResult::advance();
381 ChannelKey key = DmaQueueModel::keyOf(cfg);
382 AIE::TileOp tile = cfg.getTileOp();
383 uint32_t depth = tm.getDmaTaskQueueDepth(
384 tile.getCol(), tile.getRow(), cfg.getChannel(), cfg.getDirection());
385 if (queue.wouldOverflow(key, depth))
386 guardQueueOverflow(queue, start, tm, key, depth, enforceQueueDepth);
387 bool issuesToken = start.getPushIssueToken(cfg);
388 queue.push(key, issuesToken);
389 if (issuesToken)
390 avail[key]++;
391 } else if (auto await = dyn_cast<DMAAwaitTaskOp>(op)) {
392 DMAConfigureTaskOp cfg = await.getTaskOp();
393 // A non-issue_token await is diagnosed later by aie-dma-tasks-to-npu;
394 // an unresolved task is diagnosed by the recycle path. Skip both here.
395 if (!cfg || !cfg.getIssueToken())
396 return WalkResult::advance();
397 ChannelKey key = DmaQueueModel::keyOf(cfg);
398 int &tokens = avail[key];
399 if (tokens < 1) {
400 await.emitOpError(
401 "awaits a task-completion token on a channel where no "
402 "outstanding token is guaranteed to have been produced; the "
403 "runtime sequence would block here forever. Ensure a prior "
404 "issue_token dma_start_task on the same tile, direction and "
405 "channel reaches this await");
406 return WalkResult::interrupt();
407 }
408 tokens--;
409 queue.awaitToken(key);
410 } else if (QueueEffect raw = rawQueueEffect(op, *deviceState.symbols);
411 raw.kind == QueueEffect::Kind::Await) {
412 // A raw wait may consume a token from a push this count cannot see,
413 // such as a raw register write. Do not diagnose those here, but never
414 // reuse a token already consumed by one.
415 avail[raw.key] = std::max(0, avail[raw.key] - 1);
416 queue.awaitToken(raw.key);
417 } else if (raw.kind == QueueEffect::Kind::Push) {
418 avail[raw.key] += raw.issuesToken;
419 queue.push(raw.key, raw.issuesToken);
420 }
421 return WalkResult::advance();
422 });
423 return failure(wr.wasInterrupted());
424 }
425
426 LogicalResult validate(AIE::RuntimeSequenceOp seq) {
427 if (!seq.getBody().hasOneBlock())
428 return seq.emitOpError(
429 "requires a single block for static BD allocation");
430 WalkResult unplaced = seq.walk([](DMAConfigureTaskOp cfg) {
431 if (cfg.getTile().getDefiningOp<AIE::TileOp>())
432 return WalkResult::advance();
433 cfg.emitOpError("Cannot assign buffer descriptor ids to a DMA task "
434 "whose tile is not placed; run placement first.");
435 return WalkResult::interrupt();
436 });
437 if (unplaced.wasInterrupted())
438 return failure();
439 // Reject runtime control flow first, so the token-balance pass below runs
440 // on straight-line IR and needs no control-flow reasoning.
441 if (failed(rejectRuntimeControlFlow(seq)))
442 return failure();
443 if (failed(verifyChannelUsage(seq)))
444 return failure();
445 return success();
446 }
447
448 LogicalResult allocateConfigure(DMAConfigureTaskOp op) {
449 AIE::TileOp tile = op.getTileOp();
450 BdIdGenerator &gen = getGeneratorForTile(tile);
451
452 const AIETargetModel &targetModel =
453 tile->getParentOfType<AIE::DeviceOp>().getTargetModel();
454 uint32_t pool = targetModel.getBdPoolId(tile.getCol(), tile.getRow(),
455 op.getChannel(), op.getDirection());
456
457 // First, honor all the user-specified BD IDs.
458 WalkResult result = op.walk<WalkOrder::PreOrder>([&](AIE::DMABDOp bd_op) {
459 if (bd_op.getBdId().has_value()) {
460 if (!targetModel.isBdChannelAccessible(
461 tile.getCol(), tile.getRow(), bd_op.getBdId().value(),
462 op.getChannel(), op.getDirection())) {
463 InFlightDiagnostic diag = bd_op.emitOpError("Buffer descriptor ID ")
464 << bd_op.getBdId().value()
465 << " cannot be submitted on channel "
466 << op.getChannel();
467 // Before AIE4, only a memtile splits its BDs (by parity).
468 bool dataDir = op.getDirection() == DMAChannelDir::MM2S ||
469 op.getDirection() == DMAChannelDir::S2MM;
470 if (dataDir &&
471 targetModel.getBdPoolId(tile.getCol(), tile.getRow(),
472 op.getChannel(), DMAChannelDir::MM2S) ==
473 targetModel.getBdPoolId(tile.getCol(), tile.getRow(),
474 op.getChannel(),
475 DMAChannelDir::S2MM)) {
476 diag << " of tile (" << tile.getCol() << "," << tile.getRow()
477 << "), which partitions its buffer descriptors by channel "
478 "parity: an even channel reaches only the low half of the "
479 "ids and an odd channel only the high half.";
480 return WalkResult::interrupt();
481 }
482 auto [first, last] = targetModel.getBdIdRangeForChannel(
483 tile.getCol(), tile.getRow(), op.getChannel(), op.getDirection());
484 diag << " (" << stringifyDMAChannelDir(op.getDirection())
485 << ") of tile (" << tile.getCol() << "," << tile.getRow()
486 << "), whose BD pool holds ids " << first << " to " << last - 1
487 << ".";
488 return WalkResult::interrupt();
489 }
490 if (const HeldBy *held =
491 copyHolding(tile.getTileID(), pool, bd_op.getBdId().value())) {
492 InFlightDiagnostic diag =
493 op.emitOpError("Specified buffer descriptor ID ")
494 << bd_op.getBdId().value()
495 << " is the one an aiex.npu.dma_memcpy_nd on this tile "
496 "programs, and that copy may still be in flight here. Give "
497 "the task another ID, or retire the copy first: ";
498 diag << (held->issuesToken ? kWaitForToken : kNoTokenAdvice);
499 diag.attachNote(held->copy->getLoc()) << "the copy is here";
500 return WalkResult::interrupt();
501 }
502 if (gen.bdIdAlreadyAssigned(op.getChannel(), op.getDirection(),
503 bd_op.getBdId().value()) ||
504 gen.isReserved(op.getChannel(), op.getDirection(),
505 bd_op.getBdId().value())) {
506 op.emitOpError("Specified buffer descriptor ID ")
507 << bd_op.getBdId().value()
508 << " is already in use. Release the earlier task first: "
509 "aiex.dma_await_task waits for hardware completion before its "
510 "BDs are reusable. aiex.dma_free_task also releases them but "
511 "does NOT wait, so it is only safe when some other "
512 "synchronization already guarantees that task has finished "
513 "(see programming_guide/section-2/section-2d/DMATasks.md).";
514 return WalkResult::interrupt();
515 }
516 checkReallocation(tile, op.getChannel(), op.getDirection(),
517 bd_op.getBdId().value(), bd_op.getLoc());
518 gen.assignBdId(op.getChannel(), op.getDirection(),
519 bd_op.getBdId().value());
520 }
521 return WalkResult::advance();
522 });
523 if (result.wasInterrupted())
524 return failure();
525
526 AIE::DMABDOp head = op.getFirstBd();
527 uint32_t headAlignment = DMAStartTaskOp::headBdIdAlignment(op.getResult());
528
529 // The ids a copy reprograms while this task may run are not its to take,
530 // including any a reclaim frees on the way.
531 SmallVector<int32_t> blocked;
532 auto block = [&] {
533 auto it = forbidden.find(op);
534 if (it == forbidden.end())
535 return;
536 for (auto [id, copy] : it->second)
537 if (!gen.bdIdAlreadyAssigned(op.getChannel(), op.getDirection(), id)) {
538 gen.assignBdId(op.getChannel(), op.getDirection(), id);
539 blocked.push_back(id);
540 }
541 };
542 block();
543 unsigned tookBack = 0;
544
545 // Now allocate BD IDs for all unspecified BDs.
546 result = op.walk<WalkOrder::PreOrder>([&](AIE::DMABDOp bd_op) {
547 if (bd_op.getBdId().has_value())
548 return WalkResult::advance();
549 if (opaqueLoad) {
550 bd_op.emitOpError(
551 "needs a buffer descriptor ID, but the aiex.npu.load_pdi "
552 "before it does not name a device in this module, so the "
553 "compiler cannot tell which ids the loaded PDI's static "
554 "DMAs use. Name the loaded device with device_ref = "
555 "@<device>, or give this aie.dma_bd a bd_id that the PDI "
556 "leaves free.")
557 .attachNote(opaqueLoad.getLoc())
558 << "the PDI is loaded here";
559 return WalkResult::interrupt();
560 }
561 uint32_t alignment = bd_op == head ? headAlignment : 1;
562 std::optional<int32_t> next_id =
563 gen.nextBdId(op.getChannel(), op.getDirection(), alignment);
564 while (!next_id && reclaimBds && succeeded(reclaimFor(op))) {
565 ++tookBack;
566 block();
567 next_id = gen.nextBdId(op.getChannel(), op.getDirection(), alignment);
568 }
569 if (!next_id) {
570 auto diag =
571 op.emitOpError()
572 << "Too many simultaneously active buffer descriptors on tile ("
573 << tile.getCol() << "," << tile.getRow()
574 << "), which supports up to "
575 << targetModel.getNumBDsForChannel(tile.getCol(), tile.getRow(),
576 op.getChannel(),
577 op.getDirection())
578 << ".";
579 SmallVector<std::tuple<int32_t, Operation *, bool>> copied;
580 if (auto it = forbidden.find(op); it != forbidden.end())
581 for (auto [id, copy] : it->second)
582 if (llvm::is_contained(blocked, id))
583 copied.push_back({id, copy, true});
584 for (auto [owner, heldPool, id] : loadState.copyOwned)
585 if (owner == tile.getTileID() && heldPool == pool)
586 copied.push_back(
587 {id, copyHolding(tile.getTileID(), pool, id)->copy, false});
588 llvm::sort(copied);
589 if (!copied.empty()) {
590 diag << " Of those, aiex.npu.dma_memcpy_nd ops program "
591 << (copied.size() > 1 ? "ids " : "id ");
592 llvm::interleaveComma(
593 copied, diag, [&](auto &entry) { diag << std::get<0>(entry); });
594 diag << " while this task may run (see the notes).";
595 }
596 // reclaimFor only ever considers a liveByTile task, never a copy, so
597 // its advice -- and the task-shaped reasons it failed -- apply only
598 // where some other task actually lives on this tile to reclaim from.
599 bool otherLiveTask = llvm::any_of(
600 liveByTile[tile.getTileID()],
601 [&](DMAConfigureTaskOp t) { return !releasedTasks.contains(t); });
602 if (otherLiveTask) {
603 diag << " Emit an aiex.dma_await_task to free BDs for reuse; it "
604 "waits for hardware completion, so the recycled ids are no "
605 "longer in flight. aiex.dma_free_task also recycles ids but "
606 "does NOT wait for completion -- using it before the task "
607 "has finished is a race -- so reach for it only when some "
608 "other synchronization already guarantees completion (see "
609 "programming_guide/section-2/section-2d/DMATasks.md).";
610 if (reclaimBds && tookBack)
611 diag << " The ids the compiler took back did not cover it, and "
612 "it could not take more: every other task holding one is "
613 "not started yet, is started again later, waits on a "
614 "lock this or a later task releases, or runs on a "
615 "channel whose status it cannot poll.";
616 else if (reclaimBds)
617 diag << " The compiler could not take any back either: every "
618 "task holding one is not started yet, is started again "
619 "later, waits on a lock this or a later task releases, "
620 "or runs on a channel whose status it cannot poll.";
621 else
622 diag << " Or let the compiler poll for finished tasks and take "
623 "their ids (reclaim-bds, aiecc --reclaim-runtime-bds), "
624 "provided no task depends on a push issued after it.";
625 } else if (!copied.empty()) {
626 diag << " Every id in use here is an aiex.npu.dma_memcpy_nd copy "
627 "(reclaim-bds does not consider those); retire the ones "
628 "the notes name, or give this task's buffer descriptors "
629 "other ids.";
630 }
631 for (auto [id, copyOp, isForbidden] : copied) {
632 auto copy = cast<NpuDmaMemcpyNdOp>(copyOp);
633 Diagnostic &note = diag.attachNote(copy.getLoc());
634 note << "this copy " << (isForbidden ? "reprograms" : "holds")
635 << " buffer descriptor ID " << id
636 << (isForbidden ? " while the task may run; "
637 : " until it is retired: ");
638 note << (rawQueueEffect(copy, *deviceState.symbols).issuesToken
639 ? kWaitForToken
640 : kNoTokenAdvice);
641 }
642 return WalkResult::interrupt();
643 }
644 checkReallocation(tile, op.getChannel(), op.getDirection(), *next_id,
645 bd_op.getLoc());
646 bd_op.setBdId(next_id);
647 roundState.assignedHere.push_back(bd_op);
648 return WalkResult::advance();
649 });
650 for (int32_t id : blocked)
651 gen.freeBdId(op.getChannel(), op.getDirection(), id);
652 if (result.wasInterrupted())
653 return failure();
654
655 liveByTile[tile.getTileID()].push_back(op);
656 return success();
657 }
658
659 // One push onto a channel: the task it started (null for a raw push or
660 // memcpy transfer) and whether that push issues a token. A task started more
661 // than once may issue a token on only some of its pushes.
662 struct StartedTask {
663 DMAConfigureTaskOp task;
664 Operation *origin;
665 bool issuesToken;
666 // Program order of the push, for picking the oldest task to reclaim.
667 uint64_t order;
668 };
669 // Pushes on a channel, in program order, whose tokens no await has consumed
670 // yet. A status poll proves a prefix of them finished, the first `finished`;
671 // their tokens, if any, still wait for an await, so they stay here until one
672 // consumes them.
673 struct ChannelPushes {
674 SmallVector<StartedTask, 8> tasks;
675 size_t finished = 0;
676 };
677 std::map<DmaQueueModel::ChannelKey, ChannelPushes> startedOnChannel;
678 uint64_t pushCount = 0;
679 // Per configure, its pushes in startedOnChannel, how many of them are not
680 // yet finished, and the order of its latest one. A configure pushes onto
681 // its own channel alone.
682 struct PushCounts {
683 unsigned started = 0;
684 unsigned running = 0;
685 uint64_t lastPushOrder = 0;
686 };
687 llvm::DenseMap<Operation *, PushCounts> pushCounts;
688
689 struct TaskTriple {
690 DMAConfigureTaskOp configure;
691 DMAStartTaskOp start;
692 DMAAwaitTaskOp await;
693 };
694 struct TaskSchedule {
695 Block *block;
696 Operation *after;
697 SmallVector<SmallVector<TaskTriple>> chains;
698 SmallVector<std::pair<size_t, bool>> events;
699 };
700
701 static std::optional<TaskTriple> taskTriple(Operation *operation) {
702 auto configure = dyn_cast_or_null<DMAConfigureTaskOp>(operation);
703 auto await = configure ? taskTripleAwait(operation) : DMAAwaitTaskOp();
704 if (!await)
705 return std::nullopt;
706 return TaskTriple{configure, cast<DMAStartTaskOp>(configure->getNextNode()),
707 await};
708 }
709
710 bool fitsNow(DMAConfigureTaskOp configure) {
711 if (opaqueLoad)
712 return false;
713 BdIdGenerator available = getGeneratorForTile(configure.getTileOp());
714 for (auto [id, copy] : forbidden.lookup(configure))
715 available.reserveBdId(configure.getChannel(), configure.getDirection(),
716 id);
717 return available
718 .nextBdId(configure.getChannel(), configure.getDirection(),
719 DMAStartTaskOp::headBdIdAlignment(configure.getResult()))
720 .has_value();
721 }
722
723 LogicalResult
724 allocateDeferredTasks(ArrayRef<TaskTriple> tasks,
725 llvm::function_ref<WalkResult(Operation *)> visit) {
726 std::map<DmaQueueModel::ChannelKey, SmallVector<TaskTriple>> channels;
727 for (TaskTriple task : tasks)
728 channels[DmaQueueModel::keyOf(task.configure)].push_back(task);
729 TaskSchedule schedule{tasks.front().configure->getBlock(),
730 tasks.back().await->getNextNode(),
731 {},
732 {}};
733 std::map<DmaQueueModel::ChannelKey, size_t> next;
734 std::map<DmaQueueModel::ChannelKey, std::deque<size_t>> pending;
735 std::map<DmaQueueModel::ChannelKey, size_t> windows;
736 uint32_t depth = getOperation().getTargetModel().getDmaTaskQueueDepth();
737 for (const auto &[key, list] : channels) {
738 const ChannelPushes &channel = startedOnChannel[key];
739 windows[key] =
740 chainTasks ? 1 : depth - (channel.tasks.size() - channel.finished);
741 }
742 auto retire = [&](std::deque<size_t> &queue) -> LogicalResult {
743 size_t index = queue.front();
744 for (TaskTriple task : schedule.chains[index])
745 if (visit(task.await).wasInterrupted())
746 return failure();
747 windows[DmaQueueModel::keyOf(schedule.chains[index].front().configure)] =
748 chainTasks ? 1 : depth;
749 schedule.events.emplace_back(index, true);
750 queue.pop_front();
751 return success();
752 };
753 size_t remaining = tasks.size();
754 while (remaining) {
755 bool progress = false;
756 for (auto &[key, list] : channels) {
757 size_t &position = next[key];
758 if (position == list.size())
759 continue;
760 auto &queue = pending[key];
761 if (queue.size() >= windows[key] && failed(retire(queue)))
762 return failure();
763 SmallVector<TaskTriple> chain;
764 while (position < list.size() && fitsNow(list[position].configure)) {
765 TaskTriple task = list[position];
766 if (!chain.empty() &&
767 (task.configure->getAttrDictionary() !=
768 chain.front().configure->getAttrDictionary() ||
769 task.configure.getPacketAttr() !=
770 chain.front().configure.getPacketAttr()))
771 break;
772 if (visit(task.configure).wasInterrupted())
773 return failure();
774 chain.push_back(task);
775 ++position;
776 --remaining;
777 if (!chainTasks)
778 break;
779 }
780 if (chain.empty())
781 continue;
782 for (TaskTriple task : chain)
783 if (visit(task.start).wasInterrupted())
784 return failure();
785 size_t index = schedule.chains.size();
786 schedule.chains.push_back(std::move(chain));
787 schedule.events.emplace_back(index, false);
788 queue.push_back(index);
789 progress = true;
790 }
791 if (!progress) {
792 auto waiting = llvm::find_if(
793 pending, [](const auto &entry) { return !entry.second.empty(); });
794 if (waiting == pending.end() || failed(retire(waiting->second)))
795 return failure();
796 }
797 }
798 for (auto &[key, queue] : pending)
799 while (!queue.empty())
800 if (failed(retire(queue)))
801 return failure();
802 roundState.schedules.push_back(std::move(schedule));
803 return success();
804 }
805
806 static void commitSchedule(TaskSchedule &schedule) {
807 for (auto &chain : schedule.chains) {
808 TaskTriple first = chain.front();
809 for (TaskTriple task : llvm::drop_begin(chain)) {
810 Operation *end = first.configure.getBody().back().getTerminator();
811 OpBuilder builder(end);
812 AIE::NextBDOp::create(builder, end->getLoc(),
813 &task.configure.getBody().front());
814 end->erase();
815 first.configure.getBody().getBlocks().splice(
816 first.configure.getBody().end(),
817 task.configure.getBody().getBlocks());
818 task.await.erase();
819 task.start.erase();
820 task.configure.erase();
821 }
822 }
823 auto insertion =
824 schedule.after ? schedule.after->getIterator() : schedule.block->end();
825 for (auto [index, await] : schedule.events) {
826 TaskTriple first = schedule.chains[index].front();
827 if (await) {
828 first.await.removeDeferCompletionAttr();
829 first.await->moveBefore(schedule.block, insertion);
830 } else {
831 first.configure->moveBefore(schedule.block, insertion);
832 first.start->moveBefore(schedule.block, insertion);
833 }
834 }
835 }
836
837 void notePush(const DmaQueueModel::ChannelKey &key, DMAConfigureTaskOp task,
838 bool issuesToken, Operation *origin,
839 AIE::ShimDMAAllocationOp allocation,
840 std::optional<Volume> moved) {
841 uint64_t order = pushCount++;
842 startedOnChannel[key].tasks.push_back({task, origin, issuesToken, order});
843 if (task) {
844 PushCounts &counts = pushCounts[task];
845 ++counts.started;
846 ++counts.running;
847 counts.lastPushOrder = order;
848 }
849 if (!allocation)
850 return;
851 auto &pushes = loadState.pushesByAllocation[allocation];
852 std::optional<Volume> through =
853 pushes.empty() ? Volume() : pushes.back().through;
854 if (through && moved)
855 for (auto [term, bytes] : *moved)
856 (*through)[term] += bytes;
857 else
858 through = std::nullopt;
859 pushes.push_back({order, through});
860 }
861 // Configures whose completion an await has established.
862 llvm::SmallPtrSet<Operation *, 16> knownComplete;
863 // Configures a status poll, or the consumption an output's await proves
864 // (#aie.consumed_by), shows finished. Kept apart from knownComplete so that
865 // the ids an await releases do not move.
866 llvm::SmallPtrSet<Operation *, 16> provenFinished;
867 // Configures whose ids reclaimFor took back.
868 llvm::SmallPtrSet<Operation *, 16> reclaimed;
869 // Configures whose ids went back to the pool by any route.
870 llvm::SmallPtrSet<Operation *, 16> releasedTasks;
871 // State scoped to one allocation attempt of one sequence: reset by
872 // assignment in resetPerSequenceState, which runs again for each
873 // reallocation round within a sequence.
874 struct RoundState {
875 // Each top-level op's place in the sequence, and per lock the last place
876 // a task releasing it is configured or started (see reclaimFor).
877 llvm::DenseMap<Operation *, unsigned> positionOf;
878 llvm::DenseMap<Value, unsigned> lastReleaseOf;
879 bool reallocate = false;
880 // What one allocation of the sequence did that the next undoes.
881 SmallVector<AIE::DMABDOp> assignedHere;
882 SmallVector<Operation *> insertedHere;
883 SmallVector<TaskSchedule> schedules;
884 };
885 RoundState roundState;
886
887 void indexLockReleases(AIE::RuntimeSequenceOp seq) {
888 unsigned position = 0;
889 for (Operation &op : seq.getBody().getOps()) {
890 roundState.positionOf[&op] = position++;
891 DMAConfigureTaskOp cfg = dyn_cast<DMAConfigureTaskOp>(op);
892 if (auto start = dyn_cast<DMAStartTaskOp>(op))
893 cfg = start.getTaskOp();
894 if (!cfg)
895 continue;
896 cfg.walk([&](AIE::UseLockOp lock) {
897 if (lock.release())
898 roundState.lastReleaseOf[lock.getLock()] = roundState.positionOf[&op];
899 });
900 }
901 }
902
903 // Configures allocated on each tile, in program order.
904 llvm::DenseMap<AIE::TileID, SmallVector<DMAConfigureTaskOp, 16>> liveByTile;
905
906 // An aiex.npu.dma_memcpy_nd's BD id is held on its tile from its push until
907 // the queue model counts that push finished. Holds are kept per channel in
908 // push order, so they retire as a prefix; per (tile, pool, id), the copies
909 // holding it by push order, and whether they took it in the generator.
910 struct CopyHold {
911 uint64_t order;
912 AIE::TileID tile;
913 uint32_t pool;
914 int32_t id;
915 };
916 using TileBdId = std::tuple<AIE::TileID, uint32_t, int32_t>;
917 struct HeldBy {
918 NpuDmaMemcpyNdOp copy;
919 bool issuesToken;
920 };
921 // Per configure, the ids it may not take and the copy that reprograms each
922 // while it may run.
923 llvm::DenseMap<Operation *, SmallVector<std::pair<int32_t, Operation *>>>
924 forbidden;
925
926 // The oldest copy still holding (`tile`, `pool`, `id`), if any.
927 const HeldBy *copyHolding(AIE::TileID tile, uint32_t pool, int32_t id) const {
928 if (!loadState.copyOwned.contains({tile, pool, id}))
929 return nullptr;
930 return &loadState.holdsOn.find({tile, pool, id})->second.begin()->second;
931 }
932
933 // Return `task`'s id to its pool; a copy waiting for it takes it at once.
934 void releaseTaskBdId(AIE::TileID tile, BdIdGenerator &gen,
935 DMAConfigureTaskOp task, int32_t id) {
936 gen.freeBdId(task.getChannel(), task.getDirection(), id);
937 uint32_t pool = gen.targetModel.getBdPoolId(
938 gen.col, gen.row, task.getChannel(), task.getDirection());
939 if (!loadState.holdsOn.contains({tile, pool, id}))
940 return;
941 gen.assignBdId(task.getChannel(), task.getDirection(), id);
942 loadState.copyOwned.insert({tile, pool, id});
943 }
944
945 static DMAStartTaskOp startAfter(DMAConfigureTaskOp task, Operation *op) {
946 DMAStartTaskOp first;
947 for (Operation *user : task.getResult().getUsers())
948 if (auto start = dyn_cast<DMAStartTaskOp>(user);
949 start && start->getBlock() == op->getBlock() &&
950 op->isBeforeInBlock(start) &&
951 (!first || start->isBeforeInBlock(first)))
952 first = start;
953 return first;
954 }
955
956 // The copy reprograms its BD at once, so a task on that id must neither be
957 // in flight nor be started again after it.
958 LogicalResult holdCopy(NpuDmaMemcpyNdOp copy,
959 const DmaQueueModel::ChannelKey &key, uint64_t order,
960 bool issuesToken) {
961 AIE::ShimDMAAllocationOp allocation = allocationOf(copy);
962 AIE::TileOp tile = allocation.getTileOp();
963 AIE::TileID tileId = tile.getTileID();
964 auto id = static_cast<int32_t>(copy.getId());
965 auto staticConflict = [&]() -> LogicalResult {
966 InFlightDiagnostic diag =
967 copy.emitOpError("programs buffer descriptor ID ")
968 << id << ", which a static DMA program on tile (" << tile.getCol()
969 << "," << tile.getRow() << ") already uses; give the copy another ID";
970 SmallVector<AIE::DeviceOp, 3> devices{getOperation()};
971 for (AIE::DeviceOp device : {loadedDevice, configuredDevice})
972 if (device && !llvm::is_contained(devices, device))
973 devices.push_back(device);
974 for (AIE::DeviceOp device : devices)
975 for (AIE::DmaBody program : device.getOps<AIE::DmaBody>())
976 if (program.getTileID() == tileId)
977 program.getDmaBody().walk([&](AIE::DMABDOp bd) {
978 if (bd.getBdId() == id)
979 diag.attachNote(bd.getLoc())
980 << "the static program's buffer descriptor is here";
981 });
982 return diag;
983 };
984 int channel = allocation.getChannelIndex();
985 AIE::DMAChannelDir dir = allocation.getChannelDir();
986 BdIdGenerator &gen = getGeneratorForTile(tile);
987 if (gen.isReserved(channel, dir, id))
988 return staticConflict();
989 uint32_t pool = gen.targetModel.getBdPoolId(gen.col, gen.row, channel, dir);
990 if (auto held = loadState.holdsOn.find({tileId, pool, id});
991 held != loadState.holdsOn.end() && warnUnsafeBdReuse) {
992 const HeldBy &earlier = held->second.begin()->second;
993 auto [entry, inserted] = copiesOverCopies.try_emplace(
994 copy.getLoc(),
995 CopyOverCopy{id, tile.getCol(), tile.getRow(), earlier.copy->getLoc(),
996 earlier.issuesToken});
997 entry->second.tiles.insert({tile.getCol(), tile.getRow()});
998 entry->second.count++;
999 }
1000 loadState.holdsByChannel[key].push_back({order, tileId, pool, id});
1001 loadState.holdsOn[{tileId, pool, id}][order] = {copy, issuesToken};
1002 if (!gen.bdIdAlreadyAssigned(channel, dir, id)) {
1003 checkReallocation(tile, channel, dir, id, copy.getLoc());
1004 gen.assignBdId(channel, dir, id);
1005 loadState.copyOwned.insert({tileId, pool, id});
1006 return success();
1007 }
1008 if (loadState.copyOwned.contains({tileId, pool, id}))
1009 return success();
1010 for (DMAConfigureTaskOp task : liveByTile[tileId]) {
1011 if (releasedTasks.contains(task) || unloaded.contains(task))
1012 continue;
1013 // A task drawing from another pool holds a different BD of this id.
1014 if (gen.targetModel.getBdPoolId(gen.col, gen.row, task.getChannel(),
1015 task.getDirection()) != pool)
1016 continue;
1017 AIE::DMABDOp held;
1018 task.walk([&](AIE::DMABDOp bd) {
1019 if (bd.getBdId() == id)
1020 held = bd;
1021 });
1022 if (!held)
1023 continue;
1024 bool running = pushCounts.lookup(task).running;
1025 // A task not yet started even once has no prior push to its name: its
1026 // only start landing after the copy is its first, not a restart.
1027 bool everStarted = pushCounts.contains(task);
1028 DMAStartTaskOp restart = startAfter(task, copy);
1029 if (!running && !restart)
1030 return success();
1031 if (!llvm::is_contained(roundState.assignedHere, held)) {
1032 InFlightDiagnostic diag =
1033 task.emitOpError("Specified buffer descriptor ID ") << id;
1034 if (running)
1035 diag << " is the one an aiex.npu.dma_memcpy_nd on this tile "
1036 "programs while this task may be in flight. Give the task "
1037 "another ID, or await it before the copy.";
1038 else if (everStarted)
1039 diag << " is the one an aiex.npu.dma_memcpy_nd on this tile "
1040 "programs before this task is started again, so the "
1041 "restart would run the copy's descriptor. Give the task "
1042 "another ID, or configure a new task after the copy.";
1043 else
1044 diag << " is the one an aiex.npu.dma_memcpy_nd on this tile "
1045 "programs after this task's own configure wrote it, so "
1046 "starting the task would launch the copy's descriptor "
1047 "instead of its own. Give the task another ID, or start it "
1048 "before the copy.";
1049 diag.attachNote(copy.getLoc()) << "the copy is here";
1050 if (!running)
1051 diag.attachNote(restart.getLoc())
1052 << (everStarted ? "the task is started again here"
1053 : "the task starts here, after the copy");
1054 return failure();
1055 }
1056 assert(llvm::none_of(forbidden[task],
1057 [&](auto &entry) { return entry.first == id; }) &&
1058 "a forbidden id was handed out again");
1059 forbidden[task].push_back({id, copy});
1060 roundState.reallocate = true;
1061 return success();
1062 }
1063 // The id was already taken in the generator, owned by neither a copy
1064 // nor a live task: only a static DMA program claims an id that way.
1065 return staticConflict();
1066 }
1067
1068 void releaseRetiredCopies(const DmaQueueModel::ChannelKey &key) {
1069 auto holds = loadState.holdsByChannel.find(key);
1070 if (holds == loadState.holdsByChannel.end())
1071 return;
1072 const ChannelPushes &channel = startedOnChannel[key];
1073 std::optional<uint64_t> oldest;
1074 if (channel.finished < channel.tasks.size())
1075 oldest = channel.tasks[channel.finished].order;
1076 while (!holds->second.empty() &&
1077 (!oldest || holds->second.front().order < *oldest)) {
1078 CopyHold hold = holds->second.front();
1079 holds->second.pop_front();
1080 auto on = loadState.holdsOn.find({hold.tile, hold.pool, hold.id});
1081 on->second.erase(hold.order);
1082 if (!on->second.empty())
1083 continue;
1084 loadState.holdsOn.erase(on);
1085 if (loadState.copyOwned.erase({hold.tile, hold.pool, hold.id}))
1086 gens.find(hold.tile)->second.freeBdId(
1087 key[3], static_cast<AIE::DMAChannelDir>(key[2]), hold.id);
1088 }
1089 }
1090
1091 // BD ids released by aiex.dma_free_task while the task could still have been
1092 // in flight, by tile and (pool, id), with the releasing task and free.
1093 struct ReleasedTask {
1094 DMAConfigureTaskOp configure;
1095 Operation *freeOp;
1096 };
1097 std::map<std::pair<int, int>,
1098 std::map<std::pair<uint32_t, uint32_t>, ReleasedTask>>
1099 freedInFlight;
1100
1101 // An await consumes the oldest outstanding token on the channel, regardless
1102 // of the configure named by its SSA operand. Only that token-issuing task and
1103 // the tasks queued ahead of it are known to have finished.
1104 void noteAwaited(const DmaQueueModel::ChannelKey &key) {
1105 ChannelPushes &channel = startedOnChannel[key];
1106 auto &started = channel.tasks;
1107 auto *it = llvm::find_if(
1108 started, [](const StartedTask &s) { return s.issuesToken; });
1109 if (it == started.end())
1110 return;
1111 size_t retired = std::distance(started.begin(), it) + 1;
1112 for (size_t i = 0; i < retired; ++i)
1113 if (DMAConfigureTaskOp task = started[i].task) {
1114 --pushCounts[task].started;
1115 if (i >= channel.finished)
1116 --pushCounts[task].running;
1117 }
1118 for (size_t i = 0; i < retired; ++i)
1119 if (DMAConfigureTaskOp task = started[i].task)
1120 if (pushCounts.lookup(task).started == 0)
1121 knownComplete.insert(task);
1122 // Counts are cumulative, so the newest push an allocation retired here
1123 // credits all that its older ones would.
1124 SmallVector<std::pair<AIE::ShimDMAAllocationOp, uint64_t>> newest;
1125 for (const StartedTask &push :
1126 llvm::reverse(llvm::make_range(started.begin(), std::next(it))))
1127 if (AIE::ShimDMAAllocationOp output =
1128 push.task ? allocationOf(push.task)
1129 : allocationOf(dyn_cast<NpuDmaMemcpyNdOp>(push.origin)))
1130 if (llvm::none_of(newest,
1131 [&](auto &seen) { return seen.first == output; }))
1132 newest.push_back({output, push.order});
1133 started.erase(started.begin(), std::next(it));
1134 channel.finished -= std::min(channel.finished, retired);
1135 for (auto [output, order] : newest)
1136 creditInputs(output, order);
1137 releaseRetiredCopies(key);
1138 }
1139
1140 // A status poll, or consumption an output proves, shows at most
1141 // `unfinished` pushes on `key` still queued or running. The channel runs its
1142 // queue in order, so those are the newest.
1143 void noteDrained(const DmaQueueModel::ChannelKey &key, size_t unfinished) {
1144 ChannelPushes &channel = startedOnChannel[key];
1145 if (channel.tasks.size() <= unfinished)
1146 return;
1147 for (size_t done = channel.tasks.size() - unfinished;
1148 channel.finished < done; ++channel.finished)
1149 if (DMAConfigureTaskOp task = channel.tasks[channel.finished].task)
1150 if (--pushCounts[task].running == 0)
1151 provenFinished.insert(task);
1152 releaseRetiredCopies(key);
1153 }
1154
1155 // The output bytes `proof` lets count: `received` rounded down to a
1156 // multiple of its granule, at least `received` - (granule - 1).
1157 static Volume countedOutput(const Volume &received,
1158 AIE::ConsumedByAttr proof) {
1159 int64_t granule = proof.getGranuleBytes();
1160 Volume counted = received;
1161 if (!wholeGranules(received, granule))
1162 counted[-1] -= granule - 1;
1163 return counted;
1164 }
1165
1166 // Whether the host library holds the scratchpad parameter `seq` reads at
1167 // state-table index `index` at 0 or above. Commands that never run together
1168 // share slots, so where `seq` does not list what it reads, every parameter
1169 // on the slot must be.
1170 bool nonNegative(AIE::RuntimeSequenceOp seq, int64_t index) {
1171 auto [it, inserted] = deviceState.nonNegativeByIndex.try_emplace(
1172 {seq.getOperation(), index}, false);
1173 if (!inserted)
1174 return it->second;
1175 auto module = getOperation()->getParentOfType<ModuleOp>();
1176 if (!module)
1177 return false;
1178 ArrayAttr reads = seq.getScratchpadParametersAttr();
1179 bool found = false, held = true;
1180 for (auto parameter : module.getOps<ScratchpadParameterOp>()) {
1181 if (parameter.getStateTableIdx() != index ||
1182 (reads &&
1183 !llvm::is_contained(reads.getAsValueRange<FlatSymbolRefAttr>(),
1184 parameter.getSymName())))
1185 continue;
1186 std::optional<int32_t> min = parameter.getMinValue();
1187 found = true;
1188 held &= min && *min >= 0;
1189 }
1190 it->second = found && held;
1191 return it->second;
1192 }
1193
1194 // The bytes one push of `cfg` by `start` moves, or nullopt where its chain
1195 // loops, iterates, continues outside its body, or takes its length from a
1196 // parameter not held non-negative.
1197 std::optional<Volume> pushVolume(DMAStartTaskOp start,
1198 DMAConfigureTaskOp cfg) {
1199 std::optional<int64_t> repeat =
1200 start.hasRepeatParameter()
1201 ? std::nullopt
1202 : getConstantIntValue(start.getPushRepeatCount(cfg));
1203 Region &body = cfg.getBody();
1204 if (!repeat || *repeat < 0 || body.empty())
1205 return std::nullopt;
1206 Volume bytes;
1207 llvm::SmallPtrSet<Block *, 8> seen;
1208 for (Block *block = &body.front(); block;) {
1209 if (!seen.insert(block).second)
1210 return std::nullopt;
1211 for (AIE::DMABDOp bd : block->getOps<AIE::DMABDOp>()) {
1212 std::optional<int64_t> len = bd.getStaticLenInBytes();
1213 if (!len || bd.getIteration() || bd.getNextBdId() ||
1214 bd.getLengthParameterAttr())
1215 return std::nullopt;
1216 int64_t width = bd.getBufferElementTypeWidthInBytes();
1217 bytes[-1] += *len;
1218 if (std::optional<uint8_t> index = bd.getLengthStateTableIdx()) {
1219 std::optional<int32_t> unit = bd.getLengthUnit();
1220 if (!unit ||
1221 !nonNegative(start->getParentOfType<AIE::RuntimeSequenceOp>(),
1222 *index))
1223 return std::nullopt;
1224 bytes[*index] += static_cast<int64_t>(*unit) * width;
1225 }
1226 }
1227 auto next = dyn_cast<AIE::NextBDOp>(block->getTerminator());
1228 block = next ? next.getDest() : nullptr;
1229 }
1230 for (auto &[key, coefficient] : bytes)
1231 if (llvm::MulOverflow(coefficient, *repeat + 1, coefficient))
1232 return std::nullopt;
1233 return bytes;
1234 }
1235
1236 // The bytes one push of `copy` moves, or nullopt unless all its sizes are
1237 // constants.
1238 static std::optional<Volume> copyVolume(NpuDmaMemcpyNdOp copy) {
1239 std::optional<int64_t> bytes = copy.getStaticBytesStreamed();
1240 if (!bytes)
1241 return std::nullopt;
1242 Volume volume;
1243 volume[-1] = *bytes;
1244 return volume;
1245 }
1246
1247 // State whose lifetime is this device's whole processing in runOnOperation,
1248 // independent of which sequence or load is being walked: reset by
1249 // assignment there, so a new field is reset without a hand-kept list.
1250 struct DeviceState {
1251 // The device's symbols; a task names one of its own device's
1252 // allocations. runOnOperation sets this before visiting any op.
1253 std::optional<SymbolTable> symbols;
1254 // Each output's proofs, with the input that holds each.
1255 llvm::DenseMap<
1256 Operation *,
1257 SmallVector<std::pair<AIE::ShimDMAAllocationOp, AIE::ConsumedByAttr>>>
1258 proofsByOutput;
1259 // Whether leavesNothing already proved (input, output) balanced, valid
1260 // for the device's lifetime since nothing it depends on changes per
1261 // sequence.
1262 llvm::DenseMap<std::pair<Operation *, Operation *>, bool> balancedPairs;
1263 // nonNegative's memo.
1264 llvm::DenseMap<std::pair<Operation *, int64_t>, bool> nonNegativeByIndex;
1265 };
1266 DeviceState deviceState;
1267
1268 // The shim allocation `cfg` was configured for, when substitution kept it.
1269 AIE::ShimDMAAllocationOp allocationOf(DMAConfigureTaskOp cfg) {
1270 FlatSymbolRefAttr alloc = cfg.getAllocAttr();
1271 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
1272 return alloc ? deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1273 alloc.getAttr())
1274 : nullptr;
1275 }
1276
1277 // The shim allocation `copy` moves through.
1278 AIE::ShimDMAAllocationOp allocationOf(NpuDmaMemcpyNdOp copy) {
1279 if (!copy)
1280 return nullptr;
1281 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
1282 return deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1283 copy.getMetadata().getRootReference());
1284 }
1285
1286 // A shim allocation's pushes since the latest load, in program order, with
1287 // the bytes it has moved through each: nullopt from the first whose bytes
1288 // are unknown.
1289 struct AllocationPush {
1290 uint64_t order;
1291 std::optional<Volume> through;
1292 };
1293 // Per output, the bytes moved through its newest push an await retired since
1294 // the latest load (nullopt where unknown), and how many pushes the sequence
1295 // had issued by that await.
1296 struct Awaited {
1297 std::optional<Volume> through;
1298 uint64_t pushesBefore;
1299 };
1300 // State valid for one "loaded device" span: wiped at the per-sequence
1301 // reset and again whenever a new aiex.npu.load_pdi reconfigures the array.
1302 struct LoadState {
1303 llvm::DenseMap<Operation *, SmallVector<AllocationPush>> pushesByAllocation;
1304 // Per (input, output), how many of the input's pushes that output has
1305 // already proven taken: both counts only grow, so a credit resumes there.
1306 llvm::DenseMap<std::pair<Operation *, Operation *>, size_t> creditedPushes;
1307 llvm::DenseMap<Operation *, Awaited> awaitedThrough;
1308 std::map<DmaQueueModel::ChannelKey, std::deque<CopyHold>> holdsByChannel;
1309 llvm::DenseMap<TileBdId, std::map<uint64_t, HeldBy>> holdsOn;
1310 llvm::DenseSet<TileBdId> copyOwned;
1311 };
1312 LoadState loadState;
1313
1314 // Whether every stretch of every runtime sequence of this device, from its
1315 // start or a load to the next load or its end, ends with all of `input`'s
1316 // bytes covered by `output`'s under `proof`. The counts restart at each
1317 // stretch, but a load of the PDI already loaded leaves the array as it was,
1318 // so a stretch starts where the previous one, perhaps another dispatch's,
1319 // left it, and its counts hold only when none leaves input bytes behind.
1320 // They count only the two allocations' own tasks, so any other push on
1321 // either channel, in any sequence, voids the pair.
1322 bool leavesNothing(AIE::ShimDMAAllocationOp input,
1323 AIE::ShimDMAAllocationOp output,
1324 AIE::ConsumedByAttr proof) {
1325 auto entry = deviceState.balancedPairs.try_emplace({input, output}, true);
1326 if (entry.second)
1327 entry.first->second = llvm::all_of(
1328 getOperation().getOps<AIE::RuntimeSequenceOp>(),
1329 [&](AIE::RuntimeSequenceOp seq) {
1330 return stretchesUnbalanced(seq, nullptr, proofDevice(proof), input,
1331 output, {input}, {output},
1332 proof) == Unbalanced::No;
1333 });
1334 return entry.first->second;
1335 }
1336
1337 // The device whose array `proof` describes: the one materialization copied
1338 // it from, else this one; none where that device is not in the module.
1339 AIE::DeviceOp proofDevice(AIE::ConsumedByAttr proof) {
1340 FlatSymbolRefAttr device = proof.getDevice();
1341 Operation *module = getOperation()->getParentOp();
1342 if (!device)
1343 return getOperation();
1344 return module ? SymbolTable::lookupNearestSymbolFrom<AIE::DeviceOp>(module,
1345 device)
1346 : AIE::DeviceOp();
1347 }
1348
1349 // The device `load` configures; none where it names none in the module.
1350 AIE::DeviceOp loadedBy(NpuLoadPdiOp load) {
1351 FlatSymbolRefAttr ref = load.getDeviceRefAttr();
1352 Operation *module = getOperation()->getParentOp();
1353 return ref && module ? SymbolTable::lookupNearestSymbolFrom<AIE::DeviceOp>(
1354 module, ref)
1355 : AIE::DeviceOp();
1356 }
1357
1358 // Whether each stretch of `seq` after `from` (all of them when null) with
1359 // `target` loaded ends with the bytes `proof`'s input channel moved covered
1360 // by those its output channel moved. Pushes through `inputs` and `outputs`
1361 // count as the proof's, and with `byChannel` any push on a circuit channel
1362 // (no packet header on it or on `input`/`output`), which carries only that
1363 // route's words; any other on those channels is traffic the proof does not
1364 // describe. Stretches under another PDI end at a real load of `target`.
1365 // `at` receives where the verdict stops, null for the sequence end, and the
1366 // stretch's counts there.
1367 struct Verdict {
1368 Operation *where = nullptr;
1369 Volume in, out;
1370 };
1371 Unbalanced stretchesUnbalanced(
1372 AIE::RuntimeSequenceOp seq, Operation *from, AIE::DeviceOp target,
1373 AIE::ShimDMAAllocationOp input, AIE::ShimDMAAllocationOp output,
1374 ArrayRef<AIE::ShimDMAAllocationOp> inputs,
1375 ArrayRef<AIE::ShimDMAAllocationOp> outputs, AIE::ConsumedByAttr proof,
1376 bool byChannel = false, Verdict *at = nullptr) {
1379 auto fromLoad = dyn_cast_or_null<NpuLoadPdiOp>(from);
1380 AIE::DeviceOp loaded = fromLoad ? loadedBy(fromLoad) : getOperation();
1381 bool counting = !from;
1382 Volume in, out;
1383 Unbalanced why = Unbalanced::No;
1384 seq.walk([&](Operation *op) {
1385 if (op == from) {
1386 counting = true;
1387 return WalkResult::advance();
1388 }
1389 if (!counting)
1390 return WalkResult::advance();
1391 if (auto load = dyn_cast<NpuLoadPdiOp>(op)) {
1392 if (target && loaded == target)
1393 why = balanceUnder(proof, in, out);
1394 if (why != Unbalanced::No) {
1395 if (at)
1396 *at = {op, in, out};
1397 return WalkResult::interrupt();
1398 }
1399 in.clear();
1400 out.clear();
1401 loaded = loadedBy(load);
1402 return WalkResult::advance();
1403 }
1404 if (!target || loaded != target)
1405 return WalkResult::advance();
1406 auto start = dyn_cast<DMAStartTaskOp>(op);
1407 DMAConfigureTaskOp cfg = start ? start.getTaskOp() : nullptr;
1408 auto copy = dyn_cast<NpuDmaMemcpyNdOp>(op);
1409 AIE::ShimDMAAllocationOp allocation =
1410 cfg ? allocationOf(cfg) : allocationOf(copy);
1411 std::optional<DmaQueueModel::ChannelKey> channel;
1412 if (cfg)
1413 channel = DmaQueueModel::keyOf(cfg);
1414 else if (QueueEffect raw = rawQueueEffect(op, *deviceState.symbols);
1415 raw.kind == QueueEffect::Kind::Push)
1416 channel = raw.key;
1417 bool circuit = byChannel && allocation && !allocation.getPacket();
1418 bool isInput =
1419 llvm::is_contained(inputs, allocation) ||
1420 (circuit && channel && *channel == inKey && !input.getPacket());
1421 bool isOutput =
1422 llvm::is_contained(outputs, allocation) ||
1423 (circuit && channel && *channel == outKey && !output.getPacket());
1424 if ((channel && ((*channel == inKey && !isInput) ||
1425 (*channel == outKey && !isOutput))) ||
1426 writesQueue(op, {inKey, outKey})) {
1427 why = Unbalanced::Traffic;
1428 if (at)
1429 *at = {op, in, out};
1430 return WalkResult::interrupt();
1431 }
1432 if (!allocation || (!isInput && !isOutput))
1433 return WalkResult::advance();
1434 // A dynamic-pool sequence keeps its loops, whose trip counts these
1435 // counts cannot follow.
1436 std::optional<Volume> moved = op->getParentOp() != seq ? std::nullopt
1437 : cfg ? pushVolume(start, cfg)
1438 : copyVolume(copy);
1439 if (!moved) {
1440 why = Unbalanced::Unsized;
1441 if (at)
1442 *at = {op, in, out};
1443 return WalkResult::interrupt();
1444 }
1445 for (auto [key, bytes] : *moved)
1446 (isInput ? in : out)[key] += bytes;
1447 return WalkResult::advance();
1448 });
1449 if (why == Unbalanced::No && target && loaded == target)
1450 why = balanceUnder(proof, in, out);
1451 if (at && why != Unbalanced::No && !at->where)
1452 *at = {nullptr, in, out};
1453 return why;
1454 }
1455
1456 // Ending on another device's PDI hands that array on as leavesNothing
1457 // describes, so the last stretch is held to the loaded device's own proofs,
1458 // read off it as seedFromStaticBds reads its BDs: pushes on a proof's
1459 // channels count through the copies materialization stamped with it, and
1460 // any other there is traffic the proof does not describe.
1461 LogicalResult checkForeignTail(AIE::RuntimeSequenceOp seq) {
1462 NpuLoadPdiOp last;
1463 for (auto load : seq.getOps<NpuLoadPdiOp>())
1464 last = load;
1465 AIE::DeviceOp loaded = last ? loadedBy(last) : AIE::DeviceOp();
1466 if (!loaded || loaded == getOperation())
1467 return success();
1468 SmallVector<std::tuple<AIE::ShimDMAAllocationOp, AIE::ShimDMAAllocationOp,
1469 Unbalanced>>
1470 unbalanced;
1471 for (auto input : loaded.getOps<AIE::ShimDMAAllocationOp>()) {
1472 ArrayAttr proofs = input.getConsumedByAttr();
1473 if (!proofs)
1474 continue;
1475 for (auto proof : proofs.getAsRange<AIE::ConsumedByAttr>()) {
1476 auto output = AIE::ShimDMAAllocationOp::getForSymbol(
1477 loaded, proof.getOutput().getValue());
1478 if (!output || proof.getDevice())
1479 continue;
1480 SmallVector<AIE::ShimDMAAllocationOp> inputs, outputs;
1481 for (auto copy : getOperation().getOps<AIE::ShimDMAAllocationOp>()) {
1482 ArrayAttr copied = copy.getConsumedByAttr();
1483 if (!copied ||
1484 DmaQueueModel::keyOf(copy) != DmaQueueModel::keyOf(input))
1485 continue;
1486 for (auto cp : copied.getAsRange<AIE::ConsumedByAttr>()) {
1487 if (proofDevice(cp) != loaded)
1488 continue;
1489 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
1490 auto out = deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1491 cp.getOutput().getAttr());
1492 if (out &&
1493 DmaQueueModel::keyOf(out) == DmaQueueModel::keyOf(output)) {
1494 inputs.push_back(copy);
1495 outputs.push_back(out);
1496 }
1497 }
1498 }
1499 Unbalanced why = stretchesUnbalanced(seq, last, loaded, input, output,
1500 inputs, outputs, proof,
1501 /*byChannel=*/true);
1502 if (why != Unbalanced::No)
1503 unbalanced.push_back({input, output, why});
1504 }
1505 }
1506 // Every unbalanced pair, by its channels rather than declaration order.
1507 llvm::stable_sort(unbalanced, [&](const auto &a, const auto &b) {
1508 return std::pair(DmaQueueModel::keyOf(std::get<0>(a)),
1509 DmaQueueModel::keyOf(std::get<1>(a))) <
1510 std::pair(DmaQueueModel::keyOf(std::get<0>(b)),
1511 DmaQueueModel::keyOf(std::get<1>(b)));
1512 });
1513 for (auto [input, output, why] : unbalanced) {
1514 auto diag = last.emitOpError()
1515 << "leaves " << last.getDeviceRefAttr()
1516 << " loaded, and its next dispatch, whose proof that @"
1517 << input.getSymName() << " is consumed by @"
1518 << output.getSymName()
1519 << " counts on a clean start, finds what this "
1520 "sequence's last stretch left: it ";
1521 if (why == Unbalanced::Excess)
1522 diag << "moves more through that input than the output proves "
1523 "taken";
1524 else if (why == Unbalanced::PartGranule)
1525 diag << "may end with the output partway through an object of the "
1526 "join the proof passes";
1527 else if (why == Unbalanced::Traffic)
1528 diag << "has other traffic on their channels";
1529 else
1530 diag << "moves bytes on their channels whose count is not known, "
1531 "so cannot be proven balanced";
1532 diag << ". Balance them before the sequence ends, or load this "
1533 "device's PDI again.";
1534 }
1535 return failure(!unbalanced.empty());
1536 }
1537
1538 // `output`'s pushes up to `order` have finished; see recordConsumption in
1539 // aie-objectfifo-verify for why that finishes its inputs' pushes too.
1540 void creditInputs(AIE::ShimDMAAllocationOp output, uint64_t order) {
1541 auto outPushes = loadState.pushesByAllocation.find(output);
1542 auto proofs = deviceState.proofsByOutput.find(output);
1543 if (outPushes == loadState.pushesByAllocation.end() ||
1544 proofs == deviceState.proofsByOutput.end())
1545 return;
1546 auto byOrder = [](const auto &push, uint64_t bound) {
1547 return push.order < bound;
1548 };
1549 const AllocationPush *done =
1550 llvm::lower_bound(outPushes->second, order, byOrder);
1551 if (done == outPushes->second.end() || done->order != order)
1552 return;
1553 loadState.awaitedThrough[output] = {done->through, pushCount};
1554 if (!done->through)
1555 return;
1556 AIE::DeviceOp configured = opaqueLoad ? AIE::DeviceOp()
1557 : loadedDevice ? loadedDevice
1558 : getOperation();
1559 for (auto [input, proof] : proofs->second) {
1560 if (!configured || proofDevice(proof) != configured)
1561 continue;
1562 auto inPushes = loadState.pushesByAllocation.find(input);
1563 DmaQueueModel::ChannelKey key = DmaQueueModel::keyOf(input);
1564 if (inPushes == loadState.pushesByAllocation.end() ||
1565 !leavesNothing(input, output, proof))
1566 continue;
1567 ArrayRef<AllocationPush> pushes = inPushes->second;
1568 size_t &credited = loadState.creditedPushes[{input, output}];
1569 size_t covered = credited;
1570 Volume counted = countedOutput(*done->through, proof);
1571 for (; covered < pushes.size(); ++covered) {
1572 const std::optional<Volume> &through = pushes[covered].through;
1573 if (!through || !atMost(*through, proof.getOutputBytes(), counted,
1574 proof.getInputBytes()))
1575 break;
1576 }
1577 if (covered == credited)
1578 continue;
1579 credited = covered;
1580 auto &tasks = startedOnChannel[key].tasks;
1581 const StartedTask *at =
1582 llvm::lower_bound(tasks, pushes[covered - 1].order, byOrder);
1583 if (at != tasks.end() && at->order == pushes[covered - 1].order)
1584 noteDrained(key, tasks.end() - at - 1);
1585 }
1586 }
1587
1588 // Credit a maskpoll on a channel's status register, whether the queue-depth
1589 // guard, reclaimFor or the design emitted it. A poll bounding the queue size
1590 // by b leaves at most b + 1 unfinished (see getDmaTaskQueueSizeMask); one
1591 // that also clears the running and stall bits leaves none.
1592 void notePoll(NpuMaskPollOp poll) {
1593 std::optional<uint32_t> address = poll.getAbsoluteAddress();
1594 std::optional<uint32_t> mask = getConstantIntOperand(poll.getMask());
1595 std::optional<uint32_t> value = getConstantIntOperand(poll.getValue());
1596 const AIETargetModel &tm =
1597 poll->getParentOfType<AIE::DeviceOp>().getTargetModel();
1598 uint32_t field = tm.getDmaTaskQueueSizeMask();
1599 uint32_t idle = tm.getDmaChannelIdleMask();
1600 if (!address || !mask || !value || !field)
1601 return;
1602 for (const auto &[key, channel] : startedOnChannel) {
1603 if (tm.getDmaStatusAddress(key[0], key[1], key[3],
1604 static_cast<AIE::DMAChannelDir>(key[2])) !=
1605 address)
1606 continue;
1607 if (idle && (*mask & idle) == idle && (*value & idle) == 0)
1608 return noteDrained(key, 0);
1609 unsigned shift = llvm::countr_zero(field);
1610 uint32_t bound = 0;
1611 for (uint32_t size = 0; size <= field >> shift; ++size)
1612 if (((size << shift) & *mask & field) == (*value & *mask & field))
1613 bound = size;
1614 return noteDrained(key, bound + 1);
1615 }
1616 }
1617
1618 // Record ids released without any completion guarantee. nextBdId scans upward
1619 // from 0, so a just-freed low id is the first one handed out again -- the
1620 // worst case for aliasing a BD that is still running.
1621 void noteFreedInFlight(DMAConfigureTaskOp cfg, Operation *freeOp) {
1622 if (!pushCounts.lookup(cfg).started)
1623 return;
1624 AIE::TileOp tile = cfg.getTileOp();
1625 auto &ids = freedInFlight[{tile.getCol(), tile.getRow()}];
1626 uint32_t pool = AIE::getTargetModel(tile).getBdPoolId(
1627 tile.getCol(), tile.getRow(), cfg.getChannel(), cfg.getDirection());
1628 cfg.walk([&](AIE::DMABDOp bd) {
1629 if (bd.getBdId().has_value())
1630 ids[{pool, bd.getBdId().value()}] = {cfg, freeOp};
1631 });
1632 }
1633
1634 // Prints `bytes` scaled by `scale` as "c + k*@param + ...", dropping a zero
1635 // constant unless nothing else would print, and a coefficient of 1.
1636 void printVolume(llvm::raw_ostream &os, const Volume &bytes, int64_t scale,
1637 AIE::RuntimeSequenceOp seq) {
1638 auto constant = bytes.find(-1);
1639 int64_t constantValue =
1640 constant == bytes.end() ? 0 : constant->second * scale;
1641 bool hasTerm = llvm::any_of(
1642 bytes, [](const auto &term) { return term.first >= 0 && term.second; });
1643 bool printed = false;
1644 if (constantValue || !hasTerm) {
1645 os << constantValue;
1646 printed = true;
1647 }
1648 for (const auto &term : bytes) {
1649 if (term.first < 0 || !term.second)
1650 continue;
1651 if (printed)
1652 os << " + ";
1653 int64_t coefficient = term.second * scale;
1654 if (coefficient != 1)
1655 os << coefficient << "*";
1656 printParameter(os, term.first, seq);
1657 printed = true;
1658 }
1659 }
1660
1661 void printParameter(llvm::raw_ostream &os, int64_t index,
1662 AIE::RuntimeSequenceOp seq) {
1663 auto module = getOperation()->getParentOfType<ModuleOp>();
1664 ArrayAttr reads = seq.getScratchpadParametersAttr();
1665 if (module)
1666 for (auto parameter : module.getOps<ScratchpadParameterOp>())
1667 if (parameter.getStateTableIdx() == index &&
1668 (!reads ||
1669 llvm::is_contained(reads.getAsValueRange<FlatSymbolRefAttr>(),
1670 parameter.getSymName()))) {
1671 os << "@" << parameter.getSymName();
1672 return;
1673 }
1674 os << "parameter " << index;
1675 }
1676
1677 // Why no proof shows `task`'s transfer finished, for the unsafe-reuse
1678 // warning: one clause per proof its allocation holds, and the ops they
1679 // point at as notes.
1680 void explainUnproven(DMAConfigureTaskOp task,
1681 SmallVectorImpl<std::string> &why,
1682 SmallVectorImpl<std::pair<Location, std::string>> &at) {
1683 AIE::ShimDMAAllocationOp input = allocationOf(task);
1684 ArrayAttr proofs = input ? input.getConsumedByAttr() : ArrayAttr();
1685 if (!input) {
1686 why.push_back("it names no shim allocation, so no output's progress "
1687 "can prove it consumed");
1688 return;
1689 }
1690 if (!proofs || proofs.empty()) {
1691 std::string clause;
1692 {
1693 llvm::raw_string_ostream os(clause);
1694 os << "aie-objectfifo-verify found no output whose progress proves @"
1695 << input.getSymName() << " consumed";
1696 }
1697 why.push_back(std::move(clause));
1698 return;
1699 }
1700 auto seq = task->getParentOfType<AIE::RuntimeSequenceOp>();
1701 AIE::DeviceOp configured = opaqueLoad ? AIE::DeviceOp()
1702 : loadedDevice ? loadedDevice
1703 : getOperation();
1704 size_t excess = 0;
1705 SmallVector<std::pair<int64_t, AIE::RuntimeSequenceOp>> exceeding;
1706 auto explainProof = [&](AIE::ConsumedByAttr proof, llvm::raw_ostream &os) {
1707 auto output = deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
1708 proof.getOutput().getAttr());
1709 os << "through " << proof.getOutput() << ", ";
1710 if (!output) {
1711 os << "that output is not in this device";
1712 return;
1713 }
1714 if (!configured || proofDevice(proof) != configured) {
1715 os << "the proof describes the array of "
1716 << (proof.getDevice()
1717 ? proof.getDevice()
1718 : FlatSymbolRefAttr::get(getOperation().getSymNameAttr()))
1719 << ", which is not the one loaded";
1720 return;
1721 }
1722 if (!leavesNothing(input, output, proof)) {
1723 for (auto other : getOperation().getOps<AIE::RuntimeSequenceOp>()) {
1724 Verdict verdict;
1725 Unbalanced why = stretchesUnbalanced(
1726 other, nullptr, proofDevice(proof), input, output, {input},
1727 {output}, proof, /*byChannel=*/false, &verdict);
1728 Operation *where = verdict.where;
1729 if (why == Unbalanced::No)
1730 continue;
1731 std::string note;
1732 if (why == Unbalanced::Traffic) {
1733 os << "another transfer shares their channels, which the "
1734 "counts do not describe";
1735 note = "the other transfer";
1736 } else if (why == Unbalanced::PartGranule) {
1737 os << "a stretch of @" << other.getSymName()
1738 << " may end with the output partway through an object of "
1739 "the join the proof passes ("
1740 << proof.getGranuleBytes()
1741 << " output bytes), whose later segments it has then taken "
1742 "less of";
1743 note = "the stretch ends here";
1744 } else if (why == Unbalanced::Unsized) {
1745 os << "a transfer on them moves a byte count the compiler "
1746 "cannot follow (a BD chain, a loop, or a length "
1747 "parameter without min_value >= 0)";
1748 note = "the transfer";
1749 } else {
1750 bool scaled = proof.getInputBytes() != proof.getOutputBytes();
1751 os << "a stretch of @" << other.getSymName()
1752 << " can end having moved more through the input than the "
1753 "output proves taken, so the next dispatch's counts do "
1754 "not start clean (input bytes";
1755 if (scaled)
1756 os << " times " << proof.getOutputBytes();
1757 os << ", ";
1758 printVolume(os, verdict.in, proof.getOutputBytes(), other);
1759 os << ", against output bytes";
1760 if (scaled)
1761 os << " times " << proof.getInputBytes();
1762 os << ", ";
1763 printVolume(os, verdict.out, proof.getInputBytes(), other);
1764 os << ")";
1765 ++excess;
1766 for (const auto &term : verdict.in) {
1767 int64_t index = term.first;
1768 auto taken = verdict.out.find(index);
1769 if (index >= 0 &&
1770 term.second * proof.getOutputBytes() >
1771 (taken == verdict.out.end() ? 0 : taken->second) *
1772 proof.getInputBytes() &&
1773 llvm::none_of(exceeding, [&](const auto &seen) {
1774 return seen.first == index;
1775 }))
1776 exceeding.push_back({index, other});
1777 }
1778 note = "the stretch ends here";
1779 }
1780 std::pair<Location, std::string> pointer = {
1781 where ? where->getLoc() : other.getLoc(), note};
1782 if (!llvm::is_contained(at, pointer))
1783 at.push_back(pointer);
1784 return;
1785 }
1786 }
1787 auto pushes = loadState.pushesByAllocation.find(input);
1788 auto order = pushCounts.find(task);
1789 const AllocationPush *push =
1790 pushes == loadState.pushesByAllocation.end() ||
1791 order == pushCounts.end()
1792 ? nullptr
1793 : llvm::find_if(pushes->second, [&](const AllocationPush &p) {
1794 return p.order == order->second.lastPushOrder;
1795 });
1796 if (!push || push == pushes->second.end() || !push->through) {
1797 os << "the bytes the input has moved up to this transfer are not "
1798 "known";
1799 return;
1800 }
1801 auto awaited = loadState.awaitedThrough.find(output);
1802 if (awaited == loadState.awaitedThrough.end()) {
1803 os << "no await on it has retired a transfer yet";
1804 return;
1805 }
1806 if (awaited->second.pushesBefore <= push->order) {
1807 os << "no await on it has retired a transfer since this one was "
1808 "pushed";
1809 return;
1810 }
1811 const std::optional<Volume> &taken = awaited->second.through;
1812 if (!taken) {
1813 os << "the bytes its awaited transfers moved are not known";
1814 return;
1815 }
1816 Volume counted = countedOutput(*taken, proof);
1817 if (atMost(*push->through, proof.getOutputBytes(), counted,
1818 proof.getInputBytes())) {
1819 os << "its awaited transfers cover this transfer's bytes, but "
1820 "not those of every push of this task";
1821 return;
1822 }
1823 bool scaled = proof.getInputBytes() != proof.getOutputBytes();
1824 os << "the bytes its awaited transfers moved";
1825 if (!wholeGranules(*taken, proof.getGranuleBytes()))
1826 os << ", less the part of an object of the join the proof passes ("
1827 << proof.getGranuleBytes() << " bytes) they may end in,";
1828 if (scaled)
1829 os << " times " << proof.getInputBytes();
1830 os << ", ";
1831 printVolume(os, counted, proof.getInputBytes(), seq);
1832 os << ", fall short of the bytes the input moved up to this "
1833 "transfer";
1834 if (scaled)
1835 os << " times " << proof.getOutputBytes();
1836 os << ", ";
1837 printVolume(os, *push->through, proof.getOutputBytes(), seq);
1838 auto isParameter = [](auto term) { return term.first >= 0; };
1839 if (llvm::any_of(counted, isParameter) ||
1840 llvm::any_of(*push->through, isParameter))
1841 os << ", for some parameter values";
1842 };
1843 for (AIE::ConsumedByAttr proof : proofs.getAsRange<AIE::ConsumedByAttr>()) {
1844 std::string clause;
1845 {
1846 llvm::raw_string_ostream os(clause);
1847 explainProof(proof, os);
1848 }
1849 why.push_back(std::move(clause));
1850 }
1851 if (proofs.size() > 1 && excess == proofs.size()) {
1852 std::string clause;
1853 {
1854 llvm::raw_string_ostream os(clause);
1855 os << "no one output's proof covers the input: it moves more than "
1856 "each proves alone";
1857 if (!exceeding.empty()) {
1858 os << ", by how much depending on the runtime parameter";
1859 if (exceeding.size() > 1)
1860 os << "s";
1861 os << " ";
1862 llvm::interleaveComma(exceeding, os, [&](const auto &parameter) {
1863 printParameter(os, parameter.first, parameter.second);
1864 });
1865 }
1866 }
1867 why.push_back(std::move(clause));
1868 }
1869 }
1870
1871 // Warn where the hazard actually bites: reusing the id, not releasing it.
1872 // Only a reuse in the BD pool of the channel that freed the id aliases it.
1873 void checkReallocation(AIE::TileOp tile, int channel, AIE::DMAChannelDir dir,
1874 uint32_t id, Location at) {
1875 if (!warnUnsafeBdReuse)
1876 return;
1877 auto tileIt = freedInFlight.find({tile.getCol(), tile.getRow()});
1878 if (tileIt == freedInFlight.end())
1879 return;
1880 uint32_t pool = AIE::getTargetModel(tile).getBdPoolId(
1881 tile.getCol(), tile.getRow(), channel, dir);
1882 auto idIt = tileIt->second.find({pool, id});
1883 if (idIt == tileIt->second.end())
1884 return;
1885 ReleasedTask released = idIt->second;
1886 tileIt->second.erase(idIt);
1887 if (knownComplete.contains(released.configure) ||
1888 provenFinished.contains(released.configure))
1889 return;
1890 auto [entry, inserted] = unsafeReuses.try_emplace(
1891 at, UnsafeReuse{id, tile.getCol(), tile.getRow(), {}});
1892 UnsafeReuse &reuse = entry->second;
1893 if (inserted)
1894 explainUnproven(released.configure, reuse.why, reuse.notes);
1895 if (!llvm::is_contained(reuse.freeLocs, released.freeOp->getLoc()))
1896 reuse.freeLocs.push_back(released.freeOp->getLoc());
1897 reuse.tiles.insert({tile.getCol(), tile.getRow()});
1898 reuse.count++;
1899 }
1900
1901 // A full ELF inlines a sequence at every call, so one source transfer can
1902 // reuse an id once per call; it is reported once, with how often. Several
1903 // distinct frees can still merge here -- a generated control-packet copy
1904 // and a user task both reusing the id this allocation pass's own location
1905 // names -- so every free actually seen is kept, not just the first.
1906 struct UnsafeReuse {
1907 uint32_t id;
1908 int col, row;
1909 SmallVector<Location> freeLocs;
1910 std::set<std::pair<int, int>> tiles = {};
1911 int64_t count = 0;
1912 SmallVector<std::string> why = {};
1913 SmallVector<std::pair<Location, std::string>> notes = {};
1914 };
1915 llvm::MapVector<Location, UnsafeReuse> unsafeReuses;
1916 // Copies that reprogram a BD id an earlier copy on the tile may still have
1917 // in flight, reported once per copy like unsafeReuses.
1918 struct CopyOverCopy {
1919 int32_t id;
1920 int col, row;
1921 Location earlier;
1922 bool earlierIssuesToken;
1923 std::set<std::pair<int, int>> tiles = {};
1924 int64_t count = 0;
1925 };
1926 llvm::MapVector<Location, CopyOverCopy> copiesOverCopies;
1927
1928 void emitUnsafeReuses() {
1929 for (auto &[loc, reuse] : unsafeReuses) {
1930 // Not bd->emitWarning(): its "see current operation" note verifies and
1931 // numbers the whole device for each warning, quadratic in the sequence.
1932 auto diag =
1933 mlir::emitWarning(loc)
1934 << "reuses buffer descriptor ID " << reuse.id << " on tile ("
1935 << reuse.col << "," << reuse.row
1936 << ") after it was released by an aiex.dma_free_task that had no "
1937 "completion guarantee, so the DMA it belonged to may still be "
1938 "running and this reprograms it underneath. Consume the "
1939 "outstanding tokens on the same tile, direction and channel "
1940 "through a task queued at or after this transfer -- each await "
1941 "consumes the oldest token, regardless of the task it names.";
1942 for (const std::string &why : reuse.why)
1943 diag.attachNote() << "not proven finished: " << why;
1944 for (Location freeLoc : reuse.freeLocs)
1945 diag.attachNote(freeLoc) << "released here";
1946 for (auto &[noteLoc, text] : reuse.notes)
1947 diag.attachNote(noteLoc) << text;
1948 if (reuse.count > 1) {
1949 Diagnostic &note = diag.attachNote();
1950 note << "and " << reuse.count - 1
1951 << " more times from this transfer, on tile"
1952 << (reuse.tiles.size() > 1 ? "s " : " ");
1953 llvm::interleaveComma(reuse.tiles, note, [&](auto tile) {
1954 note << "(" << tile.first << "," << tile.second << ")";
1955 });
1956 }
1957 }
1958 unsafeReuses.clear();
1959 for (auto &[loc, reuse] : copiesOverCopies) {
1960 auto diag = mlir::emitWarning(loc)
1961 << "reuses buffer descriptor ID " << reuse.id << " on tile ("
1962 << reuse.col << "," << reuse.row
1963 << ") while an earlier aiex.npu.dma_memcpy_nd of that ID may "
1964 "still be in flight, so this reprograms it underneath. "
1965 "Give this copy another ID, or retire the earlier copy "
1966 "first: ";
1967 diag << (reuse.earlierIssuesToken ? kWaitForToken : kNoTokenAdvice);
1968 diag.attachNote(reuse.earlier) << "the earlier copy is here";
1969 if (reuse.count > 1) {
1970 Diagnostic &note = diag.attachNote();
1971 note << "and " << reuse.count - 1
1972 << " more times from this copy, on tile"
1973 << (reuse.tiles.size() > 1 ? "s " : " ");
1974 llvm::interleaveComma(reuse.tiles, note, [&](auto tile) {
1975 note << "(" << tile.first << "," << tile.second << ")";
1976 });
1977 }
1978 }
1979 copiesOverCopies.clear();
1980 }
1981
1982 // Configures already completed by an aiex.dma_await_task. Awaiting a task
1983 // returns its BD ids to the pool (like a free), but a subsequent
1984 // aiex.dma_free_task of the same task is the common "wait, then release"
1985 // idiom, not a double free -- so freeing an awaited task's already-returned
1986 // ids is tolerated.
1987 llvm::SmallPtrSet<Operation *, 8> awaitedConfigures;
1988 // Awaited configures whose IDs remain live until their FIFO completion.
1989 llvm::SmallPtrSet<Operation *, 8> pendingAwaitReleases;
1990
1991 // Return the ids of the configure's chain to the pool. `isAwait` records the
1992 // configure so a later free of it is treated as a redundant release rather
1993 // than a double free. Otherwise an already-freed id is a real double free (or
1994 // a free of a task that was never started) and is an error.
1995 LogicalResult recycle(DMAConfigureTaskOp task_op, Operation *freeOp,
1996 bool isAwait) {
1997 pendingAwaitReleases.erase(task_op);
1998 // Those IDs may now belong to another configure. A redundant release must
1999 // not inspect or change the generator's current ownership.
2000 if (awaitedConfigures.contains(task_op) || reclaimed.contains(task_op) ||
2001 unloaded.contains(task_op))
2002 return success();
2003 BdIdGenerator &gen = getGeneratorForTile(task_op.getTileOp());
2004 WalkResult result = task_op.walk<WalkOrder::PreOrder>([&](AIE::DMABDOp bd) {
2005 if (!bd.getBdId().has_value()) {
2006 bd.emitOpError("Free called on BD chain with unassigned IDs.");
2007 return WalkResult::interrupt();
2008 }
2009 if (gen.bdIdAlreadyAssigned(task_op.getChannel(), task_op.getDirection(),
2010 bd.getBdId().value()) &&
2011 !loadState.copyOwned.contains(
2012 {task_op.getTileOp().getTileID(),
2013 gen.targetModel.getBdPoolId(gen.col, gen.row,
2014 task_op.getChannel(),
2015 task_op.getDirection()),
2016 bd.getBdId().value()})) {
2017 releaseTaskBdId(task_op.getTileOp().getTileID(), gen, task_op,
2018 bd.getBdId().value());
2019 } else {
2020 freeOp->emitOpError("frees buffer descriptor ID ")
2021 << bd.getBdId().value()
2022 << ", which is not currently in use; it was already completed by "
2023 "an "
2024 "earlier aiex.dma_free_task or aiex.dma_await_task";
2025 return WalkResult::interrupt();
2026 }
2027 return WalkResult::advance();
2028 });
2029 if (result.wasInterrupted())
2030 return failure();
2031 releasedTasks.insert(task_op);
2032 if (isAwait)
2033 awaitedConfigures.insert(task_op);
2034 else
2035 noteFreedInFlight(task_op, freeOp);
2036 return success();
2037 }
2038
2039 // Resolve a free/await to its configure. In straight-line IR the task value
2040 // is defined directly by the configure op; anything else is an unlowered task
2041 // op.
2042 LogicalResult recycleTask(Value task, Operation *op, bool isAwait) {
2043 auto cfg = dyn_cast_or_null<DMAConfigureTaskOp>(task.getDefiningOp());
2044 if (!cfg) {
2045 auto err = op->emitOpError(
2046 "does not reference a valid configure_task operation.");
2047 if (Operation *def = task.getDefiningOp()) {
2048 if (isa<DMAStartBdChainOp>(def))
2049 err.attachNote(def->getLoc())
2050 << "Lower this operation first using the "
2051 "--aie-materialize-bd-chains pass.";
2052 if (isa<DMAConfigureTaskForOp>(def))
2053 err.attachNote(def->getLoc())
2054 << "Lower this operation first using the "
2055 "--aie-substitute-shim-dma-allocations pass.";
2056 }
2057 return err;
2058 }
2059 if (!isAwait)
2060 return recycle(cfg, op, /*isAwait=*/false);
2061 pendingAwaitReleases.insert(cfg);
2062 return recycleCompletedTasks(op);
2063 }
2064
2065 LogicalResult recycleCompletedTasks(Operation *op) {
2066 SmallVector<Operation *, 8> pending(pendingAwaitReleases.begin(),
2067 pendingAwaitReleases.end());
2068 for (Operation *pendingOp : pending) {
2069 auto pendingCfg = cast<DMAConfigureTaskOp>(pendingOp);
2070 // An earlier await may have named this task while consuming an older
2071 // token. Revisit its release when a later await proves it complete.
2072 if (!knownComplete.contains(pendingCfg))
2073 continue;
2074 // Retain ownership across any remaining starts of the same configure.
2075 if (llvm::any_of(pendingCfg.getResult().getUsers(), [&](Operation *user) {
2076 return isa<DMAStartTaskOp>(user) &&
2077 user->getBlock() == op->getBlock() &&
2078 op->isBeforeInBlock(user);
2079 }))
2080 continue;
2081 if (failed(recycle(pendingCfg, op, /*isAwait=*/true)))
2082 return failure();
2083 }
2084 return success();
2085 }
2086
2087 // Take back the ids of a started task that is not started again after `op`
2088 // and holds an id in the BD pool of `op`'s channel.
2089 // One a poll already proved finished is taken as is. Otherwise a poll before
2090 // `op` proves one finished: the oldest with j >= 1 pushes queued behind it,
2091 // for which Task_Queue_Size <= j - 1 is proof (as a masked equality, the
2092 // largest 2^k - 1 <= j - 1), so it waits on no push not yet issued; failing
2093 // that, the oldest, until its channel is idle. A task that acquires a lock
2094 // `op` or a later push releases is never polled for: it cannot finish
2095 // before that push, so the poll would never return. The same dependence
2096 // through a core the compiler cannot see; a design with one releases its own
2097 // BDs.
2098 LogicalResult reclaimFor(DMAConfigureTaskOp op) {
2099 AIE::TileOp tile = op.getTileOp();
2100 const AIETargetModel &tm =
2101 tile->getParentOfType<AIE::DeviceOp>().getTargetModel();
2102 auto isCandidate = [&](DMAConfigureTaskOp task) {
2103 if (releasedTasks.contains(task) || startAfter(task, op))
2104 return false;
2105 if (tm.getBdPoolId(tile.getCol(), tile.getRow(), task.getChannel(),
2106 task.getDirection()) !=
2107 tm.getBdPoolId(tile.getCol(), tile.getRow(), op.getChannel(),
2108 op.getDirection()))
2109 return false;
2110 bool usable = false;
2111 task.walk([&](AIE::DMABDOp bd) {
2112 usable |= bd.getBdId() &&
2113 tm.isBdChannelAccessible(tile.getCol(), tile.getRow(),
2114 *bd.getBdId(), op.getChannel(),
2115 op.getDirection());
2116 });
2117 return usable;
2118 };
2119 auto take = [&](DMAConfigureTaskOp task) {
2120 BdIdGenerator &gen = getGeneratorForTile(tile);
2121 task.walk([&](AIE::DMABDOp bd) {
2122 releaseTaskBdId(tile.getTileID(), gen, task, *bd.getBdId());
2123 });
2124 reclaimed.insert(task);
2125 releasedTasks.insert(task);
2126 pendingAwaitReleases.erase(task);
2127 };
2128
2129 ArrayRef<DMAConfigureTaskOp> live = liveByTile[tile.getTileID()];
2130 for (DMAConfigureTaskOp task : live)
2131 if ((knownComplete.contains(task) || provenFinished.contains(task)) &&
2132 isCandidate(task)) {
2133 take(task);
2134 return success();
2135 }
2136
2137 unsigned at = roundState.positionOf.lookup(op);
2138 auto waitsOnLater = [&](DMAConfigureTaskOp task) {
2139 bool waits = false;
2140 task.walk([&](AIE::UseLockOp lock) {
2141 auto last = roundState.lastReleaseOf.find(lock.getLock());
2142 waits |= (lock.acquire() || lock.acquireGE()) &&
2143 last != roundState.lastReleaseOf.end() && last->second >= at;
2144 });
2145 return waits;
2146 };
2147
2148 uint32_t field = tm.getDmaTaskQueueSizeMask();
2149 uint32_t idle = tm.getDmaChannelIdleMask();
2150 DMAConfigureTaskOp victim;
2151 size_t victimQueuedBehind = 0;
2152 uint64_t victimOrder = 0;
2153 for (DMAConfigureTaskOp task : live) {
2154 if (!isCandidate(task) || waitsOnLater(task))
2155 continue;
2157 if (!tm.getDmaStatusAddress(key[0], key[1], key[3],
2158 static_cast<AIE::DMAChannelDir>(key[2])))
2159 continue;
2160 const ChannelPushes &channel = startedOnChannel[key];
2161 ArrayRef<StartedTask> started = channel.tasks;
2162 auto last =
2163 llvm::find_if(llvm::reverse(started),
2164 [&](const StartedTask &s) { return s.task == task; });
2165 size_t queuedBehind = std::distance(started.rbegin(), last);
2166 // Never started, or retired by an await and caught above.
2167 if (last == started.rend() ||
2168 started.size() - 1 - queuedBehind < channel.finished)
2169 continue;
2170 if (queuedBehind == 0 ? !idle : !field)
2171 continue;
2172 // Rule 1 before rule 2, then oldest.
2173 if (victim && std::make_pair(queuedBehind == 0, last->order) >=
2174 std::make_pair(victimQueuedBehind == 0, victimOrder))
2175 continue;
2176 victim = task;
2177 victimQueuedBehind = queuedBehind;
2178 victimOrder = last->order;
2179 }
2180 if (!victim)
2181 return failure();
2182
2184 std::optional<uint32_t> status = tm.getDmaStatusAddress(
2185 key[0], key[1], key[3], static_cast<AIE::DMAChannelDir>(key[2]));
2186 if (!status)
2187 return failure();
2188 uint32_t mask = idle;
2189 size_t unfinished = 0;
2190 if (victimQueuedBehind > 0) {
2191 unsigned shift = llvm::countr_zero(field);
2192 uint32_t bound =
2193 std::min<uint32_t>(llvm::bit_floor(victimQueuedBehind),
2194 llvm::bit_floor((field >> shift) + 1) / 2) -
2195 1;
2196 mask = field & ~(bound << shift);
2197 unfinished = bound + 1;
2198 }
2199 OpBuilder b(op);
2200 auto cst = [&](uint32_t v) {
2201 auto constant = arith::ConstantOp::create(b, op.getLoc(), b.getI32Type(),
2202 b.getI32IntegerAttr(v));
2203 roundState.insertedHere.push_back(constant);
2204 return constant.getResult();
2205 };
2206 Value maskValue = cst(mask);
2207 for (TaskSchedule &schedule : roundState.schedules)
2208 if (schedule.after == op.getOperation())
2209 schedule.after = maskValue.getDefiningOp();
2210 Value compareValue = cst(0);
2211 Value statusValue = cst(*status);
2212 auto poll = NpuMaskPollOp::create(b, op.getLoc(), statusValue, compareValue,
2213 maskValue,
2214 /*buffer=*/nullptr, /*column=*/nullptr,
2215 /*row=*/nullptr);
2216 roundState.insertedHere.push_back(poll);
2217 SmallVector<int32_t> ids;
2218 victim.walk([&](AIE::DMABDOp bd) { ids.push_back(*bd.getBdId()); });
2219 // Not poll.emitRemark(): its "see current operation" note verifies and
2220 // numbers the whole device for each poll, quadratic in the sequence.
2221 auto remark = mlir::emitRemark(poll.getLoc())
2222 << "tile (" << tile.getCol() << "," << tile.getRow()
2223 << ") has no free buffer descriptor id, so this poll waits "
2224 << (victimQueuedBehind > 0
2225 ? "until the queue behind an earlier task is short "
2226 "enough to prove it finished"
2227 : "until the channel of an earlier task is idle")
2228 << " and takes back its ids ";
2229 llvm::interleaveComma(ids, remark);
2230 remark.attachNote(victim.getLoc()) << "the task it waits for";
2231 noteDrained(key, unfinished);
2232 take(victim);
2233 return success();
2234 }
2235
2236 // All of this is scoped to one runtime sequence. `gens` restarts BD id
2237 // allocation per sequence, so hazard state left over from an earlier one
2238 // describes ids that no longer name the same tasks. freedInFlight is the
2239 // one that bites rather than merely misleads: it holds aiex.dma_free_task
2240 // pointers, and those ops are erased once the sequence that owns them is
2241 // done, so carrying an entry forward leaves a dangling note location.
2242 void resetPerSequenceState() {
2243 gens.clear();
2244 awaitedConfigures.clear();
2245 pendingAwaitReleases.clear();
2246 startedOnChannel.clear();
2247 pushCount = 0;
2248 pushCounts.clear();
2249 knownComplete.clear();
2250 provenFinished.clear();
2251 reclaimed.clear();
2252 releasedTasks.clear();
2253 liveByTile.clear();
2254 freedInFlight.clear();
2255 loadedDevice = {};
2256 configuredDevice = {};
2257 opaqueLoad = {};
2258 unloaded.clear();
2259 resetChannels.clear();
2260 loadState = {};
2261 roundState = {};
2262 }
2263
2264 void warnLeaks(AIE::RuntimeSequenceOp sequence) {
2265 if (!warnUnreleasedTransfers)
2266 return;
2267 for (const auto &[key, channel] : startedOnChannel) {
2268 SmallVector<Operation *> outstanding;
2269 for (const StartedTask &push :
2270 llvm::drop_begin(channel.tasks, channel.finished))
2271 if (!push.task || (!releasedTasks.contains(push.task) &&
2272 !unloaded.contains(push.task)))
2273 outstanding.push_back(push.origin);
2274 if (outstanding.empty())
2275 continue;
2276 auto diag = mlir::emitWarning(sequence.getLoc())
2277 << "may exit with " << outstanding.size()
2278 << " DMA transfer(s) neither awaited nor freed on tile ("
2279 << key[0] << "," << key[1] << ") "
2280 << AIE::stringifyDMAChannelDir(
2281 static_cast<AIE::DMAChannelDir>(key[2]))
2282 << " channel " << key[3]
2283 << "; runtime sequences called by aiex.run must finish using "
2284 "their channels before returning. Await completion, or "
2285 "free tasks whose completion is guaranteed indirectly";
2286 diag.attachNote(outstanding.front()->getLoc())
2287 << "first outstanding transfer starts here";
2288 }
2289 }
2290
2291 void runOnOperation() override {
2292 AIE::DeviceOp device = getOperation();
2293 loopingStarts.clear();
2294 deviceState = {};
2295 deviceState.symbols.emplace(device);
2296 for (auto input : device.getOps<AIE::ShimDMAAllocationOp>())
2297 if (ArrayAttr proofs = input.getConsumedByAttr())
2298 for (auto proof : proofs.getAsRange<AIE::ConsumedByAttr>())
2299 if (auto output =
2300 deviceState.symbols->lookup<AIE::ShimDMAAllocationOp>(
2301 proof.getOutput().getAttr()))
2302 deviceState.proofsByOutput[output].push_back({input, proof});
2303
2304 WalkResult wr = device.walk([&](AIE::RuntimeSequenceOp seq) -> WalkResult {
2305 if (seq.getBody().empty())
2306 return WalkResult::advance();
2307 if (failed(checkForeignTail(seq)))
2308 return WalkResult::interrupt();
2309 // Skip sequences already handled by the dynamic free-list pool path
2310 // (aie-lower-dynamic-bd-pool): they draw BD ids at runtime via
2311 // dma_bd_pool_pop and keep their scf.for rolled, which the static
2312 // straight-line allocator neither needs to touch nor can validate.
2313 bool dynamicPool = false;
2314 bool hasTasks = false;
2315 bool hasControlFlow = false;
2316 seq.walk([&](Operation *op) {
2317 dynamicPool |= isa<DMABdPoolPopOp>(op);
2318 hasControlFlow |= isa<scf::ForOp, scf::IfOp, scf::WhileOp>(op);
2319 hasTasks |=
2320 isa<DMAConfigureTaskOp, DMAConfigureTaskForOp, DMAStartBdChainOp,
2321 DMAStartTaskOp, DMAAwaitTaskOp, DMAFreeTaskOp>(op);
2322 });
2323 if (dynamicPool || (!hasTasks && hasControlFlow))
2324 return WalkResult::advance();
2325
2326 if (hasTasks && failed(validate(seq)))
2327 return WalkResult::interrupt();
2328
2329 // Straight-line walk. Collect frees to erase after (recycling reads the
2330 // configure the free points at, so erase only once the walk is done).
2331 // This allocation strategy works only for straight-line IR without
2332 // branching or conditionals; the verifier of this pass ensures this is
2333 // the case on the input IR.
2334 SmallVector<DMAFreeTaskOp> frees;
2335 auto visit = [&](Operation *op) -> WalkResult {
2336 if (auto cfg = dyn_cast<DMAConfigureTaskOp>(op)) {
2337 if (failed(allocateConfigure(cfg)))
2338 return WalkResult::interrupt();
2339 } else if (auto start = dyn_cast<DMAStartTaskOp>(op)) {
2340 if (DMAConfigureTaskOp cfg = start.getTaskOp()) {
2341 if (unloaded.contains(cfg)) {
2342 start.emitOpError(
2343 "starts a task configured before an aiex.npu.load_pdi, "
2344 "which reconfigured the array; its buffer descriptor ids "
2345 "may now belong to the loaded device's static DMAs. "
2346 "Configure the task after the load_pdi instead.");
2347 return WalkResult::interrupt();
2348 }
2349 // Only an explicit aiex.dma_free_task releases a task that is
2350 // started again (an await or a reclaim keeps the ids of one that
2351 // is), so this start would push ids that may already describe
2352 // another task's transfer.
2353 if (releasedTasks.contains(cfg)) {
2354 start.emitOpError(
2355 "starts a task whose buffer descriptors an earlier "
2356 "aiex.dma_free_task released; their ids may already be "
2357 "reprogrammed for another task. Free the task after its "
2358 "last start instead.");
2359 return WalkResult::interrupt();
2360 }
2361 if (failed(checkNotBehindLoop(start, cfg)))
2362 return WalkResult::interrupt();
2363 knownComplete.erase(cfg);
2364 provenFinished.erase(cfg);
2365 notePush(DmaQueueModel::keyOf(cfg), cfg,
2366 start.getPushIssueToken(cfg), start, allocationOf(cfg),
2367 pushVolume(start, cfg));
2368 }
2369 } else if (auto load = dyn_cast<NpuLoadPdiOp>(op)) {
2370 noteLoadPdi(load);
2371 } else if (auto context = dyn_cast<SetDeviceOp>(op)) {
2372 noteConfigured(context);
2373 } else if (auto reset = dyn_cast<DmaChannelResetOp>(op)) {
2374 resetChannels.insert(DmaQueueModel::keyOf(
2375 reset.getTileOp(), reset.getDirection(), reset.getChannel()));
2376 } else if (auto poll = dyn_cast<NpuMaskPollOp>(op)) {
2377 notePoll(poll);
2378 } else if (auto await = dyn_cast<DMAAwaitTaskOp>(op)) {
2379 if (DMAConfigureTaskOp cfg = await.getTaskOp())
2380 if (cfg.getIssueToken())
2381 noteAwaited(DmaQueueModel::keyOf(cfg));
2382 if (failed(recycleTask(await.getTask(), await, /*isAwait=*/true)))
2383 return WalkResult::interrupt();
2384 } else if (auto freeOp = dyn_cast<DMAFreeTaskOp>(op)) {
2385 if (failed(recycleTask(freeOp.getTask(), freeOp, /*isAwait=*/false)))
2386 return WalkResult::interrupt();
2387 frees.push_back(freeOp);
2388 } else if (QueueEffect raw = rawQueueEffect(op, *deviceState.symbols);
2390 noteAwaited(raw.key);
2391 if (failed(recycleCompletedTasks(op)))
2392 return WalkResult::interrupt();
2393 } else if (raw.kind == QueueEffect::Kind::Push) {
2394 auto copy = dyn_cast<NpuDmaMemcpyNdOp>(op);
2395 AIE::ShimDMAAllocationOp allocation = allocationOf(copy);
2396 notePush(raw.key, DMAConfigureTaskOp{}, raw.issuesToken, op,
2397 allocation, copy ? copyVolume(copy) : std::nullopt);
2398 if (copy) {
2399 if (failed(holdCopy(copy, raw.key, pushCount - 1, raw.issuesToken)))
2400 return WalkResult::interrupt();
2401 if (roundState.reallocate)
2402 return WalkResult::interrupt();
2403 }
2404 }
2405 return WalkResult::advance();
2406 };
2407 // A copy that meets a task in flight on its id forbids the task that id
2408 // and the sequence is allocated again; each round adds one such pair.
2409 // A round's diagnostics are held until it stands. Other threads' pass
2410 // instances share the context, so only this thread's are held.
2411 forbidden.clear();
2412 auto reusesBefore = unsafeReuses;
2413 auto copiesBefore = copiesOverCopies;
2414 WalkResult r = WalkResult::advance();
2415 std::vector<Diagnostic> held;
2416 for (;;) {
2417 resetPerSequenceState();
2418 // roundState.positionOf/roundState.lastReleaseOf only ever feed
2419 // reclaimFor.
2420 if (reclaimBds)
2421 indexLockReleases(seq);
2422 frees.clear();
2423 held.clear();
2424 {
2425 uint64_t thread = llvm::get_threadid();
2426 ScopedDiagnosticHandler hold(&getContext(), [&](Diagnostic &diag) {
2427 if (llvm::get_threadid() != thread)
2428 return failure();
2429 held.push_back(std::move(diag));
2430 return success();
2431 });
2432 r = WalkResult::advance();
2433 auto &body = seq.getBody().front();
2434 for (auto iterator = body.begin(); iterator != body.end();) {
2435 Operation *operation = &*iterator++;
2436 SmallVector<TaskTriple> tasks;
2437 auto triple = taskTriple(operation);
2438 while (triple) {
2439 tasks.push_back(*triple);
2440 if (!triple->await.getDeferCompletion())
2441 break;
2442 triple = taskTriple(triple->await->getNextNode());
2443 }
2444 bool eligible =
2445 tasks.size() > 1 && tasks.front().await.getDeferCompletion() &&
2446 llvm::all_of(tasks, [&](TaskTriple task) {
2447 const auto &channel =
2448 startedOnChannel[DmaQueueModel::keyOf(task.configure)];
2449 return fitsNow(task.configure) &&
2450 channel.tasks.size() - channel.finished <
2451 getOperation()
2452 .getTargetModel()
2453 .getDmaTaskQueueDepth() &&
2454 llvm::none_of(
2455 channel.tasks,
2456 [](const StartedTask &push) {
2457 return push.issuesToken;
2458 });
2459 });
2460 if (eligible) {
2461 iterator = std::next(tasks.back().await->getIterator());
2462 if (failed(allocateDeferredTasks(tasks, visit))) {
2463 r = WalkResult::interrupt();
2464 break;
2465 }
2466 } else if (operation->walk(visit).wasInterrupted()) {
2467 r = WalkResult::interrupt();
2468 break;
2469 }
2470 }
2471 }
2472 if (!roundState.reallocate)
2473 break;
2474 for (AIE::DMABDOp bd : roundState.assignedHere)
2475 bd.removeBdIdAttr();
2476 for (Operation *inserted : llvm::reverse(roundState.insertedHere))
2477 inserted->erase();
2478 unsafeReuses = reusesBefore;
2479 copiesOverCopies = copiesBefore;
2480 }
2481 for (Diagnostic &diag : held)
2482 getContext().getDiagEngine().emit(std::move(diag));
2483 if (r.wasInterrupted())
2484 return WalkResult::interrupt();
2485 warnLeaks(seq);
2486 for (TaskSchedule &schedule : roundState.schedules)
2487 commitSchedule(schedule);
2488 for (auto await : seq.getOps<DMAAwaitTaskOp>())
2489 await.removeDeferCompletionAttr();
2490 for (DMAFreeTaskOp freeOp : frees)
2491 freeOp.erase();
2492 for (auto context : llvm::make_early_inc_range(seq.getOps<SetDeviceOp>()))
2493 context.erase();
2494 return WalkResult::advance();
2495 });
2496 emitUnsafeReuses();
2497 if (wr.wasInterrupted())
2498 return signalPassFailure();
2499 }
2500};
2501
2502} // namespace
2503
2504std::unique_ptr<OperationPass<AIE::DeviceOp>>
2506 return std::make_unique<AIENormalizeDMATaskGroupsPass>();
2507}
2508
2509std::unique_ptr<OperationPass<AIE::DeviceOp>>
2511 return std::make_unique<AIEAssignRuntimeSequenceBDIDsPass>();
2512}
2513
2514std::unique_ptr<OperationPass<AIE::DeviceOp>>
2516 const AIEAssignRuntimeSequenceBDIDsOptions &options) {
2517 return std::make_unique<AIEAssignRuntimeSequenceBDIDsPass>(options);
2518}
static void push(ChannelState &q, bool issuesToken)
Record a push.
static void awaitToken(ChannelState &q)
Retire what a task-completion-token await proves has drained.
std::array< int, 4 > ChannelKey
{col, row, direction, channel}.
static bool wouldOverflow(const ChannelState &q, uint32_t depth)
True when a push would land on a full queue.
static ChannelKey keyOf(AIE::TileOp tile, AIE::DMAChannelDir direction, int64_t channel)
std::pair< uint32_t, uint32_t > getBdIdRangeForChannel(int col, int row, int channel, DMAChannelDir dir) const
Return the half-open range of BD ids channel in dir can submit.
virtual uint32_t getDmaChannelIdleMask() const
Return the bits of the getDmaStatusAddress() register that are all clear exactly when the channel has...
uint32_t getNumBDsForChannel(int col, int row, int channel, DMAChannelDir dir) const
virtual uint32_t getBdPoolId(int col, int row, int channel, DMAChannelDir dir) const
Return the pool channel in direction dir draws its BDs from.
virtual uint32_t getDmaTaskQueueDepth() const =0
Return how many DMA tasks a single channel's task queue holds (unsupported = 0).
bool isBdChannelAccessible(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
virtual uint32_t getDmaTaskQueueSizeMask() const
Return the mask selecting the live task-queue occupancy field within the getDmaStatusAddress() regist...
uint32_t getDmaQueueAddress(int col, int row, int channel, AIE::DMAChannelDir direction) const
Return the array address of the task queue register a push writes, the word after the channel's contr...
virtual std::optional< uint32_t > getDmaStatusAddress(int, int, int, AIE::DMAChannelDir) const
Return the address of the DMA status register for a channel, or nullopt when this target's layout has...
QueueEffect rawQueueEffect(mlir::Operation *op, mlir::SymbolTable &symbols)
What a push or an await that names no task does to its channel: an aiex.npu.push_queue; an aiex....
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIENormalizeDMATaskGroupsPass()
bool atMost(const Volume &a, int64_t scaleA, const Volume &b, int64_t scaleB)
Definition AIEUtils.cpp:354
llvm::SmallVector< StaticBd > staticBdIds(llvm::ArrayRef< AIE::DeviceOp > devices, AIE::TileID tile)
void guardQueueOverflow(DmaQueueModel &queue, mlir::Operation *push, const AIE::AIETargetModel &tm, const DmaQueueModel::ChannelKey &key, uint32_t depth, bool enforce)
Handle a push on key that would land on a full queue: poll where one can be emitted,...
bool wholeGranules(const Volume &bytes, int64_t granule)
Definition AIEUtils.cpp:371
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
std::map< int64_t, int64_t > Volume
Definition AIEUtils.h:148
std::unique_ptr< mlir::OperationPass< AIE::DeviceOp > > createAIEAssignRuntimeSequenceBDIDsPass()
Unbalanced balanceUnder(AIE::ConsumedByAttr proof, const Volume &in, const Volume &out)
Definition AIEUtils.cpp:377
struct TileID { friend std::ostream &operator<<(std::ostream &os, const TileID &s) { os<< "TileID("<< s.col<< ", "<< s.row<< ")"; return os; } friend std::string to_string(const TileID &s) { std::ostringstream ss; ss<< s; return ss.str(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const TileID &s) { os<< to_string(s); return os; } inline bool operator<(const TileID &rhs) const { return std::tie(col, row)< std::tie(rhs.col, rhs.row); } bool operator==(const TileID &rhs) const { return std::tie(col, row)==std::tie(rhs.col, rhs.row); } bool operator!=(const TileID &rhs) const { return !(*this==rhs);} int col, row;} TileID
const AIETargetModel & getTargetModel(mlir::Operation *op)
bool isReserved(int channelIndex, DMAChannelDir dir, uint32_t bdId) const
const AIETargetModel & targetModel
std::set< std::pair< uint32_t, uint32_t > > reserved
void reserveBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
std::optional< uint32_t > nextBdId(int channelIndex, DMAChannelDir dir, uint32_t alignment=1)
void freeBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
void assignBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
bool bdIdAlreadyAssigned(int channelIndex, DMAChannelDir dir, uint32_t bdId)
What one op in a loop body does to a channel queue.