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"
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"
32#define DEBUG_TYPE "aie-stream-dependency"
40std::optional<TileID> tileOf(Value tile) {
41 if (
auto tileOp = dyn_cast_or_null<TileOp>(tile.getDefiningOp()))
42 return tileOp.getTileID();
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());
52 if (
auto start = dyn_cast<DMAStartOp>(op)) {
53 std::optional<TileID> tile = parentTile(op);
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) {
67 auto next = dyn_cast<NextBDOp>(b->getTerminator());
68 b = next ? next.getDest() :
nullptr;
72 if (
auto dma = dyn_cast<DMAOp>(op)) {
73 std::optional<TileID> tile = parentTile(op);
77 {*tile, dma.getChannelDir(), dma.getChannelIndex()}};
78 p.
passes += dma.getRepeatCount();
79 for (Region &r : dma.getBds())
81 p.
loops = dma.getLoop();
84 if (
auto task = dyn_cast<AIEX::DMAConfigureTaskOp>(op)) {
85 std::optional<TileID> tile = tileOf(task.getTile());
89 op, {*tile, task.getDirection(),
static_cast<int>(task.getChannel())}};
90 p.
regions.push_back(&task.getBody());
91 p.
passes += task.getRepeatCount();
94 if (
auto task = dyn_cast<AIEX::DMAConfigureTaskForOp>(op)) {
95 auto alloc = ShimDMAAllocationOp::getForSymbol(
96 device, task.getAlloc().getRootReference());
99 std::optional<TileID> tile = tileOf(alloc.getTile());
103 {*tile, alloc.getChannelDir(),
104 static_cast<int>(alloc.getChannelIndex())}};
105 p.
regions.push_back(&task.getBody());
106 p.
passes += task.getRepeatCount();
112template <
typename OpT>
114 llvm::function_ref<
void(OpT)> fn) {
115 for (Block *b : p.
bds)
116 for (
auto op : b->getOps<OpT>())
119 r->walk([&](OpT op) { fn(op); });
122std::optional<TileDMAChannel> channelOfSymbol(DeviceOp device,
124 auto alloc = ShimDMAAllocationOp::getForSymbol(device, symbol);
127 std::optional<TileID> tile = tileOf(alloc.getTile());
131 static_cast<int>(alloc.getChannelIndex())};
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)
145 Operation *op = v.getDefiningOp();
146 if (isa_and_nonnull<AIEX::DMAConfigureTaskOp, AIEX::DMAConfigureTaskForOp,
147 AIEX::DMAStartBdChainOp, AIEX::DMAStartBdChainForOp>(
149 creators.push_back(op);
153 op ? op : cast<BlockArgument>(v).getOwner()->getParentOp();
154 auto branch = dyn_cast_or_null<RegionBranchOpInterface>(owner);
157 RegionBranchInverseSuccessorMapping mapping;
158 branch.getSuccessorInputOperandMapping(mapping);
159 auto it = mapping.find(v);
160 if (it == mapping.end())
162 for (OpOperand *operand : it->second)
163 worklist.push_back(operand->get());
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))
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());
188 if (!llvm::is_contained(keys, *key))
189 keys.push_back(*key);
197void walkLoopsTwice(Region ®ion, function_ref<
void(Operation *)> fn) {
198 for (Operation &op : region.getOps()) {
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);
209std::map<TileDMAChannel, std::set<int>> collectSentPacketIDs(DeviceOp device) {
210 std::map<TileDMAChannel, std::set<int>> ids;
212 if (p.
dma.
dir != DMAChannelDir::MM2S)
214 forEachInProgram<DMABDOp>(p, [&](DMABDOp bd) {
215 if (std::optional<PacketInfoAttr> packet = bd.getPacket())
216 ids[p.
dma].insert(packet->assignedId());
219 for (
auto alloc : device.getOps<ShimDMAAllocationOp>()) {
220 std::optional<PacketInfoAttr> packet = alloc.getPacket();
221 std::optional<TileID> tile = tileOf(alloc.getTile());
223 ids[{*tile, alloc.getChannelDir(),
224 static_cast<int>(alloc.getChannelIndex())}]
225 .insert(packet->assignedId());
227 device.walk([&](AIEX::NpuDmaMemcpyNdOp memcpy) {
228 std::optional<PacketInfoAttr> packet = memcpy.getPacket();
231 if (std::optional<TileDMAChannel> key =
232 channelOfSymbol(device, memcpy.getMetadata().getRootReference()))
233 ids[*key].insert(packet->assignedId());
240 explicit StreamTracer(DeviceOp device)
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);
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()))
259 traceFrom({tile, p}, sb, p);
260 return std::move(streams);
265 Interconnect interconnect;
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))
284 std::optional<std::set<int>> ids;
286 if (src.
port.bundle == WireBundle::DMA) {
287 auto it = sentIDs.find({src.
tile, DMAChannelDir::MM2S, src.
port.channel});
288 if (it != sentIDs.end())
292 step(src, {interconnect, input}, std::nullopt);
296 step(src, {interconnect, input}, id);
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}};
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}};
313 if (
auto sb = switchboxes.find(next->first); sb != switchboxes.end())
314 return Hop{sb->second, next->second};
321 std::pair<Operation *, Port> input{hop.interconnect, hop.input};
322 if (!onPath.insert(input).second)
324 llvm::scope_exit leave([&] { onPath.erase(input); });
325 auto sb = dyn_cast<SwitchboxOp>(hop.interconnect.getOperation());
326 Block &b = hop.interconnect.getConnections().front();
328 auto next = [&](
Port out, std::optional<int> nextID,
331 path.push_back({sb.getTileOp().getTileID(), hop.input, arbiter});
332 llvm::scope_exit backtrack([&] {
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});
340 step(src, std::get<Hop>(to), nextID);
343 for (
auto connect : b.getOps<ConnectOp>())
344 if (connect.sourcePort() == hop.input)
345 next(connect.destPort(),
id, std::nullopt);
347 for (
auto rules : b.getOps<PacketRulesOp>()) {
348 if (rules.sourcePort() != hop.input)
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());
359 for (
int packetID =
id.value_or(0); packetID <=
id.value_or(maxPacketID);
361 for (
auto rule : rules.getRules().front().getOps<PacketRuleOp>())
362 if ((packetID & rule.maskInt()) ==
363 (rule.valueInt() & rule.maskInt())) {
364 route(rule, packetID);
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;
376 llvm::DenseSet<std::pair<Operation *, Port>> onPath;
377 SmallVector<StreamHop, 8> path;
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));
395 return StreamTracer(device).trace();
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)
405 {{*srcTile, {flow.getSourceBundle(), flow.sourceIndex()}},
406 {*dstTile, {flow.getDestBundle(), flow.destIndex()}},
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());
422 for (
auto dst : b.getOps<PacketDestOp>())
423 if (std::optional<TileID> dstTile = tileOf(dst.getTile()))
425 {{*srcTile, src.port()},
426 {*dstTile, dst.port()},
429 keepAt.lookup({*dstTile, dst.port()})),
431 static_cast<int>(flow.getMask().value_or(~0))});
438 ArrayRef<RoutedStream> streams)
439 : device(device), streams(streams) {
441 programs[p.dma].push_back(std::move(p));
442 for (
const auto &[dma, channelPrograms] : programs)
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);
454static SmallVector<Block *> chainBlocks(
const DmaChannelProgram &p) {
455 SmallVector<Block *> sequence(p.
bds);
457 sequence.push_back(&r->front());
464static size_t blockAt(
const DmaChannelProgram &p,
size_t size, uint64_t step) {
468 return start + (step - start) % (size - start);
472static std::optional<int64_t> lockAmount(UseLockOp use) {
474 if (!use.getLock().getDefiningOp<LockOp>() ||
475 !matchPattern(use.getValue(), m_ConstantInt(&amount)))
477 return amount.getSExtValue();
481static std::optional<uint64_t> lockTokens(UseLockOp use) {
482 std::optional<int64_t> n = lockAmount(use);
490std::optional<uint64_t>
492 if (stream.
src.
port.bundle != WireBundle::DMA)
496 constexpr uint64_t pktHeaderBytes = 4;
497 auto headerBytes = [&](std::optional<PacketInfoAttr> packet) -> uint64_t {
500 auto bytesOf = [&](DMABDOp bd) -> uint64_t {
501 if (!stream.
carries(bd.getPacket()))
503 return bd.getLenInBytes() + headerBytes(bd.getPacket());
507 if (
auto it = programs.find(dma); it != programs.end()) {
509 bool carried =
false;
511 forEachInProgram<DMABDOp>(p, [&](DMABDOp bd) {
512 if (!stream.
carries(bd.getPacket()))
515 bytes += bytesOf(bd);
521 std::optional<uint64_t> looped = loopedVolume(p, bytesOf);
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()))
535 for (Operation *user : p.
op->getUsers()) {
536 if (isa<AIEX::DMAAwaitTaskOp, AIEX::DMAFreeTaskOp>(user))
540 auto start = dyn_cast<AIEX::DMAStartTaskOp>(user);
541 if (!start || start.hasRepeatParameter())
543 if (user->getParentOfType<LoopLikeOpInterface>())
548 total += bytes * runs;
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();
556 packet = ShimDMAAllocationOp::getForSymbol(
557 device, memcpy.getMetadata().getRootReference())
561 auto type = dyn_cast<BaseMemRefType>(memcpy.getMemref().getType());
562 if (memcpy->getParentOfType<LoopLikeOpInterface>() || !type ||
563 !type.getElementType().isIntOrFloat())
565 std::optional<SmallVector<int64_t>> sizes =
566 getConstantIntValues(memcpy.getMixedSizes());
569 uint64_t elements = 1;
570 for (int64_t n : *sizes)
574 uint64_t runs = sizes->front();
576 total += elements * type.getElementTypeBitWidth() / 8 +
577 runs * headerBytes(packet);
585std::optional<uint64_t> StreamVolumeAnalysis::loopedVolume(
587 function_ref<uint64_t(DMABDOp)> bytesOf)
const {
589 if (!walkLoop(program, [&](DMABDOp bd) { bytes += bytesOf(bd); }))
595 function_ref<
void(DMABDOp)> visit)
const {
598 !visiting.insert(&p).second)
600 llvm::scope_exit done([&] { visiting.erase(&p); });
601 SmallVector<Block *> sequence = chainBlocks(p);
602 if (sequence.empty())
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()))
612 auto it = tokens.find(lock);
613 if (it == tokens.end()) {
614 std::optional<uint64_t> others = tokensFromOthers(lock, &p);
617 it = tokens.try_emplace(lock, lock.getInit().value_or(0) + *others)
622 else if (it->second < *n)
626 }
else if (
auto bd = dyn_cast<DMABDOp>(bdOp)) {
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))
641 if (isa<CoreOp>(parent))
647std::optional<uint64_t>
648StreamVolumeAnalysis::tokensFromOthers(LockOp lock,
649 const DmaChannelProgram *self)
const {
650 llvm::SetVector<const DmaChannelProgram *> releasers;
652 for (Operation *user : lock->getUsers()) {
653 auto use = dyn_cast<UseLockOp>(user);
658 auto owner = lockUseProgram.find(use);
659 if (owner == lockUseProgram.end()) {
660 std::optional<uint64_t> n = lockTokens(use);
661 if (!onceInCore(use) || !n)
666 if (owner->second != self)
667 releasers.insert(owner->second);
669 for (
const DmaChannelProgram *program : releasers) {
670 std::optional<uint64_t> n = releasesOver(*program, lock);
681 if (first.
src != then.
src)
687 if (first.
src.
port.bundle != WireBundle::DMA)
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))
696 bool sent =
false, after =
false;
697 auto visit = [&](DMABDOp bd) {
698 after |= sent && then.
carries(bd.getPacket());
699 sent |= first.
carries(bd.getPacket());
702 if (!walkLoop(p, visit))
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>())
714std::optional<uint64_t>
717 if (!isa<DMAStartOp, DMAOp>(p.
op))
719 SmallVector<Block *> sequence = chainBlocks(p);
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);
730 return perPass * p.
passes;
733 if (p.
dma.
dir != DMAChannelDir::S2MM || sequence.empty())
736 uint64_t received = 0;
737 for (
const RoutedStream &s : streams) {
738 if (s.dst != endpoint)
740 std::optional<uint64_t> bytes = sendVolume(s);
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)
751 filled += bd.getLenInBytes();
752 }
else if (
auto use = dyn_cast<UseLockOp>(bdOp)) {
753 if (!use.release() || use.getLock().getDefiningOp() != lock)
755 std::optional<uint64_t> n = lockTokens(use);
765static std::optional<uint64_t> programCapacity(
const DmaChannelProgram &p,
767 if (!isa<DMAStartOp, DMAOp>(p.
op))
771 SmallVector<Block *> sequence = chainBlocks(p);
772 if (sequence.empty())
779 DenseMap<Operation *, int64_t> lockValues;
783 std::optional<DenseMap<Operation *, int64_t>> cycleLocks;
784 uint64_t cycleBytes = 0;
786 for (uint64_t step = 0;; step++) {
787 if (!p.
loops && step >= p.
passes * sequence.size())
789 size_t i = blockAt(p, sequence.size(), step);
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;
799 (p.
passes - step / sequence.size()) * (bytes - cycleBytes);
801 cycleLocks = lockValues;
805 if (step >=
static_cast<uint64_t
>(
maxBDSteps))
807 for (Operation &bdOp : *sequence[i]) {
808 if (
auto use = dyn_cast<UseLockOp>(bdOp)) {
809 std::optional<int64_t> n = lockAmount(use);
812 auto lock = use.getLock().getDefiningOp<LockOp>();
814 lockValues.try_emplace(lock, lock.getInit().value_or(0))
819 else if (value != *n)
821 }
else if (use.release()) {
823 }
else if (!use.acquireGE() || value < *n) {
828 }
else if (
auto bd = dyn_cast<DMABDOp>(bdOp)) {
829 bytes += bd.getLenInBytes();
835std::optional<uint64_t>
837 if (endpoint.
port.bundle != WireBundle::DMA)
839 auto it = programs.find(
840 {endpoint.
tile, DMAChannelDir::S2MM, endpoint.
port.channel});
841 if (it == programs.end())
843 std::optional<uint64_t> capacity;
845 if (std::optional<uint64_t> c = programCapacity(p, device))
846 capacity = std::min(*c, capacity.value_or(*c));
851 ArrayRef<RoutedStream> streams)
const {
857 if (s.dst != endpoint)
859 std::optional<uint64_t> bytes =
sendVolume(s);
864 return sent > *capacity;
868 ArrayRef<RoutedStream> streams,
870 std::set<TileDMAChannel> neverFull;
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];
881 DenseMap<Operation *, llvm::SetVector<unsigned>> acquirers, releasers;
882 auto noteLock = [&](UseLockOp use,
unsigned agent) {
883 Operation *lock = use.getLock().getDefiningOp();
886 if (use.getAction() == LockAction::Release)
887 releasers[lock].insert(agent);
889 acquirers[lock].insert(agent);
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); });
901 modeled.insert(agent);
902 forEachInProgram<UseLockOp>(p,
903 [&](UseLockOp use) { noteLock(use, agent); });
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())
911 for (
unsigned p : waiting->second)
912 for (
unsigned q : it->second)
913 if (p != q && waitsOnLocks(p))
914 addEdge(p, q, EdgeKind::Lock);
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)
925 addEdge(*from, *to, EdgeKind::Stream,
true);
926 addEdge(*to, *from, EdgeKind::Stream,
false,
true);
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()))
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())},
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>{};
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)});
984 if (isa<AIEX::NpuMaskPollOp>(op))
985 return SmallVector<TileDMAChannel>{};
988 llvm::SetVector<TileDMAChannel, SmallVector<TileDMAChannel>,
989 std::set<TileDMAChannel>>
991 sequence.walk([&](Operation *op) {
992 if (std::optional<SmallVector<TileDMAChannel>> keys = issued(op))
993 issuedKeys.insert(keys->begin(), keys->end());
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)
1004 addEdge(agent, w, EdgeKind::Host);
1007 for (unsigned a = 0; a < numStreamAgents; a++)
1008 if (agents[a].kind == Agent::Kind::Channel)
1009 for (unsigned w : waited)
1011 addEdge(a, w, EdgeKind::Host);
1012 }
else if (std::optional<SmallVector<TileDMAChannel>> keys =
1015 keys->empty() ? issuedKeys.getArrayRef() : ArrayRef(*keys)) {
1017 for (
unsigned a = 0; a < numStreamAgents; a++)
1019 agents[a].dma.tile.col == key.tile.col)
1030 for (Agent &a : agents)
1031 a.onShim = a.kind == Agent::Kind::Channel &&
1033 for (
unsigned a = 0; a < agents.size(); a++) {
1034 if (modeled.contains(a) || agents[a].kind == Agent::Kind::Controller ||
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);
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)"
1051 << (e.kind == EdgeKind::Lock && !modeled.contains(a)
1058std::optional<StreamWaitGraph::Agent>
1060 if (endpoint.
port.bundle == WireBundle::Core)
1062 if (endpoint.
port.bundle == WireBundle::TileControl && sending)
1064 if (endpoint.
port.bundle == WireBundle::DMA)
1066 sending ? DMAChannelDir::MM2S : DMAChannelDir::S2MM,
1067 endpoint.
port.channel});
1070 return std::nullopt;
1073unsigned StreamWaitGraph::getOrCreate(
const Agent &agent) {
1074 auto [it, inserted] =
1075 agentIDs.try_emplace({agent.
kind, agent.
dma}, agents.size());
1077 agents.push_back(agent);
1078 edges.emplace_back();
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;
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) {
1095 e.receives |= receives;
1099 edges[from].push_back({to, kind, sends, receives});
1103 bool sending)
const {
1104 if (std::optional<Agent> agent =
Agent::at(endpoint, sending))
1105 return lookup(*agent);
1106 return std::nullopt;
1112 SmallVector<unsigned> drainers;
1113 for (
const Edge &e : edges[agent])
1114 if (e.kind != EdgeKind::Stream)
1115 drainers.push_back(e.to);
1119SmallVector<unsigned>
1121 ArrayRef<unsigned> avoid)
const {
1134 llvm::SparseBitVector<> took;
1135 std::optional<size_t> parent;
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))
1146 seen[next.agent].push_back(states.size());
1147 worklist.push_back(states.size());
1148 states.push_back(std::move(next));
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());
1164 for (
const Edge &e : edges[a]) {
1165 const State &state = states[index];
1166 if (state.taking && e.receives && !e.sends &&
1169 if (llvm::is_contained(avoid, e.to) || state.took.test(e.to))
1171 bool takes = e.kind == EdgeKind::Stream && e.sends &&
1173 llvm::SparseBitVector<> took = state.took;
1176 visit({e.to, takes, std::move(took), index});
1183 const Agent &a = agents[id];
1185 llvm::raw_string_ostream os(s);
1190 os <<
"TileControl";
1197 ArrayRef<RoutedStream> streams)
1198 : streams(streams), volumes(device, streams),
1199 graph(device, streams, volumes), stalls(streams.size()),
1200 silence(streams.size()) {}
1202bool StreamDeadlockAnalysis::canStall(
size_t f)
const {
1203 std::optional<bool> &stall = stalls[f];
1205 stall = volumes.
canFill(streams[f].dst, streams);
1209SmallVector<unsigned> StreamDeadlockAnalysis::blockingChain(
size_t f,
1212 std::optional<unsigned> fDst = graph.
agentAt(fs.
dst,
false);
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))
1224 for (std::optional<unsigned> a :
1226 if (a && !llvm::is_contained(own, *a))
1227 targets.push_back(*a);
1228 if (targets.empty())
1230 return graph.waitChain(drainers, targets, avoid);
1234 if (
auto it = blocks.find({f, g}); it != blocks.end())
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();
1243 std::optional<bool> &quiet = silence[f];
1245 quiet = volumes.sendVolume(streams[f]) == std::optional<uint64_t>(0);
1251 SmallVector<unsigned> chain = blockingChain(f, g);
1253 llvm::raw_string_ostream os(s);
1254 os <<
describeStream(fs) <<
" can fill its receiver, and draining that "
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 "
1269 SmallVector<std::string> assumed;
1271 if (other.dst == fs.
dst && !volumes.sendVolume(other)) {
1273 " carries is unknown, so it is assumed to overrun its "
1277 if (fs.
src == gs.src && !volumes.maySendAfter(fs, gs))
1278 assumed.push_back(
"Both come from " +
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))
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." :
"."));
1298 llvm::raw_string_ostream os(s);
1299 os << (stream.
packetID ?
"packet flow " :
"flow ")
1303 os <<
" (id " << *stream.
packetID <<
")";
1309 numRequested(streams.size()) {
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);
1322 waits.resize(treeMembers.size());
1325std::optional<StreamConflicts::TreeKey>
1326StreamConflicts::treeKey(
size_t s)
const {
1329 return std::nullopt;
1336 analysis.emplace(device, streams);
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)
1344 return getAnalysis().canBlock(s, t);
1349bool StreamConflicts::related(
size_t s,
size_t t)
const {
1350 if (streams[s].src == streams[t].src)
1352 for (
size_t m : treeMembers[treeOf[s]])
1353 for (
size_t n : treeMembers[treeOf[t]])
1354 if (streams[m].dst == streams[n].dst)
1360 return !related(s, t) && (blocks(s, t) || blocks(t, s));
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];
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();
1375 for (
size_t g = 0; g < treeMembers.size(); g++) {
1376 if (g == a || reached.contains(g) ||
1377 !streams[treeMembers[g].front()].packetID)
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])
1383 return std::pair{x, m};
1384 return std::nullopt;
1398 return blocks(s, t) || blocks(t, s) ||
1399 waitsFrom(treeOf[s]).contains(treeOf[t]) ||
1400 waitsFrom(treeOf[t]).contains(treeOf[s]);
1409 if (!waitsFrom(treeOf[s]).contains(treeOf[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);
1417 std::reverse(steps.begin(), steps.end());
1418 return llvm::join(steps,
" ");
1422 SmallVector<std::pair<size_t, size_t>> pairs;
1424 for (
size_t s = 0; s < numRequested; s++)
1425 for (
size_t t = 0; t < numRequested; t++) {
1428 if (s == t || treeOf[s] == treeOf[t] ||
1429 !(streams[s].packetID || streams[t].packetID) || !related(s, t) ||
1433 pairs.push_back({s, t});
1435 LLVM_DEBUG(llvm::dbgs() <<
"Unavoidable only by assumption: "
1446 std::optional<HoldCycle::Step> step;
1449 SmallVector<std::pair<TileID, int>, 4> orders = {};
1454 llvm::function_ref<ArrayRef<WaitEdge>(
size_t)> successors;
1457using WaitNode = std::pair<const WaitGraph *, size_t>;
1462struct GraphTraits<const WaitGraph *> {
1471 return map_iterator(n.first->successors(n.second).begin(),
ToNode{n.first});
1474 return map_iterator(n.first->successors(n.second).end(),
ToNode{n.first});
1479std::optional<HoldCycle>
1481 bool forcedWaits,
bool definite)
const {
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;
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))
1496 auto [it, inserted] = treeIDs.try_emplace(*key, trees.size());
1498 trees.emplace_back();
1499 Tree &tree = trees[it->second];
1500 tree.members.push_back(i);
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);
1519 auto sameSource = [&](
size_t a,
size_t b) {
1520 return streams[trees[a].members.front()].src ==
1521 streams[trees[b].members.front()].src;
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;
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))
1533 if (streams[trees[a].members.front()].packetID !=
1534 streams[trees[b].members.front()].packetID)
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()];
1549 enum class Kind { Hop, Receiver, Anywhere, Past };
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});
1567 auto receiverNode = [&](
size_t t,
size_t m) {
1568 return trees[t].base + trees[t].hops.size() + m;
1570 auto anywhereNode = [&](
size_t t) {
1571 return receiverNode(t, trees[t].members.size());
1573 auto pastNode = [&](
size_t t,
size_t h) {
return anywhereNode(t) + 1 + h; };
1575 std::map<std::pair<TileID, Port>, SmallVector<std::pair<size_t, size_t>, 4>>
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});
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()),
1594 return trees[t].hops[h].first == g.first &&
1595 trees[t].arbiter[h] == g.second;
1599 int pa = trees[a].parent[ha], pb = trees[b].parent[hb];
1600 if (pa < 0 || pb < 0)
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};
1608 grants.insert(grants.begin(), g);
1609 else if (once(a, g) && once(b, g))
1610 grants.push_back(g);
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> {
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));
1631 const Node &node = nodes[n];
1632 const Tree &u = trees[node.tree];
1633 switch (node.kind) {
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))
1640 size_t sharer = trees[t].members.front();
1641 bool sameId = streams[waiting].packetID == streams[sharer].packetID;
1642 if (t != node.tree && (!sameId || forcedWaits))
1646 tile, input, input, -1, sameId},
1647 orderedBy(node.tree, node.index, t, ht)});
1648 std::optional<int> arbiter = trees[t].arbiter[ht];
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)
1659 bool isForced = !self && forced(t, ht, v, hv, tile);
1660 if (isForced && !forcedWaits)
1665 trees[v].members.front(), tile, input,
1666 holderInput, *arbiter, isForced}});
1671 case Kind::Receiver: {
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;
1679 for (
size_t m : trees[g].members)
1681 (!definite || getAnalysis().assumptions(s, m).empty())) {
1682 out.push_back({anywhereNode(g),
1690 case Kind::Anywhere:
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])
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});
1704 return *(edges[n] = std::move(out));
1709 auto counts = [&](
const Edge &e) {
1712 return e.step->waiting < numRequested || e.step->sharer < numRequested ||
1713 e.step->holding < numRequested;
1715 for (
size_t n = 0; n < nodes.size(); n++)
1716 if (nodes[n].kind == Kind::Hop && llvm::any_of(successors(n), counts))
1719 const WaitGraph graph{successors, nodes.size()};
1720 std::vector<int> component(nodes.size() + 1, -1);
1722 for (
auto scc = llvm::scc_begin(&graph); !scc.isAtEnd(); ++scc, ++components)
1723 for (WaitNode n : *scc)
1724 component[n.second] = components;
1736 std::optional<size_t> fixed;
1737 SmallVector<size_t, 2> excluded;
1739 using Constraints = std::map<Grant, Holders>;
1740 auto allowed = [](
const Edge &edge,
const Constraints &c) {
1743 auto it = c.find({edge.step->tile, edge.step->arbiter});
1746 size_t holder = edge.step->holding;
1747 return it->second.fixed ? *it->second.fixed == holder
1748 : !llvm::is_contained(it->second.excluded, holder);
1752 constexpr size_t maxOrders = 8;
1754 [&](
size_t x,
const Edge &e,
1755 const Constraints &c) -> std::optional<SmallVector<const Edge *>> {
1757 return std::nullopt;
1760 size_t k = std::min<size_t>(e.orders.size(), maxOrders);
1761 auto unordered = [&](
const Edge &edge) {
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;
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);
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);
1790 std::reverse(path.begin(), path.end());
1793 auto toCycle = [](ArrayRef<const Edge *> path) {
1795 for (
const Edge *edge : path)
1797 cycle.
steps.push_back(*edge->step);
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])
1805 std::optional<SmallVector<const Edge *>> first;
1806 SmallVector<Constraints> pending{{}};
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);
1815 Constraints c = pending.pop_back_val();
1816 std::optional<SmallVector<const Edge *>> path = closeWalk(x, e, c);
1821 std::map<Grant, size_t> held;
1822 std::optional<std::pair<Grant, size_t>> clash;
1823 for (
const Edge *edge : *path) {
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) {
1834 LLVM_DEBUG(llvm::dbgs() <<
"Hold cycle search closed a walk after "
1835 << search + 1 <<
" walks\n");
1836 return toCycle(*path);
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));
1844 LLVM_DEBUG(llvm::dbgs() <<
"Hold cycle search closed no walk after "
1845 << search <<
" walks\n");
1847 return std::nullopt;
1852 llvm::raw_string_ostream os(s);
1853 for (
auto [i, step] : llvm::enumerate(cycle.
steps)) {
1856 switch (step.wait) {
1858 os <<
describeStream(streams[step.waiting]) <<
" can queue behind "
1860 <<
describePort(step.sharerInput) <<
" into tile (" << step.tile.col
1861 <<
", " << step.tile.row <<
").";
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])
1868 if (step.waiting != step.sharer)
1870 <<
" can queue behind it";
1874 os << getAnalysis().explainBlock(step.waiting, step.holding);
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,...
StreamConflicts(DeviceOp device)
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
std::string describePort(Port port)
Names a port the way diagnostics do, e.g. "DMA:1".
NodeRef operator()(const WaitEdge &e) const
static ChildIteratorType child_begin(NodeRef n)
static NodeRef getEntryNode(const WaitGraph *g)
mapped_iterator< const WaitEdge *, ToNode > ChildIteratorType
static ChildIteratorType child_end(NodeRef n)
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 Agent core(TileID tile)
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)
static Agent controller(TileID tile)
One DMA channel of one tile.