MLIR-AIE 1.4.6.dev
DmaQueueModel.h
Go to the documentation of this file.
1//===- DmaQueueModel.h ------------------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// Per-channel DMA task queue, shared by the dma_start_task and
9// npu.dma_memcpy_nd paths so the retirement rule cannot drift between them.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef AIE_DIALECT_AIEX_UTILS_DMAQUEUEMODEL_H
14#define AIE_DIALECT_AIEX_UTILS_DMAQUEUEMODEL_H
15
18
19#include "mlir/Dialect/Arith/IR/Arith.h"
20#include "mlir/Dialect/SCF/IR/SCF.h"
21#include "mlir/Dialect/Utils/StaticValueUtils.h"
22#include "mlir/IR/Builders.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SetVector.h"
26#include "llvm/ADT/SmallVector.h"
27
28#include "llvm/Support/MathExtras.h"
29#include <climits>
30
31#include <algorithm>
32#include <array>
33#include <cstdint>
34#include <functional>
35#include <map>
36#include <set>
37
38namespace xilinx::AIEX {
39
40/// Tracks, per DMA channel, the pushes not yet known to have completed along
41/// one execution path. The sequence analysis below joins control-flow paths.
43public:
44 /// {col, row, direction, channel}. Queues are per channel and per direction,
45 /// and shim tiles are one per column, so the same channel number in two
46 /// columns is two independent queues.
47 using ChannelKey = std::array<int, 4>;
48
49 static ChannelKey keyOf(AIE::TileOp tile, AIE::DMAChannelDir direction,
50 int64_t channel) {
51 return {tile.getCol(), tile.getRow(), static_cast<int>(direction),
52 static_cast<int>(channel)};
53 }
54
55 /// The channel of a shim allocation on a placed tile.
56 static ChannelKey keyOf(AIE::ShimDMAAllocationOp allocation) {
57 return keyOf(allocation.getTileOp(), allocation.getChannelDir(),
58 allocation.getChannelIndex());
59 }
60
61 /// The channel of a configure on a placed tile.
62 static ChannelKey keyOf(DMAConfigureTaskOp cfg) {
63 return keyOf(cfg.getTileOp(), cfg.getDirection(), cfg.getChannel());
64 }
65
66 /// One channel's queue: its pushes not yet known to have completed, oldest
67 /// first, each true when it issues a completion token.
68 struct ChannelState {
69 llvm::SmallVector<bool, 8> pushes;
70 bool unknownTokens = false;
71 bool operator==(const ChannelState &other) const {
72 return pushes == other.pushes && unknownTokens == other.unknownTokens;
73 }
74 };
75
76 /// True when a push would land on a full queue. `depth` of 0 means the
77 /// target has no queued-task model and nothing can overflow.
78 static bool wouldOverflow(const ChannelState &q, uint32_t depth) {
79 return depth != 0 && q.pushes.size() >= depth;
80 }
81
82 /// Record a push. Every push occupies a slot, not just issue_token ones, and
83 /// one push occupies exactly one whatever its repeat_count.
84 static void push(ChannelState &q, bool issuesToken) {
85 q.pushes.push_back(issuesToken && !q.unknownTokens);
86 }
87
88 /// Retire what a task-completion-token await proves has drained. The sync
89 /// pops whichever token the channel produces first -- the oldest outstanding
90 /// token-issuing push, not necessarily the task the await names -- and
91 /// in-order execution means everything queued ahead of it has drained too.
92 /// With no token-issuing push queued, nothing can be retired.
93 static void awaitToken(ChannelState &q) {
94 if (q.unknownTokens)
95 return;
96 auto *tok = llvm::find(q.pushes, true);
97 if (tok != q.pushes.end())
98 q.pushes.erase(q.pushes.begin(), std::next(tok));
99 }
100
101 /// Record that a queue-space poll has guaranteed room. Keeps the newest
102 /// depth-1 entries rather than clearing. Polling does not consume completion
103 /// tokens: if it drops a token-bearing entry, later syncs cannot safely be
104 /// credited to newer pushes.
105 static void noteSpaceGuaranteed(ChannelState &q, uint32_t depth) {
106 if (depth > 0 && q.pushes.size() > depth - 1) {
107 auto end = q.pushes.end() - (depth - 1);
108 q.unknownTokens |=
109 llvm::is_contained(llvm::make_range(q.pushes.begin(), end), true);
110 q.pushes.erase(q.pushes.begin(), end);
111 if (q.unknownTokens)
112 llvm::fill(q.pushes, false);
113 }
114 }
115
116 bool wouldOverflow(const ChannelKey &key, uint32_t depth) const {
117 auto it = queued.find(key);
118 return it != queued.end() && wouldOverflow(it->second, depth);
119 }
120
121 void push(const ChannelKey &key, bool issuesToken) {
122 push(queued[key], issuesToken);
123 }
124
125 void awaitToken(const ChannelKey &key) {
126 if (auto it = queued.find(key); it != queued.end())
127 awaitToken(it->second);
128 }
129
130 void noteSpaceGuaranteed(const ChannelKey &key, uint32_t depth) {
131 noteSpaceGuaranteed(queued[key], depth);
132 }
133
134 /// True the first time a channel is reported. An over-subscribed channel
135 /// usually stays that way for every later push, and repeating the same
136 /// diagnostic per push buries it.
137 bool shouldReport(const ChannelKey &key) {
138 return reported.insert(key).second;
139 }
140
141 /// Outstanding pushes on `key`, for diagnostics.
142 size_t outstanding(const ChannelKey &key) const {
143 auto it = queued.find(key);
144 return it == queued.end() ? 0 : it->second.pushes.size();
145 }
146
147 /// Every channel's queue. `reported` is deliberately not part of it: it is
148 /// diagnostic bookkeeping, not queue state, and folding it in would stop
149 /// two otherwise identical states from comparing equal.
150 using State = std::map<ChannelKey, ChannelState>;
151 const State &state() const { return queued; }
152 void setState(State s) { queued = std::move(s); }
153
154private:
155 State queued;
156 std::set<ChannelKey> reported;
157};
158
159/// The channel an aiex.npu.sync retires on, or nullopt when it cannot be
160/// pinned down. Its six operands are exactly a ChannelKey, with direction
161/// numbered as AIE::DMAChannelDir because DmaWaitToSyncPattern builds that
162/// operand by casting the enum. Unresolvable retires nothing, which
163/// over-reports; guessing the other way would hide a real hang.
164inline std::optional<DmaQueueModel::ChannelKey> syncChannelKey(NpuSyncOp sync) {
165 std::optional<uint32_t> col = getConstantIntOperand(sync.getColumn());
166 std::optional<uint32_t> row = getConstantIntOperand(sync.getRow());
167 std::optional<uint32_t> dir = getConstantIntOperand(sync.getDirection());
168 std::optional<uint32_t> chan = getConstantIntOperand(sync.getChannel());
169 std::optional<uint32_t> colNum = getConstantIntOperand(sync.getColumnNum());
170 std::optional<uint32_t> rowNum = getConstantIntOperand(sync.getRowNum());
171 if (!col || !row || !dir || !chan || !colNum || !rowNum)
172 return std::nullopt;
173 // Nothing in tree settles whether a sync spanning a range of tiles waits for
174 // one token per tile or one for the range -- the cert lowering ignores both
175 // fields -- and crediting nothing is the only reading sound either way.
176 if (*colNum != 1 || *rowNum != 1)
177 return std::nullopt;
179 static_cast<int>(*col), static_cast<int>(*row), static_cast<int>(*dir),
180 static_cast<int>(*chan)};
181}
182
183/// The channels an aiex.npu.sync syncChannelKey cannot pin down may wait on:
184/// its tile range expanded, any value for an operand known only at run time.
185struct SyncCover {
186 int colLo = 0, colHi = INT_MAX, rowLo = 0, rowHi = INT_MAX;
187 std::optional<int> dir, chan;
188
189 bool covers(const DmaQueueModel::ChannelKey &key) const {
190 return key[0] >= colLo && key[0] < colHi && key[1] >= rowLo &&
191 key[1] < rowHi && (!dir || *dir == key[2]) &&
192 (!chan || *chan == key[3]);
193 }
194};
195
196inline SyncCover syncCover(NpuSyncOp sync) {
197 SyncCover cover;
198 auto range = [](std::optional<uint32_t> first, std::optional<uint32_t> num,
199 int &lo, int &hi) {
200 if (!first)
201 return;
202 lo = static_cast<int>(*first);
203 if (num)
204 hi = lo + static_cast<int>(*num);
205 };
206 range(getConstantIntOperand(sync.getColumn()),
207 getConstantIntOperand(sync.getColumnNum()), cover.colLo, cover.colHi);
208 range(getConstantIntOperand(sync.getRow()),
209 getConstantIntOperand(sync.getRowNum()), cover.rowLo, cover.rowHi);
210 if (std::optional<uint32_t> dir = getConstantIntOperand(sync.getDirection()))
211 cover.dir = static_cast<int>(*dir);
212 if (std::optional<uint32_t> chan = getConstantIntOperand(sync.getChannel()))
213 cover.chan = static_cast<int>(*chan);
214 return cover;
215}
216
217/// Retire what an aiex.npu.sync proves has drained. This is the lowered form of
218/// npu.dma_wait and the same hardware event, so it retires by the same rule;
219/// sequences written or lowered down to raw syncs would otherwise look like
220/// they never drain a channel at all.
221inline void awaitSync(DmaQueueModel &queue, NpuSyncOp sync) {
222 if (std::optional<DmaQueueModel::ChannelKey> key = syncChannelKey(sync))
223 queue.awaitToken(*key);
224}
225
226/// Shared wording for the two lowering paths, so the explanation does not
227/// depend on whether the transfer came from dma_start_task or
228/// npu.dma_memcpy_nd.
229inline mlir::InFlightDiagnostic
230emitQueueOverflowWarning(mlir::Operation *op, int col, int row,
231 AIE::DMAChannelDir dir, uint32_t channel,
232 uint32_t depth, size_t outstanding) {
233 // Not op->emitWarning(): its "see current operation" note verifies and
234 // numbers the whole device for each warning, quadratic in the sequence.
235 return mlir::emitWarning(op->getLoc())
236 << "pushes a DMA task onto tile (" << col << "," << row << ") "
237 << AIE::stringifyDMAChannelDir(dir) << " channel " << channel
238 << ", whose task queue is only " << depth << " deep, with "
239 << outstanding
240 << " push(es) not yet known to have completed. A push onto a full "
241 "queue is dropped by hardware and its transfer never runs, so "
242 "whatever waits on it blocks forever. Whether it happens depends "
243 "on how fast the consumer drains, which is why this is a warning "
244 "and not an error. Drain the channel with an await on this tile, "
245 "direction and channel before pushing again";
246}
247
248/// Wording for a dma_free_task that releases a buffer descriptor id the
249/// runtime pool could hand straight back out before hardware has actually
250/// finished the freed transfer -- the rolled-loop counterpart to
251/// aie-assign-runtime-sequence-bd-ids's unsafe-BD-reuse warning.
252inline mlir::InFlightDiagnostic
253emitUnsafeBdReuseWarning(mlir::Operation *freeOp, int col, int row,
254 AIE::DMAChannelDir dir, uint32_t channel) {
255 // Not freeOp->emitWarning(), as in emitQueueOverflowWarning.
256 return mlir::emitWarning(freeOp->getLoc())
257 << "frees a task on tile (" << col << "," << row << ") "
258 << AIE::stringifyDMAChannelDir(dir) << " channel " << channel
259 << " with no completion guarantee, so its buffer descriptor id "
260 "goes back to the runtime pool while the DMA may still be "
261 "running; the pool may hand that id straight to the next task "
262 "drawn on this tile, reprogramming a BD still in flight. Await "
263 "this task, or a later one queued on the same tile, direction "
264 "and channel, before freeing it -- an await consumes the oldest "
265 "outstanding token, regardless of the task it names";
266}
267
268/// Address and mask for a poll that waits for a free task-queue slot.
269/// Unavailable when the target reports no pollable
270/// occupancy register, or when `depth` is not a power of two -- a maskpoll
271/// tests masked equality, not "<", so "occupancy < depth" has to be the single
272/// "depth bit is clear" test (for depth 4, bit 22 of Task_Queue_Size).
273inline std::optional<std::pair<uint32_t, uint32_t>>
274queueSpacePoll(const AIE::AIETargetModel &tm, int col, int row,
275 uint32_t channel, AIE::DMAChannelDir dir, uint32_t depth) {
276 uint32_t fieldMask = tm.getDmaTaskQueueSizeMask();
277 if (!fieldMask || depth == 0 || (depth & (depth - 1)) != 0)
278 return std::nullopt;
279 std::optional<uint32_t> statusAddr =
280 tm.getDmaStatusAddress(col, row, channel, dir);
281 if (!statusAddr)
282 return std::nullopt;
283 uint32_t depthBit = depth << llvm::countr_zero(fieldMask);
284 if ((depthBit & fieldMask) != depthBit)
285 return std::nullopt;
286 return std::make_pair(*statusAddr, depthBit);
287}
288
289inline mlir::LogicalResult
290insertQueueSpaceWait(mlir::Operation *before, const AIE::AIETargetModel &tm,
291 int col, int row, uint32_t channel, AIE::DMAChannelDir dir,
292 uint32_t depth) {
293 auto poll = queueSpacePoll(tm, col, row, channel, dir, depth);
294 if (!poll)
295 return mlir::failure();
296 mlir::OpBuilder b(before);
297 mlir::Location loc = before->getLoc();
298 auto i32 = b.getI32Type();
299 auto cst = [&](uint32_t v) {
300 return mlir::arith::ConstantOp::create(b, loc, i32, b.getI32IntegerAttr(v))
301 .getResult();
302 };
303 NpuMaskPollOp::create(b, loc, cst(poll->first), cst(0), cst(poll->second),
304 /*buffer=*/nullptr, /*column=*/nullptr,
305 /*row=*/nullptr);
306 return mlir::success();
307}
308
309inline constexpr llvm::StringLiteral queueDiagnosedAttr =
310 "aiex.dma_queue_overflow_diagnosed";
311
312/// Handle a push on `key` that would land on a full queue: poll where one can
313/// be emitted, warn where it cannot (see insertQueueSpaceWait above for when
314/// that is). Warning rather than failing keeps a default from rejecting
315/// designs that build today on a target the user can do nothing about; the
316/// note is what keeps it from declining quietly.
317inline void guardQueueOverflow(DmaQueueModel &queue, mlir::Operation *push,
318 const AIE::AIETargetModel &tm,
319 const DmaQueueModel::ChannelKey &key,
320 uint32_t depth, bool enforce) {
321 int col = key[0], row = key[1];
322 auto dir = static_cast<AIE::DMAChannelDir>(key[2]);
323 auto chan = static_cast<uint32_t>(key[3]);
324
325 if (enforce && mlir::succeeded(insertQueueSpaceWait(push, tm, col, row, chan,
326 dir, depth))) {
327 queue.noteSpaceGuaranteed(key, depth);
328 return;
329 }
330 if (!queue.shouldReport(key))
331 return;
332 // Keep diagnostics per sequence/channel across task and combined lowering.
333 // This marker suppresses only warnings, never queue accounting or guards.
334 if (auto seq = push->getParentOfType<AIE::RuntimeSequenceOp>()) {
335 auto channel = mlir::DenseI32ArrayAttr::get(push->getContext(), key);
336 llvm::SmallVector<mlir::Attribute> diagnosed;
337 if (auto previous =
338 seq->getAttrOfType<mlir::ArrayAttr>(queueDiagnosedAttr)) {
339 if (llvm::is_contained(previous, channel))
340 return;
341 llvm::append_range(diagnosed, previous);
342 }
343 diagnosed.push_back(channel);
344 seq->setAttr(queueDiagnosedAttr,
345 mlir::ArrayAttr::get(push->getContext(), diagnosed));
346 }
347 mlir::InFlightDiagnostic diag = emitQueueOverflowWarning(
348 push, col, row, dir, chan, depth, queue.outstanding(key));
349 if (enforce)
350 diag.attachNote() << "the compiler would have waited for a free slot here, "
351 "but this target reports no pollable task-queue "
352 "occupancy register for this channel";
353}
354
355/// What one op in a loop body does to a channel queue. The two lowering paths
356/// spell pushes and awaits with different ops, so the fixed point below takes
357/// the classification from its caller and keeps the FIFO rule to itself.
358///
359/// Free is a read-only check, not a hardware event: a dma_free_task returns a
360/// buffer descriptor id to the compiler's pool without touching the channel,
361/// so it neither pushes nor retires anything here. It asks whether `task`'s
362/// own push -- the one a later pop could still be waiting behind -- has
363/// already been proven complete.
365 enum class Kind { Ignore, Configure, Push, Await, Free };
368 bool issuesToken = false;
369 mlir::Value task;
370
372 mlir::Value task) {
373 return {Kind::Configure, key, false, task};
374 }
376 mlir::Value task = {}) {
377 return {Kind::Push, key, issuesToken, task};
378 }
380 return {Kind::Await, key, false, {}};
381 }
383 return {Kind::Free, key, false, task};
384 }
385};
386
387/// What a push or an await that names no task does to its channel: an
388/// aiex.npu.push_queue; an aiex.npu.dma_memcpy_nd through the placed shim
389/// allocation its metadata names, which always issues a token on S2MM (its
390/// lowering sets one); an aiex.npu.sync syncChannelKey pins down; an
391/// aiex.npu.dma_wait on a placed shim allocation. Ignore for anything else.
392inline QueueEffect rawQueueEffect(mlir::Operation *op,
393 mlir::SymbolTable &symbols) {
394 if (auto push = mlir::dyn_cast<NpuPushQueueOp>(op))
395 return QueueEffect::push({static_cast<int>(push.getColumn()),
396 static_cast<int>(push.getRow()),
397 static_cast<int>(push.getDirection()),
398 static_cast<int>(push.getChannel())},
399 push.getIssueToken());
400 if (auto sync = mlir::dyn_cast<NpuSyncOp>(op)) {
401 if (std::optional<DmaQueueModel::ChannelKey> key = syncChannelKey(sync))
402 return QueueEffect::await(*key);
403 return {};
404 }
405 auto copy = mlir::dyn_cast<NpuDmaMemcpyNdOp>(op);
406 auto wait = mlir::dyn_cast<NpuDmaWaitOp>(op);
407 if (!copy && !wait)
408 return {};
409 auto allocation = symbols.lookup<AIE::ShimDMAAllocationOp>(
410 copy ? copy.getMetadata().getRootReference()
411 : wait.getSymbolAttr().getAttr());
412 if (!allocation || !allocation.getTileOp())
413 return {};
415 if (wait)
416 return QueueEffect::await(key);
417 return QueueEffect::push(key, copy.getIssueToken() ||
418 AIE::isS2MM(allocation.getChannelDir()));
419}
420
421/// Completion is distinct from queue occupancy: Task_Queue_Size excludes the
422/// running task. Task identities are path-local and renamed at joins, so a
423/// configure executed again in a loop is distinct from the carried old task.
425 struct Push {
427 unsigned owner;
428 // Stands in for the newest push of an unknown region, whose owners are
429 // all in forgottenOwners: none of them is proven complete while it is.
430 bool unknownRegion = false;
431 bool operator==(const Push &other) const {
432 return issuesToken == other.issuesToken && owner == other.owner &&
434 }
435 };
436 llvm::SmallVector<unsigned> tasks;
437 llvm::SmallVector<Push, 8> pushes;
438 std::set<unsigned> forgottenOwners;
439 bool unknownTokens = false;
441
442 bool operator==(const DmaCompletionState &other) const {
443 return tasks == other.tasks && pushes == other.pushes &&
445 unknownTokens == other.unknownTokens &&
447 }
448
449 // Canonical identities keep loop fixed points finite. Instances no longer
450 // named by any SSA task need only retain their token and FIFO position.
451 void normalize() {
452 llvm::DenseMap<unsigned, unsigned> names;
453 unsigned next = 1;
454 for (unsigned &task : tasks)
455 if (task) {
456 auto [it, inserted] = names.try_emplace(task, next);
457 next += inserted;
458 task = it->second;
459 }
460 for (Push &push : pushes)
461 push.owner = names.lookup(push.owner);
462 std::set<unsigned> renamed;
463 for (unsigned owner : forgottenOwners)
464 if (unsigned name = names.lookup(owner))
465 renamed.insert(name);
466 forgottenOwners = std::move(renamed);
467 }
468
469 void awaitToken() {
470 if (unknownTokens)
471 return;
472 auto tok =
473 llvm::find_if(pushes, [](const Push &p) { return p.issuesToken; });
474 if (tok != pushes.end()) {
475 pushes.erase(pushes.begin(), std::next(tok));
477 }
478 }
479
480 // Forgotten owners were pushed no later than any remaining unknown-region
481 // stand-in; they are complete once every such stand-in has drained too.
483 if (llvm::none_of(pushes, [](const Push &p) { return p.unknownRegion; }))
484 forgottenOwners.clear();
485 }
486
487 void noteIdle() {
488 // Completion does not consume tokens; later awaits still see these pushes.
489 for (Push &push : pushes) {
490 push.owner = 0;
491 push.unknownRegion = false;
492 }
493 forgottenOwners.clear();
494 }
495
496 // A real space poll leaves at most depth-1 queued tasks AND one running.
497 // Abstract truncation instead retains every lost owner's uncertainty.
498 void bound(unsigned limit, bool spaceGuaranteed) {
499 // Attempted pushes no longer bound FIFO progress after a possible drop.
500 spaceGuaranteed &= !mayHaveDroppedPushes;
501 bool drained = spaceGuaranteed && pushes.size() >= limit;
502 if (pushes.size() > limit) {
503 auto end = pushes.end() - limit;
504 for (const Push &push : llvm::make_range(pushes.begin(), end)) {
505 unknownTokens |= push.issuesToken;
506 if (!spaceGuaranteed && push.owner)
507 forgottenOwners.insert(push.owner);
508 }
509 pushes.erase(pushes.begin(), end);
510 }
511 if (drained)
513 }
514
515 bool isProvenComplete(unsigned owner) const {
516 return owner && !forgottenOwners.count(owner) &&
517 !llvm::any_of(pushes,
518 [&](const Push &p) { return p.owner == owner; });
519 }
520};
521
522/// Per-channel analysis visits only the block each push, await or poll
523/// reaches through, plus the ops enclosing them, in block order, rather than
524/// the whole sequence.
526 llvm::DenseMap<mlir::Block *, llvm::SmallVector<mlir::Operation *>>;
527
528/// Record `op` and each operation enclosing it up to `body`'s own op into
529/// `blocks`, once per block: an ancestor chain's visited block repeats until
530/// the chain's op there changes.
531inline void recordChannelVisit(mlir::Region &body, mlir::Operation *op,
532 ChannelVisits &blocks) {
533 for (mlir::Operation *at = op; at != body.getParentOp();
534 at = at->getParentOp()) {
535 auto &ops = blocks[at->getBlock()];
536 if (!ops.empty() && ops.back() == at)
537 break;
538 ops.push_back(at);
539 }
540}
541
542/// Guard every push in a runtime sequence that can land on a full queue, and
543/// (when `warnUnsafeBdReuse`) warn at every Free effect whose own push is not
544/// yet proven complete along some reachable path.
545///
546/// Retain all reachable states at branches and loop exits, including zero
547/// iterations. Nested loops are analyzed recursively, not walked once. Queue
548/// states are finite because overflowing pushes are capped at the target depth;
549/// targets without a queued-task model must be ignored rather than accumulated.
550/// Analyze each independent channel separately to avoid a Cartesian product
551/// of states across channels.
552template <typename EffectFn>
553inline void guardSequenceQueueDepth(mlir::Region &body, DmaQueueModel &queue,
554 const AIE::AIETargetModel &tm, bool enforce,
555 bool warnUnsafeBdReuse, EffectFn effectOf) {
556 auto depthOf = [&](const DmaQueueModel::ChannelKey &k) {
557 return tm.getDmaTaskQueueDepth(k[0], k[1], k[3],
558 static_cast<AIE::DMAChannelDir>(k[2]));
559 };
560
561 struct PathState {
563 DmaCompletionState completion;
564 bool operator==(const PathState &other) const {
565 return queue == other.queue && completion == other.completion;
566 }
567 };
568 using States = llvm::SmallVector<PathState, 8>;
569 llvm::DenseMap<mlir::Value, unsigned> taskIndices;
570 auto track = [&](mlir::Value value) {
571 if (value && value.getType().isIndex())
572 taskIndices.try_emplace(value, taskIndices.size());
573 };
574 std::set<DmaQueueModel::ChannelKey> keys;
575 for (const auto &[key, channel] : queue.state())
576 if (depthOf(key) != 0)
577 keys.insert(key);
578 llvm::DenseMap<mlir::Operation *, QueueEffect> effects;
579 body.walk([&](mlir::Operation *op) {
580 if (warnUnsafeBdReuse) {
581 for (mlir::Value value : op->getOperands())
582 track(value);
583 for (mlir::Value value : op->getResults())
584 track(value);
585 for (mlir::Region &region : op->getRegions())
586 for (mlir::Block &block : region)
587 for (mlir::Value arg : block.getArguments())
588 track(arg);
589 }
590 QueueEffect e = effectOf(op);
591 if (!warnUnsafeBdReuse) {
592 e.task = {};
595 return;
596 }
597 if (e.kind != QueueEffect::Kind::Ignore && depthOf(e.key) != 0) {
598 keys.insert(e.key);
599 effects[op] = e;
600 }
601 });
602
603 // Each channel's analysis visits only its own pushes, awaits and polls and
604 // the ops enclosing them, in block order, rather than the whole sequence.
605 std::map<uint32_t, DmaQueueModel::ChannelKey> keyByStatus;
606 for (const auto &key : keys)
607 if (auto status = tm.getDmaStatusAddress(
608 key[0], key[1], key[3], static_cast<AIE::DMAChannelDir>(key[2])))
609 keyByStatus[*status] = key;
610 std::map<DmaQueueModel::ChannelKey, ChannelVisits> visits;
611 auto visit = [&](mlir::Operation *op, const DmaQueueModel::ChannelKey &key) {
612 recordChannelVisit(body, op, visits[key]);
613 };
614 body.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
615 if (warnUnsafeBdReuse && mlir::isa<mlir::scf::ForOp, mlir::scf::IfOp>(op))
616 for (const auto &key : keys)
617 visit(op, key);
618 if (auto it = effects.find(op); it != effects.end()) {
619 visit(op, it->second.key);
620 } else if (auto poll = mlir::dyn_cast<NpuMaskPollOp>(op)) {
621 if (auto address = poll.getAbsoluteAddress())
622 if (auto it = keyByStatus.find(*address); it != keyByStatus.end())
623 visit(op, it->second);
624 }
625 });
626
627 DmaQueueModel::State entry = queue.state();
628 DmaQueueModel::State merged = entry;
629 for (const auto &key : keys) {
630 uint32_t depth = depthOf(key);
631 const ChannelVisits &channelVisits = visits[key];
632 auto channelEffectOf = [&](mlir::Operation *op) {
633 auto it = effects.find(op);
634 return it != effects.end() && it->second.key == key ? it->second
635 : QueueEffect{};
636 };
637 llvm::SetVector<mlir::Operation *> overflowing;
638 llvm::SetVector<mlir::Operation *> unsafeFrees;
639 std::map<mlir::Operation *, DmaQueueModel::ChannelState> witnesses;
640 bool trackCompletion = warnUnsafeBdReuse;
641 auto warnUnsafeFree = [&](mlir::Operation *op) {
642 if (warnUnsafeBdReuse && unsafeFrees.insert(op)) {
643 auto diag = emitUnsafeBdReuseWarning(
644 op, key[0], key[1], static_cast<AIE::DMAChannelDir>(key[2]),
645 key[3]);
646 if (!trackCompletion)
647 diag.attachNote() << "task ownership analysis budget exhausted; "
648 "completion is conservatively unproven";
649 }
650 };
651 size_t completionWork = 0;
652 auto equivalent = [&](const PathState &a, const PathState &b) {
653 return a.queue == b.queue &&
654 (!trackCompletion || a.completion == b.completion);
655 };
656 auto contains = [&](const States &states, const PathState &state) {
657 return llvm::any_of(states, [&](const PathState &other) {
658 return equivalent(state, other);
659 });
660 };
661 auto compact = [&](States &states) {
662 States unique;
663 for (const auto &state : states)
664 if (!contains(unique, state))
665 unique.push_back(state);
666 states = std::move(unique);
667 };
668 // Bound optional ownership analysis without weakening queue-depth guards.
669 // Beyond the budget, all frees are uncertain and only occupancy is tracked.
670 auto append = [&](States &to, const States &from) {
671 if (warnUnsafeBdReuse && !trackCompletion)
672 compact(to);
673 for (const auto &state : from)
674 if (!contains(to, state)) {
675 if (trackCompletion && to.size() >= 256) {
676 trackCompletion = false;
677 compact(to);
678 if (contains(to, state))
679 continue;
680 }
681 to.push_back(state);
682 }
683 };
684 auto dedupe = [&](States &states) {
685 if (trackCompletion)
686 for (auto &state : states)
687 state.completion.normalize();
688 if (states.size() < 2)
689 return;
690 States unique;
691 append(unique, states);
692 states = std::move(unique);
693 };
694 auto transfer = [&](States &states, mlir::ValueRange from,
695 mlir::ValueRange to) {
696 if (!trackCompletion)
697 return;
698 for (auto &state : states) {
699 auto previous = state.completion.tasks;
700 for (auto [source, dest] : llvm::zip_equal(from, to)) {
701 auto src = taskIndices.find(source), dst = taskIndices.find(dest);
702 if (src != taskIndices.end() && dst != taskIndices.end())
703 state.completion.tasks[dst->second] = previous[src->second];
704 }
705 }
706 dedupe(states);
707 };
708 auto forgetScope = [&](States &states, mlir::Region &region,
709 bool keepArguments = false) {
710 if (!trackCompletion)
711 return;
712 for (auto [value, index] : taskIndices) {
713 mlir::Region *parent = value.getParentRegion();
714 if (parent != &region && !region.isAncestor(parent))
715 continue;
716 if (keepArguments)
717 if (auto arg = mlir::dyn_cast<mlir::BlockArgument>(value))
718 if (arg.getOwner() == &region.front())
719 continue;
720 for (auto &state : states)
721 state.completion.tasks[index] = 0;
722 }
723 dedupe(states);
724 };
725 bool canPoll =
726 enforce &&
727 queueSpacePoll(tm, key[0], key[1], key[3],
728 static_cast<AIE::DMAChannelDir>(key[2]), depth)
729 .has_value();
730
731 // Earlier passes may already have guarded a start. Credit only polls whose
732 // constant address and mask prove space or idleness on a tracked channel.
733 enum class PollEffect { Ignore, Space, Idle };
734 auto pollEffectOf = [&](NpuMaskPollOp poll) {
735 auto address = poll.getAbsoluteAddress();
736 auto mask = getConstantIntOperand(poll.getMask());
737 auto value = getConstantIntOperand(poll.getValue());
738 if (!address || !mask || !value)
739 return PollEffect::Ignore;
740 auto status = tm.getDmaStatusAddress(
741 key[0], key[1], key[3], static_cast<AIE::DMAChannelDir>(key[2]));
742 if (status != address)
743 return PollEffect::Ignore;
744 uint32_t idleMask = tm.getDmaChannelIdleMask();
745 if (idleMask && (*mask & idleMask) == idleMask &&
746 (*value & idleMask) == 0)
747 return PollEffect::Idle;
748 uint32_t fieldMask = tm.getDmaTaskQueueSizeMask();
749 if (!fieldMask || (depth & (depth - 1)) != 0)
750 return PollEffect::Ignore;
751 uint32_t depthBit = depth << llvm::countr_zero(fieldMask);
752 return depthBit && (depthBit & fieldMask) == depthBit &&
753 (*mask & depthBit) == depthBit && (*value & depthBit) == 0
754 ? PollEffect::Space
755 : PollEffect::Ignore;
756 };
757
758 // Unknown region semantics (including unstructured CFGs) must not credit
759 // conditional waits. Guard their pushes and conservatively forget tokens.
760 auto unknownRegion = [&](mlir::Region &region, States states) {
761 region.walk([&](mlir::Operation *op) {
762 QueueEffect e = channelEffectOf(op);
764 warnUnsafeFree(op);
766 return;
767 for (auto &state : states) {
768 state.queue.pushes.assign(depth, false);
769 state.queue.unknownTokens = true;
770 if (trackCompletion) {
771 state.completion.unknownTokens = true;
772 state.completion.mayHaveDroppedPushes |= !canPoll;
773 for (unsigned owner : state.completion.tasks)
774 if (owner)
775 state.completion.forgottenOwners.insert(owner);
776 // Later polls must count this push before crediting its owners.
777 state.completion.pushes.push_back(
778 {/*issuesToken=*/false, /*owner=*/0, /*unknownRegion=*/true});
779 state.completion.bound(depth + 1, /*spaceGuaranteed=*/false);
780 }
781 if (overflowing.insert(op))
782 witnesses[op] = state.queue;
783 }
784 });
785 dedupe(states);
786 return states;
787 };
788
789 std::function<States(mlir::Region &, States)> analyze;
790 analyze = [&](mlir::Region &region, States states) -> States {
791 if (!region.hasOneBlock())
792 return unknownRegion(region, std::move(states));
793 auto blockVisits = channelVisits.find(&region.front());
794 if (blockVisits == channelVisits.end())
795 return states;
796 for (mlir::Operation *visited : blockVisits->second) {
797 if (trackCompletion) {
798 completionWork += states.size();
799 if (completionWork > 16384) {
800 trackCompletion = false;
801 compact(states);
802 }
803 }
804 mlir::Operation &op = *visited;
805 if (auto loop = mlir::dyn_cast<mlir::scf::ForOp>(&op)) {
806 auto lb = mlir::getConstantIntValue(loop.getLowerBound());
807 auto ub = mlir::getConstantIntValue(loop.getUpperBound());
808 if (lb && ub && *lb >= *ub &&
809 (!loop->hasAttr("unsignedCmp") || (*lb >= 0 && *ub >= 0))) {
810 transfer(states, loop.getInitArgs(), loop.getResults());
811 continue;
812 }
813 // Every loop header state is a possible exit for an unknown trip
814 // count. Include the entry: even an await-only loop might execute
815 // zero times.
816 transfer(states, loop.getInitArgs(), loop.getRegionIterArgs());
817 States reachable = states;
818 for (size_t i = 0; i < reachable.size();) {
819 bool wasTrackingCompletion = trackCompletion;
820 States next = analyze(loop.getRegion(), States{reachable[i]});
821 transfer(next, loop.getYieldedValues(), loop.getRegionIterArgs());
822 forgetScope(next, loop.getRegion(), /*keepArguments=*/true);
823 append(reachable, next);
824 if (wasTrackingCompletion && !trackCompletion) {
825 // Revisit earlier paths with uncertain ownership as well.
826 compact(reachable);
827 i = 0;
828 } else {
829 ++i;
830 }
831 }
832 transfer(reachable, loop.getRegionIterArgs(), loop.getResults());
833 forgetScope(reachable, loop.getRegion());
834 states = std::move(reachable);
835 continue;
836 }
837 if (auto branch = mlir::dyn_cast<mlir::scf::IfOp>(&op)) {
838 States alternatives = analyze(branch.getThenRegion(), states);
839 States otherwise = analyze(branch.getElseRegion(), states);
840 if (branch.getNumResults()) {
841 transfer(alternatives, branch.thenYield().getResults(),
842 branch.getResults());
843 transfer(otherwise, branch.elseYield().getResults(),
844 branch.getResults());
845 }
846 forgetScope(alternatives, branch.getThenRegion());
847 forgetScope(otherwise, branch.getElseRegion());
848 append(alternatives, otherwise);
849 states = std::move(alternatives);
850 continue;
851 }
852 for (mlir::Region &nested : op.getRegions())
853 states = unknownRegion(nested, std::move(states));
854
855 if (auto poll = mlir::dyn_cast<NpuMaskPollOp>(&op))
856 if (auto effect = pollEffectOf(poll); effect != PollEffect::Ignore) {
857 for (auto &state : states) {
858 DmaQueueModel::noteSpaceGuaranteed(state.queue, depth);
859 if (trackCompletion) {
860 if (effect == PollEffect::Idle)
861 state.completion.noteIdle();
862 else
863 state.completion.bound(depth, /*spaceGuaranteed=*/true);
864 }
865 }
866 dedupe(states);
867 }
868
869 QueueEffect e = channelEffectOf(&op);
871 continue;
872 if (e.kind == QueueEffect::Kind::Free) {
873 if (warnUnsafeBdReuse)
874 for (const auto &state : states)
875 if (!trackCompletion ||
876 !state.completion.isProvenComplete(
877 state.completion.tasks[taskIndices.lookup(e.task)]))
878 warnUnsafeFree(&op);
879 continue;
880 }
881 for (auto &state : states) {
883 if (trackCompletion)
884 state.completion.tasks[taskIndices.lookup(e.task)] =
885 taskIndices.size() + 1;
886 continue;
887 }
889 DmaQueueModel::awaitToken(state.queue);
890 if (trackCompletion)
891 state.completion.awaitToken();
892 continue;
893 }
894 if (DmaQueueModel::wouldOverflow(state.queue, depth)) {
895 if (overflowing.insert(&op))
896 witnesses[&op] = state.queue;
897 DmaQueueModel::noteSpaceGuaranteed(state.queue, depth);
898 if (trackCompletion && canPoll)
899 state.completion.bound(depth, /*spaceGuaranteed=*/true);
900 else if (trackCompletion)
901 state.completion.mayHaveDroppedPushes = true;
902 }
903 DmaQueueModel::push(state.queue, e.issuesToken);
904 if (trackCompletion) {
905 unsigned owner =
906 e.task ? state.completion.tasks[taskIndices.lookup(e.task)] : 0;
907 state.completion.pushes.push_back({e.issuesToken, owner});
908 state.completion.bound(depth + 1, /*spaceGuaranteed=*/false);
909 }
910 }
911 dedupe(states);
912 }
913 return states;
914 };
915
916 DmaQueueModel::ChannelState channelEntry;
917 if (auto it = entry.find(key); it != entry.end())
918 channelEntry = it->second;
919 PathState initial{channelEntry, {}};
920 initial.completion.tasks.resize(taskIndices.size());
921 States exits = analyze(body, States{initial});
922 for (mlir::Operation *push : overflowing) {
923 queue.setState({{key, witnesses[push]}});
924 guardQueueOverflow(queue, push, tm, key, depth, enforce);
925 }
926
927 // Preserve exact straight-line state for callers. If control-flow paths
928 // disagree, retain the largest occupancy without crediting ambiguous
929 // tokens.
930 DmaQueueModel::ChannelState channelExit = exits.front().queue;
931 for (const auto &state : exits)
932 if (!(channelExit == state.queue)) {
933 channelExit.pushes.assign(
934 std::max(channelExit.pushes.size(), state.queue.pushes.size()),
935 false);
936 channelExit.unknownTokens = true;
937 }
938 merged[key] = channelExit;
939 }
940 queue.setState(std::move(merged));
941}
942
943/// Check that `sequence` ends, on every path, with no task-completion token
944/// outstanding on a channel some sequence of the device awaits: one in
945/// `awaited`, or one a sync in `mayAwait` may wait on. A token left at the end
946/// outlives the command: the next command's await on that channel takes it and
947/// returns before its own transfer has finished (measured on Strix, NPU
948/// firmware 1.1.2.64), and every completion the compiler derives from an await
949/// assumes the channel started with none. A token on a channel nothing awaits
950/// is never taken. An await consumes the oldest token, so only the count
951/// matters. A loop with an unknown trip count must leave the count where it
952/// found it, or what remains grows with the trip count. Regions the check
953/// cannot follow are not diagnosed, nor channels a sync of the sequence's own
954/// may have waited on.
955template <typename EffectFn>
956inline mlir::LogicalResult
957checkTokensConsumed(AIE::RuntimeSequenceOp sequence,
958 const std::set<DmaQueueModel::ChannelKey> &awaited,
959 llvm::ArrayRef<SyncCover> mayAwait, EffectFn effectOf) {
960 mlir::Region &body = sequence.getBody();
961 auto covered = [](llvm::ArrayRef<SyncCover> covers,
962 const DmaQueueModel::ChannelKey &key) {
963 return llvm::any_of(covers,
964 [&](const SyncCover &c) { return c.covers(key); });
965 };
966 llvm::SmallVector<SyncCover> ownInexact;
967 body.walk([&](NpuSyncOp sync) {
968 if (!syncChannelKey(sync))
969 ownInexact.push_back(syncCover(sync));
970 });
971 // Each channel's analysis visits only its own pushes and syncs and the ops
972 // enclosing them, in block order.
973 llvm::DenseMap<mlir::Operation *, QueueEffect> effects;
974 std::map<DmaQueueModel::ChannelKey, ChannelVisits> visits;
975 body.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
976 QueueEffect e = effectOf(op);
977 if ((e.kind != QueueEffect::Kind::Push &&
979 (!awaited.count(e.key) && !covered(mayAwait, e.key)) ||
980 covered(ownInexact, e.key))
981 return;
982 effects[op] = e;
983 recordChannelVisit(body, op, visits[e.key]);
984 });
985
986 auto describe = [](mlir::InFlightDiagnostic &diag,
987 const DmaQueueModel::ChannelKey &key) {
988 diag << " on tile (" << key[0] << "," << key[1] << ") "
989 << AIE::stringifyDMAChannelDir(static_cast<AIE::DMAChannelDir>(key[2]))
990 << " channel " << key[3];
991 };
992 // Small constant trip counts are followed pass by pass, as unrolling would.
993 constexpr int64_t maxFollowedTrips = 64;
994 bool consumed = true;
995 for (const auto &channel : visits) {
996 const DmaQueueModel::ChannelKey &key = channel.first;
997 const ChannelVisits &blocks = channel.second;
998 using Counts = std::set<int64_t>;
999 bool unknown = false;
1000 std::function<Counts(mlir::Region &, Counts)> analyze;
1001 analyze = [&](mlir::Region &region, Counts counts) -> Counts {
1002 if (region.empty())
1003 return counts;
1004 if (!region.hasOneBlock()) {
1005 unknown = true;
1006 return counts;
1007 }
1008 auto visited = blocks.find(&region.front());
1009 if (visited == blocks.end())
1010 return counts;
1011 for (mlir::Operation *at : visited->second) {
1012 mlir::Operation &op = *at;
1013 if (unknown)
1014 return counts;
1015 if (auto it = effects.find(&op); it != effects.end()) {
1016 Counts next;
1017 for (int64_t count : counts)
1018 next.insert(it->second.kind == QueueEffect::Kind::Push
1019 ? count + it->second.issuesToken
1020 : std::max<int64_t>(count - 1, 0));
1021 counts = std::move(next);
1022 continue;
1023 }
1024 if (auto loop = mlir::dyn_cast<mlir::scf::ForOp>(&op)) {
1025 auto lb = mlir::getConstantIntValue(loop.getLowerBound());
1026 auto ub = mlir::getConstantIntValue(loop.getUpperBound());
1027 auto step = mlir::getConstantIntValue(loop.getStep());
1028 if (lb && ub && step && *step > 0 && !loop->hasAttr("unsignedCmp")) {
1029 int64_t trips = *ub > *lb ? llvm::divideCeil(*ub - *lb, *step) : 0;
1030 if (trips <= maxFollowedTrips) {
1031 for (int64_t i = 0; i < trips && !unknown; i++)
1032 counts = analyze(loop.getRegion(), counts);
1033 continue;
1034 }
1035 }
1036 for (int64_t count : counts) {
1037 Counts after = analyze(loop.getRegion(), Counts{count});
1038 if (unknown)
1039 return counts;
1040 if (after == Counts{count})
1041 continue;
1042 auto diag = loop.emitOpError("changes how many task-completion "
1043 "tokens are outstanding");
1044 describe(diag, key);
1045 diag << " in each pass, so how many it leaves depends on its trip "
1046 "count; await as many tokens in each pass as it issues";
1047 consumed = false;
1048 unknown = true;
1049 return counts;
1050 }
1051 continue;
1052 }
1053 if (auto branch = mlir::dyn_cast<mlir::scf::IfOp>(&op)) {
1054 Counts taken = analyze(branch.getThenRegion(), counts);
1055 Counts otherwise = analyze(branch.getElseRegion(), counts);
1056 taken.insert(otherwise.begin(), otherwise.end());
1057 counts = std::move(taken);
1058 continue;
1059 }
1060 unknown = true;
1061 return counts;
1062 }
1063 return counts;
1064 };
1065 Counts exits = analyze(body, Counts{0});
1066 if (unknown || *exits.rbegin() == 0)
1067 continue;
1068 int64_t left = *exits.rbegin();
1069 // Not sequence.emitOpError(): that would print the whole sequence.
1070 auto diag = mlir::emitError(sequence.getLoc())
1071 << "ends with " << left << " task-completion token"
1072 << (left > 1 ? "s" : "") << " no await consumes";
1073 describe(diag, key);
1074 diag << "; the next command's await on that channel would return for "
1075 "this sequence's transfer instead of its own. Await every "
1076 "token-issuing transfer before the sequence ends, or start it "
1077 "without issue_token";
1078 consumed = false;
1079 }
1080 return mlir::success(consumed);
1081}
1082
1083} // namespace xilinx::AIEX
1084
1085#endif // AIE_DIALECT_AIEX_UTILS_DMAQUEUEMODEL_H
Tracks, per DMA channel, the pushes not yet known to have completed along one execution path.
static void push(ChannelState &q, bool issuesToken)
Record a push.
void push(const ChannelKey &key, bool issuesToken)
size_t outstanding(const ChannelKey &key) const
Outstanding pushes on key, for diagnostics.
static void awaitToken(ChannelState &q)
Retire what a task-completion-token await proves has drained.
void noteSpaceGuaranteed(const ChannelKey &key, uint32_t depth)
std::array< int, 4 > ChannelKey
{col, row, direction, channel}.
static void noteSpaceGuaranteed(ChannelState &q, uint32_t depth)
Record that a queue-space poll has guaranteed room.
bool shouldReport(const ChannelKey &key)
True the first time a channel is reported.
void awaitToken(const ChannelKey &key)
static ChannelKey keyOf(AIE::ShimDMAAllocationOp allocation)
The channel of a shim allocation on a placed tile.
static bool wouldOverflow(const ChannelState &q, uint32_t depth)
True when a push would land on a full queue.
static ChannelKey keyOf(DMAConfigureTaskOp cfg)
The channel of a configure on a placed tile.
static ChannelKey keyOf(AIE::TileOp tile, AIE::DMAChannelDir direction, int64_t channel)
bool wouldOverflow(const ChannelKey &key, uint32_t depth) const
const State & state() const
std::map< ChannelKey, ChannelState > State
Every channel's queue.
virtual uint32_t getDmaChannelIdleMask() const
Return the bits of the getDmaStatusAddress() register that are all clear exactly when the channel has...
virtual uint32_t getDmaTaskQueueDepth() const =0
Return how many DMA tasks a single channel's task queue holds (unsupported = 0).
virtual uint32_t getDmaTaskQueueSizeMask() const
Return the mask selecting the live task-queue occupancy field within the getDmaStatusAddress() regist...
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...
void recordChannelVisit(mlir::Region &body, mlir::Operation *op, ChannelVisits &blocks)
Record op and each operation enclosing it up to body's own op into blocks, once per block: an ancesto...
std::optional< std::pair< uint32_t, uint32_t > > queueSpacePoll(const AIE::AIETargetModel &tm, int col, int row, uint32_t channel, AIE::DMAChannelDir dir, uint32_t depth)
Address and mask for a poll that waits for a free task-queue slot.
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....
mlir::InFlightDiagnostic emitQueueOverflowWarning(mlir::Operation *op, int col, int row, AIE::DMAChannelDir dir, uint32_t channel, uint32_t depth, size_t outstanding)
Shared wording for the two lowering paths, so the explanation does not depend on whether the transfer...
constexpr llvm::StringLiteral queueDiagnosedAttr
mlir::LogicalResult checkTokensConsumed(AIE::RuntimeSequenceOp sequence, const std::set< DmaQueueModel::ChannelKey > &awaited, llvm::ArrayRef< SyncCover > mayAwait, EffectFn effectOf)
Check that sequence ends, on every path, with no task-completion token outstanding on a channel some ...
SyncCover syncCover(NpuSyncOp sync)
std::optional< DmaQueueModel::ChannelKey > syncChannelKey(NpuSyncOp sync)
The channel an aiex.npu.sync retires on, or nullopt when it cannot be pinned down.
llvm::DenseMap< mlir::Block *, llvm::SmallVector< mlir::Operation * > > ChannelVisits
Per-channel analysis visits only the block each push, await or poll reaches through,...
mlir::LogicalResult insertQueueSpaceWait(mlir::Operation *before, const AIE::AIETargetModel &tm, int col, int row, uint32_t channel, AIE::DMAChannelDir dir, uint32_t depth)
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,...
mlir::InFlightDiagnostic emitUnsafeBdReuseWarning(mlir::Operation *freeOp, int col, int row, AIE::DMAChannelDir dir, uint32_t channel)
Wording for a dma_free_task that releases a buffer descriptor id the runtime pool could hand straight...
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
void guardSequenceQueueDepth(mlir::Region &body, DmaQueueModel &queue, const AIE::AIETargetModel &tm, bool enforce, bool warnUnsafeBdReuse, EffectFn effectOf)
Guard every push in a runtime sequence that can land on a full queue, and (when warnUnsafeBdReuse) wa...
void awaitSync(DmaQueueModel &queue, NpuSyncOp sync)
Retire what an aiex.npu.sync proves has drained.
bool isS2MM(DMAChannelDir dir)
True if dir moves data from a stream into memory (S2MM, TraceS2MM).
Definition AIEEnums.h:24
bool operator==(const Push &other) const
Completion is distinct from queue occupancy: Task_Queue_Size excludes the running task.
llvm::SmallVector< Push, 8 > pushes
void bound(unsigned limit, bool spaceGuaranteed)
bool operator==(const DmaCompletionState &other) const
llvm::SmallVector< unsigned > tasks
std::set< unsigned > forgottenOwners
bool isProvenComplete(unsigned owner) const
One channel's queue: its pushes not yet known to have completed, oldest first, each true when it issu...
llvm::SmallVector< bool, 8 > pushes
bool operator==(const ChannelState &other) const
What one op in a loop body does to a channel queue.
static QueueEffect await(DmaQueueModel::ChannelKey key)
static QueueEffect configure(DmaQueueModel::ChannelKey key, mlir::Value task)
static QueueEffect free(DmaQueueModel::ChannelKey key, mlir::Value task)
DmaQueueModel::ChannelKey key
static QueueEffect push(DmaQueueModel::ChannelKey key, bool issuesToken, mlir::Value task={})
The channels an aiex.npu.sync syncChannelKey cannot pin down may wait on: its tile range expanded,...
std::optional< int > dir
std::optional< int > chan
bool covers(const DmaQueueModel::ChannelKey &key) const