MLIR-AIE 1.4.6.dev
AIEStreamDependencyAnalysis.cpp
Go to the documentation of this file.
1//===- AIEStreamDependencyAnalysis.cpp --------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
11
12#include "mlir/Dialect/Utils/StaticValueUtils.h"
13#include "mlir/IR/Matchers.h"
14#include "mlir/Interfaces/ControlFlowInterfaces.h"
15#include "mlir/Interfaces/LoopLikeInterface.h"
16
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/GraphTraits.h"
19#include "llvm/ADT/SCCIterator.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SparseBitVector.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/FormatVariadic.h"
26
27#include <algorithm>
28#include <deque>
29#include <set>
30#include <variant>
31
32#define DEBUG_TYPE "aie-stream-dependency"
33
34using namespace mlir;
35using namespace xilinx;
36using namespace xilinx::AIE;
37
38namespace {
39
40std::optional<TileID> tileOf(Value tile) {
41 if (auto tileOp = dyn_cast_or_null<TileOp>(tile.getDefiningOp()))
42 return tileOp.getTileID();
43 return std::nullopt;
44}
45
46std::optional<DmaChannelProgram> makeProgram(Operation *op, DeviceOp device) {
47 auto parentTile = [](Operation *op) -> std::optional<TileID> {
48 if (auto element = op->getParentOfType<TileElement>())
49 return tileOf(element.getTile());
50 return std::nullopt;
51 };
52 if (auto start = dyn_cast<DMAStartOp>(op)) {
53 std::optional<TileID> tile = parentTile(op);
54 if (!tile)
55 return std::nullopt;
57 op, {*tile, start.getChannelDir(), start.getChannelIndex()}};
58 p.passes += start.getRepeatCount();
59 llvm::SmallPtrSet<Block *, 8> seen;
60 for (Block *b = start.getDest(); b;) {
61 if (!seen.insert(b).second) {
62 p.loops = true;
63 p.loopStart = llvm::find(p.bds, b) - p.bds.begin();
64 break;
65 }
66 p.bds.push_back(b);
67 auto next = dyn_cast<NextBDOp>(b->getTerminator());
68 b = next ? next.getDest() : nullptr;
69 }
70 return p;
71 }
72 if (auto dma = dyn_cast<DMAOp>(op)) {
73 std::optional<TileID> tile = parentTile(op);
74 if (!tile)
75 return std::nullopt;
77 {*tile, dma.getChannelDir(), dma.getChannelIndex()}};
78 p.passes += dma.getRepeatCount();
79 for (Region &r : dma.getBds())
80 p.regions.push_back(&r);
81 p.loops = dma.getLoop();
82 return p;
83 }
84 if (auto task = dyn_cast<AIEX::DMAConfigureTaskOp>(op)) {
85 std::optional<TileID> tile = tileOf(task.getTile());
86 if (!tile)
87 return std::nullopt;
89 op, {*tile, task.getDirection(), static_cast<int>(task.getChannel())}};
90 p.regions.push_back(&task.getBody());
91 p.passes += task.getRepeatCount();
92 return p;
93 }
94 if (auto task = dyn_cast<AIEX::DMAConfigureTaskForOp>(op)) {
95 auto alloc = ShimDMAAllocationOp::getForSymbol(
96 device, task.getAlloc().getRootReference());
97 if (!alloc)
98 return std::nullopt;
99 std::optional<TileID> tile = tileOf(alloc.getTile());
100 if (!tile)
101 return std::nullopt;
103 {*tile, alloc.getChannelDir(),
104 static_cast<int>(alloc.getChannelIndex())}};
105 p.regions.push_back(&task.getBody());
106 p.passes += task.getRepeatCount();
107 return p;
108 }
109 return std::nullopt;
110}
111
112template <typename OpT>
113void forEachInProgram(const DmaChannelProgram &p,
114 llvm::function_ref<void(OpT)> fn) {
115 for (Block *b : p.bds)
116 for (auto op : b->getOps<OpT>())
117 fn(op);
118 for (Region *r : p.regions)
119 r->walk([&](OpT op) { fn(op); });
120}
121
122std::optional<TileDMAChannel> channelOfSymbol(DeviceOp device,
123 StringRef symbol) {
124 auto alloc = ShimDMAAllocationOp::getForSymbol(device, symbol);
125 if (!alloc)
126 return std::nullopt;
127 std::optional<TileID> tile = tileOf(alloc.getTile());
128 if (!tile)
129 return std::nullopt;
130 return TileDMAChannel{*tile, alloc.getChannelDir(),
131 static_cast<int>(alloc.getChannelIndex())};
132}
133
134// The ops that can create `task`, following it back through the results and
135// block arguments of runtime control flow (scf.for iter_args, scf.if results).
136// Empty when some value it can come from has no creator here.
137SmallVector<Operation *> taskCreators(Value task) {
138 SmallVector<Operation *> creators;
139 llvm::SmallPtrSet<Value, 8> seen;
140 SmallVector<Value> worklist{task};
141 while (!worklist.empty()) {
142 Value v = worklist.pop_back_val();
143 if (!seen.insert(v).second)
144 continue;
145 Operation *op = v.getDefiningOp();
146 if (isa_and_nonnull<AIEX::DMAConfigureTaskOp, AIEX::DMAConfigureTaskForOp,
147 AIEX::DMAStartBdChainOp, AIEX::DMAStartBdChainForOp>(
148 op)) {
149 creators.push_back(op);
150 continue;
151 }
152 Operation *owner =
153 op ? op : cast<BlockArgument>(v).getOwner()->getParentOp();
154 auto branch = dyn_cast_or_null<RegionBranchOpInterface>(owner);
155 if (!branch)
156 return {};
157 RegionBranchInverseSuccessorMapping mapping;
158 branch.getSuccessorInputOperandMapping(mapping);
159 auto it = mapping.find(v);
160 if (it == mapping.end())
161 return {};
162 for (OpOperand *operand : it->second)
163 worklist.push_back(operand->get());
164 }
165 return creators;
166}
167
168// The channels `task` can run on; empty when that is not known here.
169SmallVector<TileDMAChannel> channelsOfTask(DeviceOp device, Value task) {
170 SmallVector<TileDMAChannel> keys;
171 for (Operation *op : taskCreators(task)) {
172 std::optional<TileDMAChannel> key;
173 auto onTile = [&](Value tileValue, DMAChannelDir dir, int channel) {
174 if (std::optional<TileID> tile = tileOf(tileValue))
175 key = TileDMAChannel{*tile, dir, channel};
176 };
177 if (auto configure = dyn_cast<AIEX::DMAConfigureTaskOp>(op))
178 onTile(configure.getTile(), configure.getDirection(),
179 configure.getChannel());
180 else if (auto chain = dyn_cast<AIEX::DMAStartBdChainOp>(op))
181 onTile(chain.getTile(), chain.getDirection(), chain.getChannel());
182 else if (auto configure = dyn_cast<AIEX::DMAConfigureTaskForOp>(op))
183 key = channelOfSymbol(device, configure.getAlloc().getRootReference());
184 else if (auto chain = dyn_cast<AIEX::DMAStartBdChainForOp>(op))
185 key = channelOfSymbol(device, chain.getAlloc());
186 if (!key)
187 return {};
188 if (!llvm::is_contained(keys, *key))
189 keys.push_back(*key);
190 }
191 return keys;
192}
193
194// Visits the ops in `region` in program order, going through the body of
195// each loop twice, so that what one iteration does follows all the previous
196// iteration did.
197void walkLoopsTwice(Region &region, function_ref<void(Operation *)> fn) {
198 for (Operation &op : region.getOps()) {
199 fn(&op);
200 auto branch = dyn_cast<RegionBranchOpInterface>(op);
201 int passes = branch && branch.hasLoop() ? 2 : 1;
202 for (int pass = 0; pass < passes; pass++)
203 for (Region &r : op.getRegions())
204 walkLoopsTwice(r, fn);
205 }
206}
207
208// Packet ids each sending channel is programmed with.
209std::map<TileDMAChannel, std::set<int>> collectSentPacketIDs(DeviceOp device) {
210 std::map<TileDMAChannel, std::set<int>> ids;
211 for (const DmaChannelProgram &p : collectDmaPrograms(device)) {
212 if (p.dma.dir != DMAChannelDir::MM2S)
213 continue;
214 forEachInProgram<DMABDOp>(p, [&](DMABDOp bd) {
215 if (std::optional<PacketInfoAttr> packet = bd.getPacket())
216 ids[p.dma].insert(packet->assignedId());
217 });
218 }
219 for (auto alloc : device.getOps<ShimDMAAllocationOp>()) {
220 std::optional<PacketInfoAttr> packet = alloc.getPacket();
221 std::optional<TileID> tile = tileOf(alloc.getTile());
222 if (packet && tile)
223 ids[{*tile, alloc.getChannelDir(),
224 static_cast<int>(alloc.getChannelIndex())}]
225 .insert(packet->assignedId());
226 }
227 device.walk([&](AIEX::NpuDmaMemcpyNdOp memcpy) {
228 std::optional<PacketInfoAttr> packet = memcpy.getPacket();
229 if (!packet)
230 return;
231 if (std::optional<TileDMAChannel> key =
232 channelOfSymbol(device, memcpy.getMetadata().getRootReference()))
233 ids[*key].insert(packet->assignedId());
234 });
235 return ids;
236}
237
238class StreamTracer {
239public:
240 explicit StreamTracer(DeviceOp device)
241 : maxPacketID(getTargetModel(device).getMaxPacketId()) {
242 for (auto sb : device.getOps<SwitchboxOp>())
243 switchboxes[sb.getTileOp().getTileID()] = sb;
244 for (auto mux : device.getOps<ShimMuxOp>())
245 shimMuxes[mux.getTileOp().getTileID()] = mux;
246 sentIDs = collectSentPacketIDs(device);
247 }
248
249 std::vector<RoutedStream> trace() {
250 for (auto &[tile, mux] : shimMuxes)
251 for (Port p : inputPorts(mux.getConnections()))
252 if (p.bundle != WireBundle::North)
253 traceFrom({tile, p}, mux, p);
254 for (auto &[tile, sb] : switchboxes)
255 for (Port p : inputPorts(sb.getConnections()))
256 // A bundle with a wire to another switchbox carries streams both ways,
257 // so its inputs are not where streams enter the fabric.
258 if (!getLinkedInput(tile, p))
259 traceFrom({tile, p}, sb, p);
260 return std::move(streams);
261 }
262
263private:
264 struct Hop {
265 Interconnect interconnect;
266 Port input;
267 };
268
269 static SmallVector<Port> inputPorts(Region &connections) {
270 SmallVector<Port> ports;
271 for (Operation &op : connections.front()) {
272 std::optional<Port> p;
273 if (auto connect = dyn_cast<ConnectOp>(op))
274 p = connect.sourcePort();
275 else if (auto rules = dyn_cast<PacketRulesOp>(op))
276 p = rules.sourcePort();
277 if (p && !llvm::is_contained(ports, *p))
278 ports.push_back(*p);
279 }
280 return ports;
281 }
282
283 void traceFrom(StreamEndpoint src, Interconnect interconnect, Port input) {
284 std::optional<std::set<int>> ids;
285 // A tile sends from its MM2S channel on the port of the same number.
286 if (src.port.bundle == WireBundle::DMA) {
287 auto it = sentIDs.find({src.tile, DMAChannelDir::MM2S, src.port.channel});
288 if (it != sentIDs.end())
289 ids = it->second;
290 }
291 if (!ids) {
292 step(src, {interconnect, input}, std::nullopt);
293 return;
294 }
295 for (int id : *ids)
296 step(src, {interconnect, input}, id);
297 }
298
299 // The switchbox input a master port of `from` drives, or the tile port it
300 // leaves the fabric at.
301 std::variant<Hop, StreamEndpoint> follow(Interconnect from, Port out) {
302 TileID here{from.colIndex(), from.rowIndex()};
303 if (isa<ShimMuxOp>(from)) {
304 if (out.bundle == WireBundle::North)
305 if (auto sb = switchboxes.find(here); sb != switchboxes.end())
306 return Hop{sb->second, {WireBundle::South, out.channel}};
307 return StreamEndpoint{here, out};
308 }
309 if (out.bundle == WireBundle::South)
310 if (auto mux = shimMuxes.find(here); mux != shimMuxes.end())
311 return Hop{mux->second, {WireBundle::North, out.channel}};
312 if (auto next = getLinkedInput(here, out))
313 if (auto sb = switchboxes.find(next->first); sb != switchboxes.end())
314 return Hop{sb->second, next->second};
315 return StreamEndpoint{here, out};
316 }
317
318 // Follows the stream `src` sends with `id` on from `hop`, along every
319 // branch that does not come back to an input it already took.
320 void step(StreamEndpoint src, Hop hop, std::optional<int> id) {
321 std::pair<Operation *, Port> input{hop.interconnect, hop.input};
322 if (!onPath.insert(input).second)
323 return;
324 llvm::scope_exit leave([&] { onPath.erase(input); });
325 auto sb = dyn_cast<SwitchboxOp>(hop.interconnect.getOperation());
326 Block &b = hop.interconnect.getConnections().front();
327
328 auto next = [&](Port out, std::optional<int> nextID,
329 std::optional<int> arbiter, bool keepsPktHeader = false) {
330 if (sb)
331 path.push_back({sb.getTileOp().getTileID(), hop.input, arbiter});
332 llvm::scope_exit backtrack([&] {
333 if (sb)
334 path.pop_back();
335 });
336 std::variant<Hop, StreamEndpoint> to = follow(hop.interconnect, out);
337 if (auto *endpoint = std::get_if<StreamEndpoint>(&to))
338 streams.push_back({src, *endpoint, nextID, keepsPktHeader, path});
339 else
340 step(src, std::get<Hop>(to), nextID);
341 };
342
343 for (auto connect : b.getOps<ConnectOp>())
344 if (connect.sourcePort() == hop.input)
345 next(connect.destPort(), id, std::nullopt);
346
347 for (auto rules : b.getOps<PacketRulesOp>()) {
348 if (rules.sourcePort() != hop.input)
349 continue;
350 auto route = [&](PacketRuleOp rule, int ruleID) {
351 std::optional<int> arbiter;
352 if (auto amsel = rule.getAmsel().getDefiningOp<AMSelOp>())
353 arbiter = amsel.arbiterIndex();
354 for (auto masterSet : b.getOps<MasterSetOp>())
355 if (llvm::is_contained(masterSet.getAmsels(), rule.getAmsel()))
356 next(masterSet.destPort(), ruleID, arbiter,
357 masterSet.keepsPktHeader());
358 };
359 for (int packetID = id.value_or(0); packetID <= id.value_or(maxPacketID);
360 ++packetID)
361 for (auto rule : rules.getRules().front().getOps<PacketRuleOp>())
362 if ((packetID & rule.maskInt()) ==
363 (rule.valueInt() & rule.maskInt())) {
364 route(rule, packetID);
365 break;
366 }
367 }
368 }
369
370 std::map<TileID, SwitchboxOp> switchboxes;
371 std::map<TileID, ShimMuxOp> shimMuxes;
372 std::map<TileDMAChannel, std::set<int>> sentIDs;
373 std::vector<RoutedStream> streams;
374 // The interconnect inputs the stream `step` follows has taken, and the
375 // switchboxes it has passed.
376 llvm::DenseSet<std::pair<Operation *, Port>> onPath;
377 SmallVector<StreamHop, 8> path;
378 int maxPacketID;
379};
380
381} // namespace
382
383SmallVector<DmaChannelProgram> AIE::collectDmaPrograms(DeviceOp device) {
384 SmallVector<DmaChannelProgram> programs;
385 device.walk([&](Operation *op) {
386 if (isa<DMAStartOp, DMAOp, AIEX::DMAConfigureTaskOp,
387 AIEX::DMAConfigureTaskForOp>(op))
388 if (std::optional<DmaChannelProgram> p = makeProgram(op, device))
389 programs.push_back(std::move(*p));
390 });
391 return programs;
392}
393
394std::vector<RoutedStream> AIE::traceRoutedStreams(DeviceOp device) {
395 return StreamTracer(device).trace();
396}
397
398std::vector<RoutedStream> AIE::requestedStreams(DeviceOp device) {
399 std::vector<RoutedStream> streams;
400 for (auto flow : device.getOps<FlowOp>()) {
401 std::optional<TileID> srcTile = tileOf(flow.getSource());
402 std::optional<TileID> dstTile = tileOf(flow.getDest());
403 if (srcTile && dstTile)
404 streams.push_back(
405 {{*srcTile, {flow.getSourceBundle(), flow.sourceIndex()}},
406 {*dstTile, {flow.getDestBundle(), flow.destIndex()}},
407 std::nullopt});
408 }
409 // The router writes one keep_pkt_header per destination port, the last
410 // packet flow's into it.
411 DenseMap<std::pair<TileID, Port>, std::optional<bool>> keepAt;
412 for (auto flow : device.getOps<PacketFlowOp>())
413 for (auto dst : flow.getPorts().front().getOps<PacketDestOp>())
414 if (std::optional<TileID> dstTile = tileOf(dst.getTile()))
415 keepAt[{*dstTile, dst.port()}] = flow.getKeepPktHeader();
416 for (auto flow : device.getOps<PacketFlowOp>()) {
417 Block &b = flow.getPorts().front();
418 for (auto src : b.getOps<PacketSourceOp>()) {
419 std::optional<TileID> srcTile = tileOf(src.getTile());
420 if (!srcTile)
421 continue;
422 for (auto dst : b.getOps<PacketDestOp>())
423 if (std::optional<TileID> dstTile = tileOf(dst.getTile()))
424 streams.push_back(
425 {{*srcTile, src.port()},
426 {*dstTile, dst.port()},
427 flow.IDInt(),
428 keepsPktHeader(*dstTile, dst.port(),
429 keepAt.lookup({*dstTile, dst.port()})),
430 {},
431 static_cast<int>(flow.getMask().value_or(~0))});
432 }
433 }
434 return streams;
435}
436
438 ArrayRef<RoutedStream> streams)
439 : device(device), streams(streams) {
440 for (DmaChannelProgram &p : collectDmaPrograms(device))
441 programs[p.dma].push_back(std::move(p));
442 for (const auto &[dma, channelPrograms] : programs)
443 for (const DmaChannelProgram &p : channelPrograms)
444 forEachInProgram<UseLockOp>(
445 p, [&](UseLockOp use) { lockUseProgram[use] = &p; });
446 device.walk([&](AIEX::NpuDmaMemcpyNdOp memcpy) {
447 if (std::optional<TileDMAChannel> dma =
448 channelOfSymbol(device, memcpy.getMetadata().getRootReference()))
449 memcpys[*dma].push_back(memcpy);
450 });
451}
452
453// The BD blocks of a program in the order its channel runs them.
454static SmallVector<Block *> chainBlocks(const DmaChannelProgram &p) {
455 SmallVector<Block *> sequence(p.bds);
456 for (Region *r : p.regions)
457 sequence.push_back(&r->front());
458 return sequence;
459}
460
461// Index into `sequence` of the block a program runs at `step`: the blocks
462// before the cycle once, then the cycle over and over. A looping chain cycles
463// from where it returns to, a repeated one over the whole chain.
464static size_t blockAt(const DmaChannelProgram &p, size_t size, uint64_t step) {
465 size_t start = p.loops ? p.loopStart : 0;
466 if (step < start)
467 return step;
468 return start + (step - start) % (size - start);
469}
470
471// The value `use` acquires or releases, if it is a constant.
472static std::optional<int64_t> lockAmount(UseLockOp use) {
473 APInt amount;
474 if (!use.getLock().getDefiningOp<LockOp>() ||
475 !matchPattern(use.getValue(), m_ConstantInt(&amount)))
476 return std::nullopt;
477 return amount.getSExtValue();
478}
479
480// The tokens `use` takes or gives, if that is a known count.
481static std::optional<uint64_t> lockTokens(UseLockOp use) {
482 std::optional<int64_t> n = lockAmount(use);
483 if (!n || *n < 0)
484 return std::nullopt;
485 return *n;
486}
487
488constexpr int maxBDSteps = 1024;
489
490std::optional<uint64_t>
492 if (stream.src.port.bundle != WireBundle::DMA)
493 return std::nullopt;
494 TileDMAChannel dma{stream.src.tile, DMAChannelDir::MM2S,
495 stream.src.port.channel};
496 constexpr uint64_t pktHeaderBytes = 4;
497 auto headerBytes = [&](std::optional<PacketInfoAttr> packet) -> uint64_t {
498 return packet && stream.keepsPktHeader ? pktHeaderBytes : 0;
499 };
500 auto bytesOf = [&](DMABDOp bd) -> uint64_t {
501 if (!stream.carries(bd.getPacket()))
502 return 0;
503 return bd.getLenInBytes() + headerBytes(bd.getPacket());
504 };
505 bool known = false;
506 uint64_t total = 0;
507 if (auto it = programs.find(dma); it != programs.end()) {
508 for (const DmaChannelProgram &p : it->second) {
509 bool carried = false;
510 uint64_t bytes = 0;
511 forEachInProgram<DMABDOp>(p, [&](DMABDOp bd) {
512 if (!stream.carries(bd.getPacket()))
513 return;
514 carried = true;
515 bytes += bytesOf(bd);
516 });
517 known = true;
518 if (!carried)
519 continue;
520 if (p.loops) {
521 std::optional<uint64_t> looped = loopedVolume(p, bytesOf);
522 if (!looped)
523 return std::nullopt;
524 total += *looped;
525 continue;
526 }
527 uint64_t runs = p.passes;
528 if (isa<AIEX::DMAConfigureTaskOp, AIEX::DMAConfigureTaskForOp>(p.op)) {
529 auto task = dyn_cast<AIEX::DMAConfigureTaskOp>(p.op);
530 auto taskFor = dyn_cast<AIEX::DMAConfigureTaskForOp>(p.op);
531 if ((task && task.getRepeatCountVal()) ||
532 (taskFor && taskFor.getRepeatCountVal()))
533 return std::nullopt;
534 runs = 0;
535 for (Operation *user : p.op->getUsers()) {
536 if (isa<AIEX::DMAAwaitTaskOp, AIEX::DMAFreeTaskOp>(user))
537 continue;
538 // Any other user, such as an scf.yield or an scf.for init, can
539 // forward the task to starts this does not count.
540 auto start = dyn_cast<AIEX::DMAStartTaskOp>(user);
541 if (!start || start.hasRepeatParameter())
542 return std::nullopt;
543 if (user->getParentOfType<LoopLikeOpInterface>())
544 return std::nullopt;
545 runs += p.passes;
546 }
547 }
548 total += bytes * runs;
549 }
550 }
551 if (auto it = memcpys.find(dma); it != memcpys.end()) {
552 for (Operation *op : it->second) {
553 auto memcpy = cast<AIEX::NpuDmaMemcpyNdOp>(op);
554 std::optional<PacketInfoAttr> packet = memcpy.getPacket();
555 if (!packet)
556 packet = ShimDMAAllocationOp::getForSymbol(
557 device, memcpy.getMetadata().getRootReference())
558 .getPacket();
559 if (!stream.carries(packet))
560 continue;
561 auto type = dyn_cast<BaseMemRefType>(memcpy.getMemref().getType());
562 if (memcpy->getParentOfType<LoopLikeOpInterface>() || !type ||
563 !type.getElementType().isIntOrFloat())
564 return std::nullopt;
565 std::optional<SmallVector<int64_t>> sizes =
566 getConstantIntValues(memcpy.getMixedSizes());
567 if (!sizes)
568 return std::nullopt;
569 uint64_t elements = 1;
570 for (int64_t n : *sizes)
571 elements *= n;
572 // The outermost dimension re-runs the BD (as iterations, or as repeats
573 // when its stride is 0), and each run sends its own header.
574 uint64_t runs = sizes->front();
575 known = true;
576 total += elements * type.getElementTypeBitWidth() / 8 +
577 runs * headerBytes(packet);
578 }
579 }
580 if (!known)
581 return std::nullopt;
582 return total;
583}
584
585std::optional<uint64_t> StreamVolumeAnalysis::loopedVolume(
586 const DmaChannelProgram &program,
587 function_ref<uint64_t(DMABDOp)> bytesOf) const {
588 uint64_t bytes = 0;
589 if (!walkLoop(program, [&](DMABDOp bd) { bytes += bytesOf(bd); }))
590 return std::nullopt;
591 return bytes;
592}
593
594bool StreamVolumeAnalysis::walkLoop(const DmaChannelProgram &p,
595 function_ref<void(DMABDOp)> visit) const {
596 // Binary locks hold a state rather than count tokens.
597 if (!getTargetModel(device).hasProperty(AIETargetModel::UsesSemaphoreLocks) ||
598 !visiting.insert(&p).second)
599 return false;
600 llvm::scope_exit done([&] { visiting.erase(&p); });
601 SmallVector<Block *> sequence = chainBlocks(p);
602 if (sequence.empty())
603 return false;
604 DenseMap<Operation *, uint64_t> tokens;
605 for (int step = 0; step < maxBDSteps; step++) {
606 for (Operation &bdOp : *sequence[blockAt(p, sequence.size(), step)]) {
607 if (auto use = dyn_cast<UseLockOp>(bdOp)) {
608 auto lock = use.getLock().getDefiningOp<LockOp>();
609 std::optional<uint64_t> n = lockTokens(use);
610 if (!n || (!use.release() && !use.acquireGE()))
611 return false;
612 auto it = tokens.find(lock);
613 if (it == tokens.end()) {
614 std::optional<uint64_t> others = tokensFromOthers(lock, &p);
615 if (!others)
616 return false;
617 it = tokens.try_emplace(lock, lock.getInit().value_or(0) + *others)
618 .first;
619 }
620 if (use.release())
621 it->second += *n;
622 else if (it->second < *n)
623 return true;
624 else
625 it->second -= *n;
626 } else if (auto bd = dyn_cast<DMABDOp>(bdOp)) {
627 visit(bd);
628 }
629 }
630 }
631 return false;
632}
633
634// Whether `op` runs at most once each time its core runs its body.
635static bool onceInCore(Operation *op) {
636 for (Operation *parent = op->getParentOp(); parent;
637 op = parent, parent = parent->getParentOp()) {
638 if (!op->getParentRegion()->hasOneBlock() ||
639 isa<LoopLikeOpInterface>(parent))
640 return false;
641 if (isa<CoreOp>(parent))
642 return true;
643 }
644 return false;
645}
646
647std::optional<uint64_t>
648StreamVolumeAnalysis::tokensFromOthers(LockOp lock,
649 const DmaChannelProgram *self) const {
650 llvm::SetVector<const DmaChannelProgram *> releasers;
651 uint64_t tokens = 0;
652 for (Operation *user : lock->getUsers()) {
653 auto use = dyn_cast<UseLockOp>(user);
654 if (!use)
655 return std::nullopt;
656 if (!use.release())
657 continue;
658 auto owner = lockUseProgram.find(use);
659 if (owner == lockUseProgram.end()) {
660 std::optional<uint64_t> n = lockTokens(use);
661 if (!onceInCore(use) || !n)
662 return std::nullopt;
663 tokens += *n;
664 continue;
665 }
666 if (owner->second != self)
667 releasers.insert(owner->second);
668 }
669 for (const DmaChannelProgram *program : releasers) {
670 std::optional<uint64_t> n = releasesOver(*program, lock);
671 if (!n)
672 return std::nullopt;
673 tokens += *n;
674 }
675 return tokens;
676}
677
678std::optional<bool>
680 const RoutedStream &then) const {
681 if (first.src != then.src)
682 return std::nullopt;
683 if (!first.packetID || !then.packetID ||
684 ((*first.packetID ^ *then.packetID) & first.packetMask &
685 then.packetMask) == 0)
686 return true;
687 if (first.src.port.bundle != WireBundle::DMA)
688 return std::nullopt;
689 TileDMAChannel dma{first.src.tile, DMAChannelDir::MM2S,
690 first.src.port.channel};
691 auto it = programs.find(dma);
692 if (it == programs.end() || it->second.size() != 1 ||
693 !isa<DMAStartOp, DMAOp>(it->second.front().op) || memcpys.count(dma))
694 return std::nullopt;
695 const DmaChannelProgram &p = it->second.front();
696 bool sent = false, after = false;
697 auto visit = [&](DMABDOp bd) {
698 after |= sent && then.carries(bd.getPacket());
699 sent |= first.carries(bd.getPacket());
700 };
701 if (p.loops) {
702 if (!walkLoop(p, visit))
703 return std::nullopt;
704 return after;
705 }
706 SmallVector<Block *> sequence = chainBlocks(p);
707 for (uint64_t pass = 0; pass < p.passes && !after; pass++)
708 for (Block *b : sequence)
709 for (DMABDOp bd : b->getOps<DMABDOp>())
710 visit(bd);
711 return after;
712}
713
714std::optional<uint64_t>
715StreamVolumeAnalysis::releasesOver(const DmaChannelProgram &p,
716 LockOp lock) const {
717 if (!isa<DMAStartOp, DMAOp>(p.op))
718 return std::nullopt;
719 SmallVector<Block *> sequence = chainBlocks(p);
720 if (!p.loops) {
721 uint64_t perPass = 0;
722 for (Block *b : sequence)
723 for (auto use : b->getOps<UseLockOp>())
724 if (use.release() && use.getLock().getDefiningOp() == lock) {
725 std::optional<uint64_t> n = lockTokens(use);
726 if (!n)
727 return std::nullopt;
728 perPass += *n;
729 }
730 return perPass * p.passes;
731 }
732 // A looping receiver finishes only the BDs what it is sent fills.
733 if (p.dma.dir != DMAChannelDir::S2MM || sequence.empty())
734 return std::nullopt;
735 StreamEndpoint endpoint{p.dma.tile, {WireBundle::DMA, p.dma.channel}};
736 uint64_t received = 0;
737 for (const RoutedStream &s : streams) {
738 if (s.dst != endpoint)
739 continue;
740 std::optional<uint64_t> bytes = sendVolume(s);
741 if (!bytes)
742 return std::nullopt;
743 received += *bytes;
744 }
745 uint64_t filled = 0, tokens = 0;
746 for (int step = 0; step < maxBDSteps; step++) {
747 for (Operation &bdOp : *sequence[blockAt(p, sequence.size(), step)]) {
748 if (auto bd = dyn_cast<DMABDOp>(bdOp)) {
749 if (filled + bd.getLenInBytes() > received)
750 return tokens;
751 filled += bd.getLenInBytes();
752 } else if (auto use = dyn_cast<UseLockOp>(bdOp)) {
753 if (!use.release() || use.getLock().getDefiningOp() != lock)
754 continue;
755 std::optional<uint64_t> n = lockTokens(use);
756 if (!n)
757 return std::nullopt;
758 tokens += *n;
759 }
760 }
761 }
762 return std::nullopt;
763}
764
765static std::optional<uint64_t> programCapacity(const DmaChannelProgram &p,
766 DeviceOp device) {
767 if (!isa<DMAStartOp, DMAOp>(p.op))
768 return 0;
769
770 // Run the BD chain from its initial lock values until an acquire blocks.
771 SmallVector<Block *> sequence = chainBlocks(p);
772 if (sequence.empty())
773 return 0;
774 // Binary locks hold a state an acquire waits to equal and a release sets;
775 // semaphore locks count, and an acquire waiting for an exact count is taken
776 // to block.
777 bool stateLocks =
779 DenseMap<Operation *, int64_t> lockValues;
780 uint64_t bytes = 0;
781 // Lock values and bytes when the cycle last began. A cycle that leaves every
782 // lock where it found it, or with more tokens, runs again the same way.
783 std::optional<DenseMap<Operation *, int64_t>> cycleLocks;
784 uint64_t cycleBytes = 0;
785 size_t start = p.loops ? p.loopStart : 0;
786 for (uint64_t step = 0;; step++) {
787 if (!p.loops && step >= p.passes * sequence.size())
788 return bytes;
789 size_t i = blockAt(p, sequence.size(), step);
790 if (i == start) {
791 if (cycleLocks && cycleLocks->size() == lockValues.size() &&
792 llvm::all_of(lockValues, [&](const auto &lv) {
793 int64_t before = cycleLocks->at(lv.first);
794 return stateLocks ? lv.second == before : lv.second >= before;
795 })) {
796 if (p.loops)
797 return std::nullopt;
798 return bytes +
799 (p.passes - step / sequence.size()) * (bytes - cycleBytes);
800 }
801 cycleLocks = lockValues;
802 cycleBytes = bytes;
803 }
804 // Past the analysis limit, what it took in so far is a safe capacity.
805 if (step >= static_cast<uint64_t>(maxBDSteps))
806 return bytes;
807 for (Operation &bdOp : *sequence[i]) {
808 if (auto use = dyn_cast<UseLockOp>(bdOp)) {
809 std::optional<int64_t> n = lockAmount(use);
810 if (!n)
811 return 0;
812 auto lock = use.getLock().getDefiningOp<LockOp>();
813 int64_t &value =
814 lockValues.try_emplace(lock, lock.getInit().value_or(0))
815 .first->second;
816 if (stateLocks) {
817 if (use.release())
818 value = *n;
819 else if (value != *n)
820 return bytes;
821 } else if (use.release()) {
822 value += *n;
823 } else if (!use.acquireGE() || value < *n) {
824 return bytes;
825 } else {
826 value -= *n;
827 }
828 } else if (auto bd = dyn_cast<DMABDOp>(bdOp)) {
829 bytes += bd.getLenInBytes();
830 }
831 }
832 }
833}
834
835std::optional<uint64_t>
837 if (endpoint.port.bundle != WireBundle::DMA)
838 return 0;
839 auto it = programs.find(
840 {endpoint.tile, DMAChannelDir::S2MM, endpoint.port.channel});
841 if (it == programs.end())
842 return 0;
843 std::optional<uint64_t> capacity;
844 for (const DmaChannelProgram &p : it->second)
845 if (std::optional<uint64_t> c = programCapacity(p, device))
846 capacity = std::min(*c, capacity.value_or(*c));
847 return capacity;
848}
849
851 ArrayRef<RoutedStream> streams) const {
852 std::optional<uint64_t> capacity = receiveCapacity(endpoint);
853 if (!capacity)
854 return false;
855 uint64_t sent = 0;
856 for (const RoutedStream &s : streams) {
857 if (s.dst != endpoint)
858 continue;
859 std::optional<uint64_t> bytes = sendVolume(s);
860 if (!bytes)
861 return true;
862 sent += *bytes;
863 }
864 return sent > *capacity;
865}
866
868 ArrayRef<RoutedStream> streams,
869 const StreamVolumeAnalysis &volumes) {
870 std::set<TileDMAChannel> neverFull;
871 for (const RoutedStream &s : streams)
872 if (s.dst.port.bundle == WireBundle::DMA &&
873 !volumes.canFill(s.dst, streams))
874 neverFull.insert({s.dst.tile, DMAChannelDir::S2MM, s.dst.port.channel});
875 auto waitsOnLocks = [&](unsigned agent) {
876 const Agent &a = agents[agent];
877 return a.kind == Agent::Kind::Core || !neverFull.count(a.dma);
878 };
879
880 // Who acquires and who releases each lock.
881 DenseMap<Operation *, llvm::SetVector<unsigned>> acquirers, releasers;
882 auto noteLock = [&](UseLockOp use, unsigned agent) {
883 Operation *lock = use.getLock().getDefiningOp();
884 if (!lock)
885 return;
886 if (use.getAction() == LockAction::Release)
887 releasers[lock].insert(agent);
888 else
889 acquirers[lock].insert(agent);
890 };
891
892 // Agents whose waits the design spells out; see the end of this constructor
893 // for the rest.
894 for (auto core : device.getOps<CoreOp>()) {
895 unsigned agent = getOrCreate(Agent::core(core.getTileOp().getTileID()));
896 modeled.insert(agent);
897 core.walk([&](UseLockOp use) { noteLock(use, agent); });
898 }
899 for (const DmaChannelProgram &p : collectDmaPrograms(device)) {
900 unsigned agent = getOrCreate(Agent::channel(p.dma));
901 modeled.insert(agent);
902 forEachInProgram<UseLockOp>(p,
903 [&](UseLockOp use) { noteLock(use, agent); });
904 }
905 // Document order, not pointer order: edge order picks the chain a
906 // diagnostic reports.
907 for (auto lock : device.getOps<LockOp>()) {
908 auto waiting = acquirers.find(lock), it = releasers.find(lock);
909 if (waiting == acquirers.end() || it == releasers.end())
910 continue;
911 for (unsigned p : waiting->second)
912 for (unsigned q : it->second)
913 if (p != q && waitsOnLocks(p))
914 addEdge(p, q, EdgeKind::Lock);
915 }
916
917 for (const RoutedStream &s : streams) {
918 std::optional<unsigned> from, to;
919 if (std::optional<Agent> agent = Agent::at(s.src, true))
920 from = getOrCreate(*agent);
921 if (std::optional<Agent> agent = Agent::at(s.dst, false))
922 to = getOrCreate(*agent);
923 if (!from || !to || *from == *to)
924 continue;
925 addEdge(*from, *to, EdgeKind::Stream, /*sends=*/true);
926 addEdge(*to, *from, EdgeKind::Stream, /*sends=*/false, /*receives=*/true);
927 }
928
929 // The host issues a channel's transfer only after every wait before it in
930 // the runtime sequence completes. Each issue is modeled: a later one can
931 // follow waits the first did not. A wait on a channel not known here may be
932 // on any the sequence issues, and an issue on one, or a raw register write,
933 // may start any channel.
934 unsigned numStreamAgents = agents.size();
935 for (auto sequence : device.getOps<RuntimeSequenceOp>()) {
936 auto bySymbol = [&](SymbolRefAttr symbol) -> SmallVector<TileDMAChannel> {
937 if (std::optional<TileDMAChannel> key =
938 channelOfSymbol(device, symbol.getRootReference()))
939 return {*key};
940 return {};
941 };
942 auto issued =
943 [&](Operation *op) -> std::optional<SmallVector<TileDMAChannel>> {
944 if (auto memcpy = dyn_cast<AIEX::NpuDmaMemcpyNdOp>(op))
945 return bySymbol(memcpy.getMetadata());
946 if (auto start = dyn_cast<AIEX::DMAStartTaskOp>(op))
947 return channelsOfTask(device, start.getTask());
948 if (isa<AIEX::DMAStartBdChainOp, AIEX::DMAStartBdChainForOp>(op))
949 return channelsOfTask(device, op->getResult(0));
950 if (auto push = dyn_cast<AIEX::NpuPushQueueOp>(op))
951 return SmallVector<TileDMAChannel>{
952 {{static_cast<int>(push.getColumn()),
953 static_cast<int>(push.getRow())},
954 push.getDirection(),
955 static_cast<int>(push.getChannel())}};
956 if (isa<AIEX::NpuWrite32Op, AIEX::NpuMaskWrite32Op, AIEX::NpuBlockWriteOp,
957 AIEX::NpuWriteConfigOp, AIEX::NpuWriteTeardownOp>(op))
958 return SmallVector<TileDMAChannel>{};
959 return std::nullopt;
960 };
961 auto awaited =
962 [&](Operation *op) -> std::optional<SmallVector<TileDMAChannel>> {
963 if (auto dmaWait = dyn_cast<AIEX::NpuDmaWaitOp>(op))
964 return bySymbol(dmaWait.getSymbolAttr());
965 if (auto await = dyn_cast<AIEX::DMAAwaitTaskOp>(op))
966 return channelsOfTask(device, await.getTask());
967 if (auto sync = dyn_cast<AIEX::NpuSyncOp>(op)) {
968 std::optional<int64_t> col = getConstantIntValue(sync.getColumn()),
969 row = getConstantIntValue(sync.getRow()),
970 dir = getConstantIntValue(sync.getDirection()),
971 channel = getConstantIntValue(sync.getChannel()),
972 cols = getConstantIntValue(sync.getColumnNum()),
973 rows = getConstantIntValue(sync.getRowNum());
974 if (!col || !row || !dir || !channel || !cols || !rows)
975 return SmallVector<TileDMAChannel>{};
976 SmallVector<TileDMAChannel> keys;
977 for (int64_t c = *col; c < *col + *cols; c++)
978 for (int64_t r = *row; r < *row + *rows; r++)
979 keys.push_back({{static_cast<int>(c), static_cast<int>(r)},
980 *dir ? DMAChannelDir::MM2S : DMAChannelDir::S2MM,
981 static_cast<int>(*channel)});
982 return keys;
983 }
984 if (isa<AIEX::NpuMaskPollOp>(op))
985 return SmallVector<TileDMAChannel>{};
986 return std::nullopt;
987 };
988 llvm::SetVector<TileDMAChannel, SmallVector<TileDMAChannel>,
989 std::set<TileDMAChannel>>
990 issuedKeys;
991 sequence.walk([&](Operation *op) {
992 if (std::optional<SmallVector<TileDMAChannel>> keys = issued(op))
993 issuedKeys.insert(keys->begin(), keys->end());
994 });
995
996 llvm::SetVector<unsigned> waited;
997 walkLoopsTwice(sequence.getBody(), [&](Operation *op) {
998 if (std::optional<SmallVector<TileDMAChannel>> keys = issued(op)) {
999 for (const TileDMAChannel &key : *keys) {
1000 unsigned agent = getOrCreate(Agent::channel(key));
1001 modeled.insert(agent);
1002 for (unsigned w : waited)
1003 if (w != agent)
1004 addEdge(agent, w, EdgeKind::Host);
1005 }
1006 if (keys->empty())
1007 for (unsigned a = 0; a < numStreamAgents; a++)
1008 if (agents[a].kind == Agent::Kind::Channel)
1009 for (unsigned w : waited)
1010 if (w != a)
1011 addEdge(a, w, EdgeKind::Host);
1012 } else if (std::optional<SmallVector<TileDMAChannel>> keys =
1013 awaited(op)) {
1014 for (const TileDMAChannel &key :
1015 keys->empty() ? issuedKeys.getArrayRef() : ArrayRef(*keys)) {
1016 waited.insert(getOrCreate(Agent::channel(key)));
1017 for (unsigned a = 0; a < numStreamAgents; a++)
1018 if (agents[a].kind == Agent::Kind::Controller &&
1019 agents[a].dma.tile.col == key.tile.col)
1020 waited.insert(a);
1021 }
1022 }
1023 });
1024 }
1025
1026 // A channel nothing programs here is programmed elsewhere, in ways this
1027 // cannot see, so it may wait on anything else on its tile. One on a shim
1028 // tile is driven by the host, which may wait on any other shim tile first.
1029 const AIETargetModel &targetModel = getTargetModel(device);
1030 for (Agent &a : agents)
1031 a.onShim = a.kind == Agent::Kind::Channel &&
1032 targetModel.isShimNOCorPLTile(a.dma.tile.col, a.dma.tile.row);
1033 for (unsigned a = 0; a < agents.size(); a++) {
1034 if (modeled.contains(a) || agents[a].kind == Agent::Kind::Controller ||
1035 !waitsOnLocks(a))
1036 continue;
1037 for (unsigned b = 0; b < agents.size(); b++)
1038 if (b != a && agents[b].kind != Agent::Kind::Controller &&
1039 (agents[b].dma.tile == agents[a].dma.tile ||
1040 (agents[a].onShim && agents[b].onShim)))
1041 addEdge(a, b, EdgeKind::Lock);
1042 }
1043
1044 LLVM_DEBUG({
1045 for (unsigned a = 0; a < agents.size(); a++)
1046 for (const Edge &e : edges[a])
1047 llvm::dbgs() << "Wait: " << describe(a) << " on " << describe(e.to)
1048 << (e.kind == EdgeKind::Lock ? " (lock)"
1049 : e.kind == EdgeKind::Stream ? " (stream)"
1050 : " (host)")
1051 << (e.kind == EdgeKind::Lock && !modeled.contains(a)
1052 ? ", assumed"
1053 : "")
1054 << "\n";
1055 });
1056}
1057
1058std::optional<StreamWaitGraph::Agent>
1059StreamWaitGraph::Agent::at(const StreamEndpoint &endpoint, bool sending) {
1060 if (endpoint.port.bundle == WireBundle::Core)
1061 return core(endpoint.tile);
1062 if (endpoint.port.bundle == WireBundle::TileControl && sending)
1063 return controller(endpoint.tile);
1064 if (endpoint.port.bundle == WireBundle::DMA)
1065 return channel({endpoint.tile,
1066 sending ? DMAChannelDir::MM2S : DMAChannelDir::S2MM,
1067 endpoint.port.channel});
1068 // Other ports (PLIO, NOC, a receiving TileControl) are taken to always
1069 // drain, so the streams into them never block.
1070 return std::nullopt;
1071}
1072
1073unsigned StreamWaitGraph::getOrCreate(const Agent &agent) {
1074 auto [it, inserted] =
1075 agentIDs.try_emplace({agent.kind, agent.dma}, agents.size());
1076 if (inserted) {
1077 agents.push_back(agent);
1078 edges.emplace_back();
1079 }
1080 return it->second;
1081}
1082
1083std::optional<unsigned> StreamWaitGraph::lookup(const Agent &agent) const {
1084 auto it = agentIDs.find({agent.kind, agent.dma});
1085 if (it == agentIDs.end())
1086 return std::nullopt;
1087 return it->second;
1088}
1089
1090void StreamWaitGraph::addEdge(unsigned from, unsigned to, EdgeKind kind,
1091 bool sends, bool receives) {
1092 for (Edge &e : edges[from]) {
1093 if (e.to == to && e.kind == kind) {
1094 e.sends |= sends;
1095 e.receives |= receives;
1096 return;
1097 }
1098 }
1099 edges[from].push_back({to, kind, sends, receives});
1100}
1101
1102std::optional<unsigned> StreamWaitGraph::agentAt(const StreamEndpoint &endpoint,
1103 bool sending) const {
1104 if (std::optional<Agent> agent = Agent::at(endpoint, sending))
1105 return lookup(*agent);
1106 return std::nullopt;
1107}
1108
1109SmallVector<unsigned> StreamWaitGraph::drainersOf(unsigned agent) const {
1110 if (agents[agent].kind == Agent::Kind::Core)
1111 return {agent};
1112 SmallVector<unsigned> drainers;
1113 for (const Edge &e : edges[agent])
1114 if (e.kind != EdgeKind::Stream)
1115 drainers.push_back(e.to);
1116 return drainers;
1117}
1118
1119SmallVector<unsigned>
1120StreamWaitGraph::waitChain(ArrayRef<unsigned> from, ArrayRef<unsigned> targets,
1121 ArrayRef<unsigned> avoid) const {
1122 // A state is an agent plus `took`, the subset of channel agents already
1123 // waited on to reach it, and `taking`, whether it was reached as a DMA
1124 // receiver still taking data. A state is dropped once a prior state at the
1125 // same agent is at least as free and took a subset of the same agents: it
1126 // leads nowhere new. Live states per agent therefore form an antichain in
1127 // that subset lattice, so by Sperner's theorem their count can be
1128 // exponential in the worst case -- a known, understood limitation, not an
1129 // oversight. No smaller *exact* representation preserves this dominance
1130 // search's soundness.
1131 struct State {
1132 unsigned agent;
1133 bool taking;
1134 llvm::SparseBitVector<> took;
1135 std::optional<size_t> parent;
1136 };
1137 std::vector<State> states;
1138 DenseMap<unsigned, SmallVector<size_t>> seen;
1139 std::deque<size_t> worklist;
1140 auto visit = [&](State next) {
1141 for (size_t i : seen.lookup(next.agent)) {
1142 const State &s = states[i];
1143 if ((next.taking || !s.taking) && next.took.contains(s.took))
1144 return;
1145 }
1146 seen[next.agent].push_back(states.size());
1147 worklist.push_back(states.size());
1148 states.push_back(std::move(next));
1149 };
1150 for (unsigned a : from)
1151 if (!llvm::is_contained(avoid, a))
1152 visit({a, false, {}, std::nullopt});
1153 while (!worklist.empty()) {
1154 size_t index = worklist.front();
1155 worklist.pop_front();
1156 unsigned a = states[index].agent;
1157 if (llvm::is_contained(targets, a)) {
1158 SmallVector<unsigned> chain;
1159 for (std::optional<size_t> at = index; at; at = states[*at].parent)
1160 chain.push_back(states[*at].agent);
1161 std::reverse(chain.begin(), chain.end());
1162 return chain;
1163 }
1164 for (const Edge &e : edges[a]) {
1165 const State &state = states[index];
1166 if (state.taking && e.receives && !e.sends &&
1167 agents[e.to].kind == Agent::Kind::Channel)
1168 continue;
1169 if (llvm::is_contained(avoid, e.to) || state.took.test(e.to))
1170 continue;
1171 bool takes = e.kind == EdgeKind::Stream && e.sends &&
1172 agents[e.to].kind == Agent::Kind::Channel;
1173 llvm::SparseBitVector<> took = state.took;
1174 if (takes)
1175 took.set(e.to);
1176 visit({e.to, takes, std::move(took), index});
1177 }
1178 }
1179 return {};
1180}
1181
1182std::string StreamWaitGraph::describe(unsigned id) const {
1183 const Agent &a = agents[id];
1184 std::string s;
1185 llvm::raw_string_ostream os(s);
1186 os << "(" << a.dma.tile.col << ", " << a.dma.tile.row << ") ";
1187 if (a.kind == Agent::Kind::Core)
1188 os << "core";
1189 else if (a.kind == Agent::Kind::Controller)
1190 os << "TileControl";
1191 else
1192 os << stringifyDMAChannelDir(a.dma.dir) << " " << a.dma.channel;
1193 return s;
1194}
1195
1197 ArrayRef<RoutedStream> streams)
1198 : streams(streams), volumes(device, streams),
1199 graph(device, streams, volumes), stalls(streams.size()),
1200 silence(streams.size()) {}
1201
1202bool StreamDeadlockAnalysis::canStall(size_t f) const {
1203 std::optional<bool> &stall = stalls[f];
1204 if (!stall)
1205 stall = volumes.canFill(streams[f].dst, streams);
1206 return *stall;
1207}
1208
1209SmallVector<unsigned> StreamDeadlockAnalysis::blockingChain(size_t f,
1210 size_t g) const {
1211 const RoutedStream &fs = streams[f], &gs = streams[g];
1212 std::optional<unsigned> fDst = graph.agentAt(fs.dst, false);
1213 if (!fDst)
1214 return {};
1215 SmallVector<unsigned> own;
1216 if (std::optional<unsigned> fSrc = graph.agentAt(fs.src, true))
1217 own.push_back(*fSrc);
1218 own.push_back(*fDst);
1219 SmallVector<unsigned> drainers = graph.drainersOf(*fDst);
1220 SmallVector<unsigned> avoid, targets;
1221 for (unsigned a : own)
1222 if (!llvm::is_contained(drainers, a))
1223 avoid.push_back(a);
1224 for (std::optional<unsigned> a :
1225 {graph.agentAt(gs.src, true), graph.agentAt(gs.dst, false)})
1226 if (a && !llvm::is_contained(own, *a))
1227 targets.push_back(*a);
1228 if (targets.empty())
1229 return {};
1230 return graph.waitChain(drainers, targets, avoid);
1231}
1232
1233bool StreamDeadlockAnalysis::canBlock(size_t f, size_t g) const {
1234 if (auto it = blocks.find({f, g}); it != blocks.end())
1235 return it->second;
1236 return blocks[{f, g}] = canStall(f) && !silent(f) && !silent(g) &&
1237 volumes.maySendAfter(streams[f], streams[g]) !=
1238 std::optional(false) &&
1239 !blockingChain(f, g).empty();
1240}
1241
1243 std::optional<bool> &quiet = silence[f];
1244 if (!quiet)
1245 quiet = volumes.sendVolume(streams[f]) == std::optional<uint64_t>(0);
1246 return *quiet;
1247}
1248
1249std::string StreamDeadlockAnalysis::explainBlock(size_t f, size_t g) const {
1250 const RoutedStream &fs = streams[f], &gs = streams[g];
1251 SmallVector<unsigned> chain = blockingChain(f, g);
1252 std::string s;
1253 llvm::raw_string_ostream os(s);
1254 os << describeStream(fs) << " can fill its receiver, and draining that "
1255 << "waits on ";
1256 for (auto [i, a] : llvm::enumerate(chain))
1257 os << (i ? ", then " : "") << graph.describe(a);
1258 os << (graph.agentAt(gs.dst, false) == chain.back() ? ", which receives "
1259 : ", which sends ")
1260 << describeStream(gs) << '.';
1261 for (const std::string &a : assumptions(f, g))
1262 os << ' ' << a;
1263 return s;
1264}
1265
1266SmallVector<std::string> StreamDeadlockAnalysis::assumptions(size_t f,
1267 size_t g) const {
1268 const RoutedStream &fs = streams[f], &gs = streams[g];
1269 SmallVector<std::string> assumed;
1270 for (const RoutedStream &other : streams)
1271 if (other.dst == fs.dst && !volumes.sendVolume(other)) {
1272 assumed.push_back("The volume " + describeStream(other) +
1273 " carries is unknown, so it is assumed to overrun its "
1274 "receiver.");
1275 break;
1276 }
1277 if (fs.src == gs.src && !volumes.maySendAfter(fs, gs))
1278 assumed.push_back("Both come from " +
1279 describeTilePort(fs.src.tile, fs.src.port) +
1280 ", and the order it sends in is not modeled.");
1281 SmallVector<unsigned> chain = blockingChain(f, g);
1282 std::optional<unsigned> receiver = graph.agentAt(fs.dst, false);
1283 assert(receiver && "a stream that can block has a receiver");
1284 SmallVector<unsigned> waiters{*receiver};
1285 waiters.append(chain.begin(), std::prev(chain.end()));
1286 for (auto [i, a] : llvm::enumerate(waiters))
1287 if (!graph.isModeled(a) &&
1288 !llvm::is_contained(ArrayRef(waiters).take_front(i), a))
1289 assumed.push_back(
1290 "Nothing in the design programs " + graph.describe(a) +
1291 ", so it is assumed to wait on anything on its tile" +
1292 (graph.getAgent(a).onShim ? " or on another shim tile." : "."));
1293 return assumed;
1294}
1295
1296std::string AIE::describeStream(const RoutedStream &stream) {
1297 std::string s;
1298 llvm::raw_string_ostream os(s);
1299 os << (stream.packetID ? "packet flow " : "flow ")
1300 << describeTilePort(stream.src.tile, stream.src.port) << " -> "
1301 << describeTilePort(stream.dst.tile, stream.dst.port);
1302 if (stream.packetID)
1303 os << " (id " << *stream.packetID << ")";
1304 return s;
1305}
1306
1308 : device(device), streams(requestedStreams(device)),
1309 numRequested(streams.size()) {
1310 for (RoutedStream &s : traceRoutedStreams(device))
1311 streams.push_back(std::move(s));
1312 std::map<TreeKey, size_t> treeIDs;
1313 for (size_t i = 0; i < streams.size(); i++) {
1314 size_t tree = treeMembers.size();
1315 if (std::optional<TreeKey> key = treeKey(i))
1316 tree = treeIDs.try_emplace(*key, tree).first->second;
1317 if (tree == treeMembers.size())
1318 treeMembers.emplace_back();
1319 treeMembers[tree].push_back(i);
1320 treeOf.push_back(tree);
1321 }
1322 waits.resize(treeMembers.size());
1323}
1324
1325std::optional<StreamConflicts::TreeKey>
1326StreamConflicts::treeKey(size_t s) const {
1327 const RoutedStream &stream = streams[s];
1328 if (!stream.packetID)
1329 return std::nullopt;
1330 return TreeKey{stream.src.tile, stream.src.port, *stream.packetID,
1331 s < numRequested};
1332}
1333
1334const StreamDeadlockAnalysis &StreamConflicts::getAnalysis() const {
1335 if (!analysis)
1336 analysis.emplace(device, streams);
1337 return *analysis;
1338}
1339
1340bool StreamConflicts::blocks(size_t s, size_t t) const {
1341 const RoutedStream &a = streams[s], &b = streams[t];
1342 if (a.src == b.src || a.dst == b.dst)
1343 return false;
1344 return getAnalysis().canBlock(s, t);
1345}
1346
1347// Trees from one source, or into one receiver, already wait on each other
1348// there whatever the routing.
1349bool StreamConflicts::related(size_t s, size_t t) const {
1350 if (streams[s].src == streams[t].src)
1351 return true;
1352 for (size_t m : treeMembers[treeOf[s]])
1353 for (size_t n : treeMembers[treeOf[t]])
1354 if (streams[m].dst == streams[n].dst)
1355 return true;
1356 return false;
1357}
1358
1359bool StreamConflicts::conflict(size_t s, size_t t) const {
1360 return !related(s, t) && (blocks(s, t) || blocks(t, s));
1361}
1362
1363// The chains holdCycle follows from a tree stuck at a receiver to the trees
1364// it waits on, which hold for any routing.
1365const DenseMap<size_t, std::pair<size_t, size_t>> &
1366StreamConflicts::waitsFrom(size_t a) const {
1367 std::optional<DenseMap<size_t, std::pair<size_t, size_t>>> &cached = waits[a];
1368 if (cached)
1369 return *cached;
1370 DenseMap<size_t, std::pair<size_t, size_t>> &reached = cached.emplace();
1371 std::deque<size_t> work{a};
1372 while (!work.empty()) {
1373 size_t u = work.front();
1374 work.pop_front();
1375 for (size_t g = 0; g < treeMembers.size(); g++) {
1376 if (g == a || reached.contains(g) ||
1377 !streams[treeMembers[g].front()].packetID)
1378 continue;
1379 auto by = [&]() -> std::optional<std::pair<size_t, size_t>> {
1380 for (size_t x : treeMembers[u])
1381 for (size_t m : treeMembers[g])
1382 if (blocks(x, m))
1383 return std::pair{x, m};
1384 return std::nullopt;
1385 }();
1386 if (!by)
1387 continue;
1388 reached[g] = *by;
1389 work.push_back(g);
1390 }
1391 }
1392 return reached;
1393}
1394
1395bool StreamConflicts::mustSeparate(size_t s, size_t t) const {
1396 if (related(s, t))
1397 return false;
1398 return blocks(s, t) || blocks(t, s) ||
1399 waitsFrom(treeOf[s]).contains(treeOf[t]) ||
1400 waitsFrom(treeOf[t]).contains(treeOf[s]);
1401}
1402
1403std::string StreamConflicts::explain(size_t s, size_t t) const {
1404 const StreamDeadlockAnalysis &a = getAnalysis();
1405 if (a.canBlock(s, t))
1406 return a.explainBlock(s, t);
1407 if (a.canBlock(t, s))
1408 return a.explainBlock(t, s);
1409 if (!waitsFrom(treeOf[s]).contains(treeOf[t]))
1410 std::swap(s, t);
1411 SmallVector<std::string> steps;
1412 for (size_t g = treeOf[t]; g != treeOf[s];) {
1413 auto [x, m] = waitsFrom(treeOf[s]).at(g);
1414 steps.push_back(a.explainBlock(x, m));
1415 g = treeOf[x];
1416 }
1417 std::reverse(steps.begin(), steps.end());
1418 return llvm::join(steps, " ");
1419}
1420
1421SmallVector<std::pair<size_t, size_t>> StreamConflicts::unavoidable() const {
1422 SmallVector<std::pair<size_t, size_t>> pairs;
1423 const StreamDeadlockAnalysis &a = getAnalysis();
1424 for (size_t s = 0; s < numRequested; s++)
1425 for (size_t t = 0; t < numRequested; t++) {
1426 // A tree's branches move as one, as a circuit broadcast's do, so a wait
1427 // between them is the design's own.
1428 if (s == t || treeOf[s] == treeOf[t] ||
1429 !(streams[s].packetID || streams[t].packetID) || !related(s, t) ||
1430 !a.canBlock(s, t))
1431 continue;
1432 if (a.assumptions(s, t).empty())
1433 pairs.push_back({s, t});
1434 else
1435 LLVM_DEBUG(llvm::dbgs() << "Unavoidable only by assumption: "
1436 << a.explainBlock(s, t) << "\n");
1437 }
1438 return pairs;
1439}
1440
1441namespace {
1442// A wait in the graph holdCycle searches: a head stuck at one node waits on
1443// one at `to`, for the reason `step` gives, if any.
1444struct WaitEdge {
1445 size_t to;
1446 std::optional<HoldCycle::Step> step;
1447 // For a link wait, each switchbox and arbiter above the link that granted
1448 // both trees it in turn.
1449 SmallVector<std::pair<TileID, int>, 4> orders = {};
1450};
1451// The graph holdCycle searches, built as it is walked. Node `entry` leads to
1452// every root.
1453struct WaitGraph {
1454 llvm::function_ref<ArrayRef<WaitEdge>(size_t)> successors;
1455 size_t entry;
1456};
1457using WaitNode = std::pair<const WaitGraph *, size_t>;
1458} // namespace
1459
1460namespace llvm {
1461template <>
1462struct GraphTraits<const WaitGraph *> {
1463 using NodeRef = WaitNode;
1464 struct ToNode {
1465 const WaitGraph *graph;
1466 NodeRef operator()(const WaitEdge &e) const { return {graph, e.to}; }
1467 };
1468 using ChildIteratorType = mapped_iterator<const WaitEdge *, ToNode>;
1469 static NodeRef getEntryNode(const WaitGraph *g) { return {g, g->entry}; }
1471 return map_iterator(n.first->successors(n.second).begin(), ToNode{n.first});
1472 }
1474 return map_iterator(n.first->successors(n.second).end(), ToNode{n.first});
1475 }
1476};
1477} // namespace llvm
1478
1479std::optional<HoldCycle>
1480StreamConflicts::holdCycle(ArrayRef<SmallVector<StreamHop, 8>> routes,
1481 bool forcedWaits, bool definite) const {
1482 // The packets one source sends with one id move down every branch as one.
1483 struct Tree {
1484 SmallVector<size_t, 2> members;
1485 SmallVector<std::pair<TileID, Port>, 8> hops;
1486 SmallVector<int, 8> parent;
1487 SmallVector<std::optional<int>, 8> arbiter;
1488 size_t base = 0;
1489 };
1490 std::vector<Tree> trees;
1491 std::map<TreeKey, size_t> treeIDs;
1492 for (size_t i = 0; i < streams.size(); i++) {
1493 std::optional<TreeKey> key = treeKey(i);
1494 if (!key || getAnalysis().silent(i))
1495 continue;
1496 auto [it, inserted] = treeIDs.try_emplace(*key, trees.size());
1497 if (inserted)
1498 trees.emplace_back();
1499 Tree &tree = trees[it->second];
1500 tree.members.push_back(i);
1501 int prev = -1;
1502 for (const StreamHop &hop : routes[i]) {
1503 std::pair<TileID, Port> key{hop.tile, hop.input};
1504 int h = llvm::find(tree.hops, key) - tree.hops.begin();
1505 if (h == static_cast<int>(tree.hops.size())) {
1506 tree.hops.push_back(key);
1507 tree.parent.push_back(prev);
1508 tree.arbiter.push_back(hop.arbiter);
1509 }
1510 prev = h;
1511 }
1512 }
1513
1514 // One source sends one tree's packet at a time. Trees into one receiver are
1515 // both in flight at once, and wait on each other at its master port however
1516 // they are routed, where both enter its switchbox for it; and trees with one
1517 // id wait on each other where they meet and below, going on as one. Those
1518 // waits count only with `forcedWaits`.
1519 auto sameSource = [&](size_t a, size_t b) {
1520 return streams[trees[a].members.front()].src ==
1521 streams[trees[b].members.front()].src;
1522 };
1523 auto forced = [&](size_t a, int ha, size_t b, int hb, TileID tile) {
1524 Port ina = trees[a].hops[ha].second, inb = trees[b].hops[hb].second;
1525 auto into = [&](size_t m, Port in) {
1526 return streams[m].dst.tile == tile && !routes[m].empty() &&
1527 routes[m].back().tile == tile && routes[m].back().input == in;
1528 };
1529 for (size_t m : trees[a].members)
1530 for (size_t n : trees[b].members)
1531 if (streams[m].dst == streams[n].dst && into(m, ina) && into(n, inb))
1532 return true;
1533 if (streams[trees[a].members.front()].packetID !=
1534 streams[trees[b].members.front()].packetID)
1535 return false;
1536 for (auto above : llvm::enumerate(trees[a].parent))
1537 if (above.value() == ha &&
1538 llvm::any_of(llvm::enumerate(trees[b].parent), [&](auto below) {
1539 return below.value() == hb &&
1540 trees[b].hops[below.index()] == trees[a].hops[above.index()];
1541 }))
1542 return true;
1543 return false;
1544 };
1545
1546 // Per tree, a node for a head of it stuck entering each hop or at each
1547 // receiver, one for it stuck anywhere, and one per hop for it stuck
1548 // anywhere past that hop, so still holding what it took there.
1549 enum class Kind { Hop, Receiver, Anywhere, Past };
1550 struct Node {
1551 size_t tree;
1552 Kind kind;
1553 size_t index;
1554 };
1555 std::vector<Node> nodes;
1556 for (size_t t = 0; t < trees.size(); t++) {
1557 Tree &tree = trees[t];
1558 tree.base = nodes.size();
1559 for (size_t h = 0; h < tree.hops.size(); h++)
1560 nodes.push_back({t, Kind::Hop, h});
1561 for (size_t m = 0; m < tree.members.size(); m++)
1562 nodes.push_back({t, Kind::Receiver, m});
1563 nodes.push_back({t, Kind::Anywhere, 0});
1564 for (size_t h = 0; h < tree.hops.size(); h++)
1565 nodes.push_back({t, Kind::Past, h});
1566 }
1567 auto receiverNode = [&](size_t t, size_t m) {
1568 return trees[t].base + trees[t].hops.size() + m;
1569 };
1570 auto anywhereNode = [&](size_t t) {
1571 return receiverNode(t, trees[t].members.size());
1572 };
1573 auto pastNode = [&](size_t t, size_t h) { return anywhereNode(t) + 1 + h; };
1574
1575 std::map<std::pair<TileID, Port>, SmallVector<std::pair<size_t, size_t>, 4>>
1576 entering;
1577 std::map<TileID, SmallVector<std::pair<size_t, size_t>, 8>> passing;
1578 for (size_t t = 0; t < trees.size(); t++)
1579 for (size_t h = 0; h < trees[t].hops.size(); h++) {
1580 entering[trees[t].hops[h]].push_back({t, h});
1581 passing[trees[t].hops[h].first].push_back({t, h});
1582 }
1583
1584 // The arbiters that granted two trees a hop they share in one order: the
1585 // one both took to leave the switchbox above it where they came into it
1586 // apart. Also each arbiter on their shared path below it, provided each
1587 // tree passes it only once.
1588 using Grant = std::pair<TileID, int>;
1589 auto orderedBy = [&](size_t a, int ha, size_t b, int hb) {
1590 SmallVector<Grant, 4> grants;
1591 auto once = [&](size_t t, const Grant &g) {
1592 return llvm::count_if(llvm::seq<size_t>(0, trees[t].hops.size()),
1593 [&](size_t h) {
1594 return trees[t].hops[h].first == g.first &&
1595 trees[t].arbiter[h] == g.second;
1596 }) == 1;
1597 };
1598 for (;;) {
1599 int pa = trees[a].parent[ha], pb = trees[b].parent[hb];
1600 if (pa < 0 || pb < 0)
1601 return grants;
1602 std::optional<int> arbiter = trees[a].arbiter[pa];
1603 bool shared = trees[a].hops[pa] == trees[b].hops[pb];
1604 if (trees[a].hops[pa].first == trees[b].hops[pb].first && arbiter &&
1605 arbiter == trees[b].arbiter[pb]) {
1606 Grant g{trees[a].hops[pa].first, *arbiter};
1607 if (!shared)
1608 grants.insert(grants.begin(), g);
1609 else if (once(a, g) && once(b, g))
1610 grants.push_back(g);
1611 }
1612 if (!shared)
1613 return grants;
1614 ha = pa;
1615 hb = pb;
1616 }
1617 };
1618
1619 using Edge = WaitEdge;
1620 SmallVector<size_t> roots;
1621 std::vector<std::optional<SmallVector<Edge, 4>>> edges(nodes.size() + 1);
1622 auto successors = [&](size_t n) -> ArrayRef<Edge> {
1623 if (edges[n])
1624 return *edges[n];
1625 SmallVector<Edge, 4> out;
1626 if (n == nodes.size()) {
1627 for (size_t root : roots)
1628 out.push_back({root, std::nullopt});
1629 return *(edges[n] = std::move(out));
1630 }
1631 const Node &node = nodes[n];
1632 const Tree &u = trees[node.tree];
1633 switch (node.kind) {
1634 case Kind::Hop: {
1635 auto [tile, input] = u.hops[node.index];
1636 size_t waiting = u.members.front();
1637 for (auto [t, ht] : entering.at({tile, input})) {
1638 if (t != node.tree && sameSource(node.tree, t))
1639 continue;
1640 size_t sharer = trees[t].members.front();
1641 bool sameId = streams[waiting].packetID == streams[sharer].packetID;
1642 if (t != node.tree && (!sameId || forcedWaits))
1643 out.push_back(
1644 {pastNode(t, ht),
1645 HoldCycle::Step{HoldCycle::Wait::Link, waiting, sharer, sharer,
1646 tile, input, input, -1, sameId},
1647 orderedBy(node.tree, node.index, t, ht)});
1648 std::optional<int> arbiter = trees[t].arbiter[ht];
1649 if (!arbiter)
1650 continue;
1651 // A tree's branches move as one, so where two come into a switchbox
1652 // apart onto one arbiter, the one holding it waits on the other.
1653 for (auto [v, hv] : passing.at(tile)) {
1654 Port holderInput = trees[v].hops[hv].second;
1655 bool self = v == node.tree && t == node.tree;
1656 if ((!self && (v == node.tree || v == t || sameSource(t, v))) ||
1657 holderInput == input || trees[v].arbiter[hv] != arbiter)
1658 continue;
1659 bool isForced = !self && forced(t, ht, v, hv, tile);
1660 if (isForced && !forcedWaits)
1661 continue;
1662 out.push_back(
1663 {pastNode(v, hv),
1665 trees[v].members.front(), tile, input,
1666 holderInput, *arbiter, isForced}});
1667 }
1668 }
1669 break;
1670 }
1671 case Kind::Receiver: {
1672 // A tree into the full receiver is stuck there however it is routed.
1673 size_t s = u.members[node.index];
1674 for (size_t g = 0; g < trees.size(); g++) {
1675 if (g == node.tree || llvm::any_of(trees[g].members, [&](size_t m) {
1676 return streams[m].dst == streams[s].dst;
1677 }))
1678 continue;
1679 for (size_t m : trees[g].members)
1680 if (blocks(s, m) &&
1681 (!definite || getAnalysis().assumptions(s, m).empty())) {
1682 out.push_back({anywhereNode(g),
1684 TileID{}, Port{}, Port{}, -1}});
1685 break;
1686 }
1687 }
1688 break;
1689 }
1690 case Kind::Anywhere:
1691 case Kind::Past: {
1692 llvm::SmallDenseSet<size_t, 8> behind;
1693 if (node.kind == Kind::Past)
1694 for (int h = node.index; h >= 0; h = u.parent[h])
1695 behind.insert(h);
1696 for (size_t h = 0; h < u.hops.size(); h++)
1697 if (!behind.contains(h))
1698 out.push_back({u.base + h, std::nullopt});
1699 for (size_t m = 0; m < u.members.size(); m++)
1700 out.push_back({receiverNode(node.tree, m), std::nullopt});
1701 break;
1702 }
1703 }
1704 return *(edges[n] = std::move(out));
1705 };
1706
1707 // A cycle of receivers alone waiting on each other is the design's own, so
1708 // only cycles through a wait some requested routing adds count.
1709 auto counts = [&](const Edge &e) {
1710 if (!e.step || e.step->wait == HoldCycle::Wait::Drain)
1711 return false;
1712 return e.step->waiting < numRequested || e.step->sharer < numRequested ||
1713 e.step->holding < numRequested;
1714 };
1715 for (size_t n = 0; n < nodes.size(); n++)
1716 if (nodes[n].kind == Kind::Hop && llvm::any_of(successors(n), counts))
1717 roots.push_back(n);
1718
1719 const WaitGraph graph{successors, nodes.size()};
1720 std::vector<int> component(nodes.size() + 1, -1);
1721 int components = 0;
1722 for (auto scc = llvm::scc_begin(&graph); !scc.isAtEnd(); ++scc, ++components)
1723 for (WaitNode n : *scc)
1724 component[n.second] = components;
1725
1726 // A counted wait within one component lies on a closed walk. No state has two
1727 // trees holding one arbiter (see HoldCycle), so a walk that needs that is no
1728 // deadlock. Nor is one where each packet is behind the next on links one
1729 // arbiter granted them all in one order, so a walk from a link wait must,
1730 // for each arbiter that ordered that link, also wait otherwise. The search
1731 // fixes or rules out a holder per arbiter until the shortest walk left
1732 // agrees. Each clash splits it in two, so past maxWalkSearches it keeps the
1733 // first walk, which at worst steers the router off a routing that cannot
1734 // deadlock.
1735 struct Holders {
1736 std::optional<size_t> fixed;
1737 SmallVector<size_t, 2> excluded;
1738 };
1739 using Constraints = std::map<Grant, Holders>;
1740 auto allowed = [](const Edge &edge, const Constraints &c) {
1741 if (!edge.step || edge.step->wait != HoldCycle::Wait::Arbiter)
1742 return true;
1743 auto it = c.find({edge.step->tile, edge.step->arbiter});
1744 if (it == c.end())
1745 return true;
1746 size_t holder = edge.step->holding;
1747 return it->second.fixed ? *it->second.fixed == holder
1748 : !llvm::is_contained(it->second.excluded, holder);
1749 };
1750 // Arbiters past these that ordered a link go untracked, which at worst steers
1751 // the router off a routing that cannot deadlock.
1752 constexpr size_t maxOrders = 8;
1753 auto closeWalk =
1754 [&](size_t x, const Edge &e,
1755 const Constraints &c) -> std::optional<SmallVector<const Edge *>> {
1756 if (!allowed(e, c))
1757 return std::nullopt;
1758 // A state is a node and, per arbiter that ordered e's link, whether the
1759 // walk there has waited other than on a link it ordered too.
1760 size_t k = std::min<size_t>(e.orders.size(), maxOrders);
1761 auto unordered = [&](const Edge &edge) {
1762 size_t mask = 0;
1763 for (size_t i = 0; i < k; i++)
1764 if (edge.step && !llvm::is_contained(edge.orders, e.orders[i]))
1765 mask |= size_t(1) << i;
1766 return mask;
1767 };
1768 size_t all = (size_t(1) << k) - 1;
1769 auto state = [&](size_t node, size_t mask) { return (node << k) | mask; };
1770 size_t start = state(e.to, 0), end = state(x, all);
1771 DenseMap<size_t, std::pair<size_t, const Edge *>> via;
1772 via[start] = {start, nullptr};
1773 std::deque<size_t> worklist{start};
1774 while (!via.contains(end)) {
1775 if (worklist.empty())
1776 return std::nullopt;
1777 size_t n = worklist.front();
1778 worklist.pop_front();
1779 for (const Edge &next : successors(n >> k)) {
1780 size_t to = state(next.to, (n & all) | unordered(next));
1781 if (component[next.to] == component[x] && allowed(next, c) &&
1782 via.try_emplace(to, n, &next).second)
1783 worklist.push_back(to);
1784 }
1785 }
1786 SmallVector<const Edge *> path;
1787 for (size_t n = end; n != start; n = via.at(n).first)
1788 path.push_back(via.at(n).second);
1789 path.push_back(&e);
1790 std::reverse(path.begin(), path.end());
1791 return path;
1792 };
1793 auto toCycle = [](ArrayRef<const Edge *> path) {
1794 HoldCycle cycle;
1795 for (const Edge *edge : path)
1796 if (edge->step)
1797 cycle.steps.push_back(*edge->step);
1798 return cycle;
1799 };
1800 constexpr int maxWalkSearches = 1024;
1801 for (size_t x : roots)
1802 for (const Edge &e : successors(x)) {
1803 if (!counts(e) || component[e.to] != component[x])
1804 continue;
1805 std::optional<SmallVector<const Edge *>> first;
1806 SmallVector<Constraints> pending{{}};
1807 int search = 0;
1808 for (; !pending.empty(); search++) {
1809 if (search == maxWalkSearches) {
1810 assert(first && "only a walk found adds pending constraints");
1811 LLVM_DEBUG(llvm::dbgs() << "Hold cycle search gave up after "
1812 << search << " walks\n");
1813 return toCycle(*first);
1814 }
1815 Constraints c = pending.pop_back_val();
1816 std::optional<SmallVector<const Edge *>> path = closeWalk(x, e, c);
1817 if (!path)
1818 continue;
1819 if (!first)
1820 first = path;
1821 std::map<Grant, size_t> held;
1822 std::optional<std::pair<Grant, size_t>> clash;
1823 for (const Edge *edge : *path) {
1824 if (!edge->step || edge->step->wait != HoldCycle::Wait::Arbiter)
1825 continue;
1826 auto [it, inserted] = held.try_emplace(
1827 {edge->step->tile, edge->step->arbiter}, edge->step->holding);
1828 if (!inserted && it->second != edge->step->holding) {
1829 clash = *it;
1830 break;
1831 }
1832 }
1833 if (!clash) {
1834 LLVM_DEBUG(llvm::dbgs() << "Hold cycle search closed a walk after "
1835 << search + 1 << " walks\n");
1836 return toCycle(*path);
1837 }
1838 Constraints fix = c, exclude = c;
1839 fix[clash->first].fixed = clash->second;
1840 exclude[clash->first].excluded.push_back(clash->second);
1841 pending.push_back(std::move(exclude));
1842 pending.push_back(std::move(fix));
1843 }
1844 LLVM_DEBUG(llvm::dbgs() << "Hold cycle search closed no walk after "
1845 << search << " walks\n");
1846 }
1847 return std::nullopt;
1848}
1849
1850std::string StreamConflicts::explain(const HoldCycle &cycle) const {
1851 std::string s;
1852 llvm::raw_string_ostream os(s);
1853 for (auto [i, step] : llvm::enumerate(cycle.steps)) {
1854 if (i)
1855 os << ' ';
1856 switch (step.wait) {
1858 os << describeStream(streams[step.waiting]) << " can queue behind "
1859 << describeStream(streams[step.holding]) << " on "
1860 << describePort(step.sharerInput) << " into tile (" << step.tile.col
1861 << ", " << step.tile.row << ").";
1862 break;
1864 os << describeStream(streams[step.holding]) << " can hold arbiter "
1865 << step.arbiter << " at tile (" << step.tile.col << ", "
1866 << step.tile.row << ") that " << describeStream(streams[step.sharer])
1867 << " needs";
1868 if (step.waiting != step.sharer)
1869 os << ", and " << describeStream(streams[step.waiting])
1870 << " can queue behind it";
1871 os << ".";
1872 break;
1874 os << getAnalysis().explainBlock(step.waiting, step.holding);
1875 break;
1876 }
1877 }
1878 return s;
1879}
constexpr int maxBDSteps
bool isShimNOCorPLTile(int col, int row) const
Return true if the given tile is either a ShimNOC or ShimPL tile.
bool hasProperty(ModelProperty Prop) const
llvm::SmallVector< std::pair< size_t, size_t > > unavoidable() const
The requested streams where the first can hold up the second however they are routed,...
bool mustSeparate(size_t s, size_t t) const
Whether a routing that puts packet streams s and t on one arbiter anywhere has a hold cycle: they con...
bool conflict(size_t s, size_t t) const
Whether s and t can deadlock if they share an arbiter or a link.
std::optional< HoldCycle > holdCycle(llvm::ArrayRef< llvm::SmallVector< StreamHop, 8 > > routes, bool forcedWaits=false, bool definite=false) const
A cycle of waits the packet streams can deadlock in when routed along routes, indexed like getStreams...
std::string explain(size_t s, size_t t) const
Why s and t conflict.
Which streams can deadlock against each other if they share an arbiter or a link.
bool canBlock(size_t f, size_t g) const
Whether stream f, stalled at its receiver, can keep stream g from ever arriving: f carries more than ...
std::string explainBlock(size_t f, size_t g) const
Why f can block g: the chain of waits from f's receiver to g, and which links of it are assumed for l...
bool silent(size_t f) const
Whether stream f carries nothing, so it neither holds nor waits.
llvm::SmallVector< std::string > assumptions(size_t f, size_t g) const
What explainBlock(f, g) takes on trust rather than reads off the design, one sentence each.
StreamDeadlockAnalysis(DeviceOp device, llvm::ArrayRef< RoutedStream > streams)
streams must outlive the analysis.
How much data a stream carries over a run and how much a receiver takes in before it has to wait on a...
StreamVolumeAnalysis(DeviceOp device, llvm::ArrayRef< RoutedStream > streams)
std::optional< uint64_t > sendVolume(const RoutedStream &stream) const
Bytes the stream's source sends with the stream's packet id, headers included where the receiver keep...
std::optional< uint64_t > receiveCapacity(const StreamEndpoint &endpoint) const
Bytes the receiver at endpoint accepts before it waits on another agent, or nullopt when it never doe...
bool canFill(const StreamEndpoint &endpoint, llvm::ArrayRef< RoutedStream > streams) const
Whether streams can send the receiver at endpoint more than it takes in before it waits on another ag...
std::optional< bool > maySendAfter(const RoutedStream &first, const RoutedStream &then) const
Whether the source both streams come from can send a packet of then after one of first; nullopt if it...
std::optional< unsigned > agentAt(const StreamEndpoint &endpoint, bool sending) const
The agent pushing data into (sending) or pulling data out of the fabric at endpoint,...
std::string describe(unsigned id) const
llvm::SmallVector< unsigned > waitChain(llvm::ArrayRef< unsigned > from, llvm::ArrayRef< unsigned > targets, llvm::ArrayRef< unsigned > avoid) const
A shortest chain of waits from an agent in from to one in targets that avoids avoid,...
llvm::SmallVector< unsigned > drainersOf(unsigned agent) const
Agents whose progress frees room in agent for more incoming data: a core frees itself,...
StreamWaitGraph(DeviceOp device, llvm::ArrayRef< RoutedStream > streams, const StreamVolumeAnalysis &volumes)
llvm::SmallVector< DmaChannelProgram > collectDmaPrograms(DeviceOp device)
Every DMA channel program: aie.dma_start and aie.dma inside the tile DMA ops, and runtime-configured ...
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
std::string describeStream(const RoutedStream &stream)
Names the stream by its endpoints and packet id, e.g.
std::optional< std::pair< TileID, Port > > getLinkedInput(TileID tile, Port output)
The switchbox input driven by an output's physical wire, with the channel preserved.
const AIETargetModel & getTargetModel(mlir::Operation *op)
bool keepsPktHeader(TileID tile, Port master, std::optional< bool > keep)
std::vector< RoutedStream > requestedStreams(DeviceOp device)
The streams the aie.flow and aie.packet_flow ops ask for, one per source, destination and packet id,...
std::vector< RoutedStream > traceRoutedStreams(DeviceOp device)
Follows every stream from its source tile port through the configured switchboxes,...
std::string describeTilePort(TileID tile, Port port)
Names a tile port the way diagnostics do, e.g. "(0, 2) DMA:1".
struct Port { WireBundle bundle; int channel; bool operator==(const Port &rhs) const { return std::tie(bundle, channel)==std::tie(rhs.bundle, rhs.channel); } bool operator!=(const Port &rhs) const { return !(*this==rhs);} bool operator<(const Port &rhs) const { return std::tie(bundle, channel)< std::tie(rhs.bundle, rhs.channel); } friend std::ostream &operator<<(std::ostream &os, const Port &port) { os<< "("; os<< stringifyWireBundle(port.bundle).str(); os<< ": "<< std::to_string(port.channel)<< ")"; return os; } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Port &port) { os<< to_string(port); return os; } } Port
Definition AIEDialect.h:265
std::string describePort(Port port)
Names a port the way diagnostics do, e.g. "DMA:1".
static ChildIteratorType child_begin(NodeRef n)
mapped_iterator< const WaitEdge *, ToNode > ChildIteratorType
The BD chain a DMA channel runs, as one aie.dma_start, aie.dma or runtime task programs it.
llvm::SmallVector< mlir::Region * > regions
uint64_t passes
Times one start of the channel runs the chain: its repeat count plus one.
bool loops
Whether the BD chain runs forever.
size_t loopStart
The first of bds a looping chain returns to once it has run them all.
llvm::SmallVector< mlir::Block * > bds
A cycle of waits packet streams can deadlock in, given their routes.
llvm::SmallVector< Step, 4 > steps
@ Drain
waiting fills its receiver, and draining that waits on holding.
@ Link
waiting queues behind holding on the port both enter tile by.
@ Arbiter
waiting, or sharer it queues behind, needs the arbiter holding holds at tile; sharer enters by sharer...
One stream from a source tile port to a destination tile port, recovered from the physical switchbox ...
bool carries(std::optional< PacketInfoAttr > packet) const
Whether what a BD sends with header packet, or with none, goes on this stream.
int packetMask
The stream carries every id that agrees with packetID on these bits.
bool keepsPktHeader
The destination stores each packet's header along with its payload.
std::optional< int > packetID
The packet id carried, if any.
A tile port at the edge of the stream fabric.
A switchbox a stream passes: the port it enters by and, where it is packet switched there,...
A core, a DMA channel, or a tile's controller.
static std::optional< Agent > at(const StreamEndpoint &endpoint, bool sending)
Each agent at a stream endpoint: the core, DMA channel or controller pushing data into (sending) or p...
static Agent channel(const TileDMAChannel &dma)